blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
244464e660f7fc656c3dd1a1d9d828323d616f4a | aca4f00c884e1d0e6b2978512e4e08e52eebd6e9 | /2013/MUTC/1/proH.cpp | 5a287695e37a4fd0aebf96c8c0b32b4b4b07f6a3 | [] | no_license | jki14/competitive-programming | 2d28f1ac8c7de62e5e82105ae1eac2b62434e2a4 | ba80bee7827521520eb16a2d151fc0c3ca1f7454 | refs/heads/master | 2023-08-07T19:07:22.894480 | 2023-07-30T12:18:36 | 2023-07-30T12:18:36 | 166,743,930 | 2 | 0 | null | 2021-09-04T09:25:40 | 2019-01-21T03:40:47 | C++ | UTF-8 | C++ | false | false | 870 | cpp | #include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
using namespace std;
#define N 1100000
int n,m,w,p;
int nbs[N],nxt[N],dst[N],num;
int mrk[N];
void addEdge(const int &u,const int &v){
nxt[++num]=nbs[u];nbs[u]=num;dst[num]=v;
}
void dfs(const int &u,const int &_w){
mrk[u]=1;if(_w>w){ w=_w;p=u; }
for(int i=nbs[u];i;i=nxt[i]){int v=dst[i];
if(mrk[v])continue;
dfs(v,_w+1);
}
}
int main(){
int T;scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&m);
memset(nbs,0,sizeof(nbs));num=0;
for(int i=1;i<n;i++){
int u,v;scanf("%d%d",&u,&v);
addEdge(u,v);addEdge(v,u);
}
w=p=1;
memset(mrk,0,sizeof(mrk));
dfs(1,1);
memset(mrk,0,sizeof(mrk));
dfs(p,1);
for(int i=0;i<m;i++){
int k;scanf("%d",&k);
//printf("w=%d k=%d\n",w,k);
if(k<=w){
printf("%d\n",k-1);
}else printf("%d\n",k+k-w-1);
}
}
return 0;
}
| [
"jki14wz@gmail.com"
] | jki14wz@gmail.com |
ff30db813cb85598476f31cedd708df6fb8d63eb | d9e43fa0caa63be642a161f2a1253e3c10b0e174 | /EXIT/FixedPointQuantizer.h | 97d28a5b09cc61f2343732c9511465f1c1fbd687 | [] | no_license | guiji101/Turbo | 60860eec342dd79708e36142ce84fdc05ff0df43 | edec859a702922240e327d9f21c7f7da597b7e8d | refs/heads/master | 2020-12-12T21:00:41.738833 | 2013-11-15T01:47:17 | 2013-11-15T01:47:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 733 | h | #ifndef FIXED_POINT_QUANTIZER
#define FIXED_POINT_QUANTIZER
#include <vector>
using std::vector;
class FixedPointQuantizer
{
public:
FixedPointQuantizer();
FixedPointQuantizer(int n, int nf);
void init(int n, int nf);
double quantify(double val)
{
double ret = int(val * _powN) / double(_powN);
if (ret > _upperLimit)
{
return _upperLimit;
}
else if (ret < -_upperLimit)
{
return -_upperLimit;
}
else
{
return ret;
}
}
void quantifyVec(vector<double>& vec);
private:
int _n;//number of total bits
int _ni;//number of bits for integral part(include 1 bit for sign)
int _nf;//number of bits for fractional part
double _powN;//2^_nf
double _upperLimit;//max number can be represented
};
#endif | [
"guiji101@qq.com"
] | guiji101@qq.com |
6cd09726e63344ceb11879230fb4e002f044f653 | 272c3b13339d0e7871c27a9c5d555a171380afe4 | /libFileRevisorTests/ValueTypes/RenameResultTests.cpp | df27f8a543e67c2bf999e033a6b575b3b50a9e2d | [
"MIT"
] | permissive | NeilJustice/FileRevisor | 4b219a8b6dfafdcb8994365bf7df941c964022ca | a12d7d57503cfe6f2a0dcd6fa8dd31a2ff8a005a | refs/heads/main | 2023-08-16T15:42:29.221920 | 2023-08-12T18:30:48 | 2023-08-12T18:30:48 | 151,807,150 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,903 | cpp | #include "pch.h"
#include "libFileRevisor/ValueTypes/RenameResult.h"
TESTS(RenameResultTests)
AFACT(DefaultConstructor_SetsFieldsToDefaults)
AFACT(ThreeArgConstructor_SetsFields)
FACTS(DidRenameFileOrDirectoryFieldIsTrue_ReturnsTrueIfDidRenameFileOrDirectoryFieldIsTrue)
EVIDENCE
TEST(DefaultConstructor_SetsFieldsToDefaults)
{
const RenameResult defaultRenameResult;
RenameResult expectedDefaultRenameResult;
expectedDefaultRenameResult.didRenameFileOrDirectory = false;
expectedDefaultRenameResult.originalFileOrDirectoryPath = fs::path();
expectedDefaultRenameResult.renamedFileOrDirectoryPath = fs::path();
ARE_EQUAL(expectedDefaultRenameResult, defaultRenameResult);
}
TEST(ThreeArgConstructor_SetsFields)
{
const bool didRenameFileOrDirectory = ZenUnit::Random<bool>();
const fs::path originalPath = ZenUnit::Random<fs::path>();
const fs::path renamedFileOrDirectoryPath = ZenUnit::Random<fs::path>();
//
const RenameResult renameResult(didRenameFileOrDirectory, originalPath, renamedFileOrDirectoryPath);
//
ARE_EQUAL(didRenameFileOrDirectory, renameResult.didRenameFileOrDirectory);
ARE_EQUAL(originalPath, renameResult.originalFileOrDirectoryPath);
ARE_EQUAL(renamedFileOrDirectoryPath, renameResult.renamedFileOrDirectoryPath);
}
TEST2X2(DidRenameFileOrDirectoryFieldIsTrue_ReturnsTrueIfDidRenameFileOrDirectoryFieldIsTrue,
bool didRenameFileOrDirectoryFieldValue, bool expectedReturnValue,
false, false,
true, true)
{
RenameResult renameResult = ZenUnit::Random<RenameResult>();
renameResult.didRenameFileOrDirectory = didRenameFileOrDirectoryFieldValue;
//
bool didRenameFileOrDirectoryFieldIsTrue = RenameResult::DidRenameFileOrDirectoryFieldIsTrue(renameResult);
//
ARE_EQUAL(expectedReturnValue, didRenameFileOrDirectoryFieldIsTrue);
}
RUN_TESTS(RenameResultTests)
| [
"njjustice@gmail.com"
] | njjustice@gmail.com |
104be8ad5ef28fed89d559a2658470c0b4529d08 | b6b498ddc8600f91a9e2abdbeb72cd41024b464c | /06_납품현황/2017/06_화성동탄이마트/03_SERVER/New_PS_ServApp/stdafx.cpp | 3d12d1c4a16e27e57b3a8f3fc28eae0a06bd5250 | [] | no_license | dongdong-2009/02_PGS-1 | 01cfa514cef4010139c693a78757744085522123 | daeb6477ac9cf2d1cdc1b3e700363b745880c37a | refs/heads/master | 2021-09-12T17:53:26.784206 | 2018-04-19T11:59:05 | 2018-04-19T11:59:05 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 25,268 | cpp |
// stdafx.cpp : 표준 포함 파일만 들어 있는 소스 파일입니다.
// PS_ServApp.pch는 미리 컴파일된 헤더가 됩니다.
// stdafx.obj에는 미리 컴파일된 형식 정보가 포함됩니다.
#include "stdafx.h"
#include "math.h"
#include "WrapManNetComm.h"
#include "PaneBD.h"
#include "PS_ServAppDoc.h"
#include "PS_ServAppView.h"
#include "Shlwapi.h"
#define M_PI (acos (-1.))
#define GET_ROUNDED_VAL(x) (((x)>0) ? short((x) +0.5) : short((x) -0.5))
INFO_GLOBAL glInfoGlobal;
void ReadDebugData ();
void ReadDebugDataFromFile (int idxCCM, LPCTSTR strFilePath);
void ReadInitSettingsFromFile ()
{
ReadDebugData ();
ReadInfoBDA ();
}
void ReadDebugData ()
{
int i;
char strCurAppPath[MAX_PATH], strDebugDataFilePath[MAX_PATH], strTmp[MAX_PATH];
GetCurrentDirectory (MAX_PATH, strCurAppPath);
for (i=0; i<MAX_NUM_CCM; i++)
{
sprintf_s (strTmp, MAX_PATH, STR_DEBUG_DATA_FORMAT, MIN_DEV_ID_CCM +i);
sprintf_s (strDebugDataFilePath, MAX_PATH, "%s\\%s", strCurAppPath, strTmp);
if (::PathFileExists (strDebugDataFilePath) == TRUE)
{
ReadDebugDataFromFile (i, strDebugDataFilePath);
}
}
}
void ReadDebugDataFromFile (int idxCCM, LPCTSTR strFilePath)
{
SYSTEMTIME curTime;
GetLocalTime(&curTime);
INFO_CTRL_DEV_ALL *pICDA = &glInfoGlobal.iCDA;
if (pICDA->bufICDevCCM[idxCCM].bUse == FALSE)
{
pICDA->bufICDevCCM[idxCCM].bUse = TRUE;
sprintf_s (pICDA->bufICDevCCM[idxCCM].strName, "CCM %d", idxCCM +MIN_DEV_ID_CCM);
pICDA->bufICDevCCM[idxCCM].iDev.nSN.nRev = 1;
pICDA->bufICDevCCM[idxCCM].iDev.nSN.nDevNum = idxCCM +MIN_DEV_ID_CCM;
pICDA->bufICDevCCM[idxCCM].iDev.nDevID = idxCCM +MIN_DEV_ID_CCM;
pICDA->numDevCCM++;
}
pICDA->bufNumDevSCM[idxCCM] = 0;
memset (&pICDA->bbufNumDevUSM[idxCCM][0], 0, sizeof(int) *MAX_NUM_SCM);
memset (&pICDA->bbufNumDevLGM[idxCCM][0], 0, sizeof(int) *MAX_NUM_SCM);
memset (&pICDA->bbufICDevSCM[idxCCM][0], 0, sizeof(INFO_CTRL_DEV_SCM) *MAX_NUM_SCM);
memset (&pICDA->bbbufICDevUSM[idxCCM][0][0], 0, sizeof(INFO_CTRL_DEV_USM) *MAX_NUM_SCM *MAX_NUM_USM);
memset (&pICDA->bbbufICDevLGM[idxCCM][0][0], 0, sizeof(INFO_CTRL_DEV_LGM) *MAX_NUM_SCM *MAX_NUM_LGM);
FILE *fp;
char strLine[1024];
int idxDevType, bufTmp[16], idxSCM;
INFO_DEV_USM *pIDUSM;
INFO_DEV_LGM *pIDLGM;
fopen_s (&fp, strFilePath, "rt");
if (fp == NULL)
{
return;
}
idxDevType = IDX_DEV_TYPE_USM;
idxSCM = 0;
while (fgets (strLine, 1023, fp) != 0)
{
if (strLine[0] == 'U' && strLine[1] == 'S' && strLine[2] == 'M')
{
idxDevType = IDX_DEV_TYPE_USM;
}
else if (strLine[0] == 'L' && strLine[1] == 'G' && strLine[2] == 'M')
{
idxDevType = IDX_DEV_TYPE_LGM;
}
else if (strLine[0] == 'S' && strLine[1] == 'C' && strLine[2] == 'M')
{
idxDevType = IDX_DEV_TYPE_SCM;
}
else
{
if (idxDevType == IDX_DEV_TYPE_USM)
{
if (sscanf_s (strLine, "%03d %08d %d %03d %03d %03d %02d %02d %03d",
&bufTmp[0], &bufTmp[1], &bufTmp[2], &bufTmp[3], &bufTmp[4], &bufTmp[5], &bufTmp[6], &bufTmp[7], &bufTmp[8]) == 9)
{
if (bufTmp[0] > 0)
{
if (bufTmp[0] <= MAX_DEV_ID_USM)
{
pICDA->bbbufICDevUSM[idxCCM][idxSCM][bufTmp[0] -MIN_DEV_ID_USM].bUse = TRUE;
sprintf_s (pICDA->bbbufICDevUSM[idxCCM][idxSCM][bufTmp[0] -MIN_DEV_ID_USM].strName, "USM %d", bufTmp[0] -MIN_DEV_ID_USM +1);
pIDUSM = &pICDA->bbbufICDevUSM[idxCCM][idxSCM][bufTmp[0] -MIN_DEV_ID_USM].iDev;
pIDUSM->nSN.nRev = 1;
pIDUSM->nSN.nDevNum = bufTmp[1];
pIDUSM->nDevID = bufTmp[0];
pIDUSM->idxOpMode = IDX_OPM_SENS_LED_OFF;
pIDUSM->bufParam[IDX_USM_PARAM_MAX_DET_DIST] = (bufTmp[4] -MIN_USMP_MAX_DET_DIST) /INC_USMP_MAX_DET_DIST;
pIDUSM->bufParam[IDX_USM_PARAM_ADC_AMP_LV] = (bufTmp[5] -MIN_USMP_ADC_AMP_LV) /INC_USMP_ADC_AMP_LV;
pIDUSM->bufParam[IDX_USM_PARAM_ADC_SNS_LV] = (bufTmp[6] -MIN_USMP_ADC_SNS_LV) /INC_USMP_ADC_SNS_LV;
pIDUSM->bufParam[IDX_USN_PARAM_TX_BURST_CNT] = (bufTmp[7] -MIN_USMP_TX_BURST_CNT) /INC_USMP_TX_BURST_CNT;
pIDUSM->nDevID_LGM = bufTmp[3];
pIDUSM->nGroup = bufTmp[8];
pIDUSM->nLTPTimeRef.wDay = curTime.wDay;
pIDUSM->nLTPTimeRef.wHour = curTime.wHour;
pIDUSM->nLTPTimeRef.wMinute = curTime.wMinute;
pIDUSM->nLTPTimeRef.wSecond = curTime.wSecond;
pIDUSM->bStartParkingF = 0;
pIDUSM->bGreenCnt=0;
pICDA->bbufNumDevUSM[idxCCM][idxSCM]++;
}
else
{
AfxMessageBox (_T("ERROR: Invalid USM device ID (1 to 127)"));
}
}
}
}
else if (idxDevType == IDX_DEV_TYPE_LGM)
{
if (sscanf_s (strLine, "%03d %08d %d",
&bufTmp[0], &bufTmp[1], &bufTmp[2]) == 3)
{
if (bufTmp[0] > 0)
{
if (bufTmp[0] >= MIN_DEV_ID_LGM)
{
pICDA->bbbufICDevLGM[idxCCM][idxSCM][bufTmp[0] -MIN_DEV_ID_LGM].bUse = TRUE;
sprintf_s (pICDA->bbbufICDevLGM[idxCCM][idxSCM][bufTmp[0] -MIN_DEV_ID_LGM].strName, "LGM %d", bufTmp[0] -MIN_DEV_ID_LGM +1);
pIDLGM = &pICDA->bbbufICDevLGM[idxCCM][idxSCM][bufTmp[0] -MIN_DEV_ID_LGM].iDev;
pIDLGM->nSN.nRev = 1;
pIDLGM->nSN.nDevNum = bufTmp[1];
pIDLGM->nDevID = bufTmp[0];
pIDLGM->idxOpMode = IDX_OPM_SENS_LED_OFF;;
pICDA->bbufNumDevLGM[idxCCM][idxSCM]++;
}
else
{
AfxMessageBox (_T("ERROR: Invalid LGM device ID (129 to 255)"));
}
}
}
}
else
{
if (sscanf_s (strLine, "%03d", &bufTmp[0]) == 1)
{
if (bufTmp[0] >= MIN_DEV_ID_SCM && bufTmp[0] <= MAX_DEV_ID_SCM)
{
idxSCM = bufTmp[0] -MIN_DEV_ID_SCM;
if (pICDA->bbufICDevSCM[idxCCM][idxSCM].bUse == FALSE)
{
pICDA->bbufICDevSCM[idxCCM][idxSCM].bUse = TRUE;
sprintf_s (pICDA->bbufICDevSCM[idxCCM][idxSCM].strName, "SCM %d - %d", idxCCM +MIN_DEV_ID_CCM, idxSCM +MIN_DEV_ID_SCM);
pICDA->bbufICDevSCM[idxCCM][idxSCM].iDev.nSN.nRev = 1;
pICDA->bbufICDevSCM[idxCCM][idxSCM].iDev.nSN.nDevNum = (idxCCM +MIN_DEV_ID_CCM) *100 +(idxSCM +MIN_DEV_ID_SCM);
pICDA->bbufICDevSCM[idxCCM][idxSCM].iDev.nDevID = idxSCM +MIN_DEV_ID_SCM;
pICDA->bufNumDevSCM[idxCCM]++;
}
}
else
{
AfxMessageBox (_T("ERROR: Invalid SCM device ID (1 to 15)"));
}
}
}
}
}
fclose (fp);
}
void ReadInfoBDA ()
{
CFile fp;
DWORD szRead;
int i;
char strCurAppPath[MAX_PATH], strTmp[MAX_PATH];
GetCurrentDirectory (MAX_PATH, strCurAppPath);
sprintf_s (strTmp, MAX_PATH, "%s\\%s", strCurAppPath, STR_INFO_BDA_FILE_NAME);
if (fp.Open (strTmp, CFile::modeRead) == FALSE)
{
INIT_IBDA:
memset (&glInfoGlobal.iBDA, 0, sizeof(INFO_BACK_DRAWING_ALL));
return;
}
szRead = sizeof(INFO_BACK_DRAWING_ALL);
if (fp.Read (&glInfoGlobal.iBDA, szRead) != szRead)
{
fp.Close ();
goto INIT_IBDA;
}
// Read INFO_BACK_DRAWING_ITEM[S]
if (glInfoGlobal.iBDA.maxBDI == 0)
{
return;
}
glInfoGlobal.iBDA.bufBDI = new INFO_BACK_DRAWING_ITEM[glInfoGlobal.iBDA.maxBDI];
szRead = glInfoGlobal.iBDA.maxBDI *sizeof(INFO_BACK_DRAWING_ITEM);
if (fp.Read (&glInfoGlobal.iBDA.bufBDI[0], szRead) != szRead)
{
fp.Close ();
goto INIT_IBDA;
}
// Read INFO_BACK_DRAWING_ITEM[E]
// Read INFO_DISP_ITEM[S]
for (i=0; i<glInfoGlobal.iBDA.maxBDI; i++)
{
if (glInfoGlobal.iBDA.bufBDI[i].maxDispItem > 0)
{
glInfoGlobal.iBDA.bufBDI[i].bufDispItem = new INFO_DISP_ITEM[glInfoGlobal.iBDA.bufBDI[i].maxDispItem];
szRead = glInfoGlobal.iBDA.bufBDI[i].maxDispItem *sizeof(INFO_DISP_ITEM);
if (fp.Read (&glInfoGlobal.iBDA.bufBDI[i].bufDispItem[0], szRead) != szRead)
{
fp.Close ();
goto INIT_IBDA;
}
}
}
// Read INFO_DISP_ITEM[E]
fp.Close ();
}
void WriteInfoBDA ()
{
CFile fp;
int i;
char strCurAppPath[MAX_PATH], strTmp[MAX_PATH];
GetCurrentDirectory (MAX_PATH, strCurAppPath);
sprintf_s (strTmp, MAX_PATH, "%s\\%s", strCurAppPath, STR_INFO_BDA_FILE_NAME);
if (fp.Open (strTmp, CFile::modeCreate |CFile::modeWrite) == FALSE)
{
return;
}
fp.Write (&glInfoGlobal.iBDA, sizeof(INFO_BACK_DRAWING_ALL));
// Write INFO_BACK_DRAWING_ITEM[S]
if (glInfoGlobal.iBDA.maxBDI > 0)
{
fp.Write (&glInfoGlobal.iBDA.bufBDI[0], glInfoGlobal.iBDA.maxBDI *sizeof(INFO_BACK_DRAWING_ITEM));
// Write INFO_DISP_ITEM[S]
for (i=0; i<glInfoGlobal.iBDA.maxBDI; i++)
{
if (glInfoGlobal.iBDA.bufBDI[i].maxDispItem > 0)
{
fp.Write (&glInfoGlobal.iBDA.bufBDI[i].bufDispItem[0], glInfoGlobal.iBDA.bufBDI[i].maxDispItem *sizeof(INFO_DISP_ITEM));
}
}
// Write INFO_DISP_ITEM[E]
}
// Write INFO_BACK_DRAWING_ITEM[E]
fp.Close ();
}
void SetPtDrawDisp_from_ZoomParam (INFO_DISP_ITEM *pIDI, INFO_ZOOM_PARAM *pZP)
{
int i, posX, posY, szH, szV, szTmpH, szTmpV;
if (pZP->nZoom == NUM_ZOOM_FIT_TO_SCR)
{
posX = pIDI->ptDrawOrgX *pZP->szWndClient.cx /pZP->szBackDrawing.cx;
posY = pIDI->ptDrawOrgY *pZP->szWndClient.cy /pZP->szBackDrawing.cy;
szH = pIDI->szDI_Hor *pZP->szWndClient.cx /pZP->szBackDrawing.cx;
szV = pIDI->szDI_Ver *pZP->szWndClient.cy /pZP->szBackDrawing.cy;
}
else
{
if (pZP->nZoom >= NUM_ZOOM_1_TO_1)
{
posX = pIDI->ptDrawOrgX *(pZP->nZoom /NUM_ZOOM_1_TO_1);
posY = pIDI->ptDrawOrgY *(pZP->nZoom /NUM_ZOOM_1_TO_1);
szH = pIDI->szDI_Hor *(pZP->nZoom /NUM_ZOOM_1_TO_1);
szV = pIDI->szDI_Ver *(pZP->nZoom /NUM_ZOOM_1_TO_1);
}
else
{
posX = pIDI->ptDrawOrgX /(NUM_ZOOM_1_TO_1 /pZP->nZoom);
posY = pIDI->ptDrawOrgY /(NUM_ZOOM_1_TO_1 /pZP->nZoom);
szH = pIDI->szDI_Hor /(NUM_ZOOM_1_TO_1 /pZP->nZoom);
szV = pIDI->szDI_Ver /(NUM_ZOOM_1_TO_1 /pZP->nZoom);
}
}
if (szH < MIN_SZ_DI_HOR)
{
szH = MIN_SZ_DI_HOR;
}
if (szV < MIN_SZ_DI_VER)
{
szV = MIN_SZ_DI_VER;
}
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_ITEM][IDX_DISPI_PT_UL].x = 0;
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_ITEM][IDX_DISPI_PT_UL].y = 0;
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_ITEM][IDX_DISPI_PT_UR].x = GET_ROUNDED_VAL(szH *cos (double(pIDI->nDI_Angle) /180 *M_PI) -0 *sin (double(pIDI->nDI_Angle) /180 *M_PI));
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_ITEM][IDX_DISPI_PT_UR].y = GET_ROUNDED_VAL(szH *sin (double(pIDI->nDI_Angle) /180 *M_PI) +0 *cos (double(pIDI->nDI_Angle) /180 *M_PI));
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_ITEM][IDX_DISPI_PT_DR].x = GET_ROUNDED_VAL(szH *cos (double(pIDI->nDI_Angle) /180 *M_PI) -szV *sin (double(pIDI->nDI_Angle) /180 *M_PI));
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_ITEM][IDX_DISPI_PT_DR].y = GET_ROUNDED_VAL(szH *sin (double(pIDI->nDI_Angle) /180 *M_PI) +szV *cos (double(pIDI->nDI_Angle) /180 *M_PI));
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_ITEM][IDX_DISPI_PT_DL].x = GET_ROUNDED_VAL(0 *cos (double(pIDI->nDI_Angle) /180 *M_PI) -szV *sin (double(pIDI->nDI_Angle) /180 *M_PI));
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_ITEM][IDX_DISPI_PT_DL].y = GET_ROUNDED_VAL(0 *sin (double(pIDI->nDI_Angle) /180 *M_PI) +szV *cos (double(pIDI->nDI_Angle) /180 *M_PI));
szTmpH = szH +2;
szTmpV = szV +2;
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_SEL][IDX_DISPI_PT_UL].x = 0;
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_SEL][IDX_DISPI_PT_UL].y = 0;
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_SEL][IDX_DISPI_PT_UR].x = GET_ROUNDED_VAL(szTmpH *cos (double(pIDI->nDI_Angle) /180 *M_PI) -0 *sin (double(pIDI->nDI_Angle) /180 *M_PI));
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_SEL][IDX_DISPI_PT_UR].y = GET_ROUNDED_VAL(szTmpH *sin (double(pIDI->nDI_Angle) /180 *M_PI) +0 *cos (double(pIDI->nDI_Angle) /180 *M_PI));
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_SEL][IDX_DISPI_PT_DR].x = GET_ROUNDED_VAL(szTmpH *cos (double(pIDI->nDI_Angle) /180 *M_PI) -szTmpV *sin (double(pIDI->nDI_Angle) /180 *M_PI));
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_SEL][IDX_DISPI_PT_DR].y = GET_ROUNDED_VAL(szTmpH *sin (double(pIDI->nDI_Angle) /180 *M_PI) +szTmpV *cos (double(pIDI->nDI_Angle) /180 *M_PI));
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_SEL][IDX_DISPI_PT_DL].x = GET_ROUNDED_VAL(0 *cos (double(pIDI->nDI_Angle) /180 *M_PI) -szTmpV *sin (double(pIDI->nDI_Angle) /180 *M_PI));
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_SEL][IDX_DISPI_PT_DL].y = GET_ROUNDED_VAL(0 *sin (double(pIDI->nDI_Angle) /180 *M_PI) +szTmpV *cos (double(pIDI->nDI_Angle) /180 *M_PI));
szTmpH = szH +6;
szTmpV = szV +6;
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_LTPM][IDX_DISPI_PT_UL].x = 0;
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_LTPM][IDX_DISPI_PT_UL].y = 0;
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_LTPM][IDX_DISPI_PT_UR].x = GET_ROUNDED_VAL(szTmpH *cos (double(pIDI->nDI_Angle) /180 *M_PI) -0 *sin (double(pIDI->nDI_Angle) /180 *M_PI));
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_LTPM][IDX_DISPI_PT_UR].y = GET_ROUNDED_VAL(szTmpH *sin (double(pIDI->nDI_Angle) /180 *M_PI) +0 *cos (double(pIDI->nDI_Angle) /180 *M_PI));
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_LTPM][IDX_DISPI_PT_DR].x = GET_ROUNDED_VAL(szTmpH *cos (double(pIDI->nDI_Angle) /180 *M_PI) -szTmpV *sin (double(pIDI->nDI_Angle) /180 *M_PI));
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_LTPM][IDX_DISPI_PT_DR].y = GET_ROUNDED_VAL(szTmpH *sin (double(pIDI->nDI_Angle) /180 *M_PI) +szTmpV *cos (double(pIDI->nDI_Angle) /180 *M_PI));
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_LTPM][IDX_DISPI_PT_DL].x = GET_ROUNDED_VAL(0 *cos (double(pIDI->nDI_Angle) /180 *M_PI) -szTmpV *sin (double(pIDI->nDI_Angle) /180 *M_PI));
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_LTPM][IDX_DISPI_PT_DL].y = GET_ROUNDED_VAL(0 *sin (double(pIDI->nDI_Angle) /180 *M_PI) +szTmpV *cos (double(pIDI->nDI_Angle) /180 *M_PI));
for (i=0; i<NUM_DISPI_PT; i++)
{
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_ITEM][i].x += short(posX +pZP->ptOffset.x);
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_ITEM][i].y += short(posY +pZP->ptOffset.y);
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_SEL][i].x += short(posX +pZP->ptOffset.x -1);
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_SEL][i].y += short(posY +pZP->ptOffset.y -1);
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_LTPM][i].x += short(posX +pZP->ptOffset.x -3);
pIDI->bbufPtDrawDisp[IDX_DISPI_RGN_LTPM][i].y += short(posY +pZP->ptOffset.y -3);
}
}
int GetCurOpModeFromDI (INFO_DISP_ITEM *pIDI)
{
BYTE nStat, nGroup;
INFO_CTRL_DEV_ALL *pICDA = &glInfoGlobal.iCDA;
ITEM_STAT_CCM *pBufISC = glInfoGlobal.unGVA.iGVA.pWMNC->GetBasePtrStatCCM ();
if (pIDI->idxDevType == IDX_DEV_TYPE_USM)
{
nStat = pBufISC[pIDI->idxCCM].bufItem[pIDI->idxSCM].iStat.bufUSM_Stat[pIDI->idxUSM_LGM] &MASK_FOR_ICCS_USM_LGM_STAT;
//장애인 구역은 파란색으로 표시 [S]
nGroup = pICDA->bbbufICDevUSM[pIDI->idxCCM][pIDI->idxSCM][pIDI->idxUSM_LGM].iDev.nGroup;
if(nStat == IDX_OPM_SENS_LED_ON_GREEN){
if(nGroup > 200 && nGroup < 216) nStat = IDX_OPM_SENS_LED_ON_BLUE;
//장애인 구역은 파란색으로 표시 [E]
}
}
else if (pIDI->idxDevType == IDX_DEV_TYPE_LGM)
{
nStat = pBufISC[pIDI->idxCCM].bufItem[pIDI->idxSCM].iStat.bufLGM_Stat[pIDI->idxUSM_LGM] &MASK_FOR_ICCS_USM_LGM_STAT;
}
else
{
nStat = IDX_OPM_SENS_LED_OFF;
}
return nStat;
}
int ResetTimeForLTPM(INFO_DISP_ITEM *pIDI) // Long Term Parking Monitoring
{
INFO_DEV_USM *pInfoDevUsm = &glInfoGlobal.iCDA.bbbufICDevUSM[pIDI->idxCCM][pIDI->idxSCM][pIDI->idxUSM_LGM].iDev;
if (pIDI->idxDevType == IDX_DEV_TYPE_USM)
{
if(pInfoDevUsm->bGreenCnt > 1){
pInfoDevUsm->bStartParkingF = 0;
pInfoDevUsm->bGreenCnt = 0;
return 1;
}
else{
pInfoDevUsm->bGreenCnt++;
return 0;
}
}
else return 0;
}
int GetTimeIndexForLTPM(INFO_DISP_ITEM *pIDI) // Long Term Parking Monitoring
{
BYTE nStat;
int timeIndex;
SYSTEMTIME curTime;
GetLocalTime(&curTime);
int ndYear, ndMonth, npMonth, ndDay, npDay, ndHour, npHour , ndMinute, npMinute ;// npMonth = Plus Month
INFO_DEV_USM *pInfoDevUsm = &glInfoGlobal.iCDA.bbbufICDevUSM[pIDI->idxCCM][pIDI->idxSCM][pIDI->idxUSM_LGM].iDev;
if (pIDI->idxDevType == IDX_DEV_TYPE_USM)
{
if(pInfoDevUsm->bStartParkingF == 0)
{
pInfoDevUsm->nLTPTimeRef = curTime;
pInfoDevUsm->bStartParkingF = 1;
return 0;
}
else
{
ndYear = curTime.wYear - pInfoDevUsm->nLTPTimeRef.wYear;
npMonth = 12 * ndYear;
ndMonth = npMonth + curTime.wMonth - pInfoDevUsm->nLTPTimeRef.wMonth ;
npDay = 30 * ndMonth;
ndDay = npDay + curTime.wDay - pInfoDevUsm->nLTPTimeRef.wDay ;
npHour = 24 *ndDay;
ndHour = npHour + curTime.wHour - pInfoDevUsm->nLTPTimeRef.wHour;
npMinute = 60 * ndHour;
ndMinute = npMinute + curTime.wMinute - pInfoDevUsm->nLTPTimeRef.wMinute;
// 3시간 : 180분, 6시간 : 360분, 9시간 : 540분, 12시간 : 720분, 24시간 : 1440분
// 2시간 : 120분, 4시간 : 240분, 6시간 : 360분
if(ndMinute < 180)
return 0;
else if (ndMinute < 360)
return 1;
else if (ndMinute < 540)
return 2;
else if (ndMinute < 720)
return 3;
else if (ndMinute < 1440)
return 4;
else if (ndMinute >= 1440)
return 5;
else
return 0;
}
}
return 0;
}
void GetCurStatFromBDI (
INFO_BACK_DRAWING_ITEM *pIBDI
, STAT_PARKING_AREA &stPaAll
, STAT_PARKING_AREA &stPaB1F
, STAT_PARKING_AREA &stPaB2F
, STAT_PARKING_AREA &stPaB3F
, STAT_PARKING_AREA &stPaB4F
)
{
int i;
BYTE nStat;
INFO_DISP_ITEM *pIDI;
ITEM_STAT_CCM *pBufISC = glInfoGlobal.unGVA.iGVA.pWMNC->GetBasePtrStatCCM ();
//stPaAll.nTotal = 0;
//stPaAll.nParked = 0;
//stPaAll.nFree = 0;
stPaB1F.nTotal = 0;
stPaB1F.nParked = 0;
stPaB1F.nFree = 0;
stPaB2F.nTotal = 0;
stPaB2F.nParked = 0;
stPaB2F.nFree = 0;
stPaB3F.nTotal = 0;
stPaB3F.nParked = 0;
stPaB3F.nFree = 0;
stPaB4F.nTotal = 0;
stPaB4F.nParked = 0;
stPaB4F.nFree = 0;
for (i=0; i<pIBDI->numDispItem; i++)
{
pIDI = &pIBDI->bufDispItem[i];
if (pIDI->idxDevType != IDX_DEV_TYPE_USM)
{
continue;
}
stPaAll.nTotal++;
if(pIDI->idxCCM == 0){
if (pIDI->idxSCM == 0 || pIDI->idxSCM == 1 || pIDI->idxSCM == 2 || pIDI->idxSCM == 3 || pIDI->idxSCM == 4)
{
stPaB1F.nTotal++;
}
if (pIDI->idxSCM == 5 || pIDI->idxSCM == 6 || pIDI->idxSCM == 7 || pIDI->idxSCM == 8 || pIDI->idxSCM == 9)
{
stPaB2F.nTotal++;
}
}
//else if(pIDI->idxCCM == 1){
// stPaB2F.nTotal++;
//}
//else if(pIDI->idxCCM == 2){
// stPaB3F.nTotal++;
//}
//else if(pIDI->idxCCM == 3){
// stPaB4F.nTotal++;
//}
//else if(pIDI->idxCCM == 1){
// if (pIDI->idxSCM == 0 || pIDI->idxSCM == 1 || pIDI->idxSCM == 2)
// {
// stPa3F.nTotal++;
// }
// else if (pIDI->idxSCM == 3 || pIDI->idxSCM == 4 || pIDI->idxSCM == 5 )
// {
// stPa4F.nTotal++;
// }
// else if (pIDI->idxSCM == 6 || pIDI->idxSCM == 7 || pIDI->idxSCM == 8)
// {
// stPa5F.nTotal++;
// }
// ////else if (pIDI->idxSCM == 9)
// //{
// // stPa6F.nTotal = 196;
// //}
//}
nStat = pBufISC[pIDI->idxCCM].bufItem[pIDI->idxSCM].iStat.bufUSM_Stat[pIDI->idxUSM_LGM] & MASK_FOR_ICCS_USM_LGM_STAT;
if (nStat == IDX_OPM_SENS_LED_ON_GREEN ||
nStat == IDX_OPM_FORC_LED_ON_GREEN)
{
stPaAll.nFree++;
if(pIDI->idxCCM == 0){
if (pIDI->idxSCM == 0 || pIDI->idxSCM == 1 || pIDI->idxSCM == 2 || pIDI->idxSCM == 3 || pIDI->idxSCM == 4)
{
stPaB1F.nFree++;
}
if (pIDI->idxSCM == 5 || pIDI->idxSCM == 6 || pIDI->idxSCM == 7 || pIDI->idxSCM == 8 || pIDI->idxSCM == 9)
{
stPaB2F.nFree++;
}
}
/* else if(pIDI->idxCCM == 1){
stPaB2F.nFree++;
}
else if(pIDI->idxCCM == 2){
stPaB3F.nFree++;
}
else if(pIDI->idxCCM == 3){
stPaB4F.nFree++;
}*/
//else if(pIDI->idxCCM == 1){
// if (pIDI->idxSCM == 0 || pIDI->idxSCM == 1 || pIDI->idxSCM == 2)
// {
// stPa3F.nFree++;
// }
// else if (pIDI->idxSCM == 3 || pIDI->idxSCM == 4 || pIDI->idxSCM == 5 )
// {
// stPa4F.nFree++;
// }
// else if (pIDI->idxSCM == 6 || pIDI->idxSCM == 7 || pIDI->idxSCM == 8)
// {
// stPa5F.nFree++;
// }
// //else if (pIDI->idxSCM == 9)
// //{
// // stPa6F.nFree++;
// //}
//}
}
else
{
stPaAll.nParked++;
if(pIDI->idxCCM == 0){
if (pIDI->idxSCM == 0 || pIDI->idxSCM == 1 || pIDI->idxSCM == 2 || pIDI->idxSCM == 3 || pIDI->idxSCM == 4)
{
stPaB1F.nParked++;
}
if (pIDI->idxSCM == 5 || pIDI->idxSCM == 6 || pIDI->idxSCM == 7 || pIDI->idxSCM == 8 || pIDI->idxSCM == 9)
{
stPaB2F.nParked++;
}
}
//else if(pIDI->idxCCM == 1){
// stPaB2F.nParked++;
//}
//else if(pIDI->idxCCM == 2){
// stPaB3F.nParked++;
//}
//else if(pIDI->idxCCM == 3){
// stPaB4F.nParked++;
//}
//else if(pIDI->idxCCM == 1){
// if (pIDI->idxSCM == 0 || pIDI->idxSCM == 1 || pIDI->idxSCM == 2)
// {
// stPa3F.nParked++;
// }
// else if (pIDI->idxSCM == 3 || pIDI->idxSCM == 4 || pIDI->idxSCM == 5 )
// {
// stPa4F.nParked++;
// }
// else if (pIDI->idxSCM == 6 || pIDI->idxSCM == 7 || pIDI->idxSCM == 8)
// {
// stPa5F.nParked++;
// }
// //else if (pIDI->idxSCM == 9)
// //{
// // stPa6F.nParked++;
// //}
//}
}
}
}
void GetCurStat_B1_Upper (int &nTotal, int &nParked, int &nFree)
{
int i, j;
BYTE nStat;
ITEM_STAT_CCM *pBufISC = glInfoGlobal.unGVA.iGVA.pWMNC->GetBasePtrStatCCM ();
nTotal = 0;
nParked = 0;
nFree = 0;
for (i=13; i<=14; i++)
{
for (j=0; j<MAX_NUM_USM; j++)
{
if ((pBufISC[0].bufItem[i].iStat.bufUSM_Stat[j] &FLAG_ICCS_USM_USED) != 0)
{
nTotal++;
nStat = pBufISC[0].bufItem[i].iStat.bufUSM_Stat[j] &MASK_FOR_ICCS_USM_LGM_STAT;
if (nStat == IDX_OPM_SENS_LED_ON_GREEN ||
nStat == IDX_OPM_FORC_LED_ON_GREEN)
{
nFree++;
}
else
{
nParked++;
}
}
}
}
}
void GetCurStat_B1_Lower (int &nTotal, int &nParked, int &nFree)
{
int i, j;
BYTE nStat;
ITEM_STAT_CCM *pBufISC = glInfoGlobal.unGVA.iGVA.pWMNC->GetBasePtrStatCCM ();
nTotal = 0;
nParked = 0;
nFree = 0;
for (i=10; i<=12; i++)
{
for (j=0; j<MAX_NUM_USM; j++)
{
if ((pBufISC[0].bufItem[i].iStat.bufUSM_Stat[j] &FLAG_ICCS_USM_USED) != 0)
{
nTotal++;
nStat = pBufISC[0].bufItem[i].iStat.bufUSM_Stat[j] &MASK_FOR_ICCS_USM_LGM_STAT;
if (nStat == IDX_OPM_SENS_LED_ON_RED ||
nStat == IDX_OPM_FORC_LED_ON_RED)
{
nParked++;
}
else
{
nFree++;
}
}
}
}
}
void UpdateCurDispStat ()
{
int i;
for (i=0; i<glInfoGlobal.iBDA.numBDI; i++)
{
if (glInfoGlobal.iBDA.bufBDI[i].iVS.pView != NULL)
{
glInfoGlobal.iBDA.bufBDI[i].iVS.pView->SetBD_DispWndUpdateFlag ();
}
}
if (glInfoGlobal.unGVA.iGVA.pPaneBD != NULL)
{
glInfoGlobal.unGVA.iGVA.pPaneBD->UpdateCurStat ();
}
}
int MakeEBoardSendData (int nDST, CString strSnd, int *bufClr, BYTE *bufSnd)
{
INFO_BACK_DRAWING_ITEM *pIBDI;
STAT_PARKING_AREA stPaAll, stPaB1F,stPaB2F, stPaB3F, stPaB4F;
int bufClr2[MAX_PATH];
int szTxt = strSnd.GetLength ();
BYTE *pBufSnd;
int i, nLEN;
//pIBDI = &glInfoGlobal.iBDA.bufBDI[glInfoGlobal.iBDA.bufIdxMainBDI[1]];
//GetCurStatFromBDI (pIBDI, stPaAll, stPaB1F,stPaB2F, stPaB3F, stPaB4F);
for (i=0; i<MAX_PATH; i++)
{
bufClr[i] = IDX_EBD_CLR_GREEN;
}
pBufSnd = &bufSnd[0];
*pBufSnd++ = 0x10; // DLE
*pBufSnd++ = 0x02; // STX
*pBufSnd++ = nDST; // DST
nLEN = 12 +szTxt +szTxt;
*pBufSnd++ = (nLEN >>8) &0xff; // LEN(H)
*pBufSnd++ = (nLEN >>0) &0xff; // LEN(L)
*pBufSnd++ = 0x54; // CMD
*pBufSnd++ = 0x00; // Param 문구블록
*pBufSnd++ = 0x01; // Param 표시방법, 배경이미지
*pBufSnd++ = 0xf0; // Param 반복횟수
*pBufSnd++ = 0x93; // Param 문구 폰트크기, 문구 표시방법, 문구 전송방법
*pBufSnd++ = 0x00; // Param 화면분할위치
*pBufSnd++ = 0x00; // Param 문구 글자코드
*pBufSnd++ = 0x00; // Param 분할화면 효과
*pBufSnd++ = 0x00; // Param 메인화면 효과
*pBufSnd++ = 0xff; // Param 효과속도
*pBufSnd++ = 0xff; // Param 표시시간
*pBufSnd++ = 0x00; // Param 문구 수직위치
// Param 글자 색상[S]
for (i=0; i<szTxt; i++)
{
*pBufSnd++ = bufClr[i];
}
// Param 글자 색상[E]
// Param 문구[S]
for (i=0; i<szTxt; i++)
{
*pBufSnd++ = strSnd[i];
}
// Param 문구[E]
*pBufSnd++ = 0x10; // DLE
*pBufSnd++ = 0x03; // STX
// pComm->Send (bufSnd, 5 +nLEN +2);
// Write Debug Data[S]
char strDbg[256];
for (i=0; i<strSnd.GetLength (); i++)
{
strDbg[i] = strSnd[i];
}
strDbg[i +0] = '\n';
strDbg[i +1] = 0;
// AddReport (strDbg);
// Write Debug Data[E]
return (5 +nLEN +2);
}
int GetNumOfAllSCM ()
{
int numSCM, i, j;
INFO_CTRL_DEV_ALL *pICDA = &glInfoGlobal.iCDA;
numSCM = 0;
for (i=0; i<MAX_NUM_CCM; i++)
{
if (pICDA->bufICDevCCM[i].bUse == TRUE)
{
for (j=0; j<MAX_NUM_SCM; j++)
{
if (pICDA->bbufICDevSCM[i][j].bUse == TRUE)
{
numSCM++;
}
}
}
}
return numSCM;
}
int GetNumOfAllUSM ()
{
int numUSM, i, j, k;
INFO_CTRL_DEV_ALL *pICDA = &glInfoGlobal.iCDA;
numUSM = 0;
for (i=0; i<MAX_NUM_CCM; i++)
{
if (pICDA->bufICDevCCM[i].bUse == TRUE)
{
for (j=0; j<MAX_NUM_SCM; j++)
{
if (pICDA->bbufICDevSCM[i][j].bUse == TRUE)
{
for (k=0; k<MAX_NUM_USM; k++)
{
if (pICDA->bbbufICDevUSM[i][j][k].bUse == TRUE)
{
numUSM++;
}
}
}
}
}
}
return numUSM;
}
int GetNumOfAllLGM ()
{
int numLGM, i, j, k;
INFO_CTRL_DEV_ALL *pICDA = &glInfoGlobal.iCDA;
numLGM = 0;
for (i=0; i<MAX_NUM_CCM; i++)
{
if (pICDA->bufICDevCCM[i].bUse == TRUE)
{
for (j=0; j<MAX_NUM_SCM; j++)
{
if (pICDA->bbufICDevSCM[i][j].bUse == TRUE)
{
for (k=0; k<MAX_NUM_LGM; k++)
{
if (pICDA->bbbufICDevLGM[i][j][k].bUse == TRUE)
{
numLGM++;
}
}
}
}
}
}
return numLGM;
}
| [
"myeom66@gmail.com"
] | myeom66@gmail.com |
d606a04493cd0f526aef32278565b489ca54ff10 | a615d3604fc47643df42f7d9fd14102eb27efc7e | /vod/src/model/DescribeVodStorageDataRequest.cc | 68ec9312ce8ca5b163f7916dfe2683196b28bcd9 | [
"Apache-2.0"
] | permissive | CharlesE-233/aliyun-openapi-cpp-sdk | b5d336e8d5f8c6041f3d294d99b89965e3370831 | cba94f21199ae8943b5d0024099a90b1880024e7 | refs/heads/master | 2021-04-19T10:15:35.376349 | 2020-03-24T02:53:36 | 2020-03-24T02:53:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,407 | cc | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/vod/model/DescribeVodStorageDataRequest.h>
using AlibabaCloud::Vod::Model::DescribeVodStorageDataRequest;
DescribeVodStorageDataRequest::DescribeVodStorageDataRequest() :
RpcServiceRequest("vod", "2017-03-21", "DescribeVodStorageData")
{}
DescribeVodStorageDataRequest::~DescribeVodStorageDataRequest()
{}
std::string DescribeVodStorageDataRequest::getStartTime()const
{
return startTime_;
}
void DescribeVodStorageDataRequest::setStartTime(const std::string& startTime)
{
startTime_ = startTime;
setCoreParameter("StartTime", startTime);
}
std::string DescribeVodStorageDataRequest::getStorage()const
{
return storage_;
}
void DescribeVodStorageDataRequest::setStorage(const std::string& storage)
{
storage_ = storage;
setCoreParameter("Storage", storage);
}
std::string DescribeVodStorageDataRequest::getStorageType()const
{
return storageType_;
}
void DescribeVodStorageDataRequest::setStorageType(const std::string& storageType)
{
storageType_ = storageType;
setCoreParameter("StorageType", storageType);
}
std::string DescribeVodStorageDataRequest::getEndTime()const
{
return endTime_;
}
void DescribeVodStorageDataRequest::setEndTime(const std::string& endTime)
{
endTime_ = endTime;
setCoreParameter("EndTime", endTime);
}
long DescribeVodStorageDataRequest::getOwnerId()const
{
return ownerId_;
}
void DescribeVodStorageDataRequest::setOwnerId(long ownerId)
{
ownerId_ = ownerId;
setCoreParameter("OwnerId", std::to_string(ownerId));
}
std::string DescribeVodStorageDataRequest::getRegion()const
{
return region_;
}
void DescribeVodStorageDataRequest::setRegion(const std::string& region)
{
region_ = region;
setCoreParameter("Region", region);
}
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
36ae440e48a1dfed4be498131d0d9906c0b32b17 | 381bb42ab2c4c56fc934e7fb979c02b591b74022 | /project/video/CXStreamer/common/factorycommon.cpp | 2482f519d22cf79541ececbad05cd0f43e077cbf | [] | no_license | wp4613/HI3531D_BSP | 8858a880c317769d492bd05d24f189093e067d7c | 64cda51e76df56617cfc385ef9e50887d44bb269 | refs/heads/master | 2021-04-16T11:20:49.520645 | 2020-03-03T19:37:24 | 2020-03-03T19:37:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 537 | cpp | #include <string.h>
#include "../factory.h"
namespace CXS{
class FactoryCommon : public Factory
{
FactoryCommon(){
}
~FactoryCommon(){
}
public:
DECLARE_FACTORY_GET_INSTANCE(FactoryCommon)
};
static int init()
{
return 0;
}
static void deInit()
{
}
static struct FactoryDescriptor factoryDescriptor = {
"common",
init,
deInit,
FactoryCommon::getInstance
};
REGISTER_FACTORY(&factoryDescriptor);
}
| [
"you@example.com"
] | you@example.com |
64245e6e1e80d1fbd0ef6b5416f1acd06b9b97a3 | 0ae39e4f9744046848868cd58598f3f489fb22b4 | /Libraries/JUCE/modules/juce_audio_utils/gui/juce_BluetoothMidiDevicePairingDialogue.h | ae590154774486dcad1242aff461adf026104cbb | [] | no_license | gogirogi/RS-MET | b908509ddd7390d05476ffce9c9cbb30e95439e8 | d767896f542d8e00e803ad09d20c05b2f25c2c71 | refs/heads/master | 2021-08-19T21:56:36.416451 | 2017-11-27T14:11:52 | 2017-11-27T14:11:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,698 | h | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2015 - ROLI Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
#ifndef JUCE_BLUETOOTHMIDIDEVICPAIRINGCOMPONENT_H_INCLUDED
#define JUCE_BLUETOOTHMIDIDEVICPAIRINGCOMPONENT_H_INCLUDED
//==============================================================================
/**
Opens a Bluetooth MIDI pairing dialogue that allows the user to view and
connect to Bluetooth MIDI devices that are currently found nearby.
The dialogue will ignore non-MIDI Bluetooth devices.
Only after a Bluetooth MIDI device has been paired will its MIDI ports
be available through JUCE's MidiInput and MidiOutput classes.
This dialogue is currently only available on iOS and Android. On OSX,
you should instead pair Bluetooth MIDI devices using the "Audio MIDI Setup"
app (located in /Applications/Utilities). On Windows, you should use
the system settings. On Linux, Bluetooth MIDI devices are currently not
supported.
*/
class JUCE_API BluetoothMidiDevicePairingDialogue
{
public:
/** Opens the Bluetooth MIDI pairing dialogue, if it is available.
@return true if the dialogue was opened, false on error.
*/
static bool open();
/** Checks if a Bluetooth MIDI pairing dialogue is available on this
platform.
On iOS, this will be true for iOS versions 8.0 and higher.
On Android, this will be true only for Android SDK versions 23 and
higher, and additionally only if the device itself supports MIDI
over Bluetooth.
On desktop platforms, this will typically be false as the bluetooth
pairing is not done inside the app but by other means.
@return true if the Bluetooth MIDI pairing dialogue is available,
false otherwise.
*/
static bool isAvailable();
};
#endif // JUCE_BLUETOOTHMIDIDEVICPAIRINGCOMPONENT_H_INCLUDED
| [
"robin@rs-met.com"
] | robin@rs-met.com |
75806fc95965d9c833b46ba8306130e82aa7d15f | e50b5f066628ef65fd7f79078b4b1088f9d11e87 | /llvm/tools/clang/include/clang/AST/ASTTypeTraits.h | f14e45950360234004b925bd19158bfb54f7995e | [
"NCSA"
] | permissive | uzleo/coast | 1471e03b2a1ffc9883392bf80711e6159917dca1 | 04bd688ac9a18d2327c59ea0c90f72e9b49df0f4 | refs/heads/master | 2020-05-16T11:46:24.870750 | 2019-04-23T13:57:53 | 2019-04-23T13:57:53 | 183,025,687 | 0 | 0 | null | 2019-04-23T13:52:28 | 2019-04-23T13:52:27 | null | UTF-8 | C++ | false | false | 19,214 | h | //===--- ASTTypeTraits.h ----------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Provides a dynamic type identifier and a dynamically typed node container
// that can be used to store an AST base node at runtime in the same storage in
// a type safe way.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_ASTTYPETRAITS_H
#define LLVM_CLANG_AST_ASTTYPETRAITS_H
#include "clang/AST/ASTFwd.h"
#include "clang/AST/Decl.h"
#include "clang/AST/NestedNameSpecifier.h"
#include "clang/AST/Stmt.h"
#include "clang/AST/TemplateBase.h"
#include "clang/AST/TypeLoc.h"
#include "clang/Basic/LLVM.h"
#include "llvm/ADT/DenseMapInfo.h"
#include "llvm/Support/AlignOf.h"
namespace llvm {
class raw_ostream;
}
namespace clang {
struct PrintingPolicy;
namespace ast_type_traits {
/// \brief Kind identifier.
///
/// It can be constructed from any node kind and allows for runtime type
/// hierarchy checks.
/// Use getFromNodeKind<T>() to construct them.
class ASTNodeKind {
public:
/// \brief Empty identifier. It matches nothing.
ASTNodeKind() : KindId(NKI_None) {}
/// \brief Construct an identifier for T.
template <class T>
static ASTNodeKind getFromNodeKind() {
return ASTNodeKind(KindToKindId<T>::Id);
}
/// \{
/// \brief Construct an identifier for the dynamic type of the node
static ASTNodeKind getFromNode(const Decl &D);
static ASTNodeKind getFromNode(const Stmt &S);
static ASTNodeKind getFromNode(const Type &T);
/// \}
/// \brief Returns \c true if \c this and \c Other represent the same kind.
bool isSame(ASTNodeKind Other) const {
return KindId != NKI_None && KindId == Other.KindId;
}
/// \brief Returns \c true only for the default \c ASTNodeKind()
bool isNone() const { return KindId == NKI_None; }
/// \brief Returns \c true if \c this is a base kind of (or same as) \c Other.
/// \param Distance If non-null, used to return the distance between \c this
/// and \c Other in the class hierarchy.
bool isBaseOf(ASTNodeKind Other, unsigned *Distance = nullptr) const;
/// \brief String representation of the kind.
StringRef asStringRef() const;
/// \brief Strict weak ordering for ASTNodeKind.
bool operator<(const ASTNodeKind &Other) const {
return KindId < Other.KindId;
}
/// \brief Return the most derived type between \p Kind1 and \p Kind2.
///
/// Return ASTNodeKind() if they are not related.
static ASTNodeKind getMostDerivedType(ASTNodeKind Kind1, ASTNodeKind Kind2);
/// \brief Return the most derived common ancestor between Kind1 and Kind2.
///
/// Return ASTNodeKind() if they are not related.
static ASTNodeKind getMostDerivedCommonAncestor(ASTNodeKind Kind1,
ASTNodeKind Kind2);
/// \brief Hooks for using ASTNodeKind as a key in a DenseMap.
struct DenseMapInfo {
// ASTNodeKind() is a good empty key because it is represented as a 0.
static inline ASTNodeKind getEmptyKey() { return ASTNodeKind(); }
// NKI_NumberOfKinds is not a valid value, so it is good for a
// tombstone key.
static inline ASTNodeKind getTombstoneKey() {
return ASTNodeKind(NKI_NumberOfKinds);
}
static unsigned getHashValue(const ASTNodeKind &Val) { return Val.KindId; }
static bool isEqual(const ASTNodeKind &LHS, const ASTNodeKind &RHS) {
return LHS.KindId == RHS.KindId;
}
};
/// Check if the given ASTNodeKind identifies a type that offers pointer
/// identity. This is useful for the fast path in DynTypedNode.
bool hasPointerIdentity() const {
return KindId > NKI_LastKindWithoutPointerIdentity;
}
private:
/// \brief Kind ids.
///
/// Includes all possible base and derived kinds.
enum NodeKindId {
NKI_None,
NKI_TemplateArgument,
NKI_NestedNameSpecifierLoc,
NKI_QualType,
NKI_TypeLoc,
NKI_LastKindWithoutPointerIdentity = NKI_TypeLoc,
NKI_CXXCtorInitializer,
NKI_NestedNameSpecifier,
NKI_Decl,
#define DECL(DERIVED, BASE) NKI_##DERIVED##Decl,
#include "clang/AST/DeclNodes.inc"
NKI_Stmt,
#define STMT(DERIVED, BASE) NKI_##DERIVED,
#include "clang/AST/StmtNodes.inc"
NKI_Type,
#define TYPE(DERIVED, BASE) NKI_##DERIVED##Type,
#include "clang/AST/TypeNodes.def"
NKI_NumberOfKinds
};
/// \brief Use getFromNodeKind<T>() to construct the kind.
ASTNodeKind(NodeKindId KindId) : KindId(KindId) {}
/// \brief Returns \c true if \c Base is a base kind of (or same as) \c
/// Derived.
/// \param Distance If non-null, used to return the distance between \c Base
/// and \c Derived in the class hierarchy.
static bool isBaseOf(NodeKindId Base, NodeKindId Derived, unsigned *Distance);
/// \brief Helper meta-function to convert a kind T to its enum value.
///
/// This struct is specialized below for all known kinds.
template <class T> struct KindToKindId {
static const NodeKindId Id = NKI_None;
};
template <class T>
struct KindToKindId<const T> : KindToKindId<T> {};
/// \brief Per kind info.
struct KindInfo {
/// \brief The id of the parent kind, or None if it has no parent.
NodeKindId ParentId;
/// \brief Name of the kind.
const char *Name;
};
static const KindInfo AllKindInfo[NKI_NumberOfKinds];
NodeKindId KindId;
};
#define KIND_TO_KIND_ID(Class) \
template <> struct ASTNodeKind::KindToKindId<Class> { \
static const NodeKindId Id = NKI_##Class; \
};
KIND_TO_KIND_ID(CXXCtorInitializer)
KIND_TO_KIND_ID(TemplateArgument)
KIND_TO_KIND_ID(NestedNameSpecifier)
KIND_TO_KIND_ID(NestedNameSpecifierLoc)
KIND_TO_KIND_ID(QualType)
KIND_TO_KIND_ID(TypeLoc)
KIND_TO_KIND_ID(Decl)
KIND_TO_KIND_ID(Stmt)
KIND_TO_KIND_ID(Type)
#define DECL(DERIVED, BASE) KIND_TO_KIND_ID(DERIVED##Decl)
#include "clang/AST/DeclNodes.inc"
#define STMT(DERIVED, BASE) KIND_TO_KIND_ID(DERIVED)
#include "clang/AST/StmtNodes.inc"
#define TYPE(DERIVED, BASE) KIND_TO_KIND_ID(DERIVED##Type)
#include "clang/AST/TypeNodes.def"
#undef KIND_TO_KIND_ID
inline raw_ostream &operator<<(raw_ostream &OS, ASTNodeKind K) {
OS << K.asStringRef();
return OS;
}
/// \brief A dynamically typed AST node container.
///
/// Stores an AST node in a type safe way. This allows writing code that
/// works with different kinds of AST nodes, despite the fact that they don't
/// have a common base class.
///
/// Use \c create(Node) to create a \c DynTypedNode from an AST node,
/// and \c get<T>() to retrieve the node as type T if the types match.
///
/// See \c ASTNodeKind for which node base types are currently supported;
/// You can create DynTypedNodes for all nodes in the inheritance hierarchy of
/// the supported base types.
class DynTypedNode {
public:
/// \brief Creates a \c DynTypedNode from \c Node.
template <typename T>
static DynTypedNode create(const T &Node) {
return BaseConverter<T>::create(Node);
}
/// \brief Retrieve the stored node as type \c T.
///
/// Returns NULL if the stored node does not have a type that is
/// convertible to \c T.
///
/// For types that have identity via their pointer in the AST
/// (like \c Stmt, \c Decl, \c Type and \c NestedNameSpecifier) the returned
/// pointer points to the referenced AST node.
/// For other types (like \c QualType) the value is stored directly
/// in the \c DynTypedNode, and the returned pointer points at
/// the storage inside DynTypedNode. For those nodes, do not
/// use the pointer outside the scope of the DynTypedNode.
template <typename T>
const T *get() const {
return BaseConverter<T>::get(NodeKind, Storage.buffer);
}
/// \brief Retrieve the stored node as type \c T.
///
/// Similar to \c get(), but asserts that the type is what we are expecting.
template <typename T>
const T &getUnchecked() const {
return BaseConverter<T>::getUnchecked(NodeKind, Storage.buffer);
}
ASTNodeKind getNodeKind() const { return NodeKind; }
/// \brief Returns a pointer that identifies the stored AST node.
///
/// Note that this is not supported by all AST nodes. For AST nodes
/// that don't have a pointer-defined identity inside the AST, this
/// method returns NULL.
const void *getMemoizationData() const {
return NodeKind.hasPointerIdentity()
? *reinterpret_cast<void *const *>(Storage.buffer)
: nullptr;
}
/// \brief Prints the node to the given output stream.
void print(llvm::raw_ostream &OS, const PrintingPolicy &PP) const;
/// \brief Dumps the node to the given output stream.
void dump(llvm::raw_ostream &OS, SourceManager &SM) const;
/// \brief For nodes which represent textual entities in the source code,
/// return their SourceRange. For all other nodes, return SourceRange().
SourceRange getSourceRange() const;
/// @{
/// \brief Imposes an order on \c DynTypedNode.
///
/// Supports comparison of nodes that support memoization.
/// FIXME: Implement comparsion for other node types (currently
/// only Stmt, Decl, Type and NestedNameSpecifier return memoization data).
bool operator<(const DynTypedNode &Other) const {
if (!NodeKind.isSame(Other.NodeKind))
return NodeKind < Other.NodeKind;
if (ASTNodeKind::getFromNodeKind<QualType>().isSame(NodeKind))
return getUnchecked<QualType>().getAsOpaquePtr() <
Other.getUnchecked<QualType>().getAsOpaquePtr();
if (ASTNodeKind::getFromNodeKind<TypeLoc>().isSame(NodeKind)) {
auto TLA = getUnchecked<TypeLoc>();
auto TLB = Other.getUnchecked<TypeLoc>();
return std::make_pair(TLA.getType().getAsOpaquePtr(),
TLA.getOpaqueData()) <
std::make_pair(TLB.getType().getAsOpaquePtr(),
TLB.getOpaqueData());
}
if (ASTNodeKind::getFromNodeKind<NestedNameSpecifierLoc>().isSame(
NodeKind)) {
auto NNSLA = getUnchecked<NestedNameSpecifierLoc>();
auto NNSLB = Other.getUnchecked<NestedNameSpecifierLoc>();
return std::make_pair(NNSLA.getNestedNameSpecifier(),
NNSLA.getOpaqueData()) <
std::make_pair(NNSLB.getNestedNameSpecifier(),
NNSLB.getOpaqueData());
}
assert(getMemoizationData() && Other.getMemoizationData());
return getMemoizationData() < Other.getMemoizationData();
}
bool operator==(const DynTypedNode &Other) const {
// DynTypedNode::create() stores the exact kind of the node in NodeKind.
// If they contain the same node, their NodeKind must be the same.
if (!NodeKind.isSame(Other.NodeKind))
return false;
// FIXME: Implement for other types.
if (ASTNodeKind::getFromNodeKind<QualType>().isSame(NodeKind))
return getUnchecked<QualType>() == Other.getUnchecked<QualType>();
if (ASTNodeKind::getFromNodeKind<TypeLoc>().isSame(NodeKind))
return getUnchecked<TypeLoc>() == Other.getUnchecked<TypeLoc>();
if (ASTNodeKind::getFromNodeKind<NestedNameSpecifierLoc>().isSame(NodeKind))
return getUnchecked<NestedNameSpecifierLoc>() ==
Other.getUnchecked<NestedNameSpecifierLoc>();
assert(getMemoizationData() && Other.getMemoizationData());
return getMemoizationData() == Other.getMemoizationData();
}
bool operator!=(const DynTypedNode &Other) const {
return !operator==(Other);
}
/// @}
/// \brief Hooks for using DynTypedNode as a key in a DenseMap.
struct DenseMapInfo {
static inline DynTypedNode getEmptyKey() {
DynTypedNode Node;
Node.NodeKind = ASTNodeKind::DenseMapInfo::getEmptyKey();
return Node;
}
static inline DynTypedNode getTombstoneKey() {
DynTypedNode Node;
Node.NodeKind = ASTNodeKind::DenseMapInfo::getTombstoneKey();
return Node;
}
static unsigned getHashValue(const DynTypedNode &Val) {
// FIXME: Add hashing support for the remaining types.
if (ASTNodeKind::getFromNodeKind<TypeLoc>().isSame(Val.NodeKind)) {
auto TL = Val.getUnchecked<TypeLoc>();
return llvm::hash_combine(TL.getType().getAsOpaquePtr(),
TL.getOpaqueData());
}
if (ASTNodeKind::getFromNodeKind<NestedNameSpecifierLoc>().isSame(
Val.NodeKind)) {
auto NNSL = Val.getUnchecked<NestedNameSpecifierLoc>();
return llvm::hash_combine(NNSL.getNestedNameSpecifier(),
NNSL.getOpaqueData());
}
assert(Val.getMemoizationData());
return llvm::hash_value(Val.getMemoizationData());
}
static bool isEqual(const DynTypedNode &LHS, const DynTypedNode &RHS) {
auto Empty = ASTNodeKind::DenseMapInfo::getEmptyKey();
auto TombStone = ASTNodeKind::DenseMapInfo::getTombstoneKey();
return (ASTNodeKind::DenseMapInfo::isEqual(LHS.NodeKind, Empty) &&
ASTNodeKind::DenseMapInfo::isEqual(RHS.NodeKind, Empty)) ||
(ASTNodeKind::DenseMapInfo::isEqual(LHS.NodeKind, TombStone) &&
ASTNodeKind::DenseMapInfo::isEqual(RHS.NodeKind, TombStone)) ||
LHS == RHS;
}
};
private:
/// \brief Takes care of converting from and to \c T.
template <typename T, typename EnablerT = void> struct BaseConverter;
/// \brief Converter that uses dyn_cast<T> from a stored BaseT*.
template <typename T, typename BaseT> struct DynCastPtrConverter {
static const T *get(ASTNodeKind NodeKind, const char Storage[]) {
if (ASTNodeKind::getFromNodeKind<T>().isBaseOf(NodeKind))
return &getUnchecked(NodeKind, Storage);
return nullptr;
}
static const T &getUnchecked(ASTNodeKind NodeKind, const char Storage[]) {
assert(ASTNodeKind::getFromNodeKind<T>().isBaseOf(NodeKind));
return *cast<T>(static_cast<const BaseT *>(
*reinterpret_cast<const void *const *>(Storage)));
}
static DynTypedNode create(const BaseT &Node) {
DynTypedNode Result;
Result.NodeKind = ASTNodeKind::getFromNode(Node);
new (Result.Storage.buffer) const void *(&Node);
return Result;
}
};
/// \brief Converter that stores T* (by pointer).
template <typename T> struct PtrConverter {
static const T *get(ASTNodeKind NodeKind, const char Storage[]) {
if (ASTNodeKind::getFromNodeKind<T>().isSame(NodeKind))
return &getUnchecked(NodeKind, Storage);
return nullptr;
}
static const T &getUnchecked(ASTNodeKind NodeKind, const char Storage[]) {
assert(ASTNodeKind::getFromNodeKind<T>().isSame(NodeKind));
return *static_cast<const T *>(
*reinterpret_cast<const void *const *>(Storage));
}
static DynTypedNode create(const T &Node) {
DynTypedNode Result;
Result.NodeKind = ASTNodeKind::getFromNodeKind<T>();
new (Result.Storage.buffer) const void *(&Node);
return Result;
}
};
/// \brief Converter that stores T (by value).
template <typename T> struct ValueConverter {
static const T *get(ASTNodeKind NodeKind, const char Storage[]) {
if (ASTNodeKind::getFromNodeKind<T>().isSame(NodeKind))
return reinterpret_cast<const T *>(Storage);
return nullptr;
}
static const T &getUnchecked(ASTNodeKind NodeKind, const char Storage[]) {
assert(ASTNodeKind::getFromNodeKind<T>().isSame(NodeKind));
return *reinterpret_cast<const T *>(Storage);
}
static DynTypedNode create(const T &Node) {
DynTypedNode Result;
Result.NodeKind = ASTNodeKind::getFromNodeKind<T>();
new (Result.Storage.buffer) T(Node);
return Result;
}
};
ASTNodeKind NodeKind;
/// \brief Stores the data of the node.
///
/// Note that we can store \c Decls, \c Stmts, \c Types,
/// \c NestedNameSpecifiers and \c CXXCtorInitializer by pointer as they are
/// guaranteed to be unique pointers pointing to dedicated storage in the AST.
/// \c QualTypes, \c NestedNameSpecifierLocs, \c TypeLocs and
/// \c TemplateArguments on the other hand do not have storage or unique
/// pointers and thus need to be stored by value.
llvm::AlignedCharArrayUnion<const void *, TemplateArgument,
NestedNameSpecifierLoc, QualType,
TypeLoc> Storage;
};
template <typename T>
struct DynTypedNode::BaseConverter<
T, typename std::enable_if<std::is_base_of<Decl, T>::value>::type>
: public DynCastPtrConverter<T, Decl> {};
template <typename T>
struct DynTypedNode::BaseConverter<
T, typename std::enable_if<std::is_base_of<Stmt, T>::value>::type>
: public DynCastPtrConverter<T, Stmt> {};
template <typename T>
struct DynTypedNode::BaseConverter<
T, typename std::enable_if<std::is_base_of<Type, T>::value>::type>
: public DynCastPtrConverter<T, Type> {};
template <>
struct DynTypedNode::BaseConverter<
NestedNameSpecifier, void> : public PtrConverter<NestedNameSpecifier> {};
template <>
struct DynTypedNode::BaseConverter<
CXXCtorInitializer, void> : public PtrConverter<CXXCtorInitializer> {};
template <>
struct DynTypedNode::BaseConverter<
TemplateArgument, void> : public ValueConverter<TemplateArgument> {};
template <>
struct DynTypedNode::BaseConverter<
NestedNameSpecifierLoc,
void> : public ValueConverter<NestedNameSpecifierLoc> {};
template <>
struct DynTypedNode::BaseConverter<QualType,
void> : public ValueConverter<QualType> {};
template <>
struct DynTypedNode::BaseConverter<
TypeLoc, void> : public ValueConverter<TypeLoc> {};
// The only operation we allow on unsupported types is \c get.
// This allows to conveniently use \c DynTypedNode when having an arbitrary
// AST node that is not supported, but prevents misuse - a user cannot create
// a DynTypedNode from arbitrary types.
template <typename T, typename EnablerT> struct DynTypedNode::BaseConverter {
static const T *get(ASTNodeKind NodeKind, const char Storage[]) {
return NULL;
}
};
} // end namespace ast_type_traits
} // end namespace clang
namespace llvm {
template <>
struct DenseMapInfo<clang::ast_type_traits::ASTNodeKind>
: clang::ast_type_traits::ASTNodeKind::DenseMapInfo {};
template <>
struct DenseMapInfo<clang::ast_type_traits::DynTypedNode>
: clang::ast_type_traits::DynTypedNode::DenseMapInfo {};
} // end namespace llvm
#endif
| [
"jeffrey.goeders@gmail.com"
] | jeffrey.goeders@gmail.com |
6078c08e30b518d08d4cd71f51031c02064a7d51 | 43ef1f7464e4dbaacb116176698c6c09daef3558 | /과제제출/API/Mine/Doyun's_Engine/ResourcesManager.h | 0647b4ed85ff5e986365bc11a30db863efe7b225 | [] | no_license | Sicarim/UmDoYun | ab17b61c0679fb9cffb48863b152b1425c288745 | ec7f29025ee1b6d649a1a6fc97913c42081095eb | refs/heads/master | 2023-04-29T11:18:55.521613 | 2021-05-11T07:43:07 | 2021-05-11T07:43:07 | 207,284,540 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,040 | h | #pragma once
#include "GlobalDefine.h"
#include "SingleTon.h"
#include "BitMap.h"
using namespace std;
namespace DoEngine
{
/**
* @brief DoEngine::BitMap클레스를 관리하는 클래스
* @details DoEngine::BitMap클레스를 관리하는 클래스 , 같은 DoEngine::BitMap 객체가 생성되는 것을 막아주고 파일로드를 담당.
*/
class ResourcesManager : public Singleton<ResourcesManager>
{
private:
DoEngine::BitMap* m_pBack; //비트맵 객체 선언
map<string, DoEngine::BitMap*> m_mapBitmap; //맵(자료구조)형식의 BitMap선언
DoEngine::BitMap* InitBitmap(std::string strFileName); //Resoureces에 해당 그림을 그린다
public:
ResourcesManager(); //생성자
void InitBack(HDC hdc, int cx, int cy); //윈도우 크기에 맞추서 BackDC를 생성
HDC get_BackDC();
void DrawBack(HDC hdc);
DoEngine::BitMap* get_Bitmap(std::string strFileName); //vector에서 같은 이름을 가진 bmp파일을 찾는다 없다면 새로 만든다
~ResourcesManager(); //소멸자
};
} | [
"djawleh@naver.com"
] | djawleh@naver.com |
5055b72155520e0e788e5a70a1b201797b9be235 | 31ac07ecd9225639bee0d08d00f037bd511e9552 | /externals/OCCTLib/inc/BOPAlgo_BuilderSolid.hxx | cb859a7c97410963e9a4bd3e2b85d182eb27c826 | [] | no_license | litao1009/SimpleRoom | 4520e0034e4f90b81b922657b27f201842e68e8e | 287de738c10b86ff8f61b15e3b8afdfedbcb2211 | refs/heads/master | 2021-01-20T19:56:39.507899 | 2016-07-29T08:01:57 | 2016-07-29T08:01:57 | 64,462,604 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,313 | hxx | // This file is generated by WOK (CPPExt).
// Please do not edit this file; modify original file instead.
// The copyright and license terms as defined for the original file apply to
// this header file considered to be the "object code" form of the original source.
#ifndef _BOPAlgo_BuilderSolid_HeaderFile
#define _BOPAlgo_BuilderSolid_HeaderFile
#ifndef _Standard_HeaderFile
#include <Standard.hxx>
#endif
#ifndef _Standard_DefineAlloc_HeaderFile
#include <Standard_DefineAlloc.hxx>
#endif
#ifndef _Standard_Macro_HeaderFile
#include <Standard_Macro.hxx>
#endif
#ifndef _TopoDS_Solid_HeaderFile
#include <TopoDS_Solid.hxx>
#endif
#ifndef _BOPAlgo_BuilderArea_HeaderFile
#include <BOPAlgo_BuilderArea.hxx>
#endif
#ifndef _BOPCol_BaseAllocator_HeaderFile
#include <BOPCol_BaseAllocator.hxx>
#endif
class TopoDS_Solid;
//! The algorithm to build solids from set of faces <br>
class BOPAlgo_BuilderSolid : public BOPAlgo_BuilderArea {
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT BOPAlgo_BuilderSolid();
Standard_EXPORT virtual ~BOPAlgo_BuilderSolid();
Standard_EXPORT BOPAlgo_BuilderSolid(const BOPCol_BaseAllocator& theAllocator);
//! Sets the source solid <theSolid> <br>
Standard_EXPORT void SetSolid(const TopoDS_Solid& theSolid) ;
//! Returns the source solid <br>
Standard_EXPORT const TopoDS_Solid& Solid() const;
//! Performs the algorithm <br>
Standard_EXPORT virtual void Perform() ;
protected:
//! Collect the faces that <br>
//! a) are internal <br>
//! b) are the same and have different orientation <br>
Standard_EXPORT virtual void PerformShapesToAvoid() ;
//! Build draft shells <br>
//! a)myLoops - draft shells that consist of <br>
//! boundary faces <br>
//! b)myLoopsInternal - draft shells that contains <br>
//! inner faces <br>
Standard_EXPORT virtual void PerformLoops() ;
//! Build draft solids that contains boundary faces <br>
Standard_EXPORT virtual void PerformAreas() ;
//! Build finalized solids with internal shells <br>
Standard_EXPORT virtual void PerformInternalShapes() ;
TopoDS_Solid mySolid;
private:
};
// other Inline functions and methods (like "C++: function call" methods)
#endif
| [
"litao1009@gmail.com"
] | litao1009@gmail.com |
3a3dd97992b26a19c45378adc06cc7a426c2c71e | 5e324fbfcb83944332f11834342dfd188f0c5c09 | /tests/DrawOpAtlasTest.cpp | e45ef525a170609d7dc62cb27a018deda7ed5e7e | [
"BSD-3-Clause"
] | permissive | weiwang74/skia | 5d48d8c63abba54abe7da29f43eb5cb037c5e0c3 | 827af667bbe8e057f9ee08e9f9b598add232b491 | refs/heads/master | 2021-04-03T08:31:05.296757 | 2018-03-09T21:08:58 | 2018-03-12T14:07:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,664 | cpp | /*
* Copyright 2018 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkTypes.h"
#if SK_SUPPORT_GPU
#include "GrContextPriv.h"
#include "Test.h"
#include "text/GrGlyphCache.h"
static const int kNumPlots = 2;
static const int kPlotSize = 32;
static const int kAtlasSize = kNumPlots * kPlotSize;
int GrDrawOpAtlas::numAllocated_TestingOnly() const {
int count = 0;
for (uint32_t i = 0; i < this->maxPages(); ++i) {
if (fProxies[i]->priv().isInstantiated()) {
++count;
}
}
return count;
}
void GrAtlasManager::setMaxPages_TestingOnly(uint32_t numPages) {
for (int i = 0; i < kMaskFormatCount; i++) {
if (fAtlases[i]) {
fAtlases[i]->setMaxPages_TestingOnly(numPages);
}
}
}
void GrDrawOpAtlas::setMaxPages_TestingOnly(uint32_t maxPages) {
SkASSERT(!fNumActivePages);
fMaxPages = maxPages;
}
void EvictionFunc(GrDrawOpAtlas::AtlasID atlasID, void*) {
SkASSERT(0); // The unit test shouldn't exercise this code path
}
static void check(skiatest::Reporter* r, GrDrawOpAtlas* atlas,
uint32_t expectedActive, uint32_t expectedMax, int expectedAlloced) {
REPORTER_ASSERT(r, expectedActive == atlas->numActivePages());
REPORTER_ASSERT(r, expectedMax == atlas->maxPages());
REPORTER_ASSERT(r, expectedAlloced == atlas->numAllocated_TestingOnly());
}
class TestingUploadTarget : public GrDeferredUploadTarget {
public:
TestingUploadTarget() { }
const GrTokenTracker* tokenTracker() final { return &fTokenTracker; }
GrTokenTracker* writeableTokenTracker() { return &fTokenTracker; }
GrDeferredUploadToken addInlineUpload(GrDeferredTextureUploadFn&&) final {
SkASSERT(0); // this test shouldn't invoke this code path
return fTokenTracker.nextDrawToken();
}
virtual GrDeferredUploadToken addASAPUpload(GrDeferredTextureUploadFn&& upload) final {
return fTokenTracker.nextTokenToFlush();
}
void issueDrawToken() { fTokenTracker.issueDrawToken(); }
void flushToken() { fTokenTracker.flushToken(); }
private:
GrTokenTracker fTokenTracker;
typedef GrDeferredUploadTarget INHERITED;
};
static bool fill_plot(GrDrawOpAtlas* atlas,
GrResourceProvider* resourceProvider,
GrDeferredUploadTarget* target,
GrDrawOpAtlas::AtlasID* atlasID,
int alpha) {
SkImageInfo ii = SkImageInfo::MakeA8(kPlotSize, kPlotSize);
SkBitmap data;
data.allocPixels(ii);
data.eraseARGB(alpha, 0, 0, 0);
SkIPoint16 loc;
GrDrawOpAtlas::ErrorCode code;
code = atlas->addToAtlas(resourceProvider, atlasID, target, kPlotSize, kPlotSize,
data.getAddr(0, 0), &loc);
return GrDrawOpAtlas::ErrorCode::kSucceeded == code;
}
// This is a basic DrawOpAtlas test. It simply verifies that multitexture atlases correctly
// add and remove pages. Note that this is simulating flush-time behavior.
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(BasicDrawOpAtlas, reporter, ctxInfo) {
auto context = ctxInfo.grContext();
auto proxyProvider = context->contextPriv().proxyProvider();
auto resourceProvider = context->contextPriv().resourceProvider();
auto drawingManager = context->contextPriv().drawingManager();
GrOnFlushResourceProvider onFlushResourceProvider(drawingManager);
TestingUploadTarget uploadTarget;
std::unique_ptr<GrDrawOpAtlas> atlas = GrDrawOpAtlas::Make(
proxyProvider,
kAlpha_8_GrPixelConfig,
kAtlasSize, kAtlasSize,
kNumPlots, kNumPlots,
GrDrawOpAtlas::AllowMultitexturing::kYes,
EvictionFunc, nullptr);
check(reporter, atlas.get(), 0, 4, 0);
// Fill up the first level
GrDrawOpAtlas::AtlasID atlasIDs[kNumPlots * kNumPlots];
for (int i = 0; i < kNumPlots * kNumPlots; ++i) {
bool result = fill_plot(atlas.get(), resourceProvider, &uploadTarget, &atlasIDs[i], i*32);
REPORTER_ASSERT(reporter, result);
check(reporter, atlas.get(), 1, 4, 1);
}
atlas->instantiate(&onFlushResourceProvider);
check(reporter, atlas.get(), 1, 4, 1);
// Force allocation of a second level
GrDrawOpAtlas::AtlasID atlasID;
bool result = fill_plot(atlas.get(), resourceProvider, &uploadTarget, &atlasID, 4*32);
REPORTER_ASSERT(reporter, result);
check(reporter, atlas.get(), 2, 4, 2);
// Simulate a lot of draws using only the first plot. The last texture should be compacted.
for (int i = 0; i < 512; ++i) {
atlas->setLastUseToken(atlasIDs[0], uploadTarget.tokenTracker()->nextDrawToken());
uploadTarget.issueDrawToken();
uploadTarget.flushToken();
atlas->compact(uploadTarget.tokenTracker()->nextTokenToFlush());
}
check(reporter, atlas.get(), 1, 4, 1);
}
#include "GrTest.h"
#include "GrDrawingManager.h"
#include "GrOpFlushState.h"
#include "GrProxyProvider.h"
#include "effects/GrConstColorProcessor.h"
#include "ops/GrAtlasTextOp.h"
#include "text/GrAtlasTextContext.h"
// This test verifies that the GrAtlasTextOp::onPrepare method correctly handles a failure
// when allocating an atlas page.
DEF_GPUTEST_FOR_RENDERING_CONTEXTS(GrAtlasTextOpPreparation, reporter, ctxInfo) {
auto context = ctxInfo.grContext();
auto gpu = context->contextPriv().getGpu();
auto resourceProvider = context->contextPriv().resourceProvider();
auto drawingManager = context->contextPriv().drawingManager();
auto textContext = drawingManager->getAtlasTextContext();
auto rtc = context->contextPriv().makeDeferredRenderTargetContext(SkBackingFit::kApprox,
32, 32,
kRGBA_8888_GrPixelConfig,
nullptr);
SkPaint paint;
paint.setColor(SK_ColorRED);
paint.setLCDRenderText(false);
paint.setAntiAlias(false);
paint.setSubpixelText(false);
GrTextUtils::Paint utilsPaint(&paint, &rtc->colorSpaceInfo());
const char* text = "a";
std::unique_ptr<GrDrawOp> op = textContext->createOp_TestingOnly(context, textContext,
rtc.get(), paint,
SkMatrix::I(), text,
16, 16);
op->finalize(*context->caps(), nullptr, GrPixelConfigIsClamped::kNo);
TestingUploadTarget uploadTarget;
GrOpFlushState flushState(gpu, resourceProvider, uploadTarget.writeableTokenTracker());
GrOpFlushState::OpArgs opArgs = {
op.get(),
rtc->asRenderTargetProxy(),
nullptr,
GrXferProcessor::DstProxy(nullptr, SkIPoint::Make(0, 0))
};
// Cripple the atlas manager so it can't allocate any pages. This will force a failure
// in the preparation of the text op
auto atlasManager = context->contextPriv().getAtlasManager();
unsigned int numProxies;
atlasManager->getProxies(kA8_GrMaskFormat, &numProxies);
atlasManager->setMaxPages_TestingOnly(0);
flushState.setOpArgs(&opArgs);
op->prepare(&flushState);
flushState.setOpArgs(nullptr);
}
#endif
| [
"skia-commit-bot@chromium.org"
] | skia-commit-bot@chromium.org |
e723b93a503fad0e8d6ddb64ca1c759b6dacaa41 | 53b609ab511e401a4a91df2551e8654dc9510194 | /Ray.h | d0fd044a6008213a00eb95fc95e08718926c36f9 | [] | no_license | Software-Steve/RayTracer | f6268770cd154a744361abba373a11cd3ed1ca66 | 60edc980e1e7cec7f5b8f0c0303d09044d808430 | refs/heads/master | 2021-01-18T13:59:21.878668 | 2015-08-07T01:53:15 | 2015-08-07T01:53:15 | 40,334,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 133 | h | #ifndef RAY_H
#define RAY_H
#include <glm/glm.hpp>
class Ray
{
public:
glm::vec4 start;
glm::vec4 dir;
};
#endif // RAY_H
| [
"scgooda@gmail.com"
] | scgooda@gmail.com |
a738a0dc15cd360d71a08ab4bfd13a6ac008f6ea | 05c046d94416a2b86b469888f4353080e6e5fadb | /vector.hpp | c70c2f912c0d650dd5ee623c25e9c61d1ffe982a | [] | no_license | ivan371/Jana | 4847fcc0bb26e147a45671b4af80a31b57003308 | 5aae9957d5d41bbd51dda97afcf5c6f3f0ffaa0a | refs/heads/master | 2021-09-15T00:57:07.349018 | 2018-05-23T08:39:09 | 2018-05-23T08:39:09 | 103,926,020 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 707 | hpp | #include <stdlib.h>
const int SIZE = 1000;
class Vector {
private:
int* arr;
int size;
int v_size;
public:
Vector() {
arr = new int(SIZE);
v_size = SIZE;
size = 0;
}
~Vector() {
size = -1;
v_size = -1;
delete(arr);
}
int get(int index) {
if(index < size) {
exit(-1);
}
else {
return arr[index];
}
}
void put(int value) {
if(size > v_size) {
arr = (int*)realloc(arr, v_size + SIZE);
v_size += SIZE;
}
arr[size++] = value;
}
int modify(int index, int value) {
if(index < size) {
exit(-1);
}
else {
arr[index] = value;
}
}
int getSize() {
return size;
}
}; | [
"ivan@DESKTOP-GM6Q430.localdomain"
] | ivan@DESKTOP-GM6Q430.localdomain |
d4ebe983a1edd098ecf808d7fc5076113b549b19 | e95adb59feacfe95904c3a8e90a4159860b6c26a | /build/Android/Preview/outsideTheBox/app/src/main/include/Fuse.Animations.SplineTrack.h | 67fc48d90b26e937e691f1eb696b26d5e7f194bb | [] | no_license | deliloka/bethebox | 837dff20c1ff55db631db1e0f6cb51d935497e91 | f9bc71b8593dd54b8aaf86bc0a654d233432c362 | refs/heads/master | 2021-01-21T08:20:42.970891 | 2016-02-19T10:00:37 | 2016-02-19T10:00:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,967 | h | // This file was generated based on '/usr/local/share/uno/Packages/Fuse.Animations/0.23.2/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Animations.ContinuousTrackProvider.h>
#include <Fuse.Animations.ITrackProvider.h>
#include <Fuse.Animations.KeyframeTrack.h>
#include <Fuse.Animations.TrackProvider.h>
#include <Uno.Object.h>
namespace g{namespace Fuse{namespace Animations{struct Keyframe;}}}
namespace g{namespace Fuse{namespace Animations{struct SplineTrack;}}}
namespace g{namespace Fuse{namespace Animations{struct TrackAnimator;}}}
namespace g{namespace Fuse{namespace Animations{struct TrackAnimatorState;}}}
namespace g{namespace Uno{namespace Collections{struct List;}}}
namespace g{namespace Uno{struct Float4;}}
namespace g{
namespace Fuse{
namespace Animations{
// internal sealed class SplineTrack :2637
// {
struct SplineTrack_type : uType
{
::g::Fuse::Animations::ContinuousTrackProvider interface0;
::g::Fuse::Animations::ITrackProvider interface1;
::g::Fuse::Animations::KeyframeTrack interface2;
::g::Fuse::Animations::TrackProvider interface3;
};
SplineTrack_type* SplineTrack_typeof();
void SplineTrack__ctor__fn(SplineTrack* __this);
void SplineTrack__get_Bias_fn(SplineTrack* __this, float* __retval);
void SplineTrack__set_Bias_fn(SplineTrack* __this, float* value);
void SplineTrack__get_Continuity_fn(SplineTrack* __this, float* __retval);
void SplineTrack__set_Continuity_fn(SplineTrack* __this, float* value);
void SplineTrack__CubicHermitePoint_fn(::g::Uno::Float4* p0, ::g::Uno::Float4* p1, ::g::Uno::Float4* m0, ::g::Uno::Float4* m1, float* t, ::g::Uno::Float4* __retval);
void SplineTrack__FuseAnimationsContinuousTrackProviderGetSeekProgress_fn(SplineTrack* __this, ::g::Fuse::Animations::TrackAnimatorState* tas, double* progress, double* interval, int* dir, ::g::Uno::Float4* value, double* strength, bool* __retval);
void SplineTrack__FuseAnimationsContinuousTrackProviderGetSeekTime_fn(SplineTrack* __this, ::g::Fuse::Animations::TrackAnimatorState* tas, double* elapsed, double* interval, int* dir, ::g::Uno::Float4* value, double* strength, bool* __retval);
void SplineTrack__FuseAnimationsTrackProviderGetAnimatorVariant_fn(SplineTrack* __this, ::g::Fuse::Animations::TrackAnimator* tas, int* __retval);
void SplineTrack__FuseAnimationsTrackProviderGetDuration_fn(SplineTrack* __this, ::g::Fuse::Animations::TrackAnimator* ta, int* variant, double* __retval);
void SplineTrack__Init_fn(SplineTrack* __this);
void SplineTrack__get_Interpolation_fn(SplineTrack* __this, int* __retval);
void SplineTrack__set_Interpolation_fn(SplineTrack* __this, int* value);
void SplineTrack__get_Keyframes_fn(SplineTrack* __this, uObject** __retval);
void SplineTrack__LinearPoint_fn(::g::Uno::Float4* p0, ::g::Uno::Float4* p1, ::g::Uno::Float4* m0, ::g::Uno::Float4* m1, float* t, ::g::Uno::Float4* __retval);
void SplineTrack__New1_fn(SplineTrack** __retval);
void SplineTrack__get_Tension_fn(SplineTrack* __this, float* __retval);
void SplineTrack__set_Tension_fn(SplineTrack* __this, float* value);
struct SplineTrack : uObject
{
float _bias;
float _continuity;
double _duration;
uStrong< ::g::Uno::Collections::List*> _frames;
bool _init;
uStrong<uDelegate*> _pointInterpolater;
int _style;
float _tension;
void ctor_();
float Bias();
void Bias(float value);
float Continuity();
void Continuity(float value);
void Init();
int Interpolation();
void Interpolation(int value);
uObject* Keyframes();
float Tension();
void Tension(float value);
static ::g::Uno::Float4 CubicHermitePoint(::g::Uno::Float4 p0, ::g::Uno::Float4 p1, ::g::Uno::Float4 m0, ::g::Uno::Float4 m1, float t);
static ::g::Uno::Float4 LinearPoint(::g::Uno::Float4 p0, ::g::Uno::Float4 p1, ::g::Uno::Float4 m0, ::g::Uno::Float4 m1, float t);
static SplineTrack* New1();
};
// }
}}} // ::g::Fuse::Animations
| [
"Havard.Halse@nrk.no"
] | Havard.Halse@nrk.no |
c578afb187a91f2ebb1c822a82183fb24f845892 | 3a745bd756a010e03c900044afc9214510c5ff4d | /practices/cpp/level1/p01_Queue/Queue.cpp | 2c2b157480861a8e8034c35b918418e3d75534c7 | [] | no_license | chenxiaoyu233/CCpp2017 | 92d3c62d51ebceefe066803203ee1c29b0c2f39a | 88c07c019f40fbf14de72194f85b80f9470ad2aa | refs/heads/master | 2021-01-20T15:27:14.224857 | 2017-06-23T04:44:04 | 2017-06-23T04:44:04 | 82,816,594 | 1 | 0 | null | 2017-02-22T14:54:48 | 2017-02-22T14:54:48 | null | UTF-8 | C++ | false | false | 240 | cpp | #include "Queue.h"
void Queue::append(int x){
r++;size++;
r %= MAX_SIZE;
w[r] = x;
}
void Queue::pop(){
l++;size--;
l %= MAX_SIZE;
}
bool Queue::is_empty(){
return size == 0;
}
bool Queue::is_full(){
return size == (MAX_SIZE - 1);
}
| [
"x312035@gmail.com"
] | x312035@gmail.com |
43d2eae8ee1d440c4e360c6d948b3ae0bb739004 | f6209d36a511958860203bfae8bdc97e60be7bb5 | /approximationSDK/src/Hermite.cpp | 380c121dc895ebbbe503e3b8ad0490390855a730 | [] | no_license | tamasdzs/ApproximationTools | 7886168614ce1f8d4167de7c11a72c28d6172d94 | 47ad90234e19b7b63948a959032b0dcc81a71eb3 | refs/heads/master | 2021-09-06T21:34:03.009243 | 2018-02-11T20:51:00 | 2018-02-11T20:51:00 | 115,791,751 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,038 | cpp | #include "Hermite.h"
#include <math.h>
#include <iostream>
/* /////////////////////////////////////////////////////////////////////
* Hermite::ort_fun_sys_roots()
* Calculculate the roots of the n-th Hermite function.
* This will serve as the domain of the Hermite system used
* to approximate the ECG signal. The application of this domain
* enables us to use a Gauss-type quadrature formula.
*/ ////////////////////////////////////////////////////////////////////
void Hermite::ort_fun_sys_roots() {
/*
* 1. Create Jacobi matrix whose eigenvalues will be the roots of the nth Hermite
* function.
*/
Eigen::MatrixXd J;
J = Eigen::MatrixXd::Zero(rootNum, rootNum);
for(int i = 0; i < rootNum; ++i) {
if( i == 0 ) {
J(0, i+1) = sqrt(0.5*double(i+1));
}
else if( i > 0 && i < rootNum-1 ) {
J(i, i+1) = sqrt(0.5*(i+1));
J(i, i-1) = sqrt(0.5*(i));
}
else if( i == rootNum-1) {
J(i, rootNum-2) = sqrt(0.5*i);
}
}
/*
* 2. Calculate eigenvalues of the Jacobi matrix. Let domain's pointed value
* be equal to the matrix that stores these.
*/
Eigen::SelfAdjointEigenSolver<Eigen::MatrixXd> eigensolver(J);
//TODO: error-check if eigensolver was initalized
*domain = eigensolver.eigenvalues();
}
/* /////////////////////////////////////////////////////////////////////
* Hermite::ort_fun_sys_gen()
* This function is used to generate the orthonormal Hermite system
* using the three-term recurrence formula.
*/ ////////////////////////////////////////////////////////////////////
void Hermite::ort_fun_sys_gen() {
/*
* Initalize matrix whose columns will hold the values of the system.
* Use Eigen::Array for piecewise operations.
*/
Eigen::ArrayXXd PHI;
PHI = Eigen::ArrayXXd::Zero(rootNum, rootNum);
/*
* Initalize domain (in this case the roots of some Hermite function).
*/
Eigen::ArrayXXd x = (*domain).array();
/*
* Weight function.
*/
Eigen::ArrayXXd w = (-1*(x*x)/2.0).exp();
/*
* Zero and First order Hermite functions.
*/
PHI.col(0) = w;
PHI.col(1) = 2*(x*w)/sqrt(2);
/*
* Recursion for higher order Hermite functions.
*/
double ni, ni_1;
for(int i = 2; i < rootNum; ++i) {
ni = 1.0/sqrt(2.0*double(i));
ni_1 = 1.0/sqrt(2.0*(double(i) - 1)) * ni;
PHI.col(i) = 2.0*(x*PHI.col(i-1)*ni - (double(i)-1)*PHI.col(i-2)*ni_1);
}
/*
* Normalize the function system.
*/
PHI *= pow(4.0*atan(1.0), -1.0/4.0);
*bigSys = PHI.matrix();
}
const Eigen::MatrixXd Hermite::OrtSysGen(const Eigen::ArrayXd& x, int deg) {
Eigen::ArrayXXd PHI;
PHI = Eigen::ArrayXXd::Zero(x.rows(), deg);
Eigen::ArrayXXd w = (-1*(x*x)/2.0).exp();
PHI.col(0) = w;
PHI.col(1) = 2*(x*w)/sqrt(2);
double ni, ni_1;
for(int i = 2; i < deg; ++i) {
ni = 1.0/sqrt(2.0*double(i));
ni_1 = 1.0/sqrt(2.0*(double(i) - 1)) * ni;
PHI.col(i) = 2.0*(x*PHI.col(i-1)*ni - (double(i)-1)*PHI.col(i-2)*ni_1);
}
PHI *= pow(4.0*atan(1.0), -1.0/4.0);
return PHI.matrix();
}
void Hermite::ort_fun_sys_lamb() {
*lambda = (*bigSys)*(*bigSys).transpose();
}
| [
"tamasdzs@gmail.com"
] | tamasdzs@gmail.com |
db8df74ace17476d74745ee6496daebd10194ac8 | b09e962b2a9816eb12ed1d375994a77f29493b7f | /src/Engine/Gfx/Model.h | 8d4cbd6ae718a8e2e89010fdf0d13bce4be559c2 | [] | no_license | HyperionGroup/HeliosEngine | 3eea114c74049ffafc2e525eff97ecd8536924aa | f98933cc26e47ed21b29da8d65371fc6fd64d765 | refs/heads/master | 2021-01-23T04:39:36.218877 | 2017-08-08T13:45:13 | 2017-08-08T13:45:13 | 92,934,958 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 346 | h | #pragma once
#include "Core\Name.h"
namespace gfx
{
class CGeometry;
class CModel : public core::CName
{
public:
CModel() = default;
virtual ~CModel() = default;
void Load(const core::CStr& _filename);
protected:
std::string mFilename;
std::vector< CGeometry* > mGeometries;
};
} | [
"vazquinhos@gmail.com"
] | vazquinhos@gmail.com |
8776d53ad020543ddb81b3d0f4f7fd8be3c92c6f | c157ae97762cdef9805d7fdbb6be36f998ed02ba | /src/recipe.cpp | d9b14e4dfa219fcd127bd4ebbbf4a667ebabdd76 | [] | no_license | Chirurgus/cookbox_server_cpp | 50a9868a38888c7c50681043172c562770d31053 | b45414ed22854e371c437b7dc58249e0dd8c4fad | refs/heads/master | 2021-04-12T09:03:18.876128 | 2018-06-07T19:06:52 | 2018-06-07T19:06:52 | 126,232,210 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,914 | cpp | #include <memory>
#include <recipe.h>
namespace recipe {
// (re)definition needed to avoid link errors
constexpr Recipe::id_type Recipe::no_id;
}// namespace recipe
// helper functions
namespace {
std::string to_string(const utility::string_t& str) {
return std::string(str.begin(), str.end());
}
}
// from std::string to utility::string_t
using utility::conversions::to_string_t;
recipe::Recipe::Recipe(const json& j)
{
id = j.at(U("id")).as_integer();
name = to_string(j.at(U("name")).as_string());
short_description = to_string(j.at(U("short_description")).as_string());
long_description = to_string(j.at(U("long_description")).as_string());
target_quantity = j.at(U("target_quantity")).as_double();
target_description = to_string(j.at(U("target_description")).as_string());
preparation_time = j.at(U("preparation_time")).as_double();
source = to_string(j.at(U("source")).as_string());
for (const auto& i : j.at(U("ingredient_list")).as_array()) {
Ingredient ing {i.at(U("quantity")).as_double(),
to_string(i.at(U("description")).as_string()),
nullptr};
if (i.has_field(U("other_recipe"))) {
ing.other_recipe = std::make_shared<Recipe::id_type>(
i.at(U("other_recipe")).as_integer()
);
}
ingredient_list.push_back(ing);
}
for (const auto& i : j.at(U("instruction_lsit")).as_array()) {
instruction_list.push_back(to_string(i.as_string()));
}
for (const auto& c : j.at(U("comment_list")).as_array()) {
comment_list.push_back(to_string(c.as_string()));
}
}
// This assumes that recipes contain only 1 byte chars
recipe::Recipe::json recipe::Recipe::toJson() const
{
json j;
j[U("id")] = json::number(id);
j[U("name")] = json::string(to_string_t(name));
j[U("short_description")] = json::string(to_string_t(short_description));
j[U("long_description")] = json::string(to_string_t(long_description));
j[U("target_quantity")] = json::number(target_quantity);
j[U("target_description")] = json::string(to_string_t(target_description));
j[U("preparation_time")] = json::number(preparation_time);
j[U("source")] = json::string(to_string_t(source));
j[U("ingredient_list")] = json::array();
for (std::vector<Ingredient>::size_type i{0}; i < ingredient_list.size(); ++i) {
json j_ing;
j_ing[U("quantity")] = json::number(ingredient_list[i].quantity);
j_ing[U("description")] = json::string(to_string_t(ingredient_list[i].description));
if (ingredient_list[i].other_recipe) {
j_ing[U("other_recipe")] = json::number(*ingredient_list[i].other_recipe);
}
j[U("ingredient_list")][i] = j_ing;
}
for (std::vector<std::string>::size_type i{ 0 }; i < instruction_list.size(); ++i) {
j[U("instruction_list")][i] = json::string(to_string_t(instruction_list[i]));
}
for (std::vector<std::string>::size_type i{ 0 }; i < comment_list.size(); ++i) {
j[U("comment_list")][i] = json::string(to_string_t(comment_list[i]));
}
return j;
}
| [
"sasha.sashaxl@gmail.com"
] | sasha.sashaxl@gmail.com |
00690d62e42d2f6e5127bc8090320ba416db0113 | 235bccb2fc4f06898ac53402706371bef544f377 | /Codeforce/B. Fox And Two Dots.cpp | 3b80d36025ffd1c50991f82fca27844c3dc200f1 | [] | no_license | GaziNazim/CPP | 76fa44bff7e11d87ffcf95426b0306ea9f9dca93 | 78b0d68642efe33fef5ce6bb50153bd38a11b4bc | refs/heads/master | 2016-08-08T00:50:50.996535 | 2015-05-10T15:33:13 | 2015-05-10T15:33:13 | 30,353,615 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,229 | cpp | #include<bits/stdc++.h>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<cstdio>
using namespace std;
#define rep(i,n) for(__typeof(n) i=0;i<(n);i++)
#define REP(i,a,b) for(__typeof(b) i=(a);i<=(b);i++)
#define INF (1<<31)
#define pb push_back
#define Sort(v) sort(v.begin(),v.end())
#define sz size()
#define mem(x,y) memset(x,y,sizeof(x))
#define sc scanf
#define pf printf
#define mp make_pair
#define ff first
#define ss second
#define ri(N) scanf("%d",&N)
#define rs(S) scanf("%s",&S)
#define ll long long
#define vi vector<int>
#define pii pair<int,int>
#define piii pair<int,pair<int,int> >
#define vii vector<ii>
#define si set<int>
#define msi map<string,int>
#define fin freopen("input.txt","r",stdin)
#define fout freopen("out.txt","w",stdout)
#define pi acos(-1)
#define MAX 55
///////////////////////********************////////////////////////
/*Code start from here*/
vi node[MAX];
int color[MAX];
string s[MAX];
int main()
{
set<char>s_set;
s_set.insert('f');
set<char>::iterator it;
it=s_set.find('h');
cout<<*it;
// if(it)
cout<<"yes";
mem(color,0);
int n,m;
cin>>n>>m;
rep(i,n)
cin>>s[i];
rep(i,n)
rep(i,m)
{
}
return 0;
}
| [
"gazinazim1@gmail.com"
] | gazinazim1@gmail.com |
71116433150d491ac263d5b51cf14122bc7cc231 | b59cceebacb423b54f38775bd88a99f5a15d013b | /atcoder/abc/abc079/a.cpp | 195944321c268992cc8c18e0d4a4ea2433537240 | [
"MIT"
] | permissive | yu3mars/proconVSCodeGcc | 5e434133d4e9edf80d02a8ca4b95ee77833fbee7 | fcf36165bb14fb6f555664355e05dd08d12e426b | refs/heads/master | 2021-06-06T08:32:06.122671 | 2020-09-13T05:49:32 | 2020-09-13T05:49:32 | 151,394,627 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 325 | cpp | #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
int main()
{
string s;
cin >> s;
if(s.at(1) == s.at(2) &&
(s.at(0) == s.at(1) || s.at(2)==s.at(3)))
{
cout << "Yes"<< endl;
}
else
{
cout << "No" << endl;
}
return 0;
} | [
"yu3mars@users.noreply.github.com"
] | yu3mars@users.noreply.github.com |
36869df061d5ef4709311987d79c52f2867ce109 | c10be2d679e96ce416acdaaafd7647730d8f4dba | /chapter4/7/main.cpp | 0c1ff755428badd4fd5b2c3410ff8e65260b7e0e | [] | no_license | DMyhai/Tasks | 7111bddfffd359cc47f3bd97b201dd0ae10e210f | 90f20b958528003c5c455f87d3ba281bc391c353 | refs/heads/master | 2016-08-07T23:29:26.836811 | 2014-02-25T13:35:22 | 2014-02-25T13:35:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 718 | cpp | #include <iostream>
#include <string>
using namespace std;
struct info {
char nameCompany[15];
int diameter;
int weight;
} ;
int main()
{
info array[10];
for (int i=0; i<3; i++){
cout<<"Enter name of the company: ";
cin.get();
cin.getline(array[i].nameCompany, 15);
cout<<"Enter diameter of pizza: ";
cin>>array[i].diameter;
cout<<"Enter weight of pizza: ";
cin>>array[i].weight;
// cout<<"i= " <<i<<endl;
}
for (int i=0; i<3; i++){
cout<<"Company name: "<<array[i].nameCompany<<endl;
cout<<"Diametr: "<<array[i].diameter<<endl;
cout<<"Weight: "<<array[i].weight<<endl;
}
return 0;
}
| [
"dmytro.mykhailishen@globallogic.com"
] | dmytro.mykhailishen@globallogic.com |
cccb55368fb6bde4c61a78e96ae2b8b760aa4ee4 | 588142a878994e36c7f91070c86e8e41e8a29824 | /src/uarp.cc | 74d1ab0954ff9584e6882ed5cbd45ec0c8cdf7f6 | [] | no_license | dsosnov/uaplotter1 | 189a4f4505b9d51053454d21c3072d9e856d80ba | e86651ea30f2aafab317e4e7124dda81ad8ad528 | refs/heads/master | 2021-01-23T12:25:19.866524 | 2018-08-04T11:32:19 | 2018-08-04T22:31:23 | 93,156,295 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,323 | cc | #include "uarp.h"
#include <time.h>
#include <string>
#include "iostream"
#include "TString.h"
#include "Rtypes.h"
#include "TMath.h"
#include "TH2.h"
#include "TBranch.h"
ClassImp(uarp)
float uarp::FriciVar()
{
float var = 0;
if(track_valid[0] && track_valid[1]){
var = -0.1;
}else if (track_valid[0]){
var = y[0][0]/y[1][0];
}else if (track_valid[1]){
var = y[0][1]/y[1][1];
};
return var;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
uarp::uarp(TChain * tree, //!<tree of ua format
TDirectory * dir, //!<directory in the output root file
const bool cmstotem, //!<true for merged, false for CMS only
const bool CASTORp, //!<true proton to -Z (pPb)
const short int MC, //!< -1, 0 - data; >0 MC
const short unsigned int Ncuts //!< number of cuts
):uabase(cmstotem, MC, Ncuts, dir)
{
RPproton = 0;
RPtrackNU = 0;
RPtrackND = 0;
RPtrackFU = 0;
RPtrackFD = 0;
if(tree_combined_flag){
if(CASTORp){
tree->SetBranchAddress("rec_prot_right.", &RPproton); // here (TOTEM confirmed)
//tree->SetBranchAddress("rec_prot_left.", &RPproton); // wrong
tree->SetBranchAddress("track_rp_120.", &RPtrackNU);
tree->SetBranchAddress("track_rp_121.", &RPtrackND);
tree->SetBranchAddress("track_rp_124.", &RPtrackFU);
tree->SetBranchAddress("track_rp_125.", &RPtrackFD);
}else{
tree->SetBranchAddress("rec_prot_left.", &RPproton); // here
//tree->SetBranchAddress("rec_prot_right.", &RPproton); // wrong (TOTEM confirmed)
tree->SetBranchAddress("track_rp_20.", &RPtrackNU);
tree->SetBranchAddress("track_rp_21.", &RPtrackND);
tree->SetBranchAddress("track_rp_24.", &RPtrackFU);
tree->SetBranchAddress("track_rp_25.", &RPtrackFD);
};
};
create_histos();
};
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
uarp::~uarp(){
std::cout << "uarp::~uarp(): deleting "
<< h1D->size() << "+" << h2D->size() << " histos" << std::endl;
};
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
bool uarp::ProceedEvent(short unsigned int cut, const bool fill, const bool info){
if(fill && (cut>n_cuts) ){
std::cout << "uarp::ProceedEvent: required cut number is larger that possible, please define larger uaforward::n_cut!\n";
return false;
};
proton_valid = false;
proton_t = 0;
proton_xi = 1;
proton_y = 0;
memset(y, 0, sizeof(y));
memset(track_valid, false, sizeof(track_valid));
if(mc>0 || !tree_combined_flag)
return false;
proton_valid = RPproton->valid;
proton_xi = RPproton->xi;
proton_t = RPproton->t;
proton_y = RPproton->y0;
//double y[2][2]; // [F,N][U,D]
if(RPtrackFU->valid){
y[0][0] = RPtrackFU->y;
};
if(RPtrackFD->valid){
y[0][1] = RPtrackFD->y;
};
if(RPtrackNU->valid){
y[1][0] = RPtrackNU->y;
};
if(RPtrackND->valid){
y[1][1] = RPtrackND->y;
};
for (short unsigned int ud = 0; ud<2; ud++){
if( (y[0][ud]!=0) && (y[1][ud]!=0) ){
track_valid[ud] = true;
};
};
if(info)
PrintEventInfo(true);
if(fill)
FillLastEvent(cut);
return true;
};
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void uarp::PrintEventInfo(bool detailed){
std::cout << "uarp::PrintEventInfo:\n";
if(detailed){
std::cout << "\tvalid: " << proton_valid << "\tXi : " << proton_xi << ";\tt :"<< proton_t << ";\ty :"<< proton_y << std::endl;
std::cout << "\ttrack FU y:" << y[0][0] << "\ttrack FD y:" << y[0][1] << std::endl;
std::cout << "\ttrack NU y:" << y[1][0] << "\ttrack ND y:" << y[1][1] << std::endl;
std::cout << "\t yF/yN:" << FriciVar() << std::endl;
}else{
if(!proton_valid){
std::cout << "no protons found\n";
}else{
std::cout << "\tXi : " << proton_xi << ";\tt :"<< proton_t << std::endl;
};
};
};
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
bool uarp::FillLastEvent(const short unsigned int cut)
{
if( cut>=n_cuts ){
std::cout << "uarp::FillLastEvent: required cut number is larger that possible, do nothing. Please define larger uaforward::n_cut!\n";
return false;
};
if(mc<=0){
if(proton_valid){
//double log_xi = TMath::Log10(proton_xi);
//double log_t = TMath::Log10(-proton_t);
xi_valid_h[cut]->Fill(proton_xi);
t_valid_h[cut]->Fill(proton_t);
xi_vs_t_valid_h[cut]->Fill(TMath::Log10(-proton_t), proton_xi);
};
if(track_valid[0]) {
friciU_h[cut]->Fill(y[1][0], y[0][0]/y[1][0]);
yp_vs_yN[cut]->Fill(y[1][0], proton_y);
};
if(track_valid[1]) {
friciD_h[cut]->Fill(y[1][1], y[0][1]/y[1][1]);
yp_vs_yN[cut]->Fill(y[1][1], proton_y);
};
};
return true;
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void uarp::FillRPWithMCtruth(const short unsigned int cut, const double xi, const double t){
if( cut>=n_cuts ){
std::cout << "uarp::FillRPWithMCtruth: required cut number is larger that possible, do nothing. Please define larger uaforward::n_cut!\n";
return;
};
//double log_xi = TMath::Log10(xi);
//double log_t = TMath::Log10(-t);
xi_valid_h[cut]->Fill(xi);
t_valid_h[cut]->Fill(t);
xi_vs_t_valid_h[cut]->Fill(TMath::Log10(-t), xi);
};
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
void uarp::create_histos(){
TString title1, title2;
n_each_h1D = n_cuts;
n_each_h2D = n_cuts;
xi_valid_h = new TH1F * [n_each_h1D];
t_valid_h = new TH1F * [n_each_h1D];
xi_vs_t_valid_h = new TH2F * [n_each_h2D];
friciU_h = new TH2F * [n_each_h2D];
friciD_h = new TH2F * [n_each_h2D];
yp_vs_yN = new TH2F * [n_each_h2D];
for(short unsigned int i=0; i<n_each_h1D; i++){
title1 = "xi_valid_h["; title1+=i; title1+="]";
title2 = title1; title2+="; log_{10}(#xi)";
xi_valid_h[i] = new TH1F(title1.Data(), title2.Data(), 400, -2, 2);
xi_valid_h[i]->SetDirectory(directory);
title1 = "t_valid_h["; title1+=i; title1+="]";
title2 = title1; title2+="; t [(GeV/c)^{2}]";
t_valid_h[i] = new TH1F(title1.Data(), title2.Data(), 10001, -10000, 1);
t_valid_h[i]->SetDirectory(directory);
};
h1D->push_back(xi_valid_h);
h1D->push_back(t_valid_h);
for(short unsigned int i=0; i<n_each_h2D; i++){
title1 = "xi_vs_t_valid_h["; title1+=i; title1+="]";
title2 = title1; title2+=";log_{10}(-t [(GeV/c)^{2}]); #xi";//log_{10}(#xi)";
xi_vs_t_valid_h[i] = new TH2F(title1.Data(), title2.Data(), 700, -3, 4, 400, -2, 2);
xi_vs_t_valid_h[i]->SetDirectory(directory);
title1 = "friciU_h["; title1+=i; title1+="]";
title2 = title1; title2+=";y_N [mm]; y_F/y_N";
friciU_h[i] = new TH2F(title1.Data(), title2.Data(), 250, 5, 30, 400, 0.75, 1.15);
friciU_h[i]->SetDirectory(directory);
title1 = "friciD_h["; title1+=i; title1+="]";
title2 = title1; title2+=";y_N [mm]; y_F/y_N";
friciD_h[i] = new TH2F(title1.Data(), title2.Data(), 250, -30, -5, 400, 0.75, 1.15);
friciD_h[i]->SetDirectory(directory);
title1 = "yp_vs_yN["; title1+=i; title1+="]";
title2 = title1; title2+=";y_N [mm]; y0(p) [mm]";
yp_vs_yN[i] = new TH2F(title1.Data(), title2.Data(), 600, -30, 30, 600, -30, 30);
yp_vs_yN[i]->SetDirectory(directory);
};
h2D->push_back(xi_vs_t_valid_h);
h2D->push_back(friciU_h);
h2D->push_back(friciD_h);
h2D->push_back(yp_vs_yN);
};
| [
"dmitry.sosnov@cern.ch"
] | dmitry.sosnov@cern.ch |
4831e4bc05ef6d74a47ee5c10ece0b52de52bc1f | 6e77b2d7d45a22e4e12d3624f6e4186da600fbb8 | /src/Engine/Demo/GUtils.h | e98eacfc99c1e7291ddf53373286d2e68a893ab3 | [] | no_license | dgadens/ActionEngine | c414eb216e1a4d99251a079dab4e20164005f521 | 410e04411b55d436c0df2f548444bb5b2bb2052d | refs/heads/master | 2021-01-23T22:42:52.296434 | 2012-11-26T00:35:39 | 2012-11-26T00:35:39 | 5,075,926 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 602 | h | #ifndef __GUTILS_H
#define __GUTILS_H
#include <windows.h>
#include <conio.h>
#include <iostream>
//esse static faz a variavel ser vista apenas dentro desse arquivo :)
static bool consoleVisible = false;
class GUtils
{
public:
static void ShowConsole()
{
if (!consoleVisible)
{
AllocConsole();
freopen("conin$","r",stdin);
freopen("conout$","w",stdout);
freopen("conout$","w",stderr);
printf("Debugging Window:\n");
consoleVisible = true;
}
};
static void HideConsole()
{
consoleVisible = false;
FreeConsole();
};
};
#endif | [
"degadens@gmail.com"
] | degadens@gmail.com |
379992f54b820e87daae949245ec5fbffbc811fc | 8dff49c4dc92983cbd0934725f97224fd9754d1d | /ZeroJudge/c121.cpp | 1ed374762705885036ba05258442b768e073ce38 | [] | no_license | cherry900606/OJ_Solutions | 1c7360ca35252aec459ef01d8e6a485778d32653 | b70f8baed30f446421fd39f311f1d5071a441734 | refs/heads/main | 2023-05-14T13:38:44.475393 | 2021-06-19T07:29:35 | 2021-06-19T07:29:35 | 378,026,385 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 807 | cpp | #include <iostream>
#include <string>
using namespace std;
string fib[5001];
string add(string a,string b) // short+long
{
if(a.size()>b.size()) swap(a,b);
for(int i=0;i<a.size();i++)
b[b.size()-i-1]+=a[a.size()-1-i]-'0';
for(int i=b.size()-1;i>=1;i--)
{
if(b[i]>'9')
{
b[i]=(b[i]-'0')%10+'0';
b[i-1]++;
}
}
if(b[0]>'9')
{
b[0]=(b[0]-'0')%10+'0';
b="1"+b;
}
return b;
}
int main()
{
fib[0]="0",fib[1]="1";
for(int i=2;i<=5000;i++)
{
fib[i]=add(fib[i-1],fib[i-2]);
}
int n;
while(cin>>n)
{
cout<<"The Fibonacci number for "<<n<<" is "<<fib[n]<<endl;
}
return 0;
}
| [
"cherry900606@gmail.com"
] | cherry900606@gmail.com |
9332ec2980019b0dd41b354d7001a57906708f35 | 6859f5319c0ec8cfd0547b60dee8abaf93e4923c | /Plugins/VRExpansionPlugin/VRExpansionPlugin/Intermediate/Build/Win32/UE4/Inc/VRExpansionPlugin/GrippableBoxComponent.generated.h | 49120261bcd304f2bd7d1c912b0e6fade73dbfe6 | [
"MIT"
] | permissive | GoVRCenter/QuestVRE | b90d98cb4d6b9de9e0fdbf74caa8521d8bee0070 | e32a68f86546e20852187ba7626e2899c2180f6d | refs/heads/master | 2022-02-21T09:28:48.249435 | 2019-09-17T00:29:39 | 2019-09-17T00:29:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 34,543 | h | // Copyright 1998-2019 Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/ObjectMacros.h"
#include "UObject/ScriptMacros.h"
PRAGMA_DISABLE_DEPRECATION_WARNINGS
struct FKey;
class USceneComponent;
struct FBPActorGripInformation;
class UGripMotionControllerComponent;
class UVRGripScriptBase;
struct FTransform_NetQuantize;
struct FBPGripPair;
struct FVector;
struct FTransform;
struct FBPAdvGripSettings;
enum class EGripLateUpdateSettings : uint8;
enum class EGripMovementReplicationSettings : uint8;
enum class ESecondaryGripType : uint8;
enum class EGripCollisionType : uint8;
enum class EGripInterfaceTeleportBehavior : uint8;
#ifdef VREXPANSIONPLUGIN_GrippableBoxComponent_generated_h
#error "GrippableBoxComponent.generated.h already included, missing '#pragma once' in GrippableBoxComponent.h"
#endif
#define VREXPANSIONPLUGIN_GrippableBoxComponent_generated_h
#define vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_RPC_WRAPPERS \
virtual void OnInput_Implementation(FKey Key, EInputEvent KeyEvent); \
virtual void OnEndSecondaryUsed_Implementation(); \
virtual void OnSecondaryUsed_Implementation(); \
virtual void OnEndUsed_Implementation(); \
virtual void OnUsed_Implementation(); \
virtual void OnSecondaryGripRelease_Implementation(USceneComponent* ReleasingSecondaryGripComponent, FBPActorGripInformation const& GripInformation); \
virtual void OnSecondaryGrip_Implementation(USceneComponent* SecondaryGripComponent, FBPActorGripInformation const& GripInformation); \
virtual void OnChildGripRelease_Implementation(UGripMotionControllerComponent* ReleasingController, FBPActorGripInformation const& GripInformation, bool bWasSocketed); \
virtual void OnChildGrip_Implementation(UGripMotionControllerComponent* GrippingController, FBPActorGripInformation const& GripInformation); \
virtual void OnGripRelease_Implementation(UGripMotionControllerComponent* ReleasingController, FBPActorGripInformation const& GripInformation, bool bWasSocketed); \
virtual void OnGrip_Implementation(UGripMotionControllerComponent* GrippingController, FBPActorGripInformation const& GripInformation); \
virtual void TickGrip_Implementation(UGripMotionControllerComponent* GrippingController, FBPActorGripInformation const& GripInformation, float DeltaTime); \
virtual bool GetGripScripts_Implementation(TArray<UVRGripScriptBase*>& ArrayReference); \
virtual bool RequestsSocketing_Implementation(USceneComponent*& ParentToSocketTo, FName& OptionalSocketName, FTransform_NetQuantize& RelativeTransform); \
virtual void SetHeld_Implementation(UGripMotionControllerComponent* HoldingController, uint8 GripID, bool bIsHeld); \
virtual void IsHeld_Implementation(TArray<FBPGripPair>& HoldingControllers, bool& bIsHeld); \
virtual bool AllowsMultipleGrips_Implementation(); \
virtual void ClosestGripSlotInRange_Implementation(FVector WorldLocation, bool bSecondarySlot, bool& bHadSlotInRange, FTransform& SlotWorldTransform, UGripMotionControllerComponent* CallingController, FName OverridePrefix); \
virtual float GripBreakDistance_Implementation(); \
virtual FBPAdvGripSettings AdvancedGripSettings_Implementation(); \
virtual void GetGripStiffnessAndDamping_Implementation(float& GripStiffnessOut, float& GripDampingOut); \
virtual EGripLateUpdateSettings GripLateUpdateSetting_Implementation(); \
virtual EGripMovementReplicationSettings GripMovementReplicationType_Implementation(); \
virtual ESecondaryGripType SecondaryGripType_Implementation(); \
virtual EGripCollisionType GetPrimaryGripType_Implementation(bool bIsSlot); \
virtual bool SimulateOnDrop_Implementation(); \
virtual EGripInterfaceTeleportBehavior TeleportBehavior_Implementation(); \
virtual bool DenyGripping_Implementation(); \
\
DECLARE_FUNCTION(execOnInput) \
{ \
P_GET_STRUCT(FKey,Z_Param_Key); \
P_GET_PROPERTY(UByteProperty,Z_Param_KeyEvent); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnInput_Implementation(Z_Param_Key,EInputEvent(Z_Param_KeyEvent)); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnEndSecondaryUsed) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnEndSecondaryUsed_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnSecondaryUsed) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnSecondaryUsed_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnEndUsed) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnEndUsed_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnUsed) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnUsed_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnSecondaryGripRelease) \
{ \
P_GET_OBJECT(USceneComponent,Z_Param_ReleasingSecondaryGripComponent); \
P_GET_STRUCT_REF(FBPActorGripInformation,Z_Param_Out_GripInformation); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnSecondaryGripRelease_Implementation(Z_Param_ReleasingSecondaryGripComponent,Z_Param_Out_GripInformation); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnSecondaryGrip) \
{ \
P_GET_OBJECT(USceneComponent,Z_Param_SecondaryGripComponent); \
P_GET_STRUCT_REF(FBPActorGripInformation,Z_Param_Out_GripInformation); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnSecondaryGrip_Implementation(Z_Param_SecondaryGripComponent,Z_Param_Out_GripInformation); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnChildGripRelease) \
{ \
P_GET_OBJECT(UGripMotionControllerComponent,Z_Param_ReleasingController); \
P_GET_STRUCT_REF(FBPActorGripInformation,Z_Param_Out_GripInformation); \
P_GET_UBOOL(Z_Param_bWasSocketed); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnChildGripRelease_Implementation(Z_Param_ReleasingController,Z_Param_Out_GripInformation,Z_Param_bWasSocketed); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnChildGrip) \
{ \
P_GET_OBJECT(UGripMotionControllerComponent,Z_Param_GrippingController); \
P_GET_STRUCT_REF(FBPActorGripInformation,Z_Param_Out_GripInformation); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnChildGrip_Implementation(Z_Param_GrippingController,Z_Param_Out_GripInformation); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnGripRelease) \
{ \
P_GET_OBJECT(UGripMotionControllerComponent,Z_Param_ReleasingController); \
P_GET_STRUCT_REF(FBPActorGripInformation,Z_Param_Out_GripInformation); \
P_GET_UBOOL(Z_Param_bWasSocketed); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnGripRelease_Implementation(Z_Param_ReleasingController,Z_Param_Out_GripInformation,Z_Param_bWasSocketed); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnGrip) \
{ \
P_GET_OBJECT(UGripMotionControllerComponent,Z_Param_GrippingController); \
P_GET_STRUCT_REF(FBPActorGripInformation,Z_Param_Out_GripInformation); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnGrip_Implementation(Z_Param_GrippingController,Z_Param_Out_GripInformation); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execTickGrip) \
{ \
P_GET_OBJECT(UGripMotionControllerComponent,Z_Param_GrippingController); \
P_GET_STRUCT_REF(FBPActorGripInformation,Z_Param_Out_GripInformation); \
P_GET_PROPERTY(UFloatProperty,Z_Param_DeltaTime); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->TickGrip_Implementation(Z_Param_GrippingController,Z_Param_Out_GripInformation,Z_Param_DeltaTime); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execGetGripScripts) \
{ \
P_GET_TARRAY_REF(UVRGripScriptBase*,Z_Param_Out_ArrayReference); \
P_FINISH; \
P_NATIVE_BEGIN; \
*(bool*)Z_Param__Result=P_THIS->GetGripScripts_Implementation(Z_Param_Out_ArrayReference); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execRequestsSocketing) \
{ \
P_GET_OBJECT_REF(USceneComponent,Z_Param_Out_ParentToSocketTo); \
P_GET_PROPERTY_REF(UNameProperty,Z_Param_Out_OptionalSocketName); \
P_GET_STRUCT_REF(FTransform_NetQuantize,Z_Param_Out_RelativeTransform); \
P_FINISH; \
P_NATIVE_BEGIN; \
*(bool*)Z_Param__Result=P_THIS->RequestsSocketing_Implementation(Z_Param_Out_ParentToSocketTo,Z_Param_Out_OptionalSocketName,Z_Param_Out_RelativeTransform); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execSetHeld) \
{ \
P_GET_OBJECT(UGripMotionControllerComponent,Z_Param_HoldingController); \
P_GET_PROPERTY(UByteProperty,Z_Param_GripID); \
P_GET_UBOOL(Z_Param_bIsHeld); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->SetHeld_Implementation(Z_Param_HoldingController,Z_Param_GripID,Z_Param_bIsHeld); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execIsHeld) \
{ \
P_GET_TARRAY_REF(FBPGripPair,Z_Param_Out_HoldingControllers); \
P_GET_UBOOL_REF(Z_Param_Out_bIsHeld); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->IsHeld_Implementation(Z_Param_Out_HoldingControllers,Z_Param_Out_bIsHeld); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execAllowsMultipleGrips) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(bool*)Z_Param__Result=P_THIS->AllowsMultipleGrips_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execClosestGripSlotInRange) \
{ \
P_GET_STRUCT(FVector,Z_Param_WorldLocation); \
P_GET_UBOOL(Z_Param_bSecondarySlot); \
P_GET_UBOOL_REF(Z_Param_Out_bHadSlotInRange); \
P_GET_STRUCT_REF(FTransform,Z_Param_Out_SlotWorldTransform); \
P_GET_OBJECT(UGripMotionControllerComponent,Z_Param_CallingController); \
P_GET_PROPERTY(UNameProperty,Z_Param_OverridePrefix); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->ClosestGripSlotInRange_Implementation(Z_Param_WorldLocation,Z_Param_bSecondarySlot,Z_Param_Out_bHadSlotInRange,Z_Param_Out_SlotWorldTransform,Z_Param_CallingController,Z_Param_OverridePrefix); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execGripBreakDistance) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(float*)Z_Param__Result=P_THIS->GripBreakDistance_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execAdvancedGripSettings) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(FBPAdvGripSettings*)Z_Param__Result=P_THIS->AdvancedGripSettings_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execGetGripStiffnessAndDamping) \
{ \
P_GET_PROPERTY_REF(UFloatProperty,Z_Param_Out_GripStiffnessOut); \
P_GET_PROPERTY_REF(UFloatProperty,Z_Param_Out_GripDampingOut); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->GetGripStiffnessAndDamping_Implementation(Z_Param_Out_GripStiffnessOut,Z_Param_Out_GripDampingOut); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execGripLateUpdateSetting) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(EGripLateUpdateSettings*)Z_Param__Result=P_THIS->GripLateUpdateSetting_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execGripMovementReplicationType) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(EGripMovementReplicationSettings*)Z_Param__Result=P_THIS->GripMovementReplicationType_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execSecondaryGripType) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(ESecondaryGripType*)Z_Param__Result=P_THIS->SecondaryGripType_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execGetPrimaryGripType) \
{ \
P_GET_UBOOL(Z_Param_bIsSlot); \
P_FINISH; \
P_NATIVE_BEGIN; \
*(EGripCollisionType*)Z_Param__Result=P_THIS->GetPrimaryGripType_Implementation(Z_Param_bIsSlot); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execSimulateOnDrop) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(bool*)Z_Param__Result=P_THIS->SimulateOnDrop_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execTeleportBehavior) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(EGripInterfaceTeleportBehavior*)Z_Param__Result=P_THIS->TeleportBehavior_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execDenyGripping) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(bool*)Z_Param__Result=P_THIS->DenyGripping_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execSetDenyGripping) \
{ \
P_GET_UBOOL(Z_Param_bDenyGripping); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->SetDenyGripping(Z_Param_bDenyGripping); \
P_NATIVE_END; \
}
#define vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_RPC_WRAPPERS_NO_PURE_DECLS \
virtual void OnInput_Implementation(FKey Key, EInputEvent KeyEvent); \
virtual void OnEndSecondaryUsed_Implementation(); \
virtual void OnSecondaryUsed_Implementation(); \
virtual void OnEndUsed_Implementation(); \
virtual void OnUsed_Implementation(); \
virtual void OnSecondaryGripRelease_Implementation(USceneComponent* ReleasingSecondaryGripComponent, FBPActorGripInformation const& GripInformation); \
virtual void OnSecondaryGrip_Implementation(USceneComponent* SecondaryGripComponent, FBPActorGripInformation const& GripInformation); \
virtual void OnChildGripRelease_Implementation(UGripMotionControllerComponent* ReleasingController, FBPActorGripInformation const& GripInformation, bool bWasSocketed); \
virtual void OnChildGrip_Implementation(UGripMotionControllerComponent* GrippingController, FBPActorGripInformation const& GripInformation); \
virtual void OnGripRelease_Implementation(UGripMotionControllerComponent* ReleasingController, FBPActorGripInformation const& GripInformation, bool bWasSocketed); \
virtual void OnGrip_Implementation(UGripMotionControllerComponent* GrippingController, FBPActorGripInformation const& GripInformation); \
virtual void TickGrip_Implementation(UGripMotionControllerComponent* GrippingController, FBPActorGripInformation const& GripInformation, float DeltaTime); \
virtual bool GetGripScripts_Implementation(TArray<UVRGripScriptBase*>& ArrayReference); \
virtual bool RequestsSocketing_Implementation(USceneComponent*& ParentToSocketTo, FName& OptionalSocketName, FTransform_NetQuantize& RelativeTransform); \
virtual void SetHeld_Implementation(UGripMotionControllerComponent* HoldingController, uint8 GripID, bool bIsHeld); \
virtual void IsHeld_Implementation(TArray<FBPGripPair>& HoldingControllers, bool& bIsHeld); \
virtual bool AllowsMultipleGrips_Implementation(); \
virtual void ClosestGripSlotInRange_Implementation(FVector WorldLocation, bool bSecondarySlot, bool& bHadSlotInRange, FTransform& SlotWorldTransform, UGripMotionControllerComponent* CallingController, FName OverridePrefix); \
virtual float GripBreakDistance_Implementation(); \
virtual FBPAdvGripSettings AdvancedGripSettings_Implementation(); \
virtual void GetGripStiffnessAndDamping_Implementation(float& GripStiffnessOut, float& GripDampingOut); \
virtual EGripLateUpdateSettings GripLateUpdateSetting_Implementation(); \
virtual EGripMovementReplicationSettings GripMovementReplicationType_Implementation(); \
virtual ESecondaryGripType SecondaryGripType_Implementation(); \
virtual EGripCollisionType GetPrimaryGripType_Implementation(bool bIsSlot); \
virtual bool SimulateOnDrop_Implementation(); \
virtual EGripInterfaceTeleportBehavior TeleportBehavior_Implementation(); \
virtual bool DenyGripping_Implementation(); \
\
DECLARE_FUNCTION(execOnInput) \
{ \
P_GET_STRUCT(FKey,Z_Param_Key); \
P_GET_PROPERTY(UByteProperty,Z_Param_KeyEvent); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnInput_Implementation(Z_Param_Key,EInputEvent(Z_Param_KeyEvent)); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnEndSecondaryUsed) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnEndSecondaryUsed_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnSecondaryUsed) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnSecondaryUsed_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnEndUsed) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnEndUsed_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnUsed) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnUsed_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnSecondaryGripRelease) \
{ \
P_GET_OBJECT(USceneComponent,Z_Param_ReleasingSecondaryGripComponent); \
P_GET_STRUCT_REF(FBPActorGripInformation,Z_Param_Out_GripInformation); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnSecondaryGripRelease_Implementation(Z_Param_ReleasingSecondaryGripComponent,Z_Param_Out_GripInformation); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnSecondaryGrip) \
{ \
P_GET_OBJECT(USceneComponent,Z_Param_SecondaryGripComponent); \
P_GET_STRUCT_REF(FBPActorGripInformation,Z_Param_Out_GripInformation); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnSecondaryGrip_Implementation(Z_Param_SecondaryGripComponent,Z_Param_Out_GripInformation); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnChildGripRelease) \
{ \
P_GET_OBJECT(UGripMotionControllerComponent,Z_Param_ReleasingController); \
P_GET_STRUCT_REF(FBPActorGripInformation,Z_Param_Out_GripInformation); \
P_GET_UBOOL(Z_Param_bWasSocketed); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnChildGripRelease_Implementation(Z_Param_ReleasingController,Z_Param_Out_GripInformation,Z_Param_bWasSocketed); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnChildGrip) \
{ \
P_GET_OBJECT(UGripMotionControllerComponent,Z_Param_GrippingController); \
P_GET_STRUCT_REF(FBPActorGripInformation,Z_Param_Out_GripInformation); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnChildGrip_Implementation(Z_Param_GrippingController,Z_Param_Out_GripInformation); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnGripRelease) \
{ \
P_GET_OBJECT(UGripMotionControllerComponent,Z_Param_ReleasingController); \
P_GET_STRUCT_REF(FBPActorGripInformation,Z_Param_Out_GripInformation); \
P_GET_UBOOL(Z_Param_bWasSocketed); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnGripRelease_Implementation(Z_Param_ReleasingController,Z_Param_Out_GripInformation,Z_Param_bWasSocketed); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execOnGrip) \
{ \
P_GET_OBJECT(UGripMotionControllerComponent,Z_Param_GrippingController); \
P_GET_STRUCT_REF(FBPActorGripInformation,Z_Param_Out_GripInformation); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->OnGrip_Implementation(Z_Param_GrippingController,Z_Param_Out_GripInformation); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execTickGrip) \
{ \
P_GET_OBJECT(UGripMotionControllerComponent,Z_Param_GrippingController); \
P_GET_STRUCT_REF(FBPActorGripInformation,Z_Param_Out_GripInformation); \
P_GET_PROPERTY(UFloatProperty,Z_Param_DeltaTime); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->TickGrip_Implementation(Z_Param_GrippingController,Z_Param_Out_GripInformation,Z_Param_DeltaTime); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execGetGripScripts) \
{ \
P_GET_TARRAY_REF(UVRGripScriptBase*,Z_Param_Out_ArrayReference); \
P_FINISH; \
P_NATIVE_BEGIN; \
*(bool*)Z_Param__Result=P_THIS->GetGripScripts_Implementation(Z_Param_Out_ArrayReference); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execRequestsSocketing) \
{ \
P_GET_OBJECT_REF(USceneComponent,Z_Param_Out_ParentToSocketTo); \
P_GET_PROPERTY_REF(UNameProperty,Z_Param_Out_OptionalSocketName); \
P_GET_STRUCT_REF(FTransform_NetQuantize,Z_Param_Out_RelativeTransform); \
P_FINISH; \
P_NATIVE_BEGIN; \
*(bool*)Z_Param__Result=P_THIS->RequestsSocketing_Implementation(Z_Param_Out_ParentToSocketTo,Z_Param_Out_OptionalSocketName,Z_Param_Out_RelativeTransform); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execSetHeld) \
{ \
P_GET_OBJECT(UGripMotionControllerComponent,Z_Param_HoldingController); \
P_GET_PROPERTY(UByteProperty,Z_Param_GripID); \
P_GET_UBOOL(Z_Param_bIsHeld); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->SetHeld_Implementation(Z_Param_HoldingController,Z_Param_GripID,Z_Param_bIsHeld); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execIsHeld) \
{ \
P_GET_TARRAY_REF(FBPGripPair,Z_Param_Out_HoldingControllers); \
P_GET_UBOOL_REF(Z_Param_Out_bIsHeld); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->IsHeld_Implementation(Z_Param_Out_HoldingControllers,Z_Param_Out_bIsHeld); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execAllowsMultipleGrips) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(bool*)Z_Param__Result=P_THIS->AllowsMultipleGrips_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execClosestGripSlotInRange) \
{ \
P_GET_STRUCT(FVector,Z_Param_WorldLocation); \
P_GET_UBOOL(Z_Param_bSecondarySlot); \
P_GET_UBOOL_REF(Z_Param_Out_bHadSlotInRange); \
P_GET_STRUCT_REF(FTransform,Z_Param_Out_SlotWorldTransform); \
P_GET_OBJECT(UGripMotionControllerComponent,Z_Param_CallingController); \
P_GET_PROPERTY(UNameProperty,Z_Param_OverridePrefix); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->ClosestGripSlotInRange_Implementation(Z_Param_WorldLocation,Z_Param_bSecondarySlot,Z_Param_Out_bHadSlotInRange,Z_Param_Out_SlotWorldTransform,Z_Param_CallingController,Z_Param_OverridePrefix); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execGripBreakDistance) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(float*)Z_Param__Result=P_THIS->GripBreakDistance_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execAdvancedGripSettings) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(FBPAdvGripSettings*)Z_Param__Result=P_THIS->AdvancedGripSettings_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execGetGripStiffnessAndDamping) \
{ \
P_GET_PROPERTY_REF(UFloatProperty,Z_Param_Out_GripStiffnessOut); \
P_GET_PROPERTY_REF(UFloatProperty,Z_Param_Out_GripDampingOut); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->GetGripStiffnessAndDamping_Implementation(Z_Param_Out_GripStiffnessOut,Z_Param_Out_GripDampingOut); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execGripLateUpdateSetting) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(EGripLateUpdateSettings*)Z_Param__Result=P_THIS->GripLateUpdateSetting_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execGripMovementReplicationType) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(EGripMovementReplicationSettings*)Z_Param__Result=P_THIS->GripMovementReplicationType_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execSecondaryGripType) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(ESecondaryGripType*)Z_Param__Result=P_THIS->SecondaryGripType_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execGetPrimaryGripType) \
{ \
P_GET_UBOOL(Z_Param_bIsSlot); \
P_FINISH; \
P_NATIVE_BEGIN; \
*(EGripCollisionType*)Z_Param__Result=P_THIS->GetPrimaryGripType_Implementation(Z_Param_bIsSlot); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execSimulateOnDrop) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(bool*)Z_Param__Result=P_THIS->SimulateOnDrop_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execTeleportBehavior) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(EGripInterfaceTeleportBehavior*)Z_Param__Result=P_THIS->TeleportBehavior_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execDenyGripping) \
{ \
P_FINISH; \
P_NATIVE_BEGIN; \
*(bool*)Z_Param__Result=P_THIS->DenyGripping_Implementation(); \
P_NATIVE_END; \
} \
\
DECLARE_FUNCTION(execSetDenyGripping) \
{ \
P_GET_UBOOL(Z_Param_bDenyGripping); \
P_FINISH; \
P_NATIVE_BEGIN; \
P_THIS->SetDenyGripping(Z_Param_bDenyGripping); \
P_NATIVE_END; \
}
#define vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_EVENT_PARMS \
struct GrippableBoxComponent_eventAdvancedGripSettings_Parms \
{ \
FBPAdvGripSettings ReturnValue; \
}; \
struct GrippableBoxComponent_eventAllowsMultipleGrips_Parms \
{ \
bool ReturnValue; \
\
/** Constructor, initializes return property only **/ \
GrippableBoxComponent_eventAllowsMultipleGrips_Parms() \
: ReturnValue(false) \
{ \
} \
}; \
struct GrippableBoxComponent_eventClosestGripSlotInRange_Parms \
{ \
FVector WorldLocation; \
bool bSecondarySlot; \
bool bHadSlotInRange; \
FTransform SlotWorldTransform; \
UGripMotionControllerComponent* CallingController; \
FName OverridePrefix; \
}; \
struct GrippableBoxComponent_eventDenyGripping_Parms \
{ \
bool ReturnValue; \
\
/** Constructor, initializes return property only **/ \
GrippableBoxComponent_eventDenyGripping_Parms() \
: ReturnValue(false) \
{ \
} \
}; \
struct GrippableBoxComponent_eventGetGripScripts_Parms \
{ \
TArray<UVRGripScriptBase*> ArrayReference; \
bool ReturnValue; \
\
/** Constructor, initializes return property only **/ \
GrippableBoxComponent_eventGetGripScripts_Parms() \
: ReturnValue(false) \
{ \
} \
}; \
struct GrippableBoxComponent_eventGetGripStiffnessAndDamping_Parms \
{ \
float GripStiffnessOut; \
float GripDampingOut; \
}; \
struct GrippableBoxComponent_eventGetPrimaryGripType_Parms \
{ \
bool bIsSlot; \
EGripCollisionType ReturnValue; \
\
/** Constructor, initializes return property only **/ \
GrippableBoxComponent_eventGetPrimaryGripType_Parms() \
: ReturnValue((EGripCollisionType)0) \
{ \
} \
}; \
struct GrippableBoxComponent_eventGripBreakDistance_Parms \
{ \
float ReturnValue; \
\
/** Constructor, initializes return property only **/ \
GrippableBoxComponent_eventGripBreakDistance_Parms() \
: ReturnValue(0) \
{ \
} \
}; \
struct GrippableBoxComponent_eventGripLateUpdateSetting_Parms \
{ \
EGripLateUpdateSettings ReturnValue; \
\
/** Constructor, initializes return property only **/ \
GrippableBoxComponent_eventGripLateUpdateSetting_Parms() \
: ReturnValue((EGripLateUpdateSettings)0) \
{ \
} \
}; \
struct GrippableBoxComponent_eventGripMovementReplicationType_Parms \
{ \
EGripMovementReplicationSettings ReturnValue; \
\
/** Constructor, initializes return property only **/ \
GrippableBoxComponent_eventGripMovementReplicationType_Parms() \
: ReturnValue((EGripMovementReplicationSettings)0) \
{ \
} \
}; \
struct GrippableBoxComponent_eventIsHeld_Parms \
{ \
TArray<FBPGripPair> HoldingControllers; \
bool bIsHeld; \
}; \
struct GrippableBoxComponent_eventOnChildGrip_Parms \
{ \
UGripMotionControllerComponent* GrippingController; \
FBPActorGripInformation GripInformation; \
}; \
struct GrippableBoxComponent_eventOnChildGripRelease_Parms \
{ \
UGripMotionControllerComponent* ReleasingController; \
FBPActorGripInformation GripInformation; \
bool bWasSocketed; \
}; \
struct GrippableBoxComponent_eventOnGrip_Parms \
{ \
UGripMotionControllerComponent* GrippingController; \
FBPActorGripInformation GripInformation; \
}; \
struct GrippableBoxComponent_eventOnGripRelease_Parms \
{ \
UGripMotionControllerComponent* ReleasingController; \
FBPActorGripInformation GripInformation; \
bool bWasSocketed; \
}; \
struct GrippableBoxComponent_eventOnInput_Parms \
{ \
FKey Key; \
TEnumAsByte<EInputEvent> KeyEvent; \
}; \
struct GrippableBoxComponent_eventOnSecondaryGrip_Parms \
{ \
USceneComponent* SecondaryGripComponent; \
FBPActorGripInformation GripInformation; \
}; \
struct GrippableBoxComponent_eventOnSecondaryGripRelease_Parms \
{ \
USceneComponent* ReleasingSecondaryGripComponent; \
FBPActorGripInformation GripInformation; \
}; \
struct GrippableBoxComponent_eventRequestsSocketing_Parms \
{ \
USceneComponent* ParentToSocketTo; \
FName OptionalSocketName; \
FTransform_NetQuantize RelativeTransform; \
bool ReturnValue; \
\
/** Constructor, initializes return property only **/ \
GrippableBoxComponent_eventRequestsSocketing_Parms() \
: ReturnValue(false) \
{ \
} \
}; \
struct GrippableBoxComponent_eventSecondaryGripType_Parms \
{ \
ESecondaryGripType ReturnValue; \
\
/** Constructor, initializes return property only **/ \
GrippableBoxComponent_eventSecondaryGripType_Parms() \
: ReturnValue((ESecondaryGripType)0) \
{ \
} \
}; \
struct GrippableBoxComponent_eventSetHeld_Parms \
{ \
UGripMotionControllerComponent* HoldingController; \
uint8 GripID; \
bool bIsHeld; \
}; \
struct GrippableBoxComponent_eventSimulateOnDrop_Parms \
{ \
bool ReturnValue; \
\
/** Constructor, initializes return property only **/ \
GrippableBoxComponent_eventSimulateOnDrop_Parms() \
: ReturnValue(false) \
{ \
} \
}; \
struct GrippableBoxComponent_eventTeleportBehavior_Parms \
{ \
EGripInterfaceTeleportBehavior ReturnValue; \
\
/** Constructor, initializes return property only **/ \
GrippableBoxComponent_eventTeleportBehavior_Parms() \
: ReturnValue((EGripInterfaceTeleportBehavior)0) \
{ \
} \
}; \
struct GrippableBoxComponent_eventTickGrip_Parms \
{ \
UGripMotionControllerComponent* GrippingController; \
FBPActorGripInformation GripInformation; \
float DeltaTime; \
};
#define vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_CALLBACK_WRAPPERS
#define vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_INCLASS_NO_PURE_DECLS \
private: \
static void StaticRegisterNativesUGrippableBoxComponent(); \
friend struct Z_Construct_UClass_UGrippableBoxComponent_Statics; \
public: \
DECLARE_CLASS(UGrippableBoxComponent, UBoxComponent, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/VRExpansionPlugin"), NO_API) \
DECLARE_SERIALIZER(UGrippableBoxComponent) \
virtual UObject* _getUObject() const override { return const_cast<UGrippableBoxComponent*>(this); } \
void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
#define vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_INCLASS \
private: \
static void StaticRegisterNativesUGrippableBoxComponent(); \
friend struct Z_Construct_UClass_UGrippableBoxComponent_Statics; \
public: \
DECLARE_CLASS(UGrippableBoxComponent, UBoxComponent, COMPILED_IN_FLAGS(0 | CLASS_Config), CASTCLASS_None, TEXT("/Script/VRExpansionPlugin"), NO_API) \
DECLARE_SERIALIZER(UGrippableBoxComponent) \
virtual UObject* _getUObject() const override { return const_cast<UGrippableBoxComponent*>(this); } \
void GetLifetimeReplicatedProps(TArray<FLifetimeProperty>& OutLifetimeProps) const override;
#define vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_STANDARD_CONSTRUCTORS \
/** Standard constructor, called after all reflected properties have been initialized */ \
NO_API UGrippableBoxComponent(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UGrippableBoxComponent) \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UGrippableBoxComponent); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UGrippableBoxComponent); \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API UGrippableBoxComponent(UGrippableBoxComponent&&); \
NO_API UGrippableBoxComponent(const UGrippableBoxComponent&); \
public:
#define vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_ENHANCED_CONSTRUCTORS \
private: \
/** Private move- and copy-constructors, should never be used */ \
NO_API UGrippableBoxComponent(UGrippableBoxComponent&&); \
NO_API UGrippableBoxComponent(const UGrippableBoxComponent&); \
public: \
DECLARE_VTABLE_PTR_HELPER_CTOR(NO_API, UGrippableBoxComponent); \
DEFINE_VTABLE_PTR_HELPER_CTOR_CALLER(UGrippableBoxComponent); \
DEFINE_DEFAULT_OBJECT_INITIALIZER_CONSTRUCTOR_CALL(UGrippableBoxComponent)
#define vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_PRIVATE_PROPERTY_OFFSET
#define vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_20_PROLOG \
vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_EVENT_PARMS
#define vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_GENERATED_BODY_LEGACY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_PRIVATE_PROPERTY_OFFSET \
vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_RPC_WRAPPERS \
vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_CALLBACK_WRAPPERS \
vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_INCLASS \
vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_STANDARD_CONSTRUCTORS \
public: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#define vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_GENERATED_BODY \
PRAGMA_DISABLE_DEPRECATION_WARNINGS \
public: \
vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_PRIVATE_PROPERTY_OFFSET \
vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_RPC_WRAPPERS_NO_PURE_DECLS \
vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_CALLBACK_WRAPPERS \
vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_INCLASS_NO_PURE_DECLS \
vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h_23_ENHANCED_CONSTRUCTORS \
private: \
PRAGMA_ENABLE_DEPRECATION_WARNINGS
template<> VREXPANSIONPLUGIN_API UClass* StaticClass<class UGrippableBoxComponent>();
#undef CURRENT_FILE_ID
#define CURRENT_FILE_ID vrexppluginexample_Plugins_VRExpansionPlugin_VRExpansionPlugin_Source_VRExpansionPlugin_Public_Grippables_GrippableBoxComponent_h
PRAGMA_ENABLE_DEPRECATION_WARNINGS
| [
"Justin@tonofham.com"
] | Justin@tonofham.com |
69a482f455727cf89f71f6632634ee972124d23a | 817db7f867910c7f09c034c5cd73fb570a025842 | /Other/Various Problems and Solutions/My Implementation/Æfingaverkefni/Æfing - Average Calculator - rétt/Æfing - Average Calculator/main.cpp | b091bee04ea81d13cffa3076699282fd8e6d6dd6 | [] | no_license | eddast/T-201-GSKI | 77a8e98bd84167f6f9a21ae42d78745bf556b618 | 998cb26f10d79c5f703f1df0010efdff262b80db | refs/heads/master | 2021-03-30T17:26:38.746772 | 2017-04-21T08:53:00 | 2017-04-21T08:53:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 842 | cpp | #include <iostream>
#include "averagecalculator.h"
#include "factoraveragecalculator.h"
using namespace std;
int main(int argc, char **argv)
{
AverageCalculator avg;
avg.addNumber(1.0);
avg.addNumber(3.0);
avg.addNumber(2.0);
avg.addNumber(4.0);
avg.addNumber(2.0);
cout << "Should be 2.4: " << avg.calculateAverage() << endl;
FactorAverageCalculator favg(2);
favg.addNumber(1.0);
favg.addNumber(3.0);
favg.addNumber(2.0);
favg.addNumber(4.0);
favg.addNumber(2.0);
cout << "Should be 4.8: " << favg.calculateAverage() << endl;
FactorAverageCalculator faavg(4);
faavg.addNumber(1.0);
faavg.addNumber(3.0);
faavg.addNumber(2.0);
faavg.addNumber(4.0);
faavg.addNumber(2.0);
cout << "Should be 9.6: " << faavg.calculateAverage() << endl;
return 0;
}
| [
"eddasr15@ru.is"
] | eddasr15@ru.is |
2cfeb01cd83964eb2466cd754c8484663f119769 | 3d739f27ee3e4c86e7aeb765d3b2668ec7918147 | /CODEFORCE/1099C.cpp | e73c0a4dd7ea62332ebf0290c9d84583b8fdc146 | [] | no_license | monircse061/My-All-Codes | 4b7bcba59a4c8a3497d38b6da08fca1faf0f6110 | b5c9f4367efd134c08a4f1eff680202484963098 | refs/heads/master | 2023-04-13T18:55:50.848787 | 2021-04-24T03:46:45 | 2021-04-24T03:46:45 | 361,062,511 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,112 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
string s,ans_string="";
int k,sum=0,sub=0,letter=0,unletter=0;
cin>>s;
scanf("%d",&k);
for(int i=0; i<s.length(); i++)
{
if(s[i]>=97&&s[i]<=122)
{
letter++;
}
else
{
unletter++;
}
}
if(letter>k)
{
sub=letter-k;
}
if(letter<k)
{
sum=k-letter;
}
for(int i=0; i<s.length(); i++)
{
if((i+1)<s.length())
{
if(sub>0&&(s[i+1]<97||s[i+1]>122)&&(s[i]>=97&&s[i]<=122))
{
sub--;
i++;
continue;
}
}
if(sum>0&&s[i]=='*'&&(s[i-1]>=97&&s[i]<=122))
{
while(sum>0){
ans_string+=s[i-1];
sum--;
}
continue;
}
if(s[i]>=97&&s[i]<=122)
ans_string+=s[i];
}
if(ans_string.size()==k)
{
cout<<ans_string;
}
else
{
printf("Impossible");
}
//main();
return 0;
}
| [
"monirahammod097@gmail.com"
] | monirahammod097@gmail.com |
62a74f56d0bc1b334763324beae66159b9871c3f | a1809f8abdb7d0d5bbf847b076df207400e7b08a | /Simpsons Hit&Run/game/libs/radscript/tools/radTuner/src/resource/EnterSliderValueDlg.h | 058cac691cb693bd5c469104b46d8d9695c2f8b8 | [] | no_license | RolphWoggom/shr.tar | 556cca3ff89fff3ff46a77b32a16bebca85acabf | 147796d55e69f490fb001f8cbdb9bf7de9e556ad | refs/heads/master | 2023-07-03T19:15:13.649803 | 2021-08-27T22:24:13 | 2021-08-27T22:24:13 | 400,380,551 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,460 | h | #if !defined(AFX_ENTERSLIDERVALUEDLG_H__763D49CE_02AA_4DC6_9A57_D9EDB4861ADE__INCLUDED_)
#define AFX_ENTERSLIDERVALUEDLG_H__763D49CE_02AA_4DC6_9A57_D9EDB4861ADE__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// EnterSliderValueDlg.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CEnterSliderValueDlg dialog
class CEnterSliderValueDlg : public CDialog
{
// Construction
public:
CEnterSliderValueDlg(CWnd* pParent = NULL); // standard constructor
const CString & GetValueInText( ) const;
float GetValueInFloat( ) const;
int GetValueInInt( ) const;
// Dialog Data
//{{AFX_DATA(CEnterSliderValueDlg)
enum { IDD = IDD_DIALOG_ENTER_SLIDER_VALUE };
CString m_strValueText;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CEnterSliderValueDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CEnterSliderValueDlg)
// NOTE: the ClassWizard will add member functions here
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_ENTERSLIDERVALUEDLG_H__763D49CE_02AA_4DC6_9A57_D9EDB4861ADE__INCLUDED_)
| [
"81568815+RolphWoggom@users.noreply.github.com"
] | 81568815+RolphWoggom@users.noreply.github.com |
6b07207b1b82cebae711828e0757c07118f0ee12 | 906784a48e7bdedde263ed9d841de37515dd4aef | /src/test/coins_tests.cpp | 280b77a20b6f51b144e99b94dca36cd071a024b9 | [
"MIT"
] | permissive | conan-equal-newone/pptp | 1865dc5f62155202a72bdd50ee7485610434317b | 1013c98859e6b9301e61cce53b9feea642962910 | refs/heads/master | 2020-03-07T16:24:04.113626 | 2018-04-02T13:07:10 | 2018-04-02T13:07:10 | 127,581,220 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 37,861 | 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 "coins.h"
#include "random.h"
#include "script/standard.h"
#include "uint256.h"
#include "undo.h"
#include "utilstrencodings.h"
#include "test/test_pptp.h"
#include "validation.h"
#include "consensus/validation.h"
#include <vector>
#include <map>
#include <boost/test/unit_test.hpp>
int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out);
void UpdateCoins(const CTransaction& tx, CValidationState &state, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight);
namespace
{
//! equality test
bool operator==(const Coin &a, const Coin &b) {
// Empty Coin objects are always equal.
if (a.IsSpent() && b.IsSpent()) return true;
return a.fCoinBase == b.fCoinBase &&
a.nHeight == b.nHeight &&
a.out == b.out;
}
class CCoinsViewTest : public CCoinsView
{
uint256 hashBestBlock_;
std::map<COutPoint, Coin> map_;
public:
bool GetCoin(const COutPoint& outpoint, Coin& coin) const override
{
std::map<COutPoint, Coin>::const_iterator it = map_.find(outpoint);
if (it == map_.end()) {
return false;
}
coin = it->second;
if (coin.IsSpent() && insecure_rand() % 2 == 0) {
// Randomly return false in case of an empty entry.
return false;
}
return true;
}
uint256 GetBestBlock() const override { return hashBestBlock_; }
bool BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock) override
{
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end(); ) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) {
// Same optimization used in CCoinsViewDB is to only write dirty entries.
map_[it->first] = it->second.coin;
if (it->second.coin.IsSpent() && insecure_rand() % 3 == 0) {
// Randomly delete empty entries on write.
map_.erase(it->first);
}
}
mapCoins.erase(it++);
}
if (!hashBlock.IsNull())
hashBestBlock_ = hashBlock;
return true;
}
};
class CCoinsViewCacheTest : public CCoinsViewCache
{
public:
CCoinsViewCacheTest(CCoinsView* base) : CCoinsViewCache(base) {}
void SelfTest() const
{
// Manually recompute the dynamic usage of the whole data, and compare it.
size_t ret = memusage::DynamicUsage(cacheCoins);
size_t count = 0;
for (CCoinsMap::iterator it = cacheCoins.begin(); it != cacheCoins.end(); it++) {
ret += it->second.coin.DynamicMemoryUsage();
++count;
}
BOOST_CHECK_EQUAL(GetCacheSize(), count);
BOOST_CHECK_EQUAL(DynamicMemoryUsage(), ret);
}
CCoinsMap& map() { return cacheCoins; }
size_t& usage() { return cachedCoinsUsage; }
};
}
BOOST_FIXTURE_TEST_SUITE(coins_tests, BasicTestingSetup)
static const unsigned int NUM_SIMULATION_ITERATIONS = 40000;
// This is a large randomized insert/remove simulation test on a variable-size
// stack of caches on top of CCoinsViewTest.
//
// It will randomly create/update/delete Coin entries to a tip of caches, with
// txids picked from a limited list of random 256-bit hashes. Occasionally, a
// new tip is added to the stack of caches, or the tip is flushed and removed.
//
// During the process, booleans are kept to make sure that the randomized
// operation hits all branches.
BOOST_AUTO_TEST_CASE(coins_cache_simulation_test)
{
// Various coverage trackers.
bool removed_all_caches = false;
bool reached_4_caches = false;
bool added_an_entry = false;
bool added_an_unspendable_entry = false;
bool removed_an_entry = false;
bool updated_an_entry = false;
bool found_an_entry = false;
bool missed_an_entry = false;
bool uncached_an_entry = false;
// A simple map to track what we expect the cache stack to represent.
std::map<COutPoint, Coin> result;
// The cache stack.
CCoinsViewTest base; // A CCoinsViewTest at the bottom.
std::vector<CCoinsViewCacheTest*> stack; // A stack of CCoinsViewCaches on top.
stack.push_back(new CCoinsViewCacheTest(&base)); // Start with one cache.
// Use a limited set of random transaction ids, so we do test overwriting entries.
std::vector<uint256> txids;
txids.resize(NUM_SIMULATION_ITERATIONS / 8);
for (unsigned int i = 0; i < txids.size(); i++) {
txids[i] = GetRandHash();
}
for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {
// Do a random modification.
{
uint256 txid = txids[insecure_rand() % txids.size()]; // txid we're going to modify in this iteration.
Coin& coin = result[COutPoint(txid, 0)];
// Determine whether to test HaveCoin before or after Access* (or both). As these functions
// can influence each other's behaviour by pulling things into the cache, all combinations
// are tested.
bool test_havecoin_before = (insecure_rand() & 0x3) == 0; // TODO change to InsecureRandBits(2) when backporting Bitcoin #10321
bool test_havecoin_after = (insecure_rand() & 0x3) == 0; // TODO change to InsecureRandBits(2) when backporting Bitcoin #10321
bool result_havecoin = test_havecoin_before ? stack.back()->HaveCoin(COutPoint(txid, 0)) : false;
const Coin& entry = (insecure_rand() % 500 == 0) ? AccessByTxid(*stack.back(), txid) : stack.back()->AccessCoin(COutPoint(txid, 0));
BOOST_CHECK(coin == entry);
BOOST_CHECK(!test_havecoin_before || result_havecoin == !entry.IsSpent());
if (test_havecoin_after) {
bool ret = stack.back()->HaveCoin(COutPoint(txid, 0));
BOOST_CHECK(ret == !entry.IsSpent());
}
if (insecure_rand() % 5 == 0 || coin.IsSpent()) {
Coin newcoin;
newcoin.out.nValue = insecure_rand();
newcoin.nHeight = 1;
if (insecure_rand() % 16 == 0 && coin.IsSpent()) {
newcoin.out.scriptPubKey.assign(1 + (insecure_rand() & 0x3F), OP_RETURN);
BOOST_CHECK(newcoin.out.scriptPubKey.IsUnspendable());
added_an_unspendable_entry = true;
} else {
newcoin.out.scriptPubKey.assign(insecure_rand() & 0x3F, 0); // Random sizes so we can test memory usage accounting
(coin.IsSpent() ? added_an_entry : updated_an_entry) = true;
coin = newcoin;
}
stack.back()->AddCoin(COutPoint(txid, 0), std::move(newcoin), !coin.IsSpent() || insecure_rand() & 1);
} else {
removed_an_entry = true;
coin.Clear();
stack.back()->SpendCoin(COutPoint(txid, 0));
}
}
// One every 10 iterations, remove a random entry from the cache
if (insecure_rand() % 10) {
COutPoint out(txids[insecure_rand() % txids.size()], 0);
int cacheid = insecure_rand() % stack.size();
stack[cacheid]->Uncache(out);
uncached_an_entry |= !stack[cacheid]->HaveCoinInCache(out);
}
// Once every 1000 iterations and at the end, verify the full cache.
if (insecure_rand() % 1000 == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
BOOST_TEST_MESSAGE("coins_cache_simulation_test - verifying full cache");
for (auto it = result.begin(); it != result.end(); it++) {
bool have = stack.back()->HaveCoin(it->first);
const Coin& coin = stack.back()->AccessCoin(it->first);
BOOST_CHECK(have == !coin.IsSpent());
BOOST_CHECK(coin == it->second);
if (coin.IsSpent()) {
missed_an_entry = true;
} else {
BOOST_CHECK(stack.back()->HaveCoinInCache(it->first));
found_an_entry = true;
}
}
BOOST_FOREACH(const CCoinsViewCacheTest *test, stack) {
test->SelfTest();
}
}
if (insecure_rand() % 100 == 0) {
// Every 100 iterations, flush an intermediate cache
if (stack.size() > 1 && insecure_rand() % 2 == 0) {
unsigned int flushIndex = insecure_rand() % (stack.size() - 1);
stack[flushIndex]->Flush();
}
}
if (insecure_rand() % 100 == 0) {
// Every 100 iterations, change the cache stack.
if (stack.size() > 0 && insecure_rand() % 2 == 0) {
//Remove the top cache
stack.back()->Flush();
delete stack.back();
stack.pop_back();
}
if (stack.size() == 0 || (stack.size() < 4 && insecure_rand() % 2)) {
//Add a new cache
CCoinsView* tip = &base;
if (stack.size() > 0) {
tip = stack.back();
} else {
removed_all_caches = true;
}
stack.push_back(new CCoinsViewCacheTest(tip));
if (stack.size() == 4) {
reached_4_caches = true;
}
}
}
}
// Clean up the stack.
while (stack.size() > 0) {
delete stack.back();
stack.pop_back();
}
// Verify coverage.
BOOST_CHECK(removed_all_caches);
BOOST_CHECK(reached_4_caches);
BOOST_CHECK(added_an_entry);
BOOST_CHECK(added_an_unspendable_entry);
BOOST_CHECK(removed_an_entry);
BOOST_CHECK(updated_an_entry);
BOOST_CHECK(found_an_entry);
BOOST_CHECK(missed_an_entry);
BOOST_CHECK(uncached_an_entry);
}
// Store of all necessary tx and undo data for next test
typedef std::map<COutPoint, std::tuple<CTransaction,CTxUndo,Coin>> UtxoData;
UtxoData utxoData;
UtxoData::iterator FindRandomFrom(const std::set<COutPoint> &utxoSet) {
assert(utxoSet.size());
auto utxoSetIt = utxoSet.lower_bound(COutPoint(GetRandHash(), 0));
if (utxoSetIt == utxoSet.end()) {
utxoSetIt = utxoSet.begin();
}
auto utxoDataIt = utxoData.find(*utxoSetIt);
assert(utxoDataIt != utxoData.end());
return utxoDataIt;
}
// This test is similar to the previous test
// except the emphasis is on testing the functionality of UpdateCoins
// random txs are created and UpdateCoins is used to update the cache stack
// In particular it is tested that spending a duplicate coinbase tx
// has the expected effect (the other duplicate is overwitten at all cache levels)
BOOST_AUTO_TEST_CASE(updatecoins_simulation_test)
{
bool spent_a_duplicate_coinbase = false;
// A simple map to track what we expect the cache stack to represent.
std::map<COutPoint, Coin> result;
// The cache stack.
CCoinsViewTest base; // A CCoinsViewTest at the bottom.
std::vector<CCoinsViewCacheTest*> stack; // A stack of CCoinsViewCaches on top.
stack.push_back(new CCoinsViewCacheTest(&base)); // Start with one cache.
// Track the txids we've used in various sets
std::set<COutPoint> coinbase_coins;
std::set<COutPoint> disconnected_coins;
std::set<COutPoint> duplicate_coins;
std::set<COutPoint> utxoset;
for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {
uint32_t randiter = insecure_rand();
// 19/20 txs add a new transaction
if (randiter % 20 < 19) {
CMutableTransaction tx;
tx.vin.resize(1);
tx.vout.resize(1);
tx.vout[0].nValue = i; //Keep txs unique unless intended to duplicate
tx.vout[0].scriptPubKey.assign(insecure_rand() & 0x3F, 0); // Random sizes so we can test memory usage accounting
unsigned int height = insecure_rand();
Coin old_coin;
// 2/20 times create a new coinbase
if (randiter % 20 < 2 || coinbase_coins.size() < 10) {
// 1/10 of those times create a duplicate coinbase
if (insecure_rand() % 10 == 0 && coinbase_coins.size()) {
auto utxod = FindRandomFrom(coinbase_coins);
// Reuse the exact same coinbase
tx = std::get<0>(utxod->second);
// shouldn't be available for reconnection if its been duplicated
disconnected_coins.erase(utxod->first);
duplicate_coins.insert(utxod->first);
}
else {
coinbase_coins.insert(COutPoint(tx.GetHash(), 0));
}
assert(CTransaction(tx).IsCoinBase());
}
// 17/20 times reconnect previous or add a regular tx
else {
COutPoint prevout;
// 1/20 times reconnect a previously disconnected tx
if (randiter % 20 == 2 && disconnected_coins.size()) {
auto utxod = FindRandomFrom(disconnected_coins);
tx = std::get<0>(utxod->second);
prevout = tx.vin[0].prevout;
if (!CTransaction(tx).IsCoinBase() && !utxoset.count(prevout)) {
disconnected_coins.erase(utxod->first);
continue;
}
// If this tx is already IN the UTXO, then it must be a coinbase, and it must be a duplicate
if (utxoset.count(utxod->first)) {
assert(CTransaction(tx).IsCoinBase());
assert(duplicate_coins.count(utxod->first));
}
disconnected_coins.erase(utxod->first);
}
// 16/20 times create a regular tx
else {
auto utxod = FindRandomFrom(utxoset);
prevout = utxod->first;
// Construct the tx to spend the coins of prevouthash
tx.vin[0].prevout = prevout;
assert(!CTransaction(tx).IsCoinBase());
}
// In this simple test coins only have two states, spent or unspent, save the unspent state to restore
old_coin = result[prevout];
// Update the expected result of prevouthash to know these coins are spent
result[prevout].Clear();
utxoset.erase(prevout);
// The test is designed to ensure spending a duplicate coinbase will work properly
// if that ever happens and not resurrect the previously overwritten coinbase
if (duplicate_coins.count(prevout)) {
spent_a_duplicate_coinbase = true;
}
}
// Update the expected result to know about the new output coins
assert(tx.vout.size() == 1);
const COutPoint outpoint(tx.GetHash(), 0);
result[outpoint] = Coin(tx.vout[0], height, CTransaction(tx).IsCoinBase());
// Call UpdateCoins on the top cache
CTxUndo undo;
CValidationState dummy;
UpdateCoins(tx, dummy, *(stack.back()), undo, height);
// Update the utxo set for future spends
utxoset.insert(outpoint);
// Track this tx and undo info to use later
utxoData.emplace(outpoint, std::make_tuple(tx,undo,old_coin));
} else if (utxoset.size()) {
//1/20 times undo a previous transaction
auto utxod = FindRandomFrom(utxoset);
CTransaction &tx = std::get<0>(utxod->second);
CTxUndo &undo = std::get<1>(utxod->second);
Coin &orig_coin = std::get<2>(utxod->second);
// Update the expected result
// Remove new outputs
result[utxod->first].Clear();
// If not coinbase restore prevout
if (!tx.IsCoinBase()) {
result[tx.vin[0].prevout] = orig_coin;
}
// Disconnect the tx from the current UTXO
// See code in DisconnectBlock
// remove outputs
stack.back()->SpendCoin(utxod->first);
// restore inputs
if (!tx.IsCoinBase()) {
const COutPoint &out = tx.vin[0].prevout;
Coin coin = undo.vprevout[0];
ApplyTxInUndo(std::move(coin), *(stack.back()), out);
}
// Store as a candidate for reconnection
disconnected_coins.insert(utxod->first);
// Update the utxoset
utxoset.erase(utxod->first);
if (!tx.IsCoinBase())
utxoset.insert(tx.vin[0].prevout);
}
// Once every 1000 iterations and at the end, verify the full cache.
if (insecure_rand() % 1000 == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
BOOST_TEST_MESSAGE("updatecoins_simulation_test - verifying full cache");
for (auto it = result.begin(); it != result.end(); it++) {
bool have = stack.back()->HaveCoin(it->first);
const Coin& coin = stack.back()->AccessCoin(it->first);
BOOST_CHECK(have == !coin.IsSpent());
BOOST_CHECK(coin == it->second);
}
}
// One every 10 iterations, remove a random entry from the cache
if (utxoset.size() > 1 && insecure_rand() % 30) {
stack[insecure_rand() % stack.size()]->Uncache(FindRandomFrom(utxoset)->first);
}
if (disconnected_coins.size() > 1 && insecure_rand() % 30) {
stack[insecure_rand() % stack.size()]->Uncache(FindRandomFrom(disconnected_coins)->first);
}
if (duplicate_coins.size() > 1 && insecure_rand() % 30) {
stack[insecure_rand() % stack.size()]->Uncache(FindRandomFrom(duplicate_coins)->first);
}
if (insecure_rand() % 100 == 0) {
// Every 100 iterations, flush an intermediate cache
if (stack.size() > 1 && insecure_rand() % 2 == 0) {
unsigned int flushIndex = insecure_rand() % (stack.size() - 1);
stack[flushIndex]->Flush();
}
}
if (insecure_rand() % 100 == 0) {
// Every 100 iterations, change the cache stack.
if (stack.size() > 0 && insecure_rand() % 2 == 0) {
stack.back()->Flush();
delete stack.back();
stack.pop_back();
}
if (stack.size() == 0 || (stack.size() < 4 && insecure_rand() % 2)) {
CCoinsView* tip = &base;
if (stack.size() > 0) {
tip = stack.back();
}
stack.push_back(new CCoinsViewCacheTest(tip));
}
}
}
// Clean up the stack.
while (stack.size() > 0) {
delete stack.back();
stack.pop_back();
}
// Verify coverage.
BOOST_CHECK(spent_a_duplicate_coinbase);
}
BOOST_AUTO_TEST_CASE(ccoins_serialization)
{
// Good example
CDataStream ss1(ParseHex("97f23c835800816115944e077fe7c803cfa57f29b36bf87c1d35"), SER_DISK, CLIENT_VERSION);
Coin cc1;
ss1 >> cc1;
BOOST_CHECK_EQUAL(cc1.fCoinBase, false);
BOOST_CHECK_EQUAL(cc1.nHeight, 203998);
BOOST_CHECK_EQUAL(cc1.out.nValue, 60000000000ULL);
BOOST_CHECK_EQUAL(HexStr(cc1.out.scriptPubKey), HexStr(GetScriptForDestination(CKeyID(uint160(ParseHex("816115944e077fe7c803cfa57f29b36bf87c1d35"))))));
// Good example
CDataStream ss2(ParseHex("8ddf77bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4"), SER_DISK, CLIENT_VERSION);
Coin cc2;
ss2 >> cc2;
BOOST_CHECK_EQUAL(cc2.fCoinBase, true);
BOOST_CHECK_EQUAL(cc2.nHeight, 120891);
BOOST_CHECK_EQUAL(cc2.out.nValue, 110397);
BOOST_CHECK_EQUAL(HexStr(cc2.out.scriptPubKey), HexStr(GetScriptForDestination(CKeyID(uint160(ParseHex("8c988f1a4a4de2161e0f50aac7f17e7f9555caa4"))))));
// Smallest possible example
CDataStream ss3(ParseHex("000006"), SER_DISK, CLIENT_VERSION);
Coin cc3;
ss3 >> cc3;
BOOST_CHECK_EQUAL(cc3.fCoinBase, false);
BOOST_CHECK_EQUAL(cc3.nHeight, 0);
BOOST_CHECK_EQUAL(cc3.out.nValue, 0);
BOOST_CHECK_EQUAL(cc3.out.scriptPubKey.size(), 0);
// scriptPubKey that ends beyond the end of the stream
CDataStream ss4(ParseHex("000007"), SER_DISK, CLIENT_VERSION);
try {
Coin cc4;
ss4 >> cc4;
BOOST_CHECK_MESSAGE(false, "We should have thrown");
} catch (const std::ios_base::failure& e) {
}
// Very large scriptPubKey (3*10^9 bytes) past the end of the stream
CDataStream tmp(SER_DISK, CLIENT_VERSION);
uint64_t x = 3000000000ULL;
tmp << VARINT(x);
BOOST_CHECK_EQUAL(HexStr(tmp.begin(), tmp.end()), "8a95c0bb00");
CDataStream ss5(ParseHex("00008a95c0bb00"), SER_DISK, CLIENT_VERSION);
try {
Coin cc5;
ss5 >> cc5;
BOOST_CHECK_MESSAGE(false, "We should have thrown");
} catch (const std::ios_base::failure& e) {
}
}
const static COutPoint OUTPOINT;
const static CAmount PRUNED = -1;
const static CAmount ABSENT = -2;
const static CAmount FAIL = -3;
const static CAmount VALUE1 = 100;
const static CAmount VALUE2 = 200;
const static CAmount VALUE3 = 300;
const static char DIRTY = CCoinsCacheEntry::DIRTY;
const static char FRESH = CCoinsCacheEntry::FRESH;
const static char NO_ENTRY = -1;
const static auto FLAGS = {char(0), FRESH, DIRTY, char(DIRTY | FRESH)};
const static auto CLEAN_FLAGS = {char(0), FRESH};
const static auto DIRTY_FLAGS = {DIRTY, char(DIRTY | FRESH)};
const static auto ABSENT_FLAGS = {NO_ENTRY};
void SetCoinsValue(CAmount value, Coin& coin)
{
assert(value != ABSENT);
coin.Clear();
assert(coin.IsSpent());
if (value != PRUNED) {
coin.out.nValue = value;
coin.nHeight = 1;
assert(!coin.IsSpent());
}
}
size_t InsertCoinsMapEntry(CCoinsMap& map, CAmount value, char flags)
{
if (value == ABSENT) {
assert(flags == NO_ENTRY);
return 0;
}
assert(flags != NO_ENTRY);
CCoinsCacheEntry entry;
entry.flags = flags;
SetCoinsValue(value, entry.coin);
auto inserted = map.emplace(OUTPOINT, std::move(entry));
assert(inserted.second);
return inserted.first->second.coin.DynamicMemoryUsage();
}
void GetCoinsMapEntry(const CCoinsMap& map, CAmount& value, char& flags)
{
auto it = map.find(OUTPOINT);
if (it == map.end()) {
value = ABSENT;
flags = NO_ENTRY;
} else {
if (it->second.coin.IsSpent()) {
value = PRUNED;
} else {
value = it->second.coin.out.nValue;
}
flags = it->second.flags;
assert(flags != NO_ENTRY);
}
}
void WriteCoinsViewEntry(CCoinsView& view, CAmount value, char flags)
{
CCoinsMap map;
InsertCoinsMapEntry(map, value, flags);
view.BatchWrite(map, {});
}
class SingleEntryCacheTest
{
public:
SingleEntryCacheTest(CAmount base_value, CAmount cache_value, char cache_flags)
{
WriteCoinsViewEntry(base, base_value, base_value == ABSENT ? NO_ENTRY : DIRTY);
cache.usage() += InsertCoinsMapEntry(cache.map(), cache_value, cache_flags);
}
CCoinsView root;
CCoinsViewCacheTest base{&root};
CCoinsViewCacheTest cache{&base};
};
void CheckAccessCoin(CAmount base_value, CAmount cache_value, CAmount expected_value, char cache_flags, char expected_flags)
{
SingleEntryCacheTest test(base_value, cache_value, cache_flags);
test.cache.AccessCoin(OUTPOINT);
test.cache.SelfTest();
CAmount result_value;
char result_flags;
GetCoinsMapEntry(test.cache.map(), result_value, result_flags);
BOOST_CHECK_EQUAL(result_value, expected_value);
BOOST_CHECK_EQUAL(result_flags, expected_flags);
}
BOOST_AUTO_TEST_CASE(ccoins_access)
{
/* Check AccessCoin behavior, requesting a coin from a cache view layered on
* top of a base view, and checking the resulting entry in the cache after
* the access.
*
* Base Cache Result Cache Result
* Value Value Value Flags Flags
*/
CheckAccessCoin(ABSENT, ABSENT, ABSENT, NO_ENTRY , NO_ENTRY );
CheckAccessCoin(ABSENT, PRUNED, PRUNED, 0 , 0 );
CheckAccessCoin(ABSENT, PRUNED, PRUNED, FRESH , FRESH );
CheckAccessCoin(ABSENT, PRUNED, PRUNED, DIRTY , DIRTY );
CheckAccessCoin(ABSENT, PRUNED, PRUNED, DIRTY|FRESH, DIRTY|FRESH);
CheckAccessCoin(ABSENT, VALUE2, VALUE2, 0 , 0 );
CheckAccessCoin(ABSENT, VALUE2, VALUE2, FRESH , FRESH );
CheckAccessCoin(ABSENT, VALUE2, VALUE2, DIRTY , DIRTY );
CheckAccessCoin(ABSENT, VALUE2, VALUE2, DIRTY|FRESH, DIRTY|FRESH);
CheckAccessCoin(PRUNED, ABSENT, ABSENT, NO_ENTRY , NO_ENTRY );
CheckAccessCoin(PRUNED, PRUNED, PRUNED, 0 , 0 );
CheckAccessCoin(PRUNED, PRUNED, PRUNED, FRESH , FRESH );
CheckAccessCoin(PRUNED, PRUNED, PRUNED, DIRTY , DIRTY );
CheckAccessCoin(PRUNED, PRUNED, PRUNED, DIRTY|FRESH, DIRTY|FRESH);
CheckAccessCoin(PRUNED, VALUE2, VALUE2, 0 , 0 );
CheckAccessCoin(PRUNED, VALUE2, VALUE2, FRESH , FRESH );
CheckAccessCoin(PRUNED, VALUE2, VALUE2, DIRTY , DIRTY );
CheckAccessCoin(PRUNED, VALUE2, VALUE2, DIRTY|FRESH, DIRTY|FRESH);
CheckAccessCoin(VALUE1, ABSENT, VALUE1, NO_ENTRY , 0 );
CheckAccessCoin(VALUE1, PRUNED, PRUNED, 0 , 0 );
CheckAccessCoin(VALUE1, PRUNED, PRUNED, FRESH , FRESH );
CheckAccessCoin(VALUE1, PRUNED, PRUNED, DIRTY , DIRTY );
CheckAccessCoin(VALUE1, PRUNED, PRUNED, DIRTY|FRESH, DIRTY|FRESH);
CheckAccessCoin(VALUE1, VALUE2, VALUE2, 0 , 0 );
CheckAccessCoin(VALUE1, VALUE2, VALUE2, FRESH , FRESH );
CheckAccessCoin(VALUE1, VALUE2, VALUE2, DIRTY , DIRTY );
CheckAccessCoin(VALUE1, VALUE2, VALUE2, DIRTY|FRESH, DIRTY|FRESH);
}
void CheckSpendCoins(CAmount base_value, CAmount cache_value, CAmount expected_value, char cache_flags, char expected_flags)
{
SingleEntryCacheTest test(base_value, cache_value, cache_flags);
test.cache.SpendCoin(OUTPOINT);
test.cache.SelfTest();
CAmount result_value;
char result_flags;
GetCoinsMapEntry(test.cache.map(), result_value, result_flags);
BOOST_CHECK_EQUAL(result_value, expected_value);
BOOST_CHECK_EQUAL(result_flags, expected_flags);
};
BOOST_AUTO_TEST_CASE(ccoins_spend)
{
/* Check SpendCoin behavior, requesting a coin from a cache view layered on
* top of a base view, spending, and then checking
* the resulting entry in the cache after the modification.
*
* Base Cache Result Cache Result
* Value Value Value Flags Flags
*/
CheckSpendCoins(ABSENT, ABSENT, ABSENT, NO_ENTRY , NO_ENTRY );
CheckSpendCoins(ABSENT, PRUNED, PRUNED, 0 , DIRTY );
CheckSpendCoins(ABSENT, PRUNED, ABSENT, FRESH , NO_ENTRY );
CheckSpendCoins(ABSENT, PRUNED, PRUNED, DIRTY , DIRTY );
CheckSpendCoins(ABSENT, PRUNED, ABSENT, DIRTY|FRESH, NO_ENTRY );
CheckSpendCoins(ABSENT, VALUE2, PRUNED, 0 , DIRTY );
CheckSpendCoins(ABSENT, VALUE2, ABSENT, FRESH , NO_ENTRY );
CheckSpendCoins(ABSENT, VALUE2, PRUNED, DIRTY , DIRTY );
CheckSpendCoins(ABSENT, VALUE2, ABSENT, DIRTY|FRESH, NO_ENTRY );
CheckSpendCoins(PRUNED, ABSENT, ABSENT, NO_ENTRY , NO_ENTRY );
CheckSpendCoins(PRUNED, PRUNED, PRUNED, 0 , DIRTY );
CheckSpendCoins(PRUNED, PRUNED, ABSENT, FRESH , NO_ENTRY );
CheckSpendCoins(PRUNED, PRUNED, PRUNED, DIRTY , DIRTY );
CheckSpendCoins(PRUNED, PRUNED, ABSENT, DIRTY|FRESH, NO_ENTRY );
CheckSpendCoins(PRUNED, VALUE2, PRUNED, 0 , DIRTY );
CheckSpendCoins(PRUNED, VALUE2, ABSENT, FRESH , NO_ENTRY );
CheckSpendCoins(PRUNED, VALUE2, PRUNED, DIRTY , DIRTY );
CheckSpendCoins(PRUNED, VALUE2, ABSENT, DIRTY|FRESH, NO_ENTRY );
CheckSpendCoins(VALUE1, ABSENT, PRUNED, NO_ENTRY , DIRTY );
CheckSpendCoins(VALUE1, PRUNED, PRUNED, 0 , DIRTY );
CheckSpendCoins(VALUE1, PRUNED, ABSENT, FRESH , NO_ENTRY );
CheckSpendCoins(VALUE1, PRUNED, PRUNED, DIRTY , DIRTY );
CheckSpendCoins(VALUE1, PRUNED, ABSENT, DIRTY|FRESH, NO_ENTRY );
CheckSpendCoins(VALUE1, VALUE2, PRUNED, 0 , DIRTY );
CheckSpendCoins(VALUE1, VALUE2, ABSENT, FRESH , NO_ENTRY );
CheckSpendCoins(VALUE1, VALUE2, PRUNED, DIRTY , DIRTY );
CheckSpendCoins(VALUE1, VALUE2, ABSENT, DIRTY|FRESH, NO_ENTRY );
}
void CheckAddCoinBase(CAmount base_value, CAmount cache_value, CAmount modify_value, CAmount expected_value, char cache_flags, char expected_flags, bool coinbase)
{
SingleEntryCacheTest test(base_value, cache_value, cache_flags);
CAmount result_value;
char result_flags;
try {
CTxOut output;
output.nValue = modify_value;
test.cache.AddCoin(OUTPOINT, Coin(std::move(output), 1, coinbase), coinbase);
test.cache.SelfTest();
GetCoinsMapEntry(test.cache.map(), result_value, result_flags);
} catch (std::logic_error& e) {
result_value = FAIL;
result_flags = NO_ENTRY;
}
BOOST_CHECK_EQUAL(result_value, expected_value);
BOOST_CHECK_EQUAL(result_flags, expected_flags);
}
// Simple wrapper for CheckAddCoinBase function above that loops through
// different possible base_values, making sure each one gives the same results.
// This wrapper lets the coins_add test below be shorter and less repetitive,
// while still verifying that the CoinsViewCache::AddCoin implementation
// ignores base values.
template <typename... Args>
void CheckAddCoin(Args&&... args)
{
for (CAmount base_value : {ABSENT, PRUNED, VALUE1})
CheckAddCoinBase(base_value, std::forward<Args>(args)...);
}
BOOST_AUTO_TEST_CASE(ccoins_add)
{
/* Check AddCoin behavior, requesting a new coin from a cache view,
* writing a modification to the coin, and then checking the resulting
* entry in the cache after the modification. Verify behavior with the
* with the AddCoin potential_overwrite argument set to false, and to true.
*
* Cache Write Result Cache Result potential_overwrite
* Value Value Value Flags Flags
*/
CheckAddCoin(ABSENT, VALUE3, VALUE3, NO_ENTRY , DIRTY|FRESH, false);
CheckAddCoin(ABSENT, VALUE3, VALUE3, NO_ENTRY , DIRTY , true );
CheckAddCoin(PRUNED, VALUE3, VALUE3, 0 , DIRTY|FRESH, false);
CheckAddCoin(PRUNED, VALUE3, VALUE3, 0 , DIRTY , true );
CheckAddCoin(PRUNED, VALUE3, VALUE3, FRESH , DIRTY|FRESH, false);
CheckAddCoin(PRUNED, VALUE3, VALUE3, FRESH , DIRTY|FRESH, true );
CheckAddCoin(PRUNED, VALUE3, VALUE3, DIRTY , DIRTY , false);
CheckAddCoin(PRUNED, VALUE3, VALUE3, DIRTY , DIRTY , true );
CheckAddCoin(PRUNED, VALUE3, VALUE3, DIRTY|FRESH, DIRTY|FRESH, false);
CheckAddCoin(PRUNED, VALUE3, VALUE3, DIRTY|FRESH, DIRTY|FRESH, true );
CheckAddCoin(VALUE2, VALUE3, FAIL , 0 , NO_ENTRY , false);
CheckAddCoin(VALUE2, VALUE3, VALUE3, 0 , DIRTY , true );
CheckAddCoin(VALUE2, VALUE3, FAIL , FRESH , NO_ENTRY , false);
CheckAddCoin(VALUE2, VALUE3, VALUE3, FRESH , DIRTY|FRESH, true );
CheckAddCoin(VALUE2, VALUE3, FAIL , DIRTY , NO_ENTRY , false);
CheckAddCoin(VALUE2, VALUE3, VALUE3, DIRTY , DIRTY , true );
CheckAddCoin(VALUE2, VALUE3, FAIL , DIRTY|FRESH, NO_ENTRY , false);
CheckAddCoin(VALUE2, VALUE3, VALUE3, DIRTY|FRESH, DIRTY|FRESH, true );
}
void CheckWriteCoins(CAmount parent_value, CAmount child_value, CAmount expected_value, char parent_flags, char child_flags, char expected_flags)
{
SingleEntryCacheTest test(ABSENT, parent_value, parent_flags);
CAmount result_value;
char result_flags;
try {
WriteCoinsViewEntry(test.cache, child_value, child_flags);
test.cache.SelfTest();
GetCoinsMapEntry(test.cache.map(), result_value, result_flags);
} catch (std::logic_error& e) {
result_value = FAIL;
result_flags = NO_ENTRY;
}
BOOST_CHECK_EQUAL(result_value, expected_value);
BOOST_CHECK_EQUAL(result_flags, expected_flags);
}
BOOST_AUTO_TEST_CASE(ccoins_write)
{
/* Check BatchWrite behavior, flushing one entry from a child cache to a
* parent cache, and checking the resulting entry in the parent cache
* after the write.
*
* Parent Child Result Parent Child Result
* Value Value Value Flags Flags Flags
*/
CheckWriteCoins(ABSENT, ABSENT, ABSENT, NO_ENTRY , NO_ENTRY , NO_ENTRY );
CheckWriteCoins(ABSENT, PRUNED, PRUNED, NO_ENTRY , DIRTY , DIRTY );
CheckWriteCoins(ABSENT, PRUNED, ABSENT, NO_ENTRY , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(ABSENT, VALUE2, VALUE2, NO_ENTRY , DIRTY , DIRTY );
CheckWriteCoins(ABSENT, VALUE2, VALUE2, NO_ENTRY , DIRTY|FRESH, DIRTY|FRESH);
CheckWriteCoins(PRUNED, ABSENT, PRUNED, 0 , NO_ENTRY , 0 );
CheckWriteCoins(PRUNED, ABSENT, PRUNED, FRESH , NO_ENTRY , FRESH );
CheckWriteCoins(PRUNED, ABSENT, PRUNED, DIRTY , NO_ENTRY , DIRTY );
CheckWriteCoins(PRUNED, ABSENT, PRUNED, DIRTY|FRESH, NO_ENTRY , DIRTY|FRESH);
CheckWriteCoins(PRUNED, PRUNED, PRUNED, 0 , DIRTY , DIRTY );
CheckWriteCoins(PRUNED, PRUNED, PRUNED, 0 , DIRTY|FRESH, DIRTY );
CheckWriteCoins(PRUNED, PRUNED, ABSENT, FRESH , DIRTY , NO_ENTRY );
CheckWriteCoins(PRUNED, PRUNED, ABSENT, FRESH , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(PRUNED, PRUNED, PRUNED, DIRTY , DIRTY , DIRTY );
CheckWriteCoins(PRUNED, PRUNED, PRUNED, DIRTY , DIRTY|FRESH, DIRTY );
CheckWriteCoins(PRUNED, PRUNED, ABSENT, DIRTY|FRESH, DIRTY , NO_ENTRY );
CheckWriteCoins(PRUNED, PRUNED, ABSENT, DIRTY|FRESH, DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(PRUNED, VALUE2, VALUE2, 0 , DIRTY , DIRTY );
CheckWriteCoins(PRUNED, VALUE2, VALUE2, 0 , DIRTY|FRESH, DIRTY );
CheckWriteCoins(PRUNED, VALUE2, VALUE2, FRESH , DIRTY , DIRTY|FRESH);
CheckWriteCoins(PRUNED, VALUE2, VALUE2, FRESH , DIRTY|FRESH, DIRTY|FRESH);
CheckWriteCoins(PRUNED, VALUE2, VALUE2, DIRTY , DIRTY , DIRTY );
CheckWriteCoins(PRUNED, VALUE2, VALUE2, DIRTY , DIRTY|FRESH, DIRTY );
CheckWriteCoins(PRUNED, VALUE2, VALUE2, DIRTY|FRESH, DIRTY , DIRTY|FRESH);
CheckWriteCoins(PRUNED, VALUE2, VALUE2, DIRTY|FRESH, DIRTY|FRESH, DIRTY|FRESH);
CheckWriteCoins(VALUE1, ABSENT, VALUE1, 0 , NO_ENTRY , 0 );
CheckWriteCoins(VALUE1, ABSENT, VALUE1, FRESH , NO_ENTRY , FRESH );
CheckWriteCoins(VALUE1, ABSENT, VALUE1, DIRTY , NO_ENTRY , DIRTY );
CheckWriteCoins(VALUE1, ABSENT, VALUE1, DIRTY|FRESH, NO_ENTRY , DIRTY|FRESH);
CheckWriteCoins(VALUE1, PRUNED, PRUNED, 0 , DIRTY , DIRTY );
CheckWriteCoins(VALUE1, PRUNED, FAIL , 0 , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, PRUNED, ABSENT, FRESH , DIRTY , NO_ENTRY );
CheckWriteCoins(VALUE1, PRUNED, FAIL , FRESH , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, PRUNED, PRUNED, DIRTY , DIRTY , DIRTY );
CheckWriteCoins(VALUE1, PRUNED, FAIL , DIRTY , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, PRUNED, ABSENT, DIRTY|FRESH, DIRTY , NO_ENTRY );
CheckWriteCoins(VALUE1, PRUNED, FAIL , DIRTY|FRESH, DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, VALUE2, VALUE2, 0 , DIRTY , DIRTY );
CheckWriteCoins(VALUE1, VALUE2, FAIL , 0 , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, VALUE2, VALUE2, FRESH , DIRTY , DIRTY|FRESH);
CheckWriteCoins(VALUE1, VALUE2, FAIL , FRESH , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, VALUE2, VALUE2, DIRTY , DIRTY , DIRTY );
CheckWriteCoins(VALUE1, VALUE2, FAIL , DIRTY , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, VALUE2, VALUE2, DIRTY|FRESH, DIRTY , DIRTY|FRESH);
CheckWriteCoins(VALUE1, VALUE2, FAIL , DIRTY|FRESH, DIRTY|FRESH, NO_ENTRY );
// The checks above omit cases where the child flags are not DIRTY, since
// they would be too repetitive (the parent cache is never updated in these
// cases). The loop below covers these cases and makes sure the parent cache
// is always left unchanged.
for (CAmount parent_value : {ABSENT, PRUNED, VALUE1})
for (CAmount child_value : {ABSENT, PRUNED, VALUE2})
for (char parent_flags : parent_value == ABSENT ? ABSENT_FLAGS : FLAGS)
for (char child_flags : child_value == ABSENT ? ABSENT_FLAGS : CLEAN_FLAGS)
CheckWriteCoins(parent_value, child_value, parent_value, parent_flags, child_flags, parent_flags);
}
BOOST_AUTO_TEST_SUITE_END()
| [
"manuke77@hotmail.com"
] | manuke77@hotmail.com |
77fd366db1cbc553f2162129764cc0db8fd54f01 | b16e2f0fd07d99f4fdf2abd84b032e47033c8dd8 | /Exercises/07-09-2019/ex5.cpp | adcff2f31f59893ab7195e7a2496ae293e46fb5f | [] | no_license | pcc-cs/cs-003a-summer-2019 | aba0c724c1c7bdc116a127a642d2a4ddbbe96ac8 | 22a35b50447c88c92c494377f34e11a8ef6e62bf | refs/heads/master | 2020-06-13T18:12:02.355367 | 2019-07-31T03:48:26 | 2019-07-31T03:48:26 | 194,744,853 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 395 | cpp | #include <cstdio>
struct Duo {
int a, b;
};
class Point {
private:
int x, y;
public:
Point();
Point(int, int);
};
Point::Point() {
}
Point::Point(int a, int b) : x(a), y(b) {
}
int main() {
Duo da1[] = {
{1, 2},
{22, 3},
{-9, 4}
};
Point pa1[0x10];
Point pa2[] = {
Point(10, 20),
Point(-2, 7),
Point(1, -10)
};
Point *pp1 = new Point[0x10];
}
| [
"sekhar@allurefx.com"
] | sekhar@allurefx.com |
bddbdb7d8be885f0fb3289ff18c19465d051f233 | 1af49694004c6fbc31deada5618dae37255ce978 | /chrome/browser/android/autofill_assistant/trigger_script_bridge_android.h | 5aee6ecc4e5f1f5b5c71683ec91d69196be46a6b | [
"BSD-3-Clause"
] | permissive | sadrulhc/chromium | 59682b173a00269ed036eee5ebfa317ba3a770cc | a4b950c23db47a0fdd63549cccf9ac8acd8e2c41 | refs/heads/master | 2023-02-02T07:59:20.295144 | 2020-12-01T21:32:32 | 2020-12-01T21:32:32 | 317,678,056 | 3 | 0 | BSD-3-Clause | 2020-12-01T21:56:26 | 2020-12-01T21:56:25 | null | UTF-8 | C++ | false | false | 3,588 | 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 CHROME_BROWSER_ANDROID_AUTOFILL_ASSISTANT_TRIGGER_SCRIPT_BRIDGE_ANDROID_H_
#define CHROME_BROWSER_ANDROID_AUTOFILL_ASSISTANT_TRIGGER_SCRIPT_BRIDGE_ANDROID_H_
#include <map>
#include <memory>
#include <string>
#include "base/android/jni_android.h"
#include "base/optional.h"
#include "components/autofill_assistant/browser/client.h"
#include "components/autofill_assistant/browser/metrics.h"
#include "components/autofill_assistant/browser/service.pb.h"
#include "components/autofill_assistant/browser/trigger_context.h"
#include "components/autofill_assistant/browser/trigger_scripts/trigger_script_coordinator.h"
#include "url/gurl.h"
namespace autofill_assistant {
// Facilitates communication between trigger script UI and native coordinator.
class TriggerScriptBridgeAndroid : public TriggerScriptCoordinator::Observer {
public:
TriggerScriptBridgeAndroid();
~TriggerScriptBridgeAndroid() override;
TriggerScriptBridgeAndroid(const TriggerScriptBridgeAndroid&) = delete;
TriggerScriptBridgeAndroid& operator=(const TriggerScriptBridgeAndroid&) =
delete;
// Attempts to start a trigger script on |initial_url|. Will communicate with
// |jdelegate| to show/hide UI as necessary.
void StartTriggerScript(Client* client,
const base::android::JavaParamRef<jobject>& jdelegate,
const GURL& initial_url,
std::unique_ptr<TriggerContext> trigger_context,
jlong jservice_request_sender);
// Stops and destroys the current trigger script, if any. Also disconnects the
// java-side delegate.
void StopTriggerScript();
// Called by the UI to execute a specific trigger script action.
void OnTriggerScriptAction(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& jcaller,
jint action);
// Called by the UI when the bottom sheet has been swipe-dismissed.
void OnBottomSheetClosedWithSwipe(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& jcaller);
// Called by the UI when the back button was pressed. Returns whether the
// event was handled or not.
bool OnBackButtonPressed(JNIEnv* env,
const base::android::JavaParamRef<jobject>& jcaller);
// Access to the last shown trigger script.
base::Optional<TriggerScriptUIProto> GetLastShownTriggerScript() const;
// Clears the last shown trigger script.
void ClearLastShownTriggerScript();
// Called by the UI when the keyboard was shown or hidden.
void OnKeyboardVisibilityChanged(
JNIEnv* env,
const base::android::JavaParamRef<jobject>& jcaller,
jboolean jvisible);
private:
// From TriggerScriptCoordinator::Observer:
void OnTriggerScriptShown(const TriggerScriptUIProto& proto) override;
void OnTriggerScriptHidden() override;
void OnTriggerScriptFinished(Metrics::LiteScriptFinishedState state) override;
void OnWebContentsVisibilityChanged(bool visible) override;
// Reference to the Java counterpart to this class.
base::android::ScopedJavaGlobalRef<jobject> java_object_;
bool disable_header_animations_for_testing_ = false;
base::Optional<TriggerScriptUIProto> last_shown_trigger_script_;
std::unique_ptr<TriggerScriptCoordinator> trigger_script_coordinator_;
};
} // namespace autofill_assistant
#endif // CHROME_BROWSER_ANDROID_AUTOFILL_ASSISTANT_TRIGGER_SCRIPT_BRIDGE_ANDROID_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
8cb7753816fe62dd7fcc290bc2377a4a4e706e7c | d9a7afdf160f15a2a8bc5f07e07a0422c5d8da8b | /3-work/qt/qt-HMIClient/HMIClient/netinterface/mesmqttclient.cpp | 24adecea433d69187e3a8e04df2d35fd62873136 | [] | no_license | programcj/programming_path | 964cd53fdef74041241ebe392eeb0c4566eb1d89 | 04a410492a9ee7173612122e367ac1c5b101d7ce | refs/heads/master | 2021-12-15T10:43:33.066541 | 2021-12-11T10:20:01 | 2021-12-11T10:20:01 | 184,296,551 | 1 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 9,289 | cpp | #include "mesmqttclient.h"
#include "../appconfig.h"
#include "../tools/MQTTClient.h"
#include "../dao/mesproducteds.h"
#include "mesmsghandler.h"
//d2s/设备序列号/协议版本/data 下位机上传数据
//s2d/设备序列号/协议版本/data 上位机下传数据
//S2d/设备序列号/协议版本/config 配置消息下发
volatile MQTTClient_deliveryToken deliveredtoken;
#define QOS 1
//
static void delivered(void *context, MQTTClient_deliveryToken dt)
{
qDebug()<< QString("Message with token value %1 delivery confirmed").arg((int)dt);
deliveredtoken = dt;
}
//MQTT API:收到消息后的回调,我订阅的主题的消息都到这里来
static int _msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message)
{
//int i;
//char* payloadptr;
//变成QT形式
QString topic(topicName);
QByteArray msg;
msg.append((char*)message->payload,message->payloadlen);
MESMqttClient *client=(MESMqttClient*)context;
//让QT类处理c->c++
client->msgarrvd(topic,msg);
MQTTClient_freeMessage(&message);
MQTTClient_free(topicName);
return 1;
}
void connlost(void *context, char *cause)
{
qDebug()<< "\nConnection lost\n";
qDebug()<< QString(" cause: %1").arg(cause);
}
MESMqttClient *MESMqttClient::self;
MESMqttClient::MESMqttClient(QObject *parent) :
QThread(parent)
{
self=this;
mqtClient=NULL;
connectFlag=false;
#if QT_VERSION < 0x050000
interruptionRequested=false;
#endif
}
MESMqttClient *MESMqttClient::getInstance()
{
return self;
}
bool MESMqttClient::sendMsg(QString &topic, QByteArray &msg)
{
QByteArray ba = topic.toLatin1();
const char *c_topic = ba.data();
int length=msg.length();
int rc=0;
bool ret=false;
#define TIMEOUT 10000L
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_deliveryToken token;
mutex.lock();
if(mqtClient!=NULL){
pubmsg.payload = msg.data();
pubmsg.payloadlen = length;
pubmsg.qos = QOS;
pubmsg.retained = 0;
MQTTClient_publishMessage(mqtClient, c_topic, &pubmsg, &token);
rc = MQTTClient_waitForCompletion(mqtClient, token, TIMEOUT);
if(rc==MQTTCLIENT_SUCCESS)
ret=true;
}
mutex.unlock();
return ret;
}
bool MESMqttClient::sendD2S(QByteArray &msg)
{
QString topic = QString("d2s/%1/2/data").arg(AppConfig::getInstance().DeviceSN);
return sendMsg(topic,msg);
}
bool MESMqttClient::sendD2S(quint8 tag, quint16 key, QString &msg)
{
MESPacket packet;
packet.versions=2;
packet.tag=tag;
packet.body.key=key;
packet.body.setData(msg);
QByteArray packetBytes=packet.toByteArray();
qDebug() << QString("tag:%1,Key:%2").arg(packet.tag).arg(packet.body.key);
return sendD2S(packetBytes);
}
#include "../dao/mesdispatchorder.h"
//Mqtt收到的消息,MQTT的回调过来
void MESMqttClient::msgarrvd(QString &topic, QByteArray &msg)
{
MESPacket packet;
MESPacket::toMESPacket(msg,packet);
qDebug() << QString("收到 %1,TAG:%2,KEY:%3").arg(topic).arg(packet.tag).arg(packet.body.key);
if(topic=="s2d/444/2/order"){
QJsonParseError json_error;
QJsonDocument parse_doucment = QJsonDocument::fromJson(msg, &json_error);
if(json_error.error == QJsonParseError::NoError) {
QJsonObject obj=parse_doucment.object();
MESDispatchOrder::onSubimtOrder(obj);
}
return;
}
//把收到的主题和消息,仍给处理任务
MESMsgHandler::getInstance()->appendMsg(topic,packet);
}
void MESMqttClient::restartConnect()
{
closeConnect();
}
void MESMqttClient::closeConnect()
{
mutex.lock();
if(mqtClient!=NULL){
MQTTClient_disconnect(mqtClient, 10000);
}
mutex.unlock();
}
bool MESMqttClient::isConnected()
{
return connectFlag;
}
#if QT_VERSION < 0x050000
void MESMqttClient::requestInterruption()
{
QMutexLocker locker(&selfMutex);
interruptionRequested=true;
}
bool MESMqttClient::isInterruptionRequested()
{
QMutexLocker locker(&selfMutex);
return interruptionRequested;
}
#endif
#include "signal.h"
//线程任务
void MESMqttClient::run()
{
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_willOptions will_opts = MQTTClient_willOptions_initializer;
MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
QString topic;
QString topicWill;
QString topicTest;
int onLineId=0;
int rc=0;
signal(SIGPIPE,SIG_IGN);
statusMessage="开始运行";
while (!isInterruptionRequested())
{
QUuid uuid=QUuid::createUuid();
QString clinetID=uuid.toString();
QByteArray curl = url.toLatin1();
QByteArray cid = clinetID.toLatin1();
QByteArray cuser= userName.toLatin1();
QByteArray cpass = password.toLatin1();
QByteArray cwillMess;
QByteArray ctopicWill;
QJsonObject willMsgJson;
topic = QString("s2d/%1/2/data").arg(AppConfig::getInstance().DeviceSN);
topicTest = QString("s2d/%1/2/order").arg(AppConfig::getInstance().DeviceSN);
topicWill= QString("will/%1").arg(AppConfig::getInstance().DeviceSN);
ctopicWill=topicWill.toLatin1();
onLineId=QDateTime::currentMSecsSinceEpoch()%10000;
connectFlag=false;
qDebug() << QString("connect : %1,clientId:%2").arg(url).arg(clinetID);
if(url.length()==0)
{
QThread::sleep(1);
continue;
}
willMsgJson.insert("sn",AppConfig::getInstance().DeviceSN);
willMsgJson.insert("onLineId",onLineId);
cwillMess=QJsonDocument(willMsgJson).toJson();
mutex.lock();
MQTTClient_create(&mqtClient, curl.data(), cid.data(),
MQTTCLIENT_PERSISTENCE_NONE, this);
conn_opts.keepAliveInterval = 20; //保持,心跳
conn_opts.cleansession = 1;
conn_opts.will = &will_opts;
conn_opts.will->message = cwillMess.data();
conn_opts.will->qos = 1;
conn_opts.will->topicName = ctopicWill.data();
conn_opts.will->retained = 0;
if(cuser.length()>0)
conn_opts.username=cuser.data(); //用户名
if(cpass.length()>0)
conn_opts.password=cpass.data(); //密码
//设定消息接收回调
MQTTClient_setCallbacks(mqtClient, NULL, connlost, _msgarrvd, delivered);
mutex.unlock();
connectFlag=false;
//连接
statusMessage="开始连接...";
if ((rc = MQTTClient_connect(mqtClient, &conn_opts)) != MQTTCLIENT_SUCCESS) {
qDebug()<< QString("Failed to connect, return code %1").arg(rc);
statusMessage="正在重新连接...";
//restart....
QThread::sleep(1);
mutex.lock();
MQTTClient_disconnect(mqtClient, 10000);
MQTTClient_destroy(&mqtClient);
mqtClient=NULL;
mutex.unlock();
continue;
}
connectFlag=true;
//订阅主题
mutex.lock();
MQTTClient_subscribe(mqtClient,topic.toLatin1().data(),1);
MQTTClient_subscribe(mqtClient,topicTest.toLatin1().data(),1);
mutex.unlock();
qDebug()<< QString("subscribe Topic: %1").arg(topic);
qDebug()<< "subscribe Topic:" << topicTest;
statusMessage="连接成功";
//send online topic
{
QString onlineTopic=QString("online/%1").arg(AppConfig::getInstance().DeviceSN);
QJsonObject jsonOnline;
jsonOnline.insert("sn",AppConfig::getInstance().DeviceSN);
jsonOnline.insert("onLineId",onLineId);
QByteArray msg=QJsonDocument(jsonOnline).toJson();
sendMsg(onlineTopic, msg);
}
while (!isInterruptionRequested() && 1==MQTTClient_isConnected(mqtClient) ) {
//subimt
MESProducteds producteds;
if(MESProducteds::onCountMsg()>0){
if( MESProducteds::onFirstMsg(producteds) ){
//subimt......
//qDebug() << QString("生产数据:%1,%2 %3").arg(producteds.CreatedTime).arg(producteds.TagType).arg(producteds.Msg);
//生产数据上传
qDebug() <<"生产数据上传";
this->sendD2S(producteds.TagType,0x01,producteds.Msg);
MESProducteds::onDelete(producteds.ID);
}
}
QThread::sleep(1);
}
mutex.lock();
MQTTClient_disconnect(mqtClient, 10000);
MQTTClient_destroy(&mqtClient);
mqtClient=NULL;
mutex.unlock();
statusMessage="连接断开";
connectFlag=false;
qDebug() << "restart connect .................";
}
statusMessage="退出运行";
qDebug() << "Thread exit**************";
}
| [
"aa"
] | aa |
604d0f00cdb3a09822f381fb830aeaeefe72c939 | 7caf7448f4af84989e0a1f43bf287bd83cefce64 | /src/Namespace_Exercise.cpp | 2610898c4bed41120b7a09eba520220f0638af8c | [] | no_license | westsidepedro/Namespace_Exercise | ac2c31310a6e4a0412b8d0dfaa5022ab11f019c5 | 36d5a736ce872d69f9c761458c36256453fe62b1 | refs/heads/master | 2021-04-05T23:49:14.149109 | 2018-03-12T20:28:50 | 2018-03-12T20:28:50 | 124,916,887 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 684 | cpp | //============================================================================
// Name : Namespace_Exercise.cpp
/*
* -create 2 classes
* -put one of each in different namespaces
* -use 'using' and 'nameSpace::class' to refer to namespace in function
*/
// Description : Hello World in C++, Ansi-style
//============================================================================
#include <iostream>
#include "Numbers.h"
#include "Letters.h"
using namespace std;
using namespace Balls;
int main()
{
Numbers test;
test.sumValue(10, 3);
test.speak();
Shit::Letters realTest;
realTest.sayHello("Bill");
realTest.speak();
return 0;
}
| [
"jpetterson@DS-17.decker.local"
] | jpetterson@DS-17.decker.local |
c98acdb96b68959dfcb052657e37be38ef65184f | 78b56332ebc8fdb14e9a9433c031f5ed35f43c94 | /cxxcommon/message/message_device_realtime_data_item.cpp | 2217016946ac33d1be168d7b5caeabe30f920a34 | [] | no_license | xiezhaoHi/guolujiance_server | 0b43c193d32851f8e59af21a8b58cd4335138e5f | e3ac88b95cadc2eaa8aea167e17b356cdc32708f | refs/heads/master | 2021-05-14T14:21:26.081310 | 2018-12-11T08:39:54 | 2018-12-11T08:39:54 | 115,968,871 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,555 | cpp | #include "message_device_realtime_data_item.h"
CMessageDeviceRealtimeDataItem::CMessageDeviceRealtimeDataItem()
{
static_assert(sizeof(T_MSG_DEVICE_REALTIME_DATA_ITEM) == 12, "sizeof(T_MSG_DEVICE_REALTIME_DATA_ITEM) != 12");
memset(&m_struct, 0x00, sizeof(m_struct));
}
CMessageDeviceRealtimeDataItem::~CMessageDeviceRealtimeDataItem()
{
}
std::size_t CMessageDeviceRealtimeDataItem::Length()
{
return sizeof(m_struct);
}
bool CMessageDeviceRealtimeDataItem::WriteToOutputByteArray(OutputByteArray & out)
{
out.WriteU16(m_struct.channelNo);
out.WriteU16(m_struct.datatype);
for (int i = 0; i < 7; i++) {
out.WriteU8(m_struct.data[i]);
}
out.WriteU8(m_struct.reserved);
return true;
}
bool CMessageDeviceRealtimeDataItem::ReadFromInputByteArray(InputByteArray & in)
{
m_struct.channelNo = in.ReadU16();
m_struct.datatype = in.ReadU16();
for (int i = 0; i < 7; i++) {
m_struct.data[i] = in.ReadU8();
}
m_struct.reserved = in.ReadU8();
return true;
}
QString CMessageDeviceRealtimeDataItem::ToString()
{
QString qstr;
QTextStream stream(&qstr);
stream << "[CMessageDeviceRealtimeDataItem] { ";
stream << "[ channelNo:" << m_struct.channelNo << "], ";
stream << "[ datatype:" << m_struct.datatype << "], ";
for (int i = 0; i < sizeof(m_struct.data); i++)
{
stream << QString("[ data[%1]:%2]").arg(i).arg(m_struct.data[i]) << "], ";
}
stream << "[ reserved:" << m_struct.reserved << "], ";
stream << "}";
return qstr;
}
| [
"15182911195@163.com"
] | 15182911195@163.com |
f73bd5b3eb0b70ab3d9568707bb41c0d1b3c9e85 | 3b0711d6a7680c341f2e77d2a016f36d059b95e6 | /project_game/game.h | 8959bed588d20280c2355c7537c8000013fa5d49 | [] | no_license | tremwil/CiSA_Prog2_Arduino | 213d7a6a86b2f05961176295b0d19a6e606edc09 | 9233c54a9ef460e148dbddf6c2664895fdb93808 | refs/heads/master | 2022-04-12T22:13:01.421088 | 2020-03-10T05:27:58 | 2020-03-10T05:27:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,141 | h | #ifndef GAME_H
#define GAME_H
#include <LiquidCrystal.h>
typedef unsigned long long uint64;
#define FPS 20
// Indexed with (next << 2 | curr)
const byte LVL_TO_CHAR[16]
{
' ', 0x03, 0x05, 0x01,
0x02, '!', '!', '!',
0x04, '!', '!', '!',
0x00, '!', '!', 0xff
};
class LcdGame
{
private:
// Shift from aligning with characters - 0 to 4
byte levelShift;
// Level data stored as columns, each being 4 bits
byte level[17];
// Char data ordering:
// 0-5: Block data: 1st bit is left (0) / right (1),
// 2 other bits are full (0), top (1), bottom (2).
// 6: Player top
// 7: Player bottom
byte charData[64];
void shiftLevel()
{
levelShift = (levelShift + 1) % 5;
if (levelShift == 0)
{
for (int i = 0; i < 16; i++)
{
level[i] = level[i+1];
}
byte next = 0b1111, prv = level[15];
while ((next | prv) == 0b1111)
{
next = random((prv >> 2)? 0 : 4) << 2 | random((prv & 3)? 0 : 4);
}
Serial.println(next, BIN);
level[16] = next;
}
}
public:
LiquidCrystal *lcd;
int highScore;
int startSpeed;
int gameSpeed;
int playerX;
int itCnt;
int score;
bool gameOver;
int incSpeed; // used as bool but must be int size
int secForInc;
LcdGame(LiquidCrystal *lcd) : charData{ }, level{ }
{
this->lcd = lcd;
this->highScore = 0;
this->startSpeed = 5;
this->playerX = 2;
this->incSpeed = true;
this->secForInc = 30;
}
void start()
{
itCnt = 0;
score = 0;
levelShift = 0;
gameSpeed = startSpeed;
gameOver = false;
memset(level, 0, sizeof(level));
}
void tick(int playerY)
{
if (gameOver)
{
lcd->clear();
if (itCnt < 2*FPS) lcd->print("G A M E O V E R");
else
{
lcd->print("Score:");
lcd->print(score);
lcd->setCursor(0,1);
lcd->print("Speed:");
lcd->print(gameSpeed);
if (highScore == score) lcd->print(" (BEST!)");
}
}
else
{
// Char generation
byte leftFill = (1 << levelShift) - 1;
byte currFill = ~leftFill & 0b11111;
for (unsigned int i = 0; i < 16; i++)
{
charData[i] = (i / 8) ? currFill : leftFill;
}
for (unsigned int i = 0, n = 0x0F0F; i < 16; i++, n >>= 1)
{
charData[i+16] = (n & 1) ? ((i / 8) ? currFill : leftFill) : 0;
}
for (unsigned int i = 0, n = 0xF0F0; i < 16; i++, n >>= 1)
{
charData[i+32] = (n & 1) ? ((i / 8) ? currFill : leftFill) : 0;
}
// Create player data
uint64 player_top = (uint64)0x0606 << (8*playerY);
uint64 player_btm = (uint64)0x0606 >> max(0, 64 - 8*playerY) << max(0, 8*playerY - 64);
byte char_top = LVL_TO_CHAR[(level[playerX+1] & 3) << 2 | (level[playerX] & 3)];
byte char_btm = LVL_TO_CHAR[(level[playerX+1] >> 2) << 2 | (level[playerX] >> 2)];
uint64 bit_top = (char_top == ' ')? 0 : ((uint64*)charData)[char_top];
uint64 bit_btm = (char_btm == ' ')? 0 : ((uint64*)charData)[char_btm];
((uint64*)charData)[6] = bit_top | player_top;
((uint64*)charData)[7] = bit_btm | player_btm;
// Render level with generated char data
for (int i = 0; i < 8; i++)
{
lcd->createChar(i, charData + 8*i);
}
lcd->clear();
for (int i = 0; i < 16; i++)
{
if (i == playerX)
{
lcd->setCursor(i, 0);
lcd->write(byte(6));
lcd->setCursor(i, 1);
lcd->write(byte(7));
}
else
{
lcd->setCursor(i, 0);
lcd->write(LVL_TO_CHAR[(level[i+1] & 3) << 2 | (level[i] & 3)]);
lcd->setCursor(i, 1);
lcd->write(LVL_TO_CHAR[(level[i+1] >> 2) << 2 | (level[i] >> 2)]);
}
}
// Player lost
if ((bit_top & player_top) || (bit_btm & player_btm))
{
gameOver = true;
itCnt = 0;
}
// Shift level
else if (itCnt % (FPS / gameSpeed) == 0)
{
shiftLevel();
score++;
if (score > highScore) { highScore = score; }
}
if (incSpeed && (itCnt+1) % (secForInc * FPS) == 0)
{
gameSpeed = min(gameSpeed + 1, FPS);
}
}
itCnt++;
}
};
#endif
| [
"tremwil@gmail.com"
] | tremwil@gmail.com |
9e8347423ce6640ea7c0c10b67c14c5c34eea73e | 485003035ae6dbab60ffa280de2cde1736123048 | /acm/sicily/graph1002.cpp | 0be19ccc761b442a3dfdf1d0f1577c75d149e813 | [] | no_license | yeyue910107/algorithm | 96d900219ebf86e06b3ee6ca0b558b82155195c4 | 5aa96ab4843cbb6815744042676c84a487193d39 | refs/heads/master | 2021-01-10T01:12:56.529233 | 2014-02-28T13:06:49 | 2014-02-28T13:06:49 | 8,578,205 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,319 | cpp | #include <stdio.h>
#include <vector>
using namespace std;
class Graph {
private:
std::vector<vector<int> > table;
int num;
public:
void dfs(const int, vector<bool> &);
void get_connection_component();
void create_graph(const int, const int);
Graph() { }
Graph(const vector<vector<int> > &table, const int &num) : table(table), num(num){ }
~Graph() { }
};
void Graph::get_connection_component() {
vector<bool> flag;
int i, count = 0;
for (i = 0;i < num; i++)
flag.push_back(false);
for (i = 0; i < num; i++) {
if (!flag[i]) {
//printf("component %d:\n", ++count);
++count;
dfs(i, flag);
}
}
printf("%d\n", count);
}
void Graph::dfs(const int i, vector<bool> &flag) {
//cout << table[i][0] << endl;
flag[i] = true;
vector<int>::iterator iter;
for (iter = table[i].begin(); iter != table[i].end(); iter++) {
if (!flag[*iter])
dfs(*iter, flag);
}
}
void Graph::create_graph(const int n, const int e) {
int i, vi, vj;
num = n;
table.resize(n);
for (i = 0; i < n; i++)
table[i].push_back(i);
for (i = 0; i < e; i++) {
scanf("%d%d", &vi, &vj);
table[vi - 1].push_back(vj - 1);
table[vj - 1].push_back(vi - 1);
}
}
int main() {
int n, e;
Graph g;
scanf("%d%d", &n, &e);
g.create_graph(n, e);
//g.travel_dfs();
//g.travel_bfs();
g.get_connection_component();
} | [
"yeyue910107@gmail.com"
] | yeyue910107@gmail.com |
58e4010d5ba30ddf9272e46545ce2b960d768fb2 | 51835b8233eccfb53cffe96c071fc6fcf3d84f9b | /src/PinkGoblin.h | 6c80d03bf7a13f10c828bbf39da23057f9638cea | [
"MIT"
] | permissive | GoldbergData/newWorldSimulation | eda3dc31df52c15ff19c3cb78a0001f1ac0bd6c3 | 9534592ac2c9f5909bd0aba126fa678a40cf0408 | refs/heads/main | 2023-05-15T02:14:00.805514 | 2021-06-18T02:46:05 | 2021-06-18T02:46:05 | 373,677,715 | 0 | 0 | MIT | 2021-06-09T03:14:35 | 2021-06-04T00:32:16 | C++ | UTF-8 | C++ | false | false | 464 | h | /**
* @file PinkGoblin.h
* @author John Nguyen, Joshua Goldberg (jvn1567@gmail.com, J.GOLDBERG4674@edmail.edcc.edu)
* @brief Bare alien class. Did not have time to implement differences.
* @version 0.1
* @date 2021-06-12
*
* @copyright Copyright (c) 2021
*
*/
#ifndef _PinkGoblin_h
#define _PinkGoblin_h
#include <string>
#include "AlienBase.h"
using namespace std;
class PinkGoblin : public AlienBase {
private:
public:
PinkGoblin();
};
#endif
| [
"josh.goldberg1@outlook.com"
] | josh.goldberg1@outlook.com |
0904bff8ad90ddc386b261157cc6d347f238f30d | 7e0979fbe2d94eb0d51f0f0d174bedceab42032e | /UpnpLibrary/upnpactionreply.h | 3b0cb4179ef2598ca4afff0a1bf72b38916b8c26 | [] | no_license | robby31/Upnp | 86874a42d122f9aaf298a9ff323ce3cfb375be17 | 8bb97922eca35ce62b9fbb12297f8c60555eeed2 | refs/heads/master | 2021-01-22T14:20:42.201774 | 2020-02-15T08:53:34 | 2020-02-15T08:53:34 | 82,330,493 | 6 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 925 | h | #ifndef UPNPACTIONREPLY_H
#define UPNPACTIONREPLY_H
#include <QObject>
#include <QNetworkReply>
#include "upnperror.h"
#include "soapactionresponse.h"
class UpnpActionReply : public QObject
{
Q_OBJECT
Q_PROPERTY(SoapActionResponse* response READ response NOTIFY responseChanged)
public:
explicit UpnpActionReply(QNetworkReply *reply);
QNetworkReply::NetworkError error() const;
QByteArray data() const;
SoapActionResponse *response() const;
signals:
void errorOccured(const UpnpError &error);
void finished();
void responseChanged();
private slots:
void replyReceived();
void networkError(QNetworkReply::NetworkError error);
void replyDestroyed();
private:
QNetworkReply *m_reply = Q_NULLPTR;
QNetworkReply::NetworkError m_error = QNetworkReply::NoError;
QString m_actionName;
SoapActionResponse *m_response = Q_NULLPTR;
};
#endif // UPNPACTIONREPLY_H
| [
"guillaume.himbert@gmail.com"
] | guillaume.himbert@gmail.com |
0e8f80a49bc0cb154279314349c01cb01833e4f5 | 58958463ae51c6af762ade55e53154cdd57e9b71 | /OpenSauce/shared/Include/blamlib/Halo1/items/item_structures.hpp | 40e4b406a24c8faa097e79c1d2bd0ceafd261d0b | [] | no_license | yumiris/OpenSauce | af270d723d15bffdfb38f44dbebd90969c432c2b | d200c970c918921d40e9fb376ec685c77797c8b7 | refs/heads/master | 2022-10-10T17:18:20.363252 | 2022-08-11T20:31:30 | 2022-08-11T20:31:30 | 188,238,131 | 14 | 3 | null | 2020-07-14T08:48:26 | 2019-05-23T13:19:31 | C++ | UTF-8 | C++ | false | false | 1,967 | hpp | /*
Yelo: Open Sauce SDK
See license\OpenSauce\OpenSauce for specific license information
*/
#pragma once
#include <blamlib/Halo1/objects/object_structures.hpp>
namespace Yelo
{
namespace Flags
{
enum item_flags : long_flags {
_item_in_unit_inventory_bit,
_item_hidden_in_unit_inventory_bit, // I think? this bit is either/or with the above bit. name taken from H2
_item_unk2_bit,
_item_collided_with_bsp_bit,
_item_collided_with_object_bit,
_item_at_reset_bit, // see _object_at_reset_bit
};
};
namespace Objects
{
struct s_item_data
{
long_flags flags; // 0x1F4
game_time_t detonation_countdown; // 0x1F8
struct {
int16 surface_index; // 0x1FA
int16 bsp_reference_index; // 0x1FC
}bsp_collision;
PAD16; // 0x1FE
datum_index dropped_by_unit_index; // 0x200 set when the unit who had this item drops it
game_ticks_t last_update_time; // 0x204
struct {
datum_index object_index; // 0x208
real_point3d object_position; // 0x20C
}object_collision;
UNKNOWN_TYPE(real_vector3d); // 0x218
UNKNOWN_TYPE(real_euler_angles2d); // 0x224
}; BOOST_STATIC_ASSERT( sizeof(s_item_data) == (Enums::k_object_size_item - Enums::k_object_size_object) );
struct s_garbage_data
{
game_time_t ticks_until_gc;
PAD16;
int32 _unused[5];
}; BOOST_STATIC_ASSERT( sizeof(s_garbage_data) == (Enums::k_object_size_garbage - Enums::k_object_size_item) );
struct s_item_datum
{
enum { k_object_types_mask = Enums::_object_type_mask_item };
s_object_data object;
s_item_data item;
}; BOOST_STATIC_ASSERT( sizeof(s_item_datum) == Enums::k_object_size_item );
struct s_garbage_datum : s_item_datum
{
enum { k_object_types_mask = FLAG(Enums::_object_type_garbage) };
s_garbage_data garbage;
}; BOOST_STATIC_ASSERT( sizeof(s_garbage_datum) == Enums::k_object_size_garbage );
};
}; | [
"kornman00@gmail.com"
] | kornman00@gmail.com |
d11a05f7576ba5d07b671965f9f3b9609089ea29 | a97b9ad50e283b4e930ab59547806eb303b52c6f | /tutorials/incompressible/pisoFoam/ras/cavity/10/p | af98e70335117684f48ca9e5bd5c1badfd61d9be | [] | no_license | harrisbk/OpenFOAM_run | fdcd4f81bd3205764988ea95c25fd2a5c130841b | 9591c98336561bcfb3b7259617b5363aacf48067 | refs/heads/master | 2016-09-05T08:45:27.965608 | 2015-11-16T19:08:34 | 2015-11-16T19:08:34 | 42,883,543 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,609 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.4.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "10";
object p;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 2 -2 0 0 0 0];
internalField nonuniform List<scalar>
400
(
4.81401e-08
-0.000119257
-0.00031494
-0.0010134
-0.00244824
-0.00452359
-0.00685669
-0.00905003
-0.0108183
-0.0120212
-0.0125376
-0.0122588
-0.0111102
-0.00903169
-0.00599794
-0.00213848
0.00217985
0.00612848
0.00866615
0.00940853
0.000189831
-2.01886e-05
-0.000489237
-0.00157037
-0.00334065
-0.00558676
-0.00792738
-0.0100444
-0.0117596
-0.0129137
-0.0134096
-0.0131931
-0.0122127
-0.0103705
-0.0076409
-0.00407074
7.15716e-05
0.00414985
0.00705825
0.00824211
0.000122873
-0.00035066
-0.00131047
-0.00293969
-0.00515752
-0.00760074
-0.0099246
-0.0119584
-0.0135723
-0.0146014
-0.0150211
-0.01481
-0.0139431
-0.01238
-0.0100788
-0.00703056
-0.00331883
0.000706572
0.00400068
0.00564368
-0.000586905
-0.0013437
-0.00281462
-0.00499424
-0.00756417
-0.0100974
-0.0123339
-0.0141327
-0.0154194
-0.0162118
-0.0165137
-0.0163089
-0.0155795
-0.014306
-0.012462
-0.0100172
-0.00695073
-0.00331457
5.37376e-05
0.00187204
-0.00206456
-0.0030443
-0.00487759
-0.00738919
-0.0100507
-0.0124396
-0.0143966
-0.0158919
-0.0169336
-0.0175562
-0.01777
-0.0175752
-0.0169673
-0.0159372
-0.0144717
-0.0125501
-0.0101402
-0.00713823
-0.00402607
-0.00225189
-0.00415637
-0.0052064
-0.00716851
-0.0097238
-0.0122413
-0.0143604
-0.0160221
-0.0172636
-0.0181303
-0.0186472
-0.0188213
-0.0186564
-0.0181516
-0.0173079
-0.0161242
-0.0145967
-0.0127381
-0.0103843
-0.00781007
-0.00613524
-0.0064085
-0.00743422
-0.00934349
-0.0117572
-0.0140191
-0.0158556
-0.0172669
-0.0183266
-0.019075
-0.0195287
-0.0196909
-0.0195624
-0.0191429
-0.0184399
-0.0174649
-0.016214
-0.0147594
-0.0129443
-0.0109409
-0.00944663
-0.0084245
-0.00936392
-0.0111358
-0.0133542
-0.0153595
-0.0169579
-0.0181861
-0.019121
-0.0197891
-0.0202012
-0.0203586
-0.0202617
-0.0199112
-0.0193133
-0.0184926
-0.017429
-0.0162586
-0.0148295
-0.0133405
-0.0120347
-0.00991961
-0.0107927
-0.0124148
-0.014461
-0.0162685
-0.0176999
-0.0188088
-0.0196629
-0.0202785
-0.0206629
-0.0208171
-0.0207421
-0.020441
-0.0199133
-0.0192014
-0.0182464
-0.0172837
-0.0160886
-0.0149725
-0.0138617
-0.0108089
-0.0115986
-0.0131161
-0.0150531
-0.0167448
-0.0180899
-0.01914
-0.0199536
-0.0205421
-0.0209117
-0.0210642
-0.0210005
-0.0207282
-0.0202334
-0.0195916
-0.0186648
-0.0178614
-0.0167262
-0.0159342
-0.0149119
-0.01104
-0.0117891
-0.0132429
-0.0151262
-0.0167905
-0.0181332
-0.0191841
-0.019995
-0.0205802
-0.0209474
-0.0211002
-0.0210363
-0.0207713
-0.0202752
-0.0196553
-0.0187006
-0.017982
-0.0167635
-0.0162805
-0.0151736
-0.0106312
-0.011373
-0.0128034
-0.0146848
-0.0164073
-0.0178202
-0.0189298
-0.0197788
-0.0203889
-0.0207689
-0.0209254
-0.0208527
-0.0205693
-0.0200488
-0.0193719
-0.0183974
-0.0175731
-0.016293
-0.0160178
-0.0146486
-0.009725
-0.0104638
-0.0118797
-0.0137519
-0.0156005
-0.017145
-0.0183689
-0.0193012
-0.0199682
-0.0203784
-0.0205435
-0.0204523
-0.0201271
-0.0195418
-0.0187571
-0.0177042
-0.0166729
-0.0153482
-0.0150967
-0.0134346
-0.00848437
-0.0091768
-0.0105457
-0.0123793
-0.0143523
-0.0160753
-0.0174708
-0.0185403
-0.0193053
-0.0197703
-0.0199527
-0.0198376
-0.0194452
-0.0187529
-0.0178099
-0.0165895
-0.015314
-0.013903
-0.0135791
-0.0117224
-0.00715658
-0.00771435
-0.00892598
-0.0106562
-0.0126781
-0.0145895
-0.0162094
-0.017477
-0.0183926
-0.0189473
-0.0191607
-0.0190173
-0.0185325
-0.0176905
-0.0165342
-0.015062
-0.0135268
-0.0119532
-0.011535
-0.00954993
-0.0059563
-0.00622276
-0.00713927
-0.00865279
-0.0106189
-0.0126791
-0.0145569
-0.0160761
-0.0171979
-0.0178876
-0.0181535
-0.0179859
-0.0173985
-0.0163819
-0.0149749
-0.0132037
-0.0113595
-0.00951576
-0.00892403
-0.00654906
-0.00514154
-0.0049854
-0.00543019
-0.00656617
-0.00835119
-0.0104616
-0.0125669
-0.0143601
-0.0157335
-0.0166108
-0.0169838
-0.0168384
-0.0161759
-0.0149914
-0.0133267
-0.0112245
-0.0089565
-0.00660923
-0.00536059
-0.00118659
-0.00461507
-0.00396912
-0.0038841
-0.00457034
-0.00612076
-0.00822567
-0.0104861
-0.0124955
-0.0140867
-0.0151556
-0.0156602
-0.015577
-0.0149122
-0.0136552
-0.011804
-0.0093676
-0.00649064
-0.0031433
0.000111632
0.00922889
-0.00571881
-0.00374725
-0.00295476
-0.00318615
-0.00452707
-0.00662512
-0.00897977
-0.0111673
-0.0129262
-0.01415
-0.0147712
-0.0147829
-0.0141404
-0.012819
-0.0107661
-0.00788884
-0.00406752
0.0011607
0.00818865
0.0251428
-0.000947395
0.000676638
-0.000243921
-0.00156417
-0.00333469
-0.00559505
-0.00804208
-0.0103763
-0.0122599
-0.0135839
-0.014243
-0.0142511
-0.0135407
-0.0121544
-0.00989331
-0.00660802
-0.00137332
0.00645676
0.0180019
0.0367902
)
;
boundaryField
{
movingWall
{
type zeroGradient;
}
fixedWalls
{
type zeroGradient;
}
frontAndBack
{
type empty;
}
}
// ************************************************************************* //
| [
"brennankharris@gmail.com"
] | brennankharris@gmail.com | |
2fdb1b92b9cc675ec52ae3307df6a2d463eb3fa6 | 763159c1308c14447b389209244645c7b638ccb5 | /sstd_lua/source/lua_linit.cpp | c54bfc9ffd39f530cbc8a2d5a5f615f1d45c5255 | [] | no_license | 15831944/sstd_library | 9f53791df831724b02f7e86988fbd9a3c146e6b6 | 10c2ec1db09417c6d3217a37462db5bbf1a6fa5c | refs/heads/master | 2022-03-09T06:50:09.977767 | 2019-07-20T03:10:51 | 2019-07-20T03:10:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,734 | cpp | /*
** $Id: linit.c,v 1.39.1.1 2017/04/19 17:20:42 roberto Exp $
** Initialization of libraries for lua.c and other clients
** See Copyright Notice in lua.h
*/
#define linit_c
#define LUA_LIB
/*
** If you embed Lua in your program and need to open the standard
** libraries, call luaL_openlibs in your program. If you need a
** different set of libraries, copy this file to your project and edit
** it to suit your needs.
**
** You can also *preload* libraries, so that a later 'require' can
** open the library, which is already linked to the application.
** For that, do the following code:
**
** luaL_getsubtable(L, LUA_REGISTRYINDEX, LUA_PRELOAD_TABLE);
** lua_pushcfunction(L, luaopen_modname);
** lua_setfield(L, -2, modname);
** lua_pop(L, 1); // remove PRELOAD table
*/
#include "lprefix.h"
#include <stddef.h>
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
/*
** these libs are loaded by lua.c and are readily available to any Lua
** program
*/
static const luaL_Reg loadedlibs[] = {
{"_G", luaopen_base},
{LUA_LOADLIBNAME, luaopen_package},
{LUA_COLIBNAME, luaopen_coroutine},
{LUA_TABLIBNAME, luaopen_table},
{LUA_IOLIBNAME, luaopen_io},
{LUA_OSLIBNAME, luaopen_os},
{LUA_STRLIBNAME, luaopen_string},
{LUA_MATHLIBNAME, luaopen_math},
{LUA_UTF8LIBNAME, luaopen_utf8},
{LUA_DBLIBNAME, luaopen_debug},
#if defined(LUA_COMPAT_BITLIB)
{LUA_BITLIBNAME, luaopen_bit32},
#endif
{NULL, NULL}
};
LUALIB_API void luaL_openlibs (lua_State *L) {
const luaL_Reg *lib;
/* "require" functions from 'loadedlibs' and set results to global table */
for (lib = loadedlibs; lib->func; lib++) {
luaL_requiref(L, lib->name, lib->func, 1);
lua_pop(L, 1); /* remove lib */
}
}
| [
"zhaixueqiang@hotmail.com"
] | zhaixueqiang@hotmail.com |
608a246a633c74565f202d0cbbbf85bf64e27763 | 55416919c2f53162d8667d9e6ee978520036b5fa | /src/main.cxx | 90f5368ca250070ad6013bb2e87519f3a86c8c7d | [] | no_license | gorobaum/gc1 | e4be0dddb9d3a7da937dfc04445e55695f411f2d | d1cb123249d022e7ddb91434887914dd90b7d8fc | refs/heads/master | 2020-11-26T21:00:51.185891 | 2014-09-27T16:52:33 | 2014-09-27T16:52:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 476 | cxx | #include <iostream>
#include <fstream>
#include "parser.h"
#include "automata.h"
#include "scenegenerator.h"
int main(int argc, char** argv) {
if (argc != 2) {
std::cout << "Dae precisa do arquivo com os roles\n";
} else {
Parser parser(argv[1]);
parser.parseFile();
Automata automata(parser.getAxiom(), parser.getRules(), parser.getIterations());
automata.run();
SceneGenerator scenegenerator(automata.getFinalState());
scenegenerator.run();
}
return 0;
} | [
"gorobaum@gmail.com"
] | gorobaum@gmail.com |
1d589670d035438174f54a81e472188634d6d178 | 19b3b5f451efeb34f0a14f189beb24959222f703 | /problems_B/p40/p33_B_Decoding.cpp | 7e0d34a7305850bfad3151771447dd95c6c4e6dc | [] | no_license | PabloTabilo/codeforces-challenge | 67d559b46577ad2379c719057f018c8bffba7f23 | b51a77fd27a829fdfc0685171ecf59dc21bc6735 | refs/heads/main | 2023-07-11T02:08:02.549800 | 2021-08-12T18:04:31 | 2021-08-12T18:04:31 | 368,192,312 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 704 | cpp | #include<iostream>
#include<string>
using namespace std;
int main(){
int n, i;
string s1;
cin>>n;
cin>>s1;
if(s1.size()<=2){
cout<<s1;
}else{
string res="";
i=n-2;
if(n%2!=0){
while(i>=1){
res+=s1[i];
i-=2;
}
i=0;
while(i<n){
res+=s1[i];
i+=2;
}
}else{
while(i>=0){
res+=s1[i];
i-=2;
}
i=1;
while(i<n){
res+=s1[i];
i+=2;
}
}
cout<<res;
}
cout<<endl;
return 0;
}
| [
"pablo.tabilo@ticnow.cl"
] | pablo.tabilo@ticnow.cl |
00ad621681093d044e583b0e360d0627e88f0dc3 | ca9a8dac9adab9925fde6b99b8f7dc155312b984 | /GranularTextureSynthesis/JuceLibraryCode/BinaryData.h | efaa5bf324b4cd8992a36372fc5c0a3e55b79cf1 | [] | no_license | rupschy/GranularTextureSynthesis | 0e9cd71d0dc4c799d0004d4c85542fce709d6ef5 | bd3b3a73869c3cf15df73d7da17a4fdb34462e46 | refs/heads/main | 2023-04-02T03:11:56.179546 | 2021-04-16T18:21:24 | 2021-04-16T18:21:24 | 342,366,410 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,782 | h | /* =========================================================================================
This is an auto-generated file: Any edits you make may be overwritten!
*/
#pragma once
namespace BinaryData
{
extern const char* knob_b_small_png;
const int knob_b_small_pngSize = 5457;
extern const char* knob_w_large_png;
const int knob_w_large_pngSize = 18715;
extern const char* bg_png;
const int bg_pngSize = 443232;
extern const char* bg_1_png;
const int bg_1_pngSize = 380080;
extern const char* airstrike3d_ttf;
const int airstrike3d_ttfSize = 62100;
extern const char* bg_jpg;
const int bg_jpgSize = 89197;
extern const char* test_bg_jpg;
const int test_bg_jpgSize = 356106;
// Number of elements in the namedResourceList and originalFileNames arrays.
const int namedResourceListSize = 7;
// Points to the start of a list of resource names.
extern const char* namedResourceList[];
// Points to the start of a list of resource filenames.
extern const char* originalFilenames[];
// If you provide the name of one of the binary resource variables above, this function will
// return the corresponding data and its size (or a null pointer if the name isn't found).
const char* getNamedResource (const char* resourceNameUTF8, int& dataSizeInBytes);
// If you provide the name of one of the binary resource variables above, this function will
// return the corresponding original, non-mangled filename (or a null pointer if the name isn't found).
const char* getNamedResourceOriginalFilename (const char* resourceNameUTF8);
}
| [
"john.rupsch@pop.belmont.edu"
] | john.rupsch@pop.belmont.edu |
08625d6948935132fdcb4904fc6fcbb1bd7fc757 | 9f16950a070174c4ad6419b6aa48e0b3fd34a09e | /users/marcel/veem-sound/thermalizer.cpp | 552aed18351a21cc66c233b538ce4eb2ed70a6c0 | [] | no_license | marcel303/framework | 594043fad6a261ce2f8e862f921aee1192712612 | 9459898c280223b853bf16d6e382a6f7c573e10e | refs/heads/master | 2023-05-14T02:30:51.063401 | 2023-05-07T07:57:12 | 2023-05-07T10:16:34 | 112,006,739 | 53 | 1 | null | 2020-01-13T18:48:32 | 2017-11-25T13:45:56 | C++ | UTF-8 | C++ | false | false | 4,111 | cpp | #include "framework.h"
#include "Noise.h"
#include "thermalizer.h"
#include <cmath>
const double kCelcius = 273.0;
Thermalizer::Thermalizer()
: thermalToView(true)
{
}
Thermalizer::~Thermalizer()
{
shut();
}
void Thermalizer::init(const int _size)
{
shut();
//
if (_size > 0)
{
size = _size;
thermalToView = Mat4x4(true)
.Scale(3, 6, 1)
.Translate(0, -kCelcius, 0)
.Translate(-size/2.f, 0, 0);
heat = new double[size];
bang = new double[size];
for (int i = 0; i < size; ++i)
{
heat[i] = kCelcius + 12.0;
bang[i] = 0.0;
}
}
}
void Thermalizer::shut()
{
delete [] heat;
heat = nullptr;
delete [] bang;
bang = nullptr;
size = 0;
}
void Thermalizer::applyHeat(const int index, const double _heat, const double dt)
{
if (index < 0 || index >= size)
return;
const double kRetainPerSecond = 0.7;
const double retain = std::pow(kRetainPerSecond, dt);
heat[index] = heat[index] * retain + _heat * (1.0 - retain);
}
double Thermalizer::sampleHeat(const int index) const
{
if (index < 0)
return heat[0];
else if (index > size - 1)
return heat[size -1];
else
return heat[index];
}
void Thermalizer::diffuseHeat(const double dt)
{
double * oldHeat = (double*)alloca(size * sizeof(double));
memcpy(oldHeat, heat, size * sizeof(double));
const double kRetainPerMS = 0.8;
const double retain = std::pow(kRetainPerMS, dt * 1000.0);
const double spread = (1.0 - retain) * 0.5;
for (int i = 0; i < size; ++i)
{
const double value = spread * oldHeat[i];
if (i > 0)
{
heat[i - 1] += value;
heat[i] -= value;
}
if (i < size - 1)
{
heat[i + 1] += value;
heat[i] -= value;
}
}
}
void Thermalizer::applyHeatAtViewPos(const float x, const float y, const float dt)
{
const Mat4x4 viewToThermal = thermalToView.CalcInv();
const Vec2 p = viewToThermal.Mul4(Vec2(x, y));
const int i = int(std::round(p[0]));
if (i >= 0 && i <= size - 1)
{
const float noiseX = i;
const float noiseY = framework.time * 1.f;
const float noise = scaled_octave_noise_2d(8, .5f, 1.f, 0.f, kCelcius + 12.0, noiseX, noiseY);
applyHeat(i, noise, dt);
}
}
void Thermalizer::tick(const float dt)
{
double * oldHeat = (double*)alloca(size * sizeof(double));
memcpy(oldHeat, heat, size * sizeof(double));
const bool doApplyHeat = mouse.isDown(BUTTON_LEFT) && false;
// apply heat
if (doApplyHeat)
{
applyHeatAtViewPos(mouse.x, mouse.y, dt);
for (int i = 0; i < 2; ++i)
{
const float noiseX = i;
const float noiseY = framework.time * .2f;
const float noise = scaled_octave_noise_2d(8, .5f, 1.f, kCelcius + 12.0, kCelcius + 72.0, noiseX, noiseY);
applyHeat(i, noise, dt);
}
for (int i = size - 2; i < size; ++i)
{
const float noiseX = i;
const float noiseY = framework.time * .3f;
const float noise = scaled_octave_noise_2d(8, .5f, 1.f, kCelcius + 12.0, kCelcius + 72.0, noiseX, noiseY);
applyHeat(i, noise, dt);
}
}
// diffuse
#if 0
diffuseHeat(dt);
#else
for (int i = 0; i < 10; ++i)
diffuseHeat(dt / 10.0);
#endif
const double decayPerSecond = 0.8;
const double decay = std::pow(decayPerSecond, dt);
for (int i = 0; i < size; ++i)
{
bang[i] *= decay;
const double heatOld = oldHeat[i];
const double heatNew = heat[i];
const int shift1 = int(std::floor(heatOld / 1.0));
const int shift2 = int(std::floor(heatNew / 1.0));
if (shift1 != shift2)
bang[i] = 1.0;
}
}
void Thermalizer::draw2d() const
{
gxPushMatrix();
{
gxMultMatrixf(thermalToView.m_v);
const float spacing = .03f;
hqBegin(HQ_FILLED_ROUNDED_RECTS);
{
for (int i = 0; i < size; ++i)
{
setLumif(std::abs(heat[i]));
hqFillRoundedRect(i + spacing, kCelcius, i + 1 - spacing * 2, heat[i], .25f);
}
}
hqEnd();
setColor(255, 127, 63);
pushBlend(BLEND_ALPHA);
hqBegin(HQ_FILLED_ROUNDED_RECTS);
{
for (int i = 0; i < size; ++i)
{
setAlphaf(bang[i]);
hqFillRoundedRect(i + spacing, kCelcius, i + 1 - spacing * 2, heat[i], .25f);
}
}
hqEnd();
popBlend();
}
gxPopMatrix();
}
| [
"marcel303@gmail.com"
] | marcel303@gmail.com |
3f6e82ecfb0755c13107d06a93ac4abad8a09627 | cb68eec0d3e4a4dd2a02bdf9eb7f62468a2704d4 | /Input Test/main.cpp | a3e3db9528732a608b4109c03542102d54b29592 | [] | no_license | zomawia/IntroToCPP | 3533317d0c8fc4b902c525f08591d85b1587bac4 | a2004e9ae99b5714832fd6ce3ba4387b00b11994 | refs/heads/master | 2020-04-18T10:27:03.285531 | 2017-01-31T23:48:49 | 2017-01-31T23:48:49 | 66,312,234 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 213 | cpp | // Problem 5
#include <iostream>
int main()
{
int i = 0;
float f = 0;
char ch = 'a';
std::cin >> i >> ch >> f;
std::cout << "i: " << i << "\nch: " << ch << "\nf: " << f << std::endl;
system("pause");
} | [
"zomawai.sailo@SEA-1A7525"
] | zomawai.sailo@SEA-1A7525 |
e6b6ff5f64bd57bd0709a9b330cb3555eba05d0d | d38bd5737e0de480cba23f139d3fe542dbd4de95 | /ThirdParty/Bullet/src/BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.cpp | cb8ad5a1dd9427a4136d07b841ec5b2dd502fd1b | [] | no_license | bmjoy/GameEngine | 56ddc007e0d22cc1fa50d3a56000929c1b6f54bc | 39b59b0e382d0010526b1a40487120e4a143f3c7 | refs/heads/master | 2020-11-23T22:21:51.998221 | 2019-12-16T05:17:22 | 2019-12-16T05:17:22 | 227,844,666 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,199 | cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2006 Erwin Coumans http://continuousphysics.com/Bullet/
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "BulletCollision/CollisionDispatch/btConvexConcaveCollisionAlgorithm.h"
#include "LinearMath/btQuickprof.h"
#include "BulletCollision/CollisionDispatch/btCollisionObject.h"
#include "BulletCollision/CollisionShapes/btMultiSphereShape.h"
#include "BulletCollision/BroadphaseCollision/btBroadphaseProxy.h"
#include "BulletCollision/CollisionShapes/btConcaveShape.h"
#include "BulletCollision/CollisionDispatch/btManifoldResult.h"
#include "BulletCollision/NarrowPhaseCollision/btRaycastCallback.h"
#include "BulletCollision/CollisionShapes/btTriangleShape.h"
#include "BulletCollision/CollisionShapes/btSphereShape.h"
#include "LinearMath/btIDebugDraw.h"
#include "BulletCollision/NarrowPhaseCollision/btSubSimplexConvexCast.h"
#include "BulletCollision/CollisionDispatch/btCollisionObjectWrapper.h"
btConvexConcaveCollisionAlgorithm::btConvexConcaveCollisionAlgorithm( const btCollisionAlgorithmConstructionInfo& ci, const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped)
: btActivatingCollisionAlgorithm(ci,body0Wrap,body1Wrap),
m_btConvexTriangleCallback(ci.m_dispatcher1,body0Wrap,body1Wrap,isSwapped),
m_isSwapped(isSwapped)
{
}
btConvexConcaveCollisionAlgorithm::~btConvexConcaveCollisionAlgorithm()
{
}
void btConvexConcaveCollisionAlgorithm::getAllContactManifolds(btManifoldArray& manifoldArray)
{
if (m_btConvexTriangleCallback.m_manifoldPtr)
{
manifoldArray.push_back(m_btConvexTriangleCallback.m_manifoldPtr);
}
}
btConvexTriangleCallback::btConvexTriangleCallback(btDispatcher* dispatcher,const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,bool isSwapped):
m_dispatcher(dispatcher),
m_dispatchInfoPtr(0)
{
m_convexBodyWrap = isSwapped? body1Wrap:body0Wrap;
m_triBodyWrap = isSwapped? body0Wrap:body1Wrap;
//
// create the manifold from the dispatcher 'manifold pool'
//
m_manifoldPtr = m_dispatcher->getNewManifold(m_convexBodyWrap->getCollisionObject(),m_triBodyWrap->getCollisionObject());
clearCache();
}
btConvexTriangleCallback::~btConvexTriangleCallback()
{
clearCache();
m_dispatcher->releaseManifold( m_manifoldPtr );
}
void btConvexTriangleCallback::clearCache()
{
m_dispatcher->clearManifold(m_manifoldPtr);
}
void btConvexTriangleCallback::processTriangle(btVector3* triangle,int
partId, int triangleIndex)
{
BT_PROFILE("btConvexTriangleCallback::processTriangle");
if (!TestTriangleAgainstAabb2(triangle, m_aabbMin, m_aabbMax))
{
return;
}
//just for debugging purposes
//printf("triangle %d",m_triangleCount++);
btCollisionAlgorithmConstructionInfo ci;
ci.m_dispatcher1 = m_dispatcher;
#if 0
///debug drawing of the overlapping triangles
if (m_dispatchInfoPtr && m_dispatchInfoPtr->m_debugDraw && (m_dispatchInfoPtr->m_debugDraw->getDebugMode() &btIDebugDraw::DBG_DrawWireframe ))
{
const btCollisionObject* ob = const_cast<btCollisionObject*>(m_triBodyWrap->getCollisionObject());
btVector3 color(1,1,0);
btTransform& tr = ob->getWorldTransform();
m_dispatchInfoPtr->m_debugDraw->drawLine(tr(triangle[0]),tr(triangle[1]),color);
m_dispatchInfoPtr->m_debugDraw->drawLine(tr(triangle[1]),tr(triangle[2]),color);
m_dispatchInfoPtr->m_debugDraw->drawLine(tr(triangle[2]),tr(triangle[0]),color);
}
#endif
if (m_convexBodyWrap->getCollisionShape()->isConvex())
{
btTriangleShape tm(triangle[0],triangle[1],triangle[2]);
tm.setMargin(m_collisionMarginTriangle);
btCollisionObjectWrapper triObWrap(m_triBodyWrap,&tm,m_triBodyWrap->getCollisionObject(),m_triBodyWrap->getWorldTransform(),partId,triangleIndex);//correct transform?
btCollisionAlgorithm* colAlgo = 0;
if (m_resultOut->m_closestPointDistanceThreshold > 0)
{
colAlgo = ci.m_dispatcher1->findAlgorithm(m_convexBodyWrap, &triObWrap, 0, BT_CLOSEST_POINT_ALGORITHMS);
}
else
{
colAlgo = ci.m_dispatcher1->findAlgorithm(m_convexBodyWrap, &triObWrap, m_manifoldPtr, BT_CONTACT_POINT_ALGORITHMS);
}
const btCollisionObjectWrapper* tmpWrap = 0;
if (m_resultOut->getBody0Internal() == m_triBodyWrap->getCollisionObject())
{
tmpWrap = m_resultOut->getBody0Wrap();
m_resultOut->setBody0Wrap(&triObWrap);
m_resultOut->setShapeIdentifiersA(partId,triangleIndex);
}
else
{
tmpWrap = m_resultOut->getBody1Wrap();
m_resultOut->setBody1Wrap(&triObWrap);
m_resultOut->setShapeIdentifiersB(partId,triangleIndex);
}
colAlgo->processCollision(m_convexBodyWrap,&triObWrap,*m_dispatchInfoPtr,m_resultOut);
if (m_resultOut->getBody0Internal() == m_triBodyWrap->getCollisionObject())
{
m_resultOut->setBody0Wrap(tmpWrap);
} else
{
m_resultOut->setBody1Wrap(tmpWrap);
}
colAlgo->~btCollisionAlgorithm();
ci.m_dispatcher1->freeCollisionAlgorithm(colAlgo);
}
}
void btConvexTriangleCallback::setTimeStepAndCounters(btScalar collisionMarginTriangle,const btDispatcherInfo& dispatchInfo,const btCollisionObjectWrapper* convexBodyWrap, const btCollisionObjectWrapper* triBodyWrap, btManifoldResult* resultOut)
{
m_convexBodyWrap = convexBodyWrap;
m_triBodyWrap = triBodyWrap;
m_dispatchInfoPtr = &dispatchInfo;
m_collisionMarginTriangle = collisionMarginTriangle;
m_resultOut = resultOut;
//recalc aabbs
btTransform convexInTriangleSpace;
convexInTriangleSpace = m_triBodyWrap->getWorldTransform().inverse() * m_convexBodyWrap->getWorldTransform();
const btCollisionShape* convexShape = static_cast<const btCollisionShape*>(m_convexBodyWrap->getCollisionShape());
//CollisionShape* triangleShape = static_cast<btCollisionShape*>(triBody->m_collisionShape);
convexShape->getAabb(convexInTriangleSpace,m_aabbMin,m_aabbMax);
btScalar extraMargin = collisionMarginTriangle+ resultOut->m_closestPointDistanceThreshold;
btVector3 extra(extraMargin,extraMargin,extraMargin);
m_aabbMax += extra;
m_aabbMin -= extra;
}
void btConvexConcaveCollisionAlgorithm::clearCache()
{
m_btConvexTriangleCallback.clearCache();
}
void btConvexConcaveCollisionAlgorithm::processCollision (const btCollisionObjectWrapper* body0Wrap,const btCollisionObjectWrapper* body1Wrap,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
BT_PROFILE("btConvexConcaveCollisionAlgorithm::processCollision");
const btCollisionObjectWrapper* convexBodyWrap = m_isSwapped ? body1Wrap : body0Wrap;
const btCollisionObjectWrapper* triBodyWrap = m_isSwapped ? body0Wrap : body1Wrap;
if (triBodyWrap->getCollisionShape()->isConcave())
{
const btConcaveShape* concaveShape = static_cast<const btConcaveShape*>( triBodyWrap->getCollisionShape());
if (convexBodyWrap->getCollisionShape()->isConvex())
{
btScalar collisionMarginTriangle = concaveShape->getMargin();
resultOut->setPersistentManifold(m_btConvexTriangleCallback.m_manifoldPtr);
m_btConvexTriangleCallback.setTimeStepAndCounters(collisionMarginTriangle,dispatchInfo,convexBodyWrap,triBodyWrap,resultOut);
m_btConvexTriangleCallback.m_manifoldPtr->setBodies(convexBodyWrap->getCollisionObject(),triBodyWrap->getCollisionObject());
concaveShape->processAllTriangles( &m_btConvexTriangleCallback,m_btConvexTriangleCallback.getAabbMin(),m_btConvexTriangleCallback.getAabbMax());
resultOut->refreshContactPoints();
m_btConvexTriangleCallback.clearWrapperData();
}
}
}
btScalar btConvexConcaveCollisionAlgorithm::calculateTimeOfImpact(btCollisionObject* body0,btCollisionObject* body1,const btDispatcherInfo& dispatchInfo,btManifoldResult* resultOut)
{
(void)resultOut;
(void)dispatchInfo;
btCollisionObject* convexbody = m_isSwapped ? body1 : body0;
btCollisionObject* triBody = m_isSwapped ? body0 : body1;
//quick approximation using raycast, todo: hook up to the continuous collision detection (one of the btConvexCast)
//only perform CCD above a certain threshold, this prevents blocking on the long run
//because object in a blocked ccd state (hitfraction<1) get their linear velocity halved each frame...
btScalar squareMot0 = (convexbody->getInterpolationWorldTransform().getOrigin() - convexbody->getWorldTransform().getOrigin()).length2();
if (squareMot0 < convexbody->getCcdSquareMotionThreshold())
{
return btScalar(1.);
}
//const btVector3& from = convexbody->m_worldTransform.getOrigin();
//btVector3 to = convexbody->m_interpolationWorldTransform.getOrigin();
//todo: only do if the motion exceeds the 'radius'
btTransform triInv = triBody->getWorldTransform().inverse();
btTransform convexFromLocal = triInv * convexbody->getWorldTransform();
btTransform convexToLocal = triInv * convexbody->getInterpolationWorldTransform();
struct LocalTriangleSphereCastCallback : public btTriangleCallback
{
btTransform m_ccdSphereFromTrans;
btTransform m_ccdSphereToTrans;
btTransform m_meshTransform;
btScalar m_ccdSphereRadius;
btScalar m_hitFraction;
LocalTriangleSphereCastCallback(const btTransform& from,const btTransform& to,btScalar ccdSphereRadius,btScalar hitFraction)
:m_ccdSphereFromTrans(from),
m_ccdSphereToTrans(to),
m_ccdSphereRadius(ccdSphereRadius),
m_hitFraction(hitFraction)
{
}
virtual void processTriangle(btVector3* triangle, int partId, int triangleIndex)
{
BT_PROFILE("processTriangle");
(void)partId;
(void)triangleIndex;
//do a swept sphere for now
btTransform ident;
ident.setIdentity();
btConvexCast::CastResult castResult;
castResult.m_fraction = m_hitFraction;
btSphereShape pointShape(m_ccdSphereRadius);
btTriangleShape triShape(triangle[0],triangle[1],triangle[2]);
btVoronoiSimplexSolver simplexSolver;
btSubsimplexConvexCast convexCaster(&pointShape,&triShape,&simplexSolver);
//GjkConvexCast convexCaster(&pointShape,convexShape,&simplexSolver);
//ContinuousConvexCollision convexCaster(&pointShape,convexShape,&simplexSolver,0);
//local space?
if (convexCaster.calcTimeOfImpact(m_ccdSphereFromTrans,m_ccdSphereToTrans,
ident,ident,castResult))
{
if (m_hitFraction > castResult.m_fraction)
m_hitFraction = castResult.m_fraction;
}
}
};
if (triBody->getCollisionShape()->isConcave())
{
btVector3 rayAabbMin = convexFromLocal.getOrigin();
rayAabbMin.setMin(convexToLocal.getOrigin());
btVector3 rayAabbMax = convexFromLocal.getOrigin();
rayAabbMax.setMax(convexToLocal.getOrigin());
btScalar ccdRadius0 = convexbody->getCcdSweptSphereRadius();
rayAabbMin -= btVector3(ccdRadius0,ccdRadius0,ccdRadius0);
rayAabbMax += btVector3(ccdRadius0,ccdRadius0,ccdRadius0);
btScalar curHitFraction = btScalar(1.); //is this available?
LocalTriangleSphereCastCallback raycastCallback(convexFromLocal,convexToLocal,
convexbody->getCcdSweptSphereRadius(),curHitFraction);
raycastCallback.m_hitFraction = convexbody->getHitFraction();
btCollisionObject* concavebody = triBody;
btConcaveShape* triangleMesh = (btConcaveShape*) concavebody->getCollisionShape();
if (triangleMesh)
{
triangleMesh->processAllTriangles(&raycastCallback,rayAabbMin,rayAabbMax);
}
if (raycastCallback.m_hitFraction < convexbody->getHitFraction())
{
convexbody->setHitFraction( raycastCallback.m_hitFraction);
return raycastCallback.m_hitFraction;
}
}
return btScalar(1.);
}
| [
"ironmandev@gmail.com"
] | ironmandev@gmail.com |
8918c9156297e32f5a911da6abf54d36b1e786b7 | 7415cc42241ea7c553858fd2018d2f479f356984 | /1_7_For_Arrays/Task3/main.cpp | c35d8420acefb0296f441a753039e2b1856fedb8 | [] | no_license | nkolesnikov999/IntroCPP | f1bc6b800521ecffd5fc1e00925bada7ffc15c67 | 0b70a742288248ce512abddf65d636c755ff7ce2 | refs/heads/master | 2021-01-19T00:27:39.279714 | 2016-09-10T17:22:52 | 2016-09-10T17:22:52 | 67,435,540 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 852 | cpp | /*
Выведите все элементы массива с четными индексами (то есть A[0], A[2], A[4], ...).
Формат входных данных
В первой строке вводится количество элементов в массиве. Во второй строке вводятся элементы массива.
Формат выходных данных
Выведите ответ на задачу.
Sample Input:
5
1 2 3 4 5
Sample Output:
1 3 5
*/
#include <iostream>
#include <vector>
using namespace std;
int main() {
int n;
cin >> n;
vector <int> a;
//считывание
for (int i = 0; i < n; i++) {
int temp;
cin >> temp;
a.push_back(temp);
}
for (int i = 0; i < n; i++) {
if (i % 2 == 0) {
cout << a[i] << " ";
}
}
return 0;
} | [
"nkolesnikov@mail.ru"
] | nkolesnikov@mail.ru |
f2efe13729fe7a0aaf43c9920362d78d2200e059 | 7f2b581ba5bf174e3cd7665d65a9c66c586f3222 | /src/main.cpp | 05760b87ea441dbd743218801c46356139694a67 | [] | no_license | zsuzuki/StickLED | d7fef5760401c0f24acca339f39ebca4d41f54a9 | 74dd6179e12c791afb8008aba0dfe2390dec3511 | refs/heads/master | 2023-07-16T10:52:50.209145 | 2021-09-05T21:51:38 | 2021-09-05T21:51:38 | 394,878,222 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,087 | cpp | #include <Arduino.h>
#include <FastLED.h>
#include <vector>
#include <M5GFX.h>
#include <I2C_BM8563.h>
#include <I2C_AXP192.h>
#include <WiFi.h>
#include <array>
namespace
{
constexpr int BM8563_I2C_SDA = 21;
constexpr int BM8563_I2C_SCL = 22;
constexpr int DIN = 26;
constexpr int NB_LED = 12;
using DateType = I2C_BM8563_DateTypeDef;
using TimeType = I2C_BM8563_TimeTypeDef;
M5GFX display;
I2C_BM8563 rtc(I2C_BM8563_DEFAULT_ADDRESS, Wire1);
I2C_AXP192 axp(I2C_AXP192_DEFAULT_ADDRESS, Wire1);
CRGB leds[NB_LED];
// ボタン判定クラス
class Btn
{
int pin;
bool on;
public:
Btn(int p) : pin(p) {}
void init()
{
pinMode(pin, INPUT_PULLUP);
}
void update()
{
on = !digitalRead(pin);
}
bool get() const { return on; }
};
// 色情報
struct ColorInfo
{
const char *caption; // 色名
CRGB ledColor; // LED側に光らせる色
int color; // LCD側に表示される色
int textColor; // LCD側に表示される色名の文字色
};
std::vector<ColorInfo> colorList = {
{"赤", CRGB::Red, TFT_RED, TFT_WHITE},
{"青", CRGB::Blue, TFT_BLUE, TFT_WHITE},
{"緑", CRGB::Green, TFT_GREEN, TFT_BLACK},
{"オレンジ", CRGB::Orange, TFT_ORANGE, TFT_WHITE},
{"紫", CRGB::Purple, TFT_PURPLE, TFT_WHITE},
{"黄", CRGB::Yellow, TFT_YELLOW, TFT_BLACK},
{"白", CRGB::White, TFT_WHITE, TFT_BLACK},
{"オリーブ", CRGB::Olive, TFT_OLIVE, TFT_WHITE},
{"新緑", CRGB::ForestGreen, TFT_GREENYELLOW, TFT_BLACK},
};
int colorIndex;
int lightIndex;
uint8_t lightLevel;
TimeType nowTime;
Btn buttonA(37);
Btn buttonB(39);
std::array<uint8_t, 7> lvList = {255, 128, 64, 32, 16, 8, 0};
// 操作モード
struct ModeInfo
{
using function = void (*)();
using renderFunc = void (*)(const ColorInfo &);
const char *caption;
function func;
renderFunc render;
};
void changeLightLevel();
void setupDateTime();
void selectTimer();
void renderMain(const ColorInfo &);
void renderTimer(const ColorInfo &);
std::vector<ModeInfo> modeList = {
{"点灯", []()
{
colorIndex = (colorIndex + 1) % colorList.size();
},
renderMain},
{"光量", changeLightLevel, renderMain},
{"消灯", selectTimer, renderTimer},
{"時刻", setupDateTime, renderMain},
};
int mode;
// タイマー設定
int timerIndex;
bool timerOn;
constexpr int operator"" _MIN(unsigned long long n) { return n * 60; }
constexpr int operator"" _HOUR(unsigned long long n) { return n * 60_MIN; }
std::array<int, 6> timerList = {0, 5, 30_MIN, 1_HOUR, 1_HOUR + 30_MIN, 2_HOUR};
TimeType timerTarget;
// タイマー選択
void selectTimer()
{
timerIndex = (timerIndex + 1) % timerList.size();
int remainSec = timerList[timerIndex];
if (remainSec == 0)
{
// timer off
timerOn = false;
}
else
{
// timer on
int sec = nowTime.seconds + remainSec;
timerTarget.seconds = sec % 60;
int min = nowTime.minutes + sec / 60;
timerTarget.minutes = min % 60;
int hour = nowTime.hours + min / 60;
timerTarget.hours = hour % 24;
timerOn = true;
// Serial.printf("target: %02d:%02d.%02d\n", timerTarget.hours, timerTarget.minutes, timerTarget.seconds);
}
}
// タイマー情報表示
void renderTimer([[maybe_unused]] const ColorInfo &info)
{
for (size_t i = 0; i < timerList.size(); i++)
{
int color = i == timerIndex ? TFT_LIGHTGRAY : TFT_WHITE;
display.fillRoundRect(10 + i * 20, 25, 18, 20, 2, color);
}
display.setTextColor(TFT_WHITE, TFT_BLACK);
if (timerOn)
{
char buff[64];
snprintf(buff, sizeof(buff), "Tgt:%02d:%02d.%02d\n", timerTarget.hours, timerTarget.minutes, timerTarget.seconds);
display.drawString(buff, 10, 50);
}
else
{
display.drawString("タイマー無し", 10, 50);
}
}
// タイマーチェック&電源OFF
void checkTimer()
{
if (timerOn == false)
{
return;
}
bool off = false;
if (timerTarget.hours < nowTime.hours)
off = true;
else if (timerTarget.hours == nowTime.hours)
{
if (timerTarget.minutes < nowTime.minutes)
off = true;
else if (timerTarget.minutes == nowTime.minutes)
{
if (timerTarget.seconds <= nowTime.seconds)
off = true;
}
}
if (off)
{
axp.powerOff();
}
}
// 明るさ変更
void changeLightLevel()
{
lightIndex = (lightIndex + 1) % lvList.size();
lightLevel = lvList[lightIndex];
// Serial.printf("light level: %hhu\n", lightLevel);
}
// 通常描画(LCD)
void renderMain(const ColorInfo &info)
{
display.fillRoundRect(20, 30, 120, 40, 8, info.color);
display.fillRect(120, 30, 10, 40, TFT_BLACK);
display.setTextColor(info.textColor, info.color);
for (int i = lvList.size() - lightIndex - 1; i > 0; i--)
{
display.fillRect(121, 72 - i * 7, 8, 5, info.color);
}
// float length = (float)lightIndex / (float)(lvList.size() - 1) * 40.0f;
// display.fillRect(121, 30, 8, length, TFT_BLACK);
if (lightLevel > 0)
{
display.drawCenterString(info.caption, 80, 40);
}
else
{
display.drawCenterString("消灯", 80, 40);
}
}
// バッテリー残量表示
void dispBattery(bool needUpdate = false)
{
float bv = axp.getBatteryVoltage();
constexpr float vLow = 3000.0f;
constexpr float vHigh = 4000.0f;
constexpr float vDan = (vHigh - vLow) * 0.15f + vLow;
bool onCharge = axp.getBatteryDischargeCurrent() == 0.0f;
int vCol = TFT_WHITE;
if (onCharge)
vCol = bv > vHigh ? TFT_GREEN : TFT_YELLOW;
else if (bv < vDan)
vCol = TFT_RED;
bv = std::max(bv - vLow, 0.0f);
bv = std::min(bv / (vHigh - vLow), 1.0f);
constexpr int Height = 45;
auto vHeight = (int)(bv * Height);
//
static int oldH = 0;
if (needUpdate || vHeight != oldH)
{
display.fillRoundRect(145, 75 - Height, 12, Height, 2, TFT_BLACK);
display.fillRoundRect(145, 75 - vHeight, 12, vHeight, 2, vCol);
oldH = vHeight;
}
}
// 時刻合わせ
void setupDateTime()
{
const char *ssid = "********";
const char *password = "********";
const char *ntpServer = "ntp.jst.mfeed.ad.jp";
WiFi.begin(ssid, password);
Serial.printf("Wifi[%s] setup:", ssid);
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("done.");
// get time from NTP server(UTC+9)
configTime(9 * 3600, 0, ntpServer);
// Get local time
struct tm timeInfo;
if (getLocalTime(&timeInfo))
{
// Set RTC time
TimeType TimeStruct;
TimeStruct.hours = timeInfo.tm_hour;
TimeStruct.minutes = timeInfo.tm_min;
TimeStruct.seconds = timeInfo.tm_sec;
rtc.setTime(&TimeStruct);
DateType DateStruct;
DateStruct.weekDay = timeInfo.tm_wday;
DateStruct.month = timeInfo.tm_mon + 1;
DateStruct.date = timeInfo.tm_mday;
DateStruct.year = timeInfo.tm_year + 1900;
rtc.setDate(&DateStruct);
Serial.println("time setting success");
}
// disconnect WiFi
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
Serial.println("time setting done.");
}
// 時刻表示
void dispTime(bool needUpdate = false)
{
static TimeType oldT{};
rtc.getTime(&nowTime);
if (needUpdate == false)
{
if (oldT.hours == nowTime.hours && oldT.minutes == nowTime.minutes && oldT.seconds == nowTime.seconds)
{
return;
}
}
char buff[32];
snprintf(buff, sizeof(buff), "%02d:%02d.%02d", nowTime.hours, nowTime.minutes, nowTime.seconds);
display.setTextColor(TFT_WHITE, TFT_DARKGRAY);
display.drawString(buff, 5, 0);
oldT = nowTime;
}
}
// セットアップ
void setup()
{
setCpuFrequencyMhz(160);
Serial.begin(115200);
display.begin();
display.setRotation(1);
display.setFont(&fonts::lgfxJapanGothic_20);
Wire1.begin(BM8563_I2C_SDA, BM8563_I2C_SCL);
rtc.begin();
rtc.getTime(&nowTime);
I2C_AXP192_InitDef axpInitDef{};
axpInitDef.EXTEN = true;
axpInitDef.BACKUP = true;
axpInitDef.DCDC1 = 3300;
axpInitDef.DCDC2 = 0;
axpInitDef.DCDC3 = 0;
axpInitDef.LDO2 = 3000;
axpInitDef.LDO3 = 3000;
axpInitDef.GPIO0 = 2800;
axpInitDef.GPIO1 = -1;
axpInitDef.GPIO2 = -1;
axpInitDef.GPIO3 = -1;
axpInitDef.GPIO4 = -1;
axp.begin(axpInitDef);
FastLED.addLeds<WS2812B, DIN, GRB>(leds, NB_LED).setCorrection(TypicalLEDStrip);
FastLED.setBrightness(100);
colorIndex = 0;
for (auto &led : leds)
{
led = colorList[colorIndex].ledColor;
}
mode = 0;
lightLevel = 255;
timerIndex = 0;
timerOn = false;
buttonA.init();
buttonB.init();
display.startWrite();
display.fillScreen(TFT_BLACK);
display.endWrite();
}
// ループ
void loop()
{
static bool needUpdate = true;
buttonA.update();
buttonB.update();
if (buttonA.get())
{
modeList[mode].func();
needUpdate = true;
}
if (buttonB.get())
{
mode = (mode + 1) % modeList.size();
needUpdate = true;
}
const auto &info = colorList[colorIndex];
leds[0] = info.ledColor;
if (lightLevel < 255)
{
leds[0].nscale8(lightLevel);
}
for (int i = NB_LED - 1; i > 0; i--)
{
leds[i] = leds[i - 1];
}
display.startWrite();
if (needUpdate)
{
display.fillScreen(TFT_BLACK);
modeList[mode].render(info);
display.setTextColor(TFT_WHITE, TFT_BLACK);
display.drawString(modeList[mode].caption, 98, 0);
}
dispBattery(needUpdate);
dispTime(needUpdate);
static bool tO = false;
if (needUpdate || tO != timerOn)
{
if (timerOn)
display.fillCircle(5, 30, 4, TFT_RED);
else
display.fillCircle(5, 30, 4, TFT_BLACK);
tO = timerOn;
}
needUpdate = false;
display.endWrite();
FastLED.show();
FastLED.delay(200);
checkTimer();
}
| [
"wave.suzuki.z@gmail.com"
] | wave.suzuki.z@gmail.com |
61ea0c8000d56e34fd8bb4b44ed15bf664b46824 | 33fd5786ddde55a705d74ce2ce909017e2535065 | /build/iOS/Debug/include/Fuse.Input.PointerMovedHandler.h | c6c30d85f1869e29b0109ae68a4c84f317dbc75f | [] | no_license | frpaulas/iphodfuse | 04cee30add8b50ea134eb5a83e355dce886a5d5a | e8886638c4466b3b0c6299da24156d4ee81c9112 | refs/heads/master | 2021-01-23T00:48:31.195577 | 2017-06-01T12:33:13 | 2017-06-01T12:33:13 | 92,842,106 | 3 | 3 | null | 2017-05-30T17:43:28 | 2017-05-30T14:33:26 | C++ | UTF-8 | C++ | false | false | 450 | h | // This file was generated based on '../../../../Library/Application Support/Fusetools/Packages/Fuse.Nodes/1.0.2/input/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Delegate.h>
namespace g{
namespace Fuse{
namespace Input{
// public delegate void PointerMovedHandler(object sender, Fuse.Input.PointerMovedArgs args) :2066
uDelegateType* PointerMovedHandler_typeof();
}}} // ::g::Fuse::Input
| [
"frpaulas@gmail.com"
] | frpaulas@gmail.com |
881ea7fbab372d1b6fb2a636def3dbd8bb0460f6 | e000dfb2e1ddfe62598da937d2e0d40d6efff61b | /venusmmi/app/Cosmos/ScreenLock/vapp_screen_lock_unlock_item_kit.cpp | b6b8d563e2ceb2e28f844581cc6609acf4dd9453 | [] | no_license | npnet/KJX_K7 | 9bc11e6cd1d0fa5996bb20cc6f669aa087bbf592 | 35dcd3de982792ae4d021e0e94ca6502d1ff876e | refs/heads/master | 2023-02-06T09:17:46.582670 | 2020-12-24T02:55:29 | 2020-12-24T02:55:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,525 | cpp | /*****************************************************************************
* Copyright Statement:
* --------------------
* This software is protected by Copyright and the information contained
* herein is confidential. The software may not be copied and the information
* contained herein may not be used or disclosed except with the written
* permission of MediaTek Inc. (C) 2010
*
* BY OPENING THIS FILE, BUYER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO BUYER 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 BUYER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. MEDIATEK SHALL ALSO
* NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE RELEASES MADE TO BUYER'S
* SPECIFICATION OR TO CONFORM TO A PARTICULAR STANDARD OR OPEN FORUM.
*
* BUYER'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 BUYER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* THE TRANSACTION CONTEMPLATED HEREUNDER SHALL BE CONSTRUED IN ACCORDANCE
* WITH THE LAWS OF THE STATE OF CALIFORNIA, USA, EXCLUDING ITS CONFLICT OF
* LAWS PRINCIPLES. ANY DISPUTES, CONTROVERSIES OR CLAIMS ARISING THEREOF AND
* RELATED THERETO SHALL BE SETTLED BY ARBITRATION IN SAN FRANCISCO, CA, UNDER
* THE RULES OF THE INTERNATIONAL CHAMBER OF COMMERCE (ICC).
*
*****************************************************************************/
/*****************************************************************************
*
* Filename:
* ---------
* vapp_screen_lock_unlock_item_kit.cpp
*
* Project:
* --------
* MAUI
*
* Description:
* ------------
* This file implements the unlock item kit.
*
* Author:
* -------
* -------
*
*============================================================================
* HISTORY
* Below this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
*------------------------------------------------------------------------------
* removed!
*
* removed!
* removed!
* removed!
*
* removed!
* removed!
* removed!
*
*------------------------------------------------------------------------------
* Upper this line, this part is controlled by PVCS VM. DO NOT MODIFY!!
*============================================================================
****************************************************************************/
#include "MMI_features.h"
/*****************************************************************************
* Include
*****************************************************************************/
// for __COSMOS_3D_SCREEN_LOCK__
#include "vapp_screen_lock_def.h"
#include "vapp_screen_lock_unlock_item_kit.h"
/*****************************************************************************
* Unlock Item Kit Class
*****************************************************************************/
VFX_IMPLEMENT_CLASS("VappScreenLockUnlockItemKit", VappScreenLockUnlockItemKit, VfxObject);
VappScreenLockUnlockItemKit::VappScreenLockUnlockItemKit() :
m_factory(NULL)
{
// Do nothing.
}
void VappScreenLockUnlockItemKit::onInit()
{
VFX_OBJ_CREATE(m_factory, VappScreenLockUnlockItemFactory, this);
}
void VappScreenLockUnlockItemKit::onDeinit()
{
if (m_factory)
{
VFX_OBJ_CLOSE(m_factory);
}
}
VappScreenLockUnlockItem *VappScreenLockUnlockItemKit::createUnlockItem(
const VappScreenLockUnlockItemTypeEnum id,
VfxObject *parentObj)
{
VFX_ASSERT(m_factory);
VappScreenLockUnlockItem *unlockItem = m_factory->createUnlockItem(id, parentObj);
if (!unlockItem)
{
return NULL;
}
return unlockItem;
}
VappScreenLockUnlockItemTypeEnum VappScreenLockUnlockItemKit::getUnlockItemId(
const VappScreenLockUnlockItemPos pos)
{
return m_factory->getUnlockItemId(pos);
}
| [
"3447782@qq.com"
] | 3447782@qq.com |
2a865f45eea1a1260c9892cb811df21e4e62ab83 | 618ff458ffbcfa4c66930d47667162b148bcb57a | /exe1/EpslonRestrito.cpp | 73e79eb653833e8ed396b83bd7a14ffd1585fd9e | [] | no_license | dsaleixo/TrabalhoInf628 | 351f9095b80a74eb5cdd35fc7348756f4265dcff | b132846c4fab416ad0759ca266f0ba17b17db694 | refs/heads/master | 2022-12-02T18:03:27.870502 | 2020-08-11T00:19:38 | 2020-08-11T00:19:38 | 278,403,853 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,899 | cpp | #include "EpslonRestrito.h"
EpslonRestrito::EpslonRestrito(string s, int p, string saida,bool otimizado) : MMO(s, p, saida) {
this->otimizado = otimizado;
}
void EpslonRestrito::rodar() {
this->model.setInicio(0);
this->model.setFim(this->model.Z_size);
double A1, A2, B1, B2;
int i, f;
model.CriaVariavel();
model.setFuncaoObj(model.getFuncaoObjCusto());
model.geraRestricoesbase();
model.finalizarestricoes();
model.resolve();
if (!model.tem_solucao())return;
A1 = model.getValorCusto();
f = this->model.buscaBinaria(this->model.getValorRaio() + 1);
model.reset();
if (this->otimizado) {
i = this->model.buscaBinaria(this->model.Menores[this->model.dados.p]);
this->model.setInicio(i);
int aux = this->model.buscaBinaria(this->model.maiorD()) + 1;
if (f < aux)this->model.setFim(f);
else this->model.setFim(aux);
}
model.CriaVariavel();
model.setFuncaoObj(model.getFuncaoObjRaio());
model.geraRestricoesbase();
model.finalizarestricoes();
model.resolve();
if (!model.tem_solucao())return;
B2 = model.getValorRaio();
i = this->model.buscaBinaria(B2);
model.reset();
if (this->otimizado) {
this->model.setInicio(i);
this->model.setFim(f);
}
model.CriaVariavel();
model.setFuncaoObj(model.getFuncaoObjRaio());
model.geraRestricoesbase();
model.addRestricao(model.getFuncaoObjCusto() <= A1);
model.finalizarestricoes();
model.resolve();
if (!model.tem_solucao())return;
this->salva_resultado();
A2 = model.getValorRaio();
model.reset();
if (this->otimizado) {
this->model.setInicio(i);
this->model.setFim(f);
}
model.CriaVariavel();
model.setFuncaoObj(model.getFuncaoObjCusto());
model.geraRestricoesbase();
model.addRestricao(model.getFuncaoObjRaio() <= B2);
model.finalizarestricoes();
model.resolve();
if (!model.tem_solucao())return;
this->salva_resultado();
B1 = model.getValorCusto();
model.reset();
rodar(A1, A2, B1, B2);
}
void EpslonRestrito::rodar(double A1, double A2, double B1, double B2) {
while (!(abs(A1 - B1) < 0.5 && abs(B2 - A2) < 0.5)) {
if (this->otimizado) {
this->model.setInicio(this->model.buscaBinaria(B2));
this->model.setFim(this->model.buscaBinaria(A2) + 1);
}
int C1;
model.CriaVariavel();
model.setFuncaoObj(model.getFuncaoObjCusto());
model.geraRestricoesbase();
model.addRestricao(model.getFuncaoObjRaio() <= A2-0.5);
model.finalizarestricoes();
model.resolve();
if (!model.tem_solucao())return;
C1 = model.getValorCusto();
model.reset();
int C2;
model.CriaVariavel();
model.setFuncaoObj(model.getFuncaoObjRaio());
model.geraRestricoesbase();
model.addRestricao(model.getFuncaoObjCusto() <= C1);
model.finalizarestricoes();
model.resolve();
if (!model.tem_solucao())return;
this->salva_resultado();
C2 = model.getValorRaio();
model.reset();
//cout<<"C " << C1 << " " << C2 << endl;
A1 = C1;
A2 = C2;
}
} | [
"david_leixo@hotmail.com"
] | david_leixo@hotmail.com |
307e87698d4769dc35cf07f6a3236e522099e235 | 3ff1fe3888e34cd3576d91319bf0f08ca955940f | /cms/src/v20190321/model/UserKeyword.cpp | ba437240b2292f161414086d3ddb9dc2f9da7917 | [
"Apache-2.0"
] | permissive | TencentCloud/tencentcloud-sdk-cpp | 9f5df8220eaaf72f7eaee07b2ede94f89313651f | 42a76b812b81d1b52ec6a217fafc8faa135e06ca | refs/heads/master | 2023-08-30T03:22:45.269556 | 2023-08-30T00:45:39 | 2023-08-30T00:45:39 | 188,991,963 | 55 | 37 | Apache-2.0 | 2023-08-17T03:13:20 | 2019-05-28T08:56:08 | C++ | UTF-8 | C++ | false | false | 4,850 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/cms/v20190321/model/UserKeyword.h>
using TencentCloud::CoreInternalOutcome;
using namespace TencentCloud::Cms::V20190321::Model;
using namespace std;
UserKeyword::UserKeyword() :
m_contentHasBeenSet(false),
m_labelHasBeenSet(false),
m_remarkHasBeenSet(false),
m_wordTypeHasBeenSet(false)
{
}
CoreInternalOutcome UserKeyword::Deserialize(const rapidjson::Value &value)
{
string requestId = "";
if (value.HasMember("Content") && !value["Content"].IsNull())
{
if (!value["Content"].IsString())
{
return CoreInternalOutcome(Core::Error("response `UserKeyword.Content` IsString=false incorrectly").SetRequestId(requestId));
}
m_content = string(value["Content"].GetString());
m_contentHasBeenSet = true;
}
if (value.HasMember("Label") && !value["Label"].IsNull())
{
if (!value["Label"].IsString())
{
return CoreInternalOutcome(Core::Error("response `UserKeyword.Label` IsString=false incorrectly").SetRequestId(requestId));
}
m_label = string(value["Label"].GetString());
m_labelHasBeenSet = true;
}
if (value.HasMember("Remark") && !value["Remark"].IsNull())
{
if (!value["Remark"].IsString())
{
return CoreInternalOutcome(Core::Error("response `UserKeyword.Remark` IsString=false incorrectly").SetRequestId(requestId));
}
m_remark = string(value["Remark"].GetString());
m_remarkHasBeenSet = true;
}
if (value.HasMember("WordType") && !value["WordType"].IsNull())
{
if (!value["WordType"].IsString())
{
return CoreInternalOutcome(Core::Error("response `UserKeyword.WordType` IsString=false incorrectly").SetRequestId(requestId));
}
m_wordType = string(value["WordType"].GetString());
m_wordTypeHasBeenSet = true;
}
return CoreInternalOutcome(true);
}
void UserKeyword::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const
{
if (m_contentHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Content";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_content.c_str(), allocator).Move(), allocator);
}
if (m_labelHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Label";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_label.c_str(), allocator).Move(), allocator);
}
if (m_remarkHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "Remark";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_remark.c_str(), allocator).Move(), allocator);
}
if (m_wordTypeHasBeenSet)
{
rapidjson::Value iKey(rapidjson::kStringType);
string key = "WordType";
iKey.SetString(key.c_str(), allocator);
value.AddMember(iKey, rapidjson::Value(m_wordType.c_str(), allocator).Move(), allocator);
}
}
string UserKeyword::GetContent() const
{
return m_content;
}
void UserKeyword::SetContent(const string& _content)
{
m_content = _content;
m_contentHasBeenSet = true;
}
bool UserKeyword::ContentHasBeenSet() const
{
return m_contentHasBeenSet;
}
string UserKeyword::GetLabel() const
{
return m_label;
}
void UserKeyword::SetLabel(const string& _label)
{
m_label = _label;
m_labelHasBeenSet = true;
}
bool UserKeyword::LabelHasBeenSet() const
{
return m_labelHasBeenSet;
}
string UserKeyword::GetRemark() const
{
return m_remark;
}
void UserKeyword::SetRemark(const string& _remark)
{
m_remark = _remark;
m_remarkHasBeenSet = true;
}
bool UserKeyword::RemarkHasBeenSet() const
{
return m_remarkHasBeenSet;
}
string UserKeyword::GetWordType() const
{
return m_wordType;
}
void UserKeyword::SetWordType(const string& _wordType)
{
m_wordType = _wordType;
m_wordTypeHasBeenSet = true;
}
bool UserKeyword::WordTypeHasBeenSet() const
{
return m_wordTypeHasBeenSet;
}
| [
"tencentcloudapi@tencent.com"
] | tencentcloudapi@tencent.com |
effc2b344aafb4e76d8830003f3fab47fe14a1ac | 55fe6d52a77c6a08de59fa3b562e4f428a21cf29 | /cipher.cpp | 6624e56a214019a12fa90153dc0f11c9354c22ea | [] | no_license | helenwub/DataAlgorithmProj | 451a63cc9f09cf6f6d98249aa18323205254e076 | 64886818b56ccfd0cc9d5b38ef92dd3ae5ea46a7 | refs/heads/main | 2023-06-18T01:55:23.776211 | 2021-07-13T23:47:00 | 2021-07-13T23:47:00 | 385,760,376 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 815 | cpp | #include <iostream>
#include <fstream>
#include "encrypt.h"
#include "decrypt.h"
using namespace std;
int main()
{
char letter;
const int size = 126;
char FilePath[size];
int shift;
char text[size];
char* pEncrypt;
memset(text,0x20, size);
ifstream inFile;
cout << "Would you like to (e)ncrypt or (d)ecrypt a file?";
cin >> letter;
cout << "Enter the shift value: ";
cin >> shift;
cout << "Enter the path to the file: ";
cin >> FilePath;
inFile.open(FilePath);
if (!inFile)
{
return 1;
}
inFile.read(text, size);
inFile.close();
if (letter = 'e') {
pEncrypt = encrypt(text, shift);
for (int i = 0;i < size;i++) {
cout << pEncrypt[i];
}
}
else if (letter = 'd') {
cout << "The decrypted text is: " << decrypt(text, shift) << endl;
}
else
{
return 0;
}
return 0;
}
| [
"helina123konjo@gmail.com"
] | helina123konjo@gmail.com |
be4d40d004e1eaee715fab8970a343012bf40460 | a0d60beae8a2a77bfbe7e73c37274cc6f77c1ee1 | /program6/mstapp.cpp | cd6f9024e403364d77e6fe281fea0553c846be7a | [] | no_license | german9304/CSCI311-CSUCHICO | 1dfa45dc074c1f81bd429819f6e899592d2f6d45 | 84b7be3dc1e64622587ac5e493998154c100a2d1 | refs/heads/master | 2021-08-30T19:17:10.665037 | 2017-12-19T04:30:04 | 2017-12-19T04:30:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,199 | cpp | /**
@Brief In this assignment you will implement Prim's algorithm
for generating a Minimum Spanning Tree (MST).
@Author German Razo Rodriguez
*/
#include <stdio.h>
#include "mstapp.h"
#include <sstream>
using std::cin;
using std::cout;
using std::endl;
/*******
@Description This function eads a weighted undirected graph from stdin and
writes the structure of the MST to stdout.
@return none
***/
void MSTapp::readGraph(){
Graph agraph;
string name;
string first;
getline(cin,name);
vector<string> vertices;
string temp="";
for(int i=0;i<(int) name.length()+1;i++){
if(name[i]!=' '&&name[i]!='\0'){
temp+=name[i];
}else{
if(temp!=""){
vertices.push_back(temp);
temp="";
}
}
}
for(int index=0;index<(int) vertices.size();index++){
if(index==0){
first=vertices[index];
agraph.addVertex(first);
}else{
agraph.addVertex(vertices[index]);
}
}
string from,to;
int weight;
while(!cin.eof()){
cin>>from>>to>>weight;
agraph.addEdge(from,to,weight); //Adds edges to the graph
}
agraph.mst(first); //root of the MST(first)
}
int main(){
MSTapp amst;
amst.readGraph();
return 0;
}
| [
"31298672+german9304@users.noreply.github.com"
] | 31298672+german9304@users.noreply.github.com |
0dc306eac9e10b450599e94ad3d533f4b9ae9b7d | e04045891517f5ffb5820177d50bcc48ed65a3fb | /task9/main.cpp | 2e7cf7ebdc9d8f51f149381d5800599cea58d072 | [] | no_license | ZaiqiangWu/pba | 8580d16d8501444e6d744c6b87b3671eee4772cb | ed39259c07b10ef02455f0e71cbb88c656915837 | refs/heads/main | 2023-06-09T13:29:27.121004 | 2021-06-28T05:44:09 | 2021-06-28T05:44:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,026 | cpp |
#include "delfem2/glfw/viewer2.h"
#include <GLFW/glfw3.h>
#include <cstdlib>
#include <cstdio>
// print out error
static void error_callback(int error, const char* description){
fputs(description, stderr);
}
void Draw(){
glBegin(GL_LINE_LOOP);
glColor3f(0.f, 0.f, 0.f);
glVertex2f(0.f, 0.f);
glVertex2f(1.f, 0.f);
glVertex2f(1.f, 1.f);
glVertex2f(0.f, 1.f);
glEnd();
}
int main()
{
delfem2::glfw::CViewer2 viewer;
{
viewer.view_height = 1.0;
viewer.trans[0] = -0.5;
viewer.trans[1] = -0.5;
viewer.title = "task9: Shape Matching Deformation";
}
glfwSetErrorCallback(error_callback);
if ( !glfwInit() ) { exit(EXIT_FAILURE); }
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
// ------
viewer.InitGL();
while (!glfwWindowShouldClose(viewer.window))
{
viewer.DrawBegin_oldGL();
Draw();
viewer.SwapBuffers();
glfwPollEvents();
}
glfwDestroyWindow(viewer.window);
glfwTerminate();
exit(EXIT_SUCCESS);
}
| [
"n.umetani@gmail.com"
] | n.umetani@gmail.com |
90a6859ef3372b3b7264ecb9038cf4fb102be767 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /third_party/blink/renderer/platform/wtf/threading_win.cc | 93f324ea512fe3610e4ca752b201ced8c8ba8958 | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 8,697 | cc | /*
* Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
* Copyright (C) 2009 Google Inc. All rights reserved.
* Copyright (C) 2009 Torch Mobile, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of Apple Computer, Inc. ("Apple") 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 APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* There are numerous academic and practical works on how to implement
* pthread_cond_wait/pthread_cond_signal/pthread_cond_broadcast
* functions on Win32. Here is one example:
* http://www.cs.wustl.edu/~schmidt/win32-cv-1.html which is widely credited as
* a 'starting point' of modern attempts. There are several more or less proven
* implementations, one in Boost C++ library (http://www.boost.org) and another
* in pthreads-win32 (http://sourceware.org/pthreads-win32/).
*
* The number of articles and discussions is the evidence of significant
* difficulties in implementing these primitives correctly. The brief search
* of revisions, ChangeLog entries, discussions in comp.programming.threads and
* other places clearly documents numerous pitfalls and performance problems
* the authors had to overcome to arrive to the suitable implementations.
* Optimally, WebKit would use one of those supported/tested libraries
* directly. To roll out our own implementation is impractical, if even for
* the lack of sufficient testing. However, a faithful reproduction of the code
* from one of the popular supported libraries seems to be a good compromise.
*
* The early Boost implementation
* (http://www.boxbackup.org/trac/browser/box/nick/win/lib/win32/boost_1_32_0/libs/thread/src/condition.cpp?rev=30)
* is identical to pthreads-win32
* (http://sourceware.org/cgi-bin/cvsweb.cgi/pthreads/pthread_cond_wait.c?rev=1.10&content-type=text/x-cvsweb-markup&cvsroot=pthreads-win32).
* Current Boost uses yet another (although seemingly equivalent) algorithm
* which came from their 'thread rewrite' effort.
*
* This file includes timedWait/signal/broadcast implementations translated to
* WebKit coding style from the latest algorithm by Alexander Terekhov and
* Louis Thomas, as captured here:
* http://sourceware.org/cgi-bin/cvsweb.cgi/pthreads/pthread_cond_wait.c?rev=1.10&content-type=text/x-cvsweb-markup&cvsroot=pthreads-win32
* It replaces the implementation of their previous algorithm, also documented
* in the same source above. The naming and comments are left very close to
* original to enable easy cross-check.
*
* The corresponding Pthreads-win32 License is included below, and CONTRIBUTORS
* file which it refers to is added to source directory (as
* CONTRIBUTORS.pthreads-win32).
*/
/*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2005 Pthreads-win32 contributors
*
* Contact Email: rpj@callisto.canberra.edu.au
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.html
*
* This library 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 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include "third_party/blink/renderer/platform/wtf/threading.h"
#include "build/build_config.h"
#if defined(OS_WIN)
#include <errno.h>
#include <process.h>
#include <windows.h>
#include "base/threading/scoped_blocking_call.h"
#include "third_party/blink/renderer/platform/wtf/threading_primitives.h"
#include "third_party/blink/renderer/platform/wtf/time.h"
namespace WTF {
MutexBase::MutexBase(bool recursive) {
mutex_.recursion_count_ = 0;
InitializeCriticalSection(&mutex_.internal_mutex_);
}
MutexBase::~MutexBase() {
DeleteCriticalSection(&mutex_.internal_mutex_);
}
void MutexBase::lock() {
EnterCriticalSection(&mutex_.internal_mutex_);
DCHECK(!mutex_.recursion_count_)
<< "WTF does not support recursive mutex acquisition!";
++mutex_.recursion_count_;
}
void MutexBase::unlock() {
DCHECK(mutex_.recursion_count_);
--mutex_.recursion_count_;
LeaveCriticalSection(&mutex_.internal_mutex_);
}
bool Mutex::TryLock() {
// This method is modeled after the behavior of pthread_mutex_trylock,
// which will return an error if the lock is already owned by the
// current thread. Since the primitive Win32 'TryEnterCriticalSection'
// treats this as a successful case, it changes the behavior of several
// tests in WebKit that check to see if the current thread already
// owned this mutex (see e.g., IconDatabase::getOrCreateIconRecord)
DWORD result = TryEnterCriticalSection(&mutex_.internal_mutex_);
if (result != 0) { // We got the lock
// If this thread already had the lock, we must unlock and return
// false since this is a non-recursive mutex. This is to mimic the
// behavior of POSIX's pthread_mutex_trylock. We don't do this
// check in the lock method (presumably due to performance?). This
// means lock() will succeed even if the current thread has already
// entered the critical section.
DCHECK(!mutex_.recursion_count_)
<< "WTF does not support recursive mutex acquisition!";
if (mutex_.recursion_count_ > 0) {
LeaveCriticalSection(&mutex_.internal_mutex_);
return false;
}
++mutex_.recursion_count_;
return true;
}
return false;
}
bool RecursiveMutex::TryLock() {
// CRITICAL_SECTION is recursive/reentrant so TryEnterCriticalSection will
// succeed if the current thread is already in the critical section.
DWORD result = TryEnterCriticalSection(&mutex_.internal_mutex_);
if (result == 0) { // We didn't get the lock.
return false;
}
DCHECK(!mutex_.recursion_count_)
<< "WTF does not support recursive mutex acquisition!";
++mutex_.recursion_count_;
return true;
}
ThreadCondition::ThreadCondition(Mutex& mutex)
: condition_(CONDITION_VARIABLE_INIT), mutex_(mutex.Impl()) {}
ThreadCondition::~ThreadCondition() {}
void ThreadCondition::Wait() {
base::ScopedBlockingCall scoped_blocking_call(FROM_HERE,
base::BlockingType::MAY_BLOCK);
--mutex_.recursion_count_;
BOOL result =
SleepConditionVariableCS(&condition_, &mutex_.internal_mutex_, INFINITE);
DCHECK_NE(result, 0);
++mutex_.recursion_count_;
}
void ThreadCondition::Signal() {
WakeConditionVariable(&condition_);
}
void ThreadCondition::Broadcast() {
WakeAllConditionVariable(&condition_);
}
} // namespace WTF
#endif // defined(OS_WIN)
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
f130251ebbf3dd6185ba9385eac939b62fcf525d | 23dd9d94f20f52fe405b7ac96ea05e0db943e718 | /PAO/addvisitdialog.h | 62f5252fe6ba59a9537fb26afe92de8bd652c3bc | [] | no_license | fedsib/pao-project | c44d7ed19839ec50f47e19a303e152d94869cfaa | 83744a04892c792c0908acdcea0f7031322f2c2c | refs/heads/master | 2021-03-27T16:39:13.872401 | 2017-01-01T11:12:40 | 2017-01-01T11:12:40 | 24,765,166 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 994 | h | #ifndef ADDVISITDIALOG_H
#define ADDVISITDIALOG_H
#include <QRadioButton>
//#include <QLabel>
#include <QPushButton>
#include "basicvisit.h"
#include "specializedvisit.h"
#include "vaccinevisit.h"
#include "vetcontrol.h"
class AddVisitDialog : public QDialog {
Q_OBJECT
private:
VetControl* vetc;
QGroupBox* IDGroupBox;
QGroupBox* VisitCoreGroupBox;
QGroupBox* RBGroupBox;
QDialogButtonBox* buttonbox;
QLineEdit* cfv_led;
QLineEdit* animalID_led;
QLineEdit* basicPrice_led;
QDateEdit* date_ded;
QLineEdit* note_led; //maybe a QTextEdit?
QRadioButton* basicRB;
QRadioButton* vaccineRB;
QRadioButton* specializedRB;
void createIDGroupBox();
void createVCGroupBox();
void createRBGroupBox();
void createButtonBox();
void prepareGUI();
void prepareConnections();
public:
explicit AddVisitDialog(QWidget* , VetControl*);
public slots:
void createVisitAndExit();
};
#endif // ADDVISITDIALOG_H
| [
"fedsib@users.noreply.github.com"
] | fedsib@users.noreply.github.com |
943abbdbf191e5617af64205e9bb390a93a36bed | ab1c643f224197ca8c44ebd562953f0984df321e | /snapin/dfsadmin/dfsgui/utils.h | edb931bca3162d18063ebacfe1f8bd6c707b9c50 | [] | no_license | KernelPanic-OpenSource/Win2K3_NT_admin | e162e0452fb2067f0675745f2273d5c569798709 | d36e522f16bd866384bec440517f954a1a5c4a4d | refs/heads/master | 2023-04-12T13:25:45.807158 | 2021-04-13T16:33:59 | 2021-04-13T16:33:59 | 357,613,696 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,943 | h | /*++
Module Name:
Utils.h
Abstract:
This module contains the definition for CUtils class.
Contains utility method which are used throughout the project.
--*/
#if !defined(AFX_UTILS_H__B3542C03_4260_11D1_AA28_00C06C00392D__INCLUDED_)
#define AFX_UTILS_H__B3542C03_4260_11D1_AA28_00C06C00392D__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#include <lmcons.h>
#include <lmerr.h>
#include <icanon.h>
#include "dfsenums.h"
#include <schedule.h>
#include "ldaputils.h"
class CThemeContextActivator
{
public:
CThemeContextActivator() : m_ulActivationCookie(0)
{ SHActivateContext (&m_ulActivationCookie); }
~CThemeContextActivator()
{ SHDeactivateContext (m_ulActivationCookie); }
private:
ULONG_PTR m_ulActivationCookie;
};
class CWaitCursor
{
public:
CWaitCursor() { SetStandardCursor(IDC_WAIT); }
~CWaitCursor() { SetStandardCursor(IDC_ARROW); }
HRESULT SetStandardCursor(
IN LPCTSTR i_lpCursorName
);
};
BOOL Is256ColorSupported(
VOID
);
VOID SetControlFont(
IN HFONT hFont,
IN HWND hwnd,
IN INT nId
);
VOID SetupFonts(
IN HINSTANCE hInstance,
IN HWND hwnd,
IN HFONT *pBigBoldFont,
IN HFONT *pBoldFont
);
VOID
DestroyFonts(
IN HFONT hBigBoldFont,
IN HFONT hBoldFont
);
HRESULT LoadStringFromResource(
IN const UINT i_uResourceID,
OUT BSTR* o_pbstrReadValue
);
HRESULT FormatResourceString(
IN const UINT i_uResourceID,
IN LPCTSTR i_szFirstArg,
OUT BSTR* o_pbstrReadString
);
HRESULT CreateSmallImageList(
IN HINSTANCE i_hInstance,
IN int* i_pIconID,
IN const int i_nNumOfIcons,
OUT HIMAGELIST* o_phImageList
);
HRESULT InsertIntoListView(
IN HWND i_hwndList,
IN LPCTSTR i_szItemText,
IN int i_iImageIndex = 0
);
HRESULT GetListViewItemText(
IN HWND i_hwndListView,
IN int i_iItemID,
OUT BSTR* o_pbstrItemText
);
HRESULT GetComboBoxText(
IN HWND i_hwndCombo,
OUT BSTR* o_pbstrText
);
HRESULT EnableToolbarButtons(
IN const LPTOOLBAR i_lpToolbar,
IN const INT i_iFirstButtonID,
IN const INT i_iLastButtonID,
IN const BOOL i_bEnableState
);
HRESULT AddBitmapToToolbar(
IN const LPTOOLBAR i_lpToolbar,
IN const INT i_iBitmapResource
);
HRESULT
GetMessage(
OUT BSTR* o_pbstrMsg,
IN DWORD dwErr,
IN UINT iStringId,
...);
int
DisplayMessageBox(
IN HWND hwndParent,
IN UINT uType,
IN DWORD dwErr,
IN UINT iStringId,
...);
HRESULT DisplayMessageBoxWithOK(
IN const int i_iMessageResID,
IN const BSTR i_bstrArgument = NULL
);
HRESULT DisplayMessageBoxForHR(
IN HRESULT i_hr
);
HRESULT GetInputText(
IN HWND hwnd,
OUT BSTR* o_pbstrText,
OUT DWORD* o_pdwTextLength
);
BOOL CheckRegKey();
BOOL
ValidateNetPath(
IN BSTR i_bstrNetPath,
OUT BSTR *o_pbstrServer,
OUT BSTR *o_pbstrShare
);
HRESULT
IsComputerLocal(
IN LPCTSTR lpszServer
);
BOOL
IsValidLocalAbsolutePath(
IN LPCTSTR lpszPath
);
HRESULT
GetFullPath(
IN LPCTSTR lpszServer,
IN LPCTSTR lpszPath,
OUT BSTR *o_pbstrFullPath
);
HRESULT
VerifyDriveLetter(
IN LPCTSTR lpszServer,
IN LPCTSTR lpszPath
);
HRESULT
IsAdminShare(
IN LPCTSTR lpszServer,
IN LPCTSTR lpszPath
);
HRESULT
IsAnExistingFolder(
IN HWND hwnd,
IN LPCTSTR pszPath
);
HRESULT
CreateLayeredDirectory(
IN LPCTSTR lpszServer,
IN LPCTSTR lpszPath
);
HRESULT
BrowseNetworkPath(
IN HWND hwndParent,
OUT BSTR *o_pbstrPath
);
BOOL
ValidateTimeout(
IN LPCTSTR lpszTimeOut,
OUT ULONG *pulTimeout
);
TCHAR
GetDiskForStagingPath(
IN LPCTSTR lpszServer,
IN TCHAR tch
);
HRESULT GetDfsRootDisplayName
(
IN BSTR i_bstrScopeName,
IN BSTR i_bstrDfsName,
OUT BSTR* o_pbstrDisplayName
);
HRESULT GetDfsReplicaDisplayName
(
IN BSTR i_bstrServerName,
IN BSTR i_bstrShareName,
OUT BSTR* o_pbstrDisplayName
);
HRESULT
AddLVColumns(
IN const HWND hwndListBox,
IN const INT iStartingResourceID,
IN const UINT uiColumns
);
LPARAM GetListViewItemData(
IN HWND hwndList,
IN int index
);
HRESULT CreateAndHideStagingPath(
IN BSTR i_bstrServer,
IN BSTR i_bstrStagingPath
);
HRESULT ConfigAndStartNtfrs
(
BSTR i_bstrServer
);
HRESULT CheckResourceProvider(LPCTSTR pszResource);
HRESULT FRSShareCheck
(
BSTR i_bstrServer,
BSTR i_bstrFolder,
OUT FRSSHARE_TYPE *pFRSShareType
);
HRESULT FRSIsNTFRSInstalled
(
BSTR i_bstrServer
);
HRESULT InvokeScheduleDlg(
IN HWND i_hwndParent,
IN OUT SCHEDULE* io_pSchedule
);
HRESULT ReadSharePublishInfoOnFTRoot(
LPCTSTR i_pszDomainName,
LPCTSTR i_pszRootName,
OUT BOOL* o_pbPublish,
OUT BSTR* o_pbstrUNCPath,
OUT BSTR* o_pbstrDescription,
OUT BSTR* o_pbstrKeywords,
OUT BSTR* o_pbstrManagedBy);
HRESULT ReadSharePublishInfoOnSARoot(
LPCTSTR i_pszServerName,
LPCTSTR i_pszShareName,
OUT BOOL* o_pbPublish,
OUT BSTR* o_pbstrUNCPath,
OUT BSTR* o_pbstrDescription,
OUT BSTR* o_pbstrKeywords,
OUT BSTR* o_pbstrManagedBy);
HRESULT ModifySharePublishInfoOnFTRoot(
IN PCTSTR i_pszDomainName,
IN PCTSTR i_pszRootName,
IN BOOL i_bPublish,
IN PCTSTR i_pszUNCPath,
IN PCTSTR i_pszDescription,
IN PCTSTR i_pszKeywords,
IN PCTSTR i_pszManagedBy
);
HRESULT ModifySharePublishInfoOnSARoot(
IN PCTSTR i_pszServerName,
IN PCTSTR i_pszShareName,
IN BOOL i_bPublish,
IN PCTSTR i_pszUNCPath,
IN PCTSTR i_pszDescription,
IN PCTSTR i_pszKeywords,
IN PCTSTR i_pszManagedBy
);
HRESULT PutMultiValuesIntoAttrValList(
IN PCTSTR i_pszValues,
OUT LDAP_ATTR_VALUE** o_pVal
);
HRESULT PutMultiValuesIntoStringArray(
IN PCTSTR i_pszValues,
OUT PTSTR** o_pVal
);
void FreeStringArray(PTSTR* i_ppszStrings);
HRESULT mystrtok(
IN PCTSTR i_pszString,
IN OUT int* io_pnIndex, // start from 0
IN PCTSTR i_pszCharSet,
OUT BSTR* o_pbstrToken
);
void TrimBSTR(BSTR bstr);
BOOL CheckPolicyOnSharePublish();
BOOL CheckPolicyOnDisplayingInitialMaster();
HRESULT GetMenuResourceStrings(
IN int i_iStringID,
OUT BSTR* o_pbstrMenuText,
OUT BSTR* o_pbstrToolTipText,
OUT BSTR* o_pbstrStatusBarText
);
LRESULT CALLBACK
NoPasteEditCtrlProc(
HWND hwnd,
UINT uMsg,
WPARAM wParam,
LPARAM lParam
);
void SetActivePropertyPage(IN HWND i_hwndParent, IN HWND i_hwndPage);
void MyShowWindow(HWND hwnd, BOOL bShow);
void OpenBrowseDialog(
IN HWND hwndParent,
IN int idLabel,
IN BOOL bLocalComputer,
IN LPCTSTR lpszComputer,
OUT LPTSTR lpszDir
);
#endif // !defined(AFX_UTILS_H__B3542C03_4260_11D1_AA28_00C06C00392D__INCLUDED_)
| [
"polarisdp@gmail.com"
] | polarisdp@gmail.com |
557f5171bb7106e086b9e19204760faa345f4fbd | 31d746e5dbe161fc693909a121eaf362b2c8eaff | /assignment1.cpp | 0eedfc769b73cbc18bf0dbd032f0b747c398b1f8 | [] | no_license | ambroseled/OpenGL-2-Graphics-Scene | 88fb1972b3974a2d2a6a12d4f229741bfba5c48c | 36ae31d6e2e77b447f4a987e1b3cb8baf5afa7e0 | refs/heads/master | 2020-05-02T18:14:16.978232 | 2019-04-04T08:20:34 | 2019-04-04T08:20:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,734 | cpp | // ========================================================================
// COSC363: Computer Graphics (2019); CSSE University of Canterbury.
//
// FILE NAME: Skybox.cpp
// See Lab03.pdf for details
// ========================================================================
#include <iostream>
#include <GL/freeglut.h>
#include <cmath>
#include <fstream>
#include <climits>
#include <math.h>
#include "loadTGA.h"
#include "loadBMP.h"
using namespace std;
#define GL_CLAMP_TO_EDGE 0x812F //To get rid of seams between textures
float lookAngle = 0.0; //Camera rotation
float movePos = 0.0;
float size = 300000;
float angle=0, look_x, look_z=-1., eye_x=-80000, eye_z=110000; //Camera parameters
float *x, *y, *z; //vertex coordinate arrays
int *t1, *t2, *t3; //triangles
int nvrt, ntri; //total number of vertices and triangles
float ball_pos[3] = {26.88, 84, 0};
GLuint texId[10];
float cannonAngle = 0;
float shipHeight = 400;
float shipChange = 0;
bool shipLaunched = false;
bool changeCamera = false;
float lightAngle = 0;
bool fireCannon = false;
float gravAccel = 9.80665;
float cannonRadians = 0.785398;
float cannonVelocity = 100;
int cannonCount = 1;
GLUquadricObj* q;
float robot_1_pos[3] = {-200000.0, 0.0, 180000.0};
float robot_pos[3] = {-20000, 0.0, 40000.0};
bool shipUp = true;
float robotAngle1 = 90;
float robotAngle = 180;
int robotState = 0;
int robotState1 = 0;
float theta = 0;
bool gaurdForward = true;
float robot2_z = -70;
float gaurdAngle = 0;
float doorAngle = 30;
bool doorOut = true;
bool showBallFront = false;
bool raiseCannon = true;
//========================================================================================
// Loading a mesh file
void loadMeshFile(const char* fname)
{
ifstream fp_in;
int num, ne;
fp_in.open(fname, ios::in);
if(!fp_in.is_open())
{
cout << "Error opening mesh file" << endl;
exit(1);
}
fp_in.ignore(INT_MAX, '\n'); //ignore first line
fp_in >> nvrt >> ntri >> ne; // read number of vertices, polygons, edges
x = new float[nvrt]; //create arrays
y = new float[nvrt];
z = new float[nvrt];
t1 = new int[ntri];
t2 = new int[ntri];
t3 = new int[ntri];
for(int i=0; i < nvrt; i++) //read vertex list
fp_in >> x[i] >> y[i] >> z[i];
for(int i=0; i < ntri; i++) //read polygon list
{
fp_in >> num >> t1[i] >> t2[i] >> t3[i];
if(num != 3)
{
cout << "ERROR: Polygon with index " << i << " is not a triangle." << endl; //not a triangle!!
exit(1);
}
}
fp_in.close();
cout << " File successfully read." << endl;
}
// Loading the scenes textures
void loadGLTextures()
{
glGenTextures(10, texId); // Create texture ids
glBindTexture(GL_TEXTURE_2D, texId[0]);
loadBMP("textures/brickTexture.bmp");
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); //Set texture parameters
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, texId[1]);
loadBMP("textures/brassTexture.bmp");
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); //Set texture parameters
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, texId[2]);
loadBMP("textures/metalTexture.bmp");
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); //Set texture parameters
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glBindTexture(GL_TEXTURE_2D, texId[3]);
loadBMP("textures/redPaint.bmp");
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); //Set texture parameters
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
// *** left ***
glBindTexture(GL_TEXTURE_2D, texId[4]);
loadTGA("textures/iceflats_lf.tga");
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// *** front ***
glBindTexture(GL_TEXTURE_2D, texId[5]);
loadTGA("textures/iceflats_ft.tga");
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// *** right ***
glBindTexture(GL_TEXTURE_2D, texId[6]);
loadTGA("textures/iceflats_rt.tga");
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// *** back***
glBindTexture(GL_TEXTURE_2D, texId[7]);
loadTGA("textures/iceflats_bk.tga");
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
// *** top ***
glBindTexture(GL_TEXTURE_2D, texId[8]);
loadTGA("textures/iceflats_up.tga");
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(GL_TEXTURE_2D, texId[9]);
loadBMP("textures/doorTexture.bmp");
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR); //Set texture parameters
glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);
glTexEnvi(GL_TEXTURE_ENV,GL_TEXTURE_ENV_MODE,GL_MODULATE);
}
// Used to calculate the normal
void normal(int tindx)
{
float x1 = x[t1[tindx]], x2 = x[t2[tindx]], x3 = x[t3[tindx]];
float y1 = y[t1[tindx]], y2 = y[t2[tindx]], y3 = y[t3[tindx]];
float z1 = z[t1[tindx]], z2 = z[t2[tindx]], z3 = z[t3[tindx]];
float nx, ny, nz;
nx = y1*(z2-z3) + y2*(z3-z1) + y3*(z1-z2);
ny = z1*(x2-x3) + z2*(x3-x1) + z3*(x1-x2);
nz = x1*(y2-y3) + x2*(y3-y1) + x3*(y1-y2);
glNormal3f(nx, ny, nz);
}
// Drawing the cannon
void drawCannon()
{
//Construct the object model here using triangles read from OFF file
glBegin(GL_TRIANGLES);
for(int tindx = 0; tindx < ntri; tindx++)
{
normal(tindx);
glVertex3d(x[t1[tindx]], y[t1[tindx]], z[t1[tindx]]);
glVertex3d(x[t2[tindx]], y[t2[tindx]], z[t2[tindx]]);
glVertex3d(x[t3[tindx]], y[t3[tindx]], z[t3[tindx]]);
}
glEnd();
}
// Drawing the floor of the scene
void drawFloor()
{
bool flag = false;
glBegin(GL_QUADS);
glNormal3f(0, 1, 0);
for(int x = -400; x <= 400; x += 20)
{
for(int z = -400; z <= 400; z += 20)
{
if(flag) glColor3f(0.6, 1.0, 0.8);
else glColor3f(0.8, 1.0, 0.6);
glVertex3f(x, 0, z);
glVertex3f(x, 0, z+20);
glVertex3f(x+20, 0, z+20);
glVertex3f(x+20, 0, z);
flag = !flag;
}
}
glEnd();
}
// Drawing the cannon with its body
void drawCannonBody(int colourMode)
{
glDisable(GL_TEXTURE_2D);
//--start here
glPushMatrix();
glTranslatef(-10.0, 5.0, 17.0);
glScalef(80.0, 10.0, 6.0);
glutSolidCube(1);
glPopMatrix();
glPushMatrix();
glTranslatef(-20.0, 25.0, 17.0);
glScalef(40.0, 30.0, 6.0);
glutSolidCube(1);
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0, 5.0, -17.0);
glScalef(80.0, 10.0, 6.0);
glutSolidCube(1);
glPopMatrix();
glPushMatrix();
glTranslatef(-20.0, 25.0, -17.0);
glScalef(40.0, 30.0, 6.0);
glutSolidCube(1);
glPopMatrix();
glPushMatrix();
glTranslatef(-20, 30, 0); //Pivot point coordinates
glRotatef(cannonAngle, 0, 0, 1); //Rotation
glTranslatef(20, -30, 0);
if (colourMode == 0) {
glColor3f(0.4, 0.5, 0.4);
} else {
glColor3f(0, 0, 0);
}
drawCannon();
glPopMatrix();
if (showBallFront) {
glPushMatrix();
glColor3ub(0, 0, 0);
glTranslatef(ball_pos[0], ball_pos[1], 0);
glutSolidSphere(5, 36, 18);
glPopMatrix();
glEnable(GL_TEXTURE_2D);
}
}
// Drawing the cannon shadow
void drawCannonBodyShadow()
{
glDisable(GL_TEXTURE_2D);
//--start here
glPushMatrix();
glTranslatef(-10.0, 5.0, 17.0);
glScalef(80.0, 10.0, 6.0);
glutSolidCube(1);
glPopMatrix();
glPushMatrix();
glTranslatef(-20.0, 25.0, 17.0);
glScalef(40.0, 30.0, 6.0);
glutSolidCube(1);
glPopMatrix();
glPushMatrix();
glTranslatef(-10.0, 5.0, -17.0);
glScalef(80.0, 10.0, 6.0);
glutSolidCube(1);
glPopMatrix();
glPushMatrix();
glTranslatef(-20.0, 25.0, -17.0);
glScalef(40.0, 30.0, 6.0);
glutSolidCube(1);
glPopMatrix();
glPushMatrix();
glTranslatef(-20, 30, 0); //Pivot point coordinates
glRotatef(30, 0, 0, 1); //Rotation
glTranslatef(20, -30, 0);
drawCannon();
glPopMatrix();
glPushMatrix();
glColor3ub(0, 0, 0);
glTranslatef(ball_pos[0], ball_pos[1], 0);
glutSolidSphere(5, 36, 18);
glPopMatrix();
glEnable(GL_TEXTURE_2D);
}
// Functions above here have been taken from the labs provided
// drawCannonBodyShadow, drawCannonBody, drawCannon and loadGLTextures have been adapted
//========================================================================================
// Drawing a 'cube' with passed parameters, used mainly to make the castle walls
void drawWall(float length, float height, float width, int texture)
{
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texId[texture]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glBegin(GL_QUADS);
glColor3f(1, 1, 1);
// front
glTexCoord2f(0., 0.); glVertex3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(2., 0.); glVertex3f(length, 0.0f, 0.0f);
glTexCoord2f(2., 2.); glVertex3f(length, height, 0.0f);
glTexCoord2f(0., 2.); glVertex3f(0.0f, height, 0.0f);
// back
glTexCoord2f(0., 0.); glVertex3f(0.0f, 0.0f, -width);
glTexCoord2f(2., 0.); glVertex3f(length, 0.0f, -width);
glTexCoord2f(2., 2.); glVertex3f(length, height, -width);
glTexCoord2f(0., 2.); glVertex3f(0.0f, height, -width);
// right
glTexCoord2f(0., 0.); glVertex3f(length, 0.0f, 0.0f);
glTexCoord2f(2., 0.); glVertex3f(length, 0.0f, -width);
glTexCoord2f(2., 2.); glVertex3f(length, height, -width);
glTexCoord2f(0., 2.); glVertex3f(length, height, 0.0f);
// left
glTexCoord2f(0., 0.); glVertex3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(2., 0.); glVertex3f(0.0f, 0.0f, -width);
glTexCoord2f(2., 2.); glVertex3f(0.0f, height, -width);
glTexCoord2f(0., 2.); glVertex3f(0.0f, height, 0.0f);
// top
glTexCoord2f(0., 0.); glVertex3f(0.0f, height, 0.0f);
glTexCoord2f(2., 0.); glVertex3f(length, height, 0.0f);
glTexCoord2f(2., 2.); glVertex3f(length, height, -width);
glTexCoord2f(0., 2.); glVertex3f(0.0f, height, -width);
// bottom
glTexCoord2f(0., 0.); glVertex3f(0.0f, 0.0f, 0.0f);
glTexCoord2f(2., 0.); glVertex3f(length, 0.0f, 0.0f);
glTexCoord2f(2., 2.); glVertex3f(length, 0.0f, -width);
glTexCoord2f(0., 2.); glVertex3f(0.0f, 0.0f, -width);
glEnd();
}
// Drawing a cylinder that can be textured
void drawTower(int n, float width, float height, int texture) {
glBindTexture(GL_TEXTURE_2D, texId[texture]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glColor3f(1, 1, 1);
int numSegments = 360;
float texInc = 1.0f / numSegments;
// Top and bottom
for (int side = 0; side < 2; side++) {
glBegin(GL_POLYGON);
for(int i = 0; i <= (numSegments); i += (numSegments / n)) {
float angle = i * M_PI / 180;
if (side == 0) {
glVertex3f(width * cos(angle), width * sin(angle), 0.0);
} else {
glVertex3f(width * cos(angle), width * sin(angle), height);
}
}
glEnd();
}
// Body
glBegin(GL_QUAD_STRIP);
for(int i = 0; i < 480; i += (numSegments / n)) {
float angle = i * M_PI / 180;
glTexCoord2f(texInc * i, 0); glVertex3f(width * cos(angle), width * sin(angle), 0.0);
glTexCoord2f(texInc * i, 1); glVertex3f(width * cos(angle), width * sin(angle), height);
}
glEnd();
}
// Drawing the first robot
void drawRobot()
{
glPushMatrix();
glColor3f(1, 1, 0);
glTranslatef(0, 5.9, 2);
glutSolidCube(1.4);
glPopMatrix();
glPushMatrix();
glColor3f(0, 1, 0);
glTranslatef(0.25, 6.1, 2.7);
glutSolidSphere(0.15, 50, 10);
glPopMatrix();
glPushMatrix();
glColor3f(0, 1, 0);
glTranslatef(-0.25, 6.1, 2.7);
glutSolidSphere(0.15, 50, 10);
glPopMatrix();
//Torso
glPushMatrix();
glColor3f(0, 0, 0);
glTranslatef(0, 4.5, 0);
glScalef(3, 1.4, 5.4);
glutSolidCube(1);
glPopMatrix();
//Right leg
glPushMatrix();
glColor3f(1, 0, 0);
glTranslatef(-0.8, 4, 0);
glRotatef(theta, 1, 0, 0);
glTranslatef(0.8, -4, 0);
glTranslatef(-0.8, 2.2, -2);
glScalef(1, 4.4, 1);
glutSolidCube(1);
glPopMatrix();
//Left leg
glPushMatrix();
glColor3f(1, 0, 0);
glTranslatef(-0.8, 4, 0);
glRotatef(-theta, 1, 0, 0);
glTranslatef(0.8, -4, 0);
glTranslatef(0.8, 2.2, -2);
glScalef(1, 4.4, 1);
glutSolidCube(1);
glPopMatrix();
//Right leg front
glPushMatrix();
glColor3f(1, 0, 0);
glTranslatef(-0.8, 4, 0);
glRotatef(-theta, 1, 0, 0);
glTranslatef(0.8, -4, 0);
glTranslatef(-0.8, 2.2, 2);
glScalef(1, 4.4, 1);
glutSolidCube(1);
glPopMatrix();
//Left leg front
glPushMatrix();
glColor3f(1, 0, 0);
glTranslatef(-0.8, 4, 0);
glRotatef(theta, 1, 0, 0);
glTranslatef(0.8, -4, 0);
glTranslatef(0.8, 2.2, 2);
glScalef(1, 4.4, 1);
glutSolidCube(1);
glPopMatrix();
}
// Drawing the castle
void drawCastle()
{
float shadowMat[16] = { 80,0,0,0, -80,0,-0,-1,
0,0,80,0, 0,0,0,80 };
glEnable(GL_TEXTURE_2D);
// Front wall
glPushMatrix();
glTranslatef(-35., 0., -50.);
drawWall(20, 40, 5, 0);
glPopMatrix();
glPushMatrix();
glTranslatef(20., 0., -50.);
drawWall(20, 40, 5, 0);
glPopMatrix();
glPushMatrix();
glTranslatef(-15., 30., -50.);
drawWall(35, 10, 5, 0);
glPopMatrix();
// Doors right
glPushMatrix();
glTranslatef(-15., 0., -50.);
glRotatef(doorAngle, 0, 1, 0);
drawWall(17, 30, 5, 9);
glPopMatrix();
// Doors left
glPushMatrix();
glTranslatef(20., 0., -55.);
glRotatef(-doorAngle + 180, 0, 1, 0);
drawWall(17, 30, 5, 9);
glPopMatrix();
// Back wall
glPushMatrix();
glTranslatef(-35., 0., 25.);
drawWall(80, 40, 5, 0);
glPopMatrix();
// left wall
glPushMatrix();
glTranslatef(45., 0., 25.);
glRotatef(90, 0., 1., 0.);
drawWall(80, 40, 5, 0);
glPopMatrix();
// right wall
glPushMatrix();
glTranslatef(-35., 0., 25.);
glRotatef(90, 0., 1., 0.);
drawWall(80, 40, 5, 0);
glPopMatrix();
// Back Right Tower
glPushMatrix();
//glRotatef(90, 1, 0, 0);
glTranslatef(-37, 50, 22);
glRotatef(90, 1, 0, 0);
drawTower(30, 5, 50, 0);
glPushMatrix();
glRotatef(180, 0, 1, 0);
glutSolidCone(5, 10, 30, 10);
glPopMatrix();
glPopMatrix();
// Back Left Tower
glPushMatrix();
//glRotatef(90, 1, 0, 0);
glTranslatef(42, 50, 22);
glRotatef(90, 1, 0, 0);
drawTower(30, 5, 50, 0);
glPushMatrix();
glRotatef(180, 0, 1, 0);
glutSolidCone(5, 10, 30, 10);
glPopMatrix();
glPopMatrix();
// Front Right Tower
glPushMatrix();
//glRotatef(90, 1, 0, 0);
glTranslatef(-37, 50, -52);
glRotatef(90, 1, 0, 0);
drawTower(30, 5, 50, 0);
glPushMatrix();
glRotatef(180, 0, 1, 0);
glutSolidCone(5, 10, 30, 10);
glPopMatrix();
glPopMatrix();
// Front Left Tower
glPushMatrix();
//glRotatef(90, 1, 0, 0);
glTranslatef(42, 50, -52);
glRotatef(90, 1, 0, 0);
drawTower(30, 5, 50, 0);
glPushMatrix();
glRotatef(180, 0, 1, 0);
glutSolidCone(5, 10, 30, 10);
glPopMatrix();
glPopMatrix();
// Cannons
glPushMatrix();
glTranslatef(25, 0, -70);
glRotatef(90, 0, 1, 0);
glScalef(0.25, 0.25, 0.25);
glPushMatrix();
glScalef(0.75, 0.75, 0.75);
glColor3ub(102, 102, 102);
drawCannonBody(0);
glPopMatrix();
glPopMatrix();
glDisable(GL_LIGHTING);
glPushMatrix(); //Draw Shadow Object
glColor3f(0, 0, 0);
glMultMatrixf(shadowMat);
glTranslatef(25, 0, -70);
glRotatef(90, 0, 1, 0);
glScalef(0.25, 0.25, 0.25);
glPushMatrix();
glScalef(0.75, 0.75, 0.75);
drawCannonBody(1);
glPopMatrix();
glPopMatrix();
glEnable(GL_LIGHTING);
glPushMatrix();
glTranslatef(-25, 0, -70);
glRotatef(90, 0, 1, 0);
glScalef(0.25, 0.25, 0.25);
glPushMatrix();
glScalef(0.75, 0.75, 0.75);
glColor3ub(102, 102, 102);
drawCannonBody(0);
glPopMatrix();
glPopMatrix();
glDisable(GL_LIGHTING);
glPushMatrix(); //Draw Shadow Object
glColor3f(0, 0, 0);
glMultMatrixf(shadowMat);
glTranslatef(-25, 0, -70);
glRotatef(90, 0, 1, 0);
glScalef(0.25, 0.25, 0.25);
glPushMatrix();
glScalef(0.75, 0.75, 0.75);
drawCannonBody(1);
glPopMatrix();
glPopMatrix();
glEnable(GL_LIGHTING);
glEnable(GL_TEXTURE_2D);
}
// Drawing the second robot
void drawRobot2()
{
glDisable(GL_TEXTURE_2D);
// Wheel
glPushMatrix();
glColor3f(0, 0, 0);
glTranslatef(0, 2.5, 0);
glutSolidSphere(2.5, 50, 10);
glPopMatrix();
// Base
glPushMatrix();
glColor3f(1, 0, 0);
glTranslatef(0, 20, 0);
glRotatef(90, 1, 0, 0);
glutSolidCone(5, 20, 50, 5);
glPopMatrix();
glEnable(GL_TEXTURE_2D);
// Body
glPushMatrix();
glTranslatef(0, 40, 0);
glRotatef(90, 1, 0, 0);
drawTower(50, 5, 20, 2);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
// Head / Teapot
glPushMatrix();
glTranslatef(0, 43, 0);
glutSolidTeapot(6);
glPopMatrix();
// Eyes
glPushMatrix();
glColor3f(1, 0, 0);
glTranslatef(5, 44, -2);
glutSolidSphere(1, 50, 10);
glPopMatrix();
glPushMatrix();
glColor3f(1, 0, 0);
glTranslatef(5, 44, 2);
glutSolidSphere(1, 50, 10);
glPopMatrix();
// Atenna
glPushMatrix();
glColor3f(0, 1, 0);
glTranslatef(0, 53, 0);
glRotatef(90, 1, 0, 0);
drawTower(50, 0.3, 8, 3);
glPopMatrix();
glPushMatrix();
glColor3f(1, 0, 0);
glTranslatef(0, 53, 0);
glutSolidSphere(1, 50, 10);
glPopMatrix();
glEnable(GL_TEXTURE_2D);
// Arms
// Right
glPushMatrix();
glTranslatef(0, 38, 6);
glRotatef(85, 1, 0, 0);
drawTower(50, 1, 15, 3);
glPopMatrix();
// left
glPushMatrix();
glTranslatef(0, 38, -6);
glRotatef(95, 1, 0, 0);
drawTower(50, 1, 15, 3);
glPopMatrix();
}
// Drawing the alien ship
void drawUfo()
{
float lgt_pos[] = {0., 0., 0.};
float lgt_dir[] = {1., -1., 0.};
float lgt_dir1[] = {-1., -1., 0.};
glDisable(GL_TEXTURE_2D);
glPushMatrix();
glColor3f(0, 1, 0);
glTranslatef(0, shipHeight - 5, 0);
glRotatef(90, 1, 0, 0);
glutSolidCone(100, 15, 50, 10);
glPopMatrix();
glPushMatrix();
glColor3f(1, 0, 0);
glTranslatef(0, shipHeight - 5, 0);
glRotatef(-90, 1, 0, 0);
glutSolidCone(100, 15, 50, 10);
glPopMatrix();
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, texId[1]);
glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
glPushMatrix();
glRotatef(shipChange, 0, 1, 0);
glTranslatef(0, shipHeight, 0);
glLightfv(GL_LIGHT2, GL_POSITION, lgt_pos);
glLightfv(GL_LIGHT2, GL_SPOT_DIRECTION, lgt_dir1);
glLightfv(GL_LIGHT1, GL_POSITION, lgt_pos);
glLightfv(GL_LIGHT1, GL_SPOT_DIRECTION, lgt_dir);
gluSphere(q, 30, 50, 10);
glPopMatrix();
glDisable(GL_TEXTURE_2D);
}
// Drawing the skybox
void skybox(){
glEnable(GL_TEXTURE_2D);
////////////////////// LEFT WALL ///////////////////////
glBindTexture(GL_TEXTURE_2D, texId[4]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glColor3f(1, 1, 1);
glBegin(GL_QUADS);
glTexCoord2f(0., 0.); glVertex3f(-size, 0, size);
glTexCoord2f(1., 0.); glVertex3f(-size, 0., -size);
glTexCoord2f(1., 1.); glVertex3f(-size, size, -size);
glTexCoord2f(0., 1.); glVertex3f(-size, size, size);
glEnd();
////////////////////// FRONT WALL ///////////////////////
glBindTexture(GL_TEXTURE_2D, texId[5]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glColor3f(1, 1, 1);
glBegin(GL_QUADS);
glTexCoord2f(0., 0.); glVertex3f(-size, 0, -size);
glTexCoord2f(1., 0.); glVertex3f(size, 0., -size);
glTexCoord2f(1., 1.); glVertex3f(size, size, -size);
glTexCoord2f(0., 1.); glVertex3f(-size, size, -size);
glEnd();
////////////////////// RIGHT WALL ///////////////////////
glBindTexture(GL_TEXTURE_2D, texId[6]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glColor3f(1, 1, 1);
glBegin(GL_QUADS);
glTexCoord2f(0., 0.); glVertex3f(size, 0, -size);
glTexCoord2f(1., 0.); glVertex3f(size, 0, size);
glTexCoord2f(1., 1.); glVertex3f(size, size, size);
glTexCoord2f(0., 1.); glVertex3f(size, size, -size);
glEnd();
////////////////////// REAR WALL ////////////////////////
glBindTexture(GL_TEXTURE_2D, texId[7]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glColor3f(1, 1, 1);
glBegin(GL_QUADS);
glTexCoord2f(0., 0.); glVertex3f( size, 0, size);
glTexCoord2f(1., 0.); glVertex3f(-size, 0, size);
glTexCoord2f(1., 1.); glVertex3f(-size, size, size);
glTexCoord2f(0., 1.); glVertex3f( size, size, size);
glEnd();
/////////////////////// TOP //////////////////////////
glBindTexture(GL_TEXTURE_2D, texId[8]);
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE);
glColor3f(1, 1, 1);
glBegin(GL_QUADS);
glTexCoord2f(0., 0.); glVertex3f(-size, size, -size);
glTexCoord2f(1., 0.); glVertex3f(size, size, -size);
glTexCoord2f(1., 1.); glVertex3f(size, size, size);
glTexCoord2f(0., 1.); glVertex3f(-size, size, size);
glEnd();
glDisable(GL_TEXTURE_2D);
glPushMatrix();
glScalef(1000, 1000, 1000);
bool flag = false;
glBegin(GL_QUADS);
glNormal3f(0, 1, 0);
for(int x = -400; x <= 400; x += 20)
{
for(int z = -400; z <= 400; z += 20)
{
if(flag) glColor3f(0.6, 1.0, 0.8);
else glColor3f(0.8, 1.0, 0.6);
glVertex3f(x, 0, z);
glVertex3f(x, 0, z+20);
glVertex3f(x+20, 0, z+20);
glVertex3f(x+20, 0, z);
flag = !flag;
}
}
glEnd();
glPopMatrix();
}
// initialising the scene
void initialise(void)
{
float black[4] = {0.0, 0.0, 0.0, 1.0};
float white[4] = {1.0, 1.0, 1.0, 1.0};
float grey[4] = {0.2, 0.2, 0.2, 1.0};
float mat_col[4] = {1.0, 1.0, 0.0, 1.0};
q = gluNewQuadric ( );
loadGLTextures();
loadMeshFile("Cannon.off");
glEnable(GL_DEPTH_TEST);
glEnable(GL_NORMALIZE);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glLightfv(GL_LIGHT0, GL_AMBIENT, grey);
glLightfv(GL_LIGHT0, GL_DIFFUSE, white);
glLightfv(GL_LIGHT0, GL_SPECULAR, white);
glEnable(GL_LIGHT1);
glLightfv(GL_LIGHT1, GL_AMBIENT, black);
glLightfv(GL_LIGHT1, GL_DIFFUSE, white);
glLightfv(GL_LIGHT1, GL_SPECULAR, white);
glLightf(GL_LIGHT1, GL_SPOT_CUTOFF, 90.0);
glLightf(GL_LIGHT1, GL_SPOT_EXPONENT,10.1);
glEnable(GL_LIGHT2);
glLightfv(GL_LIGHT2, GL_AMBIENT, black);
glLightfv(GL_LIGHT2, GL_DIFFUSE, white);
glLightfv(GL_LIGHT2, GL_SPECULAR, white);
glLightf(GL_LIGHT2, GL_SPOT_CUTOFF, 90.0);
glLightf(GL_LIGHT2, GL_SPOT_EXPONENT,10.1);
glEnable(GL_LIGHT3);
glLightfv(GL_LIGHT3, GL_AMBIENT, grey);
glLightfv(GL_LIGHT3, GL_DIFFUSE, white);
glLightfv(GL_LIGHT3, GL_SPECULAR, white);
glLightf(GL_LIGHT3, GL_SPOT_CUTOFF, 90.0);
glLightf(GL_LIGHT3, GL_SPOT_EXPONENT,10.1);
glMaterialfv(GL_FRONT, GL_AMBIENT_AND_DIFFUSE, mat_col);
glMaterialfv(GL_FRONT, GL_SPECULAR, white);
glMaterialf(GL_FRONT, GL_SHININESS, 40);
glEnable(GL_COLOR_MATERIAL);
gluQuadricDrawStyle (q, GLU_FILL );
gluQuadricNormals (q, GLU_SMOOTH );
glEnable(GL_TEXTURE_2D);
gluQuadricTexture (q, GL_TRUE);
glMatrixMode (GL_PROJECTION);
glLoadIdentity ();
gluPerspective(80.0, 1.0, 5000.0, 700000.0); //Perspective projection
}
// Displaying the scene
void display(void)
{
float xlook, zlook, ylook; //TODO look up and down too
float cdr=3.14159265/180.0; //Conversion from degrees to radians
glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
float lgt_pos0[] = {0.0f, 4000.0f, -(size - 8000), 1.0f};
float lgt_pos3[] = {0.0f, 0.0f, 0.0f, 1.0f};
float lgt_dir3[] = {-1., -1., 0.};
float shadowMat[16] = { 80,0,0,0, -80,0,-0,-1,
0,0,80,0, 0,0,0,80 };
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glLightfv(GL_LIGHT0, GL_POSITION, lgt_pos0); //light position
if (changeCamera) {
// TODO Sort this shit out // ask why this is a 350 minimum
gluLookAt(80000, 305 * (shipHeight - 50), -160000, 80000, 0, -160000, 0, 0, 1);
} else {
gluLookAt(eye_x, size/8, eye_z, look_x, size/8, look_z, 0, 1, 0);
}
glRotatef(180, 0, 1, 0);
glPushMatrix();
glTranslatef(-90000, 1000, 160000);
glScalef(1500, 1500, 1500);
drawCastle();
glPopMatrix();
glPushMatrix();
glTranslatef(-80000, 0, 160000);
glScalef(300, 300, 300);
drawUfo();
glPopMatrix();
glDisable(GL_TEXTURE_2D);
glPushMatrix();
glTranslatef(robot_pos[0], robot_pos[1], robot_pos[2]);
glRotatef(robotAngle, 0, 1, 0);
glScalef(4000, 4000, 4000);
drawRobot();
glPopMatrix();
glEnable(GL_TEXTURE_2D);
glPushMatrix();
glTranslatef(robot_1_pos[0], robot_1_pos[1], robot_1_pos[2]);
glRotatef(robotAngle1, 0, 1, 0);
glLightfv(GL_LIGHT3, GL_POSITION, lgt_pos3);
glLightfv(GL_LIGHT3, GL_SPOT_DIRECTION, lgt_dir3);
glScalef(800, 800, 800);
drawRobot2();
glPopMatrix();
skybox();
glutSwapBuffers();
glFlush();
}
// Setting the states of the robots
void setRobotState()
{
if (robotState == 0 && robot_pos[2] <= -126000) {
robotState = 1;
robotAngle += 90;
} else if (robotState == 1 && robot_pos[0] <= -186000) {
robotState = 2;
robotAngle += 90;
} else if (robotState == 2 && robot_pos[2] >= -2000) {
robotState = 3;
robotAngle += 90;
} else if (robotState == 3 && robot_pos[0] >= 0) {
robotState = 0;
robotAngle += 90;
}
if (robotState1 == 0 && robot_1_pos[2] <= -(size - 8000)) {
robotState1 = 1;
robotAngle1 -= 90;
} else if (robotState1 == 1 && robot_1_pos[0] >= (size - 8000)) {
robotState1 = 2;
robotAngle1 -= 90;
} else if (robotState1 == 2 && robot_1_pos[2] >= (size - 8000)) {
robotState1 = 3;
robotAngle1 -= 90;
} else if (robotState1 == 3 && robot_1_pos[0] <= -(size - 8000)) {
robotState1 = 0;
robotAngle1 -= 90;
}
}
// Timer function to handle animation within the scene
void timmerFunc(int val) {
if (shipLaunched) {
shipHeight += 5;
shipChange += 10;
} else {
if (shipUp) {
shipHeight += 0.75;
if (shipHeight >= 450) {
shipUp = false;
}
} else {
shipHeight -= 0.75;
if (shipHeight <= 350) {
shipUp = true;
}
}
shipChange += 2.5;
}
if (shipHeight >= 1200) {
changeCamera = false;
}
if (val == 1) {
theta += 1;
if (theta >= 20) {
theta = 20;
val = 0;
}
} else {
theta -= 1;
if (theta <= -20) {
theta = -20;
val = 1;
}
}
if (doorOut) {
doorAngle += 1;
if (doorAngle >= 85) {
doorOut = false;
}
} else {
doorAngle -= 1;
if (doorAngle <= 0) {
doorOut = true;
}
}
lightAngle ++;
if(lightAngle > 360) lightAngle = 0;
if (fireCannon) {
if (raiseCannon) {
cannonAngle += 1;
if (cannonAngle >= 50) {
raiseCannon = false;
}
} else {
showBallFront = true;
float time = 0.05 * cannonCount;
ball_pos[0] = cannonVelocity * time * cos(cannonRadians) + 26.88;
ball_pos[1] = -0.5 * gravAccel * pow(time, 2) + cannonVelocity * time * sin(cannonRadians) + 84;
cannonCount++;
if (ball_pos[1] <= 0) {
fireCannon = false;
}
}
}
if (robotState1 == 0) {
robot_1_pos[2] -= 4000;
} else if (robotState1 == 1) {
robot_1_pos[0] += 4000;
} else if (robotState1 == 2) {
robot_1_pos[2] += 4000;
} else if (robotState1 == 3) {
robot_1_pos[0] -= 4000;
}
if (robotState == 0) {
robot_pos[2] -= 2000;
} else if (robotState == 1) {
robot_pos[0] -= 2000;
} else if (robotState == 2) {
robot_pos[2] += 2000;
} else if (robotState == 3) {
robot_pos[0] += 2000;
}
setRobotState();
glutTimerFunc(50, timmerFunc, val);
glutPostRedisplay();
}
//hanlding keys presses
void keys(unsigned char key_t, int x, int y)
{
if (key_t == 115) {
shipLaunched = true;
}
if (key_t == 99) {
fireCannon = true;
}
}
// Handling special key presses
void special(int key, int x, int y)
{
float start_x = eye_x;
float start_z = eye_z;
if(key == GLUT_KEY_LEFT) angle -= 0.1; //Change direction
else if(key == GLUT_KEY_RIGHT) angle += 0.1;
else if(key == GLUT_KEY_DOWN)
{ // Move backward
eye_x -= 5000*sin(angle);
eye_z += 5000*cos(angle);
}
else if(key == GLUT_KEY_UP)
{ // Move forward
eye_x += 5000*sin(angle);
eye_z -= 5000*cos(angle);
}
// Bounding box within the sky box
if (eye_x >= 170000 || eye_x <= -170000) {
eye_x = start_x;
}
if (eye_z >= 170000 || eye_z <= -170000) {
eye_z = start_z;
}
if (key == GLUT_KEY_HOME)
{
changeCamera = !changeCamera;
}
look_x = eye_x + 100*sin(angle);
look_z = eye_z - 100*cos(angle);
glutPostRedisplay();
}
// Starting the scene
int main(int argc, char** argv)
{
glutInit(&argc, argv);
glutInitDisplayMode (GLUT_DOUBLE | GLUT_DEPTH );
glutInitWindowSize (700, 700);
glutInitWindowPosition (50, 50);
glutCreateWindow ("Assigment 1");
initialise();
glutDisplayFunc(display);
glutSpecialFunc(special);
glutKeyboardFunc(keys);
glutTimerFunc(50, timmerFunc, 1);
glutMainLoop();
return 0;
}
| [
"ajl190@uclive.ac.nz"
] | ajl190@uclive.ac.nz |
b681d352223786663e19dd652b62658d75cc9210 | 1efed76acf602d77073cbb2356ccd5c56d8f48b6 | /src/MotionControl.cpp | 9a28d869a193095e6742582024ece17e72ace0db | [] | no_license | KITmedical/viky | 4c42a16a3cb1625ddd753ac5730f85954b53b0f3 | 26f07c67bca007483ebfb6c4d5cb81ff9e44e891 | refs/heads/master | 2020-12-25T12:28:30.817946 | 2015-03-03T13:20:16 | 2015-03-03T13:20:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,647 | cpp | #include "MotionControl.h"
// system includes
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <err.h>
#include <stdexcept>
#include <sys/ioctl.h>
// library includes
#include <ahbstring.h>
// custom includes
/*---------------------------------- public: -----------------------------{{{-*/
const RegisterBits<uint16_t> MotionControl::CST_ANSW_Bits = RegisterBits<uint16_t>(1, 2);
const RegisterBits<uint16_t> MotionControl::CST_SOR_Bits = RegisterBits<uint16_t>(3, 5);
const RegisterBits<uint16_t> MotionControl::CST_MOD_Bits = RegisterBits<uint16_t>(7, 9);
const RegisterBits<uint16_t> MotionControl::CST_EN_Bits = RegisterBits<uint16_t>(10, 10);
const RegisterBits<uint16_t> MotionControl::CST_PR_Bits = RegisterBits<uint16_t>(11, 11);
const RegisterBits<uint16_t> MotionControl::CST_ADIR_Bits = RegisterBits<uint16_t>(12, 12);
const RegisterBits<uint16_t> MotionControl::CST_APL_Bits = RegisterBits<uint16_t>(13, 13);
const RegisterBits<uint16_t> MotionControl::CST_SIN_Bits = RegisterBits<uint16_t>(14, 14);
const RegisterBits<uint16_t> MotionControl::CST_NET_Bits = RegisterBits<uint16_t>(15, 15);
const RegisterBits<uint16_t> MotionControl::OST_Homing_Bits = RegisterBits<uint16_t>(0, 0);
const RegisterBits<uint16_t> MotionControl::OST_ProgRunning_Bits = RegisterBits<uint16_t>(1, 1);
const RegisterBits<uint16_t> MotionControl::OST_ProgStopDelay_Bits = RegisterBits<uint16_t>(2, 2);
const RegisterBits<uint16_t> MotionControl::OST_ProgStopNotify_Bits = RegisterBits<uint16_t>(3, 3);
const RegisterBits<uint16_t> MotionControl::OST_CurrentLimit_Bits = RegisterBits<uint16_t>(4, 4);
const RegisterBits<uint16_t> MotionControl::OST_DeviationError_Bits = RegisterBits<uint16_t>(5, 5);
const RegisterBits<uint16_t> MotionControl::OST_OverVolt_Bits = RegisterBits<uint16_t>(6, 6);
const RegisterBits<uint16_t> MotionControl::OST_OverTemp_Bits = RegisterBits<uint16_t>(7, 7);
const RegisterBits<uint16_t> MotionControl::OST_StatusInput_Bits = RegisterBits<uint16_t>(8, 12);
const RegisterBits<uint16_t> MotionControl::OST_PosReached_Bits = RegisterBits<uint16_t>(16, 16);
const RegisterBits<uint16_t> MotionControl::OST_LimitToContCurrent_Bits = RegisterBits<uint16_t>(17, 17);
MotionControl::MotionControl(int p_motorID, const std::string& p_ttyDevicePath)
:m_motorID(p_motorID),
m_ttyDevicePath(p_ttyDevicePath),
m_ttyFD(-1),
m_initialized(false)
{
}
bool
MotionControl::init()
{
m_ttyFD = open(m_ttyDevicePath.c_str(), O_RDWR);
if (m_ttyFD == -1) {
warn("motor%d: Failed to open() tty=%s", m_motorID, m_ttyDevicePath.c_str());
return false;
}
struct termios ttyOptions;
tcgetattr(m_ttyFD, &ttyOptions);
cfsetispeed(&ttyOptions, baudrate);
cfsetospeed(&ttyOptions, baudrate);
ttyOptions.c_iflag &= ~(IXON | IXOFF | IXANY); // no HW flow control
ttyOptions.c_iflag &= ~(IGNCR | INLCR | ICRNL); // input: do not modify '\n' and '\r'
ttyOptions.c_oflag &= ~(ONLCR | OCRNL | ONLRET | ONOCR); // output: do not modify '\n' and '\r'
ttyOptions.c_cflag &= ~(PARENB | CSTOPB); // no parity; 1 stop bit
ttyOptions.c_lflag |= ICANON;
if (tcsetattr(m_ttyFD, TCSANOW, &ttyOptions) != 0) {
warn("motor%d: Failed to tcsetattr()", m_motorID);
return false;
}
sendCmd("ANSW0");
sendCmd("CONTMOD");
sendCmd("ENCRES1000");
sendCmd("KN1506");
sendCmd("RM3400");
sendCmd("SP1500");
sendCmd("AC1500");
sendCmd("DEC1500");
sendCmd("DEV100");
sendCmd("DCE20");
sendCmd("EN");
m_initialized = true;
sendCmd("GTYP");
printf("Controller: %s\n", getReply().c_str());
printf("Status: %s\n", getConfigurationStatus().c_str());
return true;
}
bool
MotionControl::initialized()
{
return m_initialized;
}
void
MotionControl::sendCmd(const std::string& p_cmd)
{
std::string cmd = p_cmd;
if (cmd[cmd.size() - 1] != '\r') {
cmd += '\r';
}
//printf("motor%d: sendCmd (len=%zd): \"%s\"\n", m_motorID, cmd.size(), cmd.c_str());
size_t bytesWritten;
if ((bytesWritten = write(m_ttyFD, cmd.c_str(), cmd.size())) != cmd.size()) {
throw std::runtime_error("Short write to motor");
}
}
std::string
MotionControl::getReply()
{
failOnUnitialized("getReply()");
char replyChars[maxReplySize];
int replyLength = read(m_ttyFD, replyChars, maxReplySize);
replyChars[replyLength] = '\0';
//printf("getReply() raw: %s=\"%s\"\n", ahb::string::toHexString(replyChars).c_str(), replyChars);
if (replyLength < 3 || replyChars[replyLength - 2] != '\r' || replyChars[replyLength - 1] != '\n') {
replyLength = 0;
} else {
replyLength = replyLength - 2; // strip "\r\n"
}
return std::string(replyChars, replyLength);
}
std::string
MotionControl::getReplyNoBlock()
{
failOnUnitialized("getReplyNoBlock()");
int replyBytesAvailable;
ioctl(m_ttyFD, FIONREAD, &replyBytesAvailable);
if (replyBytesAvailable == 0) {
return std::string();
}
return getReply();
}
std::string
MotionControl::getReplyWait(int p_waitMaxMS)
{
failOnUnitialized("getReplyWait()");
int waitDuration = 1;
int waitMaxPeriods = p_waitMaxMS / waitDuration;
for (int waitPeriods = 0; waitPeriods < waitMaxPeriods; waitPeriods++) {
std::string reply = getReplyNoBlock();
if (!reply.empty()) {
return reply;
}
usleep(waitDuration * 1000);
}
return std::string();
}
std::string
MotionControl::getConfigurationStatus()
{
boost::lock_guard<boost::mutex> ttyLock(m_ttyMutex);
sendCmd("CST");
std::string replyStr = getReply();
uint16_t reply = ahb::string::toNumberSlow<uint16_t>(replyStr);
std::string cst;
cst += "ANSW=" + ahb::string::toString(CST_ANSW_Bits.getVal(reply));
cst += " SOR=" + ahb::string::toString(CST_SOR_Bits.getVal(reply));
cst += " MOD=" + ahb::string::toString(CST_MOD_Bits.getVal(reply));
cst += " EN=" + ahb::string::toString(CST_EN_Bits.getVal(reply));
cst += " PR=" + ahb::string::toString(CST_PR_Bits.getVal(reply));
cst += " ADIR=" + ahb::string::toString(CST_ADIR_Bits.getVal(reply));
cst += " APL=" + ahb::string::toString(CST_APL_Bits.getVal(reply));
cst += " SIN=" + ahb::string::toString(CST_SIN_Bits.getVal(reply));
cst += " NET=" + ahb::string::toString(CST_NET_Bits.getVal(reply));
return cst;
}
std::string
MotionControl::getOperationStatus()
{
boost::lock_guard<boost::mutex> ttyLock(m_ttyMutex);
sendCmd("OST");
std::string replyStr = getReply();
uint32_t reply = ahb::string::toNumberSlow<uint32_t>(replyStr);
std::string ost;
ost += "Homing=" + ahb::string::toString(OST_Homing_Bits.getVal(reply));
ost += " ProgRunning=" + ahb::string::toString(OST_ProgRunning_Bits.getVal(reply));
ost += " ProgStopDelay=" + ahb::string::toString(OST_ProgStopDelay_Bits.getVal(reply));
ost += " ProgStopNotify=" + ahb::string::toString(OST_ProgStopNotify_Bits.getVal(reply));
ost += " CurrentLimit=" + ahb::string::toString(OST_CurrentLimit_Bits.getVal(reply));
ost += " DeviationError=" + ahb::string::toString(OST_DeviationError_Bits.getVal(reply));
ost += " OverVolt=" + ahb::string::toString(OST_OverVolt_Bits.getVal(reply));
ost += " OverTemp=" + ahb::string::toString(OST_OverTemp_Bits.getVal(reply));
ost += " StatusInput=" + ahb::string::toString(OST_StatusInput_Bits.getVal(reply));
ost += " PosReached=" + ahb::string::toString(OST_PosReached_Bits.getVal(reply));
ost += " LimitToContCurrent=" + ahb::string::toString(OST_LimitToContCurrent_Bits.getVal(reply));
return ost;
}
uint64_t
MotionControl::getPos()
{
boost::lock_guard<boost::mutex> ttyLock(m_ttyMutex);
sendCmd("POS");
std::string replyStr = getReply();
return ahb::string::toNumberSlow<uint64_t>(replyStr);
}
void
MotionControl::movePos(int64_t pos)
{
boost::lock_guard<boost::mutex> ttyLock(m_ttyMutex);
//printf("motor%d: movePos(%ld)\n", m_motorID, pos);
sendCmd("LA" + ahb::string::toString(pos));
sendCmd("M");
}
void
MotionControl::moveStop()
{
boost::lock_guard<boost::mutex> ttyLock(m_ttyMutex);
sendCmd("V0");
}
int
MotionControl::getCurrent()
{
boost::lock_guard<boost::mutex> ttyLock(m_ttyMutex);
sendCmd("GRC");
std::string replyStr = getReply();
return ahb::string::toNumberSlow<int>(replyStr);
}
bool
MotionControl::homing(int8_t dir)
{
//printf("Starting homing\n");
sendCmd("V" + ahb::string::toString(dir * 100));
for (unsigned measurementCnt = 0; measurementCnt < homingMeasurementMaxCnt; measurementCnt++) {
int current = getCurrent();
//printf("current=%d\n", current);
if (current >= homingCurrentThreshold) {
moveStop();
setHomePosition();
movePos(-1 * dir * 1000);
usleep(500 * 1000);
setHomePosition();
return true;
}
}
return false;
}
void
MotionControl::enableMotor()
{
boost::lock_guard<boost::mutex> ttyLock(m_ttyMutex);
sendCmd("EN");
}
void
MotionControl::disableMotor()
{
boost::lock_guard<boost::mutex> ttyLock(m_ttyMutex);
sendCmd("DI");
}
void
MotionControl::setHomePosition()
{
boost::lock_guard<boost::mutex> ttyLock(m_ttyMutex);
sendCmd("HO");
}
/*------------------------------------------------------------------------}}}-*/
/*---------------------------------- private: ----------------------------{{{-*/
void
MotionControl::failOnUnitialized(const std::string& p_errorMsg)
{
if (!initialized()) {
throw std::runtime_error("motor" + ahb::string::toString(m_motorID) + " not initialized: " + p_errorMsg);
}
}
void
MotionControl::resetMotor()
{
boost::lock_guard<boost::mutex> ttyLock(m_ttyMutex);
sendCmd("RESET");
}
/*------------------------------------------------------------------------}}}-*/
| [
"andreas.bihlmaier@gmx.de"
] | andreas.bihlmaier@gmx.de |
c6393dd3beb38b33262320bcd79de10c1e3b4993 | 4ffca8ba04cf99773e14ba3ce82d8bd80bbb3d27 | /toolkits/graphical_models/deprecated/gibbs_sampling/sampler.cpp | 67bab620f46b3adde8a7d2399f76f007240e6144 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | lqhl/PowerWalk | 3f491dd42d16988b97f7b08dc0fef49b7496ce0f | 36aeeaeaa4eb44c76ab9633ace27972260cc098f | refs/heads/master | 2020-12-28T08:30:01.070302 | 2017-01-03T05:28:24 | 2017-01-03T05:28:30 | 38,031,557 | 16 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 6,759 | cpp | /**
* Copyright (c) 2009 Carnegie Mellon University.
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an "AS
* IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*
*
*/
/**
*
* This program runs the various gibbs samplers
*
* \author Joseph Gonzalez
*/
// INCLUDES ===================================================================>
// Including Standard Libraries
#include <ctime>
#include <cstdlib>
#include <cassert>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <sstream>
#include <vector>
#include <queue>
#include <stack>
#include <string>
#include <set>
#include <algorithm>
#include <limits>
#include <cmath>
#include <boost/program_options.hpp>
#include <boost/bind.hpp>
#include <graphlab.hpp>
// Image reading/writing code
#include "util.hpp"
#include "factorized_model.hpp"
#include "mrf.hpp"
#include "junction_tree.hpp"
#include "chromatic_sampler.hpp"
#include "jt_splash_sampler.hpp"
#include "global_variables.hpp"
// Include the macro for the foreach operation
#include <graphlab/macros_def.hpp>
// Results files =============================================================>
const std::string chromatic_results_fn = "chromatic_results.tsv";
const std::string async_results_fn = "async_results.tsv";
const std::string splash_results_fn = "splash_results.tsv";
const std::string jtsplash_results_fn = "jtsplash_results.tsv";
// Command Line Arguments ====================================================>
std::string model_filename;
std::string experiment_type = "chromatic";
std::vector<double> runtimes(1, 10);
bool draw_images = false;
size_t treesize = 1000;
size_t treewidth = 3;
size_t treeheight = std::numeric_limits<size_t>::max();
size_t factorsize = std::numeric_limits<size_t>::max();
size_t subthreads = 1;
bool priorities = false;
// MAIN =======================================================================>
int main(int argc, char** argv) {
// set the global logger
global_logger().set_log_level(LOG_WARNING);
global_logger().set_log_to_console(true);
// std::srand ( graphlab::timer::usec_of_day() );
// graphlab::random::seed();
// Parse command line arguments --------------------------------------------->
graphlab::command_line_options clopts;
clopts.attach_option("model",
&model_filename, model_filename,
"model file name");
clopts.add_positional("model");
clopts.attach_option("experiment",
&experiment_type, experiment_type,
"the type of experiment to run "
"{chromatic, jtsplash}");
clopts.add_positional("experiment");
clopts.attach_option("runtimes",
&runtimes, runtimes,
"total runtime in seconds");
clopts.attach_option("draw_images",
&draw_images, draw_images,
"draw pictures (assume sqrt(numvert) rows)");
clopts.attach_option("treesize",
&treesize, treesize,
"The maximum number of variables in a junction tree");
clopts.attach_option("treewidth",
&treewidth, treewidth,
"The maximum treewidth.");
clopts.attach_option("treeheight",
&treeheight, treeheight,
"The maximum height of the trees. ");
clopts.attach_option("factorsize",
&factorsize, factorsize,
"The maximum factorsize");
clopts.attach_option("subthreads",
&subthreads, subthreads,
"The number of threads to use inside each tree "
"(zero means not used)");
clopts.attach_option("priorities",
&priorities, priorities,
"Use priorities?");
// Set defaults for scope and scheduler
clopts.set_scheduler_type("fifo");
clopts.set_scope_type("edge");
if( !clopts.parse(argc, argv) ) {
std::cout << "Error parsing command line arguments!"
<< std::endl;
return EXIT_FAILURE;
}
std::cout << "Application Options" << std::endl;
std::cout
<< "model: " << model_filename << std::endl
<< "experiment: " << experiment_type << std::endl
<< "runtime: "
<< boost::lexical_cast<std::string>(runtimes) << std::endl;
std::cout << "Graphlab Options" << std::endl;
clopts.print();
// create model filename
std::cout << "Load alchemy file." << std::endl;
factorized_model factor_graph;
factor_graph.load_alchemy(model_filename);
// Set the global factors
//SHARED_FACTORS.set(factor_graph.factors());
SHARED_FACTORS_PTR = &(factor_graph.factors());
std::cout << "Building graphlab MRF GraphLab core." << std::endl;
mrf_gl::core mrf_core;
mrf_from_factorized_model(factor_graph, mrf_core.graph());
mrf_core.set_engine_options(clopts);
std::cout << "Computing coloring." << std::endl;
size_t colors = mrf_core.graph().compute_coloring();
std::cout << "Colors: " << colors << std::endl;
// Create synthetic images -------------------------------------------------->
if(experiment_type == "chromatic") {
run_chromatic_sampler(mrf_core,
chromatic_results_fn,
runtimes,
draw_images);
} if(experiment_type == "jtsplash") {
splash_settings settings;
settings.ntrees = mrf_core.get_engine_options().get_ncpus();
settings.max_tree_size = treesize;
settings.max_tree_height = treeheight;
settings.max_tree_width = treewidth;
settings.max_tree_height = treeheight;
settings.priorities = priorities;
settings.subthreads = subthreads;
run_jtsplash_sampler(mrf_core.graph(),
jtsplash_results_fn,
runtimes,
draw_images,
settings);
} else {
std::cout << "Invalid experiment type!" << std::endl;
return EXIT_FAILURE;
}
std::cout << "Done!" << std::endl;
return EXIT_SUCCESS;
} // End of main
#include <graphlab/macros_undef.hpp>
| [
"joseph.e.gonzalez@gmail.com"
] | joseph.e.gonzalez@gmail.com |
179a28413a4f38e4d5837178c200aaa74bd23756 | 12d83468a3544af4e9d4f26711db1755d53838d6 | /cplusplus_basic/Qt/boost/mpl/list/aux_/push_back.hpp | 07064b948913efe361dc923833a0967744c010d1 | [] | no_license | ngzHappy/cxx17 | 5e06a31d127b873355cab3a8fe0524f1223715da | 22d3f55bfe2a9ba300bbb65cfcbdd2dc58150ca4 | refs/heads/master | 2021-01-11T20:48:19.107618 | 2017-01-17T17:29:16 | 2017-01-17T17:29:16 | 79,188,658 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 793 | hpp |
#ifndef BOOST_MPL_LIST_AUX_PUSH_BACK_HPP_INCLUDED
#define BOOST_MPL_LIST_AUX_PUSH_BACK_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#include <Qt/boost/mpl/push_back_fwd.hpp>
#include <Qt/boost/mpl/bool.hpp>
#include <Qt/boost/mpl/list/aux_/tag.hpp>
namespace boost { namespace mpl {
template< typename Tag > struct has_push_back_impl;
template<>
struct has_push_back_impl< aux::list_tag >
{
template< typename Seq > struct apply
: false_
{
};
};
}}
#endif // BOOST_MPL_LIST_AUX_PUSH_BACK_HPP_INCLUDED
| [
"819869472@qq.com"
] | 819869472@qq.com |
881428cfca9b485e46ee8dd6f81e9b82bfe9ba4c | e955145c9892970e1db3b51c1f1807f1fb8afd90 | /mycoppelia/src/simdemo.cpp | e6ec1f731a7352ded3ab9cd310005d77a72d167a | [] | no_license | 0000duck/CoppeliaRobotics | f04256c4591d7d6a1403261b3effd6dfce8cef3c | 6fb73679fde8dc6c876a20f1541c95646f1ec33c | refs/heads/master | 2023-01-24T12:52:51.825472 | 2020-11-23T02:58:45 | 2020-11-23T02:58:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,769 | cpp | #include <ros/ros.h>
#include <stdio.h>
#include <stdlib.h>
#define _USE_MATH_DEFINES
#include <math.h>
#define NON_MATLAB_PARSING
#define MAX_EXT_API_CONNECTIONS 255
extern "C" {
#include "../../programming/remoteApi/extApi.h"
#ifdef _Included_extApiJava
#include "extApiJava.h"
#endif
}
class Sim_client{
private:
ros::NodeHandle nh;
int _clientID = -1; // ID格納用変数
int ID ; // ID格納用変数
int _portNb = 19999; // 使用するポートの番号.V-REP側と合わせる
public:
Sim_client();
~Sim_client();
void conect_server();
};
Sim_client::Sim_client(){
}
Sim_client::~Sim_client(){
simxFinish(_clientID);
}
void Sim_client::conect_server(){
// サーバーと接続されるまで繰り返す
while (_clientID == -1) {
ROS_INFO_STREAM(_clientID<<"notconecting");
//_clientID = simxStart((simxChar*)"127.0.0.1", _portNb, true, true, 2000, 5);
_clientID = simxStart((simxChar*)"192.168.11.38", _portNb, true, true, 2000, 5);
}
this->ID = _clientID;
ROS_INFO_STREAM("conecting clientID:"<<_clientID);
}
int main(int argc, char** argv) {
ros::init (argc, argv, "img_detect");
Sim_client client ;
ros::Rate loop(10);
int time_ms = 0; // シミュレーション時間
int Joint_handle; // 関節のハンドル格納用変数
while(ros::ok()){
client.conect_server();
}
return 0;
}
/*
simxGetObjectHandle(_clientID, "Joint1", &Joint_handle, simx_opmode_blocking); // ジョイントのハンドルを取得
while (simxGetConnectionId(_clientID) != -1) {
simxSetJointTargetPosition(_clientID, Joint_handle, 45.0*M_PI / 180.0 * sin(2.0*M_PI*time_ms/1000.0), simx_opmode_oneshot); // ジョイントの角度の目標値を設定
time_ms += 10;
extApi_sleepMs(10);
}
*/
| [
"taisuke.march4@icloud.com"
] | taisuke.march4@icloud.com |
adbe47f56893b76d9b12f42864b4643ca55d8f13 | b0ac4ed4d3130712afeac22219fc94da7309ea80 | /src/demo_data.cpp | 86b32d473b0025ae0143402cc456669c09a94607 | [] | no_license | hotTeaFun/sync_epoll_client | af46cd934bdf02c43fee6c620eb5a26e09d3b7a8 | b356b509a42500dc5c77791f587200a0f1f20163 | refs/heads/master | 2023-08-12T05:27:43.555513 | 2021-10-08T10:05:52 | 2021-10-08T10:05:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,336 | cpp | #include "demo_data.h"
DemoData::DemoData() { this->header.type = data_invalid; }
DemoData::DemoData(DataType type) { this->header.type = type; }
DemoData::DemoData(DataType type, std::string content) {
this->header.type = type;
this->body.content = content;
}
DemoData::DemoData(DataType type, std::string timestamp, std::string content) {
this->header.type = type;
this->header.timestamp = timestamp;
this->body.content = content;
}
/// Layout: type(1 char) nTimestamp(int64_t) timestamp() content
DemoData::DemoData(std::string source) {
if (source == "")
this->header.type = data_invalid;
else {
this->header.type = factory.charTo<DataType>(source[0]);
int nTimeStamp = factory.charTo<int>(source[1]);
this->header.timestamp = source.substr(2, nTimeStamp);
this->body.content = source.substr(2 + nTimeStamp);
}
}
std::string DemoData::toStr() const {
return std::string(1, factory.toChar(header.type)) +
std::string(1, factory.toChar(header.timestamp.size())) +
header.timestamp + body.content;
}
long long DemoData::getSize() const {
return 2 + header.timestamp.size() + body.content.size();
}
bool DemoData::isNull() const { return header.type == data_invalid; }
DataHeader DemoData::getHeader() const { return header; }
DataBody DemoData::getBody() const { return body; } | [
"1767230254@qq.com"
] | 1767230254@qq.com |
5a8cbdc4c9b69618a6f22c2a9bf87e357413a59b | 5bfd135b7b3312a8ca476c7acbc3bc10d4590845 | /Arkanoid/Arkanoid/common.cpp | 263a1aa504144ac1fb06e53dca1c2bfa5bba9ea8 | [] | no_license | fdq09eca/cpp_study | c8a2d817d6371810d4b13e3ee42d57d1285cf2cb | 8baa8766a7fccaef413eed5b5a52191be676a38d | refs/heads/master | 2023-07-10T00:50:57.067898 | 2023-07-04T22:47:23 | 2023-07-04T22:47:23 | 338,491,323 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,457 | cpp | //
// common.cpp
// Arkanoid
//
// Created by ChrisLam on 22/03/2021.
//
#include "common.hpp"
SDL_Renderer* g_renderer = nullptr;
Point::Point(float x_, float y_):x(x_), y(y_){};
float Point::distance(const Point& p) const {
float dx = x - p.x;
float dy = y - p.y;
return sqrt(dx * dx + dy * dy);
}
bool Point::is_between(const Point& p1, const Point& p2) const {
return fabs(p1.distance(p2) - distance(p1) - distance(p2)) < FLT_EPSILON;
}
Line::Line(const Point& p1_, const Point& p2_): p1(p1_), p2(p2_) {
float dy = p2.y - p1.y;
float dx = p2.x - p1.x;
slope = dy / dx;
c = - slope * p1.x + p1.y;
}
bool Line::intersection(const Line& l, Point& interscetion) const{
float x1 = p1.x; float y1 = p1.y;
float x2 = p2.x; float y2 = p2.y;
float x3 = l.p1.x; float y3 = l.p1.y;
float x4 = l.p2.x; float y4 = l.p2.y;
float denom = (y4 - y3) * (x2 - x1) - (x4 - x3) * (y2 - y1);
float numer_a = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3);
float numer_b = (x2 - x1) * (y1 - y3) - (y2 - y1) * (x1 - x3);
bool parallel = float_eq(denom, 0.0f);
bool coincident = float_eq(numer_a, 0.0f) && float_eq(numer_b, 0.0f) && float_eq(denom, 0.0f);
if (parallel) return false;
if (coincident) {
interscetion.x = (x1 + x2) / 2;
interscetion.y = (y1 + y2) / 2;
return true;
}
float u_a = numer_a / denom;
float u_b = numer_b / denom;
bool out_of_range = u_a < 0 || u_a > 1 || u_b < 0 || u_b > 1;
if (out_of_range) return false;
interscetion.x = x1 + u_a * (x2 - x1);
interscetion.y = y1 + u_a * (y2 - y1);
return true;
};
void Numbers::draw(int n, Point pos, int cell_size, SDL_Color color) {
assert( n>= 0 && n < N);
for (int y = 0; y < H ; y++) {
for (int x = 0; x < W ; x++) {
const int& i = data[n][y][x];
if (!i) continue;
SDL_Rect rect = {(int) pos.x + x * cell_size, (int) pos.y + y * cell_size, cell_size, cell_size};
SDL_SetRenderDrawColor(g_renderer, color.r, color.g, color.b, color.a);
SDL_RenderFillRect(g_renderer, &rect);
SDL_RenderDrawRect(g_renderer, &rect);
}
}
}
ScoreBoard::ScoreBoard(int score_, int x, int y):pos(x, y), score(score_){
for (int i = 0; i < board_size; i++) {
board[i] = 0;
}
}
void ScoreBoard::set_board_max() {
for (int i = 0 ; i < board_size;i++) {
board[i] = 9;
}
}
void ScoreBoard::write() {
int s = score;
for (int i = 0; i < board_size; i++) {
board[i] = s % 10;
s /= 10;
}
}
int ScoreBoard::max_score() {
return pow(10, board_size) - 1;
}
void Drawer::draw(ScoreBoard& sb) {
sb.score >= sb.max_score()? sb.set_board_max() : sb.write();
Point p = sb.pos;
for (int i = 0; i < sb.board_size; i++) {
int n = sb.board[sb.board_size - i - 1];
sb.num.draw(n, p);
p.x += sb.num.next_num_x;
}
}
void Drawer::draw(const Point& p, int size) {
SDL_Rect rect = {(int) p.x, (int) p.y, size, size};
SDL_SetRenderDrawColor(g_renderer, 255/2, 255/2, 0, 255);
SDL_RenderFillRect(g_renderer, &rect);
}
void Drawer::draw(const Line& l) {
SDL_SetRenderDrawColor(g_renderer, 255, 0, 0, 255);
SDL_RenderDrawLine(g_renderer, (int) l.p1.x, (int) l.p1.y, (int) l.p2.x, (int) l.p2.y);
}
| [
"fdq09eca@gmail.com"
] | fdq09eca@gmail.com |
3fd14abf46d0979994e77a46d65a4313d655c57b | 5336d19e8dfbbe6a22eb3b915265b332ad7f0f88 | /LeetCode/0097_Interleaving_String_Medium/0097_Interleaving_String_Medium_01.cpp | 8bdf29856d316e7e51697119ab14a5151080fe4f | [] | no_license | kaichenhong/Coding_Practice | 84d0a7b1984469a664bb0c3d07ddd59e2a61019e | fd5bd9bb18581bad497b35255c1d7ed31c6d8e46 | refs/heads/master | 2023-08-21T22:23:25.897502 | 2023-08-21T17:02:27 | 2023-08-21T17:02:27 | 204,305,360 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,501 | cpp | /*
* Results: AC (0 ms [100.00%]; 7.1 MB [57.86%])
*/
// #define TLE
#ifndef TLE
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
dp.resize(s1.size(), vector<int>(s2.size(), -1));
return dfs(0, 0, 0, s1, s2, s3);
}
private:
bool dfs(const int idx1, const int idx2, const int idx3, const string &s1, const string &s2, const string &s3) {
if (idx3 >= s3.size()) {
// printf("s1[%d], s2[%d], s3[%d], END!\n", idx1, idx2, idx3);
return (idx1 == s1.size() && idx2 == s2.size()) ? true : false;
}
if (idx1 < s1.size() && idx2 < s2.size() && dp.at(idx1).at(idx2) != -1) {
// printf("s1[%d], s2[%d], s3[%d] => in dp\n", idx1, idx2, idx3);
return dp.at(idx1).at(idx2);
}
// printf("s1[%d], s2[%d], s3[%d]\n", idx1, idx2, idx3);
if ((idx1 < s1.size() && s1.at(idx1) == s3.at(idx3))
&& (idx2 < s2.size() && s2.at(idx2) == s3.at(idx3))) {
return dp.at(idx1).at(idx2) =
(dfs(idx1+1, idx2, idx3+1, s1, s2, s3) ||
dfs(idx1, idx2+1, idx3+1, s1, s2, s3));
} else {
if (idx1 < s1.size() && s1.at(idx1) == s3.at(idx3))
return dfs(idx1+1, idx2, idx3+1, s1, s2, s3);
if (idx2 < s2.size() && s2.at(idx2) == s3.at(idx3))
return dfs(idx1, idx2+1, idx3+1, s1, s2, s3);
}
return false;
}
vector<vector<int>> dp;
};
#else
class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
return dfs(0, 0, 0, s1, s2, s3);
}
private:
bool dfs(const int idx1, const int idx2, const int idx3, const string &s1, const string &s2, const string &s3) {
// printf("s1[%d], s2[%d], s3[%d]\n", idx1, idx2, idx3);
if (idx3 >= s3.size())
return (idx1 == s1.size() && idx2 == s2.size()) ? true : false;
if ((idx1 < s1.size() && s1.at(idx1) == s3.at(idx3))
&& (idx2 < s2.size() && s2.at(idx2) == s3.at(idx3))) {
return (dfs(idx1+1, idx2, idx3+1, s1, s2, s3) ||
dfs(idx1, idx2+1, idx3+1, s1, s2, s3));
} else {
if (idx1 < s1.size() && s1.at(idx1) == s3.at(idx3))
return dfs(idx1+1, idx2, idx3+1, s1, s2, s3);
if (idx2 < s2.size() && s2.at(idx2) == s3.at(idx3))
return dfs(idx1, idx2+1, idx3+1, s1, s2, s3);
}
return false;
}
};
#endif
| [
"kaichenhong@gmail.com"
] | kaichenhong@gmail.com |
2e45d17d4341a491b831adaabe032ebfa0127f20 | fdaa86ee590e5a097b5d9bcb6c2ea9f065d21c83 | /dtn_agent/oasys-1.4.0/thread/Atomic-mips.h | fe904bf2f72ef7ffe16d9bd0facf771a7f611708 | [
"Apache-2.0"
] | permissive | vshirikian/cmusv-dtn | 58ebaf61fe34e866440b0bb48fb5bc3f807bdc3e | a8c9ee90c804567edf62b98971124715baa4c7f6 | refs/heads/master | 2021-01-22T05:10:07.109160 | 2011-04-13T08:33:17 | 2011-04-13T08:33:17 | 1,290,466 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,451 | h | /*
* Copyright 2004-2006 Intel Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef _OASYS_ATOMIC_MIPS_H_
#define _OASYS_ATOMIC_MIPS_H_
namespace oasys {
/**
* The definition of atomic_t for x86 is just a wrapper around the
* value, since we have enough synchronization support in the
* architecture.
*/
struct atomic_t {
atomic_t(u_int32_t v = 0) : value(v) {}
volatile u_int32_t value;
};
/**
* Atomic addition function.
*
* @param i integer value to add
* @param v pointer to current value
*
*/
static inline u_int32_t
atomic_add_ret(volatile atomic_t *v, u_int32_t i)
{
u_int32_t ret;
u_int32_t temp;
__asm__ __volatile__(
" .set mips3 \n"
"1: ll %1, %2 # atomic_add_return \n"
" addu %0, %1, %3 \n"
" sc %0, %2 \n"
" beqzl %0, 1b \n"
" addu %0, %1, %3 \n"
" sync \n"
" .set mips0 \n"
: "=&r" (ret), "=&r" (temp), "=m" (v->value)
: "Ir" (i), "m" (v->value)
: "memory");
return ret;
}
/**
* Atomic subtraction function.
*
* @param i integer value to subtract
* @param v pointer to current value
*/
static inline u_int32_t
atomic_sub_ret(volatile atomic_t * v, u_int32_t i)
{
u_int32_t ret;
u_int32_t temp;
__asm__ __volatile__(
" .set mips3 \n"
"1: ll %1, %2 # atomic_sub_return \n"
" subu %0, %1, %3 \n"
" sc %0, %2 \n"
" beqzl %0, 1b \n"
" subu %0, %1, %3 \n"
" sync \n"
" .set mips0 \n"
: "=&r" (ret), "=&r" (temp), "=m" (v->value)
: "Ir" (i), "m" (v->value)
: "memory");
return ret;
}
/// @{
/// Wrapper variants around the basic add/sub functions above
static inline void
atomic_add(volatile atomic_t* v, u_int32_t i)
{
atomic_add_ret(v, i);
}
static inline void
atomic_sub(volatile atomic_t* v, u_int32_t i)
{
atomic_sub_ret(v, i);
}
static inline void
atomic_incr(volatile atomic_t* v)
{
atomic_add(v, 1);
}
static inline void
atomic_decr(volatile atomic_t* v)
{
atomic_sub(v, 1);
}
static inline u_int32_t
atomic_incr_ret(volatile atomic_t* v)
{
return atomic_add_ret(v, 1);
}
static inline u_int32_t
atomic_decr_ret(volatile atomic_t* v)
{
return atomic_sub_ret(v, 1);
}
static inline bool
atomic_decr_test(volatile atomic_t* v)
{
return (atomic_sub_ret(v, 1) == 0);
}
/**
* Atomic compare and set. Stores the new value iff the current value
* is the expected old value.
*
* @param v pointer to current value
* @param o old value to compare against
* @param n new value to store
*
* @return zero if the compare failed, non-zero otherwise
*/
static inline u_int32_t
atomic_cmpxchg32(volatile atomic_t* v, u_int32_t o, u_int32_t n)
{
u_int32_t ret;
__asm__ __volatile__(
" .set push \n"
" .set noat \n"
" .set mips3 \n"
"1: ll %0, %2 # __cmpxchg_u32 \n"
" bne %0, %z3, 2f \n"
" .set mips0 \n"
" move $1, %z4 \n"
" .set mips3 \n"
" sc $1, %1 \n"
" beqzl $1, 1b \n"
#ifdef CONFIG_SMP
" sync \n"
#endif
"2: \n"
" .set pop \n"
: "=&r" (ret), "=R" (*v)
: "R" (*v), "Jr" (o), "Jr" (n)
: "memory");
return ret;
}
}
// namespace oasy
#endif /* _OASYS_ATOMIC_MIPS_H_ */
| [
"vache@vg1.(none)"
] | vache@vg1.(none) |
9755217f38d36862a648042debb7d987f8dbcbd8 | 55e6d3c2f1976f26e8e470586a8d6114db1b2e90 | /server.cpp | 501303649e17cfe181f2d14852f240a4f468a4e2 | [] | no_license | 0crab/read_write_test | 1a0c76061181d131cefc7c7baeea8acec9db77d4 | 766ed538f5723a622fbd469dd2e36d84922840e5 | refs/heads/master | 2022-11-05T17:43:25.345530 | 2020-07-02T09:22:24 | 2020-07-02T09:22:24 | 276,603,241 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,451 | cpp | #include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/unistd.h>
#include <netinet/in.h>
#include <iostream>
using namespace std;
int main(void)
{
printf("AF_INET\n");
socklen_t listen_fd;
listen_fd = socket(AF_INET, SOCK_STREAM, 0);
if(listen_fd < 0) {
perror("cannot create communication socket");
return 1;
}
struct sockaddr_in srv_addr;
srv_addr.sin_family = AF_INET;
srv_addr.sin_port = htons(8050);
srv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
socklen_t ret;
ret = bind(listen_fd, (struct sockaddr*)&srv_addr, sizeof(srv_addr));
if(ret == -1) {
perror("cannot bind server socket");
close(listen_fd);
return 1;
}
ret = listen(listen_fd,1);
if(ret == -1) {
perror("cannot listen the client connect request");
close(listen_fd);
return 1;
}
socklen_t con_fd;
socklen_t len;
while(1) {
//have connect request use accept
len = sizeof(srv_addr);
con_fd = accept(listen_fd,(struct sockaddr*)&srv_addr,&len);
if(con_fd < 0) {
perror("cannot accept client connect request");
close(listen_fd);
return 1;
}
char buf[100];
while(true){
int rt = read(con_fd,buf,100);
cout << "rt: " << rt <<endl;
cout << buf <<endl;
}
}
}
| [
"czl_289@163.com"
] | czl_289@163.com |
c91ed68d66534d280f1f65b1168c6fa043b33243 | 4c25432a6d82aaebd82fd48e927317b15a6bf6ab | /data/dataset_2017/dataset_2017_8_formatted/sazerterus/5304486_5697460110360576_sazerterus.cpp | f2a709cc4e000952eaded489b333748c38cc8d9e | [] | no_license | wzj1988tv/code-imitator | dca9fb7c2e7559007e5dbadbbc0d0f2deeb52933 | 07a461d43e5c440931b6519c8a3f62e771da2fc2 | refs/heads/master | 2020-12-09T05:33:21.473300 | 2020-01-09T15:29:24 | 2020-01-09T15:29:24 | 231,937,335 | 1 | 0 | null | 2020-01-05T15:28:38 | 2020-01-05T15:28:37 | null | UTF-8 | C++ | false | false | 2,048 | cpp | #include <bits/stdc++.h>
using namespace std;
vector<pair<pair<long long, long long>, long long>> V;
long long R[55];
long long P[55][55];
set<pair<long long, long long>> S[55];
int main() {
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
int t;
cin >> t;
int index = 1;
while (t--) {
// M.clear();
long long int n, p;
cin >> n >> p;
V.clear();
for (int i = 1; i <= n; ++i) {
cin >> R[i];
}
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= p; ++j)
cin >> P[i][j];
for (int i = 1; i <= n; ++i) {
S[i].clear();
for (int j = 1; j <= p; ++j) {
long long lindex =
ceil((100.0 / 110.0) * (1.0 * P[i][j]) / (1.0 * R[i]));
long long rindex =
floor((100.0 / 90.0) * (1.0 * P[i][j]) / (1.0 * R[i]));
V.push_back(make_pair(make_pair(lindex, rindex), i));
}
}
sort(V.begin(), V.end());
int ans = 0;
for (int i = 0; i < V.size(); ++i) {
if (V[i].second == 1)
S[V[i].second].insert(V[i].first);
else
S[V[i].second].insert(make_pair(V[i].first.second, V[i].first.first));
}
auto it = S[1].begin();
while (!S[1].empty()) {
it = S[1].begin();
int coun = 0;
for (int j = 2; j <= n; ++j) {
auto ip = S[j].begin();
while ((ip) != S[j].end()) {
if ((*ip).first >= (*it).first && (*ip).second <= (*it).second) {
++coun;
break;
}
++ip;
}
}
S[1].erase(it);
if (coun < n - 1)
continue;
++ans;
for (int j = 2; j <= n; ++j) {
auto ip = S[j].begin();
while ((ip) != S[j].end()) {
if ((*ip).first >= (*it).first && (*ip).second <= (*it).second) {
S[j].erase(ip);
break;
}
++ip;
}
}
}
cout << "Case #" << index++ << ": " << ans << endl;
}
return 0;
}
| [
"e.quiring@tu-bs.de"
] | e.quiring@tu-bs.de |
bbb98177f3a0573a9f32ee45b8dd9a0611b53192 | 6b3a76f96746d32c2c9feb84e5a4e25f784455ca | /Gamefiles/card.cpp | c8be8ca6a25bce29653bd2d3030b595942ec032e | [] | no_license | Cnubba-Inc-odz-No-really-its-a-feature/Game_Name_pending | 9159607ced915262bae4a55533514f2756f2228f | 016949a3135072939d4c129c260e3d2b648ea72a | refs/heads/master | 2020-09-21T16:52:39.901054 | 2020-02-17T08:50:46 | 2020-02-17T08:50:46 | 224,854,973 | 0 | 0 | null | 2020-01-29T13:54:29 | 2019-11-29T12:59:49 | C++ | UTF-8 | C++ | false | false | 3,624 | cpp | #include "card.hpp"
std::ifstream& operator>>(std::ifstream& input, E_lane& unitLane){
std::string laneString;
input>>laneString;
if(laneString == "groundLane"){
unitLane = E_lane::groundLane;
return input;
}else if(laneString == "skyLane"){
unitLane = E_lane::skyLane;
return input;
}else if(laneString == "traplane"){
unitLane = E_lane::trapLane;
return input;
}else{
throw invalid_UnitLane(std::string("invalid UnitLane at") + laneString);
}
}
std::shared_ptr<card> factorCard(int cardID){
std::ifstream cardFactoryFile("cardFactoryFile.txt");
int objectID;
try{
while(true){
cardFactoryFile>>objectID;
if(objectID == cardID){
std::string cardType;
char fileBind;
std::string cardName;
std::string cardTextureFileName;
cardFactoryFile >> cardType >> fileBind;
if(!(fileBind == '{')){throw invalid_Factory_Binds("invalid Factory Bind found: " + fileBind);}
if(!(cardFactoryFile >> cardName)){throw end_of_file("no cardName found!");}
if(!(cardFactoryFile >> cardTextureFileName)){throw end_of_file("invalid textureFilename!");}
if(cardType == "summon"){
E_lane cardUnitLane;
int cardUnitDamage;
int cardUnitHealth;
int cardManaCost;
std::string unitTextureFileName;
cardFactoryFile >> cardUnitLane >> cardUnitDamage >> fileBind >> cardUnitHealth >> fileBind >> cardManaCost >> unitTextureFileName;
std::map<std::string, sf::Texture> textureMap;
sf::Texture unitCardFrame;
if(cardUnitLane == E_lane::groundLane){
unitCardFrame.loadFromFile("gameAssets/cardAssets/summonCardFrame_W.png");
}else{
unitCardFrame.loadFromFile("gameAssets/cardAssets/summonCardFrame_F.png");
}
sf::Texture summonCardTexture;
summonCardTexture.loadFromFile(cardTextureFileName);
sf::Texture unitTexture;
unitTexture.loadFromFile(unitTextureFileName);
textureMap["basicCardFrame"] = unitCardFrame;
textureMap["cardArtTexture"] = summonCardTexture;
textureMap["unitTexture"] = unitTexture;
sf::Vector2f textureSheetdimensions;
cardFactoryFile >> textureSheetdimensions.x >> fileBind >> textureSheetdimensions.y;
cardFactoryFile >> fileBind;
if(!(fileBind == '}')){
throw invalid_Factory_Binds("invalid end factory bind");
}
return std::shared_ptr<card>(new summonCard(cardName, cardUnitDamage, cardUnitHealth, cardManaCost, cardUnitLane, textureMap, objectID, textureSheetdimensions));
}
}else{
cardFactoryFile.ignore(300, '\n');
}
}
}catch(problem & e){std::cerr<< e.what() <<std::endl;}
return nullptr;
}
| [
"ties1000@live.nlgit config -- glocal user.name Matthies"
] | ties1000@live.nlgit config -- glocal user.name Matthies |
e96f8fa9b0cd705d566971046dba0954c12c43bd | 8ba5bbf806f3a9024528bbfda9d41f3e40fea02f | /Marlin/Analysis.h | 628ba2bae093ffbded6bad30f2d5d93e192474fc | [] | no_license | pkucherov/CXHibernate | 478718c8bb0e736bd2e27e3a01480bf7ca254375 | 51a30eec880593b92ca5076c1e8cb22e0d751404 | refs/heads/master | 2020-08-26T16:34:36.588686 | 2019-09-24T06:51:53 | 2019-09-24T06:51:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,102 | h | /////////////////////////////////////////////////////////////////////////////////
//
// SourceFile: Analysis.h
//
// Marlin Server: Internet server/client
//
// Copyright (c) 2015-2018 ir. W.E. Huisman
// All rights reserved
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
// ANALYSIS
//
// Logs in the format:
// YYYY-MM-DD HH:MM:SS Function_name..........Formatted string with info
//
//////////////////////////////////////////////////////////////////////////
#pragma once
#include "HTTPLoglevel.h"
#include <deque>
#include <time.h>
constexpr auto ANALYSIS_FUNCTION_SIZE = 48; // Size of prefix printing in logfile
constexpr auto LOGWRITE_INTERVAL = (CLOCKS_PER_SEC * 30); // Median is once per 30 seconds
constexpr auto LOGWRITE_INTERVAL_MIN = (CLOCKS_PER_SEC * 10); // Minimum is once per 10 seconds
constexpr auto LOGWRITE_INTERVAL_MAX = (CLOCKS_PER_SEC * 60 * 10); // Maximum is once per 10 minutes
constexpr auto LOGWRITE_CACHE = 1000; // Median number of lines cached
constexpr auto LOGWRITE_MINCACHE = 100; // Minimum number of lines cached (below is not efficient)
constexpr auto LOGWRITE_MAXCACHE = 100000; // Maximum number of lines cached (above is too slow)
constexpr auto LOGWRITE_FORCED = 4; // Every x intervals we force a flush
constexpr auto LOGWRITE_MAXHEXCHARS = 64; // Max width of a hexadecimal dump view
constexpr auto LOGWRITE_MAXHEXDUMP = (32 * 1024); // First 32 K of a file or message
constexpr auto LOGWRITE_KEEPFILES = 128; // Keep last 128 logfiles in a directory (2 months, 2 per day)
constexpr auto LOGWRITE_KEEPLOG_MIN = 10; // Keep last 10 logfiles as a minimum
constexpr auto LOGWRITE_KEEPLOG_MAX = 500; // Keep no more than 500 logfiles of a server
// Various types of log events
enum class LogType
{
LOG_TRACE = 0
,LOG_INFO = 1
,LOG_ERROR = 2
,LOG_WARN = 3
};
// Caching list for log-lines
using LogList = std::deque<CString>;
class LogAnalysis
{
public:
LogAnalysis(CString p_name);
~LogAnalysis();
// Log this line
// Intended to be called as:
// AnalysisLog(__FUNCTION__,LOG_INFO,true,"My info for the logfile: %s %d",StringParam,IntParam);
bool AnalysisLog(const char* p_function,LogType p_type,bool p_doFormat,const char* p_format,...);
// Hexadecimal view of an object
// Intended to be called as:
// AnalysisHex(__FUNCTION__,"MyMessage",buffer,len);
bool AnalysisHex(const char* p_function,CString p_name,void* p_buffer,unsigned long p_length,unsigned p_linelength = 16);
// Use sparringly!
void BareStringLog(const char* p_buffer,int p_length);
// Flushing the log file
void ForceFlush();
// Reset to not-used
void Reset();
// SETTERS
void SetLogFilename(CString p_filename,bool p_perUser = false);
void SetDoLogging(bool p_logging);
void SetLogLevel(int p_logLevel);
void SetDoTiming(bool p_doTiming) { m_doTiming = p_doTiming; };
void SetDoEvents(bool p_doEvents) { m_doEvents = p_doEvents; };
void SetLogRotation(bool p_rotate) { m_rotate = p_rotate; };
void SetKeepfiles(int p_keepfiles);
void SetCache (int p_cache);
void SetInterval(int p_interval);
// GETTERS
bool GetDoLogging();
int GetLogLevel() { return m_logLevel; };
bool GetDoEvents() { return m_doEvents; };
bool GetDoTiming() { return m_doTiming; };
CString GetLogFileName() { return m_logFileName;};
int GetCache() { return m_cache; };
int GetInterval() { return m_interval; };
bool GetLogRotation() { return m_rotate; };
int GetKeepfiles() { return m_keepfiles; };
size_t GetCacheSize();
// INTERNALS ONLY: DO NOT CALL EXTERNALLY
// Must be public to start a writing thread
void RunLog();
void RunLogAnalysis();
static void WriteEvent(HANDLE p_eventLog,LogType p_type,CString& p_buffer);
private:
void Initialisation();
void ReadConfig();
void AppendDateTimeToFilename();
void RemoveLastMonthsFiles(struct tm& today);
void RemoveLogfilesKeeping();
CString CreateUserLogfile(CString p_filename);
// Writing out a log line
void Flush(bool p_all);
void WriteLog(CString& p_buffer);
// Settings
CString m_name; // For WMI Event viewer
int m_logLevel { HLL_NOLOG }; // Active logging level
bool m_doTiming { true }; // Prepend date-and-time to log-lines
bool m_doEvents { false }; // Also write to WMI event log
bool m_rotate { false }; // Log rotation for server solutions
int m_cache { LOGWRITE_CACHE }; // Number of cached lines
int m_interval { LOGWRITE_INTERVAL }; // Interval between writes (in seconds)
int m_keepfiles { LOGWRITE_KEEPFILES }; // Keep a maximum of n files in a directory
// Internal bookkeeping
bool m_initialised { false }; // Logging is initialized and ready
HANDLE m_logThread { NULL }; // Async writing threads ID
HANDLE m_event { NULL }; // Event for waking writing thread
HANDLE m_file { NULL }; // File handle to write log to
HANDLE m_eventLog { NULL }; // WMI handle to write event-log to
CString m_logFileName { "Logfile.txt" }; // Name of the logging file
LogList m_list; // Cached list of logging lines
// Multi-threading issues
CRITICAL_SECTION m_lock;
};
| [
"edwig.huisman@hetnet.nl"
] | edwig.huisman@hetnet.nl |
2b4aa8ce498d2598755986563ff39ad1aef37a5f | bfa701005855b5efe5947f577f5320153d348f50 | /src/MPI/MPI_ExchangeBoundaryFlag.cpp | d4251916e615e6e26ec106830edb67afb475846e | [
"BSD-3-Clause"
] | permissive | hyschive/gamer-fork | b9849fa6c497d762ed3ab85dd223245d49682292 | c0eb589c8013dc120ea47ef9b3890260031cc941 | refs/heads/main | 2023-09-05T20:20:12.743585 | 2023-09-05T10:05:17 | 2023-09-05T10:05:17 | 114,169,587 | 3 | 20 | NOASSERTION | 2023-09-13T05:59:29 | 2017-12-13T21:15:01 | C++ | UTF-8 | C++ | false | false | 4,144 | cpp | #include "GAMER.h"
#ifndef SERIAL
//-------------------------------------------------------------------------------------------------------
// Function : MPI_ExchangeBoundaryFlag
// Description : Get BuffFlag_NList[] and BuffFlag_PosList[] from 26 neighbor ranks
//
// Parameter : lv : Target refinement level
//-------------------------------------------------------------------------------------------------------
void MPI_ExchangeBoundaryFlag( const int lv )
{
const int v[26] = { 0,1,2,3,4,5,6,9,7,8,10,13,11,12,14,17,16,15,18,25,19,24,20,23,21,22 };
int SendTarget[2], RecvTarget[2];
MPI_Request Req[4];
// a. get BuffFlag_NList[]
for (int s=0; s<26; s+=2)
{
// properly deal with the non-periodic B.C.
for (int t=0; t<2; t++)
{
SendTarget[t] = ( MPI_SibRank[ v[s+t] ] < 0 ) ? MPI_PROC_NULL : MPI_SibRank[ v[s+t] ];
RecvTarget[t] = ( MPI_SibRank[ v[s+t] ] < 0 ) ? MPI_PROC_NULL : MPI_SibRank[ v[s+t] ];
}
MPI_Isend( &amr->ParaVar->BounFlag_NList[lv][ v[s ] ], 1, MPI_INT, SendTarget[0], 0, MPI_COMM_WORLD, &Req[0] );
MPI_Isend( &amr->ParaVar->BounFlag_NList[lv][ v[s+1] ], 1, MPI_INT, SendTarget[1], 1, MPI_COMM_WORLD, &Req[1] );
MPI_Irecv( &amr->ParaVar->BuffFlag_NList[lv][ v[s ] ], 1, MPI_INT, RecvTarget[0], 1, MPI_COMM_WORLD, &Req[2] );
MPI_Irecv( &amr->ParaVar->BuffFlag_NList[lv][ v[s+1] ], 1, MPI_INT, RecvTarget[1], 0, MPI_COMM_WORLD, &Req[3] );
MPI_Waitall( 4, Req, MPI_STATUSES_IGNORE );
// properly deal with the non-periodic B.C.
for (int t=0; t<2; t++)
if ( MPI_SibRank[ v[s+t] ] < 0 ) amr->ParaVar->BuffFlag_NList[lv][ v[s+t] ] = 0;
} // for (int s=0; s<26; s+=2)
// b. allocate memory for BuffFlag_PosList[] (which will be deallocated by Flag_Buffer())
for (int s=0; s<26; s++)
{
if ( amr->ParaVar->BuffFlag_PosList[lv][s] != NULL )
{
delete [] amr->ParaVar->BuffFlag_PosList[lv][s];
amr->ParaVar->BuffFlag_PosList[lv][s] = NULL;
}
amr->ParaVar->BuffFlag_PosList[lv][s] = new int [ amr->ParaVar->BuffFlag_NList[lv][s] ];
}
// c. get BuffFlag_PosList[]
for (int s=0; s<26; s+=2)
{
for (int t=0; t<2; t++)
{
SendTarget[t] = ( amr->ParaVar->BounFlag_NList[lv][ v[s+t] ] == 0 ) ? MPI_PROC_NULL : MPI_SibRank[ v[s+t] ];
RecvTarget[t] = ( amr->ParaVar->BuffFlag_NList[lv][ v[s+t] ] == 0 ) ? MPI_PROC_NULL : MPI_SibRank[ v[s+t] ];
# ifdef GAMER_DEBUG
if ( amr->ParaVar->BounFlag_NList[lv][ v[s+t] ] != 0 && ( SendTarget[t] < 0 || SendTarget[t] >= MPI_NRank ) )
Aux_Error( ERROR_INFO, "incorrect SendTarget[%d] = %d !!\n", t, SendTarget[t] );
if ( amr->ParaVar->BuffFlag_NList[lv][ v[s+t] ] != 0 && ( RecvTarget[t] < 0 || RecvTarget[t] >= MPI_NRank ) )
Aux_Error( ERROR_INFO, "incorrect RecvTarget[%d] = %d !!\n", t, RecvTarget[t] );
# endif
}
MPI_Isend( amr->ParaVar->BounFlag_PosList[lv][ v[s ] ], amr->ParaVar->BounFlag_NList[lv][ v[s ] ],
MPI_INT, SendTarget[0], 2, MPI_COMM_WORLD, &Req[0] );
MPI_Isend( amr->ParaVar->BounFlag_PosList[lv][ v[s+1] ], amr->ParaVar->BounFlag_NList[lv][ v[s+1] ],
MPI_INT, SendTarget[1], 3, MPI_COMM_WORLD, &Req[1] );
MPI_Irecv( amr->ParaVar->BuffFlag_PosList[lv][ v[s ] ], amr->ParaVar->BuffFlag_NList[lv][ v[s ] ],
MPI_INT, RecvTarget[0], 3, MPI_COMM_WORLD, &Req[2] );
MPI_Irecv( amr->ParaVar->BuffFlag_PosList[lv][ v[s+1] ], amr->ParaVar->BuffFlag_NList[lv][ v[s+1] ],
MPI_INT, RecvTarget[1], 2, MPI_COMM_WORLD, &Req[3] );
MPI_Waitall( 4, Req, MPI_STATUSES_IGNORE );
} // for (int s=0; s<26; s+=2)
// d. deallocate memory for BounFlag_PosList[]
for (int s=0; s<26; s++)
{
if ( amr->ParaVar->BounFlag_PosList[lv][s] != NULL )
{
delete [] amr->ParaVar->BounFlag_PosList[lv][s];
amr->ParaVar->BounFlag_PosList[lv][s] = NULL;
}
amr->ParaVar->BounFlag_NList[lv][s] = 0;
}
} // FUNCTION : MPI_ExchangeBoundaryFlag
#endif // #ifndef SERIAL
| [
"hyschive@gmail.com"
] | hyschive@gmail.com |
e178283061d5cbc539a7f6bfe139694a56850892 | e56a80bd922563cee64ce0b5486dadd8861ce468 | /WeekendRays/sphere.h | fea7f9d915350700e1e98e8e22a52d958857ea66 | [] | no_license | HeikkiLi/WeekendRays | 3c0a5112bebc090acef0e147ada08be65bf83247 | 985c5867df8c5d9cc7133731af9956ddca02552b | refs/heads/master | 2021-01-21T15:22:47.498674 | 2018-05-20T15:11:57 | 2018-05-20T15:11:57 | 95,387,248 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,105 | h | #pragma once
#include "hitable.h"
#include "onb.h"
class Sphere: public Hitable
{
public:
Sphere() {}
~Sphere() {}
Sphere(Vec3 cen, float r, Material *m): center(cen), radius(r), material(m) {};
virtual bool hit(const Ray& r, float t_min, float t_max, HitRecord& rec) const;
virtual bool bounding_box(float t0, float t1, AABB& box) const;
virtual float pdf_value(const Vec3& o, const Vec3& v) const;
virtual Vec3 random(const Vec3& o) const;
Vec3 center;
float radius;
Material* material;
};
inline float Sphere::pdf_value(const Vec3 & o, const Vec3 & v) const
{
HitRecord rec;
if (this->hit(Ray(o, v), 0.001, FLT_MAX, rec))
{
float cos_theta_max = sqrt(1 - radius*radius / (center - o).squared_length());
float solid_angle = 2 * M_PI*(1 - cos_theta_max);
return 1 / solid_angle;
}
else
return 0.0f;
}
inline Vec3 Sphere::random(const Vec3 & o) const
{
Vec3 direction = center - o;
float distance_squared = direction.squared_length();
ONB uvw;
uvw.build_from_w(direction);
return uvw.local(random_to_sphere(radius, distance_squared));
}
bool Sphere::hit(const Ray& r, float t_min, float t_max, HitRecord& rec) const
{
Vec3 oc = r.origin() - center;
float a = dot(r.direction(), r.direction());
float b = dot(oc, r.direction());
float c = dot(oc, oc) - radius*radius;
float discriminant = b*b - a*c;
if (discriminant > 0)
{
float temp = (-b - sqrt(b*b - a*c)) / a;
if (temp < t_max && temp > t_min)
{
rec.t = temp;
rec.p = r.point(rec.t);
get_sphere_uv((rec.p - center) / radius, rec.u, rec.v);
rec.normal = (rec.p - center) / radius;
rec.material = material;
return true;
}
temp = (-b + sqrt(b*b - a*c)) / a;
if (temp < t_max && temp > t_min)
{
rec.t = temp;
rec.p = r.point(rec.t);
get_sphere_uv((rec.p - center) / radius, rec.u, rec.v);
rec.normal = (rec.p - center) / radius;
rec.material = material;
return true;
}
}
return false;
}
bool Sphere::bounding_box(float t0, float t1, AABB& box) const
{
box = AABB(center - Vec3(radius, radius, radius), center + Vec3(radius, radius, radius));
return true;
} | [
"heikki.ikaheimonen@gmail.com"
] | heikki.ikaheimonen@gmail.com |
aa30ba4a31661be89b50125f9d9e3a0e949e58f0 | eaa0a83719dff2e09af9a25ec64c09da4ad62979 | /6-communication_modes/communication_modes.cpp | 22ab62cbc3f9a0da38e7ae99cd4960142455e239 | [] | no_license | nuriozcelik/MPI-Ogretici | 0a9f0f023abe61e57ed149064a03abd56c1c7ffe | 8741d05a9c2fb045bcbf4fd43c047a23484ddb94 | refs/heads/master | 2020-05-04T13:07:42.444165 | 2019-04-02T19:58:44 | 2019-04-02T19:58:44 | 179,148,564 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,188 | cpp | ///////////////////////////////////////////////////////////
// communication_modes.c //
///////////////////////////////////////////////////////////
//kutuphaneler
#include <iostream>
#include <unistd.h>
#include <mpi.h>
int main(int argc, char **argv) {
//MPI baslatilir
MPI_Init(&argc, &argv);
//rank size degerleri elde edilir
int size, rank;
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// birisi buyuk birisi kucuk iki adet buffer olusturulur
const int small_count = 50;
const int big_count = 100000;
int buff1[small_count];
int buff2[big_count];
// Bekleme zamanı, farkın gönderilecek veri miktarından kaynaklandığını düşünüyorsanız, bu değerle oynayın
const int waiting_time = 5; // saniye
if (rank == 0) {
// iki buffer da baslatilir
for (int i=0; i < big_count; ++i) {
if (i < small_count)
buff1[i] = i;
buff2[i] = i;
}
// 1.senkronizasyon
MPI_Barrier(MPI_COMM_WORLD);
// kronometre
double time = -MPI_Wtime();
// buffer standart modda gonderilir.
MPI_Send(buff1, small_count, MPI_INT, 1, 0, MPI_COMM_WORLD);
// Gonderme isleminin tamamlanma zamanini yazdirir
std::cout << "Blocking 1 gonderme islemi icin harcanan zaman : " << time + MPI_Wtime() << "s" << std::endl;
// 2. senkronizasyon
MPI_Barrier(MPI_COMM_WORLD);
time = -MPI_Wtime();
// 2. buffer gonderilir
MPI_Send(buff2, big_count, MPI_INT, 1, 1, MPI_COMM_WORLD);
// zaman tekrar yazdirilir
std::cout << "Blocking 2 gonderme islemi icin harcanan zaman : " << time + MPI_Wtime() << "s" << std::endl;
}
else {
// senkronizasyon 1
MPI_Barrier(MPI_COMM_WORLD);
sleep(waiting_time);
// c
MPI_Recv(buff1, small_count, MPI_INT, 0, 0, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
std::cout << "buffer 1 alindi" << std::endl;
// senkronizasyon 2
MPI_Barrier(MPI_COMM_WORLD);
sleep(waiting_time);
// alma bufferı 2
MPI_Recv(buff2, big_count, MPI_INT, 0, 1, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
std::cout << "buffer 2 alindi " << std::endl;
}
MPI_Finalize();
return 0;
} | [
"nuriozcelik.07@gmail.com"
] | nuriozcelik.07@gmail.com |
a8a877dc531852ba7a67f6d3cafcc40d713d7ce2 | 639a49238e0404c69a870c6ca64a14ade3924960 | /src/THistogram.cxx | 144452af0f6627eb8dee932dc65547670c2752ad | [] | no_license | Jacek-Turnau/genex1 | dddd77746f78d6944709f7b00eb8b24c164f3050 | ef9d95ec8905a78787b85e29facd22b236e860e0 | refs/heads/master | 2021-01-10T20:32:19.435162 | 2015-02-18T19:30:27 | 2015-02-18T19:30:27 | 30,874,889 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,817 | cxx | /***********************************************************************
* THistogram
*
* Selects histogramming class depending on the number of particles in final state.
*
*
*
***********************************************************************/
#include"THistogram.h"
////////////////////////////////////////////////////////////////////////
THistogram::THistogram()
{
ConfigReader = ConfigReaderSubsystem::Instance();
Logger = LoggerSubsystem::Instance();
ReadConfigFile( string("Generator.dat") );
switch( weightStrategy )
{
case( 2 ): strategy = new THistogram4();
break;
case( 1 ): strategy = new THistogram4();
break;
case( 3 ): strategy = new THistogramN();
break;
case( 4 ): strategy = new THistogramN();
break;
case( 5 ): strategy = new THistogramf0to2();
break;
case( 6 ): strategy = new THistogramf0();
break;
default: cout << "THistogram :: NO SUCH STARTEGY" << endl;
throw( 0 );
break;
}
};
////////////////////////////////////////////////////////////////////////
THistogram::~THistogram(void)
{
delete strategy;
};
////////////////////////////////////////////////////////////////////////
void THistogram::ReadConfigFile( const string & filename )
{
//Parse variables: setting up model variables
eventGenerationStrategy = ConfigReader->GetIntValue( "eventGenerationStrategy" );
weightStrategy = ConfigReader->GetIntValue( "weightStrategy" );
//Log configuration
string ConfigLog = ConfigReader->GetStringValue( string("ConfigLogFile") );
TLog * ConfigLogger = new TLog();
ConfigLogger->setLogTime( false );
ConfigLogger->openLogFile( ConfigLog );
ConfigLogger->Write() << "# " << "-----------" << endl;
ConfigLogger->Write() << "# " << "THistogram " << endl;
ConfigLogger->Write() << "# " << "-----------" << endl;
ConfigLogger->Write() << "eventGenerationStrategy = " << eventGenerationStrategy << endl;
ConfigLogger->Write() << "weightStrategy = " << weightStrategy << endl;
cout << "weightStrategy = " << weightStrategy << endl;
delete ConfigLogger;
return;
};
////////////////////////////////////////////////////////////////////////
void THistogram::SetOutputFile( const string & filename )
{
strategy->SetOutputFile( filename );
};
////////////////////////////////////////////////////////////////////////
void THistogram::WriteHistograms(double xsection)
{
strategy->WriteHistograms(xsection);
};
////////////////////////////////////////////////////////////////////////
void THistogram::Fill( TEvent * event, double weight )
{
strategy->Fill( event, weight );
};
| [
"turnauster@gmail.com"
] | turnauster@gmail.com |
1824addbf113632e1aa86b7a954a3ba238ae7528 | c7c900a7cf64e7b84787abc2c1a660375665113d | /1.5 编程基础之循环控制/31 开关灯/31.cpp | e56ebfd4f8f66041c295b57c5bed24a4476344d2 | [] | no_license | z-Endeavor/OpenJudge-NOI | 096e1bc6a7b4ad1f146b57348b89f15f6238650a | b0a504eed8d0db2934f46371fa3189e800b25a00 | refs/heads/master | 2020-07-02T01:17:00.921397 | 2019-09-13T02:00:00 | 2019-09-13T02:00:00 | 201,370,169 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 352 | cpp | #include <iostream>
using namespace std;
int main(){
int light[5000], n, m;
cin>>n>>m;
for (int i=1; i<=n; i++) {
light[i] = 0;
for (int j=2; j<=m; j++) {
if (i%j == 0) {
light[i] = light[i] == 0 ? light[i] = 1 : light[i] = 0;
}
}
if (light[i] == 0) {
if (i == 1) printf("%d", i);
else printf(",%d", i);
}
}
return 0;
}
| [
"zkczdd@163.com"
] | zkczdd@163.com |
8d11b4cbdf35d1f6220b1ca63b593e49655c1852 | 57d177fbd7d1bac2d97acaf081ff4fa75ed8ba53 | /third_party/skia/src/pdf/SkPDFFont.cpp | f386b7152393e8773629ae865c95eb07f1ba6257 | [
"BSD-3-Clause"
] | permissive | venkatarajasekhar/chromium-42.0.2311.135 | 676241bb228810a892e3074968c1844d26d187df | 8d6b0c3b1481b2d4bf6ec75a08b686c55e06c707 | refs/heads/master | 2021-01-13T11:57:38.761197 | 2015-05-04T12:43:44 | 2015-05-11T12:58:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 52,109 | cpp | /*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include <ctype.h>
#include "SkData.h"
#include "SkGlyphCache.h"
#include "SkPaint.h"
#include "SkPDFCatalog.h"
#include "SkPDFCanon.h"
#include "SkPDFDevice.h"
#include "SkPDFFont.h"
#include "SkPDFFontImpl.h"
#include "SkPDFStream.h"
#include "SkPDFTypes.h"
#include "SkPDFUtils.h"
#include "SkRefCnt.h"
#include "SkScalar.h"
#include "SkStream.h"
#include "SkTypefacePriv.h"
#include "SkTypes.h"
#include "SkUtils.h"
#if defined (SK_SFNTLY_SUBSETTER)
#include SK_SFNTLY_SUBSETTER
#endif
#if defined (GOOGLE3)
// #including #defines doesn't work in with this build system.
#include "typography/font/sfntly/src/sample/chromium/font_subsetter.h"
#define SK_SFNTLY_SUBSETTER // For the benefit of #ifdefs below.
#endif
// PDF's notion of symbolic vs non-symbolic is related to the character set, not
// symbols vs. characters. Rarely is a font the right character set to call it
// non-symbolic, so always call it symbolic. (PDF 1.4 spec, section 5.7.1)
static const int kPdfSymbolic = 4;
namespace {
///////////////////////////////////////////////////////////////////////////////
// File-Local Functions
///////////////////////////////////////////////////////////////////////////////
bool parsePFBSection(const uint8_t** src, size_t* len, int sectionType,
size_t* size) {
// PFB sections have a two or six bytes header. 0x80 and a one byte
// section type followed by a four byte section length. Type one is
// an ASCII section (includes a length), type two is a binary section
// (includes a length) and type three is an EOF marker with no length.
const uint8_t* buf = *src;
if (*len < 2 || buf[0] != 0x80 || buf[1] != sectionType) {
return false;
} else if (buf[1] == 3) {
return true;
} else if (*len < 6) {
return false;
}
*size = (size_t)buf[2] | ((size_t)buf[3] << 8) | ((size_t)buf[4] << 16) |
((size_t)buf[5] << 24);
size_t consumed = *size + 6;
if (consumed > *len) {
return false;
}
*src = *src + consumed;
*len = *len - consumed;
return true;
}
bool parsePFB(const uint8_t* src, size_t size, size_t* headerLen,
size_t* dataLen, size_t* trailerLen) {
const uint8_t* srcPtr = src;
size_t remaining = size;
return parsePFBSection(&srcPtr, &remaining, 1, headerLen) &&
parsePFBSection(&srcPtr, &remaining, 2, dataLen) &&
parsePFBSection(&srcPtr, &remaining, 1, trailerLen) &&
parsePFBSection(&srcPtr, &remaining, 3, NULL);
}
/* The sections of a PFA file are implicitly defined. The body starts
* after the line containing "eexec," and the trailer starts with 512
* literal 0's followed by "cleartomark" (plus arbitrary white space).
*
* This function assumes that src is NUL terminated, but the NUL
* termination is not included in size.
*
*/
bool parsePFA(const char* src, size_t size, size_t* headerLen,
size_t* hexDataLen, size_t* dataLen, size_t* trailerLen) {
const char* end = src + size;
const char* dataPos = strstr(src, "eexec");
if (!dataPos) {
return false;
}
dataPos += strlen("eexec");
while ((*dataPos == '\n' || *dataPos == '\r' || *dataPos == ' ') &&
dataPos < end) {
dataPos++;
}
*headerLen = dataPos - src;
const char* trailerPos = strstr(dataPos, "cleartomark");
if (!trailerPos) {
return false;
}
int zeroCount = 0;
for (trailerPos--; trailerPos > dataPos && zeroCount < 512; trailerPos--) {
if (*trailerPos == '\n' || *trailerPos == '\r' || *trailerPos == ' ') {
continue;
} else if (*trailerPos == '0') {
zeroCount++;
} else {
return false;
}
}
if (zeroCount != 512) {
return false;
}
*hexDataLen = trailerPos - src - *headerLen;
*trailerLen = size - *headerLen - *hexDataLen;
// Verify that the data section is hex encoded and count the bytes.
int nibbles = 0;
for (; dataPos < trailerPos; dataPos++) {
if (isspace(*dataPos)) {
continue;
}
if (!isxdigit(*dataPos)) {
return false;
}
nibbles++;
}
*dataLen = (nibbles + 1) / 2;
return true;
}
int8_t hexToBin(uint8_t c) {
if (!isxdigit(c)) {
return -1;
} else if (c <= '9') {
return c - '0';
} else if (c <= 'F') {
return c - 'A' + 10;
} else if (c <= 'f') {
return c - 'a' + 10;
}
return -1;
}
static SkData* handle_type1_stream(SkStream* srcStream, size_t* headerLen,
size_t* dataLen, size_t* trailerLen) {
// srcStream may be backed by a file or a unseekable fd, so we may not be
// able to use skip(), rewind(), or getMemoryBase(). read()ing through
// the input only once is doable, but very ugly. Furthermore, it'd be nice
// if the data was NUL terminated so that we can use strstr() to search it.
// Make as few copies as possible given these constraints.
SkDynamicMemoryWStream dynamicStream;
SkAutoTDelete<SkMemoryStream> staticStream;
SkData* data = NULL;
const uint8_t* src;
size_t srcLen;
if ((srcLen = srcStream->getLength()) > 0) {
staticStream.reset(new SkMemoryStream(srcLen + 1));
src = (const uint8_t*)staticStream->getMemoryBase();
if (srcStream->getMemoryBase() != NULL) {
memcpy((void *)src, srcStream->getMemoryBase(), srcLen);
} else {
size_t read = 0;
while (read < srcLen) {
size_t got = srcStream->read((void *)staticStream->getAtPos(),
srcLen - read);
if (got == 0) {
return NULL;
}
read += got;
staticStream->seek(read);
}
}
((uint8_t *)src)[srcLen] = 0;
} else {
static const size_t kBufSize = 4096;
uint8_t buf[kBufSize];
size_t amount;
while ((amount = srcStream->read(buf, kBufSize)) > 0) {
dynamicStream.write(buf, amount);
}
amount = 0;
dynamicStream.write(&amount, 1); // NULL terminator.
data = dynamicStream.copyToData();
src = data->bytes();
srcLen = data->size() - 1;
}
// this handles releasing the data we may have gotten from dynamicStream.
// if data is null, it is a no-op
SkAutoDataUnref aud(data);
if (parsePFB(src, srcLen, headerLen, dataLen, trailerLen)) {
static const int kPFBSectionHeaderLength = 6;
const size_t length = *headerLen + *dataLen + *trailerLen;
SkASSERT(length > 0);
SkASSERT(length + (2 * kPFBSectionHeaderLength) <= srcLen);
SkData* data = SkData::NewUninitialized(length);
const uint8_t* const srcHeader = src + kPFBSectionHeaderLength;
// There is a six-byte section header before header and data
// (but not trailer) that we're not going to copy.
const uint8_t* const srcData = srcHeader + *headerLen + kPFBSectionHeaderLength;
const uint8_t* const srcTrailer = srcData + *headerLen;
uint8_t* const resultHeader = (uint8_t*)data->writable_data();
uint8_t* const resultData = resultHeader + *headerLen;
uint8_t* const resultTrailer = resultData + *dataLen;
SkASSERT(resultTrailer + *trailerLen == resultHeader + length);
memcpy(resultHeader, srcHeader, *headerLen);
memcpy(resultData, srcData, *dataLen);
memcpy(resultTrailer, srcTrailer, *trailerLen);
return data;
}
// A PFA has to be converted for PDF.
size_t hexDataLen;
if (parsePFA((const char*)src, srcLen, headerLen, &hexDataLen, dataLen,
trailerLen)) {
const size_t length = *headerLen + *dataLen + *trailerLen;
SkASSERT(length > 0);
SkAutoTMalloc<uint8_t> buffer(length);
memcpy(buffer.get(), src, *headerLen);
uint8_t* const resultData = &(buffer[SkToInt(*headerLen)]);
const uint8_t* hexData = src + *headerLen;
const uint8_t* trailer = hexData + hexDataLen;
size_t outputOffset = 0;
uint8_t dataByte = 0; // To hush compiler.
bool highNibble = true;
for (; hexData < trailer; hexData++) {
int8_t curNibble = hexToBin(*hexData);
if (curNibble < 0) {
continue;
}
if (highNibble) {
dataByte = curNibble << 4;
highNibble = false;
} else {
dataByte |= curNibble;
highNibble = true;
resultData[outputOffset++] = dataByte;
}
}
if (!highNibble) {
resultData[outputOffset++] = dataByte;
}
SkASSERT(outputOffset == *dataLen);
uint8_t* const resultTrailer = &(buffer[SkToInt(*headerLen + outputOffset)]);
memcpy(resultTrailer, src + *headerLen + hexDataLen, *trailerLen);
return SkData::NewFromMalloc(buffer.detach(), length);
}
return NULL;
}
// scale from em-units to base-1000, returning as a SkScalar
SkScalar scaleFromFontUnits(int16_t val, uint16_t emSize) {
SkScalar scaled = SkIntToScalar(val);
if (emSize == 1000) {
return scaled;
} else {
return SkScalarMulDiv(scaled, 1000, emSize);
}
}
void setGlyphWidthAndBoundingBox(SkScalar width, SkIRect box,
SkWStream* content) {
// Specify width and bounding box for the glyph.
SkPDFScalar::Append(width, content);
content->writeText(" 0 ");
content->writeDecAsText(box.fLeft);
content->writeText(" ");
content->writeDecAsText(box.fTop);
content->writeText(" ");
content->writeDecAsText(box.fRight);
content->writeText(" ");
content->writeDecAsText(box.fBottom);
content->writeText(" d1\n");
}
SkPDFArray* makeFontBBox(SkIRect glyphBBox, uint16_t emSize) {
SkPDFArray* bbox = new SkPDFArray;
bbox->reserve(4);
bbox->appendScalar(scaleFromFontUnits(glyphBBox.fLeft, emSize));
bbox->appendScalar(scaleFromFontUnits(glyphBBox.fBottom, emSize));
bbox->appendScalar(scaleFromFontUnits(glyphBBox.fRight, emSize));
bbox->appendScalar(scaleFromFontUnits(glyphBBox.fTop, emSize));
return bbox;
}
SkPDFArray* appendWidth(const int16_t& width, uint16_t emSize,
SkPDFArray* array) {
array->appendScalar(scaleFromFontUnits(width, emSize));
return array;
}
SkPDFArray* appendVerticalAdvance(
const SkAdvancedTypefaceMetrics::VerticalMetric& advance,
uint16_t emSize, SkPDFArray* array) {
appendWidth(advance.fVerticalAdvance, emSize, array);
appendWidth(advance.fOriginXDisp, emSize, array);
appendWidth(advance.fOriginYDisp, emSize, array);
return array;
}
template <typename Data>
SkPDFArray* composeAdvanceData(
SkAdvancedTypefaceMetrics::AdvanceMetric<Data>* advanceInfo,
uint16_t emSize,
SkPDFArray* (*appendAdvance)(const Data& advance, uint16_t emSize,
SkPDFArray* array),
Data* defaultAdvance) {
SkPDFArray* result = new SkPDFArray();
for (; advanceInfo != NULL; advanceInfo = advanceInfo->fNext.get()) {
switch (advanceInfo->fType) {
case SkAdvancedTypefaceMetrics::WidthRange::kDefault: {
SkASSERT(advanceInfo->fAdvance.count() == 1);
*defaultAdvance = advanceInfo->fAdvance[0];
break;
}
case SkAdvancedTypefaceMetrics::WidthRange::kRange: {
SkAutoTUnref<SkPDFArray> advanceArray(new SkPDFArray());
for (int j = 0; j < advanceInfo->fAdvance.count(); j++)
appendAdvance(advanceInfo->fAdvance[j], emSize,
advanceArray.get());
result->appendInt(advanceInfo->fStartId);
result->append(advanceArray.get());
break;
}
case SkAdvancedTypefaceMetrics::WidthRange::kRun: {
SkASSERT(advanceInfo->fAdvance.count() == 1);
result->appendInt(advanceInfo->fStartId);
result->appendInt(advanceInfo->fEndId);
appendAdvance(advanceInfo->fAdvance[0], emSize, result);
break;
}
}
}
return result;
}
} // namespace
static void append_tounicode_header(SkDynamicMemoryWStream* cmap,
uint16_t firstGlyphID,
uint16_t lastGlyphID) {
// 12 dict begin: 12 is an Adobe-suggested value. Shall not change.
// It's there to prevent old version Adobe Readers from malfunctioning.
const char* kHeader =
"/CIDInit /ProcSet findresource begin\n"
"12 dict begin\n"
"begincmap\n";
cmap->writeText(kHeader);
// The /CIDSystemInfo must be consistent to the one in
// SkPDFFont::populateCIDFont().
// We can not pass over the system info object here because the format is
// different. This is not a reference object.
const char* kSysInfo =
"/CIDSystemInfo\n"
"<< /Registry (Adobe)\n"
"/Ordering (UCS)\n"
"/Supplement 0\n"
">> def\n";
cmap->writeText(kSysInfo);
// The CMapName must be consistent to /CIDSystemInfo above.
// /CMapType 2 means ToUnicode.
// Codespace range just tells the PDF processor the valid range.
const char* kTypeInfoHeader =
"/CMapName /Adobe-Identity-UCS def\n"
"/CMapType 2 def\n"
"1 begincodespacerange\n";
cmap->writeText(kTypeInfoHeader);
// e.g. "<0000> <FFFF>\n"
SkString range;
range.appendf("<%04X> <%04X>\n", firstGlyphID, lastGlyphID);
cmap->writeText(range.c_str());
const char* kTypeInfoFooter = "endcodespacerange\n";
cmap->writeText(kTypeInfoFooter);
}
static void append_cmap_footer(SkDynamicMemoryWStream* cmap) {
const char* kFooter =
"endcmap\n"
"CMapName currentdict /CMap defineresource pop\n"
"end\n"
"end";
cmap->writeText(kFooter);
}
struct BFChar {
uint16_t fGlyphId;
SkUnichar fUnicode;
};
struct BFRange {
uint16_t fStart;
uint16_t fEnd;
SkUnichar fUnicode;
};
static void append_bfchar_section(const SkTDArray<BFChar>& bfchar,
SkDynamicMemoryWStream* cmap) {
// PDF spec defines that every bf* list can have at most 100 entries.
for (int i = 0; i < bfchar.count(); i += 100) {
int count = bfchar.count() - i;
count = SkMin32(count, 100);
cmap->writeDecAsText(count);
cmap->writeText(" beginbfchar\n");
for (int j = 0; j < count; ++j) {
cmap->writeText("<");
cmap->writeHexAsText(bfchar[i + j].fGlyphId, 4);
cmap->writeText("> <");
cmap->writeHexAsText(bfchar[i + j].fUnicode, 4);
cmap->writeText(">\n");
}
cmap->writeText("endbfchar\n");
}
}
static void append_bfrange_section(const SkTDArray<BFRange>& bfrange,
SkDynamicMemoryWStream* cmap) {
// PDF spec defines that every bf* list can have at most 100 entries.
for (int i = 0; i < bfrange.count(); i += 100) {
int count = bfrange.count() - i;
count = SkMin32(count, 100);
cmap->writeDecAsText(count);
cmap->writeText(" beginbfrange\n");
for (int j = 0; j < count; ++j) {
cmap->writeText("<");
cmap->writeHexAsText(bfrange[i + j].fStart, 4);
cmap->writeText("> <");
cmap->writeHexAsText(bfrange[i + j].fEnd, 4);
cmap->writeText("> <");
cmap->writeHexAsText(bfrange[i + j].fUnicode, 4);
cmap->writeText(">\n");
}
cmap->writeText("endbfrange\n");
}
}
// Generate <bfchar> and <bfrange> table according to PDF spec 1.4 and Adobe
// Technote 5014.
// The function is not static so we can test it in unit tests.
//
// Current implementation guarantees bfchar and bfrange entries do not overlap.
//
// Current implementation does not attempt aggresive optimizations against
// following case because the specification is not clear.
//
// 4 beginbfchar 1 beginbfchar
// <0003> <0013> <0020> <0014>
// <0005> <0015> to endbfchar
// <0007> <0017> 1 beginbfrange
// <0020> <0014> <0003> <0007> <0013>
// endbfchar endbfrange
//
// Adobe Technote 5014 said: "Code mappings (unlike codespace ranges) may
// overlap, but succeeding maps supersede preceding maps."
//
// In case of searching text in PDF, bfrange will have higher precedence so
// typing char id 0x0014 in search box will get glyph id 0x0004 first. However,
// the spec does not mention how will this kind of conflict being resolved.
//
// For the worst case (having 65536 continuous unicode and we use every other
// one of them), the possible savings by aggressive optimization is 416KB
// pre-compressed and does not provide enough motivation for implementation.
// FIXME: this should be in a header so that it is separately testable
// ( see caller in tests/ToUnicode.cpp )
void append_cmap_sections(const SkTDArray<SkUnichar>& glyphToUnicode,
const SkPDFGlyphSet* subset,
SkDynamicMemoryWStream* cmap,
bool multiByteGlyphs,
uint16_t firstGlyphID,
uint16_t lastGlyphID);
void append_cmap_sections(const SkTDArray<SkUnichar>& glyphToUnicode,
const SkPDFGlyphSet* subset,
SkDynamicMemoryWStream* cmap,
bool multiByteGlyphs,
uint16_t firstGlyphID,
uint16_t lastGlyphID) {
if (glyphToUnicode.isEmpty()) {
return;
}
int glyphOffset = 0;
if (!multiByteGlyphs) {
glyphOffset = firstGlyphID - 1;
}
SkTDArray<BFChar> bfcharEntries;
SkTDArray<BFRange> bfrangeEntries;
BFRange currentRangeEntry = {0, 0, 0};
bool rangeEmpty = true;
const int limit =
SkMin32(lastGlyphID + 1, glyphToUnicode.count()) - glyphOffset;
for (int i = firstGlyphID - glyphOffset; i < limit + 1; ++i) {
bool inSubset = i < limit &&
(subset == NULL || subset->has(i + glyphOffset));
if (!rangeEmpty) {
// PDF spec requires bfrange not changing the higher byte,
// e.g. <1035> <10FF> <2222> is ok, but
// <1035> <1100> <2222> is no good
bool inRange =
i == currentRangeEntry.fEnd + 1 &&
i >> 8 == currentRangeEntry.fStart >> 8 &&
i < limit &&
glyphToUnicode[i + glyphOffset] ==
currentRangeEntry.fUnicode + i - currentRangeEntry.fStart;
if (!inSubset || !inRange) {
if (currentRangeEntry.fEnd > currentRangeEntry.fStart) {
bfrangeEntries.push(currentRangeEntry);
} else {
BFChar* entry = bfcharEntries.append();
entry->fGlyphId = currentRangeEntry.fStart;
entry->fUnicode = currentRangeEntry.fUnicode;
}
rangeEmpty = true;
}
}
if (inSubset) {
currentRangeEntry.fEnd = i;
if (rangeEmpty) {
currentRangeEntry.fStart = i;
currentRangeEntry.fUnicode = glyphToUnicode[i + glyphOffset];
rangeEmpty = false;
}
}
}
// The spec requires all bfchar entries for a font must come before bfrange
// entries.
append_bfchar_section(bfcharEntries, cmap);
append_bfrange_section(bfrangeEntries, cmap);
}
static SkPDFStream* generate_tounicode_cmap(
const SkTDArray<SkUnichar>& glyphToUnicode,
const SkPDFGlyphSet* subset,
bool multiByteGlyphs,
uint16_t firstGlyphID,
uint16_t lastGlyphID) {
SkDynamicMemoryWStream cmap;
if (multiByteGlyphs) {
append_tounicode_header(&cmap, firstGlyphID, lastGlyphID);
} else {
append_tounicode_header(&cmap, 1, lastGlyphID - firstGlyphID + 1);
}
append_cmap_sections(glyphToUnicode, subset, &cmap, multiByteGlyphs,
firstGlyphID, lastGlyphID);
append_cmap_footer(&cmap);
SkAutoTUnref<SkData> cmapData(cmap.copyToData());
return new SkPDFStream(cmapData.get());
}
#if defined (SK_SFNTLY_SUBSETTER)
static void sk_delete_array(const void* ptr, size_t, void*) {
// Use C-style cast to cast away const and cast type simultaneously.
delete[] (unsigned char*)ptr;
}
#endif
static size_t get_subset_font_stream(const char* fontName,
const SkTypeface* typeface,
const SkTDArray<uint32_t>& subset,
SkPDFStream** fontStream) {
int ttcIndex;
SkAutoTDelete<SkStream> fontData(typeface->openStream(&ttcIndex));
SkASSERT(fontData.get());
size_t fontSize = fontData->getLength();
#if defined (SK_SFNTLY_SUBSETTER)
// Read font into buffer.
SkPDFStream* subsetFontStream = NULL;
SkTDArray<unsigned char> originalFont;
originalFont.setCount(SkToInt(fontSize));
if (fontData->read(originalFont.begin(), fontSize) == fontSize) {
unsigned char* subsetFont = NULL;
// sfntly requires unsigned int* to be passed in, as far as we know,
// unsigned int is equivalent to uint32_t on all platforms.
SK_COMPILE_ASSERT(sizeof(unsigned int) == sizeof(uint32_t),
unsigned_int_not_32_bits);
int subsetFontSize = SfntlyWrapper::SubsetFont(fontName,
originalFont.begin(),
fontSize,
subset.begin(),
subset.count(),
&subsetFont);
if (subsetFontSize > 0 && subsetFont != NULL) {
SkAutoDataUnref data(SkData::NewWithProc(subsetFont,
subsetFontSize,
sk_delete_array,
NULL));
subsetFontStream = new SkPDFStream(data.get());
fontSize = subsetFontSize;
}
}
if (subsetFontStream) {
*fontStream = subsetFontStream;
return fontSize;
}
fontData->rewind();
#else
sk_ignore_unused_variable(fontName);
sk_ignore_unused_variable(subset);
#endif
// Fail over: just embed the whole font.
*fontStream = new SkPDFStream(fontData.get());
return fontSize;
}
///////////////////////////////////////////////////////////////////////////////
// class SkPDFGlyphSet
///////////////////////////////////////////////////////////////////////////////
SkPDFGlyphSet::SkPDFGlyphSet() : fBitSet(SK_MaxU16 + 1) {
}
void SkPDFGlyphSet::set(const uint16_t* glyphIDs, int numGlyphs) {
for (int i = 0; i < numGlyphs; ++i) {
fBitSet.setBit(glyphIDs[i], true);
}
}
bool SkPDFGlyphSet::has(uint16_t glyphID) const {
return fBitSet.isBitSet(glyphID);
}
void SkPDFGlyphSet::merge(const SkPDFGlyphSet& usage) {
fBitSet.orBits(usage.fBitSet);
}
void SkPDFGlyphSet::exportTo(SkTDArray<unsigned int>* glyphIDs) const {
fBitSet.exportTo(glyphIDs);
}
///////////////////////////////////////////////////////////////////////////////
// class SkPDFGlyphSetMap
///////////////////////////////////////////////////////////////////////////////
SkPDFGlyphSetMap::FontGlyphSetPair::FontGlyphSetPair(SkPDFFont* font,
SkPDFGlyphSet* glyphSet)
: fFont(font),
fGlyphSet(glyphSet) {
}
SkPDFGlyphSetMap::F2BIter::F2BIter(const SkPDFGlyphSetMap& map) {
reset(map);
}
const SkPDFGlyphSetMap::FontGlyphSetPair* SkPDFGlyphSetMap::F2BIter::next() const {
if (fIndex >= fMap->count()) {
return NULL;
}
return &((*fMap)[fIndex++]);
}
void SkPDFGlyphSetMap::F2BIter::reset(const SkPDFGlyphSetMap& map) {
fMap = &(map.fMap);
fIndex = 0;
}
SkPDFGlyphSetMap::SkPDFGlyphSetMap() {
}
SkPDFGlyphSetMap::~SkPDFGlyphSetMap() {
reset();
}
void SkPDFGlyphSetMap::merge(const SkPDFGlyphSetMap& usage) {
for (int i = 0; i < usage.fMap.count(); ++i) {
SkPDFGlyphSet* myUsage = getGlyphSetForFont(usage.fMap[i].fFont);
myUsage->merge(*(usage.fMap[i].fGlyphSet));
}
}
void SkPDFGlyphSetMap::reset() {
for (int i = 0; i < fMap.count(); ++i) {
delete fMap[i].fGlyphSet; // Should not be NULL.
}
fMap.reset();
}
void SkPDFGlyphSetMap::noteGlyphUsage(SkPDFFont* font, const uint16_t* glyphIDs,
int numGlyphs) {
SkPDFGlyphSet* subset = getGlyphSetForFont(font);
if (subset) {
subset->set(glyphIDs, numGlyphs);
}
}
SkPDFGlyphSet* SkPDFGlyphSetMap::getGlyphSetForFont(SkPDFFont* font) {
int index = fMap.count();
for (int i = 0; i < index; ++i) {
if (fMap[i].fFont == font) {
return fMap[i].fGlyphSet;
}
}
fMap.append();
index = fMap.count() - 1;
fMap[index].fFont = font;
fMap[index].fGlyphSet = new SkPDFGlyphSet();
return fMap[index].fGlyphSet;
}
///////////////////////////////////////////////////////////////////////////////
// class SkPDFFont
///////////////////////////////////////////////////////////////////////////////
/* Font subset design: It would be nice to be able to subset fonts
* (particularly type 3 fonts), but it's a lot of work and not a priority.
*
* Resources are canonicalized and uniqueified by pointer so there has to be
* some additional state indicating which subset of the font is used. It
* must be maintained at the page granularity and then combined at the document
* granularity. a) change SkPDFFont to fill in its state on demand, kind of
* like SkPDFGraphicState. b) maintain a per font glyph usage class in each
* page/pdf device. c) in the document, retrieve the per font glyph usage
* from each page and combine it and ask for a resource with that subset.
*/
SkPDFFont::~SkPDFFont() { fCanon->removeFont(this); }
SkTypeface* SkPDFFont::typeface() {
return fTypeface.get();
}
SkAdvancedTypefaceMetrics::FontType SkPDFFont::getType() {
return fFontType;
}
bool SkPDFFont::canEmbed() const {
if (!fFontInfo.get()) {
SkASSERT(fFontType == SkAdvancedTypefaceMetrics::kOther_Font);
return true;
}
return (fFontInfo->fFlags &
SkAdvancedTypefaceMetrics::kNotEmbeddable_FontFlag) == 0;
}
bool SkPDFFont::canSubset() const {
if (!fFontInfo.get()) {
SkASSERT(fFontType == SkAdvancedTypefaceMetrics::kOther_Font);
return true;
}
return (fFontInfo->fFlags &
SkAdvancedTypefaceMetrics::kNotSubsettable_FontFlag) == 0;
}
bool SkPDFFont::hasGlyph(uint16_t id) {
return (id >= fFirstGlyphID && id <= fLastGlyphID) || id == 0;
}
int SkPDFFont::glyphsToPDFFontEncoding(uint16_t* glyphIDs, int numGlyphs) {
// A font with multibyte glyphs will support all glyph IDs in a single font.
if (this->multiByteGlyphs()) {
return numGlyphs;
}
for (int i = 0; i < numGlyphs; i++) {
if (glyphIDs[i] == 0) {
continue;
}
if (glyphIDs[i] < fFirstGlyphID || glyphIDs[i] > fLastGlyphID) {
return i;
}
glyphIDs[i] -= (fFirstGlyphID - 1);
}
return numGlyphs;
}
// static
SkPDFFont* SkPDFFont::GetFontResource(SkPDFCanon* canon,
SkTypeface* typeface,
uint16_t glyphID) {
SkASSERT(canon);
SkAutoResolveDefaultTypeface autoResolve(typeface);
typeface = autoResolve.get();
const uint32_t fontID = typeface->uniqueID();
SkPDFFont* relatedFont;
if (SkPDFFont* pdfFont = canon->findFont(fontID, glyphID, &relatedFont)) {
return SkRef(pdfFont);
}
SkAutoTUnref<const SkAdvancedTypefaceMetrics> fontMetrics;
SkPDFDict* relatedFontDescriptor = NULL;
if (relatedFont) {
fontMetrics.reset(SkSafeRef(relatedFont->fontInfo()));
relatedFontDescriptor = relatedFont->getFontDescriptor();
// This only is to catch callers who pass invalid glyph ids.
// If glyph id is invalid, then we will create duplicate entries
// for TrueType fonts.
SkAdvancedTypefaceMetrics::FontType fontType =
fontMetrics.get() ? fontMetrics.get()->fType :
SkAdvancedTypefaceMetrics::kOther_Font;
if (fontType == SkAdvancedTypefaceMetrics::kType1CID_Font ||
fontType == SkAdvancedTypefaceMetrics::kTrueType_Font) {
return SkRef(relatedFont);
}
} else {
SkAdvancedTypefaceMetrics::PerGlyphInfo info;
info = SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo;
info = SkTBitOr<SkAdvancedTypefaceMetrics::PerGlyphInfo>(
info, SkAdvancedTypefaceMetrics::kToUnicode_PerGlyphInfo);
#if !defined (SK_SFNTLY_SUBSETTER)
info = SkTBitOr<SkAdvancedTypefaceMetrics::PerGlyphInfo>(
info, SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo);
#endif
fontMetrics.reset(
typeface->getAdvancedTypefaceMetrics(info, NULL, 0));
#if defined (SK_SFNTLY_SUBSETTER)
if (fontMetrics.get() &&
fontMetrics->fType != SkAdvancedTypefaceMetrics::kTrueType_Font) {
// Font does not support subsetting, get new info with advance.
info = SkTBitOr<SkAdvancedTypefaceMetrics::PerGlyphInfo>(
info, SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo);
fontMetrics.reset(
typeface->getAdvancedTypefaceMetrics(info, NULL, 0));
}
#endif
}
SkPDFFont* font = SkPDFFont::Create(canon, fontMetrics.get(), typeface,
glyphID, relatedFontDescriptor);
canon->addFont(font, fontID, font->fFirstGlyphID);
return font;
}
SkPDFFont* SkPDFFont::getFontSubset(const SkPDFGlyphSet*) {
return NULL; // Default: no support.
}
SkPDFFont::SkPDFFont(SkPDFCanon* canon,
const SkAdvancedTypefaceMetrics* info,
SkTypeface* typeface,
SkPDFDict* relatedFontDescriptor)
: SkPDFDict("Font")
, fCanon(canon)
, fTypeface(ref_or_default(typeface))
, fFirstGlyphID(1)
, fLastGlyphID(info ? info->fLastGlyphID : 0)
, fFontInfo(SkSafeRef(info))
, fDescriptor(SkSafeRef(relatedFontDescriptor)) {
if (info == NULL ||
info->fFlags & SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag) {
fFontType = SkAdvancedTypefaceMetrics::kOther_Font;
} else {
fFontType = info->fType;
}
}
// static
SkPDFFont* SkPDFFont::Create(SkPDFCanon* canon,
const SkAdvancedTypefaceMetrics* info,
SkTypeface* typeface,
uint16_t glyphID,
SkPDFDict* relatedFontDescriptor) {
SkAdvancedTypefaceMetrics::FontType type =
info ? info->fType : SkAdvancedTypefaceMetrics::kOther_Font;
if (info &&
(info->fFlags & SkAdvancedTypefaceMetrics::kMultiMaster_FontFlag)) {
NOT_IMPLEMENTED(true, true);
return new SkPDFType3Font(canon, info, typeface, glyphID);
}
if (type == SkAdvancedTypefaceMetrics::kType1CID_Font ||
type == SkAdvancedTypefaceMetrics::kTrueType_Font) {
SkASSERT(relatedFontDescriptor == NULL);
return new SkPDFType0Font(canon, info, typeface);
}
if (type == SkAdvancedTypefaceMetrics::kType1_Font) {
return new SkPDFType1Font(canon, info, typeface, glyphID,
relatedFontDescriptor);
}
SkASSERT(type == SkAdvancedTypefaceMetrics::kCFF_Font ||
type == SkAdvancedTypefaceMetrics::kOther_Font);
return new SkPDFType3Font(canon, info, typeface, glyphID);
}
const SkAdvancedTypefaceMetrics* SkPDFFont::fontInfo() {
return fFontInfo.get();
}
void SkPDFFont::setFontInfo(const SkAdvancedTypefaceMetrics* info) {
if (info == NULL || info == fFontInfo.get()) {
return;
}
fFontInfo.reset(info);
SkSafeRef(info);
}
uint16_t SkPDFFont::firstGlyphID() const {
return fFirstGlyphID;
}
uint16_t SkPDFFont::lastGlyphID() const {
return fLastGlyphID;
}
void SkPDFFont::setLastGlyphID(uint16_t glyphID) {
fLastGlyphID = glyphID;
}
SkPDFDict* SkPDFFont::getFontDescriptor() {
return fDescriptor.get();
}
void SkPDFFont::setFontDescriptor(SkPDFDict* descriptor) {
fDescriptor.reset(descriptor);
SkSafeRef(descriptor);
}
bool SkPDFFont::addCommonFontDescriptorEntries(int16_t defaultWidth) {
if (fDescriptor.get() == NULL) {
return false;
}
const uint16_t emSize = fFontInfo->fEmSize;
fDescriptor->insertName("FontName", fFontInfo->fFontName);
fDescriptor->insertInt("Flags", fFontInfo->fStyle | kPdfSymbolic);
fDescriptor->insertScalar("Ascent",
scaleFromFontUnits(fFontInfo->fAscent, emSize));
fDescriptor->insertScalar("Descent",
scaleFromFontUnits(fFontInfo->fDescent, emSize));
fDescriptor->insertScalar("StemV",
scaleFromFontUnits(fFontInfo->fStemV, emSize));
fDescriptor->insertScalar("CapHeight",
scaleFromFontUnits(fFontInfo->fCapHeight, emSize));
fDescriptor->insertInt("ItalicAngle", fFontInfo->fItalicAngle);
fDescriptor->insert("FontBBox", makeFontBBox(fFontInfo->fBBox,
fFontInfo->fEmSize))->unref();
if (defaultWidth > 0) {
fDescriptor->insertScalar("MissingWidth",
scaleFromFontUnits(defaultWidth, emSize));
}
return true;
}
void SkPDFFont::adjustGlyphRangeForSingleByteEncoding(uint16_t glyphID) {
// Single byte glyph encoding supports a max of 255 glyphs.
fFirstGlyphID = glyphID - (glyphID - 1) % 255;
if (fLastGlyphID > fFirstGlyphID + 255 - 1) {
fLastGlyphID = fFirstGlyphID + 255 - 1;
}
}
void SkPDFFont::populateToUnicodeTable(const SkPDFGlyphSet* subset) {
if (fFontInfo == NULL || fFontInfo->fGlyphToUnicode.begin() == NULL) {
return;
}
SkAutoTUnref<SkPDFStream> pdfCmap(
generate_tounicode_cmap(fFontInfo->fGlyphToUnicode, subset,
multiByteGlyphs(), firstGlyphID(),
lastGlyphID()));
insert("ToUnicode", new SkPDFObjRef(pdfCmap.get()))->unref();
}
///////////////////////////////////////////////////////////////////////////////
// class SkPDFType0Font
///////////////////////////////////////////////////////////////////////////////
SkPDFType0Font::SkPDFType0Font(SkPDFCanon* canon,
const SkAdvancedTypefaceMetrics* info,
SkTypeface* typeface)
: SkPDFFont(canon, info, typeface, NULL) {
SkDEBUGCODE(fPopulated = false);
if (!canSubset()) {
populate(NULL);
}
}
SkPDFType0Font::~SkPDFType0Font() {}
SkPDFFont* SkPDFType0Font::getFontSubset(const SkPDFGlyphSet* subset) {
if (!canSubset()) {
return NULL;
}
SkPDFType0Font* newSubset =
new SkPDFType0Font(fCanon, fontInfo(), typeface());
newSubset->populate(subset);
return newSubset;
}
#ifdef SK_DEBUG
void SkPDFType0Font::emitObject(SkWStream* stream, SkPDFCatalog* catalog) {
SkASSERT(fPopulated);
return INHERITED::emitObject(stream, catalog);
}
#endif
bool SkPDFType0Font::populate(const SkPDFGlyphSet* subset) {
insertName("Subtype", "Type0");
insertName("BaseFont", fontInfo()->fFontName);
insertName("Encoding", "Identity-H");
SkAutoTUnref<SkPDFCIDFont> newCIDFont(
new SkPDFCIDFont(fCanon, fontInfo(), typeface(), subset));
SkAutoTUnref<SkPDFArray> descendantFonts(new SkPDFArray());
descendantFonts->append(new SkPDFObjRef(newCIDFont.get()))->unref();
insert("DescendantFonts", descendantFonts.get());
populateToUnicodeTable(subset);
SkDEBUGCODE(fPopulated = true);
return true;
}
///////////////////////////////////////////////////////////////////////////////
// class SkPDFCIDFont
///////////////////////////////////////////////////////////////////////////////
SkPDFCIDFont::SkPDFCIDFont(SkPDFCanon* canon,
const SkAdvancedTypefaceMetrics* info,
SkTypeface* typeface,
const SkPDFGlyphSet* subset)
: SkPDFFont(canon, info, typeface, NULL) {
populate(subset);
}
SkPDFCIDFont::~SkPDFCIDFont() {}
bool SkPDFCIDFont::addFontDescriptor(int16_t defaultWidth,
const SkTDArray<uint32_t>* subset) {
SkAutoTUnref<SkPDFDict> descriptor(new SkPDFDict("FontDescriptor"));
setFontDescriptor(descriptor.get());
insert("FontDescriptor", new SkPDFObjRef(descriptor.get()))->unref();
if (!addCommonFontDescriptorEntries(defaultWidth)) {
return false;
}
if (!canEmbed()) {
return true;
}
switch (getType()) {
case SkAdvancedTypefaceMetrics::kTrueType_Font: {
SkAutoTUnref<SkPDFStream> fontStream;
size_t fontSize = 0;
if (canSubset()) {
SkPDFStream* rawStream = NULL;
fontSize = get_subset_font_stream(fontInfo()->fFontName.c_str(),
typeface(),
*subset,
&rawStream);
fontStream.reset(rawStream);
} else {
int ttcIndex;
SkAutoTDelete<SkStream> fontData(
typeface()->openStream(&ttcIndex));
fontStream.reset(new SkPDFStream(fontData.get()));
fontSize = fontData->getLength();
}
SkASSERT(fontSize);
SkASSERT(fontStream.get());
fontStream->insertInt("Length1", fontSize);
descriptor->insert("FontFile2",
new SkPDFObjRef(fontStream.get()))->unref();
break;
}
case SkAdvancedTypefaceMetrics::kCFF_Font:
case SkAdvancedTypefaceMetrics::kType1CID_Font: {
int ttcIndex;
SkAutoTDelete<SkStream> fontData(typeface()->openStream(&ttcIndex));
SkAutoTUnref<SkPDFStream> fontStream(
new SkPDFStream(fontData.get()));
if (getType() == SkAdvancedTypefaceMetrics::kCFF_Font) {
fontStream->insertName("Subtype", "Type1C");
} else {
fontStream->insertName("Subtype", "CIDFontType0c");
}
descriptor->insert("FontFile3",
new SkPDFObjRef(fontStream.get()))->unref();
break;
}
default:
SkASSERT(false);
}
return true;
}
bool SkPDFCIDFont::populate(const SkPDFGlyphSet* subset) {
// Generate new font metrics with advance info for true type fonts.
if (fontInfo()->fType == SkAdvancedTypefaceMetrics::kTrueType_Font) {
// Generate glyph id array.
SkTDArray<uint32_t> glyphIDs;
if (subset) {
// Always include glyph 0.
if (!subset->has(0)) {
glyphIDs.push(0);
}
subset->exportTo(&glyphIDs);
}
SkAdvancedTypefaceMetrics::PerGlyphInfo info;
info = SkAdvancedTypefaceMetrics::kGlyphNames_PerGlyphInfo;
info = SkTBitOr<SkAdvancedTypefaceMetrics::PerGlyphInfo>(
info, SkAdvancedTypefaceMetrics::kHAdvance_PerGlyphInfo);
uint32_t* glyphs = (glyphIDs.count() == 0) ? NULL : glyphIDs.begin();
uint32_t glyphsCount = glyphs ? glyphIDs.count() : 0;
SkAutoTUnref<const SkAdvancedTypefaceMetrics> fontMetrics(
typeface()->getAdvancedTypefaceMetrics(info, glyphs, glyphsCount));
setFontInfo(fontMetrics.get());
addFontDescriptor(0, &glyphIDs);
} else {
// Other CID fonts
addFontDescriptor(0, NULL);
}
insertName("BaseFont", fontInfo()->fFontName);
if (getType() == SkAdvancedTypefaceMetrics::kType1CID_Font) {
insertName("Subtype", "CIDFontType0");
} else if (getType() == SkAdvancedTypefaceMetrics::kTrueType_Font) {
insertName("Subtype", "CIDFontType2");
insertName("CIDToGIDMap", "Identity");
} else {
SkASSERT(false);
}
SkAutoTUnref<SkPDFDict> sysInfo(new SkPDFDict);
sysInfo->insert("Registry", new SkPDFString("Adobe"))->unref();
sysInfo->insert("Ordering", new SkPDFString("Identity"))->unref();
sysInfo->insertInt("Supplement", 0);
insert("CIDSystemInfo", sysInfo.get());
if (fontInfo()->fGlyphWidths.get()) {
int16_t defaultWidth = 0;
SkAutoTUnref<SkPDFArray> widths(
composeAdvanceData(fontInfo()->fGlyphWidths.get(),
fontInfo()->fEmSize, &appendWidth,
&defaultWidth));
if (widths->size())
insert("W", widths.get());
if (defaultWidth != 0) {
insertScalar("DW", scaleFromFontUnits(defaultWidth,
fontInfo()->fEmSize));
}
}
if (fontInfo()->fVerticalMetrics.get()) {
struct SkAdvancedTypefaceMetrics::VerticalMetric defaultAdvance;
defaultAdvance.fVerticalAdvance = 0;
defaultAdvance.fOriginXDisp = 0;
defaultAdvance.fOriginYDisp = 0;
SkAutoTUnref<SkPDFArray> advances(
composeAdvanceData(fontInfo()->fVerticalMetrics.get(),
fontInfo()->fEmSize, &appendVerticalAdvance,
&defaultAdvance));
if (advances->size())
insert("W2", advances.get());
if (defaultAdvance.fVerticalAdvance ||
defaultAdvance.fOriginXDisp ||
defaultAdvance.fOriginYDisp) {
insert("DW2", appendVerticalAdvance(defaultAdvance,
fontInfo()->fEmSize,
new SkPDFArray))->unref();
}
}
return true;
}
///////////////////////////////////////////////////////////////////////////////
// class SkPDFType1Font
///////////////////////////////////////////////////////////////////////////////
SkPDFType1Font::SkPDFType1Font(SkPDFCanon* canon,
const SkAdvancedTypefaceMetrics* info,
SkTypeface* typeface,
uint16_t glyphID,
SkPDFDict* relatedFontDescriptor)
: SkPDFFont(canon, info, typeface, relatedFontDescriptor) {
populate(glyphID);
}
SkPDFType1Font::~SkPDFType1Font() {}
bool SkPDFType1Font::addFontDescriptor(int16_t defaultWidth) {
if (getFontDescriptor() != NULL) {
SkPDFDict* descriptor = getFontDescriptor();
insert("FontDescriptor", new SkPDFObjRef(descriptor))->unref();
return true;
}
SkAutoTUnref<SkPDFDict> descriptor(new SkPDFDict("FontDescriptor"));
setFontDescriptor(descriptor.get());
int ttcIndex;
size_t header SK_INIT_TO_AVOID_WARNING;
size_t data SK_INIT_TO_AVOID_WARNING;
size_t trailer SK_INIT_TO_AVOID_WARNING;
SkAutoTDelete<SkStream> rawFontData(typeface()->openStream(&ttcIndex));
SkAutoTUnref<SkData> fontData(handle_type1_stream(rawFontData.get(), &header,
&data, &trailer));
if (fontData.get() == NULL) {
return false;
}
if (canEmbed()) {
SkAutoTUnref<SkPDFStream> fontStream(new SkPDFStream(fontData.get()));
fontStream->insertInt("Length1", header);
fontStream->insertInt("Length2", data);
fontStream->insertInt("Length3", trailer);
descriptor->insert("FontFile",
new SkPDFObjRef(fontStream.get()))->unref();
}
insert("FontDescriptor", new SkPDFObjRef(descriptor.get()))->unref();
return addCommonFontDescriptorEntries(defaultWidth);
}
bool SkPDFType1Font::populate(int16_t glyphID) {
SkASSERT(!fontInfo()->fVerticalMetrics.get());
SkASSERT(fontInfo()->fGlyphWidths.get());
adjustGlyphRangeForSingleByteEncoding(glyphID);
int16_t defaultWidth = 0;
const SkAdvancedTypefaceMetrics::WidthRange* widthRangeEntry = NULL;
const SkAdvancedTypefaceMetrics::WidthRange* widthEntry;
for (widthEntry = fontInfo()->fGlyphWidths.get();
widthEntry != NULL;
widthEntry = widthEntry->fNext.get()) {
switch (widthEntry->fType) {
case SkAdvancedTypefaceMetrics::WidthRange::kDefault:
defaultWidth = widthEntry->fAdvance[0];
break;
case SkAdvancedTypefaceMetrics::WidthRange::kRun:
SkASSERT(false);
break;
case SkAdvancedTypefaceMetrics::WidthRange::kRange:
SkASSERT(widthRangeEntry == NULL);
widthRangeEntry = widthEntry;
break;
}
}
if (!addFontDescriptor(defaultWidth)) {
return false;
}
insertName("Subtype", "Type1");
insertName("BaseFont", fontInfo()->fFontName);
addWidthInfoFromRange(defaultWidth, widthRangeEntry);
SkAutoTUnref<SkPDFDict> encoding(new SkPDFDict("Encoding"));
insert("Encoding", encoding.get());
SkAutoTUnref<SkPDFArray> encDiffs(new SkPDFArray);
encoding->insert("Differences", encDiffs.get());
encDiffs->reserve(lastGlyphID() - firstGlyphID() + 2);
encDiffs->appendInt(1);
for (int gID = firstGlyphID(); gID <= lastGlyphID(); gID++) {
encDiffs->appendName(fontInfo()->fGlyphNames->get()[gID].c_str());
}
return true;
}
void SkPDFType1Font::addWidthInfoFromRange(
int16_t defaultWidth,
const SkAdvancedTypefaceMetrics::WidthRange* widthRangeEntry) {
SkAutoTUnref<SkPDFArray> widthArray(new SkPDFArray());
int firstChar = 0;
if (widthRangeEntry) {
const uint16_t emSize = fontInfo()->fEmSize;
int startIndex = firstGlyphID() - widthRangeEntry->fStartId;
int endIndex = startIndex + lastGlyphID() - firstGlyphID() + 1;
if (startIndex < 0)
startIndex = 0;
if (endIndex > widthRangeEntry->fAdvance.count())
endIndex = widthRangeEntry->fAdvance.count();
if (widthRangeEntry->fStartId == 0) {
appendWidth(widthRangeEntry->fAdvance[0], emSize, widthArray.get());
} else {
firstChar = startIndex + widthRangeEntry->fStartId;
}
for (int i = startIndex; i < endIndex; i++) {
appendWidth(widthRangeEntry->fAdvance[i], emSize, widthArray.get());
}
} else {
appendWidth(defaultWidth, 1000, widthArray.get());
}
insertInt("FirstChar", firstChar);
insertInt("LastChar", firstChar + widthArray->size() - 1);
insert("Widths", widthArray.get());
}
///////////////////////////////////////////////////////////////////////////////
// class SkPDFType3Font
///////////////////////////////////////////////////////////////////////////////
SkPDFType3Font::SkPDFType3Font(SkPDFCanon* canon,
const SkAdvancedTypefaceMetrics* info,
SkTypeface* typeface,
uint16_t glyphID)
: SkPDFFont(canon, info, typeface, NULL) {
populate(glyphID);
}
SkPDFType3Font::~SkPDFType3Font() {}
bool SkPDFType3Font::populate(uint16_t glyphID) {
SkPaint paint;
paint.setTypeface(typeface());
paint.setTextSize(1000);
SkAutoGlyphCache autoCache(paint, NULL, NULL);
SkGlyphCache* cache = autoCache.getCache();
// If fLastGlyphID isn't set (because there is not fFontInfo), look it up.
if (lastGlyphID() == 0) {
setLastGlyphID(cache->getGlyphCount() - 1);
}
adjustGlyphRangeForSingleByteEncoding(glyphID);
insertName("Subtype", "Type3");
// Flip about the x-axis and scale by 1/1000.
SkMatrix fontMatrix;
fontMatrix.setScale(SkScalarInvert(1000), -SkScalarInvert(1000));
insert("FontMatrix", SkPDFUtils::MatrixToArray(fontMatrix))->unref();
SkAutoTUnref<SkPDFDict> charProcs(new SkPDFDict);
insert("CharProcs", charProcs.get());
SkAutoTUnref<SkPDFDict> encoding(new SkPDFDict("Encoding"));
insert("Encoding", encoding.get());
SkAutoTUnref<SkPDFArray> encDiffs(new SkPDFArray);
encoding->insert("Differences", encDiffs.get());
encDiffs->reserve(lastGlyphID() - firstGlyphID() + 2);
encDiffs->appendInt(1);
SkAutoTUnref<SkPDFArray> widthArray(new SkPDFArray());
SkIRect bbox = SkIRect::MakeEmpty();
for (int gID = firstGlyphID(); gID <= lastGlyphID(); gID++) {
SkString characterName;
characterName.printf("gid%d", gID);
encDiffs->appendName(characterName.c_str());
const SkGlyph& glyph = cache->getGlyphIDMetrics(gID);
widthArray->appendScalar(SkFixedToScalar(glyph.fAdvanceX));
SkIRect glyphBBox = SkIRect::MakeXYWH(glyph.fLeft, glyph.fTop,
glyph.fWidth, glyph.fHeight);
bbox.join(glyphBBox);
SkDynamicMemoryWStream content;
setGlyphWidthAndBoundingBox(SkFixedToScalar(glyph.fAdvanceX), glyphBBox,
&content);
const SkPath* path = cache->findPath(glyph);
if (path) {
SkPDFUtils::EmitPath(*path, paint.getStyle(), &content);
SkPDFUtils::PaintPath(paint.getStyle(), path->getFillType(),
&content);
}
SkAutoTDelete<SkMemoryStream> glyphStream(new SkMemoryStream());
glyphStream->setData(content.copyToData())->unref();
SkAutoTUnref<SkPDFStream> glyphDescription(
new SkPDFStream(glyphStream.get()));
charProcs->insert(characterName.c_str(),
new SkPDFObjRef(glyphDescription.get()))->unref();
}
insert("FontBBox", makeFontBBox(bbox, 1000))->unref();
insertInt("FirstChar", 1);
insertInt("LastChar", lastGlyphID() - firstGlyphID() + 1);
insert("Widths", widthArray.get());
insertName("CIDToGIDMap", "Identity");
populateToUnicodeTable(NULL);
return true;
}
SkPDFFont::Match SkPDFFont::IsMatch(SkPDFFont* existingFont,
uint32_t existingFontID,
uint16_t existingGlyphID,
uint32_t searchFontID,
uint16_t searchGlyphID) {
if (existingFontID != searchFontID) {
return SkPDFFont::kNot_Match;
}
if (existingGlyphID == 0 || searchGlyphID == 0) {
return SkPDFFont::kExact_Match;
}
if (existingFont != NULL) {
return (existingFont->fFirstGlyphID <= searchGlyphID &&
searchGlyphID <= existingFont->fLastGlyphID)
? SkPDFFont::kExact_Match
: SkPDFFont::kRelated_Match;
}
return (existingGlyphID == searchGlyphID) ? SkPDFFont::kExact_Match
: SkPDFFont::kRelated_Match;
}
| [
"jonathan.anderson@ieee.org"
] | jonathan.anderson@ieee.org |
0fadbe7de63344e91b7b35f89adbbdcf17307a78 | 10eccad146f4cfa83c2dde2c78e7859ccbf752f1 | /downwash/canondriver.cpp | cc42cfd48247dea6cc8b271c36654e486ec6b9e6 | [
"BSD-3-Clause"
] | permissive | highfestiva/life | 4b7098432efc46e8dae7bcede4eee39e090d2772 | b05b592502d72980ab55e13e84330b74a966f377 | refs/heads/master | 2020-05-25T15:45:46.557932 | 2019-06-07T11:29:30 | 2019-06-07T11:29:30 | 58,243,887 | 10 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,762 | cpp |
// Author: Jonas Byström
// Copyright (c) Pixel Doctrine
#include "pch.h"
#include "canondriver.h"
#include "../cure/include/contextmanager.h"
#include "../cure/include/health.h"
#include "../lepra/include/random.h"
#include "../life/projectileutil.h"
#include "level.h"
namespace Downwash {
CanonDriver::CanonDriver(DownwashManager* game, cure::GameObjectId canon_id, int ammo_type):
Parent(game->GetResourceManager(), "CanonDriver"),
game_(game),
canon_id_(canon_id),
ammo_type_(ammo_type),
distance_(1000),
shoot_period_(1),
tag_set_(false) {
game->GetContext()->AddLocalObject(this);
game->GetContext()->EnableTickCallback(this);
cure::CppContextObject* canon = (cure::CppContextObject*)manager_->GetObject(canon_id_, true);
deb_assert(canon);
xform muzzle_transform;
vec3 _;
life::ProjectileUtil::GetBarrelByShooter(canon, muzzle_transform, _);
joint_start_angle_ = (muzzle_transform.GetOrientation() * vec3(0,0,1)).GetAngle(vec3(0,0,1));
}
CanonDriver::~CanonDriver() {
}
void CanonDriver::OnTick() {
Parent::OnTick();
cure::CppContextObject* canon = (cure::CppContextObject*)manager_->GetObject(canon_id_, true);
if (!canon) {
manager_->PostKillObject(GetInstanceId());
return;
}
if (!canon->IsLoaded() || canon->GetPhysics()->GetEngineCount() < 1) {
return;
}
if (!tag_set_) {
const tbc::ChunkyClass::Tag* tag = canon->FindTag("behavior", 2, 0);
deb_assert(tag);
distance_ = tag->float_value_list_[0];
shoot_period_ = 1/tag->float_value_list_[1];
tag_set_ = true;
}
cure::ContextObject* avatar = manager_->GetObject(game_->GetAvatarInstanceId());
if (!avatar) {
return;
}
const vec3 target(avatar->GetPosition() + avatar->GetVelocity()*0.2f);
const vec2 d(target.z - canon->GetPosition().z, target.x - canon->GetPosition().x);
if (d.GetLengthSquared() >= distance_*distance_) {
return; // Don't shoot at distant objects.
}
tbc::ChunkyBoneGeometry* barrel = canon->GetPhysics()->GetBoneGeometry(1);
tbc::PhysicsManager::Joint1Diff diff;
game_->GetPhysicsManager()->GetJoint1Diff(barrel->GetBodyId(), barrel->GetJointId(), diff);
const float angle = -d.GetAngle() - (joint_start_angle_ + diff.value_);
const float target_angle = Math::Clamp(angle*20, -2.0f, +2.0f);
canon->SetEnginePower(1, -target_angle);
if (last_shot_.QueryTimeDiff() >= 0) {
float low_angle = 0;
float high_angle = 0;
float bounce;
game_->GetPhysicsManager()->GetJointParams(barrel->GetJointId(), low_angle, high_angle, bounce);
if (std::abs(angle) < std::abs(high_angle-low_angle)*0.1f) {
last_shot_.Start(-Random::Normal(shoot_period_, shoot_period_/4, shoot_period_*0.75f, shoot_period_*1.25f));
game_->Shoot(canon, ammo_type_);
}
}
}
loginstance(kGameContextCpp, CanonDriver);
}
| [
"highfestiva@gmail.com"
] | highfestiva@gmail.com |
9a2ad0b686bc9b6b30d5f05366a8d471314b05f9 | 5a7b71f01b1b2b7538410eada81d26368f295460 | /client/src/convex_counter.h | 57004e8c548cb7bd6f28b7349fb50a0cdad0aef4 | [] | no_license | alkhimey/LatticeAnimals | a7089de97966af22ee27e1ab30a41287fde3016c | 61313c057984e80a5bd885ddd16d444def365e01 | refs/heads/master | 2020-12-29T01:53:31.759182 | 2017-09-03T17:55:57 | 2017-09-03T17:55:57 | 42,391,669 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 784 | h | #include <vector>
#include "counting_algorithm.h"
using namespace std;
namespace redelemeier_with_pruning {
/**
* Improved version that counts convex polycubes in a smart way pruning trees of non convex polycubes.
*/
void line_convex_counter_3d(coord_t n,
coord_t n0,
count_t lowId,
count_t hightId,
vector<count_t>* results,
std::ofstream* dump_file);
/**
* Improved version that counts convex polycubes in a smart way pruning trees of non convex polycubes.
* Counts polycubes according to the full convex defintion
*/
void full_convex_counter_3d(coord_t n,
coord_t n0,
count_t lowId,
count_t hightId,
vector<count_t>* results,
std::ofstream* dump_file);
};
| [
"artium@nihamkin.com"
] | artium@nihamkin.com |
677589e6e0599b114e43c314dccf60d5f1af5873 | 26692ccf4bb943213813b571b11d2d34c4681d85 | /app/src/main/cpp/glm/detail/type_mat4x4.hpp | dcb7269b9fd54539f3852a030b0eea639e080b7b | [
"Apache-2.0"
] | permissive | githubhaohao/NDK_OpenGLES_3_0 | a48990609bfa86933da477996531db4a97127f4c | 5fd276a84703fd8b440d60dfd5125927f88a4c67 | refs/heads/master | 2023-08-21T22:38:55.752538 | 2023-06-16T03:12:54 | 2023-06-16T03:12:54 | 196,941,867 | 2,580 | 694 | Apache-2.0 | 2021-05-04T09:33:12 | 2019-07-15T06:55:25 | C++ | UTF-8 | C++ | false | false | 8,800 | hpp | ///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Mathematics (glm.g-truc.net)
///
/// Copyright (c) 2005 - 2015 G-Truc Creation (www.g-truc.net)
/// 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.
///
/// Restrictions:
/// By making use of the Software for military purposes, you choose to make
/// a Bunny unhappy.
///
/// 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.
///
/// @ref core
/// @file glm/detail/type_mat4x4.hpp
/// @date 2005-01-27 / 2011-06-15
/// @author Christophe Riccio
///////////////////////////////////////////////////////////////////////////////////
#pragma once
#include "../fwd.hpp"
#include "type_vec4.hpp"
#include "type_mat.hpp"
#include <limits>
#include <cstddef>
namespace glm
{
template <typename T, precision P = defaultp>
struct tmat4x4
{
typedef tvec4<T, P> col_type;
typedef tvec4<T, P> row_type;
typedef tmat4x4<T, P> type;
typedef tmat4x4<T, P> transpose_type;
typedef T value_type;
template <typename U, precision Q>
friend tvec4<U, Q> operator/(tmat4x4<U, Q> const & m, tvec4<U, Q> const & v);
template <typename U, precision Q>
friend tvec4<U, Q> operator/(tvec4<U, Q> const & v, tmat4x4<U, Q> const & m);
private:
/// @cond DETAIL
col_type value[4];
/// @endcond
public:
// Constructors
GLM_FUNC_DECL tmat4x4();
GLM_FUNC_DECL tmat4x4(tmat4x4<T, P> const & m);
template <precision Q>
GLM_FUNC_DECL tmat4x4(tmat4x4<T, Q> const & m);
GLM_FUNC_DECL explicit tmat4x4(ctor);
GLM_FUNC_DECL explicit tmat4x4(T const & x);
GLM_FUNC_DECL tmat4x4(
T const & x0, T const & y0, T const & z0, T const & w0,
T const & x1, T const & y1, T const & z1, T const & w1,
T const & x2, T const & y2, T const & z2, T const & w2,
T const & x3, T const & y3, T const & z3, T const & w3);
GLM_FUNC_DECL tmat4x4(
col_type const & v0,
col_type const & v1,
col_type const & v2,
col_type const & v3);
//////////////////////////////////////
// Conversions
template <
typename X1, typename Y1, typename Z1, typename W1,
typename X2, typename Y2, typename Z2, typename W2,
typename X3, typename Y3, typename Z3, typename W3,
typename X4, typename Y4, typename Z4, typename W4>
GLM_FUNC_DECL tmat4x4(
X1 const & x1, Y1 const & y1, Z1 const & z1, W1 const & w1,
X2 const & x2, Y2 const & y2, Z2 const & z2, W2 const & w2,
X3 const & x3, Y3 const & y3, Z3 const & z3, W3 const & w3,
X4 const & x4, Y4 const & y4, Z4 const & z4, W4 const & w4);
template <typename V1, typename V2, typename V3, typename V4>
GLM_FUNC_DECL tmat4x4(
tvec4<V1, P> const & v1,
tvec4<V2, P> const & v2,
tvec4<V3, P> const & v3,
tvec4<V4, P> const & v4);
//////////////////////////////////////
// Matrix conversions
# ifdef GLM_FORCE_EXPLICIT_CTOR
template <typename U, precision Q>
GLM_FUNC_DECL explicit tmat4x4(tmat4x4<U, Q> const & m);
# else
template <typename U, precision Q>
GLM_FUNC_DECL tmat4x4(tmat4x4<U, Q> const & m);
# endif
GLM_FUNC_DECL explicit tmat4x4(tmat2x2<T, P> const & x);
GLM_FUNC_DECL explicit tmat4x4(tmat3x3<T, P> const & x);
GLM_FUNC_DECL explicit tmat4x4(tmat2x3<T, P> const & x);
GLM_FUNC_DECL explicit tmat4x4(tmat3x2<T, P> const & x);
GLM_FUNC_DECL explicit tmat4x4(tmat2x4<T, P> const & x);
GLM_FUNC_DECL explicit tmat4x4(tmat4x2<T, P> const & x);
GLM_FUNC_DECL explicit tmat4x4(tmat3x4<T, P> const & x);
GLM_FUNC_DECL explicit tmat4x4(tmat4x3<T, P> const & x);
//////////////////////////////////////
// Accesses
# ifdef GLM_FORCE_SIZE_FUNC
typedef size_t size_type;
GLM_FUNC_DECL GLM_CONSTEXPR size_t size() const;
GLM_FUNC_DECL col_type & operator[](size_type i);
GLM_FUNC_DECL col_type const & operator[](size_type i) const;
# else
typedef length_t length_type;
GLM_FUNC_DECL GLM_CONSTEXPR length_type length() const;
GLM_FUNC_DECL col_type & operator[](length_type i);
GLM_FUNC_DECL col_type const & operator[](length_type i) const;
# endif//GLM_FORCE_SIZE_FUNC
//////////////////////////////////////
// Unary arithmetic operators
GLM_FUNC_DECL tmat4x4<T, P> & operator=(tmat4x4<T, P> const & m);
template <typename U>
GLM_FUNC_DECL tmat4x4<T, P> & operator=(tmat4x4<U, P> const & m);
template <typename U>
GLM_FUNC_DECL tmat4x4<T, P> & operator+=(U s);
template <typename U>
GLM_FUNC_DECL tmat4x4<T, P> & operator+=(tmat4x4<U, P> const & m);
template <typename U>
GLM_FUNC_DECL tmat4x4<T, P> & operator-=(U s);
template <typename U>
GLM_FUNC_DECL tmat4x4<T, P> & operator-=(tmat4x4<U, P> const & m);
template <typename U>
GLM_FUNC_DECL tmat4x4<T, P> & operator*=(U s);
template <typename U>
GLM_FUNC_DECL tmat4x4<T, P> & operator*=(tmat4x4<U, P> const & m);
template <typename U>
GLM_FUNC_DECL tmat4x4<T, P> & operator/=(U s);
template <typename U>
GLM_FUNC_DECL tmat4x4<T, P> & operator/=(tmat4x4<U, P> const & m);
//////////////////////////////////////
// Increment and decrement operators
GLM_FUNC_DECL tmat4x4<T, P> & operator++();
GLM_FUNC_DECL tmat4x4<T, P> & operator--();
GLM_FUNC_DECL tmat4x4<T, P> operator++(int);
GLM_FUNC_DECL tmat4x4<T, P> operator--(int);
};
// Binary operators
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> operator+(tmat4x4<T, P> const & m, T const & s);
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> operator+(T const & s, tmat4x4<T, P> const & m);
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> operator+(tmat4x4<T, P> const & m1, tmat4x4<T, P> const & m2);
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> operator-(tmat4x4<T, P> const & m, T const & s);
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> operator-(T const & s, tmat4x4<T, P> const & m);
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> operator-(tmat4x4<T, P> const & m1, tmat4x4<T, P> const & m2);
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> operator*(tmat4x4<T, P> const & m, T const & s);
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> operator*(T const & s, tmat4x4<T, P> const & m);
template <typename T, precision P>
GLM_FUNC_DECL typename tmat4x4<T, P>::col_type operator*(tmat4x4<T, P> const & m, typename tmat4x4<T, P>::row_type const & v);
template <typename T, precision P>
GLM_FUNC_DECL typename tmat4x4<T, P>::row_type operator*(typename tmat4x4<T, P>::col_type const & v, tmat4x4<T, P> const & m);
template <typename T, precision P>
GLM_FUNC_DECL tmat2x4<T, P> operator*(tmat4x4<T, P> const & m1, tmat2x4<T, P> const & m2);
template <typename T, precision P>
GLM_FUNC_DECL tmat3x4<T, P> operator*(tmat4x4<T, P> const & m1, tmat3x4<T, P> const & m2);
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> operator*(tmat4x4<T, P> const & m1, tmat4x4<T, P> const & m2);
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> operator/(tmat4x4<T, P> const & m, T const & s);
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> operator/(T const & s, tmat4x4<T, P> const & m);
template <typename T, precision P>
GLM_FUNC_DECL typename tmat4x4<T, P>::col_type operator/(tmat4x4<T, P> const & m, typename tmat4x4<T, P>::row_type const & v);
template <typename T, precision P>
GLM_FUNC_DECL typename tmat4x4<T, P>::row_type operator/(typename tmat4x4<T, P>::col_type & v, tmat4x4<T, P> const & m);
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> operator/(tmat4x4<T, P> const & m1, tmat4x4<T, P> const & m2);
// Unary constant operators
template <typename T, precision P>
GLM_FUNC_DECL tmat4x4<T, P> const operator-(tmat4x4<T, P> const & m);
}//namespace glm
#ifndef GLM_EXTERNAL_TEMPLATE
#include "type_mat4x4.inl"
#endif//GLM_EXTERNAL_TEMPLATE
| [
"haohaochang86@gmail.com"
] | haohaochang86@gmail.com |
7c2f5e023592569ce07374e9da77dbe4092fcff2 | cc6ce8d8a462748f5a5db6a355819d012134b4a1 | /src/cartographer/cartographer/sensor/landmark_data.h | d88a6242adddba0452aa9ea11aae8976b2d4b436 | [
"Apache-2.0"
] | permissive | Xiankuanliu/google_cartographer_commit_version | 721399ab6b0765e01c098caf24473f2a6befdaa4 | 43792f9db6c084540bac781b40f8be8c66936ab3 | refs/heads/master | 2022-04-14T17:29:53.461654 | 2020-04-07T08:11:35 | 2020-04-07T08:11:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,723 | h | /*
* Copyright 2017 The Cartographer Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef CARTOGRAPHER_SENSOR_LANDMARK_DATA_H_
#define CARTOGRAPHER_SENSOR_LANDMARK_DATA_H_
#include <string>
#include "Eigen/Core"
#include "Eigen/Geometry"
#include "cartographer/common/port.h"
#include "cartographer/common/time.h"
#include "cartographer/sensor/proto/sensor.pb.h"
#include "cartographer/transform/rigid_transform.h"
// 路标点类
namespace cartographer {
namespace sensor {
// 观测到路标点结构体
struct LandmarkObservation {
std::string id; //路标点id
transform::Rigid3d landmark_to_tracking_transform; //路标点转换到tracking坐标系的变换
double translation_weight;
double rotation_weight;
};
struct LandmarkData {
common::Time time;
std::vector<LandmarkObservation> landmark_observations;
};
// Converts 'landmark_data' to a proto::LandmarkData.
proto::LandmarkData ToProto(const LandmarkData& landmark_data);
// Converts 'proto' to an LandmarkData.
LandmarkData FromProto(const proto::LandmarkData& proto);
} // namespace sensor
} // namespace cartographer
#endif // CARTOGRAPHER_SENSOR_LANDMARK_DATA_H_
| [
"406780373@qq.com"
] | 406780373@qq.com |
65725aeb29670f7e7cc8ecfccb6943404fe5f909 | 3ce3f3bffbdd447abc7b551f5efdcc0b57920d8e | /src/GTsource.cpp | cfe4d2fd03d35529390b420c812cbe37a6c22b11 | [] | no_license | dongdong-2009/live-app | 9cb8ff84dd0e5eea48679253dfc6c6426800b60c | f4734511511066453ab85c064a5a288d21e74920 | refs/heads/master | 2021-05-27T12:30:19.792659 | 2013-12-19T04:44:10 | 2013-12-19T04:44:10 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 8,972 | cpp | /*
* GTsource.cpp
*
* Created on: 2013-12-9
* Author: yangkun
*/
#include "GTsource.h"
#include "InputFile.hh"
#include "GroupsockHelper.hh"
#include "DataWR.h"
GTsource*
GTsource::createNew(UsageEnvironment& env,
GTParameters params) {
return new GTsource(env, params);
}
EventTriggerId GTsource::eventTriggerId = 0;
unsigned GTsource::referenceCount = 0;
GTsource::GTsource(UsageEnvironment& env,
GTParameters params)
: FramedSource(env), fParams(params) {
is_over = true;
if (referenceCount == 0) {
// Any global initialization of the device would be done here:
//%%% TO BE WRITTEN %%%
}
++referenceCount;
#include <Blocks.h>
dr = new gtsda::DataRead(0,gtsda::block, params.channel);
// Any instance-specific initialization of the device would be done here:
//%%% TO BE WRITTEN %%%
// We arrange here for our "deliverFrame" member function to be called
// whenever the next frame of data becomes available from the device.
//
// If the device can be accessed as a readable socket, then one easy way to do this is using a call to
// envir().taskScheduler().turnOnBackgroundReadHandling( ... )
// (See examples of this call in the "liveMedia" directory.)
//
// If, however, the device *cannot* be accessed as a readable socket, then instead we can implement it using 'event triggers':
// Create an 'event trigger' for this device (if it hasn't already been done):
// if (eventTriggerId == 0) {
// eventTriggerId = envir().taskScheduler().createEventTrigger(deliverFrame0);
// }
}
GTsource::~GTsource() {
// Any instance-specific 'destruction' (i.e., resetting) of the device would be done here:
//%%% TO BE WRITTEN %%%
delete dr;
std::cout << "debug!!" << std::endl;
--referenceCount;
// if (referenceCount == 0) {
// Any global 'destruction' (i.e., resetting) of the device would be done here:
//%%% TO BE WRITTEN %%%
// Reclaim our 'event trigger'
// envir().taskScheduler().deleteEventTrigger(eventTriggerId);
// eventTriggerId = 0;
// }
}
void GTsource::doGetNextFrame() {
// This function is called (by our 'downstream' object) when it asks for new data.
// Note: If, for some reason, the source device stops being readable (e.g., it gets closed), then you do the following:
if (0 /* the source stops being readable */ /*%%% TO BE WRITTEN %%%*/) {
handleClosure(this);
return;
}
// If a new frame of data is immediately available to be delivered, then do this now:
// if (0 /* a new frame of data is immediately available to be delivered*/ /*%%% TO BE WRITTEN %%%*/) {
deliverFrame();
// }
// No new data is immediately available to be delivered. We don't do anything more here.
// Instead, our event trigger must be called (e.g., from a separate thread) when new data becomes available.
}
void GTsource::deliverFrame0(void* clientData) {
((GTsource*)clientData)->deliverFrame();
}
void GTsource::deliverFrame() {
// This function is called when new frame data is available from the device.
// We deliver this data by copying it to the 'downstream' object, using the following parameters (class members):
// 'in' parameters (these should *not* be modified by this function):
// fTo: The frame data is copied to this address.
// (Note that the variable "fTo" is *not* modified. Instead,
// the frame data is copied to the address pointed to by "fTo".)
// fMaxSize: This is the maximum number of bytes that can be copied
// (If the actual frame is larger than this, then it should
// be truncated, and "fNumTruncatedBytes" set accordingly.)
// 'out' parameters (these are modified by this function):
// fFrameSize: Should be set to the delivered frame size (<= fMaxSize).
// fNumTruncatedBytes: Should be set iff the delivered frame would have been
// bigger than "fMaxSize", in which case it's set to the number of bytes
// that have been omitted.
// fPresentationTime: Should be set to the frame's presentation time
// (seconds, microseconds). This time must be aligned with 'wall-clock time' - i.e., the time that you would get
// by calling "gettimeofday()".
// fDurationInMicroseconds: Should be set to the frame's duration, if known.
// If, however, the device is a 'live source' (e.g., encoded from a camera or microphone), then we probably don't need
// to set this variable, because - in this case - data will never arrive 'early'.
// Note the code below.
if (!isCurrentlyAwaitingData()) return; // we're not ready for the data yet
unsigned int num[5]={40000,35000,30000,25000,20000};
unsigned int tmp;
std::cout << "debug video: "<< dr->get_remain_frame_num() << std::endl;
#define algorithm 1
if(!is_over)//ÉÏ´Îû¶ÁÍê
{
is_over = true;
if(left_value>fMaxSize)
{
memmove(fTo, newFrameDataStart + fFrameSize, fMaxSize);
fFrameSize += (left_value-fMaxSize);
left_value -= fMaxSize;
is_over = false;
}
else
{
memmove(fTo, newFrameDataStart + fFrameSize, left_value);
dr->readpool();
newFrameDataStart = (u_int8_t*)( dr->get_the_frame_buffer()->frame_buf); //%%% TO BE WRITTEN %%%
newFrameSize = dr->get_frame_buff_size(); //%%% TO BE WRITTEN %%%
if(newFrameSize + left_value > fMaxSize)
{
is_over = false;
left_value = newFrameSize + left_value - fMaxSize;
fFrameSize = fMaxSize;
fNumTruncatedBytes = newFrameSize + left_value - fMaxSize;
}
else
{
is_over = true;
fFrameSize = newFrameSize + left_value;
#if algorithm
//fDurationInMicroseconds = 40000;
fDurationtime += 40000;
fPresentationTime.tv_sec = fDurationtime / 1000000;
fPresentationTime.tv_usec = fDurationtime % 1000000;
#else
tmp=dr->get_remain_frame_num();
if(tmp>600||tmp<0)
tmp = 0;
else
{
tmp = tmp/100;
std::cout << "debug tmp: "<< tmp<< std::endl;
}
fDurationInMicroseconds = num[tmp];
fDurationtime += num[tmp];
fPresentationTime.tv_sec = fDurationtime / 1000000;
fPresentationTime.tv_usec = fDurationtime % 1000000;
#endif
memmove(fTo+left_value, newFrameDataStart, newFrameSize);
}
}
}
else
{
dr->readpool();
newFrameDataStart = (u_int8_t*)( dr->get_the_frame_buffer()->frame_buf); //%%% TO BE WRITTEN %%%
newFrameSize = dr->get_frame_buff_size(); //%%% TO BE WRITTEN %%%
// Deliver the data here:
if (newFrameSize > fMaxSize)
{
is_over = false;
left_value = newFrameSize - fMaxSize;
fFrameSize = fMaxSize;
fNumTruncatedBytes = newFrameSize - fMaxSize;
}
else
{
is_over = true;
fFrameSize = newFrameSize;
}
if( 0 == fPresentationTime.tv_sec&&0==fPresentationTime.tv_usec)
{
std::cout << "debug1!!" << std::endl;
gettimeofday(&fPresentationTime, NULL); // If you have a more accurate time - e.g., from an encoder - then use that instead.
fDurationtime = fPresentationTime.tv_usec + fPresentationTime.tv_sec*1000000;
//fDurationInMicroseconds = 40000;
}
else
{
//std::cout << "debug2!!" << std::endl;
#if algorithm
//fDurationInMicroseconds = 40000;
fDurationtime += 40000;
fPresentationTime.tv_sec = fDurationtime / 1000000;
fPresentationTime.tv_usec = fDurationtime % 1000000;
#else
tmp=dr->get_remain_frame_num();
if(tmp>600||tmp<0)
tmp = 0;
else
{
tmp = tmp/100;
std::cout << "debug tmp: "<< tmp<< std::endl;
}
fDurationInMicroseconds = num[tmp];
fDurationtime += num[tmp];
fPresentationTime.tv_sec = fDurationtime / 1000000;
fPresentationTime.tv_usec = fDurationtime % 1000000;
#endif
}
// If the device is *not* a 'live source' (e.g., it comes instead from a file or buffer), then set "fDurationInMicroseconds" here.
memmove(fTo, newFrameDataStart, fFrameSize);
}
// After delivering the data, inform the reader that it is now available:
FramedSource::afterGetting(this);
}
// The following code would be called to signal that a new frame of data has become available.
// This (unlike other "LIVE555 Streaming Media" library code) may be called from a separate thread.
// (Note, however, that "triggerEvent()" cannot be called with the same 'event trigger id' from different threads.
// Also, if you want to have multiple device threads, each one using a different 'event trigger id', then you will need
// to make "eventTriggerId" a non-static member variable of "GTsource".)
void signalNewFrameData() {
TaskScheduler* ourScheduler = NULL; //%%% TO BE WRITTEN %%%
GTsource* ourDevice = NULL; //%%% TO BE WRITTEN %%%
if (ourScheduler != NULL) { // sanity check
ourScheduler->triggerEvent(GTsource::eventTriggerId, ourDevice);
}
}
| [
"xyyangkun@gmail.com"
] | xyyangkun@gmail.com |
532b20d2aa3d13c6f2c7b3b82aa461e80f267e77 | 3a4cc9ef55549b3d8e062ed9ebe2311f5455f279 | /osx/opznet/opznetPriv.h | 890bdaaa8c8e854c2fe506a3baa345fbc8162eab | [] | no_license | seobyeongky/opznet | 5a93d0538ac8e886fa1723b72292ef640185f48b | 8443c2f7b4b9e87eac9086c8d36c6ad8b641baf7 | refs/heads/master | 2021-01-19T10:57:30.079119 | 2014-10-14T03:24:34 | 2014-10-14T03:24:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 315 | h | /*
* opznetPriv.h
* opznet
*
* Created by 서병기 on 2014. 10. 14..
* Copyright (c) 2014년 ooparts. All rights reserved.
*
*/
/* The classes below are not exported */
#pragma GCC visibility push(hidden)
class opznetPriv
{
public:
void HelloWorldPriv(const char *);
};
#pragma GCC visibility pop
| [
"byeonggee.seo@redduck.com"
] | byeonggee.seo@redduck.com |
a4e212418d9a3b549e7c24b520c17869cca04935 | 38774bbe5122c4a4328f9a5e6e9f53e8e9b54df9 | /example/falta_revisar/conjunto1.cpp | cc587069d17bd6aba9fcf07f5c59eba0a8fa094f | [] | no_license | Malows/aedcode | b2964985712e4f21cc701545bb341a942e97cd55 | 1b9dc6160b989a7699e8d48049ca6ffb78b24de4 | refs/heads/master | 2021-01-18T11:01:32.422219 | 2011-10-22T00:57:05 | 2011-10-22T00:57:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,059 | cpp | // $Id$
/*
COMIENZO DE DESCRIPCION
Diversas operaciones con conjuntos:
purge : purga elementos repetidos de una lista usando
un conjunto como estructura auxiliar y con
una implementacion tal que sea O (n).
set_intersection : interseccion de conjuntos;
prints : imprime los elementos de un conjunto.
Keywords: conjunto, lista
FIN DE DESCRIPCION */
// -----------------------------------------------------------------
// GNU: g++ -w -c util.cpp
// g++ -w -c conjunto1.cpp
// g++ -w -o conjunto1.exe util.o conjunto1.o
// INTEL: icc -w -c util.cpp
// icc -w -c conjunto1.cpp
// icc -w -o conjunto1.exe util.o conjunto1.o
// -----------------------------------------------------------------
#include <iostream>
#include <list>
#include <set>
#include "./util.h"
using namespace std;
// -------------------------------------------------------------------
// Purgar los elementos repetidos de una lista usando un conjunto
// como estructura auxiliar y con una implementacion de O (n).
//
// Observaciones:
//
// 1) antes, en el tema "listas", vimos una implementacion que
// es O (n^2), la cual tambien esta en los apuntes;
//
// 2) aqui, en "conjuntos", usamos una implementacion de O (n)
// siempre que las operaciones S.find () y S.insert () esten
// eficientemente implementadas como para ser de O (1)
template <class T>
void purge (list <T> & L) {
typename list <T> :: iterator p;
set <T> S;
T x ;
p = L.begin ();
while (p != L.end()) {
x = *p;
if ( S.find (x) != S.end () ) p = L.erase (p);
else {
S.insert(x);
p++;
} // end if
} // end while
} // end void
// -------------------------------------------------------------------
template <class T>
void set_intersection (set <T> & A, set <T> & B,set <T> & C) {
typename set <T> :: iterator p ;
T x ;
C.clear ();
p = A.begin();
while ( p != A.end () ) {
x = *p++;
if ( B.find (x) != B.end () ) C.insert (x);
} // end while
} // end void
// -------------------------------------------------------------------
template <class T>
void prints (set <T> & S) {
typename set <T> :: iterator p ;
p = S.begin ();
while (p != S.end ()) cout << *p++ << " ";
cout << endl;
} // end void
// -----------------------------------------------------------------
int main () {
list <int> L;
set <int> A, B, C;
for (int j = 0 ; j < 20 ; j++) L.insert ( L.end(), irand (20));
cout << endl ;
cout << "Antes de purge " << endl;
printl (L);
purge (L);
cout << endl ;
cout << "Despues de purge " << endl;
printl (L);
for (int j = 0 ; j < 20 ; j++) {
A.insert (irand (40));
B.insert (irand (40));
} // end for
set_intersection (A,B,C);
cout << endl ; cout << "A: ";
prints (A);
cout << endl ; cout << "B: ";
prints (B);
cout << endl ; cout << "C = interseccion (A,B): ";
prints (C);
cout << endl ;
return 0 ;
} // end main
// -----------------------------------------------------------------
| [
"DGalizzi@gmail.com"
] | DGalizzi@gmail.com |
5e27de2188c47e5667cfb5e8fadfc0b43d76d8d2 | 63c7c7e07cf23aa82b6a61a516174da63504f095 | /西北大学新生寒假训练(1)/F.cpp | e65ca22a3bf3ebb3f0802d4fd2c9cda50545ac81 | [] | no_license | Linfanty/Code-in-Freshman | 3b174b6fab510dc1aa214d760f050ca1618afc8d | b60b99f520c4740c6b8306880680a610f054f403 | refs/heads/master | 2021-01-24T12:37:29.255747 | 2018-02-27T15:10:29 | 2018-02-27T15:10:29 | 123,144,148 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 270 | cpp | #include<stdio.h>
#include<string.h>
#include<ctype.h>
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
long long int sum=0;
char s[1000];
scanf("%s",&s);
for(int i=0;i<strlen(s);i++)
{
if(s[i]>= '0' && s[i] <= '9')
sum++;
}
printf("%lld\n",sum);
}
}
| [
"wty2003728@163.com"
] | wty2003728@163.com |
6bd1e2515a04ae1d8028d4a687bd868ea07bfdc0 | 7d23b7237a8c435c3c4324f1b59ef61e8b2bde63 | /include/lua_reg/module.hpp | be3249aa3f84ec220a615e89393e2444fc0e6269 | [] | no_license | chenyu2202863/smart_cpp_lib | af1ec275090bf59af3c29df72b702b94e1e87792 | 31de423f61998f3b82a14fba1d25653d45e4e719 | refs/heads/master | 2021-01-13T01:50:49.456118 | 2016-02-01T07:11:01 | 2016-02-01T07:11:01 | 7,198,248 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 3,841 | hpp | #ifndef __LUA_REG_MODULE_HPP
#define __LUA_REG_MODULE_HPP
#include "config.hpp"
#include "details/function.hpp"
#include "class.hpp"
namespace luareg {
struct state_t;
class module_t
{
state_t &state_;
const char *name_;
public:
module_t(state_t &state, const char *name)
: state_(state)
, name_(name)
{
if( name )
{
::lua_pushstring(state_, name_);
::lua_gettable(state_, LUA_GLOBALSINDEX);
if( lua_isnil(state_, -1) ) // has same name table
{
::lua_pop(state_, 1);
::lua_newtable(state);
::lua_pushstring(state, name_);
::lua_pushvalue(state, -2);
::lua_settable(state, LUA_GLOBALSINDEX);
}
}
else
{
::lua_pushvalue(state_, LUA_GLOBALSINDEX);
}
}
~module_t()
{
lua_pop(state_, 1);
}
module_t(module_t &&rhs)
: state_(rhs.state_)
, name_(rhs.name_)
{}
module_t(const module_t &) = delete;
module_t &operator=(const module_t &) = delete;
public:
template < typename R, typename ...Args >
module_t &operator<<(const details::free_function_t<R, Args...> &func)
{
auto lambda = [](lua_State *l)->int
{
state_t state(l);
typedef typename details::free_function_t<R, Args...>::function_t function_t;
auto function = static_cast<function_t>(::lua_touserdata(state, lua_upvalueindex(1)));
return details::call(state, function);
};
::lua_pushlightuserdata(state_, func.function_);
::lua_pushcclosure(state_, lambda, 1);
::lua_setfield(state_, -2, func.name_);
return *this;
}
template < typename R, typename T, typename ...Args >
module_t &operator<<(const details::class_function_t<R, T, Args...> &func)
{
typedef typename details::class_function_t<R, T, Args...>::function_t function_t;
union implict_cast
{
function_t mem_ptr;
void *ptr;
};
auto lambda = [](lua_State *l)->int
{
state_t state(l);
implict_cast impl_cast;
impl_cast.ptr = ::lua_touserdata(state, lua_upvalueindex(1));
T *obj = static_cast<T *>(::lua_touserdata(state, lua_upvalueindex(2)));
return details::call(state, obj, impl_cast.mem_ptr, 0);
};
implict_cast impl_cast;
impl_cast.mem_ptr = func.function_;
::lua_pushlightuserdata(state_, impl_cast.ptr);
::lua_pushlightuserdata(state_, func.obj_);
::lua_pushcclosure(state_, lambda, 2);
::lua_setfield(state_, -2, func.name_);
return *this;
}
template < typename HandlerT, typename R, typename ...Args >
module_t &operator<<(const details::lambda_function_t<HandlerT, R, std::tuple<Args...>> &func)
{
using function_t = details::lambda_function_t<HandlerT, R, std::tuple<Args...>>::function_t;
auto lambda = [](lua_State *l)->int
{
state_t state(l);
HandlerT *obj = static_cast<HandlerT *>(::lua_touserdata(state, lua_upvalueindex(1)));
return details::call<HandlerT, R, Args...>(state, obj);
};
::lua_pushlightuserdata(state_, (void *)(&func.obj_));
::lua_pushcclosure(state_, lambda, 1);
::lua_setfield(state_, -2, func.name_);
return *this;
}
template < typename T >
module_t &operator[](const class_t<T> &class_val)
{
::lua_pushvalue(state_, 1);
::lua_setfield(state_, -2, class_name_t<T>::name_.c_str());
::lua_pop(state_, 1);
return *this;
}
module_t &operator()(const char *name)
{
::lua_pushstring(state_, name_);
::lua_gettable(state_, LUA_GLOBALSINDEX);
::lua_getfield(state_, -1, name);
if( !lua_istable(state_, -1) )
{
::lua_pop(state_, 1);
::lua_newtable(state_);
::lua_setfield(state_, -2, name);
::lua_getfield(state_, -1, name);
}
return *this;
}
};
inline module_t module(state_t &state, const char *name = nullptr)
{
if( name )
assert(std::strlen(name) != 0);
return module_t(state, name);
}
}
#endif | [
"chenyu2202863@gmail.com"
] | chenyu2202863@gmail.com |
cb79bd4ade4aecbca5df512f0407cede337aca86 | b7a614f1bb6aee241a761a805595d36a05045343 | /test/_lib/test_headers.h | 82433805e606d9ccc40d8e0ecfc12af1e1f137e5 | [] | no_license | sh19910711/contest-old | c67b1497d81e86bab187c86449323be3e82a1b6d | e1dbe590f0ca289faaa8a0a1be9c8acf90ca8af0 | refs/heads/master | 2021-05-27T20:47:13.916226 | 2014-02-03T00:59:09 | 2014-02-03T00:59:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 496 | h | // @snippet<sh19910711/contest-base:headers.cpp>
#define __THIS_IS_CPP11__
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <vector>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <algorithm>
#include <numeric>
#include <limits>
#include <complex>
#include <functional>
#include <iterator>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#ifdef __THIS_IS_CPP11__
#include <memory>
#include <array>
#endif
| [
"sh19910711@gmail.com"
] | sh19910711@gmail.com |
ccdae09e65080938f6e3e145143edbc850aef429 | 24d4ee3f4b18ff42a67694cd64294eb523542ee3 | /baekjoon/1874.cpp | 7da96e118008cca9c2fdd82e0459e715a49214b6 | [] | no_license | solo5star/test | 9d9ab05a647b1bbb212c280e847b92403459c6c4 | 8345250b914556ae07fe7907c19992935ef7e495 | refs/heads/main | 2023-02-28T19:46:40.849783 | 2021-02-08T18:33:51 | 2021-02-08T18:33:51 | 332,493,236 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,207 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <utility>
#include <algorithm>
#include <math.h>
#include <unordered_map>
#include <string>
#include <math.h>
using namespace std;
int stack[100000];
char history[200000];
int historyIndex = 0;
int top = 0;
int current = 1;
inline int peek() {
if (top == 0) return -1;
return stack[top - 1];
}
inline void push() {
history[historyIndex++] = '+';
stack[top++] = current++;
}
inline int pop() {
history[historyIndex++] = '-';
return stack[--top];
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n, number;
bool incomplete = false;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> number;
if (i == 0) {
while (current <= number) push();
pop();
}
else if (current <= number) {
while (current <= number) push();
pop();
}
else if (number < current) {
if (peek() != number) {
incomplete = true;
break;
}
else {
pop();
}
}
}
if (incomplete) {
cout << "NO" << "\n";
}
else {
for (int i = 0; i < historyIndex; i++) {
cout << history[i] << "\n";
}
}
} | [
"solo_5@naver.com"
] | solo_5@naver.com |
95a5e89345063ac3b4f7daaf7cdf0a87a97be6e0 | cf8ddfc720bf6451c4ef4fa01684327431db1919 | /SDK/ARKSurvivalEvolved_DmgType_ProjectileWithImpactFX_TripleTorp_parameters.hpp | f3cbb0a1866e3194084a8d4f0dbfe2febb6b310e | [
"MIT"
] | permissive | git-Charlie/ARK-SDK | 75337684b11e7b9f668da1f15e8054052a3b600f | c38ca9925309516b2093ad8c3a70ed9489e1d573 | refs/heads/master | 2023-06-20T06:30:33.550123 | 2021-07-11T13:41:45 | 2021-07-11T13:41:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 414 | hpp | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_DmgType_ProjectileWithImpactFX_TripleTorp_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"sergey.2bite@gmail.com"
] | sergey.2bite@gmail.com |
4b6c6b3abf920df71b560ff18a2d877bebff436e | 8352ca72d4f1e8e8ebbbb7d6b07a4e0963be7f41 | /DataServer/DataServer_TIP/TA_BASE/transactive/test/TestODBC/TestODBCMysql/src/TestManager.cpp | 5e7240e2bc8e687ee103cad52be75b4a2d450c1e | [] | no_license | radtek/slin_code | 114f61695fc1a23a018da727452c3c42f64ebe39 | a0073e52d600839f7836c2b7673b45b4266259e2 | refs/heads/master | 2020-06-04T15:03:56.618177 | 2015-04-27T10:27:47 | 2015-04-27T10:27:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 887 | cpp | #include "TestManager.h"
#include "TestWorker.h"
#include "TestWorkerTable.h"
#include "TestWorkerTinyODBC.h"
#include "ProjectCommonData.h"
CTestManager::CTestManager( void )
{
// m_pWorker = NULL;
// m_pWorker = new CTestWorker();
// m_pWorker->run();
m_pTestWorkerTable = NULL;
m_pTestWorkerTable = new CTestWorkerTable();
m_pTestWorkerTable->run();
// m_pTestWorkerTinyODBC = NULL;
// m_pTestWorkerTinyODBC = new CTestWorkerTinyODBC();
// m_pTestWorkerTinyODBC->run();
}
CTestManager::~CTestManager( void )
{
// if (NULL != m_pWorker)
// {
// delete m_pWorker;
// m_pWorker = NULL;
// }
if (NULL != m_pTestWorkerTable)
{
delete m_pTestWorkerTable;
m_pTestWorkerTable = NULL;
}
// if (NULL != m_pTestWorkerTinyODBC)
// {
// delete m_pTestWorkerTinyODBC;
// m_pTestWorkerTinyODBC = NULL;
// }
}
| [
"shenglonglinapple@gmail.com"
] | shenglonglinapple@gmail.com |
6762efd617c31bc215b3162716e41292192a256b | 96681d233d1c91d677c0364bcf30491f87fec929 | /Codeforces/Team Selection.cpp | 7fa6a97559185457738199cbf8be6a1a7c6ef1f5 | [] | no_license | CarlosSalazar84/Solutions-Competitive-Programming- | 533669028b0838f977b46e252463948ee16e4082 | 5ef1f736a60eb481a5392a0245970fa112677ba4 | refs/heads/main | 2022-12-31T19:50:45.688585 | 2020-10-16T01:56:43 | 2020-10-16T01:56:43 | 304,451,401 | 0 | 0 | null | 2020-10-16T01:56:44 | 2020-10-15T21:24:38 | C++ | UTF-8 | C++ | false | false | 1,122 | cpp | #include <bits/stdc++.h>
using namespace std;
#define fastIO ios::sync_with_stdio(0), cin.tie(0)
#define endl '\n'
#define ft first
#define sd second
#define pb push_back
#define pob pop_back()
#define pf push_front
#define pof pop_front()
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin, (x).rend()
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<char,char> pcc;
typedef pair<double,double> pdd;
typedef pair<long long,long long> pll;
// scanf("%d %d %d %d",&w,&b,&d,&s); %lld
// printf("%d\n" ,points);
// const double PI=acos(-1);
const int MAX=1e3+5;
const int oo= 1e18;
ll dp[MAX][MAX];
int data[MAX],values[MAX];
int n,k;
ll calculate(int i,int j){
if(j==k) return 0;
if(i==n-k+j+1) return -oo;
if(dp[i][j]!=-1) return dp[i][j];
dp[i][j]=max(calculate(i+1,j),calculate(i+1,j+1)+1LL*data[i]*values[j]);
return dp[i][j];
}
int main(){
memset(dp,-1,sizeof(dp));
cin >> n >> k;
for(int i=0;i<n;i++){
cin >> data[i];
}
for(int i=0;i<k;i++){
cin >> values[i];
}
calculate(0,0);
cout << dp[0][0] << endl;
return 0;
}
| [
"carlos.al.sa.me2002@gmail.com"
] | carlos.al.sa.me2002@gmail.com |
d974a43d5640ac5393dba932a81475a859c30ece | f6cdaaca00a8509f4a868b100905e610bedd5c3e | /Week 3/src/main.cpp | f2d06c7ffdea9b662423ca46b2e30acbcad8b656 | [
"MIT"
] | permissive | ElizaHenderson/GuiPuzzles | abf545249cbda72c2e0a68615b782c713417c132 | 34350f34a15a4ef00f1484003c52840dfe0158b0 | refs/heads/master | 2021-01-18T23:15:02.920950 | 2016-06-01T21:05:38 | 2016-06-01T21:05:38 | 55,809,493 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 430 | cpp | #include <QGuiApplication>
#include <QQmlApplicationEngine>
#include <QQmlContext>
#include "magic_8_ball.h"
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
QQmlApplicationEngine engine;
magic_8_ball cursed_8_ball;
engine.rootContext()->setContextProperty("Cursed_8_ball", &cursed_8_ball);
// Call main.qml
engine.load(QUrl(QStringLiteral("qrc:/main.qml")));
return app.exec();
}
| [
"caffeineloveaffair@gmail.com"
] | caffeineloveaffair@gmail.com |
fd3c0196ba4246562db82fc4f3f2c2e39dd26abd | 5fe634e7327f5f62bcafa356e76d46f07b794b36 | /CPPPrimer/src/13-operator-override/strVec.h | f459139b1978c210bf9a1667bb53bd2fb454851d | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | MarsonShine/Books | 8433bc1a5757e6d85e9cd649347926cfac59af08 | 7265c8a6226408ae687c796f604b35320926ed79 | refs/heads/master | 2023-08-31T05:32:35.202491 | 2023-08-30T10:29:26 | 2023-08-30T10:29:26 | 131,323,678 | 29 | 3 | Apache-2.0 | 2022-12-07T13:01:31 | 2018-04-27T17:00:17 | C# | UTF-8 | C++ | false | false | 3,260 | h | #include <string>
#include <memory>
#include <utility>
class StrVec
{
private:
// 定义下标运算符
std::string& operator [](std::size_t n) { return elements[n]; }
const std::string& operator[](std::size_t n) const { return elements[n]; }
static std::allocator<std::string> alloc;
std::string *elements; // 数组头元素位置
std::string *first_free; // 最后一个元素后的位置(即第一个空闲位置)
std::string *cap; // 指向数组尾后位置的指针
void chk_n_alloc() {
if (size() == capacity()) reallocate();
}
void free();
// 重新分配
void reallocate();
void reallocate_move();
// pair返回两个指针,分别表示新空间的开始位置和拷贝的尾后位置
std::pair<std::string*, std::string*> alloc_n_copy(const std::string*, const std::string*);
public:
StrVec() : elements(nullptr), first_free(nullptr), cap(nullptr) { };
StrVec(const StrVec&);
StrVec& operator=(const StrVec&);
~StrVec();
void push_back(const std::string&);
size_t size() { return first_free - elements; }
size_t capacity() const { return cap - elements; }
std::string *begin() const { return elements; }
std::string *end() const { return first_free; }
};
StrVec::~StrVec()
{
free();
}
void StrVec::push_back(const std::string &s)
{
chk_n_alloc();
alloc.construct(first_free++, s);
}
std::pair<std::string*, std::string*> StrVec::alloc_n_copy(const std::string *ls, const std::string *rs)
{
auto data = alloc.allocate(rs - ls);
return {data, std::uninitialized_copy(ls, rs, data)}; //uninitialized_copy返回的值最后一个构造元素的位置
}
// 释放内存
// destroy元素,然后释放alloc分配的内存
void StrVec::free()
{
// 如果数组存在值
if (elements) {
for (auto p = first_free; p != elements;)
alloc.destroy(--p);
alloc.deallocate(elements, capacity());
}
}
StrVec::StrVec(const StrVec &sv)
{
auto tmp = alloc_n_copy(sv.begin(), sv.end());
elements = tmp.first;
first_free = cap = tmp.second;
}
StrVec &StrVec::operator=(const StrVec &rsv)
{
auto tmp = alloc_n_copy(rsv.begin(), rsv.end());
free();
elements = tmp.first;
first_free = cap = tmp.second;
return *this;
}
void StrVec::reallocate()
{
// 内存大小翻倍
auto new_capacity = size() ? 2 * size() : 1;
// 分配新内存
auto new_data = alloc.allocate(new_capacity);
// 移动具体元素
auto new_first_free = new_data;
auto elem = elements;
for (size_t i = 0; i != size(); ++i)
alloc.construct(new_first_free++, std::move(*elem++));
free();
elements = new_data;
first_free = new_first_free;
cap = elements + new_capacity;
}
// 通过移动迭代器的方式实现地址移动而非值拷贝
void StrVec::reallocate_move()
{
// 内存大小翻倍
auto new_capacity = size() ? 2 * size() : 1;
// 分配新内存
auto first = alloc.allocate(new_capacity);
// 移动元素
auto last = std::uninitialized_copy(std::make_move_iterator(begin()), std::make_move_iterator(end()), first);
free();
elements = first;
first_free = last;
cap = elements + new_capacity;
}
| [
"ms27946@outlook.com"
] | ms27946@outlook.com |
af530bcfa47c6c1f55b94a453325e2ff7fbc230c | 1d4a143eee20929ba83704b4cd5f8fc47550f5e6 | /LineMode.cpp | 294e0daf5057ee24d4af0d25a1c8ff3ab8d2bca2 | [] | no_license | phanvha/DOHOAMAYTINH | 197b6dd59774b43772724a04428e4b572e85b8b0 | a70f448b895906c787bf316c10048d02cb15b08e | refs/heads/master | 2021-07-05T23:26:42.059165 | 2020-12-07T14:06:37 | 2020-12-07T14:06:37 | 213,279,252 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 706 | cpp | #include <winbgim.h>
#include<conio.h>
#define DELAY 10
int color = 2;
void Bresenham(int x1, int y1, int x2, int y2){
int Dx = abs(x2 - x1);
int Dy = abs(y2 - y1);
int p = 2*Dy - Dx;
int c1 = 2*Dy;
int c2 = 2*(Dy-Dx);
int x = x1;
int y = y1;
int x_unit = 1, y_unit = 1;
putpixel(x,y,color);
while(x != x2){
delay(DELAY);
if (p<0) p += c1;
else{
p += c2;
y += y_unit;
}
x += x_unit;
putpixel(x, y, color);
}
}
int main(){
int x1,y1,x2,y2;
int gd,gm=VGAMAX; gd=DETECT;
initgraph(&gd,&gm,NULL);
// setbkcolor(4);
Bresenham(50,150, 300, 200);
delay(9000);
return 0;
}
| [
"pvha.17it3@sict.udn.vn"
] | pvha.17it3@sict.udn.vn |
38cd754a8622b32dc7a0254c15aeaa7cb9426d12 | 3cae667175b2d6aac6d7f3d8189e9a02c38ea1cf | /AtCoder/ABC0/ABC067/B.cpp | 2ad2c6669bbd9bc9a6cad772f821dba5ba736657 | [] | no_license | kokorinosoba/contests | 3ee14acf729eda872ebec9ec7fe3431f50ae23c2 | 6e0dcd7c8ee086650d89fc65616981361b9b20b9 | refs/heads/master | 2022-08-04T13:45:29.722075 | 2022-07-24T08:50:11 | 2022-07-24T08:50:11 | 149,092,111 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 263 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, k; cin >> n >> k;
vector<int> l(n);
for (int& e: l) cin >> e;
sort(l.rbegin(), l.rend());
int ans = 0;
for (int i = 0; i < k; i++) {
ans += l.at(i);
}
cout << ans << endl;
}
| [
"34607448+kokorinosoba@users.noreply.github.com"
] | 34607448+kokorinosoba@users.noreply.github.com |
c3f0f3a0fa1408975a298772c1829b7ef6843579 | 48f83215cee33672cd53e5beee89a1a8cb67aa10 | /__exchequer_pbl/____PB6/cppgen/include/PBGCPPRT.H | 31d7a955b13021127f68823968f8dc570efb18ae | [] | no_license | dimad77771/GUKV | dc6dbe4bc7d01dde2b77ec5082f950ba9d462a6c | 193fecf40a3e1d941747683f99640034b34fc67a | refs/heads/master | 2023-08-18T23:54:56.416948 | 2022-09-25T16:32:29 | 2022-09-25T16:32:29 | 238,393,571 | 0 | 0 | null | 2023-05-31T19:57:59 | 2020-02-05T07:35:19 | C# | UTF-8 | C++ | false | false | 23,423 | h | // Copyright Sybase, Inc. 1996
//
// Sybase, Inc. ("Sybase") claims copyright in this
// program and documentation as an unpublished work, versions of
// which were first licensed on the date indicated in the foregoing
// notice. Claim of copyright does not imply waiver of Sybase's
// other rights.
//
//-----------------------------------------------------------------------------
//
// pbgcpprt.h
//
// C++ wrapper classes for the public ("PBI") runtime interfaces.
//
// PowerBuilder exposes a set of public interfaces on the runtime
// library ("pbvm"). These interfaces, declared in header files
// pbgrunif.h and pbgtypif.h, provide access to a limited set of
// runtime assets and functions to developers working outside of the
// PowerBuilder development environment.
//
// For convenience, several of these interfaces have been further
// wrapped inside of concrete C++ classes, declared below.
//
// Note that these classes are intended for use in the context of C++ code
// emitted by the PowerBuilder C++ generator. The implementations for these
// classes depends on the presence of code segments provided by the generator,
// and they will not function properly if used independently.
//
//-----------------------------------------------------------------------------
#ifndef PBGCPPRT_H
#define PBGCPPRT_H
//-----------------------------------------------------------------------------
// Forward declarations for the PowerBuilder runtime interfaces.
//-----------------------------------------------------------------------------
class PBIUnknown;
class PBIString;
class PBIDateTime;
class PBIDate;
class PBITime;
class PBIDecimal;
class PBIBlob;
class PBIArrayBounds;
class PBIArrayBoundsList;
class PBIArray;
class PBISession;
class PBIInstance;
//-----------------------------------------------------------------------------
// Forward declarations for the concrete C++ wrapper classes.
//-----------------------------------------------------------------------------
class PBUnknown;
class PBString;
class PBDateTime;
class PBDate;
class PBTime;
class PBDecimal;
class PBBlob;
class PBArrayBounds;
class PBArrayBoundsList;
template <class T> class PBArray;
class PBSession;
class PBInstance;
//-----------------------------------------------------------------------------
// PBUnknown
//
// Base class of all interface wrapper types. Manages the pointer to the
// underlying interface instance for all concrete objects.
//
// Intended for use only as a base class. No public interface, cannot
// be independently created or used.
//-----------------------------------------------------------------------------
class PBUnknown
{
protected:
// Constructors, destructor, operator =
PBUnknown( );
PBUnknown( PBIUnknown * );
PBUnknown( const PBUnknown & );
virtual ~PBUnknown( );
PBUnknown & operator = ( const PBUnknown & );
// Interface management.
PBBOOL SetInterface( PBIUnknown * );
PBIUnknown * GetInterface( );
PBIUnknown * GetInterface( ) const;
static PBBOOL SetInterfaceOn( PBUnknown &, PBIUnknown * );
static PBIUnknown * GetInterfaceFrom( const PBUnknown & );
private:
PBIUnknown * m_pInterface;
};
//-----------------------------------------------------------------------------
// PBUnknown inline function implementations.
//-----------------------------------------------------------------------------
inline PBIUnknown * PBUnknown::GetInterface( )
{
return m_pInterface;
}
inline PBIUnknown * PBUnknown::GetInterface( ) const
{
return m_pInterface;
}
inline PBIUnknown * PBUnknown::GetInterfaceFrom( const PBUnknown & other )
{
return other.m_pInterface;
}
//-----------------------------------------------------------------------------
// PBString
//
// Simple null-terminated sequence of characters.
//
// The individual characters in the string are declared to be PBCHAR.
// PBCHAR is defined in header pbgtypes.h to be either an 8-bit ASCII
// character, or a 16-bit wchar_t. The choice of which depends on whether
// symbol UNICODE has been defined.
//-----------------------------------------------------------------------------
class PBString : public PBUnknown
{
public:
// Constructors, destructor, operator =
//
// A null-constructed PBString will NOT be null-valued, but will
// contain an empty string.
// When a PBString is constructed from a PBCHAR *, the PBString will
// make its own copy of the string contents. The caller retains
// ownership of the argument string.
PBString( );
PBString( const PBCHAR * );
PBString( const PBString & );
virtual ~PBString( );
PBString & operator = ( const PBString & other );
// Equality, inequality.
PBBOOL operator == ( const PBString & other ) const;
PBBOOL operator != ( const PBString & other ) const;
// Cast the PBString to PBCHAR *
//
// The PBString retains ownership of the character array pointed to.
// This is only intended to simplify using PBStrings with runtime
// libraries or other functions expecting a character pointer.
// Do not use it to modify or delete the string value!
operator const PBCHAR * ( ) const;
// Accessor functions.
//
// GetValue has the same caveats as the cast operator (see above).
// For GetValueAt( ) and SubString( ), it's the callers responsibility
// to insure that the offsets are in bounds. The values of the
// out parameters are not defined if the offsets are not in bounds.
// All offsets are zero-based.
PBBOOL GetValue( const PBCHAR * & value ) const;
PBBOOL GetLength( PBULONG & length ) const;
PBBOOL GetValueAt( PBULONG offset, PBCHAR & value ) const;
PBBOOL SubString( PBULONG from, PBULONG to, PBString & subString) const;
// IsNull( ) is true if the string has no actual value. Note that
// an empty string is NOT null valued.
// CompareTo( ) populates out argument "comparison" with a value
// greater than, equal to, or less than zero depending on whether "this"
// PBString is greater than, equal to, or less than "other" in value.
PBBOOL IsNull( PBBOOL & isNull ) const;
PBBOOL CompareTo( const PBString & other, PBINT & comparison ) const;
// PBStrings are valid if the underlying interface pointer is not null.
PBBOOL IsValid( ) const;
protected:
PBIString * GetString( );
PBIString * GetString( ) const;
};
//-----------------------------------------------------------------------------
// PBString inline method implementations
//-----------------------------------------------------------------------------
inline PBBOOL PBString::operator != ( const PBString & other ) const
{
return !(*this == other);
}
inline PBIString * PBString::GetString( )
{
return (PBIString *)PBUnknown::GetInterface( );
}
inline PBIString * PBString::GetString( ) const
{
return (PBIString *)PBUnknown::GetInterface( );
}
//-----------------------------------------------------------------------------
// PBDateTime
//
// Contains a date and a time.
//-----------------------------------------------------------------------------
class PBDateTime : public PBUnknown
{
public:
// Constructors, destructor, operator =
PBDateTime( );
PBDateTime( const PBDate & date, const PBTime & time );
PBDateTime( const PBDateTime & );
virtual ~PBDateTime( );
PBDateTime & operator = ( const PBDateTime & );
// Get the constituent date and/or time
PBBOOL GetDate( PBDate & date ) const;
PBBOOL GetTime( PBTime & time ) const;
// IsNull( ) is true if the date and time have no actual value
// CompareTo( ) populates out argument "comparison" with a value
// greater than, equal to, or less than zero, depending on whether
// "this" PBDateTime is earlier than, equal to, or later than "other".
PBBOOL IsNull( PBBOOL & isNull ) const;
PBBOOL CompareTo( const PBDateTime & other, PBINT & comparison) const;
// A PBDateTime is valid if its underlying interface pointer is not null.
PBBOOL IsValid( ) const;
protected:
PBIDateTime * GetDateTime( );
PBIDateTime * GetDateTime( ) const;
};
//-----------------------------------------------------------------------------
// PBDateTime inline method implementations
//-----------------------------------------------------------------------------
inline PBIDateTime * PBDateTime::GetDateTime( )
{
return (PBIDateTime *)PBUnknown::GetInterface( );
}
inline PBIDateTime * PBDateTime::GetDateTime( ) const
{
return (PBIDateTime *)PBUnknown::GetInterface( );
}
//-----------------------------------------------------------------------------
// PBDate
//
// A calendar date.
//-----------------------------------------------------------------------------
class PBDate : public PBUnknown
{
public:
// Constructors, destructor, operator =
PBDate( );
PBDate( PBSHORT iYear, PBINT iMonth, PBINT iDayOfMonth );
PBDate( const PBDate & );
virtual ~PBDate( );
PBDate & operator = ( const PBDate & );
// Get the year, month or day. The day can be retrieved either
// as the day of the month or day of the week.
PBBOOL GetYear( PBSHORT & year ) const;
PBBOOL GetMonth( PBINT & month ) const;
PBBOOL GetDayOfMonth( PBINT & day ) const;
PBBOOL GetDayOfWeek( PBINT & day ) const;
// Compute the difference in days between "this" date and "other".
// The difference will be positive if "other" is later than "this".
PBBOOL DaysAfter( const PBDate & other, PBLONG & days ) const;
// Set out argument "relativeDate" to the date value "days" after
// the current value of "this".
PBBOOL RelativeDate( PBLONG days, PBDate & relativeDate ) const;
// IsNull( ) is true if the date has no actual value.
// CompareTo( ) populates out argument "comparison" with a value
// greater than, equal to, or less than zero, depending on whether
// "this" PBDate is earlier than, equal to, or later than "other".
PBBOOL IsNull( PBBOOL & isNull ) const;
PBBOOL CompareTo( const PBDate & other, PBINT & comparison ) const;
// A PBDate is valid if its underlying interface pointer is not null.
PBBOOL IsValid( ) const;
protected:
PBIDate * GetDate( );
PBIDate * GetDate( ) const;
};
//-----------------------------------------------------------------------------
// PBDate inline method implementations.
//-----------------------------------------------------------------------------
inline PBIDate * PBDate::GetDate( )
{
return (PBIDate *)PBUnknown::GetInterface( );
}
inline PBIDate * PBDate::GetDate( ) const
{
return (PBIDate *)PBUnknown::GetInterface( );
}
//-----------------------------------------------------------------------------
// PBTime
//
// Time of day.
//-----------------------------------------------------------------------------
class PBTime : public PBUnknown
{
public:
// Constructors, destructor, operator =
PBTime( );
PBTime( PBINT iHour, PBINT iMinute, PBINT iSecond );
PBTime( const PBTime & );
virtual ~PBTime( );
PBTime & operator = ( const PBTime & );
// Get the hour, minute, or second element of the time.
PBBOOL GetHour( PBINT & hour ) const;
PBBOOL GetMinute( PBINT & minute ) const;
PBBOOL GetSecond( PBINT & second ) const;
// Compute the difference in seconds between "this" time and "other".
// The difference will be positive if "other" is later than "this".
PBBOOL SecondsAfter( const PBTime & other, PBLONG & seconds ) const;
// Set out argument "relativeTime" to the time value "seconds" after
// the current value of "this".
PBBOOL RelativeTime( PBLONG seconds, PBTime & relativeTime ) const;
// IsNull( ) is true if the time has no actual value.
// CompareTo( ) populates out argument "comparison" with a value
// greater than, equal to, or less than zero, depending on whether
// "this" PBTime is earlier than, equal to, or later than "other".
PBBOOL IsNull( PBBOOL & isNull ) const;
PBBOOL CompareTo( const PBTime & other, PBINT & comparison ) const;
// A PBTime is valid if its underlying interface pointer is not null.
PBBOOL IsValid( ) const;
protected:
PBITime * GetTime( );
PBITime * GetTime( ) const;
};
//-----------------------------------------------------------------------------
// PBTime inline method implementations
//-----------------------------------------------------------------------------
inline PBITime * PBTime::GetTime( )
{
return (PBITime *)PBUnknown::GetInterface( );
}
inline PBITime * PBTime::GetTime( ) const
{
return (PBITime *)PBUnknown::GetInterface( );
}
//-----------------------------------------------------------------------------
// PBDecimal
//
// A signed decimal number with up to 18 digits.
//-----------------------------------------------------------------------------
class PBDecimal : public PBUnknown
{
public:
// Constructors, destructors, operator =
PBDecimal( );
PBDecimal( PBDOUBLE );
PBDecimal( const PBDecimal & );
virtual ~PBDecimal( );
PBDecimal & operator = ( const PBDecimal & );
// Cast the PBDecimal to a PBDOUBLE
operator PBDOUBLE( ) const;
// Get or set the decimal value from a PBDOUBLE
PBBOOL GetValue( PBDOUBLE & value ) const;
PBBOOL SetValue( PBDOUBLE value );
// IsNull( ) is true if the decimal has no actual value.
// CompareTo( ) populates out argument "comparison" with a value
// greater than, equal to, or less than zero, depending on whether
// "this" PBDecimal is greater than, equal to, or less than "other".
PBBOOL IsNull( PBBOOL & isNull ) const;
PBBOOL CompareTo( const PBDecimal & other, PBINT & comparison ) const;
// A PBDecimal is valid if its underlying interface pointer is not null.
PBBOOL IsValid( ) const;
protected:
PBIDecimal * GetDecimal( );
PBIDecimal * GetDecimal( ) const;
};
//-----------------------------------------------------------------------------
// PBIDecimal inline method implementations.
//-----------------------------------------------------------------------------
inline PBIDecimal * PBDecimal::GetDecimal( )
{
return (PBIDecimal *)PBUnknown::GetInterface( );
}
inline PBIDecimal * PBDecimal::GetDecimal( ) const
{
return (PBIDecimal *)PBUnknown::GetInterface( );
}
//-----------------------------------------------------------------------------
// PBBlob
//
// A binary large object.
//-----------------------------------------------------------------------------
class PBBlob : public PBUnknown
{
public:
// Constructors, destructors, operator =
PBBlob( );
PBBlob( PBPVOID pData, PBULONG ulSize );
PBBlob( const PBBlob & );
virtual ~PBBlob( );
PBBlob & operator = ( const PBBlob & );
// Get the size of the data stream and / or a pointer to
// the data stream. The PBBlob retains ownership of the
// data stream -- do not delete or modify the data pointed
// to by the data pointer.
PBBOOL GetSize( PBULONG & size ) const;
PBBOOL GetData( PBPVOID & data ) const;
// Insert or extract binary data into the data stream.
// It is the callers responsibility to insure that the offsets
// are in bounds. If out of bounds, the value of the out argument
// data stream is undefined.
PBBOOL InsertData( PBULONG offset, const PBBlob & data );
PBBOOL ExtractData( PBULONG start, PBULONG size, PBBlob & extract ) const;
// IsNull( ) is true when the blob does not contain any actual data.
// A PBBlob is valid if its underlying interface pointer is not null.
PBBOOL IsNull( PBBOOL & isNull ) const;
PBBOOL IsValid( ) const;
protected:
PBIBlob * GetBlob( );
PBIBlob * GetBlob( ) const;
};
//-----------------------------------------------------------------------------
// PBIBlob inline method implementations
//-----------------------------------------------------------------------------
inline PBIBlob * PBBlob::GetBlob( )
{
return (PBIBlob *)PBUnknown::GetInterface( );
}
inline PBIBlob * PBBlob::GetBlob( ) const
{
return (PBIBlob *)PBUnknown::GetInterface( );
}
//-----------------------------------------------------------------------------
// PBArrayBounds
//
// Defines the minimum and maximum number of entries that can exist in a
// particular dimension of an array.
//-----------------------------------------------------------------------------
class PBArrayBounds : public PBUnknown
{
public:
// Constructors, destructor, operator =
PBArrayBounds( );
PBArrayBounds( PBLONG upper, PBLONG lower );
PBArrayBounds( const PBArrayBounds & );
virtual ~PBArrayBounds( );
PBArrayBounds & operator = ( const PBArrayBounds & );
// Get and / or set the upper and lower bounds of the array
PBBOOL GetUpperBound( PBLONG & ) const;
PBBOOL SetUpperBound( PBLONG );
PBBOOL GetLowerBound( PBLONG & ) const;
PBBOOL SetLowerBound( PBLONG );
// A PBArrayBounds is valid if its underlying interface pointer is not null.
PBBOOL IsValid( ) const;
protected:
PBIArrayBounds * GetArrayBounds( ) const;
PBIArrayBounds * GetArrayBounds( );
};
//-----------------------------------------------------------------------------
// PBArrayBounds inline method implementations.
//-----------------------------------------------------------------------------
inline PBIArrayBounds * PBArrayBounds::GetArrayBounds( ) const
{
return (PBIArrayBounds *)GetInterface( );
}
inline PBIArrayBounds * PBArrayBounds::GetArrayBounds( )
{
return (PBIArrayBounds *)GetInterface( );
}
//-----------------------------------------------------------------------------
// PBArrayBoundsList
//
// A list of array bounds. Used to specify the bounds for all dimensions of
// an array, where one list entry is found for each array dimension.
//-----------------------------------------------------------------------------
class PBArrayBoundsList : public PBUnknown
{
public:
// Constructors, destructor, operator =
PBArrayBoundsList( );
PBArrayBoundsList( const PBArrayBoundsList & );
virtual ~PBArrayBoundsList( );
PBArrayBoundsList & operator = ( const PBArrayBoundsList & );
// Add or remove a bounds instance from the list.
PBBOOL Add( const PBArrayBounds & );
PBBOOL Remove( const PBArrayBounds & );
// Get the number of bounds in the list.
PBBOOL GetCount( PBINDEX & ) const;
// Iterate through the list in either direction.
// These methods return PBFALSE when the end of the list
// is achieved.
PBBOOL GetFirst( PBArrayBounds & );
PBBOOL GetNext( PBArrayBounds & );
PBBOOL GetLast( PBArrayBounds & );
PBBOOL GetPrevious( PBArrayBounds & );
protected:
PBIArrayBoundsList * GetArrayBoundsList( ) const;
PBIArrayBoundsList * GetArrayBoundsList( );
};
//-----------------------------------------------------------------------------
// PBIArrayBoundsList inline method implementations.
//-----------------------------------------------------------------------------
inline PBIArrayBoundsList * PBArrayBoundsList::GetArrayBoundsList( ) const
{
return (PBIArrayBoundsList *)GetInterface( );
}
inline PBIArrayBoundsList * PBArrayBoundsList::GetArrayBoundsList( )
{
return (PBIArrayBoundsList *)GetInterface( );
}
//-----------------------------------------------------------------------------
// PBArray<T>
//
// A templated array type.
//-----------------------------------------------------------------------------
template<class T> class PBArray : public PBUnknown
{
public:
// Constructors, destructor, operator =
PBArray( );
PBArray( const PBArrayBoundsList & pBoundsList );
PBArray( const PBArray<T> & );
virtual ~PBArray( );
PBArray<T> & operator = ( const PBArray<T> & );
// Get / set an array occurence. The arguments are:
// o An array of offsets, one per array dimension
// o The number of offsets (and array dimensions)
// o The value to set / populate
PBBOOL GetValueAt( PBLONG * pOffsets, PBLONG dims, T & value ) const;
PBBOOL SetValueAt( PBLONG * pOffsets, PBLONG dims, const T & value );
// Get the number of dimensions
// Get the bounds array
PBBOOL GetDimensions( PBINDEX & cDimensions ) const;
PBBOOL GetBounds( PBArrayBoundsList & pBoundsList ) const;
// A PBArray is valid if its underlying interface pointer is not null.
PBBOOL IsValid( ) const;
protected:
PBIArray * GetArray( ) const;
PBIArray * GetArray( );
};
//-----------------------------------------------------------------------------
// PBIArray<T> inline method implementations.
//-----------------------------------------------------------------------------
template<class T> inline PBIArray * PBArray<T>::GetArray( ) const
{
return (PBIArray *)GetInterface( );
}
template<class T> inline PBIArray * PBArray<T>::GetArray( )
{
return (PBIArray *)GetInterface( );
}
//-----------------------------------------------------------------------------
// PBSession
//
// Establishes a context for the other classes to operate within the
// PowerBuilder runtime.
//-----------------------------------------------------------------------------
class PBSession : public PBUnknown
{
public:
// Constructors, destructor, operator =
PBSession( );
PBSession( const PBSession & other );
virtual ~PBSession( );
PBSession & operator = ( const PBSession & other );
// A session is valid if its underlying interface is not null.
PBBOOL IsValid( ) const;
protected:
PBISession * GetSession( ) const;
PBISession * GetSession( );
};
//-----------------------------------------------------------------------------
// PBSession inline function implementations
//-----------------------------------------------------------------------------
inline PBISession * PBSession::GetSession( ) const
{
return (PBISession *)GetInterface( );
}
inline PBISession * PBSession::GetSession( )
{
return (PBISession *)GetInterface( );
}
//-----------------------------------------------------------------------------
// PBInstance
//
// The base class for all generated object types.
//-----------------------------------------------------------------------------
class PBInstance : public PBUnknown
{
public:
// Destructor.
virtual ~PBInstance( );
// A PBInstance is valid if its underlying interface is not null.
PBBOOL IsValid( ) const;
// LastErrorMessage( ) will return any error messages created
// by the last operation on the PBInstance.
PBString LastErrorMessage( ) const;
protected:
// Constructors, operator =
PBInstance( const PBSession &, const PBString & );
PBInstance( const PBString &, const PBString & );
PBInstance( const PBInstance & );
PBInstance & operator = ( const PBInstance & );
// Interface management.
PBIInstance * GetInstance( ) const;
PBIInstance * GetInstance( );
void LastErrorMessage( PBString );
private:
PBString m_LastErrorMessage;
};
//-----------------------------------------------------------------------------
// PBInstance inline function implementations.
//-----------------------------------------------------------------------------
inline PBIInstance * PBInstance::GetInstance( ) const
{
return (PBIInstance *)GetInterface( );
}
inline PBIInstance * PBInstance::GetInstance( )
{
return (PBIInstance *)GetInterface( );
}
inline PBString PBInstance::LastErrorMessage( ) const
{
return m_LastErrorMessage;
}
inline void PBInstance::LastErrorMessage( PBString strMessage )
{
m_LastErrorMessage = strMessage;
}
#endif // PBGCPPRT_H
| [
"dima7777@DESKTOP-KCF43RE"
] | dima7777@DESKTOP-KCF43RE |
76e1bc34ea9424dadf625b444b85e31b86f32f9f | e5d976cabcfc10fdf9152e16ef0f488eb91f9c70 | /Source/Layouts/Public/LayoutsCommands.h | 60915923271ba094517054b9ad81e7abdd51107f | [] | no_license | Moiz-BiM/LayoutsPlugin | 4d40550fbd5e165bc0d47172077e26effa3d5014 | 153f96c30cff49ea034bcee1cdf3f3ced4b9686d | refs/heads/master | 2022-10-27T11:02:23.953158 | 2019-05-24T21:40:18 | 2019-05-24T21:40:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 627 | h | // Copyright 1998-2018 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "Framework/Commands/Commands.h"
#include "LayoutsStyle.h"
class FLayoutsCommands : public TCommands<FLayoutsCommands>
{
public:
FLayoutsCommands()
: TCommands<FLayoutsCommands>(TEXT("Layouts"), NSLOCTEXT("Contexts", "Layouts", "Layouts Plugin"), NAME_None, FLayoutsStyle::GetStyleSetName())
{
}
// TCommands<> interface
virtual void RegisterCommands() override;
public:
TSharedPtr< FUICommandInfo > ImportLayout;
TSharedPtr< FUICommandInfo > ExportLayout;
TSharedPtr< FUICommandInfo > RecentLayouts;
}; | [
"alessafur@gmail.com"
] | alessafur@gmail.com |
d3d16b5271c9607d43bc3db4425338fb0447c893 | e6e6c81568e0f41831a85490895a7cf5c929d50e | /yukicoder/6/642.cpp | c26415d938be609092be3fdce0883034e611387f | [] | no_license | mint6421/kyopro | 69295cd06ff907cd6cc43887ce964809aa2534d9 | f4ef43669352d84bd32e605a40f75faee5358f96 | refs/heads/master | 2021-07-02T04:57:13.566704 | 2020-10-23T06:51:20 | 2020-10-23T06:51:20 | 182,088,856 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,043 | cpp |
#include<bits/stdc++.h>
using namespace std;
#define inf INT_MAX
#define INF LLONG_MAX
#define ll long long
#define ull unsigned long long
#define M (int)(1e9+7)
#define P pair<int,int>
#define FOR(i,m,n) for(int i=(int)m;i<(int)n;i++)
#define RFOR(i,m,n) for(int i=(int)m;i>=(int)n;i--)
#define rep(i,n) FOR(i,0,n)
#define rrep(i,n) RFOR(i,n,0)
#define all(a) a.begin(),a.end()
const int vx[4] = {0,1,0,-1};
const int vy[4] = {1,0,-1,0};
#define F first
#define S second
#define PB push_back
#define EB emplace_back
#define int ll
#define vi vector<int>
#define IP pair<int,P>
#define PI pair<P,int>
#define PP pair<P,P>
#define Yes(f){cout<<(f?"Yes":"No")<<endl;}
#define YES(f){cout<<(f?"YES":"NO")<<endl;}
int Madd(int x,int y) {return (x+y)%M;}
int Msub(int x,int y) {return (x-y+M)%M;}
int Mmul(int x,int y) {return (x*y)%M;}
signed main(){
cin.tie(0);
ios::sync_with_stdio(false);
cout<<fixed<<setprecision(20);
int n;
cin>>n;
n--;
int ans=0;
while(n){
ans+=1+!(n&1);
n>>=1;
}
cout<<ans<<endl;
}
| [
"ee177100@meiji.ac.jp"
] | ee177100@meiji.ac.jp |
db184aa4bcf2e0c54c05a7b886481248b3d0c354 | ed840b1b044dc07d3c131bccc8c020958f41efe7 | /leetcode/lengthoflongestsubstring.cpp | 15d43c89da94d37161d396189366b31a6105e739 | [] | no_license | niubin261/awesome-cpp-leetcode | 5fbfc90747cec7d9ab311a229487ee29130be71d | 1a3e86b0f4d45666583b20c594fa55cd69d404a1 | refs/heads/master | 2020-03-18T04:18:50.316159 | 2018-05-21T14:35:53 | 2018-05-21T14:35:53 | 134,281,376 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 578 | cpp | //
// Created by niubin on 17-9-17.
//
#include <string>
#include <iostream>
using namespace std;
class Solution {
public:
int lengthOfLongestSubstring(string s) {
int ans = 0, left = 0, len = s.length();
int last[255];
memset(last, -1, sizeof last);
for (int i = 0; i < len; i++) {
if (last[s[i]] >= left) left = last[s[i]] + 1;
last[s[i]] = i;
ans = max(ans, i - left + 1);
}
return ans;
}
};
int main(){
Solution solution;
cout<<solution.lengthOfLongestSubstring("dvdf");
} | [
"niubin@mail.ustc.edu.cn"
] | niubin@mail.ustc.edu.cn |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.