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 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
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 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
06cbfcb7ca794e640e5896f098522bb8bdba81e7 | 436d5cde84d3ec4bd16c0b663c7fdc68db02a723 | /ch01/e1.16.cpp | b71d72661721ae3692f6a4ef8252ad8a2311029a | [] | no_license | focus000/cppprimer | 31f0cadd1ee69f20a6a2a20fc62ddfa0c5341b83 | c901b55da35922a96857a108d25213fa37121b33 | refs/heads/master | 2020-09-13T04:56:55.130773 | 2020-05-09T09:23:00 | 2020-05-09T09:23:00 | 222,660,434 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 264 | cpp | //
// Created by 李蕴方 on 2019-02-19.
//
#include <iostream>
int main() {
int sum = 0, i = 0;
std::cout << "input: " << std::endl;
while (std::cin >> i) {
sum += i;
}
std::cout << "the sum is: " << sum <<std::endl;
return 0;
} | [
"hanszimmerme@gmail.com"
] | hanszimmerme@gmail.com |
50e0aa78e26f3a06a405b50af70609a15ba9635d | 51f2e9c389af4fe6070a822ca39755ffd20bcd05 | /src/appinfo.cpp | 61a9f0d53829ba519220c8a2c1f7dced37081603 | [
"BSD-3-Clause"
] | permissive | tapir-dream/berserkjs-2.0 | 0927b59e4ac9d2bfaa26aa6297938c8a29427ba2 | b4daf997f4d35e8f2d45807e50df1ff72a31345b | refs/heads/master | 2021-01-22T11:37:01.494648 | 2020-03-26T11:03:02 | 2020-03-26T11:03:02 | 34,240,472 | 9 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,255 | cpp | #include "appinfo.h"
#if defined(Q_OS_WIN32)
#include <w32api.h>
#include <windows.h>
#include <psapi.h>
CRITICAL_SECTION cs; // 供多线程同步的临界区变量
HANDLE hd; // 当前进程的句柄
DWORD t1; // 时间戳
double percent; // 最近一次计算的CPU占用率
__int64 oldp;
// 时间格式转换
__int64 fileTimeToInt64(const FILETIME& time)
{
ULARGE_INTEGER tt;
tt.LowPart = time.dwLowDateTime;
tt.HighPart = time.dwHighDateTime;
return(tt.QuadPart);
}
// 得到进程占用的CPU时间
int getTime(__int64& proc)
{
FILETIME create;
FILETIME exit;
FILETIME ker; // 内核占用时间
FILETIME user; // 用户占用时间
if(!GetProcessTimes(hd, &create, &exit, &ker, &user)){
return -1;
}
proc = (fileTimeToInt64(ker) + fileTimeToInt64(user)) / 10000;
return 0;
}
// 获取内核总数
int getCPUCoresCount()
{
SYSTEM_INFO siSysInfo;
// Copy the hardware information to the SYSTEM_INFO structure.
GetSystemInfo(&siSysInfo);
return siSysInfo.dwNumberOfProcessors;
/*
// Display the contents of the SYSTEM_INFO structure.
printf("Hardware information: \n");
printf(" OEM ID: %u\n", siSysInfo.dwOemId);
printf(" Number of processors: %u\n",
siSysInfo.dwNumberOfProcessors);
printf(" Page size: %u\n", siSysInfo.dwPageSize);
printf(" Processor type: %u\n", siSysInfo.dwProcessorType);
printf(" Minimum application address: %lx\n",
siSysInfo.lpMinimumApplicationAddress);
printf(" Maximum application address: %lx\n",
siSysInfo.lpMaximumApplicationAddress);
printf(" Active processor mask: %u\n",
siSysInfo.dwActiveProcessorMask);s
*/
}
void init()
{
// 初始化线程临界区变量
InitializeCriticalSection(&cs);
// 初始的占用率
percent = 0;
// 得到当前进程id
DWORD pid = GetCurrentProcessId();
// 通过id得到进程的句柄
hd = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
if(hd == NULL){
return;
}
// 得到初始时刻的值
getTime(oldp);
t1 = GetTickCount();
}
void destroy()
{
if(hd != NULL){
CloseHandle(hd);
}
DeleteCriticalSection(&cs);
}
// 进行换算
double cpu()
{
uint time = 15; // 毫秒数。用一个比较少的时间片作为计算单位,这个值可修改
if(hd == NULL) {
return 0;
}
EnterCriticalSection(&cs);
DWORD t2 = GetTickCount();
DWORD dt = t2 - t1;
if(dt > time) {
__int64 proc;
getTime(proc);
percent = ((proc - oldp) * 100)/dt;
t1 = t2;
oldp = proc;
}
LeaveCriticalSection(&cs);
return int(percent/getCPUCoresCount()*10)/10.0;
}
double memory()
{
/*
而内存信息结构的定义如下:
typedef struct _PROCESS_MEMORY_COUNTERS {
DWORD cb;
DWORD PageFaultCount; // 分页错误数目
SIZE_T PeakWorkingSetSize; // 工作集列 ( 物理内存 ) 的最大值
SIZE_T WorkingSetSize; // 工作集列 ( 物理内存 ) 的大小
SIZE_T QuotaPeakPagedPoolUsage; // 分页池的峰值的最大值
SIZE_T QuotaPagedPoolUsage; // 分页池的峰值大小
SIZE_T QuotaPeakNonPagedPoolUsage; // 非分页池的峰值的最大值
SIZE_T QuotaNonPagedPoolUsage; // 非分页池的峰值大小
SIZE_T PagefileUsage; // 页文件页的大小(虚拟内存)
SIZE_T PeakPagefileUsage; // 页文件页的最大值
}
*/
if(hd == NULL) {
return 0;
}
PROCESS_MEMORY_COUNTERS pmc;
pmc.cb = sizeof(PROCESS_MEMORY_COUNTERS);
GetProcessMemoryInfo(hd, &pmc, sizeof(pmc));
// WorkingSetSize 值通常会比在任务管理器中看到的值要大
// 因为它是表示程序使用内存的工作总集
// 而任务管理器中仅仅显示专用内存集
// 其区别在于后者不包括可共享的内存(如加载的DLL)
return (pmc.WorkingSetSize/1024);
}
#endif
#if defined(Q_OS_LINUX) || defined(Q_OS_MAC)
#include <unistd.h>
#include <stdio.h>
#include <sstream>
#include <iostream>
#include <stdlib.h>
#include <QString>
void exec(const char *cmd, char *result)
{
FILE* stream;
char buf[128] = {0};
stream = popen(cmd, "r" );
//将FILE* stream的数据流读取到buf中
fread(buf, sizeof(char), sizeof(buf), stream);
// buf 复制
strcpy(result, buf);
pclose(stream);
}
double cpu()
{
int pid = int(getpid());
char result[128];
std::stringstream newstr;
newstr<<pid;
std::string cmd = "ps aux|grep " + newstr.str() + "|awk '{print $3}'|awk 'NR==1'";
exec(cmd.c_str(), result);
return QString(result).toDouble();
}
double memory()
{
int pid = int(getpid());
char result[128];
std::stringstream newstr;
newstr<<pid;
std::string cmd = "ps aux|grep " + newstr.str() + "|awk '{print $6}'|awk 'NR==1'";
exec(cmd.c_str(), result);
return QString(result).toDouble();
}
#endif
AppInfo::AppInfo()
{
#ifdef Q_OS_WIN32
init();
#endif
}
AppInfo::~AppInfo()
{
#ifdef Q_OS_WIN32
destroy();
#endif
}
double AppInfo::getCPU()
{
return cpu();
}
double AppInfo::getMemory()
{
return memory();
}
| [
"tapir.dream@gmail.com"
] | tapir.dream@gmail.com |
07634842868bb695c4a643d5886a0b4c1d15d82d | e1d6417b995823e507a1e53ff81504e4bc795c8f | /gbk/Common/GameStruct.h | 6cfe483de49b1d4bd0e30d4c3a10f7ce422ecd09 | [] | no_license | cjmxp/pap_full | f05d9e3f9390c2820a1e51d9ad4b38fe044e05a6 | 1963a8a7bda5156a772ccb3c3e35219a644a1566 | refs/heads/master | 2020-12-02T22:50:41.786682 | 2013-11-15T08:02:30 | 2013-11-15T08:02:30 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 36,993 | h |
#ifndef __GAMESTRUCT_H__
#define __GAMESTRUCT_H__
#include "Type.h"
#include "GameDefine.h"
#pragma pack(push, 1)
//用来定义在世界的浮点位置
struct WORLD_POS
{
FLOAT m_fX ;
FLOAT m_fZ ;
WORLD_POS(VOID) : m_fX(0.0f), m_fZ(0.0f) {}
WORLD_POS(FLOAT fX, FLOAT fZ) : m_fX(fX) , m_fZ(fZ) {}
VOID CleanUp( ){
m_fX = 0.0f ;
m_fZ = 0.0f ;
};
WORLD_POS& operator=(WORLD_POS const& rhs)
{
m_fX = rhs.m_fX;
m_fZ = rhs.m_fZ;
return *this;
}
BOOL operator==(WORLD_POS& Ref)
{
return (fabs(m_fX-Ref.m_fX)+fabs(m_fZ-Ref.m_fZ))<0.0001f;
}
BOOL operator==(const WORLD_POS& Ref)
{
return (fabs(m_fX-Ref.m_fX)+fabs(m_fZ-Ref.m_fZ))<0.0001f;
}
};
//用来定义在世界的网格位置
struct MAP_POS
{
Coord_t m_nX ;
Coord_t m_nZ ;
MAP_POS(VOID) : m_nX(0) , m_nZ(0) {}
MAP_POS(Coord_t nX, Coord_t nZ) : m_nX(nX) , m_nZ(nZ) {}
VOID CleanUp( ){
m_nX = 0 ;
m_nX = 0 ;
};
};
//效果状态
struct _EFFECT
{
BOOL m_bActive ;
INT m_Value ; //效果值
INT m_Time ; //效果时间
_EFFECT( )
{
CleanUp( ) ;
}
VOID CleanUp( ){
m_bActive = FALSE ;
m_Value = 0 ;
m_Time = 0 ;
};
BOOL IsActive( ){ return m_bActive ; } ;
VOID SetActive( BOOL bActive ){ m_bActive = bActive ; } ;
};
//怪物生成器初始化数据
struct _MONSTERCREATER_INIT
{
CHAR m_FileName[_MAX_PATH] ;
WORLD_POS m_Position ;
};
#define DEFAULT_ITEMBOX_RECYCLE_TIME 300000 //300秒,5分钟
//装备定义
struct EQUIP_LIST
{
GUID_t m_GUID; //装备类型ID
UINT m_uParam1; //装备属性1
UINT m_uParam2; //装备属性2
};
#define EQUIP_PLAYER_FIXNUM (8) //玩家身上最多可佩戴的装备数
//饰品定义
struct EMBELLISH_LIST
{
GUID_t m_GUID; //饰品类型ID
UINT m_uParam1; //饰品属性1
UINT m_uParam2; //饰品属性2
};
#define EMBELLISH_PLAYER_FIXNUM (6) //玩家身上最多可佩戴的饰品数
//玩家基本序列化信息
struct PLAYER_OWN
{
GUID_t m_nGUID; //玩家完全唯一ID
CHAR m_szName[MAX_CHARACTER_NAME]; //玩家姓名
Coord_t m_nX; //玩家位置X
Coord_t m_nZ; //玩家位置Z
FLOAT m_fDir; //玩家面朝的方向(范围:0~1.0)
//
// 0.25
// \ | /
// 0.5 \ | /
// ---- ---- 0.0 (1.0f)
// / | \
// / | \
// 0.75
PLAYER_OWN( )
{
m_nGUID = INVALID_ID ;
memset( m_szName, 0, MAX_CHARACTER_NAME ) ;
m_nX = 0 ;
m_nZ = 0 ;
m_fDir = 0.0 ;
};
};
struct PLAYER_S
{
GUID_t m_nGUID; //玩家完全唯一ID
CHAR m_szName[MAX_CHARACTER_NAME]; //玩家姓名
Coord_t m_nX; //玩家位置X
Coord_t m_nZ; //玩家位置Z
FLOAT m_fDir; //玩家面朝的方向(范围:0~1.0)
//
// 0.25
// \ | /
// 0.5 \ | /
// ---- ---- 0.0 (1.0f)
// / | \
// / | \
// 0.75
PLAYER_S( )
{
m_nGUID = INVALID_ID ;
memset( m_szName, 0, MAX_CHARACTER_NAME ) ;
m_nX = 0 ;
m_nZ = 0 ;
m_fDir = 0.0 ;
};
};
struct VRECT
{
INT nStartx ;
INT nStartz ;
INT nEndx ;
INT nEndz ;
VRECT( )
{
nStartx = 0 ;
nStartz = 0 ;
nEndx = 0 ;
nEndz = 0 ;
};
BOOL IsContinue( INT x, INT z )const
{
if ( x < nStartx || x > nEndx || z < nStartz || z > nEndz )
return FALSE;
else
return TRUE;
}
};
//一级战斗属性结构
struct _ATTR_LEVEL1
{
INT m_pAttr[CATTR_LEVEL1_NUMBER] ;
_ATTR_LEVEL1( )
{
CleanUp( ) ;
};
INT Get( INT iAttr )const{
Assert( iAttr>=0 && iAttr<CATTR_LEVEL1_NUMBER ) ;
return m_pAttr[iAttr] ;
};
VOID Set( INT iAttr, INT iValue ){
Assert( iAttr>=0 && iAttr<CATTR_LEVEL1_NUMBER ) ;
m_pAttr[iAttr] = iValue ;
} ;
VOID CleanUp()
{
memset( m_pAttr, 0, sizeof(INT)*CATTR_LEVEL1_NUMBER ) ;
} ;
};
//二级战斗属性结构
struct _ATTR_LEVEL2
{
INT m_pAttr[CATTR_LEVEL2_NUMBER] ;
_ATTR_LEVEL2( )
{
memset( m_pAttr, 0, sizeof(INT)*CATTR_LEVEL2_NUMBER ) ;
}
INT Get( INT iAttr ){
Assert( iAttr>=0 && iAttr<CATTR_LEVEL2_NUMBER ) ;
return m_pAttr[iAttr] ;
};
VOID Set( INT iAttr, INT iValue ){
Assert( iAttr>=0 && iAttr<CATTR_LEVEL2_NUMBER ) ;
m_pAttr[iAttr] = iValue ;
} ;
};
//角色所拥有的称号
//#开头的字符串代表是一个字符串资源ID,必须通过表格索引,服务器不用保留这个表格
#define IDTOSTRING(str, strid, strsize) char str[strsize];\
memset(str, 0, strsize);\
sprintf(str, "#%d", strid);\
#define STRINGTOID(str, strid) INT strid = atoi((CHAR*)(str+1));\
struct _TITLE
{
enum
{
NO_TITLE = -1,
GUOJIA_TITLE = 1, //国家称号
BANGPAI_TITLE, //帮派称号
WANFA_TITLE, //玩法称号
MOOD_TITLE, //玩家心情
MAX_NUM_TITLE,
};
struct TITLE_INFO
{
INT m_iTitleID;
INT m_iSuitID; //组合称号ID 单一称号填-1
INT m_iTitleType; //称号类型 国家,帮会,玩法称号
INT m_iBuffID; //称号的BUFFid
UINT m_uTime; //时限title到期时间,无限期的用0
//CHAR m_szFemaleName[32];
//CHAR m_szMaleName[32];
TITLE_INFO()
{
m_iTitleID = INVALID_ID;
m_iSuitID = INVALID_ID;
m_iTitleType= INVALID_ID;
m_iBuffID = INVALID_ID;
m_uTime = 0;
//memset(m_szFemaleName, 0, sizeof(m_szFemaleName));
//memset(m_szMaleName, 0, sizeof(m_szMaleName));
}
};
struct TITLE_COMBINATION //组成称号信息
{
INT m_iGroupID;
INT m_comTitleID;
INT m_arPart[MAX_TITLE_COMBINATION]; //组合成员上限10个
TITLE_COMBINATION ()
{
m_comTitleID = INVALID_ID;
memset(m_arPart, 0, sizeof(INT)*MAX_TITLE_COMBINATION);
}
};
public:
INT m_CurCountryTitle; //当前国家称号ID 无效均为-1
INT m_CurGuildTitle; //当前帮派称号ID 无效均为-1
INT m_CurNormalTitle; //当前普通称号ID 无效均为-1
TITLE_INFO m_TitleArray[MAX_TITLE_SIZE];
CHAR m_szCurCountryTitle[MAX_CHARACTER_TITLE]; //当前国家称号
CHAR m_szCurGuildTitle[MAX_CHARACTER_TITLE]; //当前帮会称号
CHAR m_szCurNormalTitle[MAX_CHARACTER_TITLE]; //当前玩法称号
CHAR m_szOfficialTitleName[MAX_CHARACTER_TITLE]; //自定义官职称号
VOID CleanUp()
{
m_CurCountryTitle = -1;
m_CurGuildTitle = -1;
m_CurNormalTitle = -1;
memset((void*)m_TitleArray, -1, sizeof(TITLE_INFO)*MAX_TITLE_SIZE);
memset((void*)m_szOfficialTitleName, 0, MAX_CHARACTER_TITLE);
memset((void*)m_szCurCountryTitle, 0, MAX_CHARACTER_TITLE);
memset((void*)m_szCurGuildTitle, 0, MAX_CHARACTER_TITLE);
memset((void*)m_szCurNormalTitle, 0, MAX_CHARACTER_TITLE);
}
};
struct ITEM_PICK_CTL
{
ObjID_t OwnerID; //最终的拾取者ID
uint uBetTime; //系统赌博时间
UCHAR uMaxBetPoint; //最大Bet点数
PICK_RULER ePickRuler; //系统控制符号
ITEM_PICK_CTL()
{
CleanUp();
}
VOID CleanUp()
{
OwnerID = INVALID_ID; //无所有者
ePickRuler = IPR_FREE_PICK; //自由拾取
uBetTime = 0; //可以拾取
uMaxBetPoint = 0;
}
};
typedef ITEM_PICK_CTL IPC;
#define MAX_PICKER_COUNT 6
//队伍能参与拾取的人员列表
struct TEAM_PICKER
{
UINT m_uCount;
ObjID_t m_PickerID[MAX_PICKER_COUNT];
TEAM_PICKER()
{
memset(this,0,sizeof(TEAM_PICKER));
}
VOID AddPicker(ObjID_t id)
{
for(UINT nIndex=0;nIndex<m_uCount;nIndex++)
{
if(m_PickerID[nIndex]==id)
return;
}
m_PickerID[m_uCount] = id;
m_uCount++;
}
};
//最大伤害纪录
#define MAX_DAMAGE_REC_COUNT 10
//伤害纪录
struct DAMAGE_RECORD
{
GUID_t m_Killer;
ObjID_t m_KillerObjID;
TeamID_t m_TeamID;
UINT m_uDamage;
DAMAGE_RECORD()
{
CleanUp();
}
void CleanUp()
{
m_Killer = INVALID_ID;
m_KillerObjID = INVALID_ID;
m_TeamID = INVALID_ID;
m_uDamage = 0;
}
};
//伤害队列
struct DAMAGE_MEM_LIST
{
UINT m_uCount;
DAMAGE_RECORD m_DamageRec[MAX_DAMAGE_REC_COUNT];
DAMAGE_MEM_LIST()
{
CleanUp();
}
void CleanUp()
{
m_uCount = 0;
for(int i = 0;i<MAX_DAMAGE_REC_COUNT;i++)
m_DamageRec[i].CleanUp();
}
void AddMember(GUID_t KillerID, ObjID_t KillerObjID, TeamID_t KillerTeam, UINT Damage)
{
if(KillerTeam!=INVALID_ID)
{
m_DamageRec[m_uCount].m_Killer = KillerID;
m_DamageRec[m_uCount].m_KillerObjID = KillerObjID;
m_DamageRec[m_uCount].m_TeamID = KillerTeam;
m_DamageRec[m_uCount].m_uDamage = Damage;
}
else
{
m_DamageRec[m_uCount].m_Killer = KillerID;
m_DamageRec[m_uCount].m_KillerObjID = KillerObjID;
m_DamageRec[m_uCount].m_TeamID = INVALID_ID;
m_DamageRec[m_uCount].m_uDamage = Damage;
}
m_uCount++;
}
void AddMember(DAMAGE_RECORD& dRec)
{
if(dRec.m_TeamID!=INVALID_ID)
{
m_DamageRec[m_uCount].m_Killer = dRec.m_Killer;
m_DamageRec[m_uCount].m_TeamID = dRec.m_TeamID;
m_DamageRec[m_uCount].m_uDamage = dRec.m_uDamage;
}
else
{
m_DamageRec[m_uCount].m_Killer = dRec.m_Killer;
m_DamageRec[m_uCount].m_TeamID = INVALID_ID;
m_DamageRec[m_uCount].m_uDamage = dRec.m_uDamage;
}
m_uCount++;
}
DAMAGE_RECORD* FindMember(GUID_t KillerID)
{
for(UINT i =0;i<m_uCount;i++)
{
if(m_DamageRec[i].m_Killer == KillerID && KillerID!=INVALID_ID)
{
return &m_DamageRec[i];
}
}
return NULL;
}
};
struct _OWN_ABILITY
{
// AbilityID_t m_Ability_ID; 不需要 ID,索引就是 ID
WORD m_Level; // 技能等级
WORD m_Exp; // 技能熟练度
};
#define MAX_MONSTER_DROP_TASK_ITEM 5
#define MAX_MONSTER_KILLER_NUM 18
struct CHAR_OWNER_DROP_LIST
{
ObjID_t HumanID;
UINT DropItemIndex[MAX_MONSTER_DROP_TASK_ITEM];
UINT DropCount;
CHAR_OWNER_DROP_LIST()
{
CleanUp();
}
VOID CleanUp()
{
memset(this,0,sizeof(*this));
}
VOID AddItem(UINT ItemIndex)
{
Assert(DropCount<MAX_MONSTER_DROP_TASK_ITEM);
DropItemIndex[DropCount] = ItemIndex;
DropCount++;
}
};
struct OWNERCHARACTER
{
GUID_t m_Guid;
ObjID_t m_ObjID;
};
struct MONSTER_OWNER_LIST
{
OWNERCHARACTER OwnerDropList[MAX_TEAM_MEMBER];
UINT OwnerCount;
MONSTER_OWNER_LIST()
{
CleanUp();
}
VOID CleanUp()
{
memset(this,0,sizeof(*this));
}
VOID AddOwner(GUID_t HumanID, ObjID_t HumanObjID)
{
if(OwnerCount == MAX_TEAM_MEMBER)
return;
BOOL bAlive = FALSE;
for(UINT i=0; i<OwnerCount; ++i)
{
if(OwnerDropList[i].m_Guid == HumanID)
{
bAlive = TRUE;
}
}
if(!bAlive)
{
OwnerDropList[OwnerCount].m_Guid = HumanID;
OwnerDropList[OwnerCount].m_ObjID = HumanObjID;
OwnerCount++;
}
}
};
struct RELATION_MEMBER
{
GUID_t m_MemberGUID ;
CHAR m_szMemberName[MAX_CHARACTER_NAME] ;
INT m_nLevel; //角色等级
INT m_nMenPai; //门派 MENPAI_ATTRIBUTE
INT m_nPortrait; // 头像
GuildID_t m_GuildID; //帮会ID
struct ReMember_ExtData
{
INT m_nLevel; //角色等级
INT m_nMenPai; //门派 MENPAI_ATTRIBUTE
INT m_nPortrait; //头像
GuildID_t m_GuildID; //帮会ID
};
RELATION_MEMBER( )
{
CleanUp( );
};
VOID CleanUp( )
{
m_MemberGUID = INVALID_ID;
memset( m_szMemberName, 0, sizeof(m_szMemberName) );
m_nLevel = 0;
m_nMenPai = INVALID_JOB;
m_nPortrait = -1;
m_GuildID = INVALID_ID;
};
ReMember_ExtData GetExtData()
{
ReMember_ExtData ExtData;
ExtData.m_nLevel = m_nLevel;
ExtData.m_nMenPai = m_nMenPai;
ExtData.m_nPortrait = m_nPortrait;
ExtData.m_GuildID = m_GuildID;
return ExtData;
}
VOID SetExtData(ReMember_ExtData& ExtData)
{
m_nLevel = ExtData.m_nLevel;
m_nMenPai = ExtData.m_nMenPai;
m_nPortrait = ExtData.m_nPortrait;
m_GuildID = ExtData.m_GuildID;
}
};
struct MarriageInfo
{
GUID_t m_SpouseGUID; // 配偶的 GUID
// UINT m_uWeddingTime; // 婚礼时间
MarriageInfo()
{
CleanUp();
}
VOID CleanUp()
{
m_SpouseGUID = INVALID_ID;
}
};
struct PrenticeInfo
{
// UINT m_uRecruitingTime; // 收徒时间
time_t m_BetrayingTime; // 最后一次叛师时间
UINT m_uMoralPoint; // 师德点
UCHAR m_uPrenticeCount; // 徒弟数量
GUID_t m_PrenticeGUID[MAX_PRENTICE_COUNT]; // 徒弟的 GUID
PrenticeInfo()
{
CleanUp();
}
VOID CleanUp()
{
m_BetrayingTime = 0;
m_uMoralPoint = 0;
m_uPrenticeCount = 0;
for( INT i=0; i<MAX_PRENTICE_COUNT; ++i )
{
m_PrenticeGUID[i] = INVALID_ID;
}
}
};
struct MasterInfo
{
GUID_t m_MasterGUID; // 师傅的 GUID
// UINT m_uApprenticingTime; // 拜师时间
// UINT m_uBetrayingTime; // 上次叛师时间
// UINT m_uBetrayTimes; // 叛师次数
MasterInfo()
{
CleanUp();
}
VOID CleanUp()
{
m_MasterGUID = INVALID_ID;
}
};
class SocketOutputStream ;
class SocketInputStream ;
//邮件
struct MAIL
{
struct MailInfo
{
GUID_t m_GUID; // 发信人 GUID
BYTE m_SourSize ;
INT m_nPortrait; // 发信人头像
BYTE m_DestSize ;
WORD m_ContexSize ;
UINT m_uFlag ; //邮件标志 enum MAIL_TYPE
time_t m_uCreateTime ; //邮件创建时间
//执行邮件应用参数
UINT m_uParam0 ;
UINT m_uParam1 ;
UINT m_uParam2 ;
UINT m_uParam3 ;
};
VOID GetMailInfo(MailInfo& mInfo)
{
mInfo.m_GUID = m_GUID;
mInfo.m_SourSize = m_SourSize;
mInfo.m_nPortrait = m_nPortrait;
mInfo.m_DestSize = m_DestSize;
mInfo.m_ContexSize = m_ContexSize;
mInfo.m_uFlag = m_uFlag;
mInfo.m_uCreateTime = m_uCreateTime;
mInfo.m_uParam0 = m_uParam0;
mInfo.m_uParam1 = m_uParam1;
mInfo.m_uParam2 = m_uParam2;
mInfo.m_uParam3 = m_uParam3;
}
VOID SetMailInfo(MailInfo& mInfo)
{
m_GUID = mInfo.m_GUID;
m_SourSize = mInfo.m_SourSize;
m_nPortrait = mInfo.m_nPortrait;
m_DestSize = mInfo.m_DestSize;
m_ContexSize = mInfo.m_ContexSize;
m_uFlag = mInfo.m_uFlag;
m_uCreateTime = mInfo.m_uCreateTime;
m_uParam0 = mInfo.m_uParam0;
m_uParam1 = mInfo.m_uParam1;
m_uParam2 = mInfo.m_uParam2;
m_uParam3 = mInfo.m_uParam3;
}
GUID_t m_GUID; // 发信人 GUID
BYTE m_SourSize ;
CHAR m_szSourName[MAX_CHARACTER_NAME] ; //发信人
INT m_nPortrait; // 发信人头像
BYTE m_DestSize ;
CHAR m_szDestName[MAX_CHARACTER_NAME] ; //收信人
WORD m_ContexSize ;
CHAR m_szContex[MAX_MAIL_CONTEX] ; //内容
UINT m_uFlag ; //邮件标志 enum MAIL_TYPE
time_t m_uCreateTime ; //邮件创建时间
//执行邮件应用参数
UINT m_uParam0 ;
UINT m_uParam1 ;
UINT m_uParam2 ;
UINT m_uParam3 ;
MAIL( )
{
CleanUp( ) ;
};
VOID CleanUp( )
{
m_GUID = INVALID_INDEX;
m_SourSize = 0 ;
memset( m_szSourName, 0, sizeof(CHAR)*MAX_CHARACTER_NAME ) ;
m_nPortrait = -1;
m_DestSize = 0 ;
memset( m_szDestName, 0, sizeof(CHAR)*MAX_CHARACTER_NAME ) ;
m_ContexSize = 0 ;
memset( m_szContex, 0, sizeof(CHAR)*MAX_MAIL_CONTEX ) ;
m_uFlag = MAIL_TYPE_NORMAL ;
m_uCreateTime = 0 ;
m_uParam0 = 0 ;
m_uParam1 = 0 ;
m_uParam2 = 0 ;
m_uParam3 = 0 ;
};
VOID Read( SocketInputStream& iStream ) ;
VOID Write( SocketOutputStream& oStream ) const ;
};
#define MAX_MAIL_SIZE 20
struct MAIL_LIST
{
MAIL m_aMail[MAX_MAIL_SIZE] ;
BYTE m_Count ;//邮件数量
BYTE m_TotalLeft ;//用户帐号里的邮件剩余数量
MAIL_LIST( )
{
CleanUp( ) ;
};
VOID CleanUp( )
{
m_Count = 0 ;
m_TotalLeft = 0 ;
for( INT i=0;i<MAX_MAIL_SIZE; i++ )
{
m_aMail[i].CleanUp() ;
}
};
VOID Read( SocketInputStream& iStream ) ;
VOID Write( SocketOutputStream& oStream ) const ;
};
// 批量邮件,指发送给不同人的同内容邮件
#define MAX_RECEIVER 100
struct BATCH_MAIL
{
GUID_t m_GUID; // GUID
BYTE m_SourSize;
CHAR m_szSourName[MAX_CHARACTER_NAME]; //发信人
BYTE m_ReceiverCount; //收信人数量
struct
{
BYTE m_DestSize;
CHAR m_szDestName[MAX_CHARACTER_NAME]; //收信人
}m_Receivers[MAX_RECEIVER];
WORD m_ContentSize;
CHAR m_szContent[MAX_MAIL_CONTEX]; //内容
UCHAR m_uFlag; //邮件标志 enum MAIL_TYPE
time_t m_uCreateTime; //邮件创建时间
BATCH_MAIL() { CleanUp(); }
GUID_t GetGUID( )
{
return m_GUID;
}
VOID SetGUID( GUID_t guid )
{
m_GUID = guid;
}
const CHAR* GetSourName()
{
return m_szSourName;
}
VOID SetSourName( const CHAR* szName )
{
strncpy(m_szSourName, szName, MAX_CHARACTER_NAME - 1);
m_SourSize = (UCHAR)strlen(m_szSourName);
}
BYTE GetReceiverCount()
{
return m_ReceiverCount;
}
const CHAR* GetDestName(BYTE idx)
{
if( idx >= m_ReceiverCount )
{
Assert( idx );
return NULL;
}
return m_Receivers[idx].m_szDestName;
}
VOID AddDestName( const CHAR* szName )
{
strncpy(m_Receivers[m_ReceiverCount].m_szDestName, szName, MAX_CHARACTER_NAME - 1);
m_Receivers[m_ReceiverCount].m_DestSize = (UCHAR)strlen(m_Receivers[m_ReceiverCount].m_szDestName);
++m_ReceiverCount;
}
const CHAR* GetMailContent()
{
return m_szContent;
}
VOID SetMailContent( const CHAR* szContent )
{
strncpy(m_szContent, szContent, MAX_MAIL_CONTEX - 1);
m_ContentSize = (UCHAR)strlen(m_szContent);
}
UCHAR GetMailFlag()
{
return m_uFlag;
}
VOID SetMailFlag(UCHAR uFlag)
{
m_uFlag = uFlag;
}
time_t GetCreateTime()
{
return m_uCreateTime;
}
VOID SetCreateTime(time_t uCreateTime)
{
m_uCreateTime = uCreateTime;
}
VOID CleanUp();
UINT GetSize() const;
VOID Read( SocketInputStream& iStream );
VOID Write( SocketOutputStream& oStream ) const;
};
struct USER_SIMPLE_DATA
{
CHAR m_Name[MAX_CHARACTER_NAME]; // 此用户的角色名字
CHAR m_Account[MAX_ACCOUNT_LENGTH]; // 此角色所在账号
GUID_t m_GUID; // 此用户的唯一号
INT m_nCountry; // 国家
UINT m_uMenPai; // 门派
INT m_nPortrait; // 头像
UCHAR m_uFaceMeshID; // 脸部模型
UCHAR m_uHairMeshID; // 头发模型
UINT m_uHairColor; // 发色
INT m_nLevel; // 级别
USHORT m_uSex; // 性别
CHAR m_szTitle[MAX_CHARACTER_TITLE]; // 称号
GuildID_t m_GuildID; // 帮会 ID
CHAR m_szGuildName[MAX_GUILD_NAME_SIZE]; // 帮会名字
CHAR m_szFamilyName[MAX_GUILD_FAMILY_NAME_SIZE]; // 家族名字
INT m_iPostCode; // 邮编号
UINT m_uMoney; //角色身上货币
UINT m_uBankMoney; //角色银行货币
USER_SIMPLE_DATA( )
{
CleanUp( ) ;
}
VOID CleanUp( )
{
memset( m_Name, 0, sizeof(m_Name) );
memset( m_Account, 0, sizeof(m_Account) );
m_GUID = INVALID_ID;
m_nCountry = INVALID_COUNTRY;
m_uMenPai = INVALID_JOB;
m_nPortrait = -1;
m_nLevel = 0;
m_uSex = 0;
memset( m_szTitle, 0, sizeof(m_szTitle) );
memset( m_szGuildName, 0, sizeof(m_szGuildName));
memset( m_szFamilyName, 0, sizeof(m_szFamilyName));
m_GuildID = INVALID_ID;
m_iPostCode = 0;
m_uMoney = 0;
m_uBankMoney = 0;
}
};
#define MAX_SQL_LENGTH 4096
#define MAX_LONG_SQL_LENGTH 204800
struct DB_QUERY
{
UCHAR m_SqlStr[MAX_SQL_LENGTH]; //执行的Sql语句
VOID Clear()
{
memset(m_SqlStr,0,MAX_SQL_LENGTH);
}
VOID Parse(const CHAR* pTemplate,...);
};
struct LONG_DB_QUERY
{
UCHAR m_SqlStr[MAX_LONG_SQL_LENGTH]; //执行的Sql语句
VOID Clear()
{
memset(m_SqlStr,0,MAX_LONG_SQL_LENGTH);
}
VOID Parse(const CHAR* pTemplate,...);
};
struct DB_CHAR_EQUIP_LIST
{
DB_CHAR_EQUIP_LIST()
{
CleanUp();
}
VOID CleanUp()
{
memset(this,0,sizeof(*this));
}
UINT m_Equip[HEQUIP_NUMBER]; //装备
};
struct DB_CHAR_BASE_INFO
{
DB_CHAR_BASE_INFO()
{
CleanUp();
}
VOID CleanUp()
{
memset(this,0,sizeof(*this));
m_Menpai = INVALID_JOB; //角色门派
m_Country = INVALID_COUNTRY; //国家
m_Sex = INVALID_SEX;
}
GUID_t m_GUID; //角色全局编号
BYTE m_Sex; //性别
CHAR m_Name[MAX_CHARACTER_NAME]; //角色名字
INT m_Level; //角色等级
UINT m_HairColor; //头发颜色
BYTE m_FaceColor; //脸形颜色
BYTE m_HairModel; //头发模型
BYTE m_FaceModel; //脸形模型
SceneID_t m_StartScene; //角色所在场景
INT m_Menpai; //角色门派
INT m_HeadID; //头部编号
DB_CHAR_EQUIP_LIST m_EquipList; //装备列表
INT m_Country; //国家
};
// 队员列表中的队员信息项
struct TEAM_LIST_ENTRY
{
GUID_t m_GUID; // GUID
SceneID_t m_SceneID; // 场景ID
ID_t m_SceneResID; // 场景资源 ID
UINT m_ExtraID; // 队员的 PlayerID(WG) 或 ObjID(GC)
UCHAR m_NameSize; // 姓名长度
CHAR m_Name[MAX_CHARACTER_NAME]; // 队员的名字
INT m_nPortrait; // 头像
USHORT m_uDataID; // 队员的性别
UINT m_uFamily; // 2.门派
TEAM_LIST_ENTRY( )
{
CleanUp( );
};
VOID CleanUp( )
{
m_GUID = INVALID_ID;
m_SceneID = INVALID_ID;
m_SceneResID = INVALID_ID;
m_ExtraID = INVALID_ID;
m_NameSize = 0;
memset (m_Name, 0, sizeof(m_Name));
m_nPortrait = -1;
m_uDataID = 0;
m_uFamily = 0;
};
TEAM_LIST_ENTRY& operator= ( const TEAM_LIST_ENTRY& entry )
{
m_GUID = entry.m_GUID;
m_SceneID = entry.m_SceneID;
m_SceneResID = entry.m_SceneResID;
m_ExtraID = entry.m_ExtraID;
m_NameSize = entry.m_NameSize;
strncpy ( m_Name, entry.m_Name, sizeof(m_Name) - 1 );
m_nPortrait = entry.m_nPortrait;
m_uDataID = entry.m_uDataID;
m_uFamily = entry.m_uFamily;
return *this;
}
VOID SetGUID( GUID_t guid ) { m_GUID = guid; }
GUID_t GetGUID( ) const { return m_GUID; }
VOID SetSceneID( SceneID_t SceneID ) { m_SceneID = SceneID; }
SceneID_t GetSceneID( ) const { return m_SceneID; }
VOID SetSceneResID( ID_t SceneID ) { m_SceneResID = SceneID; }
ID_t GetSceneResID( ) const { return m_SceneResID; }
VOID SetExtraID( UINT id ) { m_ExtraID = id; }
UINT GetExtraID( ) const { return m_ExtraID; }
VOID SetName( const CHAR* pName )
{
strncpy ( m_Name, pName, MAX_CHARACTER_NAME-1 );
m_NameSize = (UCHAR)strlen(m_Name);
}
const CHAR* GetName( ) const { return m_Name; }
VOID SetIcon( INT icon ) { m_nPortrait = icon; }
INT GetIcon( ) const { return m_nPortrait; }
VOID SetDataID(USHORT dataid) { m_uDataID = dataid; }
USHORT GetDataID() const { return m_uDataID; }
VOID SetFamily(UINT uFamily) { m_uFamily = uFamily; }
UINT GetFamily() const { return m_uFamily; }
UINT GetSize() const;
VOID Read( SocketInputStream& iStream );
VOID Write( SocketOutputStream& oStream ) const;
};
//ID List
typedef struct _ObjID_List
{
enum
{
MAX_LIST_SIZE = 512,
};
_ObjID_List()
{
CleanUp();
}
VOID CleanUp(VOID)
{
m_nCount=0;
memset((VOID*)m_aIDs, INVALID_ID, sizeof(m_aIDs));
}
INT m_nCount;
ObjID_t m_aIDs[MAX_LIST_SIZE];
} ObjID_List;
//玩家商店的唯一ID
struct _PLAYERSHOP_GUID
{
ID_t m_World ; //世界号:
ID_t m_Server ; //服务端程序号:
ID_t m_Scene ; //场景号
INT m_PoolPos ; //数据池位置
_PLAYERSHOP_GUID()
{
Reset();
}
_PLAYERSHOP_GUID& operator=(_PLAYERSHOP_GUID const& rhs)
{
m_PoolPos = rhs.m_PoolPos;
m_Server = rhs.m_Server;
m_World = rhs.m_World;
m_Scene = rhs.m_Scene;
return *this;
}
BOOL operator ==(_PLAYERSHOP_GUID& Ref) const
{
return (Ref.m_Scene==m_Scene)&&(Ref.m_PoolPos==m_PoolPos)&&(Ref.m_Server==m_Server)&&(Ref.m_World==m_World);
}
BOOL isNull() const
{
return (m_Scene ==INVALID_ID)&&(m_World ==INVALID_ID)&&(m_PoolPos==-1)&&(m_Server == INVALID_ID);
}
VOID Reset()
{
m_PoolPos = -1;
m_Server = INVALID_ID;
m_World = INVALID_ID;
m_Scene = INVALID_ID;
}
};
enum SM_COMMANDS
{
CMD_UNKNOW,
CMD_SAVE_ALL,
CMD_CLEAR_ALL,
};
struct SM_COMMANDS_STATE
{
SM_COMMANDS cmdType;
union
{
INT iParam[6];
FLOAT fParam[6];
CHAR cParam[24];
};
};
struct GLOBAL_CONFIG
{
GLOBAL_CONFIG()
{
Commands.cmdType = CMD_UNKNOW;
}
SM_COMMANDS_STATE Commands;
};
//密保相关
#define MIBAOUNIT_NAME_LENGTH 2 //每个键值的长度
#define MIBAOUNIT_VALUE_LENGTH 2 //每个数值的长度
#define MIBAOUNIT_NUMBER 3 //密保卡一组有效数据的密保单元个数
//7×7
#define MIBAO_TABLE_ROW_MAX 7 //密保使用的表的最大行数
#define MIBAO_TABLE_COLUMN_MAX 7 //密保使用的表的最大列数
//密保单元
struct MiBaoUint
{
BYTE row;
BYTE column;
CHAR key[MIBAOUNIT_NAME_LENGTH+1];
CHAR value[MIBAOUNIT_VALUE_LENGTH+1];
MiBaoUint()
{
CleanUp();
}
VOID CleanUp()
{
row = column = BYTE_MAX;
memset(key,0,MIBAOUNIT_NAME_LENGTH+1);
memset(value,0,MIBAOUNIT_VALUE_LENGTH+1);
}
BOOL IsSame(const MiBaoUint& mu) const
{
if(row >= MIBAO_TABLE_ROW_MAX || column >= MIBAO_TABLE_COLUMN_MAX) return FALSE;
return (row == mu.row && column == mu.column)?TRUE:FALSE;
}
};
//创建人物验证码
struct CreateCode
{
USHORT code[ANASWER_LENGTH_1];
CreateCode()
{
CleanUp();
}
VOID CleanUp()
{
memset(code,0,sizeof(USHORT)*ANASWER_LENGTH_1);
}
BOOL IsSame(CreateCode* pcd)
{
//CreateCode tmp;
//if(memcmp(code,tmp.code,sizeof(USHORT)*ANASWER_LENGTH_1) == 0)
// return FALSE;
if(!pcd) return FALSE;
return (memcmp(code,pcd->code,sizeof(USHORT)*ANASWER_LENGTH_1) == 0);
}
};
//一组密保数据
struct MiBaoGroup
{
MiBaoUint unit[MIBAOUNIT_NUMBER];
MiBaoGroup()
{
CleanUp();
}
VOID CleanUp()
{
for(INT i = 0; i < MIBAOUNIT_NUMBER; ++i) unit[i].CleanUp();
}
BOOL IsAlreadyHaveUnit(BYTE row,BYTE column)
{
if(/*row < 0 || */row >= MIBAO_TABLE_ROW_MAX || /*column < 0 || */column >= MIBAO_TABLE_COLUMN_MAX) return TRUE;
MiBaoUint tu;
tu.row = row;
tu.column = column;
for(INT i = 0; i < MIBAOUNIT_NUMBER; ++i)
{
if(TRUE == unit[i].IsSame(tu)) return TRUE;
}
return FALSE;
}
const CHAR* GetMiBaoKey(INT idx) const
{
if(idx < 0 || idx >= MIBAOUNIT_NUMBER) return NULL;
return unit[idx].key;
}
};
//////////////////////////////////////////////////////
// 抽奖相关操作数据
//////////////////////////////////////////////////////
#define MAX_PRIZE_STRING 20 //参见《天龙八部推广员帐号领奖通信协议》中的奖品代码长度定义
#define MAX_PRIZE_NUMBER 30 //一次最多领30个不同种类的奖品
#define MAX_NEWUSER_CARD_SIZE 20 //新手卡长度
enum PRIZE_TYPE_ENUM
{
PRIZE_TYPE_INVALID = 0,
PRIZE_TYPE_CDKEY = 1, //推广员
PRIZE_TYPE_YUANBAO = 2, //元宝
PRIZE_TYPE_NEWUSER = 3, //新手卡(财富卡)
PRIZE_TYPE_ZENGDIAN = 4, //赠点
PRIZE_TYPE_ITEM = 5, //物品
PRIZE_TYPE_SPORTS = 6, //体育竞猜卡
PRIZE_TYPE_JU = 7, //网聚活动卡
};
//Billing返回的奖品结构
struct _PRIZE_DATA
{
CHAR m_PrizeString[MAX_PRIZE_STRING]; //奖品代码
BYTE m_PrizeNum; //奖品数量
_PRIZE_DATA()
{
memset(m_PrizeString,0,MAX_PRIZE_STRING);
m_PrizeNum = 0;
}
static UINT getSize()
{
return sizeof(CHAR)*MAX_PRIZE_STRING+sizeof(BYTE);
}
};
//Billing返回的购买结构
struct _RETBUY_DATA
{
UINT m_BuyInt; //商品代码(元宝)
USHORT m_BuyNumber; //商品数量
_RETBUY_DATA()
{
m_BuyInt = 0;
m_BuyNumber = 0;
}
static UINT getSize()
{
return sizeof(UINT)+sizeof(USHORT);
}
};
//商品结构
struct _BUY_DATA
{
CHAR m_BuyString[MAX_PRIZE_STRING]; //商品代码(CD-KEY)
UINT m_BuyPoint; //商品消耗点数
UINT m_BuyInt; //商品代码(元宝)
UINT m_BuyNumber; //商品数量
_BUY_DATA()
{
memset(m_BuyString,0,MAX_PRIZE_STRING);
m_BuyPoint = 0;
m_BuyInt = 0;
m_BuyNumber = 0;
}
BYTE GetPrizeType(); //奖品类型
UINT GetPrizeSerial(); //奖品序列号
BYTE GetPrizeNum(); //奖品数量
UINT GetCostPoint(); //消耗点数
VOID GetSubString(INT nIdx,CHAR* pBuf,INT nBufLength); //拆分奖品字串
BYTE GetGoodsType(); //商品类型
USHORT GetGoodsNum(); //商品数量
};
#define MAX_CHOOSE_SCENE_NUMBER 10
struct DB_CHOOSE_SCENE
{
DB_CHOOSE_SCENE()
{
CleanUp();
}
VOID CleanUp()
{
memset(this,0,sizeof(*this));
}
CHAR mSceneCount;
SceneID_t mSceneID[MAX_CHOOSE_SCENE_NUMBER];
};
struct CFG_CHOOSE_SCENE
{
CFG_CHOOSE_SCENE()
{
CleanUp();
}
VOID CleanUp()
{
memset(this,0,sizeof(*this));
}
CHAR mSceneCount;
SceneID_t mSceneID[MAX_CHOOSE_SCENE_NUMBER];
WORLD_POS mPos[MAX_CHOOSE_SCENE_NUMBER];
};
//帐号安全相关
enum _ACCOUNT_SAFE_FLAG
{
ASF_BIND_NONE = 0,
ASF_BIND_IP =2, //IP绑定
ASF_BIND_MIBAOKA = 4, //密保卡绑定
ASF_BIND_MOBILE_PHONE = 8, //手机绑定
ASF_BIND_MAC = 16, //MAC绑定
ASF_BIND_REALNAME = 32, //实名验证过(公安局数据库验证过)
ASF_BIND_INPUTNAME = 64, //填写过实名(玩家在WEB上填写过实名的信息,但尚未通过公安局数据库验证)
};
typedef struct tag_AccountSafeSign
{
INT m_Sign;
tag_AccountSafeSign()
{
CleanUp();
}
VOID CleanUp()
{
m_Sign = ASF_BIND_NONE;
}
BOOL IsBindSafeSign(INT nSign)
{
switch(nSign)
{
case ASF_BIND_IP:
case ASF_BIND_MIBAOKA:
case ASF_BIND_MOBILE_PHONE:
case ASF_BIND_MAC:
case ASF_BIND_REALNAME:
case ASF_BIND_INPUTNAME:
return (m_Sign & nSign)?TRUE:FALSE;
case ASF_BIND_NONE:
default:
return FALSE;
}
return FALSE;
}
VOID SetBindSafeSign(INT nSign,BOOL bSet = TRUE)
{
switch(nSign)
{
case ASF_BIND_IP:
case ASF_BIND_MIBAOKA:
case ASF_BIND_MOBILE_PHONE:
case ASF_BIND_MAC:
case ASF_BIND_REALNAME:
case ASF_BIND_INPUTNAME:
(bSet)?(m_Sign |= nSign):(m_Sign &= ~nSign);
break;
case ASF_BIND_NONE:
default:
break;
}
}
}AccountSafeSign;
//消费记录结构
struct _COST_LOG
{
CHAR m_SerialKey[MAX_PRIZE_SERIAL_LENGTH+1]; //消费序列号
INT m_WorldId; //World号
INT m_ServerId; //Server号
INT m_SceneId; //Scene号
GUID_t m_UserGUID; //用户GUID
INT m_UserLevel; //用户等级
LONG m_CostTime; //消费时间(自1970-01-01 的秒数)
INT m_YuanBao; //消耗的元宝数
CHAR m_AccName[MAX_ACCOUNT+1]; //帐号
CHAR m_CharName[MAX_CHARACTER_NAME+1]; //角色
CHAR m_Host[IP_SIZE+1]; //IP
CHAR m_OtherInfo[MAX_COST_OTHER_SIZE+1]; //Log的备注信息
_COST_LOG()
{
CleanUp();
}
VOID CleanUp()
{
memset( this, 0, sizeof(*this) ) ;
m_UserGUID = INVALID_GUID;
}
BOOL IsSame(const CHAR* pSerial)
{
return (0 == strcmp(pSerial,m_SerialKey))?TRUE:FALSE;
}
};
// add by gh for souxia 2010/05/10
//1 将 SOUXIA_DATA 中固定属性,退化为通过查表获取
struct SouXia_Skill
{
SkillID_t StudySkillId[MAX_SKILL_COUNT]; // 学习过的Skill 索引
BYTE StudyCount;
//加个赋值重载,用来做交换用
SouXia_Skill& operator =(const SouXia_Skill& other )
{
if(this == &other)
{
return *this;
}
for(int i=0; i<=other.StudyCount; ++i)
{
StudySkillId[i] = other.StudySkillId[i];
}
StudyCount = other.StudyCount;
return *this;
}
};
struct SouXia_Product
{
SkillID_t StudyProductId[MAX_PRODUCT_COUNT]; // 学习过的神器配方 索引
BYTE StudyCount;
//加个赋值重载,用来做交换用
SouXia_Product& operator =(const SouXia_Product& other )
{
if(this == &other)
{
return *this;
}
for(int i=0; i<=other.StudyCount; ++i)
{
StudyProductId[i] = other.StudyProductId[i];
}
StudyCount = other.StudyCount;
return *this;
}
};
struct ZhaoHuan
{
SkillID_t StudyZhaoHuan; // 学习过的神兽召唤技能索引
SHORT LeftUseTime; // 还可以使用的次数
//加个赋值重载,用来做交换用
ZhaoHuan& operator =(const ZhaoHuan& other )
{
if(this == &other)
{
return *this;
}
StudyZhaoHuan = other.StudyZhaoHuan;
LeftUseTime = other.LeftUseTime;
return *this;
}
};
struct SouXia_PetZhaoHuan
{
ZhaoHuan StudyPet[MAX_PET_ZHAOHUAN_COUNT]; // 学习过的神兽召唤技能索引
BYTE StudyCount; // 当前学习的数量
//加个赋值重载,用来做交换用
SouXia_PetZhaoHuan& operator =(const SouXia_PetZhaoHuan& other )
{
if(this == &other)
{
return *this;
}
for(int i=0; i<=other.StudyCount; ++i)
{
StudyPet[i] = other.StudyPet[i];
}
StudyCount = other.StudyCount;
return *this;
}
};
struct SouXia_ZuojiZhaoHuan
{
ZhaoHuan StudyZuoji[MAX_ZUOJI_ZHAOHUAN_COUNT]; // 学习过的坐骑召唤技能索引
BYTE StudyCount; // 当前学习的数量
//加个赋值重载,用来做交换用
SouXia_ZuojiZhaoHuan& operator = (const SouXia_ZuojiZhaoHuan& other )
{
if(this == &other)
{
return *this;
}
for(int i=0; i<=other.StudyCount; ++i)
{
StudyZuoji[i] = other.StudyZuoji[i];
}
StudyCount = other.StudyCount;
return *this;
}
};
/*
注意:现在拷贝构造和赋值构造由系统默认提供位拷贝,已经实现了部分用到的暂时用不到的先没写
*/
enum
{
SKILL_PER_PAGE = 3,
PRODUCT_PER_PAGE = 1,
PET_ZHAOHUAN_PER_PAGE = 8,
ZUOJI_ZHAOHUAN_PER_PAGE = PET_ZHAOHUAN_PER_PAGE,
};
struct SOUXIA_DATA
{
SHORT m_CurPos;
UINT m_SouXiaID; // 捜侠录索引
SouXia_Skill m_Skill; // 包含的搜侠技能
SouXia_Product m_Product; // ... 神器配方
SouXia_PetZhaoHuan m_Pet; // ... 神兽召唤
SouXia_ZuojiZhaoHuan m_ZuoJi; // ... 坐骑召唤
SOUXIA_DATA()
{
CleanUp();
};
void CleanUp()
{
memset(this, 0, sizeof(SOUXIA_DATA));
m_CurPos = -1;
}
SOUXIA_DATA& operator = (const SOUXIA_DATA& other)
{
if(this == &other)
{
return *this;
}
m_CurPos = other.m_CurPos;
m_SouXiaID = other.m_SouXiaID;
m_Skill = other.m_Skill;
m_Product = other.m_Product;
m_Pet = other.m_Pet;
m_ZuoJi = other.m_ZuoJi;
return *this;
};
SHORT GetCurPos() { return m_CurPos; }
VOID SetCurPos(BYTE pos) { m_CurPos = pos; }
BYTE GetCurTypeCount() { return GetCurSkillCount()>0 ? 1:0 +
GetCurProductCount() >0?1:0 +
GetCurPetCount()>0?1:0 +
GetCurZuoJiCount()>0?1:0 ; }
BOOL SkillIsFull()
{
if(MAX_SKILL_COUNT/SKILL_PER_PAGE == GetCurSkillPage())
{
return TRUE;
}
return FALSE;
}
BOOL ProductIsFull()
{
if(MAX_PRODUCT_COUNT/PRODUCT_PER_PAGE == GetCurProductPage())
{
return TRUE;
}
return FALSE;
}
BOOL PetIsFull()
{
if(MAX_PET_ZHAOHUAN_COUNT/ZUOJI_ZHAOHUAN_PER_PAGE == GetCurPetZhaoHuanPage())
{
return TRUE;
}
return FALSE;
}
BOOL ZuoJiIsFull()
{
if(MAX_ZUOJI_ZHAOHUAN_COUNT/PET_ZHAOHUAN_PER_PAGE == GetCurZuoJiZhaoHuanPage() )
{
return TRUE;
}
return FALSE;
}
BYTE GetCurSkillCount() {return m_Skill.StudyCount;}
BYTE GetCurProductCount(){return m_Product.StudyCount;}
BYTE GetCurPetCount() {return m_Pet.StudyCount;}
BYTE GetCurZuoJiCount() {return m_ZuoJi.StudyCount;}
VOID IncCurSkillCount() { m_Skill.StudyCount++; }
VOID IncCurProductCount(){ m_Product.StudyCount++; }
VOID IncCurPetCount() { m_Pet.StudyCount++; }
VOID IncCurZuoJiCount() { m_ZuoJi.StudyCount++; }
//VOID DecCurSkillCount() { m_Skill.StudyCount--; }
//VOID DecCurProductCount(){ m_Product.StudyCount--; }
VOID DecCurPetCount() { Assert(m_Pet.StudyCount>0); m_Pet.StudyCount--; }
VOID DecCurZuoJiCount() { Assert(m_ZuoJi.StudyCount>0); m_ZuoJi.StudyCount--; }
// 取得当前各项总的页数
BYTE GetCurSkillPage() { return (BYTE)(((GetCurSkillCount()+SKILL_PER_PAGE)-1)/SKILL_PER_PAGE); }
BYTE GetCurProductPage() { return GetCurProductCount(); }
BYTE GetCurPetZhaoHuanPage() { return (BYTE)(((GetCurPetCount()+PET_ZHAOHUAN_PER_PAGE)-1)/PET_ZHAOHUAN_PER_PAGE); }
BYTE GetCurZuoJiZhaoHuanPage() { return (BYTE)(((GetCurZuoJiCount()+ZUOJI_ZHAOHUAN_PER_PAGE)-1)/ZUOJI_ZHAOHUAN_PER_PAGE); }
VOID ReadSouXiaVarAttr(SocketInputStream& iStream);
VOID WriteSouXiaVarAttr(SocketOutputStream& oStream) const;
};
#pragma pack(pop)
//后面的文件会用到前面的定义
#include "GameStruct_Item.h"
#include "GameStruct_Skill.h"
#include "GameStruct_Scene.h"
#include "GameStruct_Relation.h"
#include "GameStruct_Guild.h"
#include "GameStruct_City.h"
#include "GameStruct_Script.h"
#include "GameStruct_MinorPasswd.h"
#include "GameStruct_Finger.h"
#include "GameStruct_Country.h"
#endif
| [
"viticm@126.com"
] | viticm@126.com |
1fbc595629bc7a242e2a482d35309306f100b542 | 8cb2d3088cee07199c9778adf8d4856a3301a555 | /Game.h | ff2e3569b0465317e38dbb5ccd3375a865dbcf1b | [] | no_license | cj-dimaggio/OldRogueLike | 7b72dff89afb7d1afb5242c68cd1b6d9cb119b66 | 251b994c077ee272d50fea728fca20bbe6bc65b6 | refs/heads/master | 2021-05-28T00:49:48.495217 | 2014-10-26T14:47:49 | 2014-10-26T14:47:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,133 | h | #ifndef GAME_H_INCLUDED
#define GAME_H_INCLUDED
#include "precompiledheaders.h"
#include "GameObject.h"
#include "Tile.h"
#include "Message.h"
class Game
{
public:
Game();
static void Start();
static void GameLoop();
static void HandleKeys();
static void RenderAll();
static void HandleAI();
static void CreateDungeon();
static void DrawDungeon();
static void DrawBars();
static void DrawMessages();
static void RenderInventoryScreen();
static const int SCREEN_WIDTH = 100;
static const int SCREEN_HEIGHT = 75;
static const int MAP_WIDTH = 100;
static const int MAP_HEIGHT = 60;
static const int PANEL_HEIGHT = 15;
static const int BAR_WIDTH = 20;
static TCODConsole* gameConsole;
static TCODConsole* panel;
static TCODConsole* inventoryScreen;
enum States {PlayersTurn, EnemysTurn, UpdateScreen, InventoryScreen};
static States gameState;
private:
static bool _exit;
};
#endif // GAME_H_INCLUDED
| [
"ssawaa@yahoo.com"
] | ssawaa@yahoo.com |
ab3b28416154a95aa58de47aec3f3d434731247f | 558e099d14311205fa4af5f1fd5549b39745fb8d | /graph.cpp | 818ae8cde780b3c5cf201f4eced15a6d5b2d0ee5 | [] | no_license | aswinavofficial/GraphTheory | 5ad334a8a4accf0c0b69629a3e8b2b55ce9aa529 | 3afd09dfb1d9f8e84fedb81400317f876e2b39ce | refs/heads/master | 2021-01-20T02:32:56.946967 | 2017-11-03T07:11:31 | 2017-11-03T07:11:31 | 101,324,138 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,813 | cpp | #include "graph.hpp"
#include<stdlib.h>
#include<math.h>
#include<iostream>
using namespace mits;
mits::BitMapMatrix::BitMapMatrix(int nv){
nvertex=nv;
vbitmap=(char*)malloc((nvertex*nvertex)/8);
}
bool mits::BitMapMatrix::getBit(int i, int j){
int k=nvertex*i+j;
int b=k/8;
int off=k%8;
int mask=pow(2,7-off);
if((vbitmap[b]&mask)==mask)
return 1;
else
return 0;
}
void mits::BitMapMatrix::setBit(int i, int j){
int k=nvertex*i+j;
int b=k/8;
int off=k%8;
int mask=pow(2,7-off);
vbitmap[b]=vbitmap[b]|mask;
}
void mits::BitMapMatrix::resetBit(int i, int j){
int k=nvertex*i+j;
int b=k/8;
int off=k%8;
int mask=pow(2,7-off);
vbitmap[b]&=(~mask);
}
void mits::BitMapMatrix::deleteEntry(int v){
}
mits::Graph::Graph(const int nv, const int ne, std::vector<std::string> &vn, std::vector<std::string> &en, const int* adjcMat, RepType t)
{
if(nv > MAX_VERTICES)
std::cout<<"Exceeded Maximum Number of Verices"<<std::endl;
nvertex=nv;
nedge=ne;
vnames=vn;
enames=en;
repType=t;
bmm=BitMapMatrix(nvertex);
for(int i=0;i<nvertex;i++){
for(int j=0;j<nvertex;j++){
if(*(adjcMat+i*nvertex+j) == 1)
bmm.setBit(i,j);
else
bmm.resetBit(i,j);
}
}
}
void mits::Graph::printAdjcMat()
{
for(int i=0;i<nvertex;i++){
for(int j=0;j<nvertex;j++){
if(bmm.getBit(i,j))
std::cout<<1<<' ';
else
std::cout<<0<<' ';
}
std::cout<<std::endl;
}
}
int mits::Graph::getVertexCount()
{
return nvertex;
}
int mits::Graph::getEdgeCount()
{
return nedge;
}
bool mits::Graph::isAdjacent(int v1, int v2)
{
return bmm.getBit(v1-1, v2-1);
}
int mits::Graph::getDegree(int v)
{
int deg=0;
int i=v-1;
for(int j=0;j<nvertex;j++){
if(i!=j && bmm.getBit(i,j))
deg++;
}
return deg;
}
| [
"noreply@github.com"
] | aswinavofficial.noreply@github.com |
0aa65fb44a251568f07449ce6d78dfd0f1548de5 | 36d16576057cafec3dd4a35fd5a6fc05e4baa08e | /qglv_gallery/src/background_image.cpp | 249650cdbdb51df68d1c2841400b5c7d832a55ae | [] | no_license | yichoe/qglv_toolkit | 44774941ba51510632ed487510e7a95b752bfdc8 | 1f12b2866a3c6cd0b7864ed7591a09e709011e53 | refs/heads/devel | 2020-06-19T08:26:34.839694 | 2017-06-13T07:33:36 | 2017-06-13T07:33:36 | 94,182,308 | 0 | 0 | null | 2017-06-13T07:16:18 | 2017-06-13T07:16:18 | null | UTF-8 | C++ | false | false | 5,397 | cpp | /**
* @file /dslam_viewer/src/qgl_gallery/background_image.cpp
*
* @brief Short description of this file.
**/
/*****************************************************************************
** Includes
*****************************************************************************/
#include <qapplication.h>
#include <QGLViewer/qglviewer.h>
#include <qimage.h>
#include <qfiledialog.h>
#include <QKeyEvent>
/*****************************************************************************
** Namespaces
*****************************************************************************/
using namespace qglviewer;
using namespace std;
/*****************************************************************************
** Interface
*****************************************************************************/
class Viewer : public QGLViewer
{
protected :
virtual void init();
virtual void draw();
virtual void drawBackground();
virtual void keyPressEvent(QKeyEvent *e);
virtual QString helpString() const;
void loadImage();
private :
float ratio, u_max, v_max;
bool background_;
};
/*****************************************************************************
** Implementation
*****************************************************************************/
void Viewer::init()
{
restoreStateFromFile();
// Enable GL textures
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR );
glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR );
// Nice texture coordinate interpolation
glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST );
u_max = 1.0;
v_max = 1.0;
ratio = 1.0;
background_ = true;
setKeyDescription(Qt::Key_L, "Loads a new background image");
setKeyDescription(Qt::Key_B, "Toggles background display");
loadImage();
help();
qWarning("fin init");
}
void Viewer::draw()
{
drawBackground();
const float nbSteps = 200.0;
glBegin(GL_QUAD_STRIP);
for (float i=0; i<nbSteps; ++i)
{
float ratio = i/nbSteps;
float angle = 21.0*ratio;
float c = cos(angle);
float s = sin(angle);
float r1 = 1.0 - 0.8*ratio;
float r2 = 0.8 - 0.8*ratio;
float alt = ratio - 0.5;
const float nor = .5;
const float up = sqrt(1.0-nor*nor);
glColor3f(1.0-ratio, 0.2f , ratio);
glNormal3f(nor*c, up, nor*s);
glVertex3f(r1*c, alt, r1*s);
glVertex3f(r2*c, alt+0.05, r2*s);
}
glEnd();
}
void Viewer::drawBackground()
{
if (!background_)
return;
glDisable(GL_LIGHTING);
glEnable(GL_TEXTURE_2D);
glColor3f(1,1,1);
startScreenCoordinatesSystem(true);
// Draws the background quad
glNormal3f(0.0, 0.0, 1.0);
glBegin(GL_QUADS);
glTexCoord2f(0.0, 1.0-v_max); glVertex2i(0,0);
glTexCoord2f(0.0, 1.0); glVertex2i(0,height());
glTexCoord2f(u_max, 1.0); glVertex2i(width(),height());
glTexCoord2f(u_max, 1.0-v_max); glVertex2i(width(),0);
glEnd();
stopScreenCoordinatesSystem();
// Depth clear is not absolutely needed. An other option would have been to draw the
// QUAD with a 0.999 z value (z ranges in [0, 1[ with startScreenCoordinatesSystem()).
glClear(GL_DEPTH_BUFFER_BIT);
glDisable(GL_TEXTURE_2D);
glEnable(GL_LIGHTING);
}
void Viewer::loadImage()
{
QString name = QFileDialog::getOpenFileName(this, "Select an image", ".", "Images (*.png *.xpm *.jpg)");
// In case of Cancel
if (name.isEmpty())
return;
QImage img(name);
if (img.isNull())
{
qWarning("Unable to load file, unsupported file format");
return;
}
qWarning("Loading %s, %dx%d pixels", name.toLatin1().constData(), img.width(), img.height());
// 1E-3 needed. Just try with width=128 and see !
int newWidth = 1<<(int)(1+log(img.width() -1+1E-3) / log(2.0));
int newHeight = 1<<(int)(1+log(img.height()-1+1E-3) / log(2.0));
u_max = img.width() / (float)newWidth;
v_max = img.height() / (float)newHeight;
if ((img.width()!=newWidth) || (img.height()!=newHeight))
{
qWarning("Image size set to %dx%d pixels", newWidth, newHeight);
img = img.copy(0, 0, newWidth, newHeight);
}
ratio = newWidth / float(newHeight);
QImage glImg = QGLWidget::convertToGLFormat(img); // flipped 32bit RGBA
// Bind the img texture...
glTexImage2D(GL_TEXTURE_2D, 0, 4, glImg.width(), glImg.height(), 0,
GL_RGBA, GL_UNSIGNED_BYTE, glImg.bits());
}
void Viewer::keyPressEvent(QKeyEvent *e)
{
switch (e->key())
{
case Qt::Key_L :
loadImage();
break;
case Qt::Key_B :
background_ = !background_;
updateGL();
break;
default: QGLViewer::keyPressEvent(e);
}
}
QString Viewer::helpString() const
{
QString text("<h2>B a c k g r o u n d I m a g e</h2>");
text += "This example is derivated from textureViewer.<br><br>";
text += "It displays a background image in the viewer using a texture.<br><br>";
text += "Press <b>L</b> to load a new image, and <b>B</b> to toggle the background display.";
return text;
}
/*****************************************************************************
** Main
*****************************************************************************/
int main(int argc, char** argv)
{
QApplication application(argc,argv);
Viewer viewer;
viewer.setWindowTitle("backgroundImage");
viewer.show();
return application.exec();
}
| [
"d.stonier@gmail.com"
] | d.stonier@gmail.com |
e64ceabac9c703dd2b111bf4945500619ee6a24b | 5413baae6a6d9ec1c64d6ba45de4defbad796a45 | /NES Emulator/Source/Audio/DMC.hpp | 6b3322f27cdc05e57815666cbb0e92ac0da18770 | [] | no_license | Sjhunt93/Nes-Emulator | e17f93a98d71472e7b196270a406b0cc0682dd83 | 385e4f595c6a482c77a3afef5a555b15ea76ee5d | refs/heads/master | 2020-04-21T14:10:40.298245 | 2019-03-12T16:28:10 | 2019-03-12T16:28:10 | 169,625,647 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,811 | hpp | //
// DMC.hpp
// NES Emulator - App
//
// Created by Samuel Hunt on 21/02/2019.
//
#ifndef DMC_hpp
#define DMC_hpp
#include "Audio.h"
class CPU;
class DMC {
public:
CPU * cpu;
bool enabled;
Byte value;
UInt16 sampleAddress;
UInt16 sampleLength;
UInt16 currentAddress;
UInt16 currentLength;
Byte shiftRegister;
Byte bitCount;
Byte tickPeriod;
Byte tickValue;
bool loop;
bool irq;
void writeControl(Byte _value) {
irq = (_value&0x80) == 0x80;
loop = (_value&0x40) == 0x40;
tickPeriod = dmcTable[_value&0x0F];
}
void writeValue(Byte _value) {
value = _value & 0x7F;
}
void writeAddress(Byte _value) {
// Sample address = %11AAAAAA.AA000000
sampleAddress = 0xC000 | (UInt16(_value) << 6);
}
void writeLength(Byte value ) {
// Sample length = %0000LLLL.LLLL0001
sampleLength = (UInt16(value) << 4) | 1;
}
void restart() {
currentAddress = sampleAddress;
currentLength = sampleLength;
}
void stepTimer() {
if (!enabled) {
return;
}
stepReader();
if (tickValue == 0) {
tickValue = tickPeriod;
stepShifter();
} else {
tickValue--;
}
}
void stepReader();
void stepShifter() {
if (bitCount == 0) {
return;
}
if ((shiftRegister&1) == 1) {
if (value <= 125) {
value += 2;
}
}
else {
if (value >= 2) {
value -= 2;
}
}
shiftRegister >>= 1;
bitCount--;
}
Byte output() {
return value;
}
};
#endif /* DMC_hpp */
| [
"samuel.hunt@uwe.ac.uk"
] | samuel.hunt@uwe.ac.uk |
ea844639246d8a224c368a70229c231d8a0f9299 | 129e218759644de61a3b958fa266f4f7937a16e4 | /main.cpp | 3b77670f65fd1fd0365e8a2ba6ad87d94d251221 | [
"MIT"
] | permissive | WatStuff/Chess | 8ef51e31079081d4145b3e69c02d264d2fd1cc8d | 24e521145006e077ba65ee5c16a3d08ef54354d8 | refs/heads/master | 2020-04-07T00:55:49.542931 | 2018-11-18T15:15:16 | 2018-11-18T15:15:16 | 157,924,355 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,190 | cpp | #include<iostream>
using namespace std;
char board[][8] =
{ {'t','h','b','k','q','b','h','t'},
{'p','p','p','p','p','p','p','p'},
{' ',' ',' ',' ',' ',' ',' ',' '},
{' ',' ',' ',' ',' ',' ',' ',' '},
{' ',' ',' ',' ',' ',' ',' ',' '},
{' ',' ',' ',' ',' ',' ',' ',' '},
{'P','P','P','P','P','P','P','P'},
{'T','H','B','K','Q','B','H','T'}};
#include<chess_functions.h>
int main()
{
int player = 1;
int start[2];
char st_aux;
int end[2];
player = 1;
bool rslt;
while(check_mate(player)==false)
{
current_board(player);
cin>>st_aux;
cin>>start[0];
start[1] = ch(st_aux);
if(start[1]>=8){continue;}
start[0] = 7 - (start[0]-1);
cout<<board[start[0]][start[1]];
cout<<endl<<"write the end position: ";
cin>>st_aux;
end[1] = ch(st_aux);
cin>>end[0];
end[0] = 7 - (end[0]-1);
cout<<board[end[0]][end[1]];
if(check_if_av(start,end)==true)
{
rslt = manager(start,end,player);
if(rslt==false){continue;}
}
else{continue;}
if(player==1){player = 2;continue;}
if(player==2){player = 1;continue;}
}
if(player==1){cout<<endl<<"winner: player2"<<endl;}
if(player==2){cout<<endl<<"winner: player1"<<endl;}
return 0;
}
| [
"noreply@github.com"
] | WatStuff.noreply@github.com |
33497a22342d4eca468edccab99877102a1f334f | 408c27cbe3407cc770ab4149e52498ae7da4ed0b | /hangman.h | 1ad49be41b25d9dccdbad4a89bd4d42ef9b046d7 | [] | no_license | JulianFortik/POP2-HANGMAN | d03ac42362e416f62b4744ae5a286dda4ddf2294 | 47819cc41daaf2932300592505cb41bead08d31d | refs/heads/main | 2023-04-03T15:42:38.335990 | 2021-04-09T15:36:33 | 2021-04-09T15:36:33 | 356,315,709 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,841 | h | /*************************************************************
* Instructor's Name: Mrs. Vernelle Sylvester *
* Group Members: Lianni Mathews, Jason Fortik *
* Project: Hangman *
* Description: Hangman utilizes object oriented programming *
* to create an object that stores the statistics that are being *
* generated and also uses classes to separate the functions and *
* their declarations as libraries outside the main file *
* Due Date: March 25,2021 *
*************************************************************/
#ifndef HANGMAN_H
#define HANGMAN_H
#include <string>
#include <vector>
#include "player.h"
using std::vector;
using std::string;
class Hangman
{
public:
const static int ALPHABET_SIZE = 26; //const set rows for Alphabet
const static int ASCII_ROWS = 7;
const static int ASCII_COLS = 8;
Hangman(string filename, string username);
int selectGameLevel();
int generateRandomNumber();
string selectRandomWord(int random_number);
void loadWordList(std::string filename);
void startGame();
void printMessage(string message, bool printTop = true, bool printBottom = true);
void drawHangman(int guessCount = 0);
void resetAvailableLetters();
void printAsciiMessage(string message);
void printAvailableLetters(string taken);
bool checkWin(string wordToGuess, string guessesSoFar);
bool processResults(string wordToGuess, int guessAttempts, bool hasWon);
void setDifficultyLevel(unsigned diffLevel);
unsigned getDifficultyLevel();
void setMaxAllowedAttempts(unsigned allowedAttempts);
unsigned getMaxAllowedAttempts();
unsigned attemptsMadeSoFar(std::string wordToGuess, std::string guessesSoFar);
private:
Player player;
vector<string> wordVector;
unsigned difficultyLevel;
unsigned maxAllowedAttempts;
char alphabetArray[ALPHABET_SIZE + 1];
constexpr static char G[ASCII_ROWS][ASCII_COLS]={
" #### ", //Row=0
" # ", //Row=1
" # ", //Row=2
" # ### ", //Row=3
" # # ", //Row=4
" # # ", //Row=5
" ### " //Row=6
};
constexpr static char A[ASCII_ROWS][ASCII_COLS] = {
" ### ", //Row=0
" # # ", //Row=1
" # # ", //Row=2
" ##### ", //Row=3
" # # ", //Row=4
" # # ", //Row=5
" # # " //Row=6
};
constexpr static char M[ASCII_ROWS][ASCII_COLS] = {
" # # ", //Row=0
" ## ## ",//Row=1
" # # # ",//Row=2
" # # # ",//Row=3
" # # ",//Row=4
" # # ",//Row=5
" # # " //Row=6
};
constexpr static char E[ASCII_ROWS][ASCII_COLS] = {
" ##### ", //Row=0
" # ", //Row=1
" # ", //Row=2
" ##### ", //Row=3
" # ", //Row=4
" # ", //Row=5
" ##### " //Row=6
};
constexpr static char O[ASCII_ROWS][ASCII_COLS] = {
" ### ", //Row=0
" # # ", //Row=1
" # # ", //Row=2
" # # ", //Row=3
" # # ", //Row=4
" # # ", //Row=5
" ### " //Row=6
};
constexpr static char V[ASCII_ROWS][ASCII_COLS]={ " # # ", //Row=0
" # # ", //Row=1
" # # ", //Row=2
" # # ", //Row=3
" # # ", //Row=4
" # # ", //Row=5
" # "}; //Row=6
constexpr static char R[ASCII_ROWS][ASCII_COLS] = {
" ### ", //Row 0
" # # ", //Row=1
" # # ", //Row=2
" #### ", //Row=3
" # # ", //Row=4
" # # ", //Row=5
" # # " //Row=6
};
constexpr static char Y[ASCII_ROWS][ASCII_COLS] = {
" # # ", //Row = 0
" # # ", //Row=1
" # # ", //Row=2
" ### ", //Row=3
" # ", //Row=4
" # ", //Row=5
" # " //Row=6
};
constexpr static char U[ASCII_ROWS][ASCII_COLS] = {
" # # ", //Row = 0
" # # ",//Row=1
" # # ",//Row=2
" # # ",//Row=3
" # # ",//Row=4
" # # ",//Row=5
" ### " //Row=6
};
constexpr static char W[ASCII_ROWS][ASCII_COLS] = {
" # # ", //Row =0
" # # ", //Row=1
" # # ", //Row=2
" # # # ", //Row=3
" # # # ", //Row=4
" ## ## ", //Row=5
" # # " //Row=6
};
constexpr static char N[ASCII_ROWS][ASCII_COLS] = {
" # # ", //Row=0
" ## # ", //Row=1
" # # # ", //Row=2
" # # # ", //Row=3
" # ## ", //Row=4
" # ## ", //Row=5
" # # " //Row=6
};
constexpr static char exclamation[ASCII_ROWS][ASCII_COLS] = {
" ## ", //Row=0
" ## ", //Row=1
" ## ", //Row=2
" ## ", //Row=3
" ## ", //Row=4
" ", //Row=5
" ## " //Row=6
};
constexpr static char space[ASCII_ROWS][ASCII_COLS] = {
" ", //Row=0
" ", //Row=1
" ", //Row=2
" ", //Row=3
" ", //Row=4
" ", //Row=5
" " //Row=6
};
};
#endif // HANGMAN_H
| [
"fortikdev@gmail.com"
] | fortikdev@gmail.com |
c305ad949e2f362d6d5db7aaab186b20967ce5d8 | bd60b432bd871101c1e2c1dc28fcf695c4940e50 | /Source/BattleTanks/Public/TankTurret.h | 13698e27bfdd0c87cb49d072aaa978593cac61f1 | [] | no_license | setg2002/04_BattleTanks | 1b2e7da456671eecc2c7771e229a34a38f0fda5a | cd880a871b0219b4a6fc577d747784bad909328d | refs/heads/master | 2021-07-14T06:55:03.630232 | 2019-03-05T20:57:06 | 2019-03-05T20:57:06 | 149,185,824 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 549 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Components/StaticMeshComponent.h"
#include "TankTurret.generated.h"
/**
*
*/
UCLASS( meta = (BlueprintSpawnableComponent) )
class BATTLETANKS_API UTankTurret : public UStaticMeshComponent
{
GENERATED_BODY()
public:
// -1 is max downward speed, and +1 is max up movement
void Rotate(float RelativeSpeed);
private:
UPROPERTY(EditDefaultsOnly, Category = "Setup")
float MaxDegreesPerSecond = 20; // Default
};
| [
"soren.gilbertson13@gmail.com"
] | soren.gilbertson13@gmail.com |
a9c05e1433f2e6aec0fdef34856b7d50cd32292d | cc1701cadaa3b0e138e30740f98d48264e2010bd | /chrome/browser/policy/messaging_layer/encryption/test_encryption_module.cc | f35841d79c82e645230169cf7e0c60289ef7c333 | [
"BSD-3-Clause"
] | permissive | dbuskariol-org/chromium | 35d3d7a441009c6f8961227f1f7f7d4823a4207e | e91a999f13a0bda0aff594961762668196c4d22a | refs/heads/master | 2023-05-03T10:50:11.717004 | 2020-06-26T03:33:12 | 2020-06-26T03:33:12 | 275,070,037 | 1 | 3 | BSD-3-Clause | 2020-06-26T04:04:30 | 2020-06-26T04:04:29 | null | UTF-8 | C++ | false | false | 715 | cc | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <string>
#include "chrome/browser/policy/messaging_layer/encryption/test_encryption_module.h"
#include "chrome/browser/policy/messaging_layer/util/statusor.h"
namespace reporting {
namespace test {
StatusOr<std::string> TestEncryptionModule::EncryptRecord(
base::StringPiece record) const {
return std::string(record);
}
StatusOr<std::string> AlwaysFailsEncryptionModule::EncryptRecord(
base::StringPiece record) const {
return Status(error::UNKNOWN, "Failing for tests");
}
} // namespace test
} // namespace reporting
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
0936992199c97ed6d8ab51f8b53caacb340cc923 | ac719e4e5d8bf134a6ad3ce1175e68a10ad52da2 | /Classes/Native/System_Core_System_Func_2_gen2397331331.h | 69f22e2785a0a41db810d7f06ba7df25466b3d30 | [
"MIT"
] | permissive | JasonMcCoy/BOOM-Bound | b5fa6305ec23fd6742d804da0e206a923ff22118 | 574223c5643f8d89fdad3b8fc3c5d49a6a669e6e | refs/heads/master | 2021-01-11T06:23:28.917883 | 2020-05-20T17:28:58 | 2020-05-20T17:28:58 | 72,157,115 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 811 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// UnityEngine.Purchasing.ProductDefinition
struct ProductDefinition_t2168837728;
// System.IAsyncResult
struct IAsyncResult_t2754620036;
// System.AsyncCallback
struct AsyncCallback_t1369114871;
// System.Object
struct Il2CppObject;
#include "mscorlib_System_MulticastDelegate3389745971.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Func`2<UnityEngine.Purchasing.ProductDefinition,System.Boolean>
struct Func_2_t2397331331 : public MulticastDelegate_t3389745971
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"jasonmccoy@Jasons-MacBook-Pro.local"
] | jasonmccoy@Jasons-MacBook-Pro.local |
adceae0e77b4cc5271094d3eb40aa47f8663c227 | 6197740e6297da2f3d0c8ffd2a1d7ef5d8b3d2cb | /cmake-2.8.12.2/Source/cmGetTargetPropertyCommand.cxx | bacd051a9750ff98f7e0f2d08e681dd8888c91e2 | [
"BSD-3-Clause"
] | permissive | ssh352/cppcode | 1159d4137b68ada253678718b3d416639d3849ba | 5b7c28963286295dfc9af087bed51ac35cd79ce6 | refs/heads/master | 2020-11-24T18:07:17.587795 | 2016-07-15T13:13:05 | 2016-07-15T13:13:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,632 | cxx | /*============================================================================
CMake - Cross Platform Makefile Generator
Copyright 2000-2009 Kitware, Inc., Insight Software Consortium
Distributed under the OSI-approved BSD License (the "License");
see accompanying file Copyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the License for more information.
============================================================================*/
#include "cmGetTargetPropertyCommand.h"
// cmSetTargetPropertyCommand
bool cmGetTargetPropertyCommand
::InitialPass(std::vector<std::string> const& args, cmExecutionStatus &)
{
if(args.size() != 3 )
{
this->SetError("called with incorrect number of arguments");
return false;
}
std::string var = args[0].c_str();
const char* targetName = args[1].c_str();
const char *prop = 0;
if(args[2] == "ALIASED_TARGET")
{
if(this->Makefile->IsAlias(targetName))
{
if(cmTarget* target =
this->Makefile->FindTargetToUse(targetName))
{
prop = target->GetName();
}
}
}
else if(cmTarget* tgt = this->Makefile->FindTargetToUse(targetName))
{
cmTarget& target = *tgt;
prop = target.GetProperty(args[2].c_str());
}
if (prop)
{
this->Makefile->AddDefinition(var.c_str(), prop);
return true;
}
this->Makefile->AddDefinition(var.c_str(), (var+"-NOTFOUND").c_str());
return true;
}
| [
"qq410029478@ff87cf93-6e24-4a51-a1f1-68835326ac4f"
] | qq410029478@ff87cf93-6e24-4a51-a1f1-68835326ac4f |
eccda0df62d726d5c5ba34d7e468fa68f721bf81 | 91278e991fd16748695b8e1fcab298c0840abb31 | /min4.cpp | dc2e0dcd08c1332ee1b8ab4b0335e6f07f1931d6 | [] | no_license | ucsb-cs16-s19-ykk/lab01_John | 762a3223fcbc8570a217678185b5b5c3a33937c5 | 2df6e4320a73d034ed7004f43db5af6cc1f1cc16 | refs/heads/master | 2020-05-07T14:46:12.729676 | 2019-04-12T03:00:33 | 2019-04-12T03:00:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 651 | cpp | #include <iostream>
#include <cstdlib>
using namespace std;
int smallest_of_two(int n1, int n2);
int main(int argc, char *argv[]) {
if (argc != 5) {
cerr << "Usage: " << argv[0] <<" num1 num2 num3 num4"<<endl;
cerr << " Prints smallest of the four numbers"<<endl;
exit(1);
}
int small_ab, small_cd;
int a = atoi(argv[1]);
int b = atoi(argv[2]);
int c = atoi(argv[3]);
int d = atoi(argv[4]);
small_ab = smallest_of_two(a,b);
small_cd = smallest_of_two(c,d);
cout << smallest_of_two(small_ab, small_cd)<<endl;
return 0;
}
int smallest_of_two(int n1, int n2) {
if (n1>n2)
return n2;
else
return n1;
}
| [
"noreply@github.com"
] | ucsb-cs16-s19-ykk.noreply@github.com |
e9afa857d14c2f627df07c3567b1764e1680850f | c3a2034eaa707b98462b788c2882e105e78a239f | /src/txdb-leveldb.cpp | d88d3b197113cd8db9a296eff36194624bbdd05e | [
"MIT"
] | permissive | nixoncoindev/nixon | da11def9cc6b7fbc02573c2c0f5ccd2781d1ed31 | 992f49841463198559e9f0e5f6a13c22f9f6163e | refs/heads/master | 2021-01-09T20:11:16.738774 | 2017-02-07T19:11:35 | 2017-02-07T19:11:35 | 81,244,241 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 21,146 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include <map>
#include <boost/version.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <leveldb/env.h>
#include <leveldb/cache.h>
#include <leveldb/filter_policy.h>
#include <memenv/memenv.h>
#include "kernel.h"
#include "checkpoints.h"
#include "txdb.h"
#include "util.h"
#include "main.h"
using namespace std;
using namespace boost;
leveldb::DB *txdb; // global pointer for LevelDB object instance
static leveldb::Options GetOptions() {
leveldb::Options options;
int nCacheSizeMB = GetArgInt("-dbcache", 25);
options.block_cache = leveldb::NewLRUCache(nCacheSizeMB * 1048576);
options.filter_policy = leveldb::NewBloomFilterPolicy(10);
return options;
}
void init_blockindex(leveldb::Options& options, bool fRemoveOld = false) {
// First time init.
filesystem::path directory = GetDataDir() / "txleveldb";
if (fRemoveOld) {
filesystem::remove_all(directory); // remove directory
unsigned int nFile = 1;
while (true)
{
filesystem::path strBlockFile = GetDataDir() / strprintf("blk%04u.dat", nFile);
// Break if no such file
if( !filesystem::exists( strBlockFile ) )
break;
filesystem::remove(strBlockFile);
nFile++;
}
}
filesystem::create_directory(directory);
printf("Opening LevelDB in %s\n", directory.string().c_str());
leveldb::Status status = leveldb::DB::Open(options, directory.string(), &txdb);
if (!status.ok()) {
throw runtime_error(strprintf("init_blockindex(): error opening database environment %s", status.ToString().c_str()));
}
}
// CDB subclasses are created and destroyed VERY OFTEN. That's why
// we shouldn't treat this as a free operations.
CTxDB::CTxDB(const char* pszMode)
{
assert(pszMode);
activeBatch = NULL;
fReadOnly = (!strchr(pszMode, '+') && !strchr(pszMode, 'w'));
if (txdb) {
pdb = txdb;
return;
}
bool fCreate = strchr(pszMode, 'c');
options = GetOptions();
options.create_if_missing = fCreate;
options.filter_policy = leveldb::NewBloomFilterPolicy(10);
init_blockindex(options); // Init directory
pdb = txdb;
if (Exists(string("version")))
{
ReadVersion(nVersion);
printf("Transaction index version is %d\n", nVersion);
if (nVersion < DATABASE_VERSION)
{
printf("Required index version is %d, removing old database\n", DATABASE_VERSION);
// Leveldb instance destruction
delete txdb;
txdb = pdb = NULL;
delete activeBatch;
activeBatch = NULL;
init_blockindex(options, true); // Remove directory and create new database
pdb = txdb;
bool fTmp = fReadOnly;
fReadOnly = false;
WriteVersion(DATABASE_VERSION); // Save transaction index version
fReadOnly = fTmp;
}
}
else if (fCreate)
{
bool fTmp = fReadOnly;
fReadOnly = false;
WriteVersion(DATABASE_VERSION);
fReadOnly = fTmp;
}
printf("Opened LevelDB successfully\n");
}
void CTxDB::Close()
{
delete txdb;
txdb = pdb = NULL;
delete options.filter_policy;
options.filter_policy = NULL;
delete options.block_cache;
options.block_cache = NULL;
delete activeBatch;
activeBatch = NULL;
}
bool CTxDB::TxnBegin()
{
assert(!activeBatch);
activeBatch = new leveldb::WriteBatch();
return true;
}
bool CTxDB::TxnCommit()
{
assert(activeBatch);
leveldb::Status status = pdb->Write(leveldb::WriteOptions(), activeBatch);
delete activeBatch;
activeBatch = NULL;
if (!status.ok()) {
printf("LevelDB batch commit failure: %s\n", status.ToString().c_str());
return false;
}
return true;
}
class CBatchScanner : public leveldb::WriteBatch::Handler {
public:
std::string needle;
bool *deleted;
std::string *foundValue;
bool foundEntry;
CBatchScanner() : foundEntry(false) {}
virtual void Put(const leveldb::Slice& key, const leveldb::Slice& value) {
if (key.ToString() == needle) {
foundEntry = true;
*deleted = false;
*foundValue = value.ToString();
}
}
virtual void Delete(const leveldb::Slice& key) {
if (key.ToString() == needle) {
foundEntry = true;
*deleted = true;
}
}
};
// When performing a read, if we have an active batch we need to check it first
// before reading from the database, as the rest of the code assumes that once
// a database transaction begins reads are consistent with it. It would be good
// to change that assumption in future and avoid the performance hit, though in
// practice it does not appear to be large.
bool CTxDB::ScanBatch(const CDataStream &key, string *value, bool *deleted) const {
assert(activeBatch);
*deleted = false;
CBatchScanner scanner;
scanner.needle = key.str();
scanner.deleted = deleted;
scanner.foundValue = value;
leveldb::Status status = activeBatch->Iterate(&scanner);
if (!status.ok()) {
throw runtime_error(status.ToString());
}
return scanner.foundEntry;
}
bool CTxDB::ReadTxIndex(uint256 hash, CTxIndex& txindex)
{
assert(!fClient);
txindex.SetNull();
return Read(make_pair(string("tx"), hash), txindex);
}
bool CTxDB::UpdateTxIndex(uint256 hash, const CTxIndex& txindex)
{
assert(!fClient);
return Write(make_pair(string("tx"), hash), txindex);
}
bool CTxDB::AddTxIndex(const CTransaction& tx, const CDiskTxPos& pos, int nHeight)
{
assert(!fClient);
// Add to tx index
uint256 hash = tx.GetHash();
CTxIndex txindex(pos, tx.vout.size());
return Write(make_pair(string("tx"), hash), txindex);
}
bool CTxDB::EraseTxIndex(const CTransaction& tx)
{
assert(!fClient);
uint256 hash = tx.GetHash();
return Erase(make_pair(string("tx"), hash));
}
bool CTxDB::ContainsTx(uint256 hash)
{
assert(!fClient);
return Exists(make_pair(string("tx"), hash));
}
bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx, CTxIndex& txindex)
{
assert(!fClient);
tx.SetNull();
if (!ReadTxIndex(hash, txindex))
return false;
return (tx.ReadFromDisk(txindex.pos));
}
bool CTxDB::ReadDiskTx(uint256 hash, CTransaction& tx)
{
CTxIndex txindex;
return ReadDiskTx(hash, tx, txindex);
}
bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx, CTxIndex& txindex)
{
return ReadDiskTx(outpoint.hash, tx, txindex);
}
bool CTxDB::ReadDiskTx(COutPoint outpoint, CTransaction& tx)
{
CTxIndex txindex;
return ReadDiskTx(outpoint.hash, tx, txindex);
}
bool CTxDB::WriteBlockIndex(const CDiskBlockIndex& blockindex)
{
return Write(make_pair(string("blockindex"), blockindex.GetBlockHash()), blockindex);
}
bool CTxDB::ReadHashBestChain(uint256& hashBestChain)
{
return Read(string("hashBestChain"), hashBestChain);
}
bool CTxDB::WriteHashBestChain(uint256 hashBestChain)
{
return Write(string("hashBestChain"), hashBestChain);
}
bool CTxDB::ReadBestInvalidTrust(CBigNum& bnBestInvalidTrust)
{
return Read(string("bnBestInvalidTrust"), bnBestInvalidTrust);
}
bool CTxDB::WriteBestInvalidTrust(CBigNum bnBestInvalidTrust)
{
return Write(string("bnBestInvalidTrust"), bnBestInvalidTrust);
}
bool CTxDB::ReadSyncCheckpoint(uint256& hashCheckpoint)
{
return Read(string("hashSyncCheckpoint"), hashCheckpoint);
}
bool CTxDB::WriteSyncCheckpoint(uint256 hashCheckpoint)
{
return Write(string("hashSyncCheckpoint"), hashCheckpoint);
}
bool CTxDB::ReadCheckpointPubKey(string& strPubKey)
{
return Read(string("strCheckpointPubKey"), strPubKey);
}
bool CTxDB::WriteCheckpointPubKey(const string& strPubKey)
{
return Write(string("strCheckpointPubKey"), strPubKey);
}
bool CTxDB::ReadModifierUpgradeTime(unsigned int& nUpgradeTime)
{
return Read(string("nUpgradeTime"), nUpgradeTime);
}
bool CTxDB::WriteModifierUpgradeTime(const unsigned int& nUpgradeTime)
{
return Write(string("nUpgradeTime"), nUpgradeTime);
}
static CBlockIndex *InsertBlockIndex(uint256 hash)
{
if (hash == 0)
return NULL;
// Return existing
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
return (*mi).second;
// Create new
CBlockIndex* pindexNew = new CBlockIndex();
if (!pindexNew)
throw runtime_error("LoadBlockIndex() : new CBlockIndex failed");
mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first);
return pindexNew;
}
bool CTxDB::LoadBlockIndex()
{
if (mapBlockIndex.size() > 0) {
// Already loaded once in this session. It can happen during migration
// from BDB.
return true;
}
// The block index is an in-memory structure that maps hashes to on-disk
// locations where the contents of the block can be found. Here, we scan it
// out of the DB and into mapBlockIndex.
leveldb::Iterator *iterator = pdb->NewIterator(leveldb::ReadOptions());
// Seek to start key.
CDataStream ssStartKey(SER_DISK, CLIENT_VERSION);
ssStartKey << make_pair(string("blockindex"), uint256(0));
iterator->Seek(ssStartKey.str());
// Now read each entry.
while (iterator->Valid())
{
// Unpack keys and values.
CDataStream ssKey(SER_DISK, CLIENT_VERSION);
ssKey.write(iterator->key().data(), iterator->key().size());
CDataStream ssValue(SER_DISK, CLIENT_VERSION);
ssValue.write(iterator->value().data(), iterator->value().size());
string strType;
ssKey >> strType;
// Did we reach the end of the data to read?
if (fRequestShutdown || strType != "blockindex")
break;
CDiskBlockIndex diskindex;
ssValue >> diskindex;
uint256 blockHash = diskindex.GetBlockHash();
// Construct block index object
CBlockIndex* pindexNew = InsertBlockIndex(blockHash);
pindexNew->pprev = InsertBlockIndex(diskindex.hashPrev);
pindexNew->pnext = InsertBlockIndex(diskindex.hashNext);
pindexNew->nFile = diskindex.nFile;
pindexNew->nBlockPos = diskindex.nBlockPos;
pindexNew->nHeight = diskindex.nHeight;
pindexNew->nMint = diskindex.nMint;
pindexNew->nMoneySupply = diskindex.nMoneySupply;
pindexNew->nFlags = diskindex.nFlags;
pindexNew->nStakeModifier = diskindex.nStakeModifier;
pindexNew->prevoutStake = diskindex.prevoutStake;
pindexNew->nStakeTime = diskindex.nStakeTime;
pindexNew->hashProofOfStake = diskindex.hashProofOfStake;
pindexNew->nVersion = diskindex.nVersion;
pindexNew->hashMerkleRoot = diskindex.hashMerkleRoot;
pindexNew->nTime = diskindex.nTime;
pindexNew->nBits = diskindex.nBits;
pindexNew->nNonce = diskindex.nNonce;
// Watch for genesis block
if (pindexGenesisBlock == NULL && blockHash == (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet))
pindexGenesisBlock = pindexNew;
if (!pindexNew->CheckIndex()) {
delete iterator;
return error("LoadBlockIndex() : CheckIndex failed at %d", pindexNew->nHeight);
}
// NixonCoin: build setStakeSeen
if (pindexNew->IsProofOfStake())
setStakeSeen.insert(make_pair(pindexNew->prevoutStake, pindexNew->nStakeTime));
iterator->Next();
}
delete iterator;
if (fRequestShutdown)
return true;
// Calculate nChainTrust
vector<pair<int, CBlockIndex*> > vSortedByHeight;
vSortedByHeight.reserve(mapBlockIndex.size());
BOOST_FOREACH(const PAIRTYPE(uint256, CBlockIndex*)& item, mapBlockIndex)
{
CBlockIndex* pindex = item.second;
vSortedByHeight.push_back(make_pair(pindex->nHeight, pindex));
}
sort(vSortedByHeight.begin(), vSortedByHeight.end());
BOOST_FOREACH(const PAIRTYPE(int, CBlockIndex*)& item, vSortedByHeight)
{
CBlockIndex* pindex = item.second;
pindex->nChainTrust = (pindex->pprev ? pindex->pprev->nChainTrust : 0) + pindex->GetBlockTrust();
// NixonCoin: calculate stake modifier checksum
pindex->nStakeModifierChecksum = GetStakeModifierChecksum(pindex);
if (!CheckStakeModifierCheckpoints(pindex->nHeight, pindex->nStakeModifierChecksum))
return error("CTxDB::LoadBlockIndex() : Failed stake modifier checkpoint height=%d, modifier=0x%016" PRIx64, pindex->nHeight, pindex->nStakeModifier);
}
// Load hashBestChain pointer to end of best chain
if (!ReadHashBestChain(hashBestChain))
{
if (pindexGenesisBlock == NULL)
return true;
return error("CTxDB::LoadBlockIndex() : hashBestChain not loaded");
}
if (!mapBlockIndex.count(hashBestChain))
return error("CTxDB::LoadBlockIndex() : hashBestChain not found in the block index");
pindexBest = mapBlockIndex[hashBestChain];
nBestHeight = pindexBest->nHeight;
nBestChainTrust = pindexBest->nChainTrust;
printf("LoadBlockIndex(): hashBestChain=%s height=%d trust=%s date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, CBigNum(nBestChainTrust).ToString().c_str(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
// NixonCoin: load hashSyncCheckpoint
if (!ReadSyncCheckpoint(Checkpoints::hashSyncCheckpoint))
return error("CTxDB::LoadBlockIndex() : hashSyncCheckpoint not loaded");
printf("LoadBlockIndex(): synchronized checkpoint %s\n", Checkpoints::hashSyncCheckpoint.ToString().c_str());
// Load bnBestInvalidTrust, OK if it doesn't exist
CBigNum bnBestInvalidTrust;
ReadBestInvalidTrust(bnBestInvalidTrust);
nBestInvalidTrust = bnBestInvalidTrust.getuint256();
// Verify blocks in the best chain
int nCheckLevel = GetArgInt("-checklevel", 1);
int nCheckDepth = GetArgInt( "-checkblocks", 2500);
if (nCheckDepth == 0)
nCheckDepth = 1000000000; // suffices until the year 19000
if (nCheckDepth > nBestHeight)
nCheckDepth = nBestHeight;
printf("Verifying last %i blocks at level %i\n", nCheckDepth, nCheckLevel);
CBlockIndex* pindexFork = NULL;
map<pair<unsigned int, unsigned int>, CBlockIndex*> mapBlockPos;
for (CBlockIndex* pindex = pindexBest; pindex && pindex->pprev; pindex = pindex->pprev)
{
if (fRequestShutdown || pindex->nHeight < nBestHeight-nCheckDepth)
break;
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("LoadBlockIndex() : block.ReadFromDisk failed");
// check level 1: verify block validity
// check level 7: verify block signature too
if (nCheckLevel>0 && !block.CheckBlock(true, true, (nCheckLevel>6)))
{
printf("LoadBlockIndex() : *** found bad block at %d, hash=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str());
pindexFork = pindex->pprev;
}
// check level 2: verify transaction index validity
if (nCheckLevel>1)
{
pair<unsigned int, unsigned int> pos = make_pair(pindex->nFile, pindex->nBlockPos);
mapBlockPos[pos] = pindex;
BOOST_FOREACH(const CTransaction &tx, block.vtx)
{
uint256 hashTx = tx.GetHash();
CTxIndex txindex;
if (ReadTxIndex(hashTx, txindex))
{
// check level 3: checker transaction hashes
if (nCheckLevel>2 || pindex->nFile != txindex.pos.nFile || pindex->nBlockPos != txindex.pos.nBlockPos)
{
// either an error or a duplicate transaction
CTransaction txFound;
if (!txFound.ReadFromDisk(txindex.pos))
{
printf("LoadBlockIndex() : *** cannot read mislocated transaction %s\n", hashTx.ToString().c_str());
pindexFork = pindex->pprev;
}
else
if (txFound.GetHash() != hashTx) // not a duplicate tx
{
printf("LoadBlockIndex(): *** invalid tx position for %s\n", hashTx.ToString().c_str());
pindexFork = pindex->pprev;
}
}
// check level 4: check whether spent txouts were spent within the main chain
unsigned int nOutput = 0;
if (nCheckLevel>3)
{
BOOST_FOREACH(const CDiskTxPos &txpos, txindex.vSpent)
{
if (!txpos.IsNull())
{
pair<unsigned int, unsigned int> posFind = make_pair(txpos.nFile, txpos.nBlockPos);
if (!mapBlockPos.count(posFind))
{
printf("LoadBlockIndex(): *** found bad spend at %d, hashBlock=%s, hashTx=%s\n", pindex->nHeight, pindex->GetBlockHash().ToString().c_str(), hashTx.ToString().c_str());
pindexFork = pindex->pprev;
}
// check level 6: check whether spent txouts were spent by a valid transaction that consume them
if (nCheckLevel>5)
{
CTransaction txSpend;
if (!txSpend.ReadFromDisk(txpos))
{
printf("LoadBlockIndex(): *** cannot read spending transaction of %s:%i from disk\n", hashTx.ToString().c_str(), nOutput);
pindexFork = pindex->pprev;
}
else if (!txSpend.CheckTransaction())
{
printf("LoadBlockIndex(): *** spending transaction of %s:%i is invalid\n", hashTx.ToString().c_str(), nOutput);
pindexFork = pindex->pprev;
}
else
{
bool fFound = false;
BOOST_FOREACH(const CTxIn &txin, txSpend.vin)
if (txin.prevout.hash == hashTx && txin.prevout.n == nOutput)
fFound = true;
if (!fFound)
{
printf("LoadBlockIndex(): *** spending transaction of %s:%i does not spend it\n", hashTx.ToString().c_str(), nOutput);
pindexFork = pindex->pprev;
}
}
}
}
nOutput++;
}
}
}
// check level 5: check whether all prevouts are marked spent
if (nCheckLevel>4)
{
BOOST_FOREACH(const CTxIn &txin, tx.vin)
{
CTxIndex txindex;
if (ReadTxIndex(txin.prevout.hash, txindex))
if (txindex.vSpent.size()-1 < txin.prevout.n || txindex.vSpent[txin.prevout.n].IsNull())
{
printf("LoadBlockIndex(): *** found unspent prevout %s:%i in %s\n", txin.prevout.hash.ToString().c_str(), txin.prevout.n, hashTx.ToString().c_str());
pindexFork = pindex->pprev;
}
}
}
}
}
}
if (pindexFork && !fRequestShutdown)
{
// Reorg back to the fork
printf("LoadBlockIndex() : *** moving best chain pointer back to block %d\n", pindexFork->nHeight);
CBlock block;
if (!block.ReadFromDisk(pindexFork))
return error("LoadBlockIndex() : block.ReadFromDisk failed");
CTxDB txdb;
block.SetBestChain(txdb, pindexFork);
}
return true;
}
| [
"nixoncoin@protonmail"
] | nixoncoin@protonmail |
8c22d629f321ccdddff30c45e76141a155398334 | 6012374a36d037c2b609d99fdefdee087c6e2bfa | /World.h | adb6d904f8a1b8c000ce28edc4b30d054d6f6d24 | [] | no_license | super-nova/Allegro5Framework | c61cefb6e29fb7d9e91493257c5f6036ab3e4927 | 9054c58d88777d8ec861d4429d4fd5b437d4b22c | refs/heads/master | 2020-06-05T18:07:43.732412 | 2012-09-07T18:18:04 | 2012-09-07T18:18:04 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 677 | h | #pragma once
class Entity;
class BaseComponent;
#include "Entity.h"
#include "BaseComponent.h"
#include <vector>
#include <boost/multi_array.hpp>
using std::vector;
typedef unsigned __int16 uint_16;
typedef uint_16 entityId;
typedef uint_16 componentId;
class World
{
entityId lastid;
componentId lastCompTypeId;
vector<Entity*> ents;
boost::multi_array<BaseComponent*,2> *map;
public:
World(void);
~World(void);
BaseComponent* GetComponent( Entity *ent , componentId id);
void AddComponent( Entity* ent, BaseComponent* comp );
entityId createEntity()
{
return ++lastid;
}
static World& GetInstance()
{
static World w;
return w;
}
};
| [
"super_nova26@hotmail.com"
] | super_nova26@hotmail.com |
d8e274d32e4ef0708993c3fe2f26c12c90818d3c | 62a7d30053e7640ef770e041f65b249d101c9757 | /Discover Vladivostok 2019. Division A Day 4/F.cpp | 2a857af646340fe5de4618db6f31b002ed2e2cb1 | [] | no_license | wcysai/Calabash | 66e0137fd59d5f909e4a0cab940e3e464e0641d0 | 9527fa7ffa7e30e245c2d224bb2fb77a03600ac2 | refs/heads/master | 2022-05-15T13:11:31.904976 | 2022-04-11T01:22:50 | 2022-04-11T01:22:50 | 148,618,062 | 76 | 16 | null | 2019-11-07T05:27:40 | 2018-09-13T09:53:04 | C++ | UTF-8 | C++ | false | false | 1,546 | cpp | #include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for (int i = 0; i < int(n); i++)
#define Rep(i, n) for (int i = 1; i <=int(n); i++)
#define range(x) begin(x), end(x)
#ifdef __LOCAL_DEBUG__
#define _debug(fmt, ...) fprintf(stderr, "[%s] " fmt "\n", __func__, ##__VA_ARGS__)
#else
#define _debug(...) ((void) 0)
#endif
typedef long long LL;
typedef unsigned long long ULL;
int p[] = {3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71};
int n;
const LL mod = 1'000'000'009;
LL powmod(LL b, LL e) {
LL r = 1;
while (e) {
if (e & 1) r = r * b % mod;
b = b * b % mod;
e >>= 1;
}
return r;
}
vector<int> ps;
map<double, LL> ans;
vector<int> cur;
void compute() {
auto s = cur;
sort(range(s), greater<>());
LL ans = 1;
double apans = 0.0;
for (int i = 0; i < s.size(); i++) {
ans = ans * powmod(p[i], s[i] - 1) % mod;
apans += log(p[i]) * (s[i] - 1);
}
::ans[apans] = ans;
}
void dfs(int ptr, int s) {
if (ptr == ps.size()) {
compute();
return;
}
if (ptr and ps[ptr] != ps[ptr - 1]) s = 0;
for (; s < cur.size(); s++) {
cur[s] *= ps[ptr];
dfs(ptr + 1, s);
cur[s] /= ps[ptr];
}
cur.push_back(ps[ptr]);
dfs(ptr + 1, s);
cur.pop_back();
}
int main() {
int n; cin >> n;
for (int f = 2; n > 1; f++) {
while (n % f == 0) {
n /= f;
ps.push_back(f);
}
}
dfs(0, 0);
cout << ans.begin()->second << endl;
return 0;
}
| [
"wcysai@foxmail.com"
] | wcysai@foxmail.com |
05d38715d9c67b6074e71ca20963216bef6469bb | 0a9ad1ea58e6cb162777e0216ec716cb70efd029 | /Status-5 -MyAnatomy/Binary Search Tree Insertion.cpp | 1d3f2b35ba18608c7540c01a771b968b5a41ea7b | [] | no_license | dineshnadimpalli/HackerRank | caffc2e3d711040422e52e3ee1baa10419981d26 | 0b3bb9e2867dc8e90bdd62d8c62d56802a950e89 | refs/heads/master | 2021-09-18T00:00:58.957578 | 2018-07-07T12:55:06 | 2018-07-07T12:55:06 | 114,526,748 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 510 | cpp | //Binary Search Tree Insertion
typedef struct node
{
int data;
node * left;
node * right;
}node;
node * insert(node * root, int value) {
if(root==NULL){
node* temp =new node();
temp->data = value;
temp->left = NULL;
temp->right = NULL;
root = temp;
return root;
}
if(root->data>value)
root->left = insert(root->left,value);
else
root->right = insert(root->right,value);
return root;
}
| [
"noreply@github.com"
] | dineshnadimpalli.noreply@github.com |
0f4d6bbc485669d278e854551e5e8a2c410206e0 | 0a26f8bc7bfffbfb9fcdfca96574033a4b32465f | /src/hive.cpp | 9b62c0b128e48084967529c98e59bff28ab799ad | [] | no_license | michal8833/Hive | 330b10b399a3c7132ee011ca608b40c461a3cc84 | 78fab42862f3f4ca5e8d7bf9a868e170b489472b | refs/heads/main | 2023-03-15T02:34:50.000234 | 2021-03-22T13:39:26 | 2021-03-22T13:39:26 | 350,344,140 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,460 | cpp | #include <windows.h>
#include <cstdio>
#include <tchar.h>
#include <ctime>
#include <string>
#include "Flowerbed.h"
#include "defs.h"
#pragma warning(disable:4996)
using namespace std;
void parseArgs(int argc, char *argv[], int &flowerbedsNumber, int &hiveCapacity, int &period);
void mapping(HANDLE hMapFile, int flowerbedsNumber, SYSTEM_INFO si, Flowerbed** flowerbedsInfo, int** hiveInfo, int** bees);
void killSwarm(int *bees, PROCESS_INFORMATION &Pi);
void error(std::string functionName);
int main(int argc, char *argv[]) {
HANDLE hMapFile;
Flowerbed* flowerbedsInfo;
int* hiveInfo;
int* bees;
Flowerbed* flowerbeds;
STARTUPINFO Si;
PROCESS_INFORMATION Pi;
SYSTEM_INFO si;
int flowerbedsNumber;
int hiveCapacity;
int period;
parseArgs(argc, argv, flowerbedsNumber, hiveCapacity, period);
GetSystemInfo(&si);
srand((unsigned int)time(nullptr));
flowerbeds = new Flowerbed[flowerbedsNumber];
printf("Meadow at the beginning of the program:\n");
for (int i = 0; i < flowerbedsNumber; i++)
printf("Flowerbed %d: %d flowers, %ld nectar units.\n", i + 1, flowerbeds[i].getFlowersNumber(), *(flowerbeds[i].getTotalNectarUnits()));
printf("-----------------------------------------------------------------------------------------------------------\n");
hMapFile = CreateFileMapping(
INVALID_HANDLE_VALUE,
nullptr,
PAGE_READWRITE,
0,
SIZE_OF_BUF,
fileMapping);
if (hMapFile == nullptr)
error("CreateFileMapping");
mapping(hMapFile, flowerbedsNumber, si, &flowerbedsInfo, &hiveInfo, &bees);
CopyMemory(flowerbedsInfo, flowerbeds, flowerbedsNumber * sizeof(Flowerbed));
CreateMutex(nullptr, false, TEXT("entry_door")); // hive entry door synchronization(at a time, only one bee passes through the door)
CreateMutex(nullptr, false, TEXT("exit_door")); // hive exit door synchronization(at a time, only one bee passes through the door)
CreateSemaphore(nullptr, hiveCapacity, hiveCapacity, TEXT("bees_in_hive")); // a semaphore controlling the number of bees in the hive
CreateMutex(nullptr, false, TEXT("honey_in_hive")); // honey in hive access synchronization
CreateMutex(nullptr, false, TEXT("checking_availability_of_flower")); // flowers access synchronization
CreateMutex(nullptr, false, TEXT("number_of_bees_in_and_out_of_hive")); // hiveInfo[1] i hiveInfo[2] access synchronization
ZeroMemory(&Si, sizeof(Si));
Si.cb = sizeof(Si);
ZeroMemory(&Pi, sizeof(Pi));
char buffer[50];
sprintf(buffer, "queen.exe %s", argv[1]);
if (!CreateProcess(nullptr,
buffer,
nullptr,
nullptr,
FALSE,
0,
nullptr,
nullptr,
&Si,
&Pi)
)
{
error("CreateProcess");
}
Sleep(period);
killSwarm(bees, Pi );
printf("-----------------------------------------------------------------------------------------------------------\n");
printf("Meadow at the end of the program:\n");
for (int i = 0; i < flowerbedsNumber; i++)
printf("Flowerbed %d: %d flowers, %ld nectar units.\n", i + 1, flowerbedsInfo[i].getFlowersNumber(), *(flowerbedsInfo[i].getTotalNectarUnits()));
printf("\nNumber of bees in the hive: %d\nNumber of bees outside the hive: %d\n", hiveInfo[1], hiveInfo[2]);
printf("\nThe amount of honey collected in the hive: %d\n", hiveInfo[0]);
UnmapViewOfFile(flowerbedsInfo);
UnmapViewOfFile(hiveInfo);
UnmapViewOfFile(bees);
CloseHandle(hMapFile);
return 0;
}
void parseArgs(int argc, char *argv[], int &flowerbedsNumber, int &hiveCapacity, int &period) {
char *endptr;
auto errorFunction = [programName = argv[0]]() {
printf("Usage: %s <flowerbeds_number> <hive_capacity> <period>\n", programName);
exit(1);
};
if(argc != 4)
errorFunction();
flowerbedsNumber = strtol(argv[1], &endptr, 0);
if( !((*argv[1] != '\0') && (*endptr == '\0')) )
errorFunction();
hiveCapacity = strtol(argv[2], &endptr, 0);
if( !((*argv[2] != '\0') && (*endptr == '\0')) )
errorFunction();
period = strtol(argv[3], &endptr, 0);
if( !((*argv[3] != '\0') && (*endptr == '\0')) )
errorFunction();
}
void mapping(HANDLE hMapFile, int flowerbedsNumber, SYSTEM_INFO si, Flowerbed** flowerbedsInfo, int** hiveInfo, int** bees) {
*flowerbedsInfo = (Flowerbed*)MapViewOfFile(hMapFile, // flowerbedsInfo is a flowerbed array
FILE_MAP_ALL_ACCESS,
0,
0,
flowerbedsNumber * sizeof(Flowerbed));
*hiveInfo = (int*)MapViewOfFile(hMapFile, // hiveInfo is an array consisting of 3 int values: hiveInfo[0]-the amount of honey in the hive, hiveInfo[1]-the number of bees in the hive, hiveInfo[2]-number of bees outside the hive
FILE_MAP_ALL_ACCESS,
0,
si.dwAllocationGranularity,
3 * sizeof(int));
(*hiveInfo)[0] = 0;
(*hiveInfo)[1] = 0;
(*hiveInfo)[2] = 0;
*bees = (int*)MapViewOfFile(hMapFile, //bees is an array of bee.exe processes IDs
FILE_MAP_ALL_ACCESS,
0,
2 * si.dwAllocationGranularity,
BEES_MAX * sizeof(int));
if (*flowerbedsInfo == nullptr || *hiveInfo == nullptr || *bees == nullptr) {
CloseHandle(hMapFile);
error("MapViewOfFile");
}
}
void killSwarm( int *bees, PROCESS_INFORMATION &Pi ) {
TerminateProcess( Pi.hProcess, 0 ); // queen.exe
CloseHandle( Pi.hProcess );
CloseHandle( Pi.hThread );
for (int i = 0; i < BEES_MAX; i++) {
HANDLE process = OpenProcess( PROCESS_ALL_ACCESS, false, bees[i] );
TerminateProcess( process, 0 ); //bee.exe
CloseHandle( process );
}
}
void error(std::string functionName) {
printf("Hive: Function %s() error (code: %ld).", functionName.c_str(), GetLastError());
exit(1);
}
| [
"noreply@github.com"
] | michal8833.noreply@github.com |
f666fcd83747b74d8c3a3b9fb4fb37cec4a473a1 | ebcd5b41d04929ee81f856e8585f3c1f68e117f9 | /esp32-camera-series-master/esp32-camera-series.ino | 2fa34f3b5d404b4ad4338ce248aabcef11c597bc | [] | no_license | AlshainAvior/iot | 203f182d3059c615ec6ceebfa9e4cb90f104ccbe | bd859788d1504cc836c08751968110ccbe5cacb7 | refs/heads/master | 2022-10-16T05:21:42.252004 | 2020-06-17T13:19:44 | 2020-06-17T13:19:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,764 | ino | #include <WiFi.h>
#include <OneButton.h>
#include "freertos/event_groups.h"
#include <Wire.h>
#include <Adafruit_BME280.h>
#include "esp_camera.h"
#include "esp_wifi.h"
/***************************************
* Board select
**************************************/
//! [T_CAMERA_MIC] With SSD1306 with microphone
// #define TTGO_T_CAMERA_MIC_V16
//! [T_CAMERA_V05 or TTGO_T_CAMERA_V1_7_2] With SSD1306, with BME280 position
//! Different power management, the same pin
// #define TTGO_T_CAMERA_V05
//! [T_CAMERA_PLUS] With 240*240TFT display, SD card slot
// #define TTGO_T_CAMERA_PLUS
//! [T_JORNAL] The most simplified version, without PSRAM
// #define TTGO_T_JORNAL
/***************************************
* Modules
**************************************/
#define ENABLE_SSD1306
#define SOFTAP_MODE //The comment will be connected to the specified ssid
// #define ENABLE_BME280
#define ENABLE_SLEEP
// #define ENABLE_IP5306
#define ENABLE_AS312
#define ENABLE_BUTTON
/***************************************
* WiFi
**************************************/
#define WIFI_SSID "your wifi ssid"
#define WIFI_PASSWD "you wifi password"
/***************************************
* PinOUT
**************************************/
#if defined(TTGO_T_CAMERA_MIC_V16)
#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 4
#define SIOD_GPIO_NUM 18
#define SIOC_GPIO_NUM 23
#define Y9_GPIO_NUM 36
#define Y8_GPIO_NUM 15
#define Y7_GPIO_NUM 12
#define Y6_GPIO_NUM 39
#define Y5_GPIO_NUM 35
#define Y4_GPIO_NUM 14
#define Y3_GPIO_NUM 13
#define Y2_GPIO_NUM 34
#define VSYNC_GPIO_NUM 5
#define HREF_GPIO_NUM 27
#define PCLK_GPIO_NUM 25
#define AS312_PIN 19
#define BUTTON_1 0
#define I2C_SDA 21
#define I2C_SCL 22
#undef ENABLE_BME280
#undef ENABLE_IP5306
#define SSD130_MODLE_TYPE GEOMETRY_128_64
#elif defined(TTGO_T_CAMERA_V05) || defined(TTGO_T_CAMERA_V1_7_2)
#define PWDN_GPIO_NUM 26
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 32
#define SIOD_GPIO_NUM 13
#define SIOC_GPIO_NUM 12
#define Y9_GPIO_NUM 39
#define Y8_GPIO_NUM 36
#define Y7_GPIO_NUM 23
#define Y6_GPIO_NUM 18
#define Y5_GPIO_NUM 15
#define Y4_GPIO_NUM 4
#define Y3_GPIO_NUM 14
#define Y2_GPIO_NUM 5
#define VSYNC_GPIO_NUM 27
#define HREF_GPIO_NUM 25
#define PCLK_GPIO_NUM 19
#define AS312_PIN 33
#define BUTTON_1 34
#define I2C_SDA 21
#define I2C_SCL 22
#define SSD130_MODLE_TYPE GEOMETRY_128_64
#elif defined(TTGO_T_JORNAL)
#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM 15
#define XCLK_GPIO_NUM 27
#define SIOD_GPIO_NUM 25
#define SIOC_GPIO_NUM 23
#define Y9_GPIO_NUM 19
#define Y8_GPIO_NUM 36
#define Y7_GPIO_NUM 18
#define Y6_GPIO_NUM 39
#define Y5_GPIO_NUM 5
#define Y4_GPIO_NUM 34
#define Y3_GPIO_NUM 35
#define Y2_GPIO_NUM 17
#define VSYNC_GPIO_NUM 22
#define HREF_GPIO_NUM 26
#define PCLK_GPIO_NUM 21
#define I2C_SDA 14
#define I2C_SCL 13
#define BUTTON_1 32
#define SSD130_MODLE_TYPE GEOMETRY_128_32
#undef ENABLE_BME280
#undef ENABLE_AS312
#elif defined(TTGO_T_CAMERA_PLUS)
#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 4
#define SIOD_GPIO_NUM 18
#define SIOC_GPIO_NUM 23
#define Y9_GPIO_NUM 36
#define Y8_GPIO_NUM 37
#define Y7_GPIO_NUM 38
#define Y6_GPIO_NUM 39
#define Y5_GPIO_NUM 35
#define Y4_GPIO_NUM 26
#define Y3_GPIO_NUM 13
#define Y2_GPIO_NUM 34
#define VSYNC_GPIO_NUM 5
#define HREF_GPIO_NUM 27
#define PCLK_GPIO_NUM 25
#define I2C_SDA -1
#define I2C_SCL -1
#undef ENABLE_SSD1306
#undef ENABLE_BME280
#undef ENABLE_SLEEP
#undef ENABLE_IP5306
#undef ENABLE_AS312
#undef ENABLE_BUTTON
#else
#error "Please select board type"
#endif
#ifdef ENABLE_SSD1306
#include "SSD1306.h"
#include "OLEDDisplayUi.h"
#define SSD1306_ADDRESS 0x3c
SSD1306 oled(SSD1306_ADDRESS, I2C_SDA, I2C_SCL, SSD130_MODLE_TYPE);
OLEDDisplayUi ui(&oled);
#endif
String ip;
EventGroupHandle_t evGroup;
#ifdef ENABLE_BUTTON
OneButton button1(BUTTON_1, true);
#endif
#ifdef ENABLE_BME280
#define BEM280_ADDRESS 0X77
#define SEALEVELPRESSURE_HPA (1013.25)
Adafruit_BME280 bme;
#endif
#define IP5306_ADDR 0X75
#define IP5306_REG_SYS_CTL0 0x00
void startCameraServer();
char buff[128];
#ifdef ENABLE_IP5306
bool setPowerBoostKeepOn(int en)
{
Wire.beginTransmission(IP5306_ADDR);
Wire.write(IP5306_REG_SYS_CTL0);
if (en)
Wire.write(0x37); // Set bit1: 1 enable 0 disable boost keep on
else
Wire.write(0x35); // 0x37 is default reg value
return Wire.endTransmission() == 0;
}
#endif
void buttonClick()
{
static bool en = false;
xEventGroupClearBits(evGroup, 1);
sensor_t *s = esp_camera_sensor_get();
en = en ? 0 : 1;
s->set_vflip(s, en);
delay(200);
xEventGroupSetBits(evGroup, 1);
}
void buttonLongPress()
{
#ifdef ENABLE_SSD1306
int x = oled.getWidth() / 2;
int y = oled.getHeight() / 2;
ui.disableAutoTransition();
oled.setTextAlignment(TEXT_ALIGN_CENTER);
oled.setFont(ArialMT_Plain_10);
oled.clear();
#endif
#ifdef ENABLE_SLEEP
if (PWDN_GPIO_NUM > 0) {
pinMode(PWDN_GPIO_NUM, PULLUP);
digitalWrite(PWDN_GPIO_NUM, HIGH);
}
oled.drawString(x, y, "Press again to wake up");
oled.display();
delay(6000);
oled.clear();
oled.display();
oled.displayOff();
// esp_sleep_enable_ext0_wakeup((gpio_num_t )BUTTON_1, LOW);
esp_sleep_enable_ext1_wakeup(((uint64_t)(((uint64_t)1) << BUTTON_1)), ESP_EXT1_WAKEUP_ALL_LOW);
esp_deep_sleep_start();
#endif
}
#ifdef ENABLE_SSD1306
void drawFrame1(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y)
{
display->setTextAlignment(TEXT_ALIGN_CENTER);
int y1 = 25;
if (oled.getHeight() == 32) {
y1 = 10;
}
#ifdef SOFTAP_MODE
display->setFont(ArialMT_Plain_10);
display->drawString(64 + x, y1 + y, buff);
#else
display->setFont(ArialMT_Plain_16);
display->drawString(64 + x, y1 + y, ip);
#endif
#ifdef ENABLE_AS312
if (digitalRead(AS312_PIN)) {
display->drawString(64 + x, 5 + y, "AS312 Trigger");
}
#endif
}
void drawFrame2(OLEDDisplay *display, OLEDDisplayUiState *state, int16_t x, int16_t y)
{
#ifdef ENABLE_BME280
static String temp, pressure, altitude, humidity;
static uint64_t lastMs;
if (millis() - lastMs > 2000) {
lastMs = millis();
temp = "Temp:" + String(bme.readTemperature()) + " *C";
pressure = "Press:" + String(bme.readPressure() / 100.0F) + " hPa";
altitude = "Altitude:" + String(bme.readAltitude(SEALEVELPRESSURE_HPA)) + " m";
humidity = "Humidity:" + String(bme.readHumidity()) + " %";
}
display->setFont(ArialMT_Plain_16);
display->setTextAlignment(TEXT_ALIGN_LEFT);
display->drawString(0 + x, 0 + y, temp);
display->drawString(0 + x, 16 + y, pressure);
display->drawString(0 + x, 32 + y, altitude);
display->drawString(0 + x, 48 + y, humidity);
#else
display->setTextAlignment(TEXT_ALIGN_CENTER);
display->setFont(ArialMT_Plain_10);
if (oled.getHeight() == 32) {
display->drawString( 64 + x, 0 + y, "Camera Ready! Use");
display->drawString(64 + x, 10 + y, "http://" + ip );
display->drawString(64 + x, 16 + y, "to connect");
} else {
display->drawString( 64 + x, 5 + y, "Camera Ready! Use");
display->drawString(64 + x, 25 + y, "http://" + ip );
display->drawString(64 + x, 45 + y, "to connect");
}
#endif
}
FrameCallback frames[] = {drawFrame1, drawFrame2};
#define FRAMES_SIZE (sizeof(frames) / sizeof(frames[0]))
#endif
void setup()
{
Serial.begin(115200);
Serial.setDebugOutput(true);
Serial.println();
#ifdef ENABLE_AS312
pinMode(AS312_PIN, INPUT);
#endif
if (I2C_SDA > 0)
Wire.begin(I2C_SDA, I2C_SCL);
#ifdef ENABLE_IP5306
bool isOk = setPowerBoostKeepOn(1);
String info = "IP5306 KeepOn " + String((isOk ? "PASS" : "FAIL"));
#endif
#ifdef ENABLE_SSD1306
int x = oled.getWidth() / 2;
int y = oled.getHeight() / 2;
oled.init();
// Wire.setClock(100000); //! Reduce the speed and prevent the speed from being too high, causing the screen
oled.setFont(ArialMT_Plain_16);
oled.setTextAlignment(TEXT_ALIGN_CENTER);
delay(50);
oled.drawString(x, y - 10, "TTGO Camera");
oled.display();
#endif
#ifdef ENABLE_IP5306
delay(1000);
oled.setFont(ArialMT_Plain_10);
oled.clear();
oled.drawString(x, y - 10, info);
oled.display();
oled.setFont(ArialMT_Plain_16);
delay(1000);
#endif
#ifdef ENABLE_BME280
if (!bme.begin(BEM280_ADDRESS)) {
Serial.println("Could not find a valid BME280 sensor, check wiring!");
while (1);
}
#endif
if (!(evGroup = xEventGroupCreate())) {
Serial.println("evGroup Fail");
while (1);
}
xEventGroupSetBits(evGroup, 1);
#ifdef TTGO_T_CAMERA_MIC_V16
/* IO13, IO14 is designed for JTAG by default,
* to use it as generalized input,
* firstly declair it as pullup input */
pinMode(13, INPUT_PULLUP);
pinMode(14, INPUT_PULLUP);
#endif
camera_config_t config;
config.ledc_channel = LEDC_CHANNEL_0;
config.ledc_timer = LEDC_TIMER_0;
config.pin_d0 = Y2_GPIO_NUM;
config.pin_d1 = Y3_GPIO_NUM;
config.pin_d2 = Y4_GPIO_NUM;
config.pin_d3 = Y5_GPIO_NUM;
config.pin_d4 = Y6_GPIO_NUM;
config.pin_d5 = Y7_GPIO_NUM;
config.pin_d6 = Y8_GPIO_NUM;
config.pin_d7 = Y9_GPIO_NUM;
config.pin_xclk = XCLK_GPIO_NUM;
config.pin_pclk = PCLK_GPIO_NUM;
config.pin_vsync = VSYNC_GPIO_NUM;
config.pin_href = HREF_GPIO_NUM;
config.pin_sscb_sda = SIOD_GPIO_NUM;
config.pin_sscb_scl = SIOC_GPIO_NUM;
config.pin_pwdn = PWDN_GPIO_NUM;
config.pin_reset = RESET_GPIO_NUM;
config.xclk_freq_hz = 20000000;
config.pixel_format = PIXFORMAT_JPEG;
//init with high specs to pre-allocate larger buffers
if (psramFound()) {
config.frame_size = FRAMESIZE_UXGA;
config.jpeg_quality = 10;
config.fb_count = 2;
} else {
config.frame_size = FRAMESIZE_SVGA;
config.jpeg_quality = 12;
config.fb_count = 1;
}
esp_err_t err = esp_camera_init(&config);
if (err != ESP_OK) {
Serial.printf("Camera init Fail");
#ifdef ENABLE_SSD1306
oled.clear();
oled.drawString(oled.getWidth() / 2, oled.getHeight() / 2, "Camera init Fail");
oled.display();
#endif
while (1);
}
//drop down frame size for higher initial frame rate
sensor_t *s = esp_camera_sensor_get();
s->set_framesize(s, FRAMESIZE_QVGA);
#ifdef ENABLE_BUTTON
button1.attachLongPressStart(buttonLongPress);
button1.attachClick(buttonClick);
#endif
#ifdef SOFTAP_MODE
Serial.println("Configuring access point...");
uint8_t mac[6];
esp_wifi_get_mac(WIFI_IF_AP, mac);
sprintf(buff, "TTGO-CAMERA-%02X:%02X", mac[4], mac[5]);
WiFi.softAP(buff);
ip = WiFi.softAPIP().toString();
#else
WiFi.begin(WIFI_SSID, WIFI_PASSWD);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
ip = WiFi.localIP().toString();
#endif
startCameraServer();
delay(50);
#ifdef ENABLE_SSD1306
ui.setTargetFPS(30);
ui.setIndicatorPosition(BOTTOM);
ui.setIndicatorDirection(LEFT_RIGHT);
ui.setFrameAnimation(SLIDE_LEFT);
ui.setFrames(frames, FRAMES_SIZE);
ui.setTimePerFrame(6000);
#endif
Serial.print("Camera Ready! Use 'http://");
Serial.print(ip);
Serial.println("' to connect");
}
void loop()
{
#ifdef ENABLE_SSD1306
if (ui.update()) {
#endif
#ifdef ENABLE_BUTTON
button1.tick();
#else
delay(500);
#endif
#ifdef ENABLE_SSD1306
}
#endif
}
| [
"noreply@github.com"
] | AlshainAvior.noreply@github.com |
ae73cc115e7d7eef9d0324fdfa347b87c0c77f81 | 85b6258fce5bf77b996800563374e4455b3dd421 | /c++/first.cpp | 131e0cc0179d6f5730197de3ef9c26dd92ceecef | [] | no_license | YaoChungLiang/NTUclass | 09786048d88b37e0d66a87f53397055d3961e2ed | 9e2a597fd9766e27b6695e98238963c7560ae30c | refs/heads/master | 2022-10-25T10:55:20.904284 | 2020-06-19T11:07:53 | 2020-06-19T11:07:53 | 262,518,405 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 481 | cpp |
class Position{
private :
int x;
int y;
public:
Position(int x, int y):x(x),y(y) {} // damn c++ 17, when do we need
void Print() {
// ....
}
void SetX(int x){ // this encapsulate the idea of interface
this->x = x; // x(x) == this-.x = x
}
};
int main(){
Position p(3,5); // Position p = {3,5} if x y are public
p.Print();
// if we want to be p.x = 10, means it to be public
}
| [
"yliang2@uw.edu"
] | yliang2@uw.edu |
8e477f86d56901db2564fdd0237b8ff96fba6f61 | 48c116c9b62998dbd6d4823cff15e1480783703b | /Class/22.08.20/22.08.20/Source.cpp | 004302903aab59f18750a188d3196e459568f3bc | [] | no_license | Orest3321/C---Base | f28bbc4c4e5dcd213fb134244e30d6b17a68c142 | 9e0e9740abbfd644ecef87824c8d08c880f6d56b | refs/heads/master | 2022-12-03T13:51:03.724087 | 2020-08-22T14:25:35 | 2020-08-22T14:25:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 99 | cpp | #include<iostream>
using namespace std;
int main()
{
system("pause");
return 0;
} | [
"mka@rivne.itstep.org"
] | mka@rivne.itstep.org |
b22839aff57a4bbe0c23e5047dde5b28d0f46894 | db557a30a28f77774cf4662c119a9197fb3ae0a0 | /HelperFunctions/getVkGeometryAABBNV.cpp | 86a5bd76ede73ddf573e5275e8e3f8f18ff09bc5 | [
"Apache-2.0"
] | permissive | dkaip/jvulkan-natives-Linux-x86_64 | b076587525a5ee297849e08368f32d72098ae87e | ea7932f74e828953c712feea11e0b01751f9dc9b | refs/heads/master | 2021-07-14T16:57:14.386271 | 2020-09-13T23:04:39 | 2020-09-13T23:04:39 | 183,515,517 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,021 | cpp | /*
* Copyright 2019-2020 Douglas Kaip
*
* 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.
*/
/*
* getVkGeometryAABBNV.cpp
*
* Created on: Apr 1, 2019
* Author: Douglas Kaip
*/
#include "JVulkanHelperFunctions.hh"
#include "slf4j.hh"
namespace jvulkan
{
void getVkGeometryAABBNV(
JNIEnv *env,
const jobject jVkGeometryAABBNVObject,
VkGeometryAABBNV *vkGeometryAABBNV,
std::vector<void *> *memoryToFree)
{
jclass vkGeometryAABBNVClass = env->GetObjectClass(jVkGeometryAABBNVObject);
if (env->ExceptionOccurred())
{
return;
}
////////////////////////////////////////////////////////////////////////
VkStructureType sTypeValue = getSType(env, jVkGeometryAABBNVObject);
if (env->ExceptionOccurred())
{
return;
}
////////////////////////////////////////////////////////////////////////
jobject pNextObject = getpNextObject(env, jVkGeometryAABBNVObject);
if (env->ExceptionOccurred())
{
LOGERROR(env, "%s", "Call to getpNext failed.");
return;
}
if (pNextObject != nullptr)
{
LOGERROR(env, "%s", "pNext must be null.");
return;
}
void *pNext = nullptr;
////////////////////////////////////////////////////////////////////////
jmethodID methodId = env->GetMethodID(vkGeometryAABBNVClass, "getAabbData", "()Lcom/CIMthetics/jvulkan/VulkanCore/Handles/VkBuffer;");
if (env->ExceptionOccurred())
{
return;
}
jobject jVkBufferHandleObject = env->CallObjectMethod(jVkGeometryAABBNVObject, methodId);
if (env->ExceptionOccurred())
{
return;
}
VkBuffer_T *aabbDataHandle = (VkBuffer_T *)jvulkan::getHandleValue(env, jVkBufferHandleObject);
if (env->ExceptionOccurred())
{
return;
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(vkGeometryAABBNVClass, "getNumAABBs", "()I");
if (env->ExceptionOccurred())
{
return;
}
jint numAABBs = env->CallIntMethod(jVkGeometryAABBNVObject, methodId);
if (env->ExceptionOccurred())
{
return;
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(vkGeometryAABBNVClass, "getStride", "()I");
if (env->ExceptionOccurred())
{
return;
}
jint stride = env->CallIntMethod(jVkGeometryAABBNVObject, methodId);
if (env->ExceptionOccurred())
{
return;
}
////////////////////////////////////////////////////////////////////////
methodId = env->GetMethodID(vkGeometryAABBNVClass, "getOffset", "()J");
if (env->ExceptionOccurred())
{
return;
}
jlong offset = env->CallLongMethod(jVkGeometryAABBNVObject, methodId);
if (env->ExceptionOccurred())
{
return;
}
vkGeometryAABBNV->sType = sTypeValue;
vkGeometryAABBNV->pNext = (void *)pNext;
vkGeometryAABBNV->aabbData = aabbDataHandle;
vkGeometryAABBNV->numAABBs = numAABBs;
vkGeometryAABBNV->stride = stride;
vkGeometryAABBNV->offset = offset;
}
}
| [
"dkaip@earthlink.net"
] | dkaip@earthlink.net |
2cf5572094068417d5d7eb55cb9b6fc2b25d6242 | 2723bc08dfb2499343e7ba5e3e0edd2ddfb65291 | /lldb/source/Plugins/Process/Windows/DebuggerThread.h | 586a1a76856e4326fa1d5d76d544c6e0827468d4 | [
"NCSA"
] | permissive | Rombur/llvm-project | ff5f223655f8af875eb39651b84b3144d9ca57bc | 2d153d08a9514ca4e602b96f56d94ac38f439a0a | refs/heads/master | 2020-05-29T11:35:25.185427 | 2014-12-09T18:45:30 | 2014-12-09T18:45:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,125 | h | //===-- DebuggerThread.h ----------------------------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef liblldb_Plugins_Process_Windows_DebuggerThread_H_
#define liblldb_Plugins_Process_Windows_DebuggerThread_H_
#include "ForwardDecl.h"
#include "lldb/Host/HostProcess.h"
#include "lldb/Host/HostThread.h"
#include "lldb/Host/Predicate.h"
#include "lldb/Host/windows/windows.h"
#include <memory>
namespace lldb_private
{
//----------------------------------------------------------------------
// DebuggerThread
//
// Debugs a single process, notifying listeners as appropriate when interesting
// things occur.
//----------------------------------------------------------------------
class DebuggerThread : public std::enable_shared_from_this<DebuggerThread>
{
public:
DebuggerThread(DebugDelegateSP debug_delegate);
virtual ~DebuggerThread();
Error DebugLaunch(const ProcessLaunchInfo &launch_info);
HostProcess
GetProcess() const
{
return m_process;
}
HostThread
GetMainThread() const
{
return m_main_thread;
}
ExceptionRecord *
GetActiveException()
{
return m_active_exception.get();
}
Error StopDebugging(bool terminate);
void ContinueAsyncException(ExceptionResult result);
private:
void FreeProcessHandles();
void DebugLoop();
ExceptionResult HandleExceptionEvent(const EXCEPTION_DEBUG_INFO &info, DWORD thread_id);
DWORD HandleCreateThreadEvent(const CREATE_THREAD_DEBUG_INFO &info, DWORD thread_id);
DWORD HandleCreateProcessEvent(const CREATE_PROCESS_DEBUG_INFO &info, DWORD thread_id);
DWORD HandleExitThreadEvent(const EXIT_THREAD_DEBUG_INFO &info, DWORD thread_id);
DWORD HandleExitProcessEvent(const EXIT_PROCESS_DEBUG_INFO &info, DWORD thread_id);
DWORD HandleLoadDllEvent(const LOAD_DLL_DEBUG_INFO &info, DWORD thread_id);
DWORD HandleUnloadDllEvent(const UNLOAD_DLL_DEBUG_INFO &info, DWORD thread_id);
DWORD HandleODSEvent(const OUTPUT_DEBUG_STRING_INFO &info, DWORD thread_id);
DWORD HandleRipEvent(const RIP_INFO &info, DWORD thread_id);
DebugDelegateSP m_debug_delegate;
HostProcess m_process; // The process being debugged.
HostThread m_main_thread; // The main thread of the inferior.
HANDLE m_image_file; // The image file of the process being debugged.
ExceptionRecordUP m_active_exception; // The current exception waiting to be handled
Predicate<ExceptionResult> m_exception_pred; // A predicate which gets signalled when an exception
// is finished processing and the debug loop can be
// continued.
static lldb::thread_result_t DebuggerThreadRoutine(void *data);
lldb::thread_result_t DebuggerThreadRoutine(const ProcessLaunchInfo &launch_info);
};
}
#endif
| [
"zturner@google.com"
] | zturner@google.com |
c608def80b6a30f44614116e2c04310b2b4cdeae | 57d792e02f7a2c475a824573896d734727395267 | /algos-and-data-structures/labs/lab-1/b.cpp | 5b7f0c9e9176773d854510e9e159869246246446 | [] | no_license | holounic/university | 9eec5b46f362f04938eb05426692672d76519f59 | ebad02c50e7702ae2c3ea4da64b8c928e8f30575 | refs/heads/master | 2022-10-17T17:06:10.730435 | 2022-10-03T16:06:38 | 2022-10-03T16:06:38 | 208,440,024 | 17 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 484 | cpp | #include <iostream>
#include <vector>
using namespace std;
int main() {
vector <int> a;
int temp;
while (cin >> temp) {
a.push_back(temp);
}
int* c = new int[101];
for (int i = 0; i < 101; i++) *(c + i) = 0;
for (int i = 0; i < a.size(); i++) *(c + a[i]) += 1;
int k = 0;
for (int i = 0; i < 101; i++) {
for (int j = 0; j < c[i]; j++) {
a[k] = i;
cout << a[k] << " ";
k++;
}
}
} | [
"noreply@github.com"
] | holounic.noreply@github.com |
0bb0dc322175d3a9d95dc71b591b535cbfc28f91 | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE590_Free_Memory_Not_on_Heap/s01/CWE590_Free_Memory_Not_on_Heap__delete_array_char_static_16.cpp | 8efca7a69ba827068e64262e73e3281d5f8a28d3 | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 2,824 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE590_Free_Memory_Not_on_Heap__delete_array_char_static_16.cpp
Label Definition File: CWE590_Free_Memory_Not_on_Heap__delete_array.label.xml
Template File: sources-sink-16.tmpl.cpp
*/
/*
* @description
* CWE: 590 Free Memory Not on Heap
* BadSource: static Data buffer is declared static on the stack
* GoodSource: Allocate memory on the heap
* Sink:
* BadSink : Print then free data
* Flow Variant: 16 Control flow: while(1)
*
* */
#include "std_testcase.h"
#include <wchar.h>
namespace CWE590_Free_Memory_Not_on_Heap__delete_array_char_static_16
{
#ifndef OMITBAD
void bad()
{
char * data;
data = NULL; /* Initialize data */
while(1)
{
{
/* FLAW: data is allocated on the stack and deallocated in the BadSink */
static char dataBuffer[100];
memset(dataBuffer, 'A', 100-1); /* fill with 'A's */
dataBuffer[100-1] = '\0'; /* null terminate */
data = dataBuffer;
}
break;
}
printLine(data);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() - use goodsource and badsink by changing the conditions on the while statements */
static void goodG2B()
{
char * data;
data = NULL; /* Initialize data */
while(1)
{
{
/* FIX: data is allocated on the heap and deallocated in the BadSink */
char * dataBuffer = new char[100];
memset(dataBuffer, 'A', 100-1); /* fill with 'A's */
dataBuffer[100-1] = '\0'; /* null terminate */
data = dataBuffer;
}
break;
}
printLine(data);
/* POTENTIAL FLAW: Possibly deallocating memory allocated on the stack */
delete [] data;
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE590_Free_Memory_Not_on_Heap__delete_array_char_static_16; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
d4b0f0bf1f9e43f4f5d73c00616c906302087b5b | 19c74c41c2cee8c0b8b56f76d2156950e0ba8391 | /debug_log.h | 212bc58401a85873d6f3d7ce2a6b178c28085a5b | [] | no_license | tyzjames/midi-editor | cd32296d849a36feef60058bc491e432c8587828 | 64fdfb30c0bc0321fabe1ebba46da5249618ba36 | refs/heads/master | 2021-01-25T07:19:51.683076 | 2016-01-12T16:14:29 | 2016-01-12T16:14:29 | 42,509,662 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 252 | h | #ifndef DEBUG_LOG
#define DEBUG_LOG
#include <QTextStream>
#include <QFile>
#include <QCoreApplication>
class debug_log {
public:
debug_log(bool newFile);
void writeLog(QString text);
private:
QString filename;
};
#endif // DEBUG_LOG
| [
"tyzjames@hotmail.com"
] | tyzjames@hotmail.com |
86d2bebb57176fbc11821a5392d56b4ea5a5e9c4 | 14104bd60d0ba1316e71d9557440b4aaf61e8dc2 | /98/include/Date.h | 1a74c37f31d234430b0cea9e63eb6da6ab17a75b | [] | no_license | xiaoyujia66/xiao_yujia | b935d49f8d79c05a91794dbc7ec0651dcf411c22 | 1eafd7bfd483479556debdfd4e827568d225c212 | refs/heads/master | 2020-04-27T23:48:51.897277 | 2019-06-02T11:24:39 | 2019-06-02T11:24:39 | 174,791,389 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 467 | h | #ifndef DATE_H
#define DATE_H
class Date
{
public:
Date( int, int, int );
void print();
void setDate( int, int, int );
void setMonth( int );
void setDay( int );
void setYear( int );
int getMonth();
int getDay();
int getYear();
void nextDay();
private:
int month;
int day;
int year;
bool leapYear();
int monthDays();
};
#endif // DATE_H
| [
"435713285@qq.com"
] | 435713285@qq.com |
e1179e891c8c1cfe2fbc8e13c76543be840f863d | c6563a1fd7008f1bd6b63e71d9a4b1c50ea4a206 | /JewelThief2/Game/MapLoader.cpp | 868c4c207460df27799eaabf9157005a363620f0 | [
"MIT"
] | permissive | Munky665/AIForGames | 7a1a421f88e60384565d45eb646e362f18ab6e65 | 5b77c257c5453df867537b37a5ebf960f90bcc82 | refs/heads/master | 2020-09-22T14:09:58.362779 | 2020-03-03T04:07:13 | 2020-03-03T04:07:13 | 225,225,308 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,109 | cpp | #include "MapLoader.h"
#include "Room.h"
#include "Player.h"
#include "Collider.cpp"
#include "Tile.h"
#include "Node.h"
MapLoader::MapLoader()
{
//push rooms to list based on number of rooms
for (int i = 0; i < m_numberOfRooms; ++i)
{
m_rooms.push_back(new Room(i));
}
}
MapLoader::~MapLoader()
{
}
//load new room if player collides with doorway
void MapLoader::LoadNextRoom(Player * p)
{
for (Tile* t : m_rooms[m_currentRoom]->GetMap())
{
if (t->GetId() == 4 || t->GetId() == 5)
{
if (CheckCollision(t->GetCollider(), p->GetCollider(), glm::vec2(0, 0)))
{
switch (m_currentRoom)
{
case 0://room 1
//top door to room 2
p->SetPosition(glm::vec2(t->GetPosition().x, m_roomBottomPos));
m_currentRoom = 1; //connects line 40
break;
case 1:// room2
//bottom door to room one
if (p->GetPosition().y <= m_roomBottomPos)
{
p->SetPosition(glm::vec2(t->GetPosition().x, m_roomTopPos));
m_currentRoom = 0; //connects line 33
}
//right door to room 3
else if (p->GetPosition().x >= m_roomRightPos)
{
p->SetPosition(glm::vec2(m_roomLeftPos, t->GetPosition().y));
m_currentRoom = 2; //connects line 60
}
//top door to room 4
else if (p->GetPosition().y >= m_roomTopPos)
{
p->SetPosition(glm::vec2(t->GetPosition().x, m_roomBottomPos));
m_currentRoom = 3; //connects line 74
}
break;
case 2://room3
//left door to room 2
if (p->GetPosition().x < m_roomLeftPos)
{
p->SetPosition(glm::vec2(m_roomRightPos, t->GetPosition().y));
m_currentRoom = 1; //connects line 46
}
//top door to room 5
else if (p->GetPosition().y >= m_roomTopPos)
{
p->SetPosition(glm::vec2(t->GetPosition().x, m_roomBottomPos));
m_currentRoom = 4; //connects line 88
}
break;
case 3://room4
//bottom door to room 2
if (p->GetPosition().y <= m_roomBottomPos)
{
p->SetPosition(glm::vec2(t->GetPosition().x, m_roomTopPos));
m_currentRoom = 1; //connects line 52
}
//right door to room 5
else if (p->GetPosition().x >= m_roomRightPos)
{
p->SetPosition(glm::vec2(m_roomLeftPos, t->GetPosition().y));
m_currentRoom = 4; //connects line 94
}
break;
case 4: //room5
//bottom door to room 3
if (p->GetPosition().y <= m_roomBottomPos)
{
p->SetPosition(glm::vec2(t->GetPosition().x, m_roomTopPos));
m_currentRoom = 2; //connects line 66
}
//left door to room
else if (p->GetPosition().x < m_roomLeftPos)
{
p->SetPosition(glm::vec2(m_roomRightPos, t->GetPosition().y));
m_currentRoom = 3;//connects line 80
}
//right door
else if (p->GetPosition().x >= m_roomRightPos)
{
p->SetPosition(glm::vec2(m_roomLeftPos, t->GetPosition().y));
m_currentRoom = 5; //connects line 108
}
break;
case 5: //room6
//left door
if (p->GetPosition().x < m_roomLeftPos)
{
p->SetPosition(glm::vec2(m_roomRightPos, t->GetPosition().y));
m_currentRoom = 4; //connects line 100
}
//bottom door
else if (p->GetPosition().y <= m_roomBottomPos)
{
p->SetPosition(glm::vec2(t->GetPosition().x, m_roomTopPos));
m_currentRoom = 6; //connects line 122
}
break;
case 6: //room7
//top door
if (p->GetPosition().y >= m_roomTopPos)
{
p->SetPosition(glm::vec2(t->GetPosition().x, m_roomBottomPos));
m_currentRoom = 5; //connects line 114
}
break;
}
}
}
}
}
//returns current room
Room* MapLoader::GetCurrentRoom()
{
return m_rooms[m_currentRoom];
}
//return room by index
Room* MapLoader::GetRoom(int n)
{
return m_rooms[n];
}
//change current room
void MapLoader::ChangeRoom(int roomNumber)
{
m_currentRoom = roomNumber;
}
//reset the node maps g scores to stop aStar from failing
void MapLoader::ResetGraph()
{
for (int i = 0; i < GetCurrentRoom()->GetMap().size(); ++i)
{
GetCurrentRoom()->GetNodeMap()[i]->gScore = std::numeric_limits<float>::max();
}
} | [
"adam.b.whitty@gmail.com"
] | adam.b.whitty@gmail.com |
54f460049e86385f65f41cffef4f27fb82461349 | d6a66abbeda631e1534141eab6061001c57eb583 | /Prepost_CCP/constant/triSurface/nozzle_down.eMesh | c59e18c378852f2bb74157ea81172bcd65910c0c | [] | no_license | MelodyLiu666/Mold_straightNozzle | 243c265e3e361175d207de185372de2ad9d036e1 | 81c942e6ebdfb949a71bf377385e9294ae4df799 | refs/heads/master | 2021-02-04T11:31:16.108979 | 2020-03-03T12:54:00 | 2020-03-03T12:54:00 | 243,661,662 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,063 | emesh | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 7
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class featureEdgeMesh;
location "constant/triSurface";
object nozzle_down.eMesh;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// points:
128
(
(0.00634 -0.031876 0.5)
(0.012437 -0.030026 0.5)
(0.012437 -0.030026 0.45)
(0.00634 -0.031876 0.45)
(0.012437 0.030026 0.5)
(0.00634 0.031876 0.5)
(0.00634 0.031876 0.45)
(0.012437 0.030026 0.45)
(-0.018056 0.027023 0.5)
(-0.022981 0.022981 0.5)
(-0.022981 0.022981 0.45)
(-0.018056 0.027023 0.45)
(0 -0.0325 0.5)
(-0 -0.0325 0.45)
(0.018056 0.027023 0.5)
(0.018056 0.027023 0.45)
(-0.012437 0.030026 0.5)
(-0.012437 0.030026 0.45)
(-0.00634 -0.031876 0.5)
(-0.00634 -0.031876 0.45)
(0.022981 0.022981 0.5)
(0.022981 0.022981 0.45)
(-0.00634 0.031876 0.5)
(-0.00634 0.031876 0.45)
(-0.012437 -0.030026 0.5)
(-0.012437 -0.030026 0.45)
(0.027023 0.018056 0.5)
(0.027023 0.018056 0.45)
(0 0.0325 0.5)
(-0 0.0325 0.45)
(-0.018056 -0.027023 0.5)
(-0.018056 -0.027023 0.45)
(0.030026 0.012437 0.5)
(0.030026 0.012437 0.45)
(-0.022981 -0.022981 0.5)
(-0.022981 -0.022981 0.45)
(0.031875 0.00634 0.5)
(0.031875 0.00634 0.45)
(-0.027023 -0.018056 0.5)
(-0.027023 -0.018056 0.45)
(0.0325 0 0.5)
(0.0325 -0 0.45)
(-0.030026 -0.012437 0.5)
(-0.030026 -0.012437 0.45)
(0.031875 -0.00634 0.5)
(0.031875 -0.00634 0.45)
(-0.031875 -0.00634 0.5)
(-0.031875 -0.00634 0.45)
(0.030026 -0.012437 0.5)
(0.030026 -0.012437 0.45)
(-0.0325 0 0.5)
(-0.0325 -0 0.45)
(0.027023 -0.018056 0.5)
(0.027023 -0.018056 0.45)
(-0.031875 0.00634 0.5)
(-0.031875 0.00634 0.45)
(0.022981 -0.022981 0.5)
(0.022981 -0.022981 0.45)
(-0.030026 0.012437 0.5)
(-0.030026 0.012437 0.45)
(0.018056 -0.027023 0.5)
(0.018056 -0.027023 0.45)
(-0.027023 0.018056 0.5)
(-0.027023 0.018056 0.45)
(-0.017164 0.003414 0.45)
(-0.0175 0 0.45)
(-0.0175 0 0.5)
(-0.017164 0.003414 0.5)
(0.012374 -0.012374 0.45)
(0.014551 -0.009722 0.45)
(0.014551 -0.009722 0.5)
(0.012374 -0.012374 0.5)
(-0.016168 0.006697 0.45)
(-0.016168 0.006697 0.5)
(0.009722 -0.014551 0.45)
(0.009722 -0.014551 0.5)
(-0.014551 0.009722 0.45)
(-0.014551 0.009722 0.5)
(0.006697 -0.016168 0.45)
(0.006697 -0.016168 0.5)
(0.003414 0.017164 0.45)
(0 0.0175 0.45)
(0 0.0175 0.5)
(0.003414 0.017164 0.5)
(-0.012374 0.012374 0.45)
(-0.012374 0.012374 0.5)
(0.003414 -0.017164 0.45)
(0.003414 -0.017164 0.5)
(0.006697 0.016168 0.45)
(0.006697 0.016168 0.5)
(-0.009722 0.014551 0.45)
(-0.009722 0.014551 0.5)
(-0 -0.0175 0.45)
(-0 -0.0175 0.5)
(0.009722 0.014551 0.45)
(0.009722 0.014551 0.5)
(-0.006697 0.016168 0.45)
(-0.006697 0.016168 0.5)
(-0.003414 -0.017164 0.45)
(-0.003414 -0.017164 0.5)
(0.012374 0.012374 0.45)
(0.012374 0.012374 0.5)
(-0.003414 0.017164 0.45)
(-0.003414 0.017164 0.5)
(-0.006697 -0.016168 0.45)
(-0.006697 -0.016168 0.5)
(0.014551 0.009722 0.45)
(0.014551 0.009722 0.5)
(-0.009722 -0.014551 0.45)
(-0.009722 -0.014551 0.5)
(0.016168 0.006697 0.45)
(0.016168 0.006697 0.5)
(-0.012374 -0.012374 0.45)
(-0.012374 -0.012374 0.5)
(0.017164 0.003414 0.45)
(0.017164 0.003414 0.5)
(-0.014551 -0.009722 0.45)
(-0.014551 -0.009722 0.5)
(0.0175 0 0.45)
(0.0175 0 0.5)
(-0.016168 -0.006697 0.45)
(-0.016168 -0.006697 0.5)
(0.017164 -0.003414 0.45)
(0.017164 -0.003414 0.5)
(-0.017164 -0.003414 0.45)
(-0.017164 -0.003414 0.5)
(0.016168 -0.006697 0.45)
(0.016168 -0.006697 0.5)
)
// edges:
256
(
(65 66)
(67 64)
(69 70)
(71 68)
(73 72)
(75 74)
(77 76)
(79 78)
(81 82)
(83 80)
(85 84)
(87 86)
(89 88)
(91 90)
(93 92)
(95 94)
(97 96)
(99 98)
(101 100)
(103 102)
(105 104)
(107 106)
(109 108)
(111 110)
(113 112)
(115 114)
(117 116)
(119 118)
(121 120)
(123 122)
(125 124)
(127 126)
(1 2)
(3 0)
(5 6)
(7 4)
(9 10)
(11 8)
(13 12)
(15 14)
(17 16)
(19 18)
(21 20)
(23 22)
(25 24)
(27 26)
(29 28)
(31 30)
(33 32)
(35 34)
(37 36)
(39 38)
(41 40)
(43 42)
(45 44)
(47 46)
(49 48)
(51 50)
(53 52)
(55 54)
(57 56)
(59 58)
(61 60)
(63 62)
(6 4)
(10 8)
(3 12)
(7 14)
(19 24)
(21 26)
(23 28)
(25 30)
(35 38)
(37 40)
(45 48)
(47 50)
(49 52)
(55 58)
(57 60)
(59 62)
(71 74)
(73 76)
(85 90)
(87 92)
(89 94)
(101 106)
(103 81)
(105 108)
(113 116)
(115 118)
(125 65)
(127 69)
(2 0)
(11 16)
(13 18)
(15 20)
(17 22)
(27 32)
(31 34)
(33 36)
(39 42)
(41 44)
(43 46)
(51 54)
(53 56)
(61 1)
(29 5)
(63 9)
(66 64)
(70 68)
(67 72)
(75 78)
(82 80)
(77 84)
(79 86)
(83 88)
(91 96)
(93 98)
(95 100)
(97 102)
(99 104)
(107 110)
(109 112)
(111 114)
(117 120)
(119 122)
(121 124)
(123 126)
(0 1)
(2 3)
(4 5)
(6 7)
(8 9)
(10 11)
(12 0)
(3 13)
(14 4)
(7 15)
(16 8)
(11 17)
(18 12)
(13 19)
(20 14)
(15 21)
(22 16)
(17 23)
(24 18)
(19 25)
(26 20)
(21 27)
(28 22)
(23 29)
(30 24)
(25 31)
(32 26)
(27 33)
(34 30)
(31 35)
(36 32)
(33 37)
(38 34)
(35 39)
(40 36)
(37 41)
(42 38)
(39 43)
(44 40)
(41 45)
(46 42)
(43 47)
(48 44)
(45 49)
(50 46)
(47 51)
(52 48)
(49 53)
(54 50)
(51 55)
(56 52)
(53 57)
(58 54)
(55 59)
(60 56)
(57 61)
(62 58)
(59 63)
(1 60)
(61 2)
(5 28)
(29 6)
(9 62)
(63 10)
(64 65)
(66 67)
(68 69)
(70 71)
(72 64)
(67 73)
(74 68)
(71 75)
(76 72)
(73 77)
(78 74)
(75 79)
(80 81)
(82 83)
(84 76)
(77 85)
(86 78)
(79 87)
(88 80)
(83 89)
(90 84)
(85 91)
(92 86)
(87 93)
(94 88)
(89 95)
(96 90)
(91 97)
(98 92)
(93 99)
(100 94)
(95 101)
(102 96)
(97 103)
(104 98)
(99 105)
(106 100)
(101 107)
(81 102)
(103 82)
(108 104)
(105 109)
(110 106)
(107 111)
(112 108)
(109 113)
(114 110)
(111 115)
(116 112)
(113 117)
(118 114)
(115 119)
(120 116)
(117 121)
(122 118)
(119 123)
(124 120)
(121 125)
(126 122)
(123 127)
(65 124)
(125 66)
(69 126)
(127 70)
)
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
// ************************************************************************* //
| [
"xiaoyuliu_neu@163.com"
] | xiaoyuliu_neu@163.com |
7b20efd5814f9e912ba6de14b3644813f20dc095 | 080d2db2d45683f760bfa0f7f64755e8b8e6e466 | /src/checkpoints.cpp | 4926d37644c66cb96bf1c9fac1a68251bfbcd7ab | [
"MIT"
] | permissive | latinumcoin/latinumcoin | 5ae2109388f89fca66833201af704aafdb5e4860 | 441e4ac7fcfe25041e0f71e193b552fd3d5638e2 | refs/heads/master | 2021-03-12T23:05:44.467689 | 2014-07-08T19:28:34 | 2014-07-08T19:28:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,641 | cpp | // Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "checkpoints.h"
#include "main.h"
#include "uint256.h"
#include <stdint.h>
#include <boost/assign/list_of.hpp> // for 'map_list_of()'
#include <boost/foreach.hpp>
namespace Checkpoints
{
typedef std::map<int, uint256> MapCheckpoints;
// How many times we expect transactions after the last checkpoint to
// be slower. This number is a compromise, as it can't be accurate for
// every system. When reindexing from a fast disk with a slow CPU, it
// can be up to 20, while when downloading from a slow network with a
// fast multicore CPU, it won't be much higher than 1.
static const double SIGCHECK_VERIFICATION_FACTOR = 5.0;
struct CCheckpointData {
const MapCheckpoints *mapCheckpoints;
int64_t nTimeLastCheckpoint;
int64_t nTransactionsLastCheckpoint;
double fTransactionsPerDay;
};
bool fEnabled = true;
// What makes a good checkpoint block?
// + Is surrounded by blocks with reasonable timestamps
// (no blocks before with a timestamp after, none after with
// timestamp before)
// + Contains no strange transactions
static MapCheckpoints mapCheckpoints =
boost::assign::map_list_of
(11111, uint256("0x000000000020b76e429fbd1fab0ab72788f9147457650d171f4ca257eb079527"))
(22222, uint256("0x0000000000008d98496877ef7a043ba49fbd6b29ff37d60861d3cac54c9e4023"))
;
static const CCheckpointData data = {
&mapCheckpoints,
1404710134, // * UNIX timestamp of last checkpoint block
24470, // * total number of transactions between genesis and last checkpoint
// (the tx=... number in the SetBestChain debug.log lines)
50000.0 // * estimated number of transactions per day after checkpoint
};
static MapCheckpoints mapCheckpointsTestnet =
boost::assign::map_list_of
( 0, uint256("0x000000000933ea01ad0ee984209779baaec3ced90fa3f408719526f8d77f4943"))
;
static const CCheckpointData dataTestnet = {
&mapCheckpointsTestnet,
1338180505,
16341,
300
};
static MapCheckpoints mapCheckpointsRegtest =
boost::assign::map_list_of
( 0, uint256("0f9188f13cb7b2c71f2a335e3a4fc328bf5beb436012afca590b1a11466e2206"))
;
static const CCheckpointData dataRegtest = {
&mapCheckpointsRegtest,
0,
0,
0
};
const CCheckpointData &Checkpoints() {
if (Params().NetworkID() == CChainParams::TESTNET)
return dataTestnet;
else if (Params().NetworkID() == CChainParams::MAIN)
return data;
else
return dataRegtest;
}
bool CheckBlock(int nHeight, const uint256& hash)
{
if (!fEnabled)
return true;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
MapCheckpoints::const_iterator i = checkpoints.find(nHeight);
if (i == checkpoints.end()) return true;
return hash == i->second;
}
// Guess how far we are in the verification process at the given block index
double GuessVerificationProgress(CBlockIndex *pindex, bool fSigchecks) {
if (pindex==NULL)
return 0.0;
int64_t nNow = time(NULL);
double fSigcheckVerificationFactor = fSigchecks ? SIGCHECK_VERIFICATION_FACTOR : 1.0;
double fWorkBefore = 0.0; // Amount of work done before pindex
double fWorkAfter = 0.0; // Amount of work left after pindex (estimated)
// Work is defined as: 1.0 per transaction before the last checkpoint, and
// fSigcheckVerificationFactor per transaction after.
const CCheckpointData &data = Checkpoints();
if (pindex->nChainTx <= data.nTransactionsLastCheckpoint) {
double nCheapBefore = pindex->nChainTx;
double nCheapAfter = data.nTransactionsLastCheckpoint - pindex->nChainTx;
double nExpensiveAfter = (nNow - data.nTimeLastCheckpoint)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore;
fWorkAfter = nCheapAfter + nExpensiveAfter*fSigcheckVerificationFactor;
} else {
double nCheapBefore = data.nTransactionsLastCheckpoint;
double nExpensiveBefore = pindex->nChainTx - data.nTransactionsLastCheckpoint;
double nExpensiveAfter = (nNow - pindex->nTime)/86400.0*data.fTransactionsPerDay;
fWorkBefore = nCheapBefore + nExpensiveBefore*fSigcheckVerificationFactor;
fWorkAfter = nExpensiveAfter*fSigcheckVerificationFactor;
}
return fWorkBefore / (fWorkBefore + fWorkAfter);
}
int GetTotalBlocksEstimate()
{
if (!fEnabled)
return 0;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
return checkpoints.rbegin()->first;
}
CBlockIndex* GetLastCheckpoint(const std::map<uint256, CBlockIndex*>& mapBlockIndex)
{
if (!fEnabled)
return NULL;
const MapCheckpoints& checkpoints = *Checkpoints().mapCheckpoints;
BOOST_REVERSE_FOREACH(const MapCheckpoints::value_type& i, checkpoints)
{
const uint256& hash = i.second;
std::map<uint256, CBlockIndex*>::const_iterator t = mapBlockIndex.find(hash);
if (t != mapBlockIndex.end())
return t->second;
}
return NULL;
}
}
| [
"einewton@gmail.com"
] | einewton@gmail.com |
fabd888fca8f42911693a7d0e6a018660eca6c08 | 33683be0126967b13c5af32e979d8242fb85acaa | /MyClient_System_Editing/tabs/group.h | 39286a9de929be99f4f85bf2db582396a4d57413 | [
"MIT"
] | permissive | ASIKOO/metin2-myclient-system-editing | 5b5a8bb9e1b42d077640cee2398daa2621d7bf8e | 067e0b5cd0b0b4341321be810b0e2dd6ec424df7 | refs/heads/master | 2021-06-07T06:18:50.744992 | 2016-10-14T09:48:08 | 2016-10-14T09:48:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 456 | h | #ifndef MANAGER_H
#define MANAGER_H
#include "global.h"
struct GroupStruct
{
QString Name;
uint32_t Vnum;
QString Leader;
uint32_t LeaderVnum;
QStringList SubMob;
QList<uint32_t> SubMobVnum;
};
class GroupInfo
{
public:
GroupInfo();
static QList<GroupStruct> *Groups;
bool CheckType(QStringList tabs);
void OpenGroup(char *groupPath);
private:
bool isOpen;
GroupStruct *tempGr;
};
#endif // MANAGER_H
| [
"christian.roggia@gmail.com"
] | christian.roggia@gmail.com |
24f7345de7a7cdd9f8dc25f659afad3a4c41e153 | c6eeb0463648da5b8d8c6ba44cb2d058adfcdbb0 | /ProceduralTexture.cpp | a5e4a9e593c7ee9e3a157071a2612fd80870b214 | [] | no_license | fbgtoke/TerrainGenerator | 1091e7a8e4e54728ee6a5559ad987caccf2ff9d1 | 6c96cf7613ca1c7c133ec8d572d8e74f1c9d4a2b | refs/heads/master | 2021-01-18T16:12:09.426363 | 2018-06-18T08:22:29 | 2018-06-18T08:22:29 | 86,726,185 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,003 | cpp | #include "ProceduralTexture.h"
ProceduralTexture::ProceduralTexture() {}
ProceduralTexture::~ProceduralTexture() {
if (mTextureId != GL_INVALID_VALUE)
glDeleteTextures(1, &mTextureId);
if (mPixels != nullptr) free(mPixels);
}
void ProceduralTexture::generate(unsigned int width, unsigned int height, uint64_t seed) {
mWidth = width;
mHeight = height;
mPixels = (unsigned char*) malloc(mWidth * mHeight * 3 * sizeof(unsigned char));
Simplex2d simplex(seed, 1.f/8.f, 16.f, 255.f);
unsigned int i, j;
for (i = 0; i < mHeight; ++i) {
for (j = 0; j < mWidth; ++j) {
mPixels[i*mWidth*3 + j*3 + 0] = (unsigned int)simplex.getValue(j, i)*0.25f;
mPixels[i*mWidth*3 + j*3 + 1] = (unsigned int)simplex.getValue(j, i);
mPixels[i*mWidth*3 + j*3 + 2] = (unsigned int)simplex.getValue(j, i)*0.25f;
}
}
glGenTextures(1, &mTextureId);
glBindTexture(GL_TEXTURE_2D, mTextureId);
glTexStorage2D(GL_TEXTURE_2D, 1, GL_RGB8, mWidth, mHeight);
glTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, mWidth, mHeight, GL_RGB, GL_UNSIGNED_BYTE, mPixels);
}
void ProceduralTexture::setWrapS(GLint value) { wrapS = value; }
void ProceduralTexture::setWrapT(GLint value) { wrapT = value; }
void ProceduralTexture::setMinFilter(GLint value) { minFilter = value; }
void ProceduralTexture::setMagFilter(GLint value) { magFilter = value; }
void ProceduralTexture::use() const {
glActiveTexture(mTextureUnit);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, mTextureId);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, wrapS);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, wrapT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, minFilter);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, magFilter);
}
unsigned int ProceduralTexture::getWidth() const { return mWidth; }
unsigned int ProceduralTexture::getHeight() const { return mHeight; }
GLuint ProceduralTexture::getTexId() const { return mTextureId; }
void ProceduralTexture::setTexUnit(GLenum unit) { mTextureUnit = unit; } | [
"fabio.banchelli@bsc.es"
] | fabio.banchelli@bsc.es |
d3a6aec92141a50773a0612b26a2bc19c0203621 | aaa60b19f500fc49dbaac1ec87e9c535a66b4ff5 | /array-easy/605.种花问题.cpp | 52ad3db8bcf8aed7dd5b8dde825fdff4012b1c35 | [] | no_license | younger-1/leetcode-younger | c24e4a2a77c2f226c064c4eaf61e7f47d7e98d74 | a6dc92bbb90c5a095ac405476aeae6690e204b6b | refs/heads/master | 2023-07-25T02:31:42.430740 | 2021-09-09T08:06:05 | 2021-09-09T08:06:05 | 334,441,040 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 937 | cpp | /*
* @lc app=leetcode.cn id=605 lang=cpp
*
* [605] 种花问题
*/
#include <iostream>
#include <vector>
using namespace std;
// @lc code=start
// 124/124 cases passed (24 ms)
// Your runtime beats 80.42 % of cpp submissions
// Your memory usage beats 5 % of cpp submissions (20.7 MB)
class Solution {
public:
bool canPlaceFlowers(vector<int>& flowerbed, int n) {
int m = flowerbed.size();
vector<int> bed(m + 2, 0);
for (int i = 0; i < m; i++) {
bed[i + 1] = flowerbed[i];
}
int i = 0;
while (i < m) {
i += 1;
if (bed[i - 1] || bed[i] || bed[i + 1]) {
continue;
}
bed[i] = 1;
n -= 1;
}
return n > 0 ? false : true;
}
};
// @lc code=end
int main() {
vector<int> v{1, 0, 0, 0, 1};
Solution s = Solution();
cout << boolalpha << s.canPlaceFlowers(v, 3);
} | [
"45989017+younger-1@users.noreply.github.com"
] | 45989017+younger-1@users.noreply.github.com |
8f8eb32af4b815bcddcafcd6756e929e416b64f6 | 298bf79bae0ca3d499b066259f148dbd0e28fce9 | /src/main/cpp/pistis/concurrent/EpollEventType.cpp | 317926f67c703b91b147c58edafb45b8536c9eaf | [
"Apache-2.0"
] | permissive | tomault/pistis-concurrent | 12b54fb4132a05d015db052addc8d1f2a152de83 | ce3206feb3ca42468e35f6d276cd1871c0f9133f | refs/heads/master | 2020-04-11T10:19:29.794117 | 2019-08-25T19:33:51 | 2019-08-25T19:33:51 | 161,710,957 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,340 | cpp | #include "EpollEventType.hpp"
#include <tuple>
#include <vector>
using namespace pistis::concurrent;
namespace {
static const std::vector< std::tuple<EpollEventType, std::string> >&
eventToNameMap() {
static const std::vector< std::tuple<EpollEventType, std::string> >
EVENT_TO_NAME_MAP{
std::tuple<EpollEventType, std::string>(EpollEventType::READ, "READ"),
std::tuple<EpollEventType, std::string>(EpollEventType::WRITE, "WRITE"),
std::tuple<EpollEventType, std::string>(EpollEventType::READ_HANGUP,
"READ_HANGUP"),
std::tuple<EpollEventType, std::string>(EpollEventType::HANGUP,
"HANGUP"),
std::tuple<EpollEventType, std::string>(EpollEventType::PRIORITY,
"PRIORITY"),
std::tuple<EpollEventType, std::string>(EpollEventType::ERROR, "ERROR")
};
return EVENT_TO_NAME_MAP;
}
}
namespace pistis {
namespace concurrent {
std::ostream& operator<<(std::ostream& out, EpollEventType events) {
if (events == EpollEventType::NONE) {
return out << "NONE";
} else {
int cnt = 0;
for (const auto& event : eventToNameMap()) {
if ((events & std::get<0>(event)) != EpollEventType::NONE) {
if (cnt) {
out << "|";
}
out << std::get<1>(event);
++cnt;
}
}
return out;
}
}
}
}
| [
"ault.tom@gmail.com"
] | ault.tom@gmail.com |
9b89b3931cca6621aa0e2901cc2d08e403988de1 | ad07a5478488e166dfd057db46ef22fb652e6bb1 | /src/BookKeeping.h | bbc009bbf4ce4edff4f4b9ae0d55a7bcd927ea75 | [
"Zlib"
] | permissive | shaobohou/pearley | d51714722c0055a3131f6b04d78ebeb5eb11e4fe | d451c03e9d8465135fb0c4a4cf54408db60b1e3f | refs/heads/master | 2021-01-01T05:51:10.638506 | 2012-05-21T13:21:13 | 2012-05-21T13:21:13 | 3,509,166 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,812 | h | #ifndef BOOKKEEPING
#define BOOKKEEPING
class ParseEntry
{
public:
ParseEntry()
: the_col(static_cast<unsigned int>(-1)), the_row(static_cast<unsigned int>(-1))
{}
ParseEntry(unsigned int col, unsigned int row)
: the_col(col), the_row(row)
{}
unsigned int& row()
{
return the_row;
}
const unsigned int& col() const
{
return the_col;
}
const unsigned int& row() const
{
return the_row;
}
private:
unsigned int the_col, the_row;
};
class Progenitor
{
public:
Progenitor(const ParseEntry &incompleted_index, double weight)
: the_incompleted_index(incompleted_index), the_weight(weight)
{}
Progenitor(const ParseEntry &incompleted_index, const ParseEntry &complete_index)
: the_incompleted_index(incompleted_index), the_complete_index(complete_index), the_weight(0.0)
{}
Progenitor(const ParseEntry &incompleted_index, const ParseEntry &complete_index, double weight)
: the_incompleted_index(incompleted_index), the_complete_index(complete_index), the_weight(weight)
{}
ParseEntry& complete_index()
{
return the_complete_index;
}
const ParseEntry& incompleted_index() const
{
return the_incompleted_index;
}
const ParseEntry& complete_index() const
{
return the_complete_index;
}
const double& weight() const
{
return the_weight;
}
private:
ParseEntry the_incompleted_index, the_complete_index;
double the_weight;
};
typedef std::vector<std::vector<Progenitor> > ProgenitorsLists;
#endif
| [
"shaobohou@c06704c2-2886-2df8-2b27-5efbbc2a7cc3"
] | shaobohou@c06704c2-2886-2df8-2b27-5efbbc2a7cc3 |
a539632454770dbe999b0555f46a77173fee6006 | 1990964ad16e40e560e5796e52725cb395e1e926 | /src/datasets/DataSetClassifier.cpp | 7b3f6f98443cd1c93450e9132568ccebfd9c305a | [] | no_license | tnas/neural-networks | 4775e6337143e0c1e437e6f8142619b94cc6514d | 9ed6d27e9a18c918d715595669ede8756523725f | refs/heads/master | 2020-07-29T03:13:35.919578 | 2019-10-24T18:58:35 | 2019-10-24T18:58:35 | 209,646,799 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,315 | cpp | #include "../../include/datasets/DataSetClassifier.h"
void DataSetClassifier::buildDataMatrix()
{
this->dataMatrix[0][0] = 0;
this->dataMatrix[0][1] = 1;
this->dataMatrix[1][0] = 0;
this->dataMatrix[1][1] = 2;
this->dataMatrix[2][0] = 1;
this->dataMatrix[2][1] = 1;
this->dataMatrix[3][0] = 1;
this->dataMatrix[3][1] = 2;
this->dataMatrix[4][0] = 1;
this->dataMatrix[4][1] = 3;
this->dataMatrix[5][0] = 2;
this->dataMatrix[5][1] = 2;
this->dataMatrix[6][0] = 2;
this->dataMatrix[6][1] = 3;
this->dataMatrix[7][0] = 3;
this->dataMatrix[7][1] = 2;
this->dataMatrix[8][0] = 4;
this->dataMatrix[8][1] = 1;
this->dataMatrix[9][0] = 4;
this->dataMatrix[9][1] = 3;
this->dataMatrix[10][0] = 0;
this->dataMatrix[10][1] = 3;
this->dataMatrix[11][0] = 2;
this->dataMatrix[11][1] = 0;
this->dataMatrix[12][0] = 2;
this->dataMatrix[12][1] = 1;
this->dataMatrix[13][0] = 3;
this->dataMatrix[13][1] = 0;
this->dataMatrix[14][0] = 3;
this->dataMatrix[14][1] = 1;
this->dataMatrix[15][0] = 3;
this->dataMatrix[15][1] = 3;
this->dataMatrix[16][0] = 4;
this->dataMatrix[16][1] = 0;
this->dataMatrix[17][0] = 4;
this->dataMatrix[17][1] = 2;
this->dataMatrix[18][0] = 5;
this->dataMatrix[18][1] = 0;
this->dataMatrix[19][0] = 5;
this->dataMatrix[19][1] = 1;
this->dataMatrix[20][0] = 5;
this->dataMatrix[20][1] = 2;
this->dataMatrix[21][0] = 5;
this->dataMatrix[21][1] = 3;
}
void DataSetClassifier::defineDesiredOutput()
{
this->desiredOutput[0] = 1;
this->desiredOutput[1] = 1;
this->desiredOutput[2] = 1;
this->desiredOutput[3] = 1;
this->desiredOutput[4] = 1;
this->desiredOutput[5] = 1;
this->desiredOutput[6] = 1;
this->desiredOutput[7] = 1;
this->desiredOutput[8] = 1;
this->desiredOutput[9] = 1;
this->desiredOutput[10] = 1;
this->desiredOutput[11] = -1;
this->desiredOutput[12] = -1;
this->desiredOutput[13] = -1;
this->desiredOutput[14] = -1;
this->desiredOutput[15] = -1;
this->desiredOutput[16] = -1;
this->desiredOutput[17] = -1;
this->desiredOutput[18] = -1;
this->desiredOutput[19] = -1;
this->desiredOutput[20] = -1;
this->desiredOutput[21] = -1;
}
| [
"nascimenthiago@gmail.com"
] | nascimenthiago@gmail.com |
f9aceb3a6eaf8a448c3ab4971c6be7a0fcceceb8 | f3b19b04d777eb2f53b35a07d5623337f0023305 | /ngraph/core/include/ngraph/op/util/sub_graph_base.hpp | 0ae39c580967e8dfdad9bb0e11b7a856aed17fd3 | [
"Apache-2.0"
] | permissive | shyransystems/OpenVINO-toolkit-orig | 06804065c23dd86f6564806ae2c92d3d1860c7d1 | 11f591c16852637506b1b40d083b450e56d0c8ac | refs/heads/master | 2023-03-25T03:06:34.577978 | 2021-03-12T14:22:38 | 2021-03-12T14:22:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,412 | hpp | //*****************************************************************************
// Copyright 2017-2021 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.
//*****************************************************************************
#pragma once
#include <ngraph/op/parameter.hpp>
#include "ngraph/op/op.hpp"
namespace ngraph
{
namespace op
{
namespace util
{
/// \brief Abstract base class for sub-graph based ops, i.e ops that have sub-graph
///
class NGRAPH_API SubGraphOp : public Op
{
public:
NGRAPH_RTTI_DECLARATION;
/// \brief Describes a connection between a SubGraphOp input and the body.
class InputDescription
{
protected:
///
/// \brief Constructs a new instance.
///
/// \param input_index Position of the SubGraphOp input
/// \param body_parameter_index Body parameter to receive input
///
InputDescription(uint64_t input_index, uint64_t body_parameter_index);
InputDescription() = default;
public:
using type_info_t = DiscreteTypeInfo;
virtual ~InputDescription() = default;
virtual std::shared_ptr<InputDescription> copy() const = 0;
virtual const type_info_t& get_type_info() const = 0;
uint64_t m_input_index{0};
uint64_t m_body_parameter_index{0};
};
///
/// \brief Describes a body input formed from slices of an input to
/// SubGraphOp.
///
class NGRAPH_API SliceInputDescription : public InputDescription
{
public:
static constexpr type_info_t type_info{"SliceInputDescription", 0};
const type_info_t& get_type_info() const override { return type_info; }
///
/// \brief Constructs a new instance.
///
/// \param input_index Position of the SubGraphOp input
/// \param body_parameter_index Body parameter position to receive input
/// \param start First index for slices
/// \param stride Step amount for slices
/// \param part_size Width of slices
/// \param end Last index for slices
/// \param axis Axis being sliced
///
SliceInputDescription(uint64_t input_index,
uint64_t body_parameter_index,
int64_t start,
int64_t stride,
int64_t part_size,
int64_t end,
int64_t axis);
SliceInputDescription() = default;
std::shared_ptr<InputDescription> copy() const override;
int64_t m_start{0};
int64_t m_stride{0};
int64_t m_part_size{0};
int64_t m_end{0};
int64_t m_axis{0};
};
///
/// \brief Describes a body input initialized from a SubGraphOp input on
/// the first iteration, and then a body output thereafter.
///
class NGRAPH_API MergedInputDescription : public InputDescription
{
public:
static constexpr type_info_t type_info{"MergedInputDescription", 0};
const type_info_t& get_type_info() const override { return type_info; }
///
/// \brief Constructs a new instance.
///
/// \param input_index Position of the SubGraphOp input
/// supplying a value to body_parameter for
/// the initial iteration.
/// \param body_parameter_index Body parameter position to receive input.
/// \param body_value_index Body value to supply body_parameter for
/// successive
/// iterations.
///
MergedInputDescription(uint64_t input_index,
uint64_t body_parameter_index,
uint64_t body_value_index);
MergedInputDescription() = default;
std::shared_ptr<InputDescription> copy() const override;
uint64_t m_body_value_index{0};
};
///
/// \brief Describes a body input initialized from a SubGraphOp input on
/// the first iteration, and invariant thereafter.
///
class NGRAPH_API InvariantInputDescription : public InputDescription
{
public:
static constexpr type_info_t type_info{"InvariantInputDescription", 0};
const type_info_t& get_type_info() const override { return type_info; }
///
/// \brief Constructs a new instance.
///
/// \param input_index Position of the SubGraphOp input
/// \param body_parameter_index Body parameter to receive input
///
InvariantInputDescription(uint64_t input_index, uint64_t body_parameter_index);
InvariantInputDescription() = default;
std::shared_ptr<InputDescription> copy() const override;
};
/// \brief Describes how a SubGraphOp output is produced from the body.
class OutputDescription
{
protected:
///
/// \brief Constructs a new instance.
///
/// \param body_value_index A body value that produces the output
/// \param output_index The SubGraphOp output index
///
OutputDescription(uint64_t body_value_index, uint64_t output_index);
OutputDescription() = default;
public:
using type_info_t = DiscreteTypeInfo;
virtual ~OutputDescription() = default;
virtual std::shared_ptr<OutputDescription> copy() const = 0;
virtual const type_info_t& get_type_info() const = 0;
uint64_t m_body_value_index{0};
uint64_t m_output_index{0};
};
/// \brief Produces an output by concatenating an output from each iteration
class NGRAPH_API ConcatOutputDescription : public OutputDescription
{
public:
static constexpr type_info_t type_info{"ConcatOutputDescription", 0};
const type_info_t& get_type_info() const override { return type_info; }
///
/// \brief Constructs a new instance.
///
/// \param body_value_index A body value that produces the output
/// \param output_index The SubGraphOp output index
/// \param start First index for slices
/// \param stride Step amount for slices
/// \param part_size Width of slices
/// \param end Last index for slices
/// \param axis Axis being sliced
///
ConcatOutputDescription(uint64_t body_value_index,
uint64_t output_index,
int64_t start,
int64_t stride,
int64_t part_size,
int64_t end,
int64_t axis);
ConcatOutputDescription() = default;
std::shared_ptr<OutputDescription> copy() const override;
int64_t m_start{0};
int64_t m_stride{0};
int64_t m_part_size{0};
int64_t m_end{0};
int64_t m_axis{0};
};
/// \brief Produces an output from a specific iteration
class NGRAPH_API BodyOutputDescription : public OutputDescription
{
public:
static constexpr type_info_t type_info{"BodyOutputDescription", 0};
const type_info_t& get_type_info() const override { return type_info; }
///
/// \brief Constructs a new instance.
///
/// \param body_value_index A body value that produces the output
/// \param output_index The SubGraphOp output index
/// \param iteration which iteration (typically -1, final) will
/// supply the value
///
BodyOutputDescription(uint64_t body_value_index,
uint64_t output_index,
int64_t iteration);
BodyOutputDescription() = default;
std::shared_ptr<OutputDescription> copy() const override;
int64_t m_iteration{0};
};
virtual std::shared_ptr<Function> get_function() { return m_body; };
virtual std::shared_ptr<const Function> get_function() const { return m_body; };
virtual void set_function(const std::shared_ptr<Function>& func) { m_body = func; };
/// \return a reference to the input descriptions.
const std::vector<std::shared_ptr<InputDescription>>& get_input_descriptions() const
{
return m_input_descriptions;
}
/// \return a reference to the input descriptions. Can add input descriptions
/// before
/// validation.
std::vector<std::shared_ptr<InputDescription>>& get_input_descriptions()
{
return m_input_descriptions;
}
/// \return a reference to the output descriptions.
const std::vector<std::shared_ptr<OutputDescription>>&
get_output_descriptions() const
{
return m_output_descriptions;
}
/// \return a reference to the output descriptions. Can add output descriptions
/// before
/// validation.
std::vector<std::shared_ptr<OutputDescription>>& get_output_descriptions()
{
return m_output_descriptions;
}
///
/// \brief Indicate that a body parameter comes from slices of a value
///
/// \param parameter The parameter to receive the slices
/// \param value The value to be sliced. This will be added as an input to
/// SubGraphOp.
/// \param start First index on axis of the slicing
/// \param stride Stepping of the slice
/// \param part_size Size of the slice on axis
/// \param end The last index on axis of the slicing
/// \param axis The axis to slice along
///
virtual void set_sliced_input(const std::shared_ptr<Parameter>& parameter,
const Output<Node>& value,
int64_t start,
int64_t stride,
int64_t part_size,
int64_t end,
int64_t axis);
///
/// \brief Indicates that a body parameter has an initial value in the first
/// iteration and computed value thereafter
///
/// \param[in] body_parameter The body parameter
/// \param initial_value Value for the parameter in first iteration. This
/// will be added as an input to Loop.
/// \param successive_value Value for the parameter in successive iterations.
/// The value is what is active in the most recent
/// completed iteration.
///
virtual void set_merged_input(const std::shared_ptr<Parameter>& body_parameter,
const Output<Node>& initial_value,
const Output<Node>& successive_value);
///
/// \brief Indicates that a body parameter has an invariant value during
/// iteration that may depend on values computed outside of the
/// iteration.
///
/// \param body_parameter The body parameter
/// \param value The value supplied as an input to the block
///
virtual void set_invariant_input(const std::shared_ptr<Parameter>& body_parameter,
const Output<Node>& value);
///
/// \brief Gets a value for a particular iteration point
///
/// \param body_value The value
/// \param iteration The iteration that supplies the value. Negative values
/// are from the last iteration.
/// Default value -1 (the last iteration).
///
/// \return The iterator value.
///
virtual Output<Node> get_iter_value(const Output<Node>& body_value,
int64_t iteration = -1);
///
/// \brief Concatenates slices from all iterations
///
/// \param value The value supplying slice values from each iteration.
/// \param start First index on axis of the slicing
/// \param stride Stepping of the slice
/// \param part_size Size of the slice on axis
/// \param end The last index on axis of the slicing
/// \param axis The axis to slice along
///
/// \return The concatenated slices.
///
virtual Output<Node> get_concatenated_slices(const Output<Node>& value,
int64_t start,
int64_t stride,
int64_t part_size,
int64_t end,
int64_t axis);
SubGraphOp(const SubGraphOp&) = delete;
SubGraphOp(SubGraphOp&&) = default;
SubGraphOp& operator=(const SubGraphOp&) = delete;
SubGraphOp& operator=(SubGraphOp&&) = default;
int64_t get_num_iterations() const { return m_num_iterations; }
protected:
int64_t m_num_iterations =
-1; // -1 means infinity for Loop op, inconsistent for TensorIterator
// Find an input corresponding to value, adding one if necessary.
Input<Node> input_for_value(const Output<Node>& value);
SubGraphOp() = default;
explicit SubGraphOp(const OutputVector& args);
std::shared_ptr<Function> m_body;
std::vector<std::shared_ptr<op::util::SubGraphOp::InputDescription>>
m_input_descriptions;
std::vector<std::shared_ptr<op::util::SubGraphOp::OutputDescription>>
m_output_descriptions;
};
using InputDescriptionPtr = std::shared_ptr<util::SubGraphOp::InputDescription>;
using OutputDescriptionPtr = std::shared_ptr<util::SubGraphOp::OutputDescription>;
using InputDescriptionVector = std::vector<InputDescriptionPtr>;
using OutputDescriptionVector = std::vector<OutputDescriptionPtr>;
}
}
template <>
class NGRAPH_API AttributeAdapter<
std::vector<std::shared_ptr<ngraph::op::util::SubGraphOp::InputDescription>>>
: public DirectValueAccessor<
std::vector<std::shared_ptr<ngraph::op::util::SubGraphOp::InputDescription>>>
{
public:
AttributeAdapter(
std::vector<std::shared_ptr<ngraph::op::util::SubGraphOp::InputDescription>>& value)
: DirectValueAccessor<
std::vector<std::shared_ptr<ngraph::op::util::SubGraphOp::InputDescription>>>(
value)
{
}
static constexpr DiscreteTypeInfo type_info{
"AttributeAdapter<std::vector<std::shared_ptr<ngraph::op::util::SubGraphOp::"
"InputDescription>>>",
0};
const DiscreteTypeInfo& get_type_info() const override { return type_info; }
};
template <>
class NGRAPH_API AttributeAdapter<
std::vector<std::shared_ptr<ngraph::op::util::SubGraphOp::OutputDescription>>>
: public DirectValueAccessor<
std::vector<std::shared_ptr<ngraph::op::util::SubGraphOp::OutputDescription>>>
{
public:
AttributeAdapter(
std::vector<std::shared_ptr<ngraph::op::util::SubGraphOp::OutputDescription>>& value)
: DirectValueAccessor<
std::vector<std::shared_ptr<ngraph::op::util::SubGraphOp::OutputDescription>>>(
value)
{
}
static constexpr DiscreteTypeInfo type_info{
"AttributeAdapter<std::vector<std::shared_ptr<ngraph::op::util::SubGraphOp::"
"OutputDescription>>>",
0};
const DiscreteTypeInfo& get_type_info() const override { return type_info; }
};
}
| [
"noreply@github.com"
] | shyransystems.noreply@github.com |
bc253f95d204a419e9e65a867abab6c08aac4a1d | 2b7ca25e4fba0ce04104987328f28dd6c2b4195e | /2018-2019/sem06/05_class_templ.cpp | 9bff485e3d29441a9d42befe145ee15022ca3018 | [] | no_license | blackav/cmc-cpp-seminars | 7da500782901115cfc4f808b8ad367d126ea3879 | 48c94bb340e98c3856a4f0ea8267fafd73ae318d | refs/heads/master | 2023-04-30T05:16:17.788261 | 2023-04-15T03:37:48 | 2023-04-15T03:37:48 | 53,767,957 | 18 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 443 | cpp | template<typename T>
struct is_int
{
static constexpr auto value = false;
};
template<>
struct is_int<int>
{
static constexpr auto value = true;
};
#include <iostream>
using namespace std;
int main()
{
cout << is_int<double>::value << endl;
cout << is_int<int>::value << endl;
int x = 10;
static_assert(is_int<decltype(x)>::value);
if constexpr(is_int<decltype(x)>::value) {
cout << x << endl;
}
}
| [
"blackav@gmail.com"
] | blackav@gmail.com |
cd52a0f7c0eaca90bc84c9cd5cf20a9753ed8601 | 892a394660d04682b486792f6850146113b34db6 | /uncharted-client/UnchartedClient/Input.cpp | 50663f353cda8dae755e7a82e98df7ce498acc47 | [] | no_license | inhibitor1217/Direct3D-tutorial | d2ef49d7f0270185bf3d31d90821f3a7f7589e28 | 37668a7c61960b95d14c7920b088d43d988e7a13 | refs/heads/master | 2020-04-11T13:35:33.982227 | 2019-01-18T04:14:28 | 2019-01-18T04:14:28 | 161,822,738 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,521 | cpp | #include "Input.h"
Input::Input()
{
}
Input::Input(const Input &other)
{
}
Input::~Input()
{
}
bool Input::Init(HINSTANCE hInstance, HWND hwnd, int screenWidth, int screenHeight)
{
for (int i = 0; i < 256; i++) {
m_keyboardState[i] = false;
}
m_screenWidth = screenWidth;
m_screenHeight = screenHeight;
if (FAILED(DirectInput8Create(hInstance, DIRECTINPUT_VERSION, IID_IDirectInput8, reinterpret_cast<void **>(&m_pDirectInput), NULL)))
return false;
if(FAILED(m_pDirectInput->CreateDevice(GUID_SysKeyboard, &m_pKeyboard, NULL)))
return false;
if (FAILED(m_pKeyboard->SetDataFormat(&c_dfDIKeyboard)))
return false;
if (FAILED(m_pKeyboard->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_EXCLUSIVE)))
return false;
if (FAILED(m_pKeyboard->Acquire()))
return false;
if (FAILED(m_pDirectInput->CreateDevice(GUID_SysMouse, &m_pMouse, NULL)))
return false;
if (FAILED(m_pMouse->SetDataFormat(&c_dfDIMouse)))
return false;
if (FAILED(m_pMouse->SetCooperativeLevel(hwnd, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE)))
return false;
if (FAILED(m_pMouse->Acquire()))
return false;
return true;
}
void Input::Shutdown()
{
if (m_pMouse) {
m_pMouse->Unacquire();
Memory::SafeRelease(m_pMouse);
}
if (m_pKeyboard) {
m_pKeyboard->Unacquire();
Memory::SafeRelease(m_pKeyboard);
}
Memory::SafeRelease(m_pDirectInput);
}
bool Input::Frame()
{
if (!ReadKeyboard())
return false;
if (!ReadMouse())
return false;
ProcessInput();
return true;
}
void Input::GetMouse(int &x, int &y)
{
x = m_mouseX;
y = m_mouseY;
}
bool Input::IsKeyDown(UINT key)
{
return m_keyboardState[key];
}
bool Input::ReadKeyboard()
{
HRESULT result;
if (FAILED(result = m_pKeyboard->GetDeviceState(sizeof(m_keyboardState), reinterpret_cast<void *>(&m_keyboardState)))) {
if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED)
m_pKeyboard->Acquire();
else
return false;
}
return true;
}
bool Input::ReadMouse()
{
HRESULT result;
if (FAILED(result = m_pMouse->GetDeviceState(sizeof(DIMOUSESTATE), reinterpret_cast<void *>(&m_mouseState)))) {
if (result == DIERR_INPUTLOST || result == DIERR_NOTACQUIRED)
m_pMouse->Acquire();
else
return false;
}
return true;
}
void Input::ProcessInput()
{
m_mouseX += m_mouseState.lX;
m_mouseY += m_mouseState.lY;
if (m_mouseX < 0)
m_mouseX = 0;
if (m_mouseX > m_screenWidth)
m_mouseX = m_screenWidth;
if (m_mouseY < 0)
m_mouseY = 0;
if (m_mouseY > m_screenHeight)
m_mouseY = m_screenHeight;
} | [
"cytops1217@gmail.com"
] | cytops1217@gmail.com |
e6f481e76204dc3913615119602e8689fa5e61c6 | 0f527eb8d84d99f9dba8ee9e7d34d9062434d03b | /Convert/Convert/Src/BSPHandler.h | 63a9f290832224c2dcd37255399a3a3db576c393 | [] | no_license | weichx/pof_to_dae | 50212d519a3b70252b8bae21155c96f10f5c6339 | 38b3f81b4e892e4cd2fe65f66de38fc979c3c6ef | refs/heads/master | 2016-09-06T09:26:55.390228 | 2015-06-29T04:03:07 | 2015-06-29T04:03:07 | 38,220,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,682 | h | #include "BSPDataStructs.h"
#include <ios>
#if !defined(_BSP_HANDLER_H_)
#define _BSP_HANDLER_H_
class BSP
{
public:
std::vector<BSP_BoundBox> bounders;
std::vector<BSP_DefPoints> points;
std::vector<BSP_FlatPoly> fpolys;
std::vector<BSP_SortNorm> snorms;
std::vector<BSP_TmapPoly> tpolys;
int numbounders, numpoints, numfpolys, numsnorms, numtpolys;
void Clear()
{
bounders.clear();
points.clear();
fpolys.clear();
snorms.clear();
tpolys.clear();
}
BSP()
{
Clear();
}
BSP(char *buffer, int size)
{
Clear();
DataIn(buffer, size);
}
//~BSP();
//--------------------------------
std::string DataIn(char *buffer, int size);
std::ostream& BSPDump(std::ostream &os); // dumps human readable BSP information into ostream;
int Count_Bounding()
{
return bounders.size();
}
int Count_Points()
{
return points.size();
}
int Count_FlatPolys()
{
return fpolys.size();
}
int Count_SortNorms()
{
return snorms.size();
}
int Count_TmapPolys()
{
return tpolys.size();
}
//--------------------------------
void Add_BoundBox(BSP_BoundBox bound);
bool Del_BoundBox(int index);
void Add_DefPoints(BSP_DefPoints pnts);
bool Del_DefPoints(int index);
void Add_FlatPoly(BSP_FlatPoly fpol);
bool Del_FlatPoly(int index);
void Add_SortNorm(BSP_SortNorm sn);
bool Del_SortNorm(int index);
void Add_TmapPoly(BSP_TmapPoly tpol);
bool Del_TmapPoly(int index);
};
std::ostream& operator<<(std::ostream &os, BSP_TmapPoly tpoly);
std::ostream& operator<<(std::ostream &os, BSP_FlatPoly fpoly);
bool operator==(BSP_TmapPoly &a, BSP_TmapPoly &b);
bool operator==(BSP_FlatPoly &a, BSP_FlatPoly &b);
#endif //_BSP_HANDLER_H_
| [
"matthew.weichselbaum@gmail.com"
] | matthew.weichselbaum@gmail.com |
37dd0de3ead170c8a563d05c7e26cdfef21f9d22 | 083100943aa21e05d2eb0ad745349331dd35239a | /aws-cpp-sdk-iam/include/aws/iam/model/GetPolicyVersionResult.h | 3618f23ea1b4485bee601b346f0cbeae79cc4afc | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | bmildner/aws-sdk-cpp | d853faf39ab001b2878de57aa7ba132579d1dcd2 | 983be395fdff4ec944b3bcfcd6ead6b4510b2991 | refs/heads/master | 2021-01-15T16:52:31.496867 | 2015-09-10T06:57:18 | 2015-09-10T06:57:18 | 41,954,994 | 1 | 0 | null | 2015-09-05T08:57:22 | 2015-09-05T08:57:22 | null | UTF-8 | C++ | false | false | 3,946 | h | /*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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.
*/
#pragma once
#include <aws/iam/IAM_EXPORTS.h>
#include <aws/iam/model/PolicyVersion.h>
#include <aws/iam/model/ResponseMetadata.h>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Xml
{
class XmlDocument;
} // namespace Xml
} // namespace Utils
namespace IAM
{
namespace Model
{
/*
<p>Contains the response to a successful <a>GetPolicyVersion</a> request. </p>
*/
class AWS_IAM_API GetPolicyVersionResult
{
public:
GetPolicyVersionResult();
GetPolicyVersionResult(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
GetPolicyVersionResult& operator=(const AmazonWebServiceResult<Aws::Utils::Xml::XmlDocument>& result);
/*
<p>Information about the policy version.</p> <p>For more information about managed policy versions, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html">Versioning for Managed Policies</a> in the <i>Using IAM</i> guide. </p>
*/
inline const PolicyVersion& GetPolicyVersion() const{ return m_policyVersion; }
/*
<p>Information about the policy version.</p> <p>For more information about managed policy versions, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html">Versioning for Managed Policies</a> in the <i>Using IAM</i> guide. </p>
*/
inline void SetPolicyVersion(const PolicyVersion& value) { m_policyVersion = value; }
/*
<p>Information about the policy version.</p> <p>For more information about managed policy versions, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html">Versioning for Managed Policies</a> in the <i>Using IAM</i> guide. </p>
*/
inline void SetPolicyVersion(PolicyVersion&& value) { m_policyVersion = value; }
/*
<p>Information about the policy version.</p> <p>For more information about managed policy versions, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html">Versioning for Managed Policies</a> in the <i>Using IAM</i> guide. </p>
*/
inline GetPolicyVersionResult& WithPolicyVersion(const PolicyVersion& value) { SetPolicyVersion(value); return *this;}
/*
<p>Information about the policy version.</p> <p>For more information about managed policy versions, see <a href="http://docs.aws.amazon.com/IAM/latest/UserGuide/policies-managed-versions.html">Versioning for Managed Policies</a> in the <i>Using IAM</i> guide. </p>
*/
inline GetPolicyVersionResult& WithPolicyVersion(PolicyVersion&& value) { SetPolicyVersion(value); return *this;}
inline const ResponseMetadata& GetResponseMetadata() const{ return m_responseMetadata; }
inline void SetResponseMetadata(const ResponseMetadata& value) { m_responseMetadata = value; }
inline void SetResponseMetadata(ResponseMetadata&& value) { m_responseMetadata = value; }
inline GetPolicyVersionResult& WithResponseMetadata(const ResponseMetadata& value) { SetResponseMetadata(value); return *this;}
inline GetPolicyVersionResult& WithResponseMetadata(ResponseMetadata&& value) { SetResponseMetadata(value); return *this;}
private:
PolicyVersion m_policyVersion;
ResponseMetadata m_responseMetadata;
};
} // namespace Model
} // namespace IAM
} // namespace Aws | [
"henso@amazon.com"
] | henso@amazon.com |
feaf53f3f38334a2fa6380792c126afbc5009595 | f4e5d2bde7171e0e9ccc4592cf66147de9a06f67 | /OGFLoader.h | b51c672168c77c7bf316cfc12fbc78f2af42ea72 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | mortany/OGFViewer | 585b48883e8036bffb35d7cbd670cb77a2af5592 | 35d380eaafd9bd1481f2da68349eca80cc00ed25 | refs/heads/master | 2021-10-19T14:32:47.360825 | 2019-02-21T19:49:57 | 2019-02-21T19:56:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 753 | h | #pragma once
#include "OGFModel.h"
struct Chunk2564
{
int header[3]; //1 44 2564
float info[10]; //data chunk
};
struct Chunk1284
{
int header[3]; //1 44 284
char data[40];
};
struct OGFHeader
{
int count;
int size;
char modelname[1024];
int hz1; //9
int pos1;
int hz2; //1638
int pos2;
int hz3; //0
int pos3;
int hz4; //1630
int pos4;
};
struct Bone
{
int id;
char bone[8192];
};
struct structF
{
int f[2];
};
struct TextData
{
int type;
int size;
char data[1024];
};
struct Indices
{
int count;
unsigned short *idx;
};
struct OGFVertex
{
float x,y,z;
float t1,t2;
float aa;
char flag;
float t[2];
float b[2];
float s[2];
float d[2];
};
OGFModel *Load(char *fileName,const std::string &pathToTextures); | [
"dmitrysafronov1996@gmail.com"
] | dmitrysafronov1996@gmail.com |
938b9a5384ad75f399c62be573d118e86ee5d15b | c971f2bb3a0a547daedfdc637c9be4a6ed63be29 | /environmental/main.cpp | 85768f670a84d0d1d06d511b7925e7914509fbfe | [
"BSD-3-Clause"
] | permissive | eric33440/project_connect | fc6ab5ee97844d1879289c638713887318553db1 | 531dd94d22b8af83d0837f1c73c492ea0ac341dd | refs/heads/master | 2020-12-20T04:53:41.446443 | 2019-12-14T09:00:15 | 2019-12-14T09:00:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 482 | cpp | /**
* @file main.cpp
* @author Eric Rebillon (eric.rebillon@ynov.com)
* @brief
* @version 0.1
* @date 2019-11-29
*
* @copyright Copyright (c) 2019
*
*/
#include <QCoreApplication>
#include <QObject>
#include "Sensor.h"
/**
* @brief main
* @param argc
* @param argv
* @return
* call the class contains the both class
*/
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
Sensor *sensor = new Sensor();
Q_UNUSED(sensor)
a.exec();
}
| [
"offougajoris@gmail.com"
] | offougajoris@gmail.com |
4be381803c1e27e1848e59c4b612f93092e82185 | be4737ec5e569506a3beea5cdfedafdd778e32e1 | /secondmaximum.cpp | abe1f70de3483272e273778742a40ba78411cbaf | [] | no_license | Samykakkar/DSA-practice | 8fd49c690f9c6af56437cb09475e7796538df77b | d10938f34e9467688f178b6570ccc740d3cc4dff | refs/heads/master | 2023-07-24T22:10:26.953125 | 2021-09-06T09:26:00 | 2021-09-06T09:26:00 | 392,998,137 | 0 | 1 | null | 2021-08-13T10:46:25 | 2021-08-05T10:21:28 | C++ | UTF-8 | C++ | false | false | 727 | cpp | #include <iostream>
#include<vector>
using namespace std;
vector<int> largestandsecondlargest(int sizeofarray, int arr[])
{
int max= INT_MIN , max2=INT_MIN;
for(int i=0;i<sizeofarray;i++)
{
if(arr[i]>max)
{
max2=max;
max=arr[i];
}
else if(arr[i]>max2 && arr[i]!=max)
{
max2=arr[i];
}
}
if(max2==INT_MIN)
{
max2=-1;
}
vector<int> temp(2);
temp[0]=max;
temp[1]=max2;
return temp;
}
int main()
{
std::vector<int> arr[]={2,3,5,3,5};
int n= sizeof(arr)/sizeof(arr[0]);
cout<<"Largest and second largest are"<<" "<<largestandsecondlargest(n, arr)<<endl;
return 0;
} | [
"sam8377984375@gmail.com"
] | sam8377984375@gmail.com |
d9b62a95dead57b38aac2cb4ef7da6bc5903750e | 59c94d223c8e1eb1720d608b9fc040af22f09e3a | /garnet/bin/run_test_component/run_test_component.cc | 4cf09e53e5cdee8d008d01abadd7fa6b154fdc39 | [
"BSD-3-Clause"
] | permissive | bootingman/fuchsia2 | 67f527712e505c4dca000a9d54d3be1a4def3afa | 04012f0aa1edd1d4108a2ac647a65e59730fc4c2 | refs/heads/master | 2022-12-25T20:28:37.134803 | 2019-05-14T08:26:08 | 2019-05-14T08:26:08 | 186,606,695 | 1 | 1 | BSD-3-Clause | 2022-12-16T21:17:16 | 2019-05-14T11:17:16 | C++ | UTF-8 | C++ | false | false | 3,219 | cc | // Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "garnet/bin/run_test_component/run_test_component.h"
#include <fuchsia/sys/index/cpp/fidl.h>
#include <glob.h>
#include <lib/fit/defer.h>
#include <lib/sys/cpp/service_directory.h>
#include <regex>
#include <string>
#include "src/lib/fxl/strings/string_printf.h"
#include "src/lib/pkg_url/fuchsia_pkg_url.h"
namespace run {
using fuchsia::sys::index::ComponentIndex_FuzzySearch_Result;
using fuchsia::sys::index::ComponentIndexSyncPtr;
static constexpr char kComponentIndexerUrl[] =
"fuchsia-pkg://fuchsia.com/component_index#meta/component_index.cmx";
ParseArgsResult ParseArgs(
const std::shared_ptr<sys::ServiceDirectory>& services, int argc,
const char** argv) {
ParseArgsResult result;
result.error = false;
if (argc < 2) {
result.error = true;
result.error_msg = "Pass atleast one argument";
return result;
}
std::string url = argv[1];
if (!component::FuchsiaPkgUrl::IsFuchsiaPkgScheme(url)) {
fuchsia::sys::LaunchInfo index_launch_info;
index_launch_info.url = kComponentIndexerUrl;
auto index_provider = sys::ServiceDirectory::CreateWithRequest(
&index_launch_info.directory_request);
// Connect to the Launcher service through our static environment.
fuchsia::sys::LauncherSyncPtr launcher;
services->Connect(launcher.NewRequest());
fuchsia::sys::ComponentControllerPtr component_index_controller;
launcher->CreateComponent(std::move(index_launch_info),
component_index_controller.NewRequest());
ComponentIndexSyncPtr index;
index_provider->Connect(index.NewRequest());
std::string test_name = argv[1];
ComponentIndex_FuzzySearch_Result fuzzy_search_result;
zx_status_t status = index->FuzzySearch(test_name, &fuzzy_search_result);
if (status != ZX_OK) {
result.error = true;
result.error_msg = fxl::StringPrintf(
"\"%s\" is not a valid URL. Attempted to match to a URL with "
"fuchsia.sys.index.FuzzySearch, but the service is not available.",
test_name.c_str());
return result;
}
if (fuzzy_search_result.is_err()) {
result.error = true;
result.error_msg = fxl::StringPrintf(
"\"%s\" contains unsupported characters for fuzzy "
"matching. Valid characters are [A-Z a-z 0-9 / _ - .].\n",
test_name.c_str());
return result;
} else {
std::vector<std::string> uris = fuzzy_search_result.response().uris;
if (uris.size() == 0) {
result.error = true;
result.error_msg = fxl::StringPrintf(
"\"%s\" did not match any components.\n", test_name.c_str());
return result;
} else {
for (auto& uri : uris) {
result.matching_urls.push_back(uri);
}
if (uris.size() > 1) {
return result;
}
url = uris[0];
}
}
}
result.launch_info.url = url;
for (int i = 2; i < argc; i++) {
result.launch_info.arguments.push_back(argv[i]);
}
return result;
}
} // namespace run
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
37d5f5f58871b05bb935ef014ffd18a70321f464 | 2786713e782199d177dafe6d4d23b524533cf9e4 | /Source code/FilterDl.cpp | 291418a8b25c4cade8716564d8b036e16e074d9f | [] | no_license | AgachilyPaul/Sniffer | d22187d15a34480a0935b31866bc259e1f71c4fe | 72619db385cc0307da6dc0ae388c7988d2e25f62 | refs/heads/master | 2023-01-07T20:05:41.476282 | 2020-11-06T12:24:07 | 2020-11-06T12:24:07 | 289,703,302 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,785 | cpp | // FilterDl.cpp : implementation file
//
#include "stdafx.h"
#include "CapturePacket.h"
#include "FilterDl.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CFilterDl dialog
CFilterDl::CFilterDl(CWnd* pParent /*=NULL*/)
: CDialog(CFilterDl::IDD, pParent)
{
//{{AFX_DATA_INIT(CFilterDl)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
void CFilterDl::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CFilterDl)
DDX_Control(pDX, IDC_TAB_CTR, m_tCtr);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CFilterDl, CDialog)
//{{AFX_MSG_MAP(CFilterDl)
ON_NOTIFY(TCN_SELCHANGE, IDC_TAB_CTR, OnSelchangeTabCtr)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CFilterDl message handlers
BOOL CFilterDl::OnInitDialog()
{
CDialog::OnInitDialog();
// TODO: Add extra initialization here
TCITEM item;
item.mask = TCIF_TEXT;
item.pszText = "µÚÒ»Ò³";
m_tCtr.InsertItem (0,&item);
item.pszText ="µÚ¶þÒ³";
m_tCtr.InsertItem (1,&item);
m_dlg1.Create (IDD_ABOUTBOX,&m_tCtr);
m_dlg2.Create (IDD_DIALOG_OUTPUTDATA,&m_tCtr);
m_dlg1.SetWindowPos (NULL,10,30,400,100,SWP_SHOWWINDOW);
m_dlg2.SetWindowPos (NULL,10,30,400,100,SWP_HIDEWINDOW );
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CFilterDl::OnSelchangeTabCtr(NMHDR* pNMHDR, LRESULT* pResult)
{
// TODO: Add your control notification handler code here
*pResult = 0;
}
| [
"noreply@github.com"
] | AgachilyPaul.noreply@github.com |
8e27382a945eefbdcc9852a9a0b672a732f72453 | 7046a5f8618ec6b3b015d03e68e2f4b7b7090288 | /3DAugmentation/Ferns/RealFerns/affine_image_generator06.cc | 2ede4e8528d777491a79e12fbcf9562af5af8836 | [] | no_license | dmaulikr/3DAugmentation | ca48bbb2dddcdd5fe1766c357595cbeba76b8292 | fc41bd799e81c387720f5870d1b1418691050b9a | refs/heads/master | 2021-01-01T19:36:15.639180 | 2013-06-19T10:09:35 | 2013-06-19T10:09:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,583 | cc | /*
Copyright 2007 Computer Vision Lab,
Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland.
All rights reserved.
Author: Vincent Lepetit (http://cvlab.epfl.ch/~lepetit)
This file is part of the ferns_demo software.
ferns_demo is free software; you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software
Foundation; either version 2 of the License, or (at your option) any later
version.
ferns_demo is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with
ferns_demo; if not, write to the Free Software Foundation, Inc., 51 Franklin
Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include <stdlib.h>
#include <math.h>
#include <iostream>
using namespace std;
#include "general.h"
#include "mcv.h"
#include "affine_image_generator06.h"
static const int prime = 307189;
affine_image_generator06::affine_image_generator06(void)
{
original_image = 0;
generated_image = 0;
original_image_with_128_as_background = 0;
white_noise = new char[prime];
limited_white_noise = new int[prime];
set_default_values();
save_images = false;
}
affine_image_generator06::~affine_image_generator06(void)
{
if (original_image != 0) cvReleaseImage(&original_image);
if (generated_image != 0) cvReleaseImage(&generated_image);
if (original_image_with_128_as_background) cvReleaseImage(&original_image_with_128_as_background);
delete [] white_noise;
delete [] limited_white_noise;
}
void affine_image_generator06::load_transformation_range(ifstream & f)
{
transformation_range.load(f);
}
void affine_image_generator06::save_transformation_range(ofstream & f)
{
transformation_range.save(f);
}
void affine_image_generator06::set_transformation_range(affine_transformation_range * range)
{
transformation_range = *range;
}
void affine_image_generator06::generate_Id_image(void)
{
generate_Id_affine_transformation();
generate_affine_image();
}
void affine_image_generator06::generate_random_affine_image(void)
{
generate_random_affine_transformation();
generate_affine_image();
}
void affine_image_generator06::save_generated_images(char * generic_name)
{
save_images = true;
strcpy(generic_name_of_saved_images, generic_name);
}
void affine_image_generator06::set_default_values(void)
{
set_noise_level(20);
set_use_random_background(true);
set_add_gaussian_smoothing(true);
set_change_intensities(true);
add_noise = true;
}
void affine_image_generator06::set_noise_level(int noise_level)
{
this->noise_level = noise_level;
index_white_noise = 0;
for(int i = 0; i < prime; i++) {
limited_white_noise[i] = rand() % (2 * noise_level) - noise_level;
white_noise[i] = char(rand() % 256);
}
}
void affine_image_generator06::set_original_image(IplImage * p_original_image,
int generated_image_width,
int generated_image_height)
{
if (original_image != 0) cvReleaseImage(&original_image);
original_image = cvCloneImage(p_original_image);
if (generated_image != 0) cvReleaseImage(&generated_image);
if (generated_image_width < 0)
generated_image = cvCloneImage(p_original_image);
else
generated_image = cvCreateImage(cvSize(generated_image_width, generated_image_height), IPL_DEPTH_8U, 1);
if (original_image_with_128_as_background != 0) cvReleaseImage(&original_image_with_128_as_background);
original_image_with_128_as_background = cvCloneImage(p_original_image);
mcvReplace(original_image_with_128_as_background, 128, int(127));
}
void affine_image_generator06::set_mask(int x_min, int y_min, int x_max, int y_max)
{
for(int v = 0; v < original_image_with_128_as_background->height; v++) {
unsigned char * row = mcvRow(original_image_with_128_as_background, v, unsigned char);
for(int u = 0; u < original_image_with_128_as_background->width; u++)
if (u < x_min || u > x_max || v < y_min || v > y_max)
row[u] = 128;
}
}
void affine_image_generator06::generate_affine_transformation(float a[6],
float initialTx, float initialTy,
float theta, float phi,
float lambda1, float lambda2,
float finalTx, float finalTy)
{
float t1 = cos(theta);
float t2 = cos(phi);
float t4 = sin(theta);
float t5 = sin(phi);
float t7 = t1 * t2 + t4 * t5;
float t8 = t7 * lambda1;
float t12 = t1 * t5 - t4 * t2;
float t13 = t12 * lambda2;
float t15 = t8 * t2 + t13 * t5;
float t18 = -t8 * t5 + t13 * t2;
float t22 = -t12 * lambda1;
float t24 = t7 * lambda2;
float t26 = t22 * t2 + t24 * t5;
float t29 = -t22 * t5 + t24 * t2;
a[0] = t15;
a[1] = t18;
a[2] = t15 * initialTx + t18 * initialTy + finalTx;
a[3] = t26;
a[4] = t29;
a[5] = t26 * initialTx + t29 * initialTy + finalTy;
}
void affine_image_generator06::generate_random_affine_transformation(void)
{
float theta, phi, lambda1, lambda2;
transformation_range.generate_random_parameters(theta, phi, lambda1, lambda2);
generate_affine_transformation(a, 0, 0, theta, phi, lambda1, lambda2, 0, 0);
int Tx, Ty;
float nu0, nv0, nu1, nv1, nu2, nv2, nu3, nv3;
affine_transformation(0., 0., nu0, nv0);
affine_transformation(float(original_image->width), 0., nu1, nv1);
affine_transformation(float(original_image->width), float(original_image->height), nu2, nv2);
affine_transformation(0., float(original_image->height), nu3, nv3);
if (rand() % 2 == 0) Tx = -(int)min(min(nu0, nu1), min(nu2, nu3));
else Tx = generated_image->width - (int)max(max(nu0, nu1), max(nu2, nu3));
if (rand() % 2 == 0) Ty = -(int)min(min(nv0, nv1), min(nv2, nv3));
else Ty = generated_image->height - (int)max(max(nv0, nv1), max(nv2, nv3));
generate_affine_transformation(a, 0., 0., theta, phi, lambda1, lambda2, float(Tx), float(Ty));
}
void affine_image_generator06::generate_Id_affine_transformation(void)
{
generate_affine_transformation(a, 0, 0 , 0, 0, 1, 1, 0, 0);
}
void affine_image_generator06::affine_transformation(float p_a[6],
float u, float v,
float & nu, float & nv)
{
nu = u * p_a[0] + v * p_a[1] + p_a[2];
nv = u * p_a[3] + v * p_a[4] + p_a[5];
}
void affine_image_generator06::inverse_affine_transformation(float p_a[6],
float u, float v,
float & nu, float & nv)
{
float det = p_a[0] * p_a[4] - p_a[3] * p_a[1];
nu = 1.f / det * ( p_a[4] * (u - p_a[2]) - p_a[1] * (v - p_a[5]));
nv = 1.f / det * (-p_a[3] * (u - p_a[2]) + p_a[0] * (v - p_a[5]));
}
void affine_image_generator06::affine_transformation(float u, float v, float & nu, float & nv)
{
affine_transformation(a, u, v, nu, nv);
}
void affine_image_generator06::inverse_affine_transformation(float u, float v, float & nu, float & nv)
{
inverse_affine_transformation(a, u, v, nu, nv);
}
void affine_image_generator06::add_white_noise(IplImage * image, int gray_level_to_avoid)
{
for(int y = 0; y < image->height; y++) {
unsigned char * line = (unsigned char *)(image->imageData + y * image->widthStep);
int * noise = limited_white_noise + rand() % (prime - image->width);
for(int x = 0; x < image->width; x++) {
int p = int(*line);
if (p != gray_level_to_avoid) {
p += *noise;
*line = (p > 255) ? 255 : (p < 0) ? 0 : (unsigned char)p;
}
line++;
noise++;
}
}
}
void affine_image_generator06::replace_by_noise(IplImage * image, int value)
{
for(int y = 0; y < image->height; y++) {
unsigned char * row = mcvRow(image, y, unsigned char);
for(int x = 0; x < image->width; x++)
if (int(row[x]) == value) {
row[x] = white_noise[index_white_noise];
index_white_noise++;
if (index_white_noise >= prime) index_white_noise = 1 + rand() % 6;
}
}
}
void affine_image_generator06::generate_affine_image(void)
{
CvMat A = cvMat(2, 3, CV_32F, a);
if (use_random_background)
cvSet(generated_image, cvScalar(128));
else
cvSet(generated_image, cvScalar(rand() % 256));
cvWarpAffine(original_image_with_128_as_background, generated_image, &A,
CV_INTER_NN + CV_WARP_FILL_OUTLIERS /* + CV_WARP_INVERSE_MAP*/, cvScalarAll(128));
if (use_random_background)
replace_by_noise(generated_image, 128);
if (add_gaussian_smoothing && rand() % 3 == 0) {
int aperture = 3 + 2 * (rand() % 3);
cvSmooth(generated_image, generated_image, CV_GAUSSIAN, aperture, aperture);
}
if (change_intensities) cvCvtScale(generated_image, generated_image, rand(0.8f, 1.2f), rand(-10, 10));
// mcvSaveImage("g.bmp", generated_image);
// exit(0);
if (noise_level > 0 && add_noise) {
if (use_random_background)
add_white_noise(generated_image);
else
add_white_noise(generated_image, 128);
}
if (save_images) {
static int n = 0;
mcvSaveImage(generic_name_of_saved_images, n, generated_image);
n++;
}
}
| [
"yltastep@gmail.com"
] | yltastep@gmail.com |
b13047b14d7705f1be3079b301e7b3c85dc22373 | 6ce014545af76c9f52c3a80ef3a93fc249437a0b | /include/query_structs.h | 1e5cde84395e8415904d64c9d863290790466c9a | [] | no_license | David-Durst/nba_queries | fd9340b9c140531068fa195e2249c800cbc80d47 | 0a7a2a9925d8d008b22b389fe05afd7a6c88284a | refs/heads/master | 2023-03-06T15:17:26.390528 | 2021-02-16T05:10:26 | 2021-02-16T05:10:26 | 311,221,043 | 1 | 0 | null | 2021-02-15T04:53:42 | 2020-11-09T04:13:33 | C++ | UTF-8 | C++ | false | false | 8,652 | h | #ifndef QUERY_STRUCTS_H
#define QUERY_STRUCTS_H
#include <string>
#include <vector>
#include <cmath>
#include <functional>
using std::string;
using std::vector;
struct moment {
long int team_id;
int player_id;
double x_loc;
double y_loc;
double radius;
double game_clock;
double shot_clock;
short int quarter;
long int game_id;
long int event_id;
int moment_in_event;
int64_t internal_id;
} ;
bool operator==(moment const & lhs, moment const & rhs);
std::ostream& operator<<(std::ostream& os, moment const& value);
void print_moment_csv(std::ostream& os, const moment& value);
struct player_data {
long int team_id;
int player_id;
double x_loc;
double y_loc;
double radius;
};
bool operator==(player_data const & lhs, player_data const & rhs);
std::ostream& operator<<(std::ostream& os, player_data const& value);
void print_player_data_csv(std::ostream& os, const player_data& value);
struct event_moment_data {
long int event_id;
int moment_in_event;
};
bool operator==(event_moment_data const & lhs, event_moment_data const & rhs);
std::ostream& operator<<(std::ostream& os, event_moment_data const& value);
void print_event_moment_data_csv(std::ostream& os, const event_moment_data& value);
struct extra_game_data {
long int game_id;
int game_num;
int num_ot_periods;
};
bool operator==(extra_game_data const & lhs, extra_game_data const & rhs);
std::ostream& operator<<(std::ostream& os, extra_game_data const& value);
void print_extra_game_data_csv(std::ostream& os, const extra_game_data& value);
class clock_fixed_point {
public:
long int seconds;
int twenty_fifths_of_second;
clock_fixed_point () { }
clock_fixed_point (double f) {
seconds = std::floor(f);
twenty_fifths_of_second = std::round((f - seconds) * 25);
if (twenty_fifths_of_second == 25) {
seconds++;
twenty_fifths_of_second = 0;
}
}
inline double to_double() const {
return seconds + (twenty_fifths_of_second / 25.0);
}
clock_fixed_point abs_diff(const clock_fixed_point& other) const {
return clock_fixed_point(std::abs(this->to_double() - other.to_double()));
}
bool gt(double f) const {
return this->to_double() > f;
}
inline bool gt(clock_fixed_point c) const {
return this->seconds > c.seconds || (this->seconds == c.seconds && this->twenty_fifths_of_second > c.twenty_fifths_of_second);
}
inline int64_t time_to_index(vector<extra_game_data>& extra_data, int game_num, int quarter) {
int ot_quarters = 0;
for (int i = 0; i < game_num; i++) {
ot_quarters += extra_data.at(i).num_ot_periods;
}
int non_ot_quarters_finished_this_game = std::min(4, quarter - 1);
int ot_quarters_finished_this_game = std::max(0, quarter - 5);
int seconds_elapsed_this_quarter = quarter >= 5 ? 300 - seconds : 720 - seconds;
// 720 seconds in a quarter
return
// time for multiple games
25 * 720 * 4 * game_num +
// time for Ot
25 * 300 * ot_quarters +
// time in game
(25 * (720 * non_ot_quarters_finished_this_game + 300 * ot_quarters_finished_this_game + seconds_elapsed_this_quarter) - twenty_fifths_of_second);
}
};
bool operator==(clock_fixed_point const & lhs, clock_fixed_point const & rhs);
bool operator!=(clock_fixed_point const& lhs, clock_fixed_point const& rhs);
struct cleaned_moment {
player_data ball;
player_data players[10];
clock_fixed_point game_clock;
double shot_clock;
short int quarter;
long int game_id; // game_id assigned by nba
int game_num; // game num stores game's number in vector of cleaned_moments
vector<event_moment_data> events;
} ;
bool operator==(cleaned_moment const & lhs, cleaned_moment const & rhs);
std::ostream& operator<<(std::ostream& os, cleaned_moment const& value);
void print_cleaned_moment_csv(std::ostream& os, const cleaned_moment& value);
void print_cleaned_moment_csv_header(std::ostream& os);
void get_all_player_data(vector<std::reference_wrapper<player_data>>& data, cleaned_moment& c);
struct event {
long int game_id;
long int event_num;
int event_msg_type;
int event_msg_action_type;
short int period;
string wc_timestring;
string pc_timestring;
string home_description;
string neutral_description;
string visitor_description;
string score;
string score_margin;
int person1_type;
int player1_id;
string player1_name;
float player1_team_id;
string player1_team_city;
string player1_team_nickname;
string player1_team_abbreviation;
int person2_type;
int player2_id;
string player2_name;
float player2_team_id;
string player2_team_city;
string player2_team_nickname;
string player2_team_abbreviation;
int person3_type;
int player3_id;
string player3_name;
float player3_team_id;
string player3_team_city;
string player3_team_nickname;
string player3_team_abbreviation;
} ;
struct shot {
string action_type;
int event_time;
string event_type;
string game_date;
long int game_event_id;
long int game_id;
string grid_type;
string htm;
float loc_x;
float loc_y;
int minutes_remaining;
int period;
int player_id;
string player_name;
float quarter;
int seconds_remaining;
bool shot_attempted_flag;
int shot_distance;
bool shot_made_flag;
clock_fixed_point shot_time;
string shot_type;
string shot_zone_area;
string shot_zone_basic;
string shot_zone_range;
long int team_id;
string team_name;
string team_vtm;
} ;
bool operator==(shot const & lhs, shot const & rhs);
std::ostream& operator<<(std::ostream& os, shot const& value);
void print_shot_csv(std::ostream& os, const shot& value);
bool shot_before_moment(const shot & s, const moment & m);
bool moment_before_shot(const moment & m, const shot & s);
struct cleaned_shot {
string action_type;
int event_time;
string event_type;
string game_date;
long int game_event_id;
long int game_id;
int game_num;
string grid_type;
string htm;
float loc_x;
float loc_y;
int minutes_remaining;
int period;
int player_id;
string player_name;
int quarter;
int seconds_remaining;
bool shot_attempted_flag;
int shot_distance;
bool shot_made_flag;
clock_fixed_point shot_time;
string shot_type;
string shot_zone_area;
string shot_zone_basic;
string shot_zone_range;
long int team_id;
string team_name;
string team_vtm;
} ;
bool operator==(cleaned_shot const & lhs, shot const & rhs);
std::ostream& operator<<(std::ostream& os, cleaned_shot const& value);
void print_cleaned_shot_csv(std::ostream& os, const cleaned_shot& value);
template <typename T>
struct list_node {
T data;
list_node<T>* next;
};
template <typename T>
class list {
list_node<T> *head, *tail;
size_t size;
public:
list() : head(NULL), tail(NULL), size(0) { }
~list() { clear(); }
void append_node(T elem);
T * get(size_t i);
size_t get_size();
void clear();
void to_vector(vector<T> & vec);
};
template <typename T>
inline void list<T>::append_node(T elem) {
if (head == NULL) {
head = new list_node<T>();
tail = head;
head->data = elem;
}
else {
list_node<T> * next_tail = new list_node<T>();
next_tail->data = elem;
tail->next = next_tail;
tail = tail->next;
}
size++;
}
template <typename T>
T * list<T>::get(size_t i) {
if (i >= size) {
throw std::invalid_argument("size " + std::to_string(i) + "greater than list size " + std::to_string(size));
}
list_node<T> * result_node = head;
for (int j = 0; j < i; j++) {
result_node = result_node->next;
}
return result_node->data;
}
template <typename T>
size_t list<T>::get_size() {
return size;
}
template <typename T>
void list<T>::clear() {
list_node<T> * cur_node = head;
tail = NULL;
for (int i = 0; i < size; i++) {
list_node<T> * prior_node = cur_node;
cur_node = cur_node->next;
free(prior_node);
}
head = NULL;
size = 0;
}
template <typename T>
void list<T>::to_vector(vector<T> &vec) {
vec.clear();
list_node<T> * cur_node = head;
for (int i = 0; i < size; i++) {
vec.push_back(cur_node->data);
cur_node = cur_node->next;
}
}
#endif
| [
"davidbdurst@gmail.com"
] | davidbdurst@gmail.com |
4ff9a7669503e0562497176e8e0cba38d8c47038 | 1ef4c6274b3cfb29789c1f7f2fb513d489b7e6d7 | /stack/stack.cpp | 7dec1acecbf76d9238969662113cd606c861bc92 | [
"MIT"
] | permissive | theMorning/katas | 0b0bb797dabb8b72b54d32473c095680604c46a1 | b88bab906b3891eac9c375c865cd91ab8dcef6b8 | refs/heads/master | 2020-12-19T12:06:45.660274 | 2020-01-31T05:06:13 | 2020-01-31T05:06:13 | 235,729,036 | 0 | 0 | null | 2020-01-23T05:26:30 | 2020-01-23T05:26:29 | null | UTF-8 | C++ | false | false | 452 | cpp | #include "stack.hpp"
template <typename T> Stack<T>::Stack(int lim) {
size = 0;
position = 0;
limit = lim;
items = new T[lim];
}
template <typename T> Stack<T>::~Stack() { delete[] items; }
template <typename T> void Stack<T>::push(T item) {
items[position] = item;
size++;
position++;
}
template <typename T> T Stack<T>::pop() {
size--;
return items[--position];
}
template <typename T> int Stack<T>::getSize() { return size; }
| [
"ryantmcdermott@gmail.com"
] | ryantmcdermott@gmail.com |
bd175753adeec83d03cdd8ce7e1be7dfdd41e764 | 948f4e13af6b3014582909cc6d762606f2a43365 | /testcases/juliet_test_suite/testcases/CWE122_Heap_Based_Buffer_Overflow/s01/CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_cpy_42.cpp | e8aa2f4df60dace10399f6fffeb07b6f1899cf38 | [] | no_license | junxzm1990/ASAN-- | 0056a341b8537142e10373c8417f27d7825ad89b | ca96e46422407a55bed4aa551a6ad28ec1eeef4e | refs/heads/master | 2022-08-02T15:38:56.286555 | 2022-06-16T22:19:54 | 2022-06-16T22:19:54 | 408,238,453 | 74 | 13 | null | 2022-06-16T22:19:55 | 2021-09-19T21:14:59 | null | UTF-8 | C++ | false | false | 2,830 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_cpy_42.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193.label.xml
Template File: sources-sink-42.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Allocate memory for a string, but do not allocate space for NULL terminator
* GoodSource: Allocate enough memory for a string and the NULL terminator
* Sink: cpy
* BadSink : Copy string to data using strcpy()
* Flow Variant: 42 Data flow: data returned from one function to another in the same source file
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
/* MAINTENANCE NOTE: The length of this string should equal the 10 */
#define SRC_STRING "AAAAAAAAAA"
namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_cpy_42
{
#ifndef OMITBAD
static char * badSource(char * data)
{
/* FLAW: Did not leave space for a null terminator */
data = new char[10];
return data;
}
void bad()
{
char * data;
data = NULL;
data = badSource(data);
{
char source[10+1] = SRC_STRING;
/* POTENTIAL FLAW: data may not have enough space to hold source */
strcpy(data, source);
printLine(data);
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
static char * goodG2BSource(char * data)
{
/* FIX: Allocate space for a null terminator */
data = new char[10+1];
return data;
}
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
char * data;
data = NULL;
data = goodG2BSource(data);
{
char source[10+1] = SRC_STRING;
/* POTENTIAL FLAW: data may not have enough space to hold source */
strcpy(data, source);
printLine(data);
delete [] data;
}
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE193_char_cpy_42; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"yzhang0701@gmail.com"
] | yzhang0701@gmail.com |
f760d13b3d558f6a17afa89a04a4f466d8a711a4 | 136ee4eec7e1591af2ba60ba6ae342d05b187cee | /traversingBinaryTree.cpp | c88ac4ae4710a0fb54b941b8f09974b20332fff0 | [] | no_license | hujunyu1222/leetcode | 7cd79c6d5287a6cf1db8ce0e7abb225bd53e525b | b20d4a607bdcbc1fc92670b11142433214d7e32b | refs/heads/master | 2021-01-11T06:06:55.377430 | 2017-04-11T02:54:30 | 2017-04-11T02:54:30 | 71,687,068 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,285 | cpp | #include <iostream>
#include <stack>
using namespace std;
struct TreeNode{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x):val(x), left(NULL), right(NULL){}
};
//后续遍历用于标记节点
enum Tags {Left,Right};
struct element{
TreeNode *pointer;
Tags tag;
};
//前序遍历 非递归
void PreOrder(TreeNode *root){
stack<TreeNode*> aStack;
TreeNode *p = root;
aStack.push(NULL);
while(p != NULL){
//先访问根
cout << p->val;
//右子数入栈
if (p->right != NULL){
aStack.push(p->right);
}
//左子树下降
if (p->left != NULL){
p = p->left;
}
else{
p = aStack.top();
aStack.pop();
}
}
}
//中序遍历 非递归
void InOrder(TreeNode *root){
stack<TreeNode *> aStack;
TreeNode *p = root;
while (!aStack.empty() || p != NULL){
if(p != NULL){
aStack.push(p);
p = p->left;
}
else{
p = aStack.top();
aStack.pop();
cout << p->val;
p = p->right;
}
}
}
//后续遍历 非递归
void PostOrder(TreeNode *root){
stack<element> aStack;
element node;
TreeNode *p = root;
while (!aStack.empty() || p != NULL){
while(p != NULL){
node.pointer = p;
//左路下降,tag至左
node.tag = Left;
aStack.push(node);
p = p->left;
}
node = aStack.top();
aStack.pop();
p = node.pointer;
if (node.tag == Left){
node.tag = Right;
//回到栈中
aStack.push(node);
p = p->right;
}
else{
cout << p->val;
//置p为NULL,使其继续弹栈
p = NULL;
}
}
}
int main()
{
TreeNode A(1), B(2), C(3), D(4), E(5), F(6), G(7), H(8), I(9);
A.left = &B;
A.right = &C;
B.left = &D;
B.right = &E;
E.left = &G;
C.right = &F;
F.left = &H;
F.right = &I;
cout <<"前序遍历:\n";
PreOrder(&A);
cout <<"\n中序遍历:\n";
InOrder(&A);
cout <<"\n后序遍历:\n";
PostOrder(&A);
return 0;
}
| [
"hujunyu1222@gmail.com"
] | hujunyu1222@gmail.com |
f389226213bd0f506ac04b3c4a3c733d888eb7ac | 349fe789ab1e4e46aae6812cf60ada9423c0b632 | /FIB_DataModule/GurRoznDoc/UDMGurRoznDoc.h | 125cafca16aa6508422e462650d89684e4b66fea | [] | no_license | presscad/ERP | a6acdaeb97b3a53f776677c3a585ca860d4de980 | 18ecc6c8664ed7fc3f01397d587cce91fc3ac78b | refs/heads/master | 2020-08-22T05:24:15.449666 | 2019-07-12T12:59:13 | 2019-07-12T12:59:13 | 216,326,440 | 1 | 0 | null | 2019-10-20T07:52:26 | 2019-10-20T07:52:26 | null | WINDOWS-1251 | C++ | false | false | 3,043 | h | //---------------------------------------------------------------------------
#ifndef UDMGurRoznDocH
#define UDMGurRoznDocH
//---------------------------------------------------------------------------
#include "IDMFibConnection.h"
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <DB.hpp>
#include <IBCustomDataSet.hpp>
#include <IBDatabase.hpp>
#include <IBQuery.hpp>
#include "FIBDatabase.hpp"
#include "FIBDataSet.hpp"
#include "pFIBDatabase.hpp"
#include "pFIBDataSet.hpp"
#include "FIBQuery.hpp"
#include "pFIBQuery.hpp"
//---------------------------------------------------------------------------
class TDMGurRoznDoc : public TDataModule
{
__published: // IDE-managed Components
TDataSource *DataSourceTable;
TpFIBDataSet *IBQ;
TpFIBDataSet *Table;
TpFIBTransaction *IBTr;
TFIBDateTimeField *TablePOSDOC;
TFIBSmallIntField *TablePRDOC;
TFIBIntegerField *TableNUMDOC;
TFIBBCDField *TableSUMDOC;
TFIBBCDField *TableIDDOC;
TFIBBCDField *TableIDFIRMDOC;
TFIBBCDField *TableIDSKLDOC;
TFIBBCDField *TableIDKLDOC;
TFIBBCDField *TableIDDOGDOC;
TFIBBCDField *TableIDUSERDOC;
TFIBBCDField *TableIDDOCOSNDOC;
TFIBBCDField *TableIDEXTDOC;
TFIBIntegerField *TableTYPEEXTDOC;
TpFIBQuery *Query;
TFIBBCDField *TableIDBASE_GALLDOC;
TFIBWideStringField *TableTDOC;
TFIBWideStringField *TableGID_DOC;
TFIBWideStringField *TablePREFIKSDOC;
TFIBBCDField *TableIDPROJECT_GALLDOC;
TFIBWideStringField *TableNAMEFIRM;
TFIBWideStringField *TableNAMESKLAD;
TFIBWideStringField *TableNAMEKLIENT;
TFIBWideStringField *TableNAME_USER;
void __fastcall DataModuleDestroy(TObject *Sender);
void __fastcall DataModuleCreate(TObject *Sender);
private: // User declarations
bool ExecPriv, InsertPriv, EditPriv, DeletePriv;
public: // User declarations
__fastcall TDMGurRoznDoc(TComponent* Owner);
IkanUnknown * InterfaceMainObject;
IkanUnknown * InterfaceOwnerObject;
IkanUnknown * InterfaceImpl; //интерфейс класса реализации
GUID ClsIdImpl; //GUID класса реализации
IDMFibConnection * DM_Connection;
IkanCom *InterfaceGlobalCom;
typedef void (__closure * TFunctionDeleteImplType)(void);
TFunctionDeleteImplType FunctionDeleteImpl;
bool flDeleteImpl;
int CodeError;
UnicodeString TextError;
bool Init(void);
int Done(void);
void OpenTable();
void UpdateTable(void);
__int64 IdDoc;
__int64 IdKlient;
__int64 IdSklad;
__int64 IdFirm;
UnicodeString StringTypeDoc;
UnicodeString StringFullTypeDoc;
bool OtborVkl;
bool OtborPoKlient ;
bool OtborPoFirm;
bool OtborPoSklad;
bool OtborPoTypeDoc;
TDateTime PosNach;
TDateTime PosCon;
int FindDocPoIdDog(__int64 iddogovor);
__int64 IdBase;
};
//---------------------------------------------------------------------------
extern PACKAGE TDMGurRoznDoc *DMGurRoznDoc;
//---------------------------------------------------------------------------
#endif
| [
"sasha@kaserv.ru"
] | sasha@kaserv.ru |
cb82e1c523f9630a1e956e2563e02bb529a80012 | 01193a36c2c26af2856333e7ee4d535716b0bb32 | /Source/UePortal/Portal/Throughable.h | c5d76f79ba2ff1c60a42a4e4c38fb284669837b2 | [] | no_license | WeaponSoon/UePortal | 50310ac14e17c8786a32b0eb8d336a0a4f9d2c3f | b139cb8042273a652b30d000f0611a7b04ccb413 | refs/heads/master | 2020-04-11T19:20:52.562799 | 2019-01-07T08:19:35 | 2019-01-07T08:19:35 | 162,031,031 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,593 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "UObject/Interface.h"
#include "PortalDoorComponent.h"
#include "Throughable.generated.h"
class UThroughableComponent;
USTRUCT()
struct FThroughablePrePhysicsTickFunction : public FTickFunction
{
GENERATED_USTRUCT_BODY()
/** CharacterMovementComponent that is the target of this tick **/
class UThroughableComponent* Target;
/**
* Abstract function actually execute the tick.
* @param DeltaTime - frame time to advance, in seconds
* @param TickType - kind of tick for this frame
* @param CurrentThread - thread we are executing on, useful to pass along as new tasks are created
* @param MyCompletionGraphEvent - completion event for this task. Useful for holding the completion of this task until certain child tasks are complete.
**/
virtual void ExecuteTick(float DeltaTime, enum ELevelTick TickType, ENamedThreads::Type CurrentThread, const FGraphEventRef& MyCompletionGraphEvent) override;
/** Abstract function to describe this tick. Used to print messages about illegal cycles in the dependency graph **/
virtual FString DiagnosticMessage() override;
};
template<>
struct TStructOpsTypeTraits<FThroughablePrePhysicsTickFunction> : public TStructOpsTypeTraitsBase2<FThroughablePrePhysicsTickFunction>
{
enum
{
WithCopy = false
};
};
USTRUCT()
struct FThroughablePostPhysicsTickFunction : public FTickFunction
{
GENERATED_USTRUCT_BODY()
/** CharacterMovementComponent that is the target of this tick **/
class UThroughableComponent* Target;
/**
* Abstract function actually execute the tick.
* @param DeltaTime - frame time to advance, in seconds
* @param TickType - kind of tick for this frame
* @param CurrentThread - thread we are executing on, useful to pass along as new tasks are created
* @param MyCompletionGraphEvent - completion event for this task. Useful for holding the completion of this task until certain child tasks are complete.
**/
virtual void ExecuteTick(float DeltaTime, enum ELevelTick TickType, ENamedThreads::Type CurrentThread, const FGraphEventRef& MyCompletionGraphEvent) override;
/** Abstract function to describe this tick. Used to print messages about illegal cycles in the dependency graph **/
virtual FString DiagnosticMessage() override;
};
template<>
struct TStructOpsTypeTraits<FThroughablePostPhysicsTickFunction> : public TStructOpsTypeTraitsBase2<FThroughablePostPhysicsTickFunction>
{
enum
{
WithCopy = false
};
};
// This class does not need to be modified.
UCLASS(ClassGroup = (Custom), meta = (BlueprintSpawnableComponent))
class UEPORTAL_API UThroughableComponent : public UActorComponent
{
GENERATED_BODY()
// Add interface functions to this class. This is the class that will be inherited to implement this interface.
public:
UThroughableComponent(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get());
UPROPERTY()
struct FThroughablePostPhysicsTickFunction PostPhysicsTickFunction;
UPROPERTY()
struct FThroughablePrePhysicsTickFunction PrePhysicsTickFunction;
TSet<TWeakObjectPtr<UPortalDoorComponent>> nearPortals;
TWeakObjectPtr<UPortalDoorComponent> passingPortal;
TWeakObjectPtr<USceneComponent> throughableComponent;
virtual void TickComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) override;
UFUNCTION()
void AddNearPortalDoor(UPortalDoorComponent* nearPortal);
UFUNCTION()
void RemoveNearPortalDoor(UPortalDoorComponent* nearPortal);
UFUNCTION()
void UpdatePassingPortal();
UFUNCTION(BlueprintCallable, Category="Portal Component")
void SetThroughableComponent(class USceneComponent* throughable);
static const TMap<TWeakObjectPtr<USceneComponent>, TWeakObjectPtr<UThroughableComponent>>& GetThroughableMap();
virtual void PrePhysics(float DeltaTime, enum ELevelTick TickType, ENamedThreads::Type CurrentThread, const FGraphEventRef& MyCompletionGraphEvent);
virtual void PostPhysics(float DeltaTime, enum ELevelTick TickType, ENamedThreads::Type CurrentThread, const FGraphEventRef& MyCompletionGraphEvent);
virtual void RegisterComponentTickFunctions(bool bRegister) override;
protected:
UFUNCTION()
virtual void OnSetThroughableComponent(class USceneComponent* oldOne, class USceneComponent* newOne);
protected:
virtual void EndPlay(const EEndPlayReason::Type EndPlayReason) override;
virtual void BeginPlay() override;
private:
static TMap<TWeakObjectPtr<USceneComponent>, TWeakObjectPtr<UThroughableComponent>> throughableMap;
};
| [
"sdswp@126.com"
] | sdswp@126.com |
3061e44c92b3fa6cbd719990c6229d6e879b68d3 | 286d04e93943ab67f18e9cad96211c050e4f9aee | /Arduino/msp430f2013_SD16_I2C/msp430f2013_SD16_I2C.ino | af3514e39aba4f16210bb81c74439d6795a4116f | [
"MIT"
] | permissive | agaelema/msp430f20x3_as_i2c_16bit_adc | 3b66a38be10e7bf505201b2adf3587338377a775 | 5c788fb15cdd05bb998a9a159e4da4baf5c56305 | refs/heads/master | 2020-05-16T01:28:43.140584 | 2019-04-22T04:45:32 | 2019-04-22T04:45:32 | 182,603,578 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,170 | ino | /******************************************************************************
* control SD16_A of MSP430F2013 as a I2C ADC
* - MSP430 address: 0X0B
******************************************************************************
*
* Arduino Uno/Nano
* -----------------
* | |
* I2C SDA -|A4 |
* I2C SCL -|A5 |
* | |
* | |
*
* check voltage levels between master and slave (iso converter if needed)
*
* Haroldo Amaral - 2019
* https://github.com/agaelema/msp430f20x3_as_i2c_16bit_adc
******************************************************************************/
#include "Arduino.h"
#include <Wire.h>
/******************************************************************************
* SD16 definitions and header
******************************************************************************/
#include "sd16_header.h"
#define SLV_Addr 0x0B // Address is 0x0B<<1 for R/W
/* Select operation mode - uncomment desired mode - comment all others */
//#define I2C_ADC_START_CONVERSION // start with current configuration
//#define I2C_ADC_STOP_CONVERSION
#define I2C_ADC_START_SING_CONVERSION_CH1_GAIN1x_BIPOLAR_1024_2S
//#define I2C_ADC_START_CONT_CONVERSION_CH1_GAIN1x_BIPOLAR_1024_2S
/******************************************************************************
* ADS1115 configuration
******************************************************************************/
#define ENABLE_ADS1115 // enable/disable ADS1115
#if defined ( ENABLE_ADS1115 )
#include <Adafruit_ADS1015.h>
Adafruit_ADS1115 ads(0x48);
#endif
/******************************************************************************
* setup
******************************************************************************/
void setup()
{
Serial.begin (9600);
while (!Serial);
#if defined (ENABLE_ADS1115)
ads.setGain(GAIN_FOUR); // 4x gain +/- 1.024V 1 bit = 0.03125mV
ads.begin();
#endif
}
/******************************************************************************
* main program
******************************************************************************/
void loop()
{
int var = 0;
uint8_t counter = 0;
Wire.begin();
while(1)
{
#if defined (I2C_ADC_START_CONVERSION)
/*
* set slave address - configuration register - register value - end transmission
*/
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_CONVERSION);
var = Wire.write(SD16_START_CONVERSION);
var = Wire.endTransmission();
#endif
#if defined (I2C_ADC_STOP_CONVERSION)
/*
* set slave address - configuration register - register value - end transmission
*/
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_CONVERSION);
var = Wire.write(SD16_STOP_CONVERSION);
var = Wire.endTransmission();
#endif
#if defined (I2C_ADC_START_SING_CONVERSION_CH1_GAIN1x_BIPOLAR_1024_2S)
/*
* set slave address - configuration register - register value - end transmission
*/
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_CHCTRL_LOW);
var = Wire.write(SD16_DF_2S_COMP);
var = Wire.endTransmission();
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_CHCTRL_HIGH);
var = Wire.write(SD16_OSR_1024x|SD16_SNG_CONV|SD16_BIPOLAR);
var = Wire.endTransmission();
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_IN_CTRL);
var = Wire.write(SD16_CH1|SD16_GAIN1x);
var = Wire.endTransmission();
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_CONVERSION);
var = Wire.write(SD16_START_CONVERSION);
var = Wire.endTransmission();
#endif
#if defined (I2C_ADC_START_CONT_CONVERSION_CH1_GAIN1x_BIPOLAR_1024_2S)
if ( counter == 0 )
{
/*
* set slave address - configuration register - register value - end transmission
*/
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_CHCTRL_LOW);
var = Wire.write(SD16_DF_2S_COMP);
var = Wire.endTransmission();
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_CHCTRL_HIGH);
var = Wire.write(SD16_OSR_1024x|SD16_CONT_CONV|SD16_BIPOLAR);
var = Wire.endTransmission();
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_IN_CTRL);
var = Wire.write(SD16_CH1|SD16_GAIN1x);
var = Wire.endTransmission();
Wire.beginTransmission (SLV_Addr);
var = Wire.write(SD16_CONVERSION);
var = Wire.write(SD16_START_CONVERSION);
var = Wire.endTransmission();
}
counter++;
#endif
volatile int c = 0;
int counter = 0;
int16_t bufferReceived[2] = {0};
Wire.requestFrom(SLV_Addr, 2); // read 2 bytes from i2c
while (Wire.available())
{
c = Wire.read();
bufferReceived[counter] = (int16_t)c; // save on buffer
counter++;
}
/*
* convert 2 bytes in 1 16-bit integer variable
*/
int16_t received = 0;
received |= bufferReceived[0] & 0xFF;
received |= (bufferReceived[1] & 0xFF) << 8;
#if defined (ENABLE_ADS1115)
int16_t adc0 = 0;
adc0 = ads.readADC_Differential_0_1();
Serial.print((int16_t)(adc0 & 0xFFFF)); Serial.print(' ');
#endif
Serial.println((int16_t)(received & 0xFFFF));
}
}
| [
"agaelema@gmail.com"
] | agaelema@gmail.com |
4242e38f548e2919099daa905b9db61b73e7f2fe | 63d2a6e4de06261adb6eedf312171be3f8c45f46 | /Lab5/Hash_Table/login.cpp | a32776cd4ca6a44b09c77ef7f9615c9ebbc91dd0 | [
"MIT"
] | permissive | HanlinHu/CS210_LAB_code | 17963ae5e801d81407fd1affd91fda10d6bd6c3c | c0f2d89cb6b1d2047bd6fea7e2a041660245dc32 | refs/heads/master | 2020-05-29T21:25:45.776141 | 2015-08-21T22:46:48 | 2015-08-21T22:46:48 | 39,524,574 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,205 | cpp | //--------------------------------------------------------------------
//
// Hash Table Application: STL unordered_map
// Based on Laboratory 12 from
// A Laboratory Course in C++ Data Structures, Second Edition
//
// Modified by Alex Clarke on Nov. 8, 2014
//
// Complete this program so that it:
// 1) Inserts Passwords structures into the passwords unordered_map
// using username as the hashkey.
// Print the full contents of the hashtable to confirm that it worked.
//
// 2) "Authenticates" user login attempts using the the hashtable
//
// 3) Uses a custom hash function specified in the lab notes.
//
//--------------------------------------------------------------------
#include <string>
#include <iostream>
#include <fstream>
#include <unordered_map>
#include <iomanip>
using namespace std;
//This will be the data stored in the HashTbl (class DT)
struct UserInfo
{
string firstname,
lastname,
password;
};
//*****************************************************************
// Step 3a: Add your own string hashing class
//*****************************************************************
// Our special string hashing class
class stringHash{
public:
size_t operator()(const string& Hashit) const
{
size_t val = 0;
for (size_t i = 0; i < Hashit.length(); i++)
{
val += Hashit[i];
}
return val;
}
};
int main()
{
//*************************************************************
// Step 3b: Use your own hash function
//*************************************************************
//** Rewrite this line so it uses one of your string hashing
//** objects instead of the STL string hasher.
//** You must complete Step 3a for it to work.
unordered_map<string, UserInfo> passwords;
unordered_map<string, UserInfo>::iterator i;
UserInfo tempInfo;
string username, // user-supplied name
password; // user-supplied password
//*************************************************************
// Step 1a: Read in the password file
//*************************************************************
ifstream passFile( "password.dat" );
if ( !passFile )
{
cout << "Unable to open 'password.dat'!" << endl;
return 1;
}
while (passFile >> username >> tempInfo.password
>> tempInfo.firstname >> tempInfo.lastname)
{
//**add code here to insert user info into the unordered_map
//Note: passwords is the name of the unordered map
// username is the key
// tempInfo is the mapped value
passwords[username] = tempInfo;
}
//*************************************************************
// Step 1b: Show that the data is in the hash table
//*************************************************************
//** add code here to traverse and print the unordered_map
cout << "Number of entries in table: " << passwords.size() << endl;
cout << "Number of buckets: " << passwords.bucket_count() << endl;
for (i = passwords.begin(); i != passwords.end(); i++)
{
cout << setw(10) << left << i->first << setw(4) << passwords.bucket(i->first);
cout << setw(15) << i->second.password;
cout << setw(10) << i->second.firstname;
cout << setw(10) << i->second.lastname << endl;
}
cout << endl;
//*********************************************************
// Step 2: Prompt for a Login and Password and check if valid
//*********************************************************
cout << "Login: ";
while ( cin >> username ) // to quit, type CTRL Z in Visual C++
{
cout << "Password: ";
cin >> password;
//** Retrieve element based on key.
i = passwords.find(username);
//** if user existed in table and
//** if the retrieved user password matches the
//** input password print "Authentication succeeded."
//** followed by the user's information
if (i != passwords.end() && password == i->second.password)
{
cout <<"Authentication succeeded"<< endl;
cout << i->second.firstname << " " << i->second.lastname << endl;
}
//** in all other cases print "Authentication failed."
else
{
cout << "Authentication failed" << endl;
}
cout << "Login: ";
}
cout << endl;
return 0;
}
| [
"HanlinHu@users.noreply.github.com"
] | HanlinHu@users.noreply.github.com |
64ceb2929e3822d9dae61e0431532518b9941a61 | 8cf32b4cbca07bd39341e1d0a29428e420b492a6 | /programs/nodeseat/main.cpp | 6a4709d381d452bbd27c04f11c5a349aa837cb0d | [
"MIT"
] | permissive | cubetrain/CubeTrain | e1cd516d5dbca77082258948d3c7fc70ebd50fdc | b930a3e88e941225c2c54219267f743c790e388f | refs/heads/master | 2020-04-11T23:00:50.245442 | 2018-12-17T16:07:16 | 2018-12-17T16:07:16 | 156,970,178 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,229 | cpp | /**
* @file
* @copyright defined in cubetrain/LICENSE.txt
*/
#include <appbase/application.hpp>
#include <cubetrain/chain_plugin/chain_plugin.hpp>
#include <cubetrain/http_plugin/http_plugin.hpp>
#include <cubetrain/history_plugin/history_plugin.hpp>
#include <cubetrain/net_plugin/net_plugin.hpp>
#include <cubetrain/producer_plugin/producer_plugin.hpp>
#include <cubetrain/utilities/common.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/log/appender.hpp>
#include <fc/exception/exception.hpp>
#include <boost/dll/runtime_symbol_info.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include "config.hpp"
using namespace appbase;
using namespace cubetrain;
namespace fc {
std::unordered_map<std::string,appender::ptr>& get_appender_map();
}
namespace detail {
void configure_logging(const bfs::path& config_path)
{
try {
try {
fc::configure_logging(config_path);
} catch (...) {
elog("Error reloading logging.json");
throw;
}
} catch (const fc::exception& e) {
elog("${e}", ("e",e.to_detail_string()));
} catch (const boost::exception& e) {
elog("${e}", ("e",boost::diagnostic_information(e)));
} catch (const std::exception& e) {
elog("${e}", ("e",e.what()));
} catch (...) {
// empty
}
}
} // namespace detail
void logging_conf_loop()
{
std::shared_ptr<boost::asio::signal_set> sighup_set(new boost::asio::signal_set(app().get_io_service(), SIGHUP));
sighup_set->async_wait([sighup_set](const boost::system::error_code& err, int /*num*/) {
if(!err)
{
ilog("Received HUP. Reloading logging configuration.");
auto config_path = app().get_logging_conf();
if(fc::exists(config_path))
::detail::configure_logging(config_path);
for(auto iter : fc::get_appender_map())
iter.second->initialize(app().get_io_service());
logging_conf_loop();
}
});
}
void initialize_logging()
{
auto config_path = app().get_logging_conf();
if(fc::exists(config_path))
fc::configure_logging(config_path); // intentionally allowing exceptions to escape
for(auto iter : fc::get_appender_map())
iter.second->initialize(app().get_io_service());
logging_conf_loop();
}
enum return_codes {
OTHER_FAIL = -2,
INITIALIZE_FAIL = -1,
SUCCESS = 0,
BAD_ALLOC = 1,
DATABASE_DIRTY = 2,
FIXED_REVERSIBLE = 3,
EXTRACTED_GENESIS = 4,
NODE_MANAGEMENT_SUCCESS = 5
};
int main(int argc, char** argv)
{
try {
app().set_version(cubetrain::nodeseat::config::version);
app().register_plugin<history_plugin>();
auto root = fc::app_path();
app().set_default_data_dir(root / "cubetrain/nodeseat/data" );
app().set_default_config_dir(root / "cubetrain/nodeseat/config" );
if(!app().initialize<chain_plugin, http_plugin, net_plugin, producer_plugin>(argc, argv))
return INITIALIZE_FAIL;
initialize_logging();
ilog("nodeseat version ${ver}", ("ver", app().version_string()));
ilog("cubetrain root is ${root}", ("root", root.string()));
app().startup();
app().exec();
} catch( const extract_genesis_state_exception& e ) {
return EXTRACTED_GENESIS;
} catch( const fixed_reversible_db_exception& e ) {
return FIXED_REVERSIBLE;
} catch( const node_management_success& e ) {
return NODE_MANAGEMENT_SUCCESS;
} catch( const fc::exception& e ) {
if( e.code() == fc::std_exception_code ) {
if( e.top_message().find( "database dirty flag set" ) != std::string::npos ) {
elog( "database dirty flag set (likely due to unclean shutdown): replay required" );
return DATABASE_DIRTY;
} else if( e.top_message().find( "database metadata dirty flag set" ) != std::string::npos ) {
elog( "database metadata dirty flag set (likely due to unclean shutdown): replay required" );
return DATABASE_DIRTY;
}
}
elog( "${e}", ("e", e.to_detail_string()));
return OTHER_FAIL;
} catch( const boost::interprocess::bad_alloc& e ) {
elog("bad alloc");
return BAD_ALLOC;
} catch( const boost::exception& e ) {
elog("${e}", ("e",boost::diagnostic_information(e)));
return OTHER_FAIL;
} catch( const std::runtime_error& e ) {
if( std::string(e.what()) == "database dirty flag set" ) {
elog( "database dirty flag set (likely due to unclean shutdown): replay required" );
return DATABASE_DIRTY;
} else if( std::string(e.what()) == "database metadata dirty flag set" ) {
elog( "database metadata dirty flag set (likely due to unclean shutdown): replay required" );
return DATABASE_DIRTY;
} else {
elog( "${e}", ("e",e.what()));
}
return OTHER_FAIL;
} catch( const std::exception& e ) {
elog("${e}", ("e",e.what()));
return OTHER_FAIL;
} catch( ... ) {
elog("unknown exception");
return OTHER_FAIL;
}
return SUCCESS;
}
| [
"1848@shanchain.com"
] | 1848@shanchain.com |
3c8f8470d2bf3b4c4d7d339c0b3c89d421010eca | 0914ef830712bcddd43732f4f6d4c83d42f62430 | /SupportedTitles.cpp | 480cea409d8050d7ba44a1b994d246e45d9a6f2c | [] | no_license | interdpth/RD1Engine | e6f6cf8191429bb33d6e2e60434ed1b87ceccbdf | fb9ba7d7357fed4bfc490c5a97b9bd6163640932 | refs/heads/master | 2023-03-28T18:00:30.651415 | 2021-03-29T03:07:44 | 2021-03-29T03:07:44 | 150,758,140 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 113 | cpp | #include "SupportedTitles.h"
SupportedTitles::SupportedTitles()
{
}
SupportedTitles::~SupportedTitles()
{
}
| [
"interdpth@gmail.com"
] | interdpth@gmail.com |
b48dddf61a18abe1dc81e415a2ad0435fd464144 | 84257c31661e43bc54de8ea33128cd4967ecf08f | /ppc_85xx/usr/include/c++/4.2.2/gnu/javax/crypto/jce/key/SquareSecretKeyFactoryImpl.h | 6f87aec7cbae33e15784f69604abdd71769e3e06 | [] | no_license | nateurope/eldk | 9c334a64d1231364980cbd7bd021d269d7058240 | 8895f914d192b83ab204ca9e62b61c3ce30bb212 | refs/heads/master | 2022-11-15T01:29:01.991476 | 2020-07-10T14:31:34 | 2020-07-10T14:31:34 | 278,655,691 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 801 | h | // DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __gnu_javax_crypto_jce_key_SquareSecretKeyFactoryImpl__
#define __gnu_javax_crypto_jce_key_SquareSecretKeyFactoryImpl__
#pragma interface
#include <gnu/javax/crypto/jce/key/SecretKeyFactoryImpl.h>
extern "Java"
{
namespace gnu
{
namespace javax
{
namespace crypto
{
namespace jce
{
namespace key
{
class SquareSecretKeyFactoryImpl;
}
}
}
}
}
}
class gnu::javax::crypto::jce::key::SquareSecretKeyFactoryImpl : public ::gnu::javax::crypto::jce::key::SecretKeyFactoryImpl
{
public:
SquareSecretKeyFactoryImpl ();
static ::java::lang::Class class$;
};
#endif /* __gnu_javax_crypto_jce_key_SquareSecretKeyFactoryImpl__ */
| [
"Andre.Mueller@nateurope.com"
] | Andre.Mueller@nateurope.com |
3544c4d3b05b6fd3ec6b3fbdf372e8fa7c897086 | 0a09ae843324049a02df2430a42443518887779c | /client/src/inventoryboard.cpp | eda7ce07f888aea549b7f864b7f8d02f3a78c048 | [] | no_license | FlingPenguin/mir2x | 7653b3e6179042bac94069127e4cb3276428314b | 35e9deeee4b304198fd087f4ca368d32373d8d23 | refs/heads/master | 2023-06-02T04:30:15.810406 | 2021-06-10T17:56:43 | 2021-06-10T17:56:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,131 | cpp | /*
* =====================================================================================
*
* Filename: inventoryboard.cpp
* Created: 10/08/2017 19:22:30
* Description:
*
* Version: 1.0
* Revision: none
* Compiler: gcc
*
* Author: ANHONG
* Email: anhonghe@gmail.com
* Organization: USTC
*
* =====================================================================================
*/
#include "pngtexdb.hpp"
#include "sdldevice.hpp"
#include "processrun.hpp"
#include "inventoryboard.hpp"
extern PNGTexDB *g_progUseDB;
extern PNGTexDB *g_itemDB;
extern SDLDevice *g_sdlDevice;
InventoryBoard::InventoryBoard(int nX, int nY, ProcessRun *pRun, Widget *pwidget, bool autoDelete)
: Widget(DIR_UPLEFT, nX, nY, 0, 0, pwidget, autoDelete)
, m_opNameBoard
{
DIR_UPLEFT,
132,
16,
u8"【背包】",
1,
12,
0,
colorf::WHITE + 255,
this,
}
, m_wmdAniBoard
{
DIR_UPLEFT,
23,
14,
this,
}
, m_slider
{
DIR_UPLEFT,
258,
64,
291,
2,
nullptr,
this,
}
, m_closeButton
{
DIR_UPLEFT,
242,
422,
{SYS_TEXNIL, 0X0000001C, 0X0000001D},
nullptr,
nullptr,
[this]()
{
show(false);
},
0,
0,
0,
0,
true,
true,
this,
}
, m_processRun(pRun)
{
show(false);
auto texPtr = g_progUseDB->Retrieve(0X0000001B);
if(!texPtr){
throw fflerror("no valid inventory frame texture");
}
std::tie(m_w, m_h) = SDLDeviceHelper::getTextureSize(texPtr);
}
void InventoryBoard::drawItem(int dstX, int dstY, size_t startRow, bool cursorOn, const PackBin &bin) const
{
if(true
&& bin
&& bin.x >= 0
&& bin.y >= 0
&& bin.w > 0
&& bin.h > 0){
if(auto texPtr = g_itemDB->Retrieve(DBCOM_ITEMRECORD(bin.item.itemID).pkgGfxID | 0X01000000)){
const int startX = dstX + m_invGridX0;
const int startY = dstY + m_invGridY0 - startRow * SYS_INVGRIDPH;
const int viewX = dstX + m_invGridX0;
const int viewY = dstY + m_invGridY0;
const auto [itemPW, itemPH] = SDLDeviceHelper::getTextureSize(texPtr);
int drawDstX = startX + bin.x * SYS_INVGRIDPW + (bin.w * SYS_INVGRIDPW - itemPW) / 2;
int drawDstY = startY + bin.y * SYS_INVGRIDPH + (bin.h * SYS_INVGRIDPH - itemPH) / 2;
int drawSrcX = 0;
int drawSrcY = 0;
int drawSrcW = itemPW;
int drawSrcH = itemPH;
if(mathf::ROICrop(
&drawSrcX, &drawSrcY,
&drawSrcW, &drawSrcH,
&drawDstX, &drawDstY,
drawSrcW,
drawSrcH,
0, 0, -1, -1,
viewX, viewY, SYS_INVGRIDPW * 6, SYS_INVGRIDPH * 8)){
g_sdlDevice->drawTexture(texPtr, drawDstX, drawDstY, drawSrcX, drawSrcY, drawSrcW, drawSrcH);
}
int binGridX = bin.x;
int binGridY = bin.y;
int binGridW = bin.w;
int binGridH = bin.h;
if(mathf::rectangleOverlapRegion<int>(0, startRow, 6, 8, &binGridX, &binGridY, &binGridW, &binGridH)){
if(cursorOn){
g_sdlDevice->fillRectangle(colorf::WHITE + 64,
startX + binGridX * SYS_INVGRIDPW,
startY + binGridY * SYS_INVGRIDPH, // startY is for (0, 0), not for (0, startRow)
binGridW * SYS_INVGRIDPW,
binGridH * SYS_INVGRIDPH);
}
if(bin.item.count > 1){
const LabelBoard itemCount
{
DIR_UPLEFT,
0, // reset by new width
0,
to_u8cstr(std::to_string(bin.item.count)),
1,
10,
0,
colorf::RGBA(0XFF, 0XFF, 0X00, 0XFF),
};
itemCount.drawAt(DIR_UPRIGHT, startX + (binGridX + binGridW) * SYS_INVGRIDPW, startY + binGridY * SYS_INVGRIDPH - 2 /* pixel adjust */);
}
}
}
}
}
void InventoryBoard::update(double fUpdateTime)
{
m_wmdAniBoard.update(fUpdateTime);
}
void InventoryBoard::drawEx(int dstX, int dstY, int, int, int, int) const
{
if(auto pTexture = g_progUseDB->Retrieve(0X0000001B)){
g_sdlDevice->drawTexture(pTexture, dstX, dstY);
}
const auto myHeroPtr = m_processRun->getMyHero();
if(!myHeroPtr){
return;
}
const auto startRow = getStartRow();
const auto [mousePX, mousePY] = SDLDeviceHelper::getMousePLoc();
const auto &packBinListCRef = myHeroPtr->getInvPack().getPackBinList();
const auto cursorOnIndex = getPackBinIndex(mousePX, mousePY);
for(int i = 0; i < to_d(packBinListCRef.size()); ++i){
drawItem(dstX, dstY, startRow, (i == cursorOnIndex), packBinListCRef.at(i));
}
drawGold();
m_opNameBoard.draw();
m_wmdAniBoard.draw();
m_slider .draw();
m_closeButton.draw();
if(cursorOnIndex >= 0){
drawItemHoverText(packBinListCRef.at(cursorOnIndex));
}
}
bool InventoryBoard::processEvent(const SDL_Event &event, bool valid)
{
if(!valid){
focus(false);
return false;
}
if(!show()){
return false;
}
if(m_closeButton.processEvent(event, valid)){
return true;
}
if(m_slider.processEvent(event, valid)){
return true;
}
switch(event.type){
case SDL_MOUSEMOTION:
{
if((event.motion.state & SDL_BUTTON_LMASK) && (in(event.motion.x, event.motion.y) || focus())){
const auto [rendererW, rendererH] = g_sdlDevice->getRendererSize();
const int maxX = rendererW - w();
const int maxY = rendererH - h();
const int newX = std::max<int>(0, std::min<int>(maxX, x() + event.motion.xrel));
const int newY = std::max<int>(0, std::min<int>(maxY, y() + event.motion.yrel));
moveBy(newX - x(), newY - y());
return focusConsume(this, true);
}
return focusConsume(this, false);
}
case SDL_MOUSEBUTTONDOWN:
{
auto myHeroPtr = m_processRun->getMyHero();
auto &invPackRef = myHeroPtr->getInvPack();
auto lastGrabbedItem = invPackRef.getGrabbedItem();
switch(event.button.button){
case SDL_BUTTON_LEFT:
{
if(in(event.button.x, event.button.y)){
if(const int selectedPackIndex = getPackBinIndex(event.button.x, event.button.y); selectedPackIndex >= 0){
auto selectedPackBin = invPackRef.getPackBinList().at(selectedPackIndex);
invPackRef.setGrabbedItem(selectedPackBin.item);
invPackRef.remove(selectedPackBin.item);
if(lastGrabbedItem){
// when swapping
// prefer to use current location to store
invPackRef.add(lastGrabbedItem, selectedPackBin.x, selectedPackBin.y);
}
}
else if(lastGrabbedItem){
const auto [gridX, gridY] = getInvGrid(event.button.x, event.button.y);
const auto [gridW, gridH] = InvPack::getPackBinSize(lastGrabbedItem.itemID);
const auto startGridX = gridX - gridW / 2; // can give an invalid (x, y)
const auto startGridY = gridY - gridH / 2;
invPackRef.add(lastGrabbedItem, startGridX, startGridY);
invPackRef.setGrabbedItem({});
}
return focusConsume(this, true);
}
return focusConsume(this, false);
}
case SDL_BUTTON_RIGHT:
{
if(in(event.button.x, event.button.y)){
if(const int selectedPackIndex = getPackBinIndex(event.button.x, event.button.y); selectedPackIndex >= 0){
packBinConsume(invPackRef.getPackBinList().at(selectedPackIndex));
}
return focusConsume(this, true);
}
return focusConsume(this, false);
}
default:
{
return focusConsume(this, false);
}
}
}
case SDL_MOUSEWHEEL:
{
const auto [mousePX, mousePY] = SDLDeviceHelper::getMousePLoc();
if(mathf::pointInRectangle<int>(mousePX, mousePY, x() + m_invGridX0, y() + m_invGridY0, 6 * SYS_INVGRIDPW, 8 * SYS_INVGRIDPH)){
const auto rowCount = getRowCount();
if(rowCount > 8){
m_slider.addValue((event.wheel.y > 0 ? -1.0 : 1.0) / (rowCount - 8));
}
return focusConsume(this, true);
}
return false;
}
default:
{
return focusConsume(this, false);
}
}
}
std::string InventoryBoard::getGoldStr() const
{
return str_ksep([this]() -> int
{
if(auto p = m_processRun->getMyHero()){
return p->getGold();
}
return 0;
}(), ',');
}
size_t InventoryBoard::getRowCount() const
{
const auto &packBinList = m_processRun->getMyHero()->getInvPack().getPackBinList();
if(packBinList.empty()){
return 0;
}
size_t rowCount = 0;
for(const auto &bin: packBinList){
rowCount = std::max<size_t>(rowCount, bin.y + bin.h);
}
return rowCount;
}
size_t InventoryBoard::getStartRow() const
{
const size_t rowGfxCount = 8;
const size_t rowCount = getRowCount();
if(rowCount <= rowGfxCount){
return 0;
}
return std::lround((rowCount - rowGfxCount) * m_slider.getValue());
}
void InventoryBoard::drawGold() const
{
const LabelBoard goldBoard
{
DIR_UPLEFT,
0, // reset by new width
0,
to_u8cstr(getGoldStr()),
1,
12,
0,
colorf::RGBA(0XFF, 0XFF, 0X00, 0XFF),
};
goldBoard.drawAt(DIR_NONE, x() + 106, y() + 409);
}
int InventoryBoard::getPackBinIndex(int locPX, int locPY) const
{
const auto [gridX, gridY] = getInvGrid(locPX, locPY);
if(gridX < 0 || gridY < 0){
return -1;
}
const auto startRow = getStartRow();
const auto myHeroPtr = m_processRun->getMyHero();
const auto &packBinListCRef = myHeroPtr->getInvPack().getPackBinList();
for(int i = 0; i < to_d(packBinListCRef.size()); ++i){
const auto &binCRef = packBinListCRef.at(i);
if(mathf::pointInRectangle<int>(gridX, gridY, binCRef.x, binCRef.y - startRow, binCRef.w, binCRef.h)){
return i;
}
}
return -1;
}
std::tuple<int, int> InventoryBoard::getInvGrid(int locPX, int locPY) const
{
const int gridPX0 = m_invGridX0 + x();
const int gridPY0 = m_invGridY0 + y();
if(!mathf::pointInRectangle<int>(locPX, locPY, gridPX0, gridPY0, 6 * SYS_INVGRIDPW, 8 * SYS_INVGRIDPH)){
return {-1, -1};
}
return
{
(locPX - gridPX0) / SYS_INVGRIDPW,
(locPY - gridPY0) / SYS_INVGRIDPH,
};
}
void InventoryBoard::drawItemHoverText(const PackBin &bin) const
{
const auto &ir = DBCOM_ITEMRECORD(bin.item.itemID);
const auto hoverText = str_printf
(
u8R"###( <layout> )###""\n"
u8R"###( <par>【名称】%s</par> )###""\n"
u8R"###( <par>【描述】%s</par> )###""\n"
u8R"###( </layout> )###""\n",
ir.name,
str_haschar(ir.description) ? ir.description : u8"游戏处于开发阶段,此物品暂无描述。"
);
LayoutBoard hoverTextBoard
{
DIR_UPLEFT,
0,
0,
200,
false,
{0, 0, 0, 0},
false,
1,
12,
0,
colorf::WHITE + 255,
0,
LALIGN_JUSTIFY,
};
hoverTextBoard.loadXML(to_cstr(hoverText));
const auto [mousePX, mousePY] = SDLDeviceHelper::getMousePLoc();
const auto textBoxW = std::max<int>(hoverTextBoard.w(), 200) + 20;
const auto textBoxH = hoverTextBoard.h() + 20;
g_sdlDevice->fillRectangle(colorf::RGBA(0, 0, 0, 200), mousePX, mousePY, textBoxW, textBoxH, 5);
g_sdlDevice->drawRectangle(colorf::RGBA(0, 0, 255, 255), mousePX, mousePY, textBoxW, textBoxH, 5);
hoverTextBoard.drawAt(DIR_UPLEFT, mousePX + 10, mousePY + 10);
}
void InventoryBoard::packBinConsume(const PackBin &bin)
{
const auto &ir = DBCOM_ITEMRECORD(bin.item.itemID);
if(false
|| to_u8sv(ir.type) == u8"恢复药水"
|| to_u8sv(ir.type) == u8"强化药水"
|| to_u8sv(ir.type) == u8"技能书"){
m_processRun->requestConsumeItem(bin.item.itemID, bin.item.seqID, 1);
}
}
| [
"anhonghe@gmail.com"
] | anhonghe@gmail.com |
4f8f3bae2902a4cf0c04e2e9fec2a6f27fcb5ed8 | 7f62f204ffde7fed9c1cb69e2bd44de9203f14c8 | /DboServer/Server/GameServer/BotAiAction_Escort.cpp | 240f0e6c9f8de42de0d4f8fe64f14f8fdea81fce | [] | no_license | 4l3dx/DBOGLOBAL | 9853c49f19882d3de10b5ca849ba53b44ab81a0c | c5828b24e99c649ae6a2953471ae57a653395ca2 | refs/heads/master | 2022-05-28T08:57:10.293378 | 2020-05-01T00:41:08 | 2020-05-01T00:41:08 | 259,094,679 | 3 | 3 | null | 2020-04-29T17:06:22 | 2020-04-26T17:43:08 | null | UTF-8 | C++ | false | false | 2,076 | cpp | #include "stdafx.h"
#include "BotAiAction_Escort.h"
#include "SPSNodeAction_Escort.h"
#include "BotAiAction_EscortFollow.h"
#include "BotAiState.h"
CBotAiAction_Escort::CBotAiAction_Escort(CNpc* pBot)
: CBotAiAction(pBot, BOTCONTROL_ACTION_DIRECT_PLAY, "BOTCONTROL_ACTION_DIRECT_PLAY")
{
m_eEscortType = INVALID_ESCORT_TYPE;
m_fRadius = 5.0f;
m_bRunMode = false;
m_eventID = INVALID_DWORD;
}
CBotAiAction_Escort::~CBotAiAction_Escort()
{
}
bool CBotAiAction_Escort::AttachControlScriptNode(CControlScriptNode* pControlScriptNode)
{
CSPSNodeAction_Escort* pAction = dynamic_cast<CSPSNodeAction_Escort*>(pControlScriptNode);
if (pAction)
{
m_eEscortType = pAction->m_eEscortType;
m_vDestLoc = pAction->m_vDestLoc;
m_fRadius = pAction->m_fRadius;
m_bRunMode = pAction->m_bRunMode;
m_eventID = pAction->m_eventID;
return true;
}
ERR_LOG(LOG_BOTAI, "fail : Can't dynamic_cast from CControlScriptNode[%X] to CSPSNodeAction_Escort", pControlScriptNode);
return false;
}
void CBotAiAction_Escort::OnEnter()
{
GetBot()->GetEscortManager()->Clear();
}
void CBotAiAction_Escort::OnExit()
{
}
int CBotAiAction_Escort::OnUpdate(DWORD dwTickDiff, float fMultiple)
{
return m_status;
}
int CBotAiAction_Escort::OnObjectMsg(CObjectMsg* pObjMsg) //on retail npc-server its OnEvent but we use objectmsg same as event because makes no sense to create event
{
if (pObjMsg->GetID() != OBJMSG_START_ESCORT)
return m_status;
CObjMsg_StartEscort* pMsg = check_cast<CObjMsg_StartEscort *>(pObjMsg);
if (!pMsg)
return m_status;
if (pMsg->m_byEscortType != m_eEscortType)
return m_status;
if (m_eEscortType == ESCORT_TYPE_TARGET_FOLLOW)
{
CBotAiState* pCurState = GetBot()->GetBotController()->GetCurrentState();
if (pCurState == NULL)
return m_status;
CBotAiAction_EscortFollow* pEscortFollow = new CBotAiAction_EscortFollow(GetBot(), m_vDestLoc, m_fRadius, m_bRunMode, m_eventID);
if (pCurState->AddSubControlQueue(pEscortFollow, true))
{
m_status = FAILED;
return m_status;
}
}
m_status = COMPLETED;
return m_status;
} | [
"64261665+dboguser@users.noreply.github.com"
] | 64261665+dboguser@users.noreply.github.com |
f09dbbfe499a36150b1b63d5b52c635b4d547c1e | 05f6bc4445a4e7d4dcf2d899520abd5ff5913599 | /trunk/VoiceEngine/audio_engine/modules/utility/source/audio_frame_operations.cc | ecda730daf905d175c0b64185712f7b23cedef3a | [] | no_license | XudongPan/audio-engine | c76deee93c751c5da2425b9ef56cf92337f191e6 | eea8b1f3943fb88088a90eab01d3572e49078eba | refs/heads/master | 2022-03-26T01:10:47.430520 | 2020-01-06T20:09:11 | 2020-01-06T20:09:11 | 32,212,042 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,977 | cc | #include "audio_engine/modules/interface/module_common_types.h"
#include "audio_engine/modules/utility/interface/audio_frame_operations.h"
namespace VoIP {
void AudioFrameOperations::MonoToStereo(const int16_t* src_audio,
int samples_per_channel,
int16_t* dst_audio) {
for (int i = 0; i < samples_per_channel; i++) {
dst_audio[2 * i] = src_audio[i];
dst_audio[2 * i + 1] = src_audio[i];
}
}
int AudioFrameOperations::MonoToStereo(AudioFrame* frame) {
if (frame->num_channels_ != 1) {
return -1;
}
if ((frame->samples_per_channel_ * 2) >= AudioFrame::kMaxDataSizeSamples) {
// Not enough memory to expand from mono to stereo.
return -1;
}
int16_t data_copy[AudioFrame::kMaxDataSizeSamples];
memcpy(data_copy, frame->data_,
sizeof(int16_t) * frame->samples_per_channel_);
MonoToStereo(data_copy, frame->samples_per_channel_, frame->data_);
frame->num_channels_ = 2;
return 0;
}
void AudioFrameOperations::StereoToMono(const int16_t* src_audio,
int samples_per_channel,
int16_t* dst_audio) {
for (int i = 0; i < samples_per_channel; i++) {
dst_audio[i] = (src_audio[2 * i] + src_audio[2 * i + 1]) >> 1;
}
}
int AudioFrameOperations::StereoToMono(AudioFrame* frame) {
if (frame->num_channels_ != 2) {
return -1;
}
StereoToMono(frame->data_, frame->samples_per_channel_, frame->data_);
frame->num_channels_ = 1;
return 0;
}
void AudioFrameOperations::SwapStereoChannels(AudioFrame* frame) {
if (frame->num_channels_ != 2) return;
for (int i = 0; i < frame->samples_per_channel_ * 2; i += 2) {
int16_t temp_data = frame->data_[i];
frame->data_[i] = frame->data_[i + 1];
frame->data_[i + 1] = temp_data;
}
}
void AudioFrameOperations::Mute(AudioFrame& frame) {
memset(frame.data_, 0, sizeof(int16_t) *
frame.samples_per_channel_ * frame.num_channels_);
frame.energy_ = 0;
}
int AudioFrameOperations::Scale(float left, float right, AudioFrame& frame) {
if (frame.num_channels_ != 2) {
return -1;
}
for (int i = 0; i < frame.samples_per_channel_; i++) {
frame.data_[2 * i] =
static_cast<int16_t>(left * frame.data_[2 * i]);
frame.data_[2 * i + 1] =
static_cast<int16_t>(right * frame.data_[2 * i + 1]);
}
return 0;
}
int AudioFrameOperations::ScaleWithSat(float scale, AudioFrame& frame) {
int32_t temp_data = 0;
// Ensure that the output result is saturated [-32768, +32767].
for (int i = 0; i < frame.samples_per_channel_ * frame.num_channels_;
i++) {
temp_data = static_cast<int32_t>(scale * frame.data_[i]);
if (temp_data < -32768) {
frame.data_[i] = -32768;
} else if (temp_data > 32767) {
frame.data_[i] = 32767;
} else {
frame.data_[i] = static_cast<int16_t>(temp_data);
}
}
return 0;
}
} // namespace VoIP
| [
"hawking81@gmail.com"
] | hawking81@gmail.com |
3161e4e9ca836dea1657c32bbab01941ec4cb567 | 2a8364c331fd6d052bf6001aa21ff8131830af0a | /boost/optional/stdafx.cpp | 2b1e85f26c8d3dcaf62fe4218b6c76deaf6f72ae | [] | no_license | sld666666/cpp_small_code | 5ceb3555be035079a9eb697707ebfc74c1ec3151 | aca310c403b2fd44da3d5a7924bc86c5944f8cc2 | refs/heads/master | 2021-01-10T22:03:12.161120 | 2014-08-25T15:27:48 | 2014-08-25T15:27:48 | 5,014,970 | 0 | 1 | null | null | null | null | GB18030 | C++ | false | false | 260 | cpp | // stdafx.cpp : 只包括标准包含文件的源文件
// optional.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// TODO: 在 STDAFX.H 中
// 引用任何所需的附加头文件,而不是在此文件中引用
| [
"sld666666@gmail.com"
] | sld666666@gmail.com |
a3e67b3f3d07fd3af99f1114b1d92233993c49f9 | b233702c5bb01514838ad6d3213f785f54f83ecb | /extra/chromium/files/patch-extensions_browser_api_serial_serial__api.cc | 8d02a3abb95dbdf00d447ddb5a30077385a24516 | [] | no_license | markzz/abs | f44d8d3c03653c7fec96f0702dd16c93790ea23e | f142c918c3d679b807f4548bcb926976364d0a8b | refs/heads/master | 2021-01-21T15:37:29.684333 | 2017-05-19T23:21:51 | 2017-05-19T23:21:51 | 91,852,456 | 0 | 0 | null | 2017-05-19T23:26:25 | 2017-05-19T23:26:25 | null | UTF-8 | C++ | false | false | 662 | cc | --- extensions/browser/api/serial/serial_api.cc.orig 2016-05-25 15:01:02.000000000 -0400
+++ extensions/browser/api/serial/serial_api.cc 2016-05-27 11:12:01.060235000 -0400
@@ -86,11 +86,13 @@
void SerialGetDevicesFunction::Work() {
DCHECK_CURRENTLY_ON(BrowserThread::FILE);
+#if !defined(OS_BSD)
scoped_ptr<device::SerialDeviceEnumerator> enumerator =
device::SerialDeviceEnumerator::Create();
mojo::Array<device::serial::DeviceInfoPtr> devices = enumerator->GetDevices();
results_ = serial::GetDevices::Results::Create(
devices.To<std::vector<serial::DeviceInfo>>());
+#endif
}
SerialConnectFunction::SerialConnectFunction() {
| [
"amzo@archbsd.com"
] | amzo@archbsd.com |
0c5133cbfe3992e3c5bdd3a0db9e4195f015f733 | e2ff72dedd26e6828803e85ff0aa5d8bc130c84c | /77.cpp | 5995a7279683aa9127d431ef3b119dc1e91af9f4 | [] | no_license | EggyJames/Leetcode | 533d67417d71f5daf8ebf0f5cb867065aa8f9fd5 | 2009b09672f8cd018be3456754b2492625f42d89 | refs/heads/master | 2022-05-04T22:44:38.614346 | 2022-04-29T09:12:28 | 2022-04-29T09:12:28 | 207,472,099 | 0 | 0 | null | 2022-04-22T01:26:34 | 2019-09-10T05:25:33 | C++ | UTF-8 | C++ | false | false | 567 | cpp | class Solution {
public:
vector<vector<int>>res;
vector<vector<int>> combine(int n, int k) {
if(n == 0 or k == 0 or n < k)
return res;
vector<int> path;
dfs(1,n,k,path);
return res;
}
void dfs(int start,int n,int k,vector<int> &path){
if(path.size() == k)
{
res.push_back(path);
return;
}
for(int i = start;i<=n-(k-path.size())+1;i++){
path.push_back(i);
dfs(i+1,n,k,path);
path.pop_back();
}
}
};
| [
"noreply@github.com"
] | EggyJames.noreply@github.com |
bdcfa4aa5b724b6ba93dedb1075261714d934925 | d0a6fc4f9a4a2d96451faa34cf99df92039ba9b3 | /ReactCommon/turbomodule/core/TurboModuleBinding.cpp | 5b370eede9ae6d59ee1db793982d65b0629779d5 | [
"CC-BY-4.0",
"CC-BY-NC-SA-4.0",
"CC-BY-SA-4.0",
"MIT"
] | permissive | kylieclin/local_pick2 | 2e8bc0ca0995e38dacf8cb3bfd0f9ef722bb82ce | d696fcee4615ad4cb70545dfdf1f074c452fa175 | refs/heads/master | 2023-01-08T19:10:45.790326 | 2019-12-13T01:22:23 | 2019-12-13T01:22:23 | 192,242,298 | 0 | 0 | MIT | 2023-01-04T00:42:59 | 2019-06-16T22:24:26 | JavaScript | UTF-8 | C++ | false | false | 2,343 | cpp | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "TurboModuleBinding.h"
#include <string>
#include <cxxreact/SystraceSection.h>
#include <jsireact/LongLivedObject.h>
using namespace facebook;
namespace facebook {
namespace react {
/**
* Public API to install the TurboModule system.
*/
TurboModuleBinding::TurboModuleBinding(const TurboModuleProviderFunctionType &moduleProvider)
: moduleProvider_(moduleProvider) {}
void TurboModuleBinding::install(
jsi::Runtime &runtime,
std::shared_ptr<TurboModuleBinding> binding) {
runtime.global().setProperty(
runtime,
"__turboModuleProxy",
jsi::Function::createFromHostFunction(
runtime,
jsi::PropNameID::forAscii(runtime, "__turboModuleProxy"),
1,
[binding](jsi::Runtime& rt, const jsi::Value& thisVal, const jsi::Value* args, size_t count) {
return binding->jsProxy(rt, thisVal, args, count);
}));
}
void TurboModuleBinding::invalidate() const {
// TODO (T45804587): Revisit this invalidation logic.
// The issue was that Promise resolve/reject functions that are invoked in
// some distance future might end up accessing PromiseWrapper that was already
// destroyed, if the binding invalidation removed it from the
// LongLivedObjectCollection.
// LongLivedObjectCollection::get().clear();
}
std::shared_ptr<TurboModule> TurboModuleBinding::getModule(const std::string &name) {
std::shared_ptr<TurboModule> module = nullptr;
{
SystraceSection s("TurboModuleBinding::getModule", "module", name);
module = moduleProvider_(name);
}
return module;
}
jsi::Value TurboModuleBinding::jsProxy(
jsi::Runtime& runtime,
const jsi::Value& thisVal,
const jsi::Value* args,
size_t count) {
if (count != 1) {
throw std::invalid_argument("TurboModuleBinding::jsProxy arg count must be 1");
}
std::string moduleName = args[0].getString(runtime).utf8(runtime);
std::shared_ptr<TurboModule> module = getModule(moduleName);
if (module == nullptr) {
return jsi::Value::null();
}
return jsi::Object::createFromHostObject(runtime, std::move(module));
}
} // namespace react
} // namespace facebook
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
d09caa8585ae593996bf75ed91e8d4477624461d | 9d1f6a1a84410652961fbff5aff437d7dc658eca | /Training001/Training001/stdafx.cpp | dc158effba270a4aec56478713ec5c540548c28e | [] | no_license | matei-re/holiday2018 | d46b87e1075a7a387a342b41fa09aca348bf775b | d22de5b887d979c4418ae2b5efa888a67f99e6e2 | refs/heads/master | 2020-03-21T09:26:01.955254 | 2018-08-01T16:02:57 | 2018-08-01T16:02:57 | 138,399,542 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 290 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Training001.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"re.matei@gmail.com"
] | re.matei@gmail.com |
4d46cb688a4ffb8aabeb3de832dd1624269181df | 9cea22db134f1fcec4ac14dfc8cf8f4fc123a14f | /test/test_json.cc | 14cd55410016c3a8f54f9bc1e921407bdb366020 | [] | no_license | plasorak/ptmp | d17e48c6c053378384e62da40afead94df3b5860 | 2718cd63cff564521d02ed8a5a3116f162d3f000 | refs/heads/master | 2020-04-25T05:23:33.034321 | 2019-06-25T23:40:22 | 2019-06-25T23:40:22 | 172,541,335 | 0 | 0 | null | 2019-02-25T16:23:14 | 2019-02-25T16:23:13 | null | UTF-8 | C++ | false | false | 626 | cc | #include "json.hpp"
#include <iostream>
using json = nlohmann::json;
int main()
{
// note, this isn't real JSON schema for anything in PTMP
auto jcfg = R"(
{
"name": "testcontrol",
"ports": [ ],
"type": "control",
"bind": "tcp://127.0.0.1:12345"
}
)"_json;
std::cout << jcfg.dump() << std::endl;
std::string type = jcfg["type"];
std::cout << "type: " << type << std::endl;
json cfg = { { "socket",
{
{ "type", jcfg["type"] },
{ "bind", jcfg["bind"] } }}};
std::cout << "cfg: " << cfg << std::endl;
return 0;
}
| [
"brett.viren@gmail.com"
] | brett.viren@gmail.com |
d141ab65cb1f6eb22265e5a12aaf937ca18c202d | f1bd4d38d8a279163f472784c1ead12920b70be2 | /xrFS/xr_ini.h | 31a13155f53ec242a0c87497706c1c3519d18552 | [] | no_license | YURSHAT/stk_2005 | 49613f4e4a9488ae5e3fd99d2b60fd9c6aca2c83 | b68bbf136688d57740fd9779423459ef5cbfbdbb | refs/heads/master | 2023-04-05T16:08:44.658227 | 2021-04-18T09:08:18 | 2021-04-18T18:35:59 | 361,129,668 | 1 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 6,152 | h | #ifndef xr_iniH
#define xr_iniH
// refs
class CInifile;
struct xr_token;
//-----------------------------------------------------------------------------------------------------------
//Описание Inifile
//-----------------------------------------------------------------------------------------------------------
class XRCORE_API CInifile
{
public:
struct XRCORE_API Item
{
shared_str first;
shared_str second;
shared_str comment;
Item() : first(0), second(0), comment(0) {};
};
typedef xr_vector<Item> Items;
typedef Items::iterator SectIt;
struct XRCORE_API Sect {
shared_str Name;
Items Data;
IC SectIt begin() { return Data.begin(); }
IC SectIt end() { return Data.end(); }
IC size_t size() { return Data.size(); }
IC void clear() { Data.clear(); }
BOOL line_exist (LPCSTR L, LPCSTR* val=0);
};
typedef xr_vector<Sect> Root;
typedef Root::iterator RootIt;
// factorisation
static CInifile* Create ( LPCSTR szFileName, BOOL ReadOnly=TRUE);
static void Destroy ( CInifile*);
static IC BOOL IsBOOL ( LPCSTR B) { return (xr_strcmp(B,"on")==0 || xr_strcmp(B,"yes")==0 || xr_strcmp(B,"true")==0 || xr_strcmp(B,"1")==0);}
private:
LPSTR fName;
Root DATA;
BOOL bReadOnly;
void Load (IReader* F, LPCSTR path);
public:
BOOL bSaveAtEnd;
public:
CInifile ( IReader* F, LPCSTR path=0 );
CInifile ( LPCSTR szFileName, BOOL ReadOnly=TRUE, BOOL bLoadAtStart=TRUE, BOOL SaveAtEnd=TRUE);
virtual ~CInifile ( );
bool save_as ( LPCSTR new_fname=0 );
LPCSTR fname ( ) { return fName; };
Sect& r_section ( LPCSTR S );
Sect& r_section ( const shared_str& S );
BOOL line_exist ( LPCSTR S, LPCSTR L );
BOOL line_exist ( const shared_str& S, const shared_str& L );
u32 line_count ( LPCSTR S );
u32 line_count ( const shared_str& S );
BOOL section_exist ( LPCSTR S );
BOOL section_exist ( const shared_str& S );
Root& sections ( ){return DATA;}
CLASS_ID r_clsid ( LPCSTR S, LPCSTR L );
CLASS_ID r_clsid ( const shared_str& S, LPCSTR L ) { return r_clsid(*S,L); }
LPCSTR r_string ( LPCSTR S, LPCSTR L); // оставляет кавычки
LPCSTR r_string ( const shared_str& S, LPCSTR L) { return r_string(*S,L); } // оставляет кавычки
shared_str r_string_wb ( LPCSTR S, LPCSTR L); // убирает кавычки
shared_str r_string_wb ( const shared_str& S, LPCSTR L) { return r_string_wb(*S,L); } // убирает кавычки
u8 r_u8 ( LPCSTR S, LPCSTR L );
u8 r_u8 ( const shared_str& S, LPCSTR L ) { return r_u8(*S,L); }
u16 r_u16 ( LPCSTR S, LPCSTR L );
u16 r_u16 ( const shared_str& S, LPCSTR L ) { return r_u16(*S,L); }
u32 r_u32 ( LPCSTR S, LPCSTR L );
u32 r_u32 ( const shared_str& S, LPCSTR L ) { return r_u32(*S,L); }
s8 r_s8 ( LPCSTR S, LPCSTR L );
s8 r_s8 ( const shared_str& S, LPCSTR L ) { return r_s8(*S,L); }
s16 r_s16 ( LPCSTR S, LPCSTR L );
s16 r_s16 ( const shared_str& S, LPCSTR L ) { return r_s16(*S,L); }
s32 r_s32 ( LPCSTR S, LPCSTR L );
s32 r_s32 ( const shared_str& S, LPCSTR L ) { return r_s32(*S,L); }
float r_float ( LPCSTR S, LPCSTR L );
float r_float ( const shared_str& S, LPCSTR L ) { return r_float(*S,L); }
Fcolor r_fcolor ( LPCSTR S, LPCSTR L );
Fcolor r_fcolor ( const shared_str& S, LPCSTR L ) { return r_fcolor(*S,L); }
u32 r_color ( LPCSTR S, LPCSTR L );
u32 r_color ( const shared_str& S, LPCSTR L ) { return r_color(*S,L); }
Ivector2 r_ivector2 ( LPCSTR S, LPCSTR L );
Ivector2 r_ivector2 ( const shared_str& S, LPCSTR L ) { return r_ivector2(*S,L); }
Ivector3 r_ivector3 ( LPCSTR S, LPCSTR L );
Ivector3 r_ivector3 ( const shared_str& S, LPCSTR L ) { return r_ivector3(*S,L); }
Ivector4 r_ivector4 ( LPCSTR S, LPCSTR L );
Ivector4 r_ivector4 ( const shared_str& S, LPCSTR L ) { return r_ivector4(*S,L); }
Fvector2 r_fvector2 ( LPCSTR S, LPCSTR L );
Fvector2 r_fvector2 ( const shared_str& S, LPCSTR L ) { return r_fvector2(*S,L); }
Fvector3 r_fvector3 ( LPCSTR S, LPCSTR L );
Fvector3 r_fvector3 ( const shared_str& S, LPCSTR L ) { return r_fvector3(*S,L); }
Fvector4 r_fvector4 ( LPCSTR S, LPCSTR L );
Fvector4 r_fvector4 ( const shared_str& S, LPCSTR L ) { return r_fvector4(*S,L); }
BOOL r_bool ( LPCSTR S, LPCSTR L );
BOOL r_bool ( const shared_str& S, LPCSTR L ) { return r_bool(*S,L); }
int r_token ( LPCSTR S, LPCSTR L, const xr_token *token_list);
BOOL r_line ( LPCSTR S, int L, LPCSTR* N, LPCSTR* V );
BOOL r_line ( const shared_str& S, int L, LPCSTR* N, LPCSTR* V );
void w_string ( LPCSTR S, LPCSTR L, LPCSTR V, LPCSTR comment=0 );
void w_u8 ( LPCSTR S, LPCSTR L, u8 V, LPCSTR comment=0 );
void w_u16 ( LPCSTR S, LPCSTR L, u16 V, LPCSTR comment=0 );
void w_u32 ( LPCSTR S, LPCSTR L, u32 V, LPCSTR comment=0 );
void w_s8 ( LPCSTR S, LPCSTR L, s8 V, LPCSTR comment=0 );
void w_s16 ( LPCSTR S, LPCSTR L, s16 V, LPCSTR comment=0 );
void w_s32 ( LPCSTR S, LPCSTR L, s32 V, LPCSTR comment=0 );
void w_float ( LPCSTR S, LPCSTR L, float V, LPCSTR comment=0 );
void w_fcolor ( LPCSTR S, LPCSTR L, const Fcolor& V, LPCSTR comment=0 );
void w_color ( LPCSTR S, LPCSTR L, u32 V, LPCSTR comment=0 );
void w_ivector2 ( LPCSTR S, LPCSTR L, const Ivector2& V, LPCSTR comment=0 );
void w_ivector3 ( LPCSTR S, LPCSTR L, const Ivector3& V, LPCSTR comment=0 );
void w_ivector4 ( LPCSTR S, LPCSTR L, const Ivector4& V, LPCSTR comment=0 );
void w_fvector2 ( LPCSTR S, LPCSTR L, const Fvector2& V, LPCSTR comment=0 );
void w_fvector3 ( LPCSTR S, LPCSTR L, const Fvector3& V, LPCSTR comment=0 );
void w_fvector4 ( LPCSTR S, LPCSTR L, const Fvector4& V, LPCSTR comment=0 );
void w_bool ( LPCSTR S, LPCSTR L, BOOL V, LPCSTR comment=0 );
void remove_line ( LPCSTR S, LPCSTR L );
};
// Main configuration file
extern XRCORE_API CInifile *pSettings;
#endif //__XR_INI_H__
| [
"loxotron@bk.ru"
] | loxotron@bk.ru |
79fca7ded61a43d50d58b437f972fbac21d2c716 | 5ec61911b971de3deb2e98b3fe92df1bba63db77 | /prj_4/obj_dir/Vmem__Syms.h | 243b42c70bd995cc4875679e876a88b992f08c7d | [] | no_license | nchronas/verilator_examples | 574ff2a9505ff47e33ae2861d61236ceb98678eb | 3fab42395a02f762ccfff7b71ad2f6bc4801e28d | refs/heads/master | 2021-01-23T16:53:00.316724 | 2017-06-09T10:53:38 | 2017-06-09T10:53:38 | 93,307,996 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 948 | h | // Verilated -*- C++ -*-
// DESCRIPTION: Verilator output: Symbol table internal header
//
// Internal details; most calling programs do not need this header
#ifndef _Vmem__Syms_H_
#define _Vmem__Syms_H_
#include "verilated_heavy.h"
// INCLUDE MODULE CLASSES
#include "Vmem.h"
// SYMS CLASS
class Vmem__Syms : public VerilatedSyms {
public:
// LOCAL STATE
const char* __Vm_namep;
bool __Vm_activity; ///< Used by trace routines to determine change occurred
bool __Vm_didInit;
//char __VpadToAlign10[6];
// SUBCELL STATE
Vmem* TOPp;
// COVERAGE
// SCOPE NAMES
// CREATORS
Vmem__Syms(Vmem* topp, const char* namep);
~Vmem__Syms() {};
// METHODS
inline const char* name() { return __Vm_namep; }
inline bool getClearActivity() { bool r=__Vm_activity; __Vm_activity=false; return r;}
} VL_ATTR_ALIGNED(64);
#endif /*guard*/
| [
"nchronas@gmail.com"
] | nchronas@gmail.com |
0d9c96dbcf644b59d230a641dd309e56aead34a7 | 703554ad9d972e2d467a5ed89f1e0109cab55e89 | /CodeForces/895E.cpp | 4c076a1b035990079aa321b14951700ad480b022 | [] | no_license | OmarMekkawy/Problems-Solved-Codes | 2b3c3ecad323dbaff787cfe4f84688fe912de6d4 | 3569125af8c80995006cd049bc7d607689c7e17e | refs/heads/master | 2021-09-12T18:13:15.826373 | 2018-04-19T19:35:06 | 2018-04-19T19:35:06 | 113,561,178 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,347 | cpp | #include <bits/stdc++.h>
using namespace std;
#define debug(x) cout<<#x<<"->"<<x<<endl;
double arr[100001];
double segmentTree[400005];
double lazy1[400001],lazy2[400001];
void Build(int st,int ed,int idx)
{
if(st==ed){
segmentTree[idx]=arr[st];
return;
}
Build(st,(st+ed)>>1,idx*2);
Build(((st+ed)>>1)+1,ed,idx*2+1);
segmentTree[idx]=segmentTree[idx*2]+segmentTree[idx*2+1];
return;
}
void lazy(int st,int ed,int idx,double mul=1,double add=0)
{
lazy2[idx]*=mul;
lazy2[idx]+=(1.0-mul)*add;
segmentTree[idx]=segmentTree[idx]*mul*lazy1[idx]+lazy2[idx]*(1.0+ed-st);
if(st!=ed){
lazy1[idx*2]*=lazy1[idx]*mul;
lazy2[idx*2]*=lazy1[idx]*mul;
lazy2[idx*2]+=lazy2[idx];
lazy1[idx*2+1]*=lazy1[idx]*mul;
lazy2[idx*2+1]*=lazy1[idx]*mul;
lazy2[idx*2+1]+=lazy2[idx];
}
lazy1[idx]=1;
lazy2[idx]=0;
return;
}
double Query(int st,int ed,int idx,int &qst,int &qed)
{
lazy(st,ed,idx);
if(st>=qst&&ed<=qed)
return segmentTree[idx];
if(st>qed||ed<qst)
return 0;
return Query(st,(st+ed)>>1,idx*2,qst,qed)+Query(((st+ed)>>1)+1,ed,idx*2+1,qst,qed);
}
void Update(int st,int ed,int idx,int &ust,int &ued,double val,double prob)
{
lazy(st,ed,idx);
if(ued<st||ust>ed)
return;
if(st>=ust&&ed<=ued){
lazy(st,ed,idx,prob,val);
return ;
}
Update(st,(st+ed)>>1,idx*2,ust,ued,val,prob);
Update(((st+ed)>>1)+1,ed,idx*2+1,ust,ued,val,prob);
segmentTree[idx]=segmentTree[idx*2]+segmentTree[idx*2+1];
return;
}
int main()
{
for(int i=0;i<400001;i++)
lazy1[i]=1;
int n,q;
scanf("%d%d",&n,&q);
for(int i=1;i<=n;i++)
scanf("%lf",&arr[i]);
Build(1,n,1);
while(q--){
int type;
scanf("%d",&type);
if(type==1){
int l1,r1,l2,r2;
scanf("%d%d%d%d",&l1,&r1,&l2,&r2);
double cursum=(double)Query(1,n,1,l1,r1)/(double)(r1-l1+1);
double cursum2=(double)Query(1,n,1,l2,r2)/(double)(r2-l2+1);
Update(1,n,1,l1,r1,cursum2,1.0-1.0/(r1-l1+1.0));
Update(1,n,1,l2,r2,cursum,1.0-1.0/(r2-l2+1.0));
}
else{
int l1,r1;
scanf("%d%d",&l1,&r1);
printf("%.8f\n",Query(1,n,1,l1,r1));
}
}
return 0;
}
| [
"noreply@github.com"
] | OmarMekkawy.noreply@github.com |
f94f59e3ac65a3a0451c0ac3c0142e540c8e7cfd | 3d424a8d682d4e056668b5903206ccc603f6e997 | /NeoGUI/GUI/DetailsView.h | 363cb75cdd2748cb83d190ba1fd81898ee189d1a | [] | no_license | markus851/NeoLoader | 515e238b385354b83bbc4f7399a85524d5b03d12 | 67c9b642054ead500832406a9c301a7b4cbfffd3 | refs/heads/master | 2022-04-22T07:51:15.418184 | 2015-05-08T11:37:53 | 2015-05-08T11:37:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,333 | h | #pragma once
class CCoverView;
#include "ProgressBar.h"
class CDetailsView: public QWidget
{
Q_OBJECT
public:
CDetailsView(UINT Mode, QWidget *parent = 0);
~CDetailsView();
void ShowDetails(uint64 ID);
void ChangeMode(UINT Mode) {m_Mode = Mode;}
public slots:
void UpdateDetails();
void OnMenuRequested(const QPoint &point);
void OnSetFileName();
void OnSetRating();
void OnEnableSubmit();
void OnCopyHash();
void OnSetMaster();
void OnAddHash();
void OnRemoveHash();
void OnSelectHash();
void OnBanHash();
protected:
virtual void timerEvent(QTimerEvent *e);
int m_TimerId;
uint64 m_ID;
UINT m_Mode;
friend class CDetailsUpdateJob;
friend class CDetailsApplyJob;
QVBoxLayout* m_pMainLayout;
CProgressBar* m_pProgress;
QWidget* m_pWidget;
QHBoxLayout* m_pLayout;
QWidget* m_pDetailWidget;
QFormLayout* m_pDetailLayout;
QLineEdit* m_pFileName;
QTextEdit* m_pDescription;
QComboBox* m_pRating;
QLabel* m_pInfo;
QPushButton* m_pSubmit;
QTableWidget* m_pHashes;
QMenu* m_pMenu;
QAction* m_pCopyHash;
QAction* m_pSetMaster;
QAction* m_pAddHash;
QAction* m_pRemoveHash;
QAction* m_pSelectHash;
QAction* m_pBanHash;
CCoverView* m_pCoverView;
bool m_IsComplete;
bool m_bLockDown;
}; | [
"David@X.com"
] | David@X.com |
1a40b4bd152f233514804147978b6671730e9d8a | ad1a88ead2b277336de54dd79379184024ac1def | /ResultParser/ResultParser.cpp | ad790d78b91cc7b775faac393b10d1302f549f8e | [
"MIT"
] | permissive | jstarks/diskspd | 96425ac9a04d0a442c2df94383946bc405aabd51 | 4c039d49ff0e2acdcf3c8dd471f8809e8bf76143 | refs/heads/master | 2021-01-18T05:58:59.356875 | 2014-10-29T22:54:33 | 2014-10-29T22:54:33 | 26,157,780 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,504 | cpp | /*
DISKSPD
Copyright(c) Microsoft Corporation
All rights reserved.
MIT License
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.
*/
// ResultParser.cpp : Defines the entry point for the DLL application.
//
#include "ResultParser.h"
#include "common.h"
#include <stdio.h>
#include <stdlib.h>
#include <Winternl.h> //ntdll.dll
#include <Wmistr.h> //WNODE_HEADER
#include <Evntrace.h>
#include <assert.h>
// TODO: refactor to a single function shared with the XmlResultParser
void ResultParser::_Print(const char *format, ...)
{
assert(nullptr != format);
va_list listArg;
va_start(listArg, format);
char buffer[4096] = {};
vsprintf_s(buffer, _countof(buffer), format, listArg);
va_end(listArg);
_sResult += buffer;
}
/*****************************************************************************/
// display file size in a user-friendly form
//
void ResultParser::_DisplayFileSize(UINT64 fsize)
{
if( fsize > (UINT64)10*1024*1024*1024 ) // > 10GB
{
_Print("%uGB", fsize >> 30);
}
else if( fsize > (UINT64)10*1024*1024 ) // > 10MB
{
_Print("%uMB", fsize >> 20);
}
else if( fsize > 10*1024 ) // > 10KB
{
_Print("%uKB", fsize >> 10);
}
else
{
_Print("%I64uB", fsize);
}
}
/*****************************************************************************/
void ResultParser::_DisplayETWSessionInfo(struct ETWSessionInfo sessionInfo)
{
_Print("\n\n");
_Print(" ETW Buffer Settings & Statistics\n");
_Print("--------------------------------------------------------\n");
_Print("(KB) Buffers (Secs) (Mins)\n");
_Print("Size | Min | Max | Free | Written | Flush Age\n");
_Print("%-5lu %5lu %-5lu %-2lu %8lu %8lu %8d\n\n",
sessionInfo.ulBufferSize,
sessionInfo.ulMinimumBuffers,
sessionInfo.ulMaximumBuffers,
sessionInfo.ulFreeBuffers,
sessionInfo.ulBuffersWritten,
sessionInfo.ulFlushTimer,
sessionInfo.lAgeLimit);
_Print("Allocated Buffers: %lu\n",
sessionInfo.ulNumberOfBuffers);
_Print("LOST EVENTS:%15lu\n",
sessionInfo.ulEventsLost);
_Print("LOST LOG BUFFERS:%10lu\n",
sessionInfo.ulLogBuffersLost);
_Print("LOST REAL TIME BUFFERS:%4lu\n",
sessionInfo.ulRealTimeBuffersLost);
}
/*****************************************************************************/
void ResultParser::_DisplayETW(struct ETWMask ETWMask, struct ETWEventCounters EtwEventCounters)
{
_Print("\n\n\nETW:\n");
_Print("----\n\n");
if (ETWMask.bDiskIO)
{
_Print("\tDisk I/O\n");
_Print("\t\tRead: %I64u\n", EtwEventCounters.ullIORead);
_Print("\t\tWrite: %I64u\n", EtwEventCounters.ullIOWrite);
}
if (ETWMask.bImageLoad)
{
_Print("\tLoad Image\n");
_Print("\t\tLoad Image: %I64u\n", EtwEventCounters.ullImageLoad);
}
if (ETWMask.bMemoryPageFaults)
{
_Print("\tMemory Page Faults\n");
_Print("\t\tCopy on Write: %I64u\n", EtwEventCounters.ullMMCopyOnWrite);
_Print("\t\tDemand Zero fault: %I64u\n", EtwEventCounters.ullMMDemandZeroFault);
_Print("\t\tGuard Page fault: %I64u\n", EtwEventCounters.ullMMGuardPageFault);
_Print("\t\tHard page fault: %I64u\n", EtwEventCounters.ullMMHardPageFault);
_Print("\t\tTransition fault: %I64u\n", EtwEventCounters.ullMMTransitionFault);
}
if (ETWMask.bMemoryHardFaults && !ETWMask.bMemoryPageFaults )
{
_Print("\tMemory Hard Faults\n");
_Print("\t\tHard page fault: %I64u\n", EtwEventCounters.ullMMHardPageFault);
}
if (ETWMask.bNetwork)
{
_Print("\tNetwork\n");
_Print("\t\tAccept: %I64u\n", EtwEventCounters.ullNetAccept);
_Print("\t\tConnect: %I64u\n", EtwEventCounters.ullNetConnect);
_Print("\t\tDisconnect: %I64u\n", EtwEventCounters.ullNetDisconnect);
_Print("\t\tReconnect: %I64u\n", EtwEventCounters.ullNetReconnect);
_Print("\t\tRetransmit: %I64u\n", EtwEventCounters.ullNetRetransmit);
_Print("\t\tTCP/IP Send: %I64u\n", EtwEventCounters.ullNetTcpSend);
_Print("\t\tTCP/IP Receive: %I64u\n", EtwEventCounters.ullNetTcpReceive);
_Print("\t\tUDP/IP Send: %I64u\n", EtwEventCounters.ullNetUdpSend);
_Print("\t\tUDP/IP Receive: %I64u\n", EtwEventCounters.ullNetUdpReceive);
}
if (ETWMask.bProcess)
{
_Print("\tProcess\n");
_Print("\t\tStart: %I64u\n", EtwEventCounters.ullProcessStart);
_Print("\t\tEnd: %I64u\n", EtwEventCounters.ullProcessEnd);
}
if (ETWMask.bRegistry)
{
_Print("\tRegistry\n");
_Print("\t\tNtCreateKey: %I64u\n",
EtwEventCounters.ullRegCreate);
_Print("\t\tNtDeleteKey: %I64u\n",
EtwEventCounters.ullRegDelete);
_Print("\t\tNtDeleteValueKey: %I64u\n",
EtwEventCounters.ullRegDeleteValue);
_Print("\t\tNtEnumerateKey: %I64u\n",
EtwEventCounters.ullRegEnumerateKey);
_Print("\t\tNtEnumerateValueKey: %I64u\n",
EtwEventCounters.ullRegEnumerateValueKey);
_Print("\t\tNtFlushKey: %I64u\n",
EtwEventCounters.ullRegFlush);
_Print("\t\tKcbDump/create: %I64u\n",
EtwEventCounters.ullRegKcbDmp);
_Print("\t\tNtOpenKey: %I64u\n",
EtwEventCounters.ullRegOpen);
_Print("\t\tNtQueryKey: %I64u\n",
EtwEventCounters.ullRegQuery);
_Print("\t\tNtQueryMultipleValueKey: %I64u\n",
EtwEventCounters.ullRegQueryMultipleValue);
_Print("\t\tNtQueryValueKey: %I64u\n",
EtwEventCounters.ullRegQueryValue);
_Print("\t\tNtSetInformationKey: %I64u\n",
EtwEventCounters.ullRegSetInformation);
_Print("\t\tNtSetValueKey: %I64u\n",
EtwEventCounters.ullRegSetValue);
}
if (ETWMask.bThread)
{
_Print("\tThread\n");
_Print("\t\tStart: %I64u\n", EtwEventCounters.ullThreadStart);
_Print("\t\tEnd: %I64u\n", EtwEventCounters.ullThreadEnd);
}
}
void ResultParser::_PrintTarget(Target target, bool fUseThreadsPerFile, bool fCompletionRoutines)
{
_Print("\tpath: '%s'\n", target.GetPath().c_str());
_Print("\t\tthink time: %ums\n", target.GetThinkTime());
_Print("\t\tburst size: %u\n", target.GetBurstSize());
// TODO: completion routines/ports
if (target.GetDisableAllCache())
{
_Print("\t\tsoftware and hardware write cache disabled\n");
}
if (target.GetDisableOSCache())
{
_Print("\t\tsoftware cache disabled\n");
}
if (!target.GetDisableAllCache() && !target.GetDisableOSCache())
{
_Print("\t\tusing software and hardware write cache\n");
}
if (target.GetZeroWriteBuffers())
{
_Print("\t\tzeroing write buffers\n");
}
if (target.GetRandomDataWriteBufferSize() > 0)
{
_Print("\t\twrite buffer size: %I64u\n", target.GetRandomDataWriteBufferSize());
string sWriteBufferSourcePath = target.GetRandomDataWriteBufferSourcePath();
if (sWriteBufferSourcePath != "")
{
_Print("\t\twrite buffer source: '%s'\n", sWriteBufferSourcePath.c_str());
}
}
if (target.GetUseParallelAsyncIO())
{
_Print("\t\tusing parallel async I/O\n");
}
if (target.GetWriteRatio() == 0)
{
_Print("\t\tperforming read test\n");
}
else if (target.GetWriteRatio() == 100)
{
_Print("\t\tperforming write test\n");
}
else
{
_Print("\t\tperforming mix test (write/read ratio: %d/100)\n", target.GetWriteRatio());
}
_Print("\t\tblock size: %d\n", target.GetBlockSizeInBytes());
if (target.GetRandomAlignmentInBytes() != 0)
{
_Print("\t\tusing random I/O (alignment: %I64u)\n", target.GetRandomAlignmentInBytes());
}
_Print("\t\tnumber of outstanding I/O operations: %d\n", target.GetRequestCount());
if (0 != target.GetBaseFileOffsetInBytes())
{
_Print("\t\tbase file offset: %I64u\n", target.GetBaseFileOffsetInBytes());
}
if (0 != target.GetMaxFileSize())
{
_Print("\t\tmax file size: %I64u\n", target.GetMaxFileSize());
}
_Print("\t\tstride size: %I64u\n", target.GetStrideSizeInBytes());
_Print("\t\tthread stride size: %I64u\n", target.GetThreadStrideInBytes());
if (target.GetSequentialScan())
{
_Print("\t\tusing FILE_FLAG_SEQUENTIAL_SCAN hint\n");
}
if (target.GetRandomAccess())
{
_Print("\t\tusing FILE_FLAG_RANDOM_ACCESS hint\n");
}
if (fUseThreadsPerFile)
{
_Print("\t\tthreads per file: %d\n", target.GetThreadsPerFile());
}
if (target.GetRequestCount() > 1 && fUseThreadsPerFile)
{
if (fCompletionRoutines)
{
_Print("\t\tusing completion routines (ReadFileEx/WriteFileEx)\n");
}
else
{
_Print("\t\tusing I/O Completion Ports\n");
}
}
if (target.GetIOPriorityHint() == IoPriorityHintVeryLow)
{
_Print("\t\tIO priority: very low\n");
}
else if (target.GetIOPriorityHint() == IoPriorityHintLow)
{
_Print("\t\tIO priority: low\n");
}
else if (target.GetIOPriorityHint() == IoPriorityHintNormal)
{
_Print("\t\tIO priority: normal\n");
}
else
{
_Print("\t\tIO priority: unknown\n");
}
}
void ResultParser::_PrintTimeSpan(TimeSpan timeSpan)
{
_Print("\tduration: %us\n", timeSpan.GetDuration());
_Print("\twarm up time: %us\n", timeSpan.GetWarmup());
_Print("\tcool down time: %us\n", timeSpan.GetCooldown());
if (timeSpan.GetDisableAffinity())
{
_Print("\taffinity disabled\n");
}
if (timeSpan.GetMeasureLatency())
{
_Print("\tmeasuring latency\n");
}
if (timeSpan.GetCalculateIopsStdDev())
{
_Print("\tcalculating IOPS stddev with bucket duration = %u milliseconds\n", timeSpan.GetIoBucketDurationInMilliseconds());
}
_Print("\trandom seed: %u\n", timeSpan.GetRandSeed());
vector<UINT32> vAffinity = timeSpan.GetAffinityAssignments();
if ( vAffinity.size() > 0)
{
_Print("\tadvanced affinity: ");
for (unsigned int x = 0; x < vAffinity.size(); ++x)
{
_Print("%d", vAffinity[x]);
if (x < vAffinity.size() - 1)
{
_Print(", ");
}
}
_Print("\n");
}
vector<Target> vTargets(timeSpan.GetTargets());
for (auto i = vTargets.begin(); i != vTargets.end(); i++)
{
_PrintTarget(*i, (timeSpan.GetThreadCount() == 0), timeSpan.GetCompletionRoutines());
}
}
void ResultParser::_PrintProfile(Profile profile)
{
_Print("\nCommand Line: %s\n", profile.GetCmdLine().c_str());
_Print("\n");
_Print("Input parameters:\n\n");
if (profile.GetVerbose())
{
_Print("\tusing verbose mode\n");
}
vector<TimeSpan> vTimeSpans(profile.GetTimeSpans());
int c = 1;
for (auto i = vTimeSpans.begin(); i != vTimeSpans.end(); i++)
{
_Print("\ttimespan: %3d\n", c++);
_Print("\t-------------\n");
_PrintTimeSpan(*i);
_Print("\n");
}
}
void ResultParser::_PrintCpuUtilization(const Results& results)
{
size_t ulProcCount = results.vSystemProcessorPerfInfo.size();
double fTime = PerfTimer::PerfTimeToSeconds(results.ullTimeCount);
char szFloatBuffer[1024];
_Print("\nCPU | Usage | User | Kernel | Idle\n");
_Print("-------------------------------------------\n");
double busyTime = 0;
double totalIdleTime = 0;
double totalUserTime = 0;
double totalKrnlTime = 0;
for (unsigned int x = 0; x<ulProcCount; ++x)
{
double idleTime;
double userTime;
double krnlTime;
double thisTime;
idleTime = 100.0 * results.vSystemProcessorPerfInfo[x].IdleTime.QuadPart / 10000000 / fTime;
krnlTime = 100.0 * results.vSystemProcessorPerfInfo[x].KernelTime.QuadPart / 10000000 / fTime;
userTime = 100.0 * results.vSystemProcessorPerfInfo[x].UserTime.QuadPart / 10000000 / fTime;
thisTime = (krnlTime + userTime) - idleTime;
sprintf_s(szFloatBuffer, sizeof(szFloatBuffer), "%4u| %6.2lf%%| %6.2lf%%| %6.2lf%%| %6.2lf%%\n",
x,
thisTime,
userTime,
krnlTime - idleTime,
idleTime);
_Print("%s", szFloatBuffer);
busyTime += thisTime;
totalIdleTime += idleTime;
totalUserTime += userTime;
totalKrnlTime += krnlTime;
}
_Print("-------------------------------------------\n");
sprintf_s(szFloatBuffer, sizeof(szFloatBuffer), "avg.| %6.2lf%%| %6.2lf%%| %6.2lf%%| %6.2lf%%\n",
busyTime / ulProcCount,
totalUserTime / ulProcCount,
(totalKrnlTime - totalIdleTime) / ulProcCount,
totalIdleTime / ulProcCount);
_Print("%s", szFloatBuffer);
}
void ResultParser::_PrintSectionFieldNames(const TimeSpan& timeSpan)
{
_Print("thread | bytes | I/Os | MB/s | I/O per s %s%s%s| file\n",
timeSpan.GetMeasureLatency() ? "| AvgLat " : "",
timeSpan.GetCalculateIopsStdDev() ? "| IopsStdDev " : "",
timeSpan.GetMeasureLatency() ? "| LatStdDev " : "");
}
void ResultParser::_PrintSectionBorderLine(const TimeSpan& timeSpan)
{
_Print("------------------------------------------------------------------%s%s%s------------\n",
timeSpan.GetMeasureLatency() ? "-----------" : "" ,
timeSpan.GetCalculateIopsStdDev() ? "-------------" : "",
timeSpan.GetMeasureLatency() ? "------------" : "");
}
void ResultParser::_PrintSection(_SectionEnum section, const TimeSpan& timeSpan, const Results& results)
{
double fTime = PerfTimer::PerfTimeToSeconds(results.ullTimeCount);
double fBucketTime = timeSpan.GetIoBucketDurationInMilliseconds() / 1000.0;
UINT64 ullTotalBytesCount = 0;
UINT64 ullTotalIOCount = 0;
Histogram<float> totalLatencyHistogram;
IoBucketizer totalIoBucketizer;
_PrintSectionFieldNames(timeSpan);
_PrintSectionBorderLine(timeSpan);
for (unsigned int iThread = 0; iThread < results.vThreadResults.size(); ++iThread)
{
ThreadResults threadResults = results.vThreadResults[iThread];
for (unsigned int iFile = 0; iFile < threadResults.vTargetResults.size(); iFile++)
{
TargetResults targetResults = threadResults.vTargetResults[iFile];
UINT64 ullBytesCount = 0;
UINT64 ullIOCount = 0;
Histogram<float> latencyHistogram;
IoBucketizer ioBucketizer;
if ((section == _SectionEnum::WRITE) || (section == _SectionEnum::TOTAL))
{
ullBytesCount += targetResults.ullWriteBytesCount;
ullIOCount += targetResults.ullWriteIOCount;
if (timeSpan.GetMeasureLatency())
{
latencyHistogram.Merge(targetResults.writeLatencyHistogram);
totalLatencyHistogram.Merge(targetResults.writeLatencyHistogram);
}
if (timeSpan.GetCalculateIopsStdDev())
{
ioBucketizer.Merge(targetResults.writeBucketizer);
totalIoBucketizer.Merge(targetResults.writeBucketizer);
}
}
if ((section == _SectionEnum::READ) || (section == _SectionEnum::TOTAL))
{
ullBytesCount += targetResults.ullReadBytesCount;
ullIOCount += targetResults.ullReadIOCount;
if (timeSpan.GetMeasureLatency())
{
latencyHistogram.Merge(targetResults.readLatencyHistogram);
totalLatencyHistogram.Merge(targetResults.readLatencyHistogram);
}
if (timeSpan.GetCalculateIopsStdDev())
{
ioBucketizer.Merge(targetResults.readBucketizer);
totalIoBucketizer.Merge(targetResults.readBucketizer);
}
}
_Print("%6u | %15llu | %12llu | %10.2f | %10.2f",
iThread,
ullBytesCount,
ullIOCount,
(double)ullBytesCount / 1024 / 1024 / fTime,
(double)ullIOCount / fTime);
if (timeSpan.GetMeasureLatency())
{
double avgLat = latencyHistogram.GetAvg()/1000;
_Print(" | %8.3f", avgLat);
}
if (timeSpan.GetCalculateIopsStdDev())
{
double iopsStdDev = ioBucketizer.GetStandardDeviation() / fBucketTime;
_Print(" | %10.2f", iopsStdDev);
}
if (timeSpan.GetMeasureLatency())
{
if (latencyHistogram.GetSampleSize() > 0)
{
double latStdDev = latencyHistogram.GetStandardDeviation() / 1000;
_Print(" | %8.3f", latStdDev);
}
else
{
_Print(" | N/A");
}
}
_Print(" | %s (", targetResults.sPath.c_str());
_DisplayFileSize(targetResults.ullFileSize);
_Print(")\n");
ullTotalBytesCount += ullBytesCount;
ullTotalIOCount += ullIOCount;
}
}
_PrintSectionBorderLine(timeSpan);
double totalAvgLat = 0;
if (timeSpan.GetMeasureLatency())
{
totalAvgLat = totalLatencyHistogram.GetAvg()/1000;
}
_Print("total: %15llu | %12llu | %10.2f | %10.2f",
ullTotalBytesCount,
ullTotalIOCount,
(double)ullTotalBytesCount / 1024 / 1024 / fTime,
(double)ullTotalIOCount / fTime);
if (timeSpan.GetMeasureLatency())
{
_Print(" | %8.3f", totalAvgLat);
}
if (timeSpan.GetCalculateIopsStdDev())
{
double iopsStdDev = totalIoBucketizer.GetStandardDeviation() / fBucketTime;
_Print(" | %10.2f", iopsStdDev);
}
if (timeSpan.GetMeasureLatency())
{
if (totalLatencyHistogram.GetSampleSize() > 0)
{
double latStdDev = totalLatencyHistogram.GetStandardDeviation() / 1000;
_Print(" | %8.3f", latStdDev);
}
else
{
_Print(" | N/A");
}
}
_Print("\n");
}
void ResultParser::_PrintLatencyPercentiles(const Results& results)
{
Histogram<float> readLatencyHistogram;
Histogram<float> writeLatencyHistogram;
Histogram<float> totalLatencyHistogram;
for (auto thread : results.vThreadResults)
{
for (auto target : thread.vTargetResults)
{
readLatencyHistogram.Merge(target.readLatencyHistogram);
writeLatencyHistogram.Merge(target.writeLatencyHistogram);
totalLatencyHistogram.Merge(target.writeLatencyHistogram);
totalLatencyHistogram.Merge(target.readLatencyHistogram);
}
}
bool fHasReads = readLatencyHistogram.GetSampleSize() > 0;
bool fHasWrites = writeLatencyHistogram.GetSampleSize() > 0;
_Print(" %%-ile | Read (ms) | Write (ms) | Total (ms)\n");
_Print("----------------------------------------------\n");
string readMin =
fHasReads ?
Util::DoubleToStringHelper(readLatencyHistogram.GetMin()/1000) :
"N/A";
string writeMin =
fHasWrites ?
Util::DoubleToStringHelper(writeLatencyHistogram.GetMin() / 1000) :
"N/A";
_Print(" min | %10s | %10s | %10.3lf\n",
readMin.c_str(), writeMin.c_str(), totalLatencyHistogram.GetMin()/1000);
PercentileDescriptor percentiles[] =
{
{ 0.25, "25th" },
{ 0.50, "50th" },
{ 0.75, "75th" },
{ 0.90, "90th" },
{ 0.95, "95th" },
{ 0.99, "99th" },
{ 0.999, "3-nines" },
{ 0.9999, "4-nines" },
{ 0.99999, "5-nines" },
{ 0.999999, "6-nines" },
{ 0.9999999, "7-nines" },
{ 0.99999999, "8-nines" },
};
for (auto p : percentiles)
{
string readPercentile =
fHasReads ?
Util::DoubleToStringHelper(readLatencyHistogram.GetPercentile(p.Percentile) / 1000) :
"N/A";
string writePercentile =
fHasWrites ?
Util::DoubleToStringHelper(writeLatencyHistogram.GetPercentile(p.Percentile) / 1000) :
"N/A";
_Print("%7s | %10s | %10s | %10.3lf\n",
p.Name.c_str(),
readPercentile.c_str(),
writePercentile.c_str(),
totalLatencyHistogram.GetPercentile(p.Percentile)/1000);
}
string readMax = Util::DoubleToStringHelper(readLatencyHistogram.GetMax() / 1000);
string writeMax = Util::DoubleToStringHelper(writeLatencyHistogram.GetMax() / 1000);
_Print(" max | %10s | %10s | %10.3lf\n",
fHasReads ? readMax.c_str() : "N/A",
fHasWrites ? writeMax.c_str() : "N/A",
totalLatencyHistogram.GetMax()/1000);
}
string ResultParser::ParseResults(Profile& profile, const SystemInformation& system, vector<Results> vResults)
{
// TODO: print text representation of system information (see xml parser)
UNREFERENCED_PARAMETER(system);
_sResult.clear();
_PrintProfile(profile);
for (size_t iResult = 0; iResult < vResults.size(); iResult++)
{
_Print("\n\nResults for timespan %d:\n", iResult + 1);
_Print("*******************************************************************************\n");
Results results = vResults[iResult];
TimeSpan timeSpan = profile.GetTimeSpans()[iResult];
size_t ulProcCount = results.vSystemProcessorPerfInfo.size();
double fTime = PerfTimer::PerfTimeToSeconds(results.ullTimeCount); //test duration
char szFloatBuffer[1024];
// There either is a fixed number of threads for all files to share (GetThreadCount() > 0) or a number of threads per file.
// In the latter case vThreadResults.size() == number of threads per file * file count
size_t ulThreadCnt = (timeSpan.GetThreadCount() > 0) ? timeSpan.GetThreadCount() : results.vThreadResults.size();
if (fTime < 0.0000001)
{
_Print("The test was interrupted before the measurements began. No results are displayed.\n");
}
else
{
// TODO: parameters.bCreateFile;
_Print("\n");
sprintf_s(szFloatBuffer, sizeof(szFloatBuffer), "actual test time:\t%.2lfs\n", fTime);
_Print("%s", szFloatBuffer);
_Print("thread count:\t\t%u\n", ulThreadCnt);
_Print("proc count:\t\t%u\n", ulProcCount);
_PrintCpuUtilization(results);
_Print("\nTotal IO\n");
_PrintSection(_SectionEnum::TOTAL, timeSpan, results);
_Print("\nRead IO\n");
_PrintSection(_SectionEnum::READ, timeSpan, results);
_Print("\nWrite IO\n");
_PrintSection(_SectionEnum::WRITE, timeSpan, results);
if (timeSpan.GetMeasureLatency())
{
_Print("\n\n");
_PrintLatencyPercentiles(results);
}
//etw
if (results.fUseETW)
{
_DisplayETW(results.EtwMask, results.EtwEventCounters);
_DisplayETWSessionInfo(results.EtwSessionInfo);
}
}
}
if (vResults.size() > 1)
{
_Print("\n\nTotals:\n");
_Print("*******************************************************************************\n\n");
_Print("type | bytes | I/Os | MB/s | I/O per s\n");
_Print("-------------------------------------------------------------------------------\n");
UINT64 cbTotalWritten = 0;
UINT64 cbTotalRead = 0;
UINT64 cTotalWriteIO = 0;
UINT64 cTotalReadIO = 0;
UINT64 cTotalTicks = 0;
for (auto pResults = vResults.begin(); pResults != vResults.end(); pResults++)
{
double time = PerfTimer::PerfTimeToSeconds(pResults->ullTimeCount);
if (time >= 0.0000001) // skip timespans that were interrupted
{
cTotalTicks += pResults->ullTimeCount;
auto vThreadResults = pResults->vThreadResults;
for (auto pThreadResults = vThreadResults.begin(); pThreadResults != vThreadResults.end(); pThreadResults++)
{
for (auto pTargetResults = pThreadResults->vTargetResults.begin(); pTargetResults != pThreadResults->vTargetResults.end(); pTargetResults++)
{
cbTotalRead += pTargetResults->ullReadBytesCount;
cbTotalWritten += pTargetResults->ullWriteBytesCount;
cTotalReadIO += pTargetResults->ullReadIOCount;
cTotalWriteIO += pTargetResults->ullWriteIOCount;
}
}
}
}
double totalTime = PerfTimer::PerfTimeToSeconds(cTotalTicks);
_Print("write | %15I64u | %12I64u | %10.2lf | %10.2lf\n",
cbTotalWritten,
cTotalWriteIO,
(double)cbTotalWritten / 1024 / 1024 / totalTime,
(double)cTotalWriteIO / totalTime);
_Print("read | %15I64u | %12I64u | %10.2lf | %10.2lf\n",
cbTotalRead,
cTotalReadIO,
(double)cbTotalRead / 1024 / 1024 / totalTime,
(double)cTotalReadIO / totalTime);
_Print("-------------------------------------------------------------------------------\n");
_Print("total | %15I64u | %12I64u | %10.2lf | %10.2lf\n\n",
cbTotalRead + cbTotalWritten,
cTotalReadIO + cTotalWriteIO,
(double)(cbTotalRead + cbTotalWritten) / 1024 / 1024 / totalTime,
(double)(cTotalReadIO + cTotalWriteIO) / totalTime);
_Print("total test time:\t%.2lfs\n", totalTime);
}
return _sResult;
} | [
"danlo@microsoft.com"
] | danlo@microsoft.com |
af365a047d27ce34fba65ea7c227c84c97527b7d | 4999e175dff66ebed9bfcd7a6090eaea5dc4ee49 | /Chapter3/Chapter3_test.cc | b0c62b7509936e1f8974574640eb526641df08ba | [] | no_license | zhiminJimmyXiang/CrackingTheCodingInterview | fea16250c77d5aca75b98c7e52da846f83504d7a | 00041b7397dcc368ab29a11bf06f62d0272ce38b | refs/heads/master | 2021-01-25T08:48:49.439884 | 2014-06-27T06:01:17 | 2014-06-27T06:01:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,289 | cc | #include "Chapter3.h"
bool Chapter3_test::Problem_2_test(){
Chapter3 chapter3;
int a[]={2,3,9,0,8,-1,3,3,-2,-3};
int minVal[]={2,2,2,0,0,-1,-1,-1,-2,-3};
for(int i=0; i<10; ++i){
chapter3.problem_2.push(a[i]);
if(chapter3.problem_2.top()!=a[i])
return false;
if(chapter3.problem_2.getMin()!=minVal[i])
return false;
}
for(int i=9; i>=0; --i){
if(chapter3.problem_2.top()!=a[i])
return false;
if(chapter3.problem_2.getMin()!=minVal[i])
return false;
chapter3.problem_2.pop();
}
return true;
}
bool Chapter3_test::Problem_3_test(){
Chapter3 chapter3;
//case 1
int a[]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16};
for(unsigned i=0; i<16; ++i){
chapter3.problem_3.push(a[i]);
}
for(int i=15; i>=0; --i){
if(chapter3.problem_3.back()!=a[i])
return false;
chapter3.problem_3.pop();
}
//case 2
for(unsigned i=0; i<16; ++i)
chapter3.problem_3.push(a[i]);
int correctResult[]={5,6,7,8,9,10,11,12,13,14,15,16};
for(unsigned i=0; i<12; ++i){
if(chapter3.problem_3.getElement(0,4)!=correctResult[i])
return false;
chapter3.problem_3.popAt(0);
}
return true;
}
// Hanoi tower, have to test manually
bool Chapter3_test::Problem_4_test(){
Chapter3 chapter3;
//case 1
chapter3.Problem_4(3,1,3,2);
cout<<endl;
//case 2
chapter3.Problem_4(5,1,3,2);
cout<<endl;
return true;
}
bool Chapter3_test::Problem_5_test(){
Chapter3 chapter3;
int a[]={1,2,3,4,5,6,7,8,9,10,11,12,13};
for(unsigned i=0; i<13; ++i)
chapter3.problem_5.push_back(a[i]);
for(unsigned i=0; i<13; ++i){
if(chapter3.problem_5.front()!=a[i])
return false;
chapter3.problem_5.pop_front();
}
return true;
}
bool Chapter3_test::Problem_6_test(){
Chapter3 chapter3;
//case 1
vector<int> input;
chapter3.Problem_6(input);
if(!input.empty())
return false;
//case 2
int a[]={5,92,18,-1,9,2,4,0,8,4,0,2,0};
int correctAnswer[]={-1,0,0,0,2,2,4,4,5,8,9,18,92};
input.assign(a, a+13);
chapter3.Problem_6(input);
if(input.size()!=13)
return false;
for(unsigned i=0; i<13; ++i){
if(input[i]!=correctAnswer[i])
return false;
}
return true;
}
bool Chapter3_test::Problem_7_test(){
Chapter3 chapter3;
vector<Animal> animalVec;
//case 1
Animal a1 = chapter3.problem_7.dequeueAny();
Animal a2 = chapter3.problem_7.dequeueDog();
Animal a3 = chapter3.problem_7.dequeueCat();
if(a1.type!=0 || a2.type!=0 || a3.type!=0)
return false;
//case 2
for(int i=0; i<16; ++i){
Animal animal;
animal.type=(i%2==0?1:2);
animal.id = i;
chapter3.problem_7.enqueue(animal);
}
for(int i=0; i<16; ++i){
Animal animal = chapter3.problem_7.dequeueAny();
if(animal.type!=(i%2==0?1:2) || animal.time!=i || animal.id!=i)
return false;
}
//case 3
for(int i=0; i<16; ++i){
Animal animal;
animal.type=(i%2==0?1:2);
animal.id = i;
chapter3.problem_7.enqueue(animal);
}
for(int i=0; i<16; i+=2){
Animal animal = chapter3.problem_7.dequeueDog();
if(animal.type!=1 || animal.id!=i)
return false;
}
//case 4
for(int i=0; i<16; ++i){
Animal animal;
animal.type=(i%2==0?1:2);
animal.id = i;
chapter3.problem_7.enqueue(animal);
}
for(int i=1; i<16; i+=2){
Animal animal = chapter3.problem_7.dequeueCat();
if(animal.type!=2 || animal.id!=i)
return false;
}
return true;
}
int main(){
Chapter3_test testor;
//--- Problem 2 test ---
if(!testor.Problem_2_test())
cout<<"Test 2 Failed!!!!!"<<endl;
else
cout<<"Test 2 Passed!"<<endl;
//--- Problem 3 test ---
if(!testor.Problem_3_test())
cout<<"Test 3 Failed!!!!!"<<endl;
else
cout<<"Test 3 Passed!"<<endl;
//--- Problem 4 test ---
//testor.Problem_4_test();
//correct
//--- Problem 5 test ---
if(!testor.Problem_5_test())
cout<<"Test 5 Failed!!!!!"<<endl;
else
cout<<"Test 5 Passed!"<<endl;
//--- Problem 6 test ---
if(!testor.Problem_6_test())
cout<<"Test 6 Failed!!!!!"<<endl;
else
cout<<"Test 6 Passed!"<<endl;
//--- Problem 7 test ---
if(!testor.Problem_7_test())
cout<<"Test 7 Failed!!!!!"<<endl;
else
cout<<"Test 7 Passed!"<<endl;
return 0;
}
| [
"zhiminx1@uci.edu"
] | zhiminx1@uci.edu |
8638a6f86c337b508851f5386854eecda7a4fc5e | 2f1a092537d8650cacbd274a3bd600e87a627e90 | /thrift/lib/cpp2/async/ServerSinkBridge.cpp | 02c9cf351e9c2a1d96906d6a628733f7d0289baf | [
"Apache-2.0"
] | permissive | ConnectionMaster/fbthrift | 3aa7d095c00b04030fddbabffbf09a5adca29d42 | d5d0fa3f72ee0eb4c7b955e9e04a25052678d740 | refs/heads/master | 2023-04-10T17:49:05.409858 | 2021-08-03T02:32:49 | 2021-08-03T02:33:57 | 187,603,239 | 1 | 1 | Apache-2.0 | 2023-04-03T23:15:28 | 2019-05-20T08:49:29 | C++ | UTF-8 | C++ | false | false | 5,461 | cpp | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <thrift/lib/cpp2/async/ServerSinkBridge.h>
#if FOLLY_HAS_COROUTINES
namespace apache {
namespace thrift {
namespace detail {
// Explicitly instantiate the base of ServerSinkBridge
template class TwoWayBridge<
ServerSinkBridge,
ClientMessage,
CoroConsumer,
ServerMessage,
ServerSinkBridge>;
ServerSinkBridge::ServerSinkBridge(
SinkConsumerImpl&& sinkConsumer,
folly::EventBase& evb,
SinkClientCallback* callback)
: consumer_(std::move(sinkConsumer)),
evb_(folly::getKeepAliveToken(&evb)),
clientCallback_(callback) {
interaction_ =
TileStreamGuard::transferFrom(std::move(sinkConsumer.interaction));
bool scheduledWait = clientWait(this);
DCHECK(scheduledWait);
}
ServerSinkBridge::~ServerSinkBridge() {}
ServerSinkBridge::Ptr ServerSinkBridge::create(
SinkConsumerImpl&& sinkConsumer,
folly::EventBase& evb,
SinkClientCallback* callback) {
return (new ServerSinkBridge(std::move(sinkConsumer), evb, callback))->copy();
}
// SinkServerCallback method
bool ServerSinkBridge::onSinkNext(StreamPayload&& payload) {
clientPush(folly::Try<StreamPayload>(std::move(payload)));
return true;
}
void ServerSinkBridge::onSinkError(folly::exception_wrapper ew) {
folly::exception_wrapper hijacked;
if (ew.with_exception([&hijacked](rocket::RocketException& rex) {
hijacked = folly::exception_wrapper(
apache::thrift::detail::EncodedError(rex.moveErrorData()));
})) {
clientPush(folly::Try<StreamPayload>(std::move(hijacked)));
} else {
clientPush(folly::Try<StreamPayload>(std::move(ew)));
}
close();
}
bool ServerSinkBridge::onSinkComplete() {
clientPush(SinkComplete{});
sinkComplete_ = true;
return true;
}
void ServerSinkBridge::resetClientCallback(SinkClientCallback& clientCallback) {
DCHECK(clientCallback_);
clientCallback_ = &clientCallback;
}
// start should be called on threadmanager's thread
folly::coro::Task<void> ServerSinkBridge::startImpl(ServerSinkBridge& self) {
self.serverPush(self.consumer_.bufferSize);
folly::Try<StreamPayload> finalResponse =
co_await self.consumer_.consumer(makeGenerator(self));
if (self.clientException_) {
co_return;
}
self.serverPush(std::move(finalResponse));
}
folly::coro::Task<void> ServerSinkBridge::start() {
return startImpl(*this);
}
// TwoWayBridge consumer
void ServerSinkBridge::consume() {
evb_->runInEventBaseThread(
[self = copy()]() { self->processClientMessages(); });
}
folly::coro::AsyncGenerator<folly::Try<StreamPayload>&&>
ServerSinkBridge::makeGenerator(ServerSinkBridge& self) {
uint64_t counter = 0;
while (true) {
CoroConsumer consumer;
if (self.serverWait(&consumer)) {
folly::CancellationCallback cb{
co_await folly::coro::co_current_cancellation_token,
[&]() { self.serverClose(); }};
co_await consumer.wait();
}
co_await folly::coro::co_safe_point;
for (auto messages = self.serverGetMessages(); !messages.empty();
messages.pop()) {
auto& message = messages.front();
folly::Try<StreamPayload> ele;
folly::variant_match(
message,
[&](folly::Try<StreamPayload>& payload) { ele = std::move(payload); },
[](SinkComplete&) {});
// empty Try represent the normal completion of the sink
if (!ele.hasValue() && !ele.hasException()) {
co_return;
}
if (ele.hasException()) {
self.clientException_ = true;
co_yield std::move(ele);
co_return;
}
co_yield std::move(ele);
counter++;
if (counter > self.consumer_.bufferSize / 2) {
self.serverPush(counter);
counter = 0;
}
}
}
}
void ServerSinkBridge::processClientMessages() {
if (!clientCallback_) {
return;
}
int64_t credits = 0;
do {
for (auto messages = clientGetMessages(); !messages.empty();
messages.pop()) {
bool terminated = false;
auto& message = messages.front();
folly::variant_match(
message,
[&](folly::Try<StreamPayload>& payload) {
terminated = true;
if (payload.hasValue()) {
clientCallback_->onFinalResponse(std::move(payload).value());
} else {
clientCallback_->onFinalResponseError(
std::move(payload).exception());
}
},
[&](int64_t n) { credits += n; });
if (terminated) {
close();
return;
}
}
} while (!clientWait(this));
if (!sinkComplete_ && credits > 0) {
std::ignore = clientCallback_->onSinkRequestN(credits);
}
}
void ServerSinkBridge::close() {
clientClose();
clientCallback_ = nullptr;
Ptr(this);
}
} // namespace detail
} // namespace thrift
} // namespace apache
#endif
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
52a364b2ac5fdc6bcf4d4c9ddbed3c7b1432ac5d | 88ff7bd277882913983145850d0d14457241b525 | /src/SingleLayerOptics/tst/units/RectangularPerforatedScatteringShade1.unit.cpp | 2012c82bb0aa6009d2eff3ecd3989ff99bd6b88b | [
"BSD-3-Clause-LBNL"
] | permissive | LBNL-ETA/Windows-CalcEngine | 4a3f7eeff094a277d0cce304c9339c8c8c238f19 | 610cc20b4beddfe379c566aa1adcffc71d2dd75e | refs/heads/main | 2023-08-10T17:02:43.415941 | 2023-08-03T15:32:16 | 2023-08-03T15:32:16 | 54,597,431 | 17 | 13 | NOASSERTION | 2023-08-24T16:59:01 | 2016-03-23T22:31:42 | C++ | UTF-8 | C++ | false | false | 2,779 | cpp | #include <memory>
#include <gtest/gtest.h>
#include "WCESingleLayerOptics.hpp"
#include "WCECommon.hpp"
using namespace SingleLayerOptics;
using namespace FenestrationCommon;
class TestRectangularPerforatedScatteringShade1 : public testing::Test
{
protected:
virtual void SetUp()
{}
};
TEST_F(TestRectangularPerforatedScatteringShade1, TestProperties)
{
SCOPED_TRACE("Begin Test: Rectangular perforated cell - properties.");
// make material
const auto Tmat = 0.1;
const auto Rfmat = 0.4;
const auto Rbmat = 0.4;
const auto minLambda = 0.3;
const auto maxLambda = 2.5;
const auto aMaterial = Material::singleBandMaterial(Tmat, Tmat, Rfmat, Rbmat);
// make cell geometry
const auto x = 20.0; // mm
const auto y = 25.0; // mm
const auto thickness = 7.0; // mm
const auto xHole = 5.0; // mm
const auto yHole = 8.0; // mm
auto shade =
CScatteringLayer::createPerforatedRectangularLayer(aMaterial, x, y, thickness, xHole, yHole);
const double tir = shade.getPropertySimple(
minLambda, maxLambda, PropertySimple::T, Side::Front, Scattering::DiffuseDiffuse);
EXPECT_NEAR(tir, 0.112482, 1e-6);
const double rir = shade.getPropertySimple(
minLambda, maxLambda, PropertySimple::R, Side::Front, Scattering::DiffuseDiffuse);
EXPECT_NEAR(rir, 0.394452, 1e-6);
auto irLayer = CScatteringLayerIR(shade);
const double emiss = irLayer.emissivity(Side::Front);
EXPECT_NEAR(emiss, 0.493065, 1e-6);
}
TEST_F(TestRectangularPerforatedScatteringShade1, TestHighEmissivity)
{
SCOPED_TRACE("Begin Test: Rectangular perforated cell - properties.");
// make material
const auto Tmat = 0.1;
const auto Rfmat = 0.01;
const auto Rbmat = 0.01;
const auto minLambda = 0.3;
const auto maxLambda = 2.5;
const auto aMaterial = Material::singleBandMaterial(Tmat, Tmat, Rfmat, Rbmat);
// make cell geometry
const auto x = 20.0; // mm
const auto y = 25.0; // mm
const auto thickness = 7.0; // mm
const auto xHole = 0.001; // mm
const auto yHole = 0.001; // mm
auto shade =
CScatteringLayer::createPerforatedRectangularLayer(aMaterial, x, y, thickness, xHole, yHole);
const double tir = shade.getPropertySimple(
minLambda, maxLambda, PropertySimple::T, Side::Front, Scattering::DiffuseDiffuse);
EXPECT_NEAR(tir, 0.1, 1e-6);
const double rir = shade.getPropertySimple(
minLambda, maxLambda, PropertySimple::R, Side::Front, Scattering::DiffuseDiffuse);
EXPECT_NEAR(rir, 0.01, 1e-6);
auto irLayer = CScatteringLayerIR(shade);
const double emiss = irLayer.emissivity(Side::Front);
EXPECT_NEAR(emiss, 0.89, 1e-6);
}
| [
"dvvidanovic@lbl.gov"
] | dvvidanovic@lbl.gov |
4e60a470cb6bc71862a230112518cabc30f44ba0 | 6499b38172ef0f86be100d024d7ed4e74f6aa2bc | /Engine/Sprite.h | e8887e3bde985bc3d171dc27c7c370be83addd79 | [] | no_license | ralphsmith80/Game_Engine | a76ab08b0a3834571658915f7c52c71fbce3a01a | 6ad9544638c247de0ead285a5e36b244949cf036 | refs/heads/master | 2020-05-20T09:27:08.919374 | 2012-11-03T20:13:06 | 2012-11-03T20:13:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,215 | h | /*
* Sprite.h
* Advanced2D
*
* Created by Ralph Smith on 8/3/10.
* Copyright 2010 Ralph Smith. All rights reserved.
*
*/
#include "Advanced2D.h"
#ifndef __SPRITE_H__
#define __SPRITE_H__
namespace Advanced2D {
enum CollisionType {
COLLISION_NONE = 0,
COLLISION_RECT = 1,
COLLISION_DIST = 2
};
class Sprite : public Entity {
private:
Vector3 position;
Vector3 velocity;
bool imageLoaded;
int state;
int direction;
bool initialized;
float texWidthRatio;
float texHeightRatio;
Quad2f *vertices;
Quad2f *textureCoordinates;
Quad2f *transformedVerts;
GLushort *indices;
GPoint lastTextureOffset, textureOffset;
void calculateVerticesAtPoint (GPoint aPoint, GLuint aSubImageWidth, GLuint aSubImageHeight, bool aCenter);
void calculateTexCoordsAtOffset (GPoint aOffsetPoint, int aSubImageWidth, int aSubImageHeight);
protected:
Texture *image;
int width,height;
int animcolumns;
double framestart,frametimer;
double movestart, movetimer;
bool collidable;
enum CollisionType collisionMethod;
int curframe,totalframes,animdir;
double faceAngle, moveAngle;
int animstartx, animstarty;
double rotation, scaling;
GLfloat colorfilter[4][4];
Color4f color;
public:
Sprite();
virtual ~Sprite();
void init();
bool loadImage(std::string filename, TextureType type=TGA, GLenum filter=GL_LINEAR);
void setImage(Texture *);
void move();
void animate();
void draw(bool aCenter=true);
Texture* getImage() {return image;}
Sprite* getSubSprite(GPoint aPoint, int subWidth, int subHeight);
//screen position
Vector3 getPosition() { return position; }
void setPosition(Vector3 position) { this->position = position; }
void setPosition(double x, double y) { position.Set(x,y,0); }
double getX() { return position.getX(); }
double getY() { return position.getY(); }
void setX(double x) { position.setX(x); }
void setY(double y) { position.setY(y); }
//movement velocity
Vector3 getVelocity() { return velocity; }
void setVelocity(Vector3 v) { this->velocity = v; }
void setVelocity(double x, double y) { velocity.setX(x); velocity.setY(y); }
//image size
void setSize(int width, int height) { this->width = width; this->height = height; }
int getWidth() { return this->width; }
void setWidth(int value) { this->width = value; }
int getHeight() { return this->height; }
void setHeight(int value) { this->height = value; }
void setTextureOffset(float x, float y) {textureOffset.x = x; textureOffset.y = y;}
int getState() { return state; }
void setState(int value) { state = value; }
int getDirection() { return direction; }
void setDirection(int value) { direction = value; }
int getColumns() { return animcolumns; }
void setColumns(int value) { animcolumns = value; }
int getFrameTimer() { return frametimer; }
void setFrameTimer(int value) { frametimer = value; }
int getCurrentFrame() { return curframe; }
void setCurrentFrame(int value) { curframe = value; }
int getTotalFrames() { return totalframes; }
void setTotalFrames(int value) { totalframes = value; }
int getAnimationDirection() { return animdir; }
void setAnimationDirection(int value) { animdir = value; }
double getRotation() { return rotation; }
void setRotation(double value) { rotation = value; }
double getScale() { return scaling; }
void setScale(double value) { scaling = value; }
//modified from original -- new accessor
Color4f getColor() { return color; }
void setColor(GLfloat r, GLfloat g, GLfloat b, GLfloat a=1.0) { color.red = r; color.green = g; color.blue = b; color.alpha = a;}
void setAlpha(GLfloat a) { color.alpha = a;}
int getMoveTimer() { return movetimer; }
void setMoveTimer(int value) { movetimer = value; }
bool isCollidable() { return collidable; }
void setCollidable(bool value) { collidable = value; }
CollisionType getCollisionMethod() { return collisionMethod; }
void setCollisionMethod(CollisionType type) { collisionMethod = type; }
Rect getBounds();
}; //class
};
#endif | [
"ralphsmith80@gmail.com"
] | ralphsmith80@gmail.com |
8608aa9b6c947fe1ae5e9c64a8a6e94d66b6141a | f38fed03bd6efedc0c28cae62a60994a4f5a621c | /src/main.cpp | b66a7b1de82132836c5928cfb4eb98a6d666860a | [
"MIT"
] | permissive | fubendong2/kaiyuancoind | 8419effa746a783e63993966dcb212a7632c91c9 | 712b69af211c9dbdc6e1bb2a2db7164082db8dee | refs/heads/master | 2021-01-10T18:59:14.004257 | 2014-03-15T16:47:36 | 2014-03-15T16:47:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 111,003 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Copyright (c) 2013 Kaiyuancoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "checkpoints.h"
#include "db.h"
#include "net.h"
#include "init.h"
#include "ui_interface.h"
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
using namespace std;
using namespace boost;
//
// Global state
//
CCriticalSection cs_setpwalletRegistered;
set<CWallet*> setpwalletRegistered;
CCriticalSection cs_main;
CTxMemPool mempool;
unsigned int nTransactionsUpdated = 0;
map<uint256, CBlockIndex*> mapBlockIndex;
uint256 hashGenesisBlock("0xa2135e5d3b49440f7b71b51b4919787e78f1748f85b6892ee453d49166a399e5");
static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // Kaiyuancoin: starting difficulty is 1 / 2^12
CBlockIndex* pindexGenesisBlock = NULL;
int nBestHeight = -1;
CBigNum bnBestChainWork = 0;
CBigNum bnBestInvalidWork = 0;
uint256 hashBestChain = 0;
CBlockIndex* pindexBest = NULL;
int64 nTimeBestReceived = 0;
CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
map<uint256, CBlock*> mapOrphanBlocks;
multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
map<uint256, CDataStream*> mapOrphanTransactions;
map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
// Constant stuff for coinbase transactions we create:
CScript COINBASE_FLAGS;
const string strMessageMagic = "Kaiyuancoin Signed Message:\n";
double dHashesPerSec;
int64 nHPSTimerStart;
// Settings
int64 nTransactionFee = 0;
int64 nMinimumInputValue = CENT / 1000;
//////////////////////////////////////////////////////////////////////////////
//
// dispatching functions
//
// These functions dispatch to one or all registered wallets
void RegisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.insert(pwalletIn);
}
}
void UnregisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.erase(pwalletIn);
}
}
// check whether the passed transaction is from us
bool static IsFromMe(CTransaction& tx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->IsFromMe(tx))
return true;
return false;
}
// get the wallet transaction with the given hash (if it exists)
bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->GetTransaction(hashTx,wtx))
return true;
return false;
}
// erases transaction with the given hash from all wallets
void static EraseFromWallets(uint256 hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->EraseFromWallet(hash);
}
// make sure all wallets know about the given transaction, in the given block
void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
}
// notify wallets about a new best chain
void static SetBestChain(const CBlockLocator& loc)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->SetBestChain(loc);
}
// notify wallets about an updated transaction
void static UpdatedTransaction(const uint256& hashTx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->UpdatedTransaction(hashTx);
}
// dump all wallets
void static PrintWallets(const CBlock& block)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->PrintWallet(block);
}
// notify wallets about an incoming inventory (for request counts)
void static Inventory(const uint256& hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->Inventory(hash);
}
// ask wallets to resend their transactions
void static ResendWalletTransactions()
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->ResendWalletTransactions();
}
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//
bool AddOrphanTx(const CDataStream& vMsg)
{
CTransaction tx;
CDataStream(vMsg) >> tx;
uint256 hash = tx.GetHash();
if (mapOrphanTransactions.count(hash))
return false;
CDataStream* pvMsg = new CDataStream(vMsg);
// Ignore big transactions, to avoid a
// send-big-orphans memory exhaustion attack. If a peer has a legitimate
// large transaction with a missing parent then we assume
// it will rebroadcast it later, after the parent transaction(s)
// have been mined or received.
// 10,000 orphans, each of which is at most 5,000 bytes big is
// at most 500 megabytes of orphans:
if (pvMsg->size() > 5000)
{
printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
delete pvMsg;
return false;
}
mapOrphanTransactions[hash] = pvMsg;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(),
mapOrphanTransactions.size());
return true;
}
void static EraseOrphanTx(uint256 hash)
{
if (!mapOrphanTransactions.count(hash))
return;
const CDataStream* pvMsg = mapOrphanTransactions[hash];
CTransaction tx;
CDataStream(*pvMsg) >> tx;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
}
delete pvMsg;
mapOrphanTransactions.erase(hash);
}
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
{
unsigned int nEvicted = 0;
while (mapOrphanTransactions.size() > nMaxOrphans)
{
// Evict a random orphan:
uint256 randomhash = GetRandHash();
map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first);
++nEvicted;
}
return nEvicted;
}
//////////////////////////////////////////////////////////////////////////////
//
// CTransaction and CTxIndex
//
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
{
SetNull();
if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
return false;
if (!ReadFromDisk(txindexRet.pos))
return false;
if (prevout.n >= vout.size())
{
SetNull();
return false;
}
return true;
}
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
{
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool CTransaction::ReadFromDisk(COutPoint prevout)
{
CTxDB txdb("r");
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool CTransaction::IsStandard() const
{
if (nVersion > CTransaction::CURRENT_VERSION)
return false;
BOOST_FOREACH(const CTxIn& txin, vin)
{
// Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
// pay-to-script-hash, which is 3 ~80-byte signatures, 3
// ~65-byte public keys, plus a few script ops.
if (txin.scriptSig.size() > 500)
return false;
if (!txin.scriptSig.IsPushOnly())
return false;
}
BOOST_FOREACH(const CTxOut& txout, vout)
if (!::IsStandard(txout.scriptPubKey))
return false;
return true;
}
//
// Check transaction inputs, and make sure any
// pay-to-script-hash transactions are evaluating IsStandard scripts
//
// Why bother? To avoid denial-of-service attacks; an attacker
// can submit a standard HASH... OP_EQUAL transaction,
// which will get accepted into blocks. The redemption
// script can be anything; an attacker could use a very
// expensive-to-check-upon-redemption script like:
// DUP CHECKSIG DROP ... repeated 100 times... OP_1
//
bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
{
if (IsCoinBase())
return true; // Coinbases don't use vin normally
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
vector<vector<unsigned char> > vSolutions;
txnouttype whichType;
// get the scriptPubKey corresponding to this input:
const CScript& prevScript = prev.scriptPubKey;
if (!Solver(prevScript, whichType, vSolutions))
return false;
int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
if (nArgsExpected < 0)
return false;
// Transactions with extra stuff in their scriptSigs are
// non-standard. Note that this EvalScript() call will
// be quick, because if there are any operations
// beside "push data" in the scriptSig the
// IsStandard() call returns false
vector<vector<unsigned char> > stack;
if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
return false;
if (whichType == TX_SCRIPTHASH)
{
if (stack.empty())
return false;
CScript subscript(stack.back().begin(), stack.back().end());
vector<vector<unsigned char> > vSolutions2;
txnouttype whichType2;
if (!Solver(subscript, whichType2, vSolutions2))
return false;
if (whichType2 == TX_SCRIPTHASH)
return false;
int tmpExpected;
tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
if (tmpExpected < 0)
return false;
nArgsExpected += tmpExpected;
}
if (stack.size() != (unsigned int)nArgsExpected)
return false;
}
return true;
}
unsigned int
CTransaction::GetLegacySigOpCount() const
{
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTxIn& txin, vin)
{
nSigOps += txin.scriptSig.GetSigOpCount(false);
}
BOOST_FOREACH(const CTxOut& txout, vout)
{
nSigOps += txout.scriptPubKey.GetSigOpCount(false);
}
return nSigOps;
}
int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
{
if (fClient)
{
if (hashBlock == 0)
return 0;
}
else
{
CBlock blockTmp;
if (pblock == NULL)
{
// Load the block this tx is in
CTxIndex txindex;
if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
return 0;
if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
return 0;
pblock = &blockTmp;
}
// Update the tx's hashBlock
hashBlock = pblock->GetHash();
// Locate the transaction
for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
if (pblock->vtx[nIndex] == *(CTransaction*)this)
break;
if (nIndex == (int)pblock->vtx.size())
{
vMerkleBranch.clear();
nIndex = -1;
printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
return 0;
}
// Fill in merkle branch
vMerkleBranch = pblock->GetMerkleBranch(nIndex);
}
// Is the tx in a block that's in the main chain
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return pindexBest->nHeight - pindex->nHeight + 1;
}
bool CTransaction::CheckTransaction() const
{
// Basic checks that don't depend on any context
if (vin.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
if (vout.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
// Size limits
if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
// Check for negative or overflow output values
int64 nValueOut = 0;
BOOST_FOREACH(const CTxOut& txout, vout)
{
if (txout.nValue < 0)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
if (txout.nValue > MAX_MONEY)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
nValueOut += txout.nValue;
if (!MoneyRange(nValueOut))
return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
}
// Check for duplicate inputs
set<COutPoint> vInOutPoints;
BOOST_FOREACH(const CTxIn& txin, vin)
{
if (vInOutPoints.count(txin.prevout))
return false;
vInOutPoints.insert(txin.prevout);
}
if (IsCoinBase())
{
if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
}
else
{
BOOST_FOREACH(const CTxIn& txin, vin)
if (txin.prevout.IsNull())
return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
}
return true;
}
bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
bool* pfMissingInputs)
{
if (pfMissingInputs)
*pfMissingInputs = false;
if (!tx.CheckTransaction())
return error("CTxMemPool::accept() : CheckTransaction failed");
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
// To help v0.1.5 clients who would see it as a negative number
if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
// Rather not work on nonstandard transactions (unless -testnet)
if (!fTestNet && !tx.IsStandard())
return error("CTxMemPool::accept() : nonstandard transaction type");
// Do we already have it?
uint256 hash = tx.GetHash();
{
LOCK(cs);
if (mapTx.count(hash))
return false;
}
if (fCheckInputs)
if (txdb.ContainsTx(hash))
return false;
// Check for conflicts with in-memory transactions
CTransaction* ptxOld = NULL;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (mapNextTx.count(outpoint))
{
// Disable replacement feature for now
return false;
// Allow replacing with a newer version of the same transaction
if (i != 0)
return false;
ptxOld = mapNextTx[outpoint].ptx;
if (ptxOld->IsFinal())
return false;
if (!tx.IsNewerThan(*ptxOld))
return false;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
return false;
}
break;
}
}
if (fCheckInputs)
{
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
if (fInvalid)
return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
if (pfMissingInputs)
*pfMissingInputs = true;
return false;
}
// Check for non-standard pay-to-script-hash in inputs
if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
return error("CTxMemPool::accept() : nonstandard transaction input");
// Note: if you modify this code to accept non-standard transactions, then
// you should add code here to check that the transaction does a
// reasonable number of ECDSA signature verifications.
int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
// Don't accept it if it can't get into a block
if (nFees < tx.GetMinFee(1000, true, GMF_RELAY))
return error("CTxMemPool::accept() : not enough fees");
// Continuously rate-limit free transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make other's transactions take longer to confirm.
if (nFees < MIN_RELAY_TX_FEE)
{
static CCriticalSection cs;
static double dFreeCount;
static int64 nLastTime;
int64 nNow = GetTime();
{
LOCK(cs);
// Use an exponentially decaying ~10-minute window:
dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
if (fDebug)
printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
dFreeCount += nSize;
}
}
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!tx.ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
{
return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
}
}
// Store transaction in memory
{
LOCK(cs);
if (ptxOld)
{
printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
remove(*ptxOld);
}
addUnchecked(hash, tx);
}
///// are we sure this is ok when loading transactions or restoring block txes
// If updated, erase old tx from wallet
if (ptxOld)
EraseFromWallets(ptxOld->GetHash());
printf("CTxMemPool::accept() : accepted %s (poolsz %u)\n",
hash.ToString().substr(0,10).c_str(),
mapTx.size());
return true;
}
bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
{
return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
}
bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
{
// Add to memory pool without checking anything. Don't call this directly,
// call CTxMemPool::accept to properly check the transaction first.
{
mapTx[hash] = tx;
for (unsigned int i = 0; i < tx.vin.size(); i++)
mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
nTransactionsUpdated++;
}
return true;
}
bool CTxMemPool::remove(CTransaction &tx)
{
// Remove transaction from memory pool
{
LOCK(cs);
uint256 hash = tx.GetHash();
if (mapTx.count(hash))
{
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapNextTx.erase(txin.prevout);
mapTx.erase(hash);
nTransactionsUpdated++;
}
}
return true;
}
void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
{
vtxid.clear();
LOCK(cs);
vtxid.reserve(mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
vtxid.push_back((*mi).first);
}
int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
{
if (hashBlock == 0 || nIndex == -1)
return 0;
// Find the block it claims to be in
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
// Make sure the merkle branch connects to this block
if (!fMerkleVerified)
{
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
return 0;
fMerkleVerified = true;
}
pindexRet = pindex;
return pindexBest->nHeight - pindex->nHeight + 1;
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!IsCoinBase())
return 0;
return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
}
bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
{
if (fClient)
{
if (!IsInMainChain() && !ClientConnectInputs())
return false;
return CTransaction::AcceptToMemoryPool(txdb, false);
}
else
{
return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
}
}
bool CMerkleTx::AcceptToMemoryPool()
{
CTxDB txdb("r");
return AcceptToMemoryPool(txdb);
}
bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
{
{
LOCK(mempool.cs);
// Add previous supporting transactions first
BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
{
if (!tx.IsCoinBase())
{
uint256 hash = tx.GetHash();
if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
tx.AcceptToMemoryPool(txdb, fCheckInputs);
}
}
return AcceptToMemoryPool(txdb, fCheckInputs);
}
return false;
}
bool CWalletTx::AcceptWalletTransaction()
{
CTxDB txdb("r");
return AcceptWalletTransaction(txdb);
}
int CTxIndex::GetDepthInMainChain() const
{
// Read block header
CBlock block;
if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
return 0;
// Find the block in the index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return 1 + nBestHeight - pindex->nHeight;
}
// Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
{
{
LOCK(cs_main);
{
LOCK(mempool.cs);
if (mempool.exists(hash))
{
tx = mempool.lookup(hash);
return true;
}
}
CTxDB txdb("r");
CTxIndex txindex;
if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
{
CBlock block;
if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
hashBlock = block.GetHash();
return true;
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex
//
bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
{
if (!fReadTransactions)
{
*this = pindex->GetBlockHeader();
return true;
}
if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
return false;
if (GetHash() != pindex->GetBlockHash())
return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
return true;
}
uint256 static GetOrphanRoot(const CBlock* pblock)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblock->hashPrevBlock))
pblock = mapOrphanBlocks[pblock->hashPrevBlock];
return pblock->GetHash();
}
static const int64 nDiffChangeTarget = 600000;
int64 static GetBlockValue(int nHeight, int64 nFees)
{
int64 nSubsidy = 40 * COIN;
if (nHeight < 90)
{
nSubsidy = 8888888 * COIN;
}else if (nHeight < 990)
{
nSubsidy = 5 * COIN;
}else if (nHeight < 11790)
{
nSubsidy = 100 * COIN;
}else if (nHeight < 76590)
{
nSubsidy = 200 * COIN;
}else if (nHeight < 141390)
{
nSubsidy = 300 * COIN;
}else if (nHeight < 206190)
{
nSubsidy = 400 * COIN;
}else if (nHeight < 270990)
{
nSubsidy = 500 * COIN;
}else if (nHeight < 335790)
{
nSubsidy = 400 * COIN;
}else if (nHeight < 400590)
{
nSubsidy = 300 * COIN;
}else if (nHeight < 465390)
{
nSubsidy = 200 * COIN;
}else if (nHeight < 530190)
{
nSubsidy = 160 * COIN;
}else if (nHeight < 594990)
{
nSubsidy = 120 * COIN;
}else if (nHeight < 659790)
{
nSubsidy = 90 * COIN;
}else if (nHeight < 724590)
{
nSubsidy = 60 * COIN;
}
return nSubsidy + nFees;
}
static const int64 nTargetTimespan = 60 * 60; // Kaiyuancoin: 1 hour
static const int64 nTargetSpacing = 40; // Kaiyuancoin: 40 sec
static const int64 nInterval = nTargetTimespan / nTargetSpacing;
static const int64 nTargetTimespanRe = 60 * 60; // 60 Minutes
static const int64 nTargetSpacingRe = 30; // Kaiyuancoin: 30 seconds
static const int64 nIntervalRe = nTargetTimespanRe / nTargetSpacingRe;
//
// minimum amount of work that could possibly be required nTime after
// minimum work required was nBase
//
unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
{
// Testnet has min-difficulty blocks
// after nTargetSpacing*2 time between blocks:
if (fTestNet && nTime > nTargetSpacing*2)
return bnProofOfWorkLimit.GetCompact();
CBigNum bnResult;
bnResult.SetCompact(nBase);
while (nTime > 0 && bnResult < bnProofOfWorkLimit)
{
if(nBestHeight+1<nDiffChangeTarget){
// Maximum 400% adjustment...
bnResult *= 6;
// ... in best-case exactly 4-times-normal target time
nTime -= nTargetTimespan*4;
} else {
// Maximum 10% adjustment...
bnResult = (bnResult * 110) / 100;
// ... in best-case exactly 4-times-normal target time
nTime -= nTargetTimespanRe*4;
}
}
if (bnResult > bnProofOfWorkLimit)
bnResult = bnProofOfWorkLimit;
return bnResult.GetCompact();
}
unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
{
unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
int nHeight = pindexLast->nHeight + 1;
bool fNewDifficultyProtocol = (nHeight >= nDiffChangeTarget || fTestNet);
int blockstogoback = 0;
//set default to pre-v6.4.3 patch values
int64 retargetTimespan = nTargetTimespan;
int64 retargetSpacing = nTargetSpacing;
int64 retargetInterval = nInterval;
// Genesis block
if (pindexLast == NULL) return nProofOfWorkLimit;
//if patch v6.4.3 changes are in effect for block num, alter retarget values
if(fNewDifficultyProtocol) {
retargetTimespan = nTargetTimespanRe;
retargetSpacing = nTargetSpacingRe;
retargetInterval = nIntervalRe;
}
// Only change once per interval
if ((pindexLast->nHeight+1) % retargetInterval != 0){
// Special difficulty rule for testnet:
if (fTestNet){
// If the new block's timestamp is more than 2* 10 minutes
// then allow mining of a min-difficulty block.
if (pblock->nTime > pindexLast->nTime + retargetSpacing*2)
return nProofOfWorkLimit;
else {
// Return the last non-special-min-difficulty-rules-block
const CBlockIndex* pindex = pindexLast;
while (pindex->pprev && pindex->nHeight % retargetInterval != 0 && pindex->nBits == nProofOfWorkLimit)
pindex = pindex->pprev;
return pindex->nBits;
}
}
return pindexLast->nBits;
}
// Kaiyuancoin: This fixes an issue where a 51% attack can change difficulty at will.
// Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz
blockstogoback = retargetInterval-1;
if ((pindexLast->nHeight+1) != retargetInterval) blockstogoback = retargetInterval;
// Go back by what we want to be 14 days worth of blocks
const CBlockIndex* pindexFirst = pindexLast;
for (int i = 0; pindexFirst && i < blockstogoback; i++)
pindexFirst = pindexFirst->pprev;
assert(pindexFirst);
// Limit adjustment step
int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
CBigNum bnNew;
bnNew.SetCompact(pindexLast->nBits);
// thanks to RealSolid for this code
if(fNewDifficultyProtocol) {
if (nActualTimespan < (retargetTimespan - (retargetTimespan/10)) ) nActualTimespan = (retargetTimespan - (retargetTimespan/10));
if (nActualTimespan > (retargetTimespan + (retargetTimespan/10)) ) nActualTimespan = (retargetTimespan + (retargetTimespan/10));
}
else {
if (nActualTimespan < retargetTimespan/4) nActualTimespan = retargetTimespan/4;
if (nActualTimespan > retargetTimespan*4) nActualTimespan = retargetTimespan*4;
}
// Retarget
bnNew *= nActualTimespan;
bnNew /= retargetTimespan;
/// debug print
printf("GetNextWorkRequired RETARGET \n");
printf("retargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", retargetTimespan, nActualTimespan);
printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
if (bnNew > bnProofOfWorkLimit)
bnNew = bnProofOfWorkLimit;
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
// Check range
if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
return error("CheckProofOfWork() : nBits below minimum work");
// Check proof of work matches claimed amount
if (hash > bnTarget.getuint256())
return error("CheckProofOfWork() : hash doesn't match nBits");
return true;
}
// Return maximum amount of blocks that other nodes claim to have
int GetNumBlocksOfPeers()
{
return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
}
bool IsInitialBlockDownload()
{
if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
return true;
static int64 nLastUpdate;
static CBlockIndex* pindexLastBest;
if (pindexBest != pindexLastBest)
{
pindexLastBest = pindexBest;
nLastUpdate = GetTime();
}
return (GetTime() - nLastUpdate < 10 &&
pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
}
void static InvalidChainFound(CBlockIndex* pindexNew)
{
if (pindexNew->bnChainWork > bnBestInvalidWork)
{
bnBestInvalidWork = pindexNew->bnChainWork;
CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
uiInterface.NotifyBlocksChanged();
}
printf("InvalidChainFound: invalid block=%s height=%d work=%s date=%s\n",
pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
pindexNew->bnChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S",
pindexNew->GetBlockTime()).c_str());
printf("InvalidChainFound: current best=%s height=%d work=%s date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
}
void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
{
nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
// Updating time can change work required on testnet:
if (fTestNet)
nBits = GetNextWorkRequired(pindexPrev, this);
}
bool CTransaction::DisconnectInputs(CTxDB& txdb)
{
// Relinquish previous transactions' spent pointers
if (!IsCoinBase())
{
BOOST_FOREACH(const CTxIn& txin, vin)
{
COutPoint prevout = txin.prevout;
// Get prev txindex from disk
CTxIndex txindex;
if (!txdb.ReadTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : ReadTxIndex failed");
if (prevout.n >= txindex.vSpent.size())
return error("DisconnectInputs() : prevout.n out of range");
// Mark outpoint as not spent
txindex.vSpent[prevout.n].SetNull();
// Write back
if (!txdb.UpdateTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : UpdateTxIndex failed");
}
}
// Remove transaction from index
// This can fail if a duplicate of this transaction was in a chain that got
// reorganized away. This is only possible if this transaction was completely
// spent, so erasing it would be a no-op anway.
txdb.EraseTxIndex(*this);
return true;
}
bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
{
// FetchInputs can return false either because we just haven't seen some inputs
// (in which case the transaction should be stored as an orphan)
// or because the transaction is malformed (in which case the transaction should
// be dropped). If tx is definitely invalid, fInvalid will be set to true.
fInvalid = false;
if (IsCoinBase())
return true; // Coinbase transactions have no inputs to fetch.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
if (inputsRet.count(prevout.hash))
continue; // Got it already
// Read txindex
CTxIndex& txindex = inputsRet[prevout.hash].first;
bool fFound = true;
if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
{
// Get txindex from current proposed changes
txindex = mapTestPool.find(prevout.hash)->second;
}
else
{
// Read txindex from txdb
fFound = txdb.ReadTxIndex(prevout.hash, txindex);
}
if (!fFound && (fBlock || fMiner))
return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
// Read txPrev
CTransaction& txPrev = inputsRet[prevout.hash].second;
if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
{
// Get prev tx from single transactions in memory
{
LOCK(mempool.cs);
if (!mempool.exists(prevout.hash))
return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
txPrev = mempool.lookup(prevout.hash);
}
if (!fFound)
txindex.vSpent.resize(txPrev.vout.size());
}
else
{
// Get prev tx from disk
if (!txPrev.ReadFromDisk(txindex.pos))
return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
}
}
// Make sure all prevout.n's are valid:
for (unsigned int i = 0; i < vin.size(); i++)
{
const COutPoint prevout = vin[i].prevout;
assert(inputsRet.count(prevout.hash) != 0);
const CTxIndex& txindex = inputsRet[prevout.hash].first;
const CTransaction& txPrev = inputsRet[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
{
// Revisit this if/when transaction replacement is implemented and allows
// adding inputs:
fInvalid = true;
return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
}
}
return true;
}
const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
{
MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
if (mi == inputs.end())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
const CTransaction& txPrev = (mi->second).second;
if (input.prevout.n >= txPrev.vout.size())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
return txPrev.vout[input.prevout.n];
}
int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
int64 nResult = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
nResult += GetOutputFor(vin[i], inputs).nValue;
}
return nResult;
}
unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
unsigned int nSigOps = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut& prevout = GetOutputFor(vin[i], inputs);
if (prevout.scriptPubKey.IsPayToScriptHash())
nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
}
return nSigOps;
}
bool CTransaction::ConnectInputs(MapPrevTx inputs,
map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
{
// Take over previous transactions' spent pointers
// fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
// fMiner is true when called from the internal kaiyuancoin miner
// ... both are false when called from CTransaction::AcceptToMemoryPool
if (!IsCoinBase())
{
int64 nValueIn = 0;
int64 nFees = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
// If prev is coinbase, check that it's matured
if (txPrev.IsCoinBase())
for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
// Check for negative or overflow input values
nValueIn += txPrev.vout[prevout.n].nValue;
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return DoS(100, error("ConnectInputs() : txin values out of range"));
}
// The first loop above does all the inexpensive checks.
// Only if ALL inputs pass do we perform expensive ECDSA signature checks.
// Helps prevent CPU exhaustion attacks.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
// Check for conflicts (double-spend)
// This doesn't trigger the DoS code on purpose; if it did, it would make it easier
// for an attacker to attempt to split the network.
if (!txindex.vSpent[prevout.n].IsNull())
return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
// Skip ECDSA signature verification when connecting blocks (fBlock=true)
// before the last blockchain checkpoint. This is safe because block merkle hashes are
// still computed and checked, and any change will be caught at the next checkpoint.
if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
{
// Verify signature
if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
{
// only during transition phase for P2SH: do not invoke anti-DoS code for
// potentially old clients relaying bad P2SH transactions
if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
}
}
// Mark outpoints as spent
txindex.vSpent[prevout.n] = posThisTx;
// Write back
if (fBlock || fMiner)
{
mapTestPool[prevout.hash] = txindex;
}
}
if (nValueIn < GetValueOut())
return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
// Tally transaction fees
int64 nTxFee = nValueIn - GetValueOut();
if (nTxFee < 0)
return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
nFees += nTxFee;
if (!MoneyRange(nFees))
return DoS(100, error("ConnectInputs() : nFees out of range"));
}
return true;
}
bool CTransaction::ClientConnectInputs()
{
if (IsCoinBase())
return false;
// Take over previous transactions' spent pointers
{
LOCK(mempool.cs);
int64 nValueIn = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
// Get prev tx from single transactions in memory
COutPoint prevout = vin[i].prevout;
if (!mempool.exists(prevout.hash))
return false;
CTransaction& txPrev = mempool.lookup(prevout.hash);
if (prevout.n >= txPrev.vout.size())
return false;
// Verify signature
if (!VerifySignature(txPrev, *this, i, true, 0))
return error("ConnectInputs() : VerifySignature failed");
///// this is redundant with the mempool.mapNextTx stuff,
///// not sure which I want to get rid of
///// this has to go away now that posNext is gone
// // Check for conflicts
// if (!txPrev.vout[prevout.n].posNext.IsNull())
// return error("ConnectInputs() : prev tx already used");
//
// // Flag outpoints as used
// txPrev.vout[prevout.n].posNext = posThisTx;
nValueIn += txPrev.vout[prevout.n].nValue;
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return error("ClientConnectInputs() : txin values out of range");
}
if (GetValueOut() > nValueIn)
return false;
}
return true;
}
bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
{
// Disconnect in reverse order
for (int i = vtx.size()-1; i >= 0; i--)
if (!vtx[i].DisconnectInputs(txdb))
return false;
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = 0;
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("DisconnectBlock() : WriteBlockIndex failed");
}
return true;
}
bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
{
// Check it again in case a previous version let a bad block in
if (!CheckBlock())
return false;
// Do not allow blocks that contain transactions which 'overwrite' older transactions,
// unless those are already completely spent.
// If such overwrites are allowed, coinbases and transactions depending upon those
// can be duplicated to remove the ability to spend the first instance -- even after
// being sent to another address.
// See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
// This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
// already refuses previously-known transaction id's entirely.
// This rule applies to all blocks whose timestamp is after October 1, 2012, 0:00 UTC.
int64 nBIP30SwitchTime = 1349049600;
bool fEnforceBIP30 = (pindex->nTime > nBIP30SwitchTime);
// BIP16 didn't become active until October 1 2012
int64 nBIP16SwitchTime = 1349049600;
bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
//// issue here: it doesn't know the version
unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - 1 + GetSizeOfCompactSize(vtx.size());
map<uint256, CTxIndex> mapQueuedChanges;
int64 nFees = 0;
unsigned int nSigOps = 0;
BOOST_FOREACH(CTransaction& tx, vtx)
{
uint256 hashTx = tx.GetHash();
if (fEnforceBIP30) {
CTxIndex txindexOld;
if (txdb.ReadTxIndex(hashTx, txindexOld)) {
BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
if (pos.IsNull())
return false;
}
}
nSigOps += tx.GetLegacySigOpCount();
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
MapPrevTx mapInputs;
if (!tx.IsCoinBase())
{
bool fInvalid;
if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
return false;
if (fStrictPayToScriptHash)
{
// Add in sigops done by pay-to-script-hash inputs;
// this is to prevent a "rogue miner" from creating
// an incredibly-expensive-to-validate block.
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
}
nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut();
if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
return false;
}
mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
}
// Write queued txindex changes
for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
{
if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
return error("ConnectBlock() : UpdateTxIndex failed");
}
if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
return false;
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = pindex->GetBlockHash();
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("ConnectBlock() : WriteBlockIndex failed");
}
// Watch for transactions paying to me
BOOST_FOREACH(CTransaction& tx, vtx)
SyncWithWallets(tx, this, true);
return true;
}
bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
{
printf("REORGANIZE\n");
// Find the fork
CBlockIndex* pfork = pindexBest;
CBlockIndex* plonger = pindexNew;
while (pfork != plonger)
{
while (plonger->nHeight > pfork->nHeight)
if (!(plonger = plonger->pprev))
return error("Reorganize() : plonger->pprev is null");
if (pfork == plonger)
break;
if (!(pfork = pfork->pprev))
return error("Reorganize() : pfork->pprev is null");
}
// List of what to disconnect
vector<CBlockIndex*> vDisconnect;
for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
vDisconnect.push_back(pindex);
// List of what to connect
vector<CBlockIndex*> vConnect;
for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
vConnect.push_back(pindex);
reverse(vConnect.begin(), vConnect.end());
printf("REORGANIZE: Disconnect %i blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
printf("REORGANIZE: Connect %i blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
// Disconnect shorter branch
vector<CTransaction> vResurrect;
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for disconnect failed");
if (!block.DisconnectBlock(txdb, pindex))
return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
// Queue memory transactions to resurrect
BOOST_FOREACH(const CTransaction& tx, block.vtx)
if (!tx.IsCoinBase())
vResurrect.push_back(tx);
}
// Connect longer branch
vector<CTransaction> vDelete;
for (unsigned int i = 0; i < vConnect.size(); i++)
{
CBlockIndex* pindex = vConnect[i];
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for connect failed");
if (!block.ConnectBlock(txdb, pindex))
{
// Invalid block
return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
}
// Queue memory transactions to delete
BOOST_FOREACH(const CTransaction& tx, block.vtx)
vDelete.push_back(tx);
}
if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
return error("Reorganize() : WriteHashBestChain failed");
// Make sure it's successfully written to disk before changing memory structure
if (!txdb.TxnCommit())
return error("Reorganize() : TxnCommit failed");
// Disconnect shorter branch
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
if (pindex->pprev)
pindex->pprev->pnext = NULL;
// Connect longer branch
BOOST_FOREACH(CBlockIndex* pindex, vConnect)
if (pindex->pprev)
pindex->pprev->pnext = pindex;
// Resurrect memory transactions that were in the disconnected branch
BOOST_FOREACH(CTransaction& tx, vResurrect)
tx.AcceptToMemoryPool(txdb, false);
// Delete redundant memory transactions that are in the connected branch
BOOST_FOREACH(CTransaction& tx, vDelete)
mempool.remove(tx);
printf("REORGANIZE: done\n");
return true;
}
// Called from inside SetBestChain: attaches a block to the new best chain being built
bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
{
uint256 hash = GetHash();
// Adding to current best branch
if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return false;
}
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
// Add to current best branch
pindexNew->pprev->pnext = pindexNew;
// Delete redundant memory transactions
BOOST_FOREACH(CTransaction& tx, vtx)
mempool.remove(tx);
return true;
}
bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
{
uint256 hash = GetHash();
if (!txdb.TxnBegin())
return error("SetBestChain() : TxnBegin failed");
if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
{
txdb.WriteHashBestChain(hash);
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
pindexGenesisBlock = pindexNew;
}
else if (hashPrevBlock == hashBestChain)
{
if (!SetBestChainInner(txdb, pindexNew))
return error("SetBestChain() : SetBestChainInner failed");
}
else
{
// the first block in the new chain that will cause it to become the new best chain
CBlockIndex *pindexIntermediate = pindexNew;
// list of blocks that need to be connected afterwards
std::vector<CBlockIndex*> vpindexSecondary;
// Reorganize is costly in terms of db load, as it works in a single db transaction.
// Try to limit how much needs to be done inside
while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainWork > pindexBest->bnChainWork)
{
vpindexSecondary.push_back(pindexIntermediate);
pindexIntermediate = pindexIntermediate->pprev;
}
if (!vpindexSecondary.empty())
printf("Postponing %i reconnects\n", vpindexSecondary.size());
// Switch to new best branch
if (!Reorganize(txdb, pindexIntermediate))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return error("SetBestChain() : Reorganize failed");
}
// Connect futher blocks
BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
{
printf("SetBestChain() : ReadFromDisk failed\n");
break;
}
if (!txdb.TxnBegin()) {
printf("SetBestChain() : TxnBegin 2 failed\n");
break;
}
// errors now are not fatal, we still did a reorganisation to a new chain in a valid way
if (!block.SetBestChainInner(txdb, pindex))
break;
}
}
// Update best block in wallet (so we can detect restored wallets)
bool fIsInitialDownload = IsInitialBlockDownload();
if (!fIsInitialDownload)
{
const CBlockLocator locator(pindexNew);
::SetBestChain(locator);
}
// New best block
hashBestChain = hash;
pindexBest = pindexNew;
nBestHeight = pindexBest->nHeight;
bnBestChainWork = pindexNew->bnChainWork;
nTimeBestReceived = GetTime();
nTransactionsUpdated++;
printf("SetBestChain: new best=%s height=%d work=%s date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
// Check the version of the last 100 blocks to see if we need to upgrade:
if (!fIsInitialDownload)
{
int nUpgraded = 0;
const CBlockIndex* pindex = pindexBest;
for (int i = 0; i < 100 && pindex != NULL; i++)
{
if (pindex->nVersion > CBlock::CURRENT_VERSION)
++nUpgraded;
pindex = pindex->pprev;
}
if (nUpgraded > 0)
printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
// if (nUpgraded > 100/2)
// strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
// strMiscWarning = _("Warning: this version is obsolete, upgrade required");
}
std::string strCmd = GetArg("-blocknotify", "");
if (!fIsInitialDownload && !strCmd.empty())
{
boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
return true;
}
bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
// Construct new block index object
CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
if (!pindexNew)
return error("AddToBlockIndex() : new CBlockIndex failed");
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first);
map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
if (miPrev != mapBlockIndex.end())
{
pindexNew->pprev = (*miPrev).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
}
pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
CTxDB txdb;
if (!txdb.TxnBegin())
return false;
txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
if (!txdb.TxnCommit())
return false;
// New best
if (pindexNew->bnChainWork > bnBestChainWork)
if (!SetBestChain(txdb, pindexNew))
return false;
txdb.Close();
if (pindexNew == pindexBest)
{
// Notify UI to display prev block's coinbase if it was ours
static uint256 hashPrevBestCoinBase;
UpdatedTransaction(hashPrevBestCoinBase);
hashPrevBestCoinBase = vtx[0].GetHash();
}
uiInterface.NotifyBlocksChanged();
return true;
}
bool CBlock::CheckBlock() const
{
// These are checks that are independent of context
// that can be verified before saving an orphan block.
// Size limits
if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CheckBlock() : size limits failed"));
// Check proof of work matches claimed amount
if (!CheckProofOfWork(GetPoWHash(), nBits))
return DoS(50, error("CheckBlock() : proof of work failed"));
// Check timestamp
if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
return error("CheckBlock() : block timestamp too far in the future");
// First transaction must be coinbase, the rest must not be
if (vtx.empty() || !vtx[0].IsCoinBase())
return DoS(100, error("CheckBlock() : first tx is not coinbase"));
for (unsigned int i = 1; i < vtx.size(); i++)
if (vtx[i].IsCoinBase())
return DoS(100, error("CheckBlock() : more than one coinbase"));
// Check transactions
BOOST_FOREACH(const CTransaction& tx, vtx)
if (!tx.CheckTransaction())
return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
// Check for duplicate txids. This is caught by ConnectInputs(),
// but catching it earlier avoids a potential DoS attack:
set<uint256> uniqueTx;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
uniqueTx.insert(tx.GetHash());
}
if (uniqueTx.size() != vtx.size())
return DoS(100, error("CheckBlock() : duplicate transaction"));
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
nSigOps += tx.GetLegacySigOpCount();
}
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
// Check merkleroot
if (hashMerkleRoot != BuildMerkleTree())
return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
return true;
}
bool CBlock::AcceptBlock()
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AcceptBlock() : block already in mapBlockIndex");
// Get prev block index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
if (mi == mapBlockIndex.end())
return DoS(10, error("AcceptBlock() : prev block not found"));
CBlockIndex* pindexPrev = (*mi).second;
int nHeight = pindexPrev->nHeight+1;
// Check proof of work
if (nBits != GetNextWorkRequired(pindexPrev, this))
return DoS(100, error("AcceptBlock() : incorrect proof of work"));
// Check timestamp against prev
if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
return error("AcceptBlock() : block's timestamp is too early");
// Check that all transactions are finalized
BOOST_FOREACH(const CTransaction& tx, vtx)
if (!tx.IsFinal(nHeight, GetBlockTime()))
return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
// Check that the block chain matches the known block chain up to a checkpoint
if (!Checkpoints::CheckBlock(nHeight, hash))
return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
// Write block to history file
if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
return error("AcceptBlock() : out of disk space");
unsigned int nFile = -1;
unsigned int nBlockPos = 0;
if (!WriteToDisk(nFile, nBlockPos))
return error("AcceptBlock() : WriteToDisk failed");
if (!AddToBlockIndex(nFile, nBlockPos))
return error("AcceptBlock() : AddToBlockIndex failed");
// Relay inventory, but don't relay old inventory during initial block download
int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
if (hashBestChain == hash)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
pnode->PushInventory(CInv(MSG_BLOCK, hash));
}
return true;
}
bool ProcessBlock(CNode* pfrom, CBlock* pblock)
{
// Check for duplicate
uint256 hash = pblock->GetHash();
if (mapBlockIndex.count(hash))
return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
if (mapOrphanBlocks.count(hash))
return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
// Preliminary checks
if (!pblock->CheckBlock())
return error("ProcessBlock() : CheckBlock FAILED");
CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
{
// Extra checks to prevent "fill up memory by spamming with bogus blocks"
int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
if (deltaTime < 0)
{
if (pfrom)
pfrom->Misbehaving(100);
return error("ProcessBlock() : block with timestamp before last checkpoint");
}
CBigNum bnNewBlock;
bnNewBlock.SetCompact(pblock->nBits);
CBigNum bnRequired;
bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
if (bnNewBlock > bnRequired)
{
if (pfrom)
pfrom->Misbehaving(100);
return error("ProcessBlock() : block with too little proof-of-work");
}
}
// If don't already have its previous block, shunt it off to holding area until we get it
if (!mapBlockIndex.count(pblock->hashPrevBlock))
{
printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
CBlock* pblock2 = new CBlock(*pblock);
mapOrphanBlocks.insert(make_pair(hash, pblock2));
mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
// Ask this guy to fill in what we're missing
if (pfrom)
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
return true;
}
// Store to disk
if (!pblock->AcceptBlock())
return error("ProcessBlock() : AcceptBlock FAILED");
// Recursively process any orphan blocks that depended on this one
vector<uint256> vWorkQueue;
vWorkQueue.push_back(hash);
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
++mi)
{
CBlock* pblockOrphan = (*mi).second;
if (pblockOrphan->AcceptBlock())
vWorkQueue.push_back(pblockOrphan->GetHash());
mapOrphanBlocks.erase(pblockOrphan->GetHash());
delete pblockOrphan;
}
mapOrphanBlocksByPrev.erase(hashPrev);
}
printf("ProcessBlock: ACCEPTED\n");
return true;
}
bool CheckDiskSpace(uint64 nAdditionalBytes)
{
uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
// Check for nMinDiskSpace bytes (currently 50MB)
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
{
fShutdown = true;
string strMessage = _("Warning: Disk space is low");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage, "Kaiyuancoin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
StartShutdown();
return false;
}
return true;
}
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
{
if ((nFile < 1) || (nFile == (unsigned int) -1))
return NULL;
FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode);
if (!file)
return NULL;
if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
{
if (fseek(file, nBlockPos, SEEK_SET) != 0)
{
fclose(file);
return NULL;
}
}
return file;
}
static unsigned int nCurrentBlockFile = 1;
FILE* AppendBlockFile(unsigned int& nFileRet)
{
nFileRet = 0;
loop
{
FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
if (!file)
return NULL;
if (fseek(file, 0, SEEK_END) != 0)
return NULL;
// FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
if (ftell(file) < 0x7F000000 - MAX_SIZE)
{
nFileRet = nCurrentBlockFile;
return file;
}
fclose(file);
nCurrentBlockFile++;
}
}
bool LoadBlockIndex(bool fAllowNew)
{
if (fTestNet)
{
pchMessageStart[0] = 0xfc;
pchMessageStart[1] = 0xc1;
pchMessageStart[2] = 0xb7;
pchMessageStart[3] = 0xdc;
hashGenesisBlock = uint256("0xa2135e5d3b49440f7b71b51b4919787e78f1748f85b6892ee453d49166a399e5");
}
//
// Load block index
//
CTxDB txdb("cr");
if (!txdb.LoadBlockIndex())
return false;
txdb.Close();
//
// Init with genesis block
//
if (mapBlockIndex.empty())
{
if (!fAllowNew)
return false;
// Genesis Block:
// block.GetHash() = 7231b064d3e620c55960abce2963ea19e1c3ffb6f5ff70e975114835a7024107
// hashGenesisBlock = 7231b064d3e620c55960abce2963ea19e1c3ffb6f5ff70e975114835a7024107
// block.hashMerkleRoot = 4fe8c1ba0a102fea0643287bb22ce7469ecb9b690362013f269a423fefa77b6e
// CBlock(hash=7231b064d3e620c55960, PoW=ecab9c4d0cff0d84a093, ver=1, hashPrevBlock=00000000000000000000,
// hashMerkleRoot=4fe8c1ba0a, nTime=1368503907, nBits=1e0ffff0, nNonce=102158625, vtx=1)
// CTransaction(hash=4fe8c1ba0a, ver=1, vin.size=1, vout.size=1, nLockTime=0)
// CTxIn(COutPoint(0000000000, -1), coinbase 04ffff001d01044c534d61792031332c20323031332031313a3334706d204544543a20552e532e2063727564652066757475726573207765726520757020302e332070657263656e74206174202439352e343120612062617272656c)
// CTxOut(nValue=50.00000000, scriptPubKey=040184710fa689ad5023690c80f3a4)
// vMerkleTree: 4fe8c1ba0a
// Genesis block
const char* pszTimestamp = "kaiyuancoin kaiyuancoin";
CTransaction txNew;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].nValue = 50 * COIN;
txNew.vout[0].scriptPubKey = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG;
CBlock block;
block.vtx.push_back(txNew);
block.hashPrevBlock = 0;
block.hashMerkleRoot = block.BuildMerkleTree();
block.nVersion = 1;
block.nTime = 1394784846;
block.nBits = 0x1e0ffff0;
block.nNonce = 331270;
if (fTestNet)
{
block.nTime = 1394784846;
block.nNonce = 1292958;
}
//// debug print
printf("block.GetHash() = %s\n", block.GetHash().ToString().c_str());
printf("hashGenesisBlock = %s\n", hashGenesisBlock.ToString().c_str());
printf("block.hashMerkleRoot = %s\n", block.hashMerkleRoot.ToString().c_str());
assert(block.hashMerkleRoot == uint256("0xe12ffcd9ad2477ee5072f5a4be98a5d1e32d5b5b306df5d7bf2c6d90ef0302de"));
// If genesis block hash does not match, then generate new genesis hash.
if (false && block.GetHash() != hashGenesisBlock)
//if (true)
{
printf("Searching for genesis block...\n");
// This will figure out a valid hash and Nonce if you're
// creating a different genesis block:
uint256 hashTarget = CBigNum().SetCompact(block.nBits).getuint256();
uint256 thash;
char scratchpad[SCRYPT_SCRATCHPAD_SIZE];
loop
{
scrypt_1024_1_1_256_sp(BEGIN(block.nVersion), BEGIN(thash), scratchpad);
if (thash <= hashTarget)
break;
if ((block.nNonce & 0xFFF) == 0)
{
printf("nonce %08X: hash = %s (target = %s)\n", block.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str());
}
++block.nNonce;
if (block.nNonce == 0)
{
printf("NONCE WRAPPED, incrementing time\n");
++block.nTime;
}
}
printf("block.nTime = %u \n", block.nTime);
printf("block.nNonce = %u \n", block.nNonce);
printf("block.GetHash = %s\n", block.GetHash().ToString().c_str());
}
block.print();
printf("hashGenesisBlock = %s\n", hashGenesisBlock.ToString().c_str());
printf("block.GetHash() = %s\n", block.GetHash().ToString().c_str());
assert(block.GetHash() == hashGenesisBlock);
// Start new block file
unsigned int nFile;
unsigned int nBlockPos;
if (!block.WriteToDisk(nFile, nBlockPos))
return error("LoadBlockIndex() : writing genesis block to disk failed");
if (!block.AddToBlockIndex(nFile, nBlockPos))
return error("LoadBlockIndex() : genesis block not accepted");
}
return true;
}
void PrintBlockTree()
{
// precompute tree structure
map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
CBlockIndex* pindex = (*mi).second;
mapNext[pindex->pprev].push_back(pindex);
// test
//while (rand() % 3 == 0)
// mapNext[pindex->pprev].push_back(pindex);
}
vector<pair<int, CBlockIndex*> > vStack;
vStack.push_back(make_pair(0, pindexGenesisBlock));
int nPrevCol = 0;
while (!vStack.empty())
{
int nCol = vStack.back().first;
CBlockIndex* pindex = vStack.back().second;
vStack.pop_back();
// print split or gap
if (nCol > nPrevCol)
{
for (int i = 0; i < nCol-1; i++)
printf("| ");
printf("|\\\n");
}
else if (nCol < nPrevCol)
{
for (int i = 0; i < nCol; i++)
printf("| ");
printf("|\n");
}
nPrevCol = nCol;
// print columns
for (int i = 0; i < nCol; i++)
printf("| ");
// print item
CBlock block;
block.ReadFromDisk(pindex);
printf("%d (%u,%u) %s %s tx %d",
pindex->nHeight,
pindex->nFile,
pindex->nBlockPos,
block.GetHash().ToString().substr(0,20).c_str(),
DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
block.vtx.size());
PrintWallets(block);
// put the main timechain first
vector<CBlockIndex*>& vNext = mapNext[pindex];
for (unsigned int i = 0; i < vNext.size(); i++)
{
if (vNext[i]->pnext)
{
swap(vNext[0], vNext[i]);
break;
}
}
// iterate children
for (unsigned int i = 0; i < vNext.size(); i++)
vStack.push_back(make_pair(nCol+i, vNext[i]));
}
}
bool LoadExternalBlockFile(FILE* fileIn)
{
int nLoaded = 0;
{
LOCK(cs_main);
try {
CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
unsigned int nPos = 0;
while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
{
unsigned char pchData[65536];
do {
fseek(blkdat, nPos, SEEK_SET);
int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
if (nRead <= 8)
{
nPos = (unsigned int)-1;
break;
}
void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
if (nFind)
{
if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
{
nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
break;
}
nPos += ((unsigned char*)nFind - pchData) + 1;
}
else
nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
} while(!fRequestShutdown);
if (nPos == (unsigned int)-1)
break;
fseek(blkdat, nPos, SEEK_SET);
unsigned int nSize;
blkdat >> nSize;
if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
{
CBlock block;
blkdat >> block;
if (ProcessBlock(NULL,&block))
{
nLoaded++;
nPos += 4 + nSize;
}
}
}
}
catch (std::exception &e) {
printf("%s() : Deserialize or I/O error caught during load\n",
__PRETTY_FUNCTION__);
}
}
printf("Loaded %i blocks from external file\n", nLoaded);
return nLoaded > 0;
}
//////////////////////////////////////////////////////////////////////////////
//
// CAlert
//
map<uint256, CAlert> mapAlerts;
CCriticalSection cs_mapAlerts;
string GetWarnings(string strFor)
{
int nPriority = 0;
string strStatusBar;
string strRPC;
if (GetBoolArg("-testsafemode"))
strRPC = "test";
// Misc warnings like out of disk space and clock is wrong
if (strMiscWarning != "")
{
nPriority = 1000;
strStatusBar = strMiscWarning;
}
// Longer invalid proof-of-work chain
if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
{
nPriority = 2000;
strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
}
// Alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{
const CAlert& alert = item.second;
if (alert.AppliesToMe() && alert.nPriority > nPriority)
{
nPriority = alert.nPriority;
strStatusBar = alert.strStatusBar;
}
}
}
if (strFor == "statusbar")
return strStatusBar;
else if (strFor == "rpc")
return strRPC;
assert(!"GetWarnings() : invalid parameter");
return "error";
}
CAlert CAlert::getAlertByHash(const uint256 &hash)
{
CAlert retval;
{
LOCK(cs_mapAlerts);
map<uint256, CAlert>::iterator mi = mapAlerts.find(hash);
if(mi != mapAlerts.end())
retval = mi->second;
}
return retval;
}
bool CAlert::ProcessAlert()
{
return false;
//commenting out this code until we properly implement KYB alerts.
/*
if (!CheckSignature())
return false;
if (!IsInEffect())
return false;
{
LOCK(cs_mapAlerts);
// Cancel previous alerts
for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
{
const CAlert& alert = (*mi).second;
if (Cancels(alert))
{
printf("cancelling alert %d\n", alert.nID);
uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
mapAlerts.erase(mi++);
}
else if (!alert.IsInEffect())
{
printf("expiring alert %d\n", alert.nID);
uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
mapAlerts.erase(mi++);
}
else
mi++;
}
// Check if this alert has been cancelled
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{
const CAlert& alert = item.second;
if (alert.Cancels(*this))
{
printf("alert already cancelled by %d\n", alert.nID);
return false;
}
}
// Add to mapAlerts
mapAlerts.insert(make_pair(GetHash(), *this));
// Notify UI if it applies to me
if(AppliesToMe())
uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);
}
printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
return true;
*/
}
//////////////////////////////////////////////////////////////////////////////
//
// Messages
//
bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
{
switch (inv.type)
{
case MSG_TX:
{
bool txInMap = false;
{
LOCK(mempool.cs);
txInMap = (mempool.exists(inv.hash));
}
return txInMap ||
mapOrphanTransactions.count(inv.hash) ||
txdb.ContainsTx(inv.hash);
}
case MSG_BLOCK:
return mapBlockIndex.count(inv.hash) ||
mapOrphanBlocks.count(inv.hash);
}
// Don't know what it is, just say we already got one
return true;
}
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ascii, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
unsigned char pchMessageStart[4] = { 0xfb, 0xc0, 0xb6, 0xdb }; // Kaiyuancoin: increase each by adding 2 to bitcoin's value.
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
{
static map<CService, CPubKey> mapReuseKey;
RandAddSeedPerfmon();
if (fDebug)
printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
{
printf("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
if (strCommand == "version")
{
// Each connection can only send one version message
if (pfrom->nVersion != 0)
{
pfrom->Misbehaving(1);
return false;
}
int64 nTime;
CAddress addrMe;
CAddress addrFrom;
uint64 nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
if (pfrom->nVersion < MIN_PROTO_VERSION)
{
// Since February 20, 2012, the protocol is initiated at version 209,
// and earlier versions are no longer supported
printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
pfrom->fDisconnect = true;
return false;
}
if (pfrom->nVersion == 10300)
pfrom->nVersion = 300;
if (!vRecv.empty())
vRecv >> addrFrom >> nNonce;
if (!vRecv.empty())
vRecv >> pfrom->strSubVer;
if (!vRecv.empty())
vRecv >> pfrom->nStartingHeight;
if (pfrom->fInbound && addrMe.IsRoutable())
{
pfrom->addrLocal = addrMe;
SeenLocal(addrMe);
}
// Disconnect if we connected to ourself
if (nNonce == nLocalHostNonce && nNonce > 1)
{
printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
pfrom->fDisconnect = true;
return true;
}
// Be shy and don't send version until we hear
if (pfrom->fInbound)
pfrom->PushVersion();
pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
AddTimeData(pfrom->addr, nTime);
// Change version
pfrom->PushMessage("verack");
pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
if (!pfrom->fInbound)
{
// Advertise our address
if (!fNoListen && !IsInitialBlockDownload())
{
CAddress addr = GetLocalAddress(&pfrom->addr);
if (addr.IsRoutable())
pfrom->PushAddress(addr);
}
// Get recent addresses
if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
{
pfrom->PushMessage("getaddr");
pfrom->fGetAddr = true;
}
addrman.Good(pfrom->addr);
} else {
if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
{
addrman.Add(addrFrom, addrFrom);
addrman.Good(addrFrom);
}
}
// Ask the first connected node for block updates
static int nAskedForBlocks = 0;
if (!pfrom->fClient && !pfrom->fOneShot &&
(pfrom->nVersion < NOBLKS_VERSION_START ||
pfrom->nVersion >= NOBLKS_VERSION_END) &&
(nAskedForBlocks < 1 || vNodes.size() <= 1))
{
nAskedForBlocks++;
pfrom->PushGetBlocks(pindexBest, uint256(0));
}
// Relay alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
item.second.RelayTo(pfrom);
}
pfrom->fSuccessfullyConnected = true;
printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
cPeerBlockCounts.input(pfrom->nStartingHeight);
}
else if (pfrom->nVersion == 0)
{
// Must have a version message before anything else
pfrom->Misbehaving(1);
return false;
}
else if (strCommand == "verack")
{
pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
}
else if (strCommand == "addr")
{
vector<CAddress> vAddr;
vRecv >> vAddr;
// Don't want addr from older versions unless seeding
if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
return true;
if (vAddr.size() > 1000)
{
pfrom->Misbehaving(20);
return error("message addr size() = %d", vAddr.size());
}
// Store the new addresses
vector<CAddress> vAddrOk;
int64 nNow = GetAdjustedTime();
int64 nSince = nNow - 10 * 60;
BOOST_FOREACH(CAddress& addr, vAddr)
{
if (fShutdown)
return true;
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom->AddAddressKnown(addr);
bool fReachable = IsReachable(addr);
if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
{
// Relay to a limited number of other nodes
{
LOCK(cs_vNodes);
// Use deterministic randomness to send to the same nodes for 24 hours
// at a time so the setAddrKnowns of the chosen nodes prevent repeats
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint64 hashAddr = addr.GetHash();
uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
hashRand = Hash(BEGIN(hashRand), END(hashRand));
multimap<uint256, CNode*> mapMix;
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->nVersion < CADDR_TIME_VERSION)
continue;
unsigned int nPointer;
memcpy(&nPointer, &pnode, sizeof(nPointer));
uint256 hashKey = hashRand ^ nPointer;
hashKey = Hash(BEGIN(hashKey), END(hashKey));
mapMix.insert(make_pair(hashKey, pnode));
}
int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
((*mi).second)->PushAddress(addr);
}
}
// Do not store addresses outside our network
if (fReachable)
vAddrOk.push_back(addr);
}
addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
if (vAddr.size() < 1000)
pfrom->fGetAddr = false;
if (pfrom->fOneShot)
pfrom->fDisconnect = true;
}
else if (strCommand == "inv")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > 50000)
{
pfrom->Misbehaving(20);
return error("message inv size() = %d", vInv.size());
}
// find last block in inv vector
unsigned int nLastBlock = (unsigned int)(-1);
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
nLastBlock = vInv.size() - 1 - nInv;
break;
}
}
CTxDB txdb("r");
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
{
const CInv &inv = vInv[nInv];
if (fShutdown)
return true;
pfrom->AddInventoryKnown(inv);
bool fAlreadyHave = AlreadyHave(txdb, inv);
if (fDebug)
printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
if (!fAlreadyHave)
pfrom->AskFor(inv);
else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
} else if (nInv == nLastBlock) {
// In case we are on a very long side-chain, it is possible that we already have
// the last block in an inv bundle sent in response to getblocks. Try to detect
// this situation and push another getblocks to continue.
std::vector<CInv> vGetData(1,inv);
pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
if (fDebug)
printf("force request: %s\n", inv.ToString().c_str());
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getdata")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > 50000)
{
pfrom->Misbehaving(20);
return error("message getdata size() = %d", vInv.size());
}
if (fDebugNet || (vInv.size() != 1))
printf("received getdata (%d invsz)\n", vInv.size());
BOOST_FOREACH(const CInv& inv, vInv)
{
if (fShutdown)
return true;
if (fDebugNet || (vInv.size() == 1))
printf("received getdata for: %s\n", inv.ToString().c_str());
if (inv.type == MSG_BLOCK)
{
// Send block from disk
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
if (mi != mapBlockIndex.end())
{
CBlock block;
block.ReadFromDisk((*mi).second);
pfrom->PushMessage("block", block);
// Trigger them to send a getblocks request for the next batch of inventory
if (inv.hash == pfrom->hashContinue)
{
// Bypass PushInventory, this must send even if redundant,
// and we want it right after the last block so they don't
// wait for other stuff first.
vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
pfrom->PushMessage("inv", vInv);
pfrom->hashContinue = 0;
}
}
}
else if (inv.IsKnownType())
{
// Send stream from relay memory
{
LOCK(cs_mapRelay);
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
if (mi != mapRelay.end())
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
}
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getblocks")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
// Find the last block the caller has in the main chain
CBlockIndex* pindex = locator.GetBlockIndex();
// Send the rest of the chain
if (pindex)
pindex = pindex->pnext;
int nLimit = 500;
printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
for (; pindex; pindex = pindex->pnext)
{
if (pindex->GetBlockHash() == hashStop)
{
printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
break;
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
if (--nLimit <= 0)
{
// When this block is requested, we'll send an inv that'll make them
// getblocks the next batch of inventory.
printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
}
}
else if (strCommand == "getheaders")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
CBlockIndex* pindex = NULL;
if (locator.IsNull())
{
// If locator is null, return the hashStop block
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
if (mi == mapBlockIndex.end())
return true;
pindex = (*mi).second;
}
else
{
// Find the last block the caller has in the main chain
pindex = locator.GetBlockIndex();
if (pindex)
pindex = pindex->pnext;
}
vector<CBlock> vHeaders;
int nLimit = 2000;
printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
for (; pindex; pindex = pindex->pnext)
{
vHeaders.push_back(pindex->GetBlockHeader());
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break;
}
pfrom->PushMessage("headers", vHeaders);
}
else if (strCommand == "tx")
{
vector<uint256> vWorkQueue;
vector<uint256> vEraseQueue;
CDataStream vMsg(vRecv);
CTxDB txdb("r");
CTransaction tx;
vRecv >> tx;
CInv inv(MSG_TX, tx.GetHash());
pfrom->AddInventoryKnown(inv);
bool fMissingInputs = false;
if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
{
SyncWithWallets(tx, NULL, true);
RelayMessage(inv, vMsg);
mapAlreadyAskedFor.erase(inv);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
// Recursively process any orphan transactions that depended on this one
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
mi != mapOrphanTransactionsByPrev[hashPrev].end();
++mi)
{
const CDataStream& vMsg = *((*mi).second);
CTransaction tx;
CDataStream(vMsg) >> tx;
CInv inv(MSG_TX, tx.GetHash());
bool fMissingInputs2 = false;
if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
{
printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
SyncWithWallets(tx, NULL, true);
RelayMessage(inv, vMsg);
mapAlreadyAskedFor.erase(inv);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
}
else if (!fMissingInputs2)
{
// invalid orphan
vEraseQueue.push_back(inv.hash);
printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
}
}
}
BOOST_FOREACH(uint256 hash, vEraseQueue)
EraseOrphanTx(hash);
}
else if (fMissingInputs)
{
AddOrphanTx(vMsg);
// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
if (nEvicted > 0)
printf("mapOrphan overflow, removed %u tx\n", nEvicted);
}
if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
}
else if (strCommand == "block")
{
CBlock block;
vRecv >> block;
printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
// block.print();
CInv inv(MSG_BLOCK, block.GetHash());
pfrom->AddInventoryKnown(inv);
if (ProcessBlock(pfrom, &block))
mapAlreadyAskedFor.erase(inv);
if (block.nDoS) pfrom->Misbehaving(block.nDoS);
}
else if (strCommand == "getaddr")
{
pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = addrman.GetAddr();
BOOST_FOREACH(const CAddress &addr, vAddr)
pfrom->PushAddress(addr);
}
else if (strCommand == "checkorder")
{
uint256 hashReply;
vRecv >> hashReply;
if (!GetBoolArg("-allowreceivebyip"))
{
pfrom->PushMessage("reply", hashReply, (int)2, string(""));
return true;
}
CWalletTx order;
vRecv >> order;
/// we have a chance to check the order here
// Keep giving the same key to the same ip until they use it
if (!mapReuseKey.count(pfrom->addr))
pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
// Send back approval of order and pubkey to use
CScript scriptPubKey;
scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
}
else if (strCommand == "reply")
{
uint256 hashReply;
vRecv >> hashReply;
CRequestTracker tracker;
{
LOCK(pfrom->cs_mapRequests);
map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
if (mi != pfrom->mapRequests.end())
{
tracker = (*mi).second;
pfrom->mapRequests.erase(mi);
}
}
if (!tracker.IsNull())
tracker.fn(tracker.param1, vRecv);
}
else if (strCommand == "ping")
{
if (pfrom->nVersion > BIP0031_VERSION)
{
uint64 nonce = 0;
vRecv >> nonce;
// Echo the message back with the nonce. This allows for two useful features:
//
// 1) A remote node can quickly check if the connection is operational
// 2) Remote nodes can measure the latency of the network thread. If this node
// is overloaded it won't respond to pings quickly and the remote node can
// avoid sending us more work, like chain download requests.
//
// The nonce stops the remote getting confused between different pings: without
// it, if the remote node sends a ping once per second and this node takes 5
// seconds to respond to each, the 5th ping the remote sends would appear to
// return very quickly.
pfrom->PushMessage("pong", nonce);
}
}
else if (strCommand == "alnalert")
{
CAlert alert;
vRecv >> alert;
if (alert.ProcessAlert())
{
// Relay
pfrom->setKnown.insert(alert.GetHash());
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
}
}
else
{
// Ignore unknown commands for extensibility
}
// Update the last seen time for this node's address
if (pfrom->fNetworkNode)
if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
AddressCurrentlyConnected(pfrom->addr);
return true;
}
bool ProcessMessages(CNode* pfrom)
{
CDataStream& vRecv = pfrom->vRecv;
if (vRecv.empty())
return true;
//if (fDebug)
// printf("ProcessMessages(%u bytes)\n", vRecv.size());
//
// Message format
// (4) message start
// (12) command
// (4) size
// (4) checksum
// (x) data
//
loop
{
// Don't bother if send buffer is too full to respond anyway
if (pfrom->vSend.size() >= SendBufferSize())
break;
// Scan for message start
CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
if (vRecv.end() - pstart < nHeaderSize)
{
if ((int)vRecv.size() > nHeaderSize)
{
printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
}
break;
}
if (pstart - vRecv.begin() > 0)
printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
vRecv.erase(vRecv.begin(), pstart);
// Read header
vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
CMessageHeader hdr;
vRecv >> hdr;
if (!hdr.IsValid())
{
printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
continue;
}
string strCommand = hdr.GetCommand();
// Message size
unsigned int nMessageSize = hdr.nMessageSize;
if (nMessageSize > MAX_SIZE)
{
printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
continue;
}
if (nMessageSize > vRecv.size())
{
// Rewind and wait for rest of message
vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
break;
}
// Checksum
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
if (nChecksum != hdr.nChecksum)
{
printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
continue;
}
// Copy message to its own buffer
CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
vRecv.ignore(nMessageSize);
// Process message
bool fRet = false;
try
{
{
LOCK(cs_main);
fRet = ProcessMessage(pfrom, strCommand, vMsg);
}
if (fShutdown)
return true;
}
catch (std::ios_base::failure& e)
{
if (strstr(e.what(), "end of data"))
{
// Allow exceptions from underlength message on vRecv
printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
}
else if (strstr(e.what(), "size too large"))
{
// Allow exceptions from overlong size
printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
}
else
{
PrintExceptionContinue(&e, "ProcessMessages()");
}
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ProcessMessages()");
} catch (...) {
PrintExceptionContinue(NULL, "ProcessMessages()");
}
if (!fRet)
printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
}
vRecv.Compact();
return true;
}
bool SendMessages(CNode* pto, bool fSendTrickle)
{
TRY_LOCK(cs_main, lockMain);
if (lockMain) {
// Don't send anything until we get their version message
if (pto->nVersion == 0)
return true;
// Keep-alive ping. We send a nonce of zero because we don't use it anywhere
// right now.
if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
uint64 nonce = 0;
if (pto->nVersion > BIP0031_VERSION)
pto->PushMessage("ping", nonce);
else
pto->PushMessage("ping");
}
// Resend wallet transactions that haven't gotten in a block yet
ResendWalletTransactions();
// Address refresh broadcast
static int64 nLastRebroadcast;
if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
// Periodically clear setAddrKnown to allow refresh broadcasts
if (nLastRebroadcast)
pnode->setAddrKnown.clear();
// Rebroadcast our address
if (!fNoListen)
{
CAddress addr = GetLocalAddress(&pnode->addr);
if (addr.IsRoutable())
pnode->PushAddress(addr);
}
}
}
nLastRebroadcast = GetTime();
}
//
// Message: addr
//
if (fSendTrickle)
{
vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
{
// returns true if wasn't already contained in the set
if (pto->setAddrKnown.insert(addr).second)
{
vAddr.push_back(addr);
// receiver rejects addr messages larger than 1000
if (vAddr.size() >= 1000)
{
pto->PushMessage("addr", vAddr);
vAddr.clear();
}
}
}
pto->vAddrToSend.clear();
if (!vAddr.empty())
pto->PushMessage("addr", vAddr);
}
//
// Message: inventory
//
vector<CInv> vInv;
vector<CInv> vInvWait;
{
LOCK(pto->cs_inventory);
vInv.reserve(pto->vInventoryToSend.size());
vInvWait.reserve(pto->vInventoryToSend.size());
BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
{
if (pto->setInventoryKnown.count(inv))
continue;
// trickle out tx inv to protect privacy
if (inv.type == MSG_TX && !fSendTrickle)
{
// 1/4 of tx invs blast to all immediately
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint256 hashRand = inv.hash ^ hashSalt;
hashRand = Hash(BEGIN(hashRand), END(hashRand));
bool fTrickleWait = ((hashRand & 3) != 0);
// always trickle our own transactions
if (!fTrickleWait)
{
CWalletTx wtx;
if (GetTransaction(inv.hash, wtx))
if (wtx.fFromMe)
fTrickleWait = true;
}
if (fTrickleWait)
{
vInvWait.push_back(inv);
continue;
}
}
// returns true if wasn't already contained in the set
if (pto->setInventoryKnown.insert(inv).second)
{
vInv.push_back(inv);
if (vInv.size() >= 1000)
{
pto->PushMessage("inv", vInv);
vInv.clear();
}
}
}
pto->vInventoryToSend = vInvWait;
}
if (!vInv.empty())
pto->PushMessage("inv", vInv);
//
// Message: getdata
//
vector<CInv> vGetData;
int64 nNow = GetTime() * 1000000;
CTxDB txdb("r");
while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
{
const CInv& inv = (*pto->mapAskFor.begin()).second;
if (!AlreadyHave(txdb, inv))
{
if (fDebugNet)
printf("sending getdata: %s\n", inv.ToString().c_str());
vGetData.push_back(inv);
if (vGetData.size() >= 1000)
{
pto->PushMessage("getdata", vGetData);
vGetData.clear();
}
mapAlreadyAskedFor[inv] = nNow;
}
pto->mapAskFor.erase(pto->mapAskFor.begin());
}
if (!vGetData.empty())
pto->PushMessage("getdata", vGetData);
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
//
// BitcoinMiner
//
int static FormatHashBlocks(void* pbuffer, unsigned int len)
{
unsigned char* pdata = (unsigned char*)pbuffer;
unsigned int blocks = 1 + ((len + 8) / 64);
unsigned char* pend = pdata + 64 * blocks;
memset(pdata + len, 0, 64 * blocks - len);
pdata[len] = 0x80;
unsigned int bits = len * 8;
pend[-1] = (bits >> 0) & 0xff;
pend[-2] = (bits >> 8) & 0xff;
pend[-3] = (bits >> 16) & 0xff;
pend[-4] = (bits >> 24) & 0xff;
return blocks;
}
static const unsigned int pSHA256InitState[8] =
{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
void SHA256Transform(void* pstate, void* pinput, const void* pinit)
{
SHA256_CTX ctx;
unsigned char data[64];
SHA256_Init(&ctx);
for (int i = 0; i < 16; i++)
((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
for (int i = 0; i < 8; i++)
ctx.h[i] = ((uint32_t*)pinit)[i];
SHA256_Update(&ctx, data, sizeof(data));
for (int i = 0; i < 8; i++)
((uint32_t*)pstate)[i] = ctx.h[i];
}
//
// ScanHash scans nonces looking for a hash with at least some zero bits.
// It operates on big endian data. Caller does the byte reversing.
// All input buffers are 16-byte aligned. nNonce is usually preserved
// between calls, but periodically or if nNonce is 0xffff0000 or above,
// the block is rebuilt and nNonce starts over at zero.
//
unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
{
unsigned int& nNonce = *(unsigned int*)(pdata + 12);
for (;;)
{
// Crypto++ SHA-256
// Hash pdata using pmidstate as the starting state into
// preformatted buffer phash1, then hash phash1 into phash
nNonce++;
SHA256Transform(phash1, pdata, pmidstate);
SHA256Transform(phash, phash1, pSHA256InitState);
// Return the nonce if the hash has at least some zero bits,
// caller will check if it has enough to reach the target
if (((unsigned short*)phash)[14] == 0)
return nNonce;
// If nothing found after trying for a while, return -1
if ((nNonce & 0xffff) == 0)
{
nHashesDone = 0xffff+1;
return (unsigned int) -1;
}
}
}
// Some explaining would be appreciated
class COrphan
{
public:
CTransaction* ptx;
set<uint256> setDependsOn;
double dPriority;
COrphan(CTransaction* ptxIn)
{
ptx = ptxIn;
dPriority = 0;
}
void print() const
{
printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
BOOST_FOREACH(uint256 hash, setDependsOn)
printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
}
};
uint64 nLastBlockTx = 0;
uint64 nLastBlockSize = 0;
CBlock* CreateNewBlock(CReserveKey& reservekey)
{
CBlockIndex* pindexPrev = pindexBest;
// Create new block
auto_ptr<CBlock> pblock(new CBlock());
if (!pblock.get())
return NULL;
// Create coinbase tx
CTransaction txNew;
txNew.vin.resize(1);
txNew.vin[0].prevout.SetNull();
txNew.vout.resize(1);
txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
// Add our coinbase tx as first transaction
pblock->vtx.push_back(txNew);
// Collect memory pool transactions into the block
int64 nFees = 0;
{
LOCK2(cs_main, mempool.cs);
CTxDB txdb("r");
// Priority order to process transactions
list<COrphan> vOrphan; // list memory doesn't move
map<uint256, vector<COrphan*> > mapDependers;
multimap<double, CTransaction*> mapPriority;
for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
{
CTransaction& tx = (*mi).second;
if (tx.IsCoinBase() || !tx.IsFinal())
continue;
COrphan* porphan = NULL;
double dPriority = 0;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// Read prev transaction
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
{
// Has to wait for dependencies
if (!porphan)
{
// Use list for automatic deletion
vOrphan.push_back(COrphan(&tx));
porphan = &vOrphan.back();
}
mapDependers[txin.prevout.hash].push_back(porphan);
porphan->setDependsOn.insert(txin.prevout.hash);
continue;
}
int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
// Read block header
int nConf = txindex.GetDepthInMainChain();
dPriority += (double)nValueIn * nConf;
if (fDebug && GetBoolArg("-printpriority"))
printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
}
// Priority is sum(valuein * age) / txsize
dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (porphan)
porphan->dPriority = dPriority;
else
mapPriority.insert(make_pair(-dPriority, &(*mi).second));
if (fDebug && GetBoolArg("-printpriority"))
{
printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
if (porphan)
porphan->print();
printf("\n");
}
}
// Collect transactions into block
map<uint256, CTxIndex> mapTestPool;
uint64 nBlockSize = 1000;
uint64 nBlockTx = 0;
int nBlockSigOps = 100;
while (!mapPriority.empty())
{
// Take highest priority transaction off priority queue
double dPriority = -(*mapPriority.begin()).first;
CTransaction& tx = *(*mapPriority.begin()).second;
mapPriority.erase(mapPriority.begin());
// Size limits
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
continue;
// Legacy limits on sigOps:
unsigned int nTxSigOps = tx.GetLegacySigOpCount();
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
// Transaction fee required depends on block size
// Kaiyuancoind: Reduce the exempted free transactions to 500 bytes (from Bitcoin's 3000 bytes)
bool fAllowFree = (nBlockSize + nTxSize < 1500 || CTransaction::AllowFree(dPriority));
int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK);
// Connecting shouldn't fail due to dependency on other memory pool transactions
// because we're already processing them in order of dependency
map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
MapPrevTx mapInputs;
bool fInvalid;
if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
continue;
int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
if (nTxFees < nMinFee)
continue;
nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
continue;
mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
swap(mapTestPool, mapTestPoolTmp);
// Added
pblock->vtx.push_back(tx);
nBlockSize += nTxSize;
++nBlockTx;
nBlockSigOps += nTxSigOps;
nFees += nTxFees;
// Add transactions that depend on this one to the priority queue
uint256 hash = tx.GetHash();
if (mapDependers.count(hash))
{
BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
{
if (!porphan->setDependsOn.empty())
{
porphan->setDependsOn.erase(hash);
if (porphan->setDependsOn.empty())
mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
}
}
}
}
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
printf("CreateNewBlock(): total size %lu\n", nBlockSize);
}
pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
pblock->UpdateTime(pindexPrev);
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get());
pblock->nNonce = 0;
return pblock.release();
}
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
}
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
{
//
// Prebuild hash buffers
//
struct
{
struct unnamed2
{
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
}
block;
unsigned char pchPadding0[64];
uint256 hash1;
unsigned char pchPadding1[64];
}
tmp;
memset(&tmp, 0, sizeof(tmp));
tmp.block.nVersion = pblock->nVersion;
tmp.block.hashPrevBlock = pblock->hashPrevBlock;
tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
tmp.block.nTime = pblock->nTime;
tmp.block.nBits = pblock->nBits;
tmp.block.nNonce = pblock->nNonce;
FormatHashBlocks(&tmp.block, sizeof(tmp.block));
FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
// Byte swap all the input buffer
for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
// Precalc the first half of the first hash, which stays constant
SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
memcpy(pdata, &tmp.block, 128);
memcpy(phash1, &tmp.hash1, 64);
}
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
{
uint256 hash = pblock->GetPoWHash();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
if (hash > hashTarget)
return false;
//// debug print
printf("BitcoinMiner:\n");
printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
pblock->print();
printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != hashBestChain)
return error("BitcoinMiner : generated block is stale");
// Remove key from key pool
reservekey.KeepKey();
// Track how many getdata requests this block gets
{
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[pblock->GetHash()] = 0;
}
// Process this block the same as if we had received it from another node
if (!ProcessBlock(NULL, pblock))
return error("BitcoinMiner : ProcessBlock, block not accepted");
}
return true;
}
void static ThreadBitcoinMiner(void* parg);
static bool fGenerateBitcoins = false;
static bool fLimitProcessors = false;
static int nLimitProcessors = -1;
void static BitcoinMiner(CWallet *pwallet)
{
printf("BitcoinMiner started\n");
SetThreadPriority(THREAD_PRIORITY_LOWEST);
// Make this thread recognisable as the mining thread
RenameThread("bitcoin-miner");
// Each thread has its own key and counter
CReserveKey reservekey(pwallet);
unsigned int nExtraNonce = 0;
while (fGenerateBitcoins)
{
if (fShutdown)
return;
while (vNodes.empty() || IsInitialBlockDownload())
{
Sleep(1000);
if (fShutdown)
return;
if (!fGenerateBitcoins)
return;
}
//
// Create new block
//
unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrev = pindexBest;
auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
if (!pblock.get())
return;
IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
//
// Prebuild hash buffers
//
char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
//unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
//
// Search
//
int64 nStart = GetTime();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
loop
{
unsigned int nHashesDone = 0;
//unsigned int nNonceFound;
uint256 thash;
char scratchpad[SCRYPT_SCRATCHPAD_SIZE];
loop
{
scrypt_1024_1_1_256_sp(BEGIN(pblock->nVersion), BEGIN(thash), scratchpad);
if (thash <= hashTarget)
{
// Found a solution
SetThreadPriority(THREAD_PRIORITY_NORMAL);
CheckWork(pblock.get(), *pwalletMain, reservekey);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
break;
}
pblock->nNonce += 1;
nHashesDone += 1;
if ((pblock->nNonce & 0xFF) == 0)
break;
}
// Meter hashes/sec
static int64 nHashCounter;
if (nHPSTimerStart == 0)
{
nHPSTimerStart = GetTimeMillis();
nHashCounter = 0;
}
else
nHashCounter += nHashesDone;
if (GetTimeMillis() - nHPSTimerStart > 4000)
{
static CCriticalSection cs;
{
LOCK(cs);
if (GetTimeMillis() - nHPSTimerStart > 4000)
{
dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
nHPSTimerStart = GetTimeMillis();
nHashCounter = 0;
string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
static int64 nLogTime;
if (GetTime() - nLogTime > 30 * 60)
{
nLogTime = GetTime();
printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
}
}
}
}
// Check for stop or if block needs to be rebuilt
if (fShutdown)
return;
if (!fGenerateBitcoins)
return;
if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
return;
if (vNodes.empty())
break;
if (pblock->nNonce >= 0xffff0000)
break;
if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
break;
if (pindexPrev != pindexBest)
break;
// Update nTime every few seconds
pblock->UpdateTime(pindexPrev);
nBlockTime = ByteReverse(pblock->nTime);
if (fTestNet)
{
// Changing pblock->nTime can change work required on testnet:
nBlockBits = ByteReverse(pblock->nBits);
hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
}
}
}
}
void static ThreadBitcoinMiner(void* parg)
{
CWallet* pwallet = (CWallet*)parg;
try
{
vnThreadsRunning[THREAD_MINER]++;
BitcoinMiner(pwallet);
vnThreadsRunning[THREAD_MINER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_MINER]--;
PrintException(&e, "ThreadBitcoinMiner()");
} catch (...) {
vnThreadsRunning[THREAD_MINER]--;
PrintException(NULL, "ThreadBitcoinMiner()");
}
nHPSTimerStart = 0;
if (vnThreadsRunning[THREAD_MINER] == 0)
dHashesPerSec = 0;
printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
}
void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
{
fGenerateBitcoins = fGenerate;
nLimitProcessors = GetArg("-genproclimit", -1);
if (nLimitProcessors == 0)
fGenerateBitcoins = false;
fLimitProcessors = (nLimitProcessors != -1);
if (fGenerate)
{
int nProcessors = boost::thread::hardware_concurrency();
printf("%d processors\n", nProcessors);
if (nProcessors < 1)
nProcessors = 1;
if (fLimitProcessors && nProcessors > nLimitProcessors)
nProcessors = nLimitProcessors;
int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
printf("Starting %d BitcoinMiner threads\n", nAddThreads);
for (int i = 0; i < nAddThreads; i++)
{
if (!CreateThread(ThreadBitcoinMiner, pwallet))
printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
Sleep(10);
}
}
}
| [
"fubendong100@163.com"
] | fubendong100@163.com |
607063e44f2926877646a7d444e5f74534461c8b | 64b5c5e0e86733601c268c173c6c89a8dbe9b093 | /AnimalBobble/cpp&h/tlybg.h | 3b364a7b8decb3c68d7dfb63a279d13a0ce210af | [] | no_license | Nishin3614/KOKI_NISHIYAMA | ab2ef12de5072b73fe49318a4742fedc5fc23f14 | 64bc2144f3c7655ab501606fe41bba68ea46f2e0 | refs/heads/master | 2020-09-30T13:45:25.199250 | 2020-01-31T07:26:06 | 2020-01-31T07:26:06 | 227,298,698 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 1,358 | h | // ----------------------------------------
//
// 試し背景処理の説明[tlybg.h]
// Author : Koki Nishiyama
//
// ----------------------------------------
#ifndef _TLYBG_H_
#define _TLYBG_H_ // ファイル名を基準を決める
// ----------------------------------------
//
// インクルードファイル
//
// ----------------------------------------
#include "main.h"
#include "scene_two.h"
// ----------------------------------------
//
// マクロ定義
//
// ----------------------------------------
#define MAX_TLYBG (1)
// ------------------------------------------------------------------------------------------
//
// クラス
//
// ------------------------------------------------------------------------------------------
class CTlyBg : public CScene
{
public:
/* 関数 */
CTlyBg();
~CTlyBg();
void Init(void);
void Uninit(void);
void Update(void);
void Draw(void);
static HRESULT Load(void);
static void UnLoad(void);
static CTlyBg * Create(CManager::MODE mode); // 作成
protected:
private:
static LPDIRECT3DTEXTURE9 m_pTex[CManager::MODE_MAX][MAX_TLYBG];
static CManager::MODE m_mode; // モード
static D3DXVECTOR3 m_pos[CManager::MODE_MAX][MAX_TLYBG]; // 位置情報
static D3DXVECTOR2 m_size[CManager::MODE_MAX][MAX_TLYBG]; // サイズ情報
CScene_TWO *m_aScene_Two[MAX_TLYBG];
};
#endif | [
"work.nishio240@gmail.com"
] | work.nishio240@gmail.com |
3e4279475bee832c1e090c9f23face119c480a66 | 57f6d50c518f94bddcf96b500a1800aae6699d13 | /apps-src/apps/librose/help.cpp | b33d27e2f6abe33cce4c2fdfbc8e909f3e4c342c | [] | no_license | vitaliyivanchenko/Rose | 22eef541a0c7a6dbfcade514f22d52e89f69bacf | 046b6fd36e333dd816e51c8811930ec41e5a710c | refs/heads/master | 2021-01-19T12:54:56.056888 | 2016-06-26T14:15:50 | 2017-01-24T06:58:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,126 | cpp | /* $Id: help.cpp 47608 2010-11-21 01:56:29Z shadowmaster $ */
/*
Copyright (C) 2003 - 2010 by David White <dave@whitevine.net>
Part of the Battle for Wesnoth Project http://www.wesnoth.org/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY.
See the COPYING file for more details.
*/
/**
* @file
* Routines for showing the help-dialog.
*/
#include "global.hpp"
#include "help.hpp"
#include "exceptions.hpp"
#include "gettext.hpp"
#include "gui/dialogs/transient_message.hpp"
#include "gui/dialogs/book.hpp"
#include "marked-up_text.hpp"
#include "log.hpp"
#include "sound.hpp"
#include "wml_separators.hpp"
#include "serialization/parser.hpp"
#include "font.hpp"
#include "wml_exception.hpp"
#include "integrate.hpp"
#include <boost/foreach.hpp>
#include <queue>
namespace help {
/// Thrown when the help system fails to parse something.
parse_error::parse_error(const std::string& msg) : game::error(msg) {}
std::string remove_first_space(const std::string& text);
/// Return the first word in s, not removing any spaces in the start of
/// it.
std::string get_first_word(const std::string &s);
SDL_Color string_to_color(const std::string& cmp_str)
{
if (cmp_str == "green") {
return font::GOOD_COLOR;
}
if (cmp_str == "red") {
return font::BAD_COLOR;
}
if (cmp_str == "black") {
return font::BLACK_COLOR;
}
if (cmp_str == "yellow") {
return font::YELLOW_COLOR;
}
if (cmp_str == "white") {
return font::BIGMAP_COLOR;
}
if (cmp_str == "blue") {
return font::BLUE_COLOR;
}
if (cmp_str == "gray") {
return font::GRAY_COLOR;
}
if (cmp_str == "orange") {
SDL_Color color = {255, 165, 0, 0};
return color;
}
if (!cmp_str.empty()) {
std::vector<std::string> fields = utils::split(cmp_str);
size_t size = fields.size();
if (size == 3 || size == 4) {
// make sure we have four fields
SDL_Color result;
result.r = lexical_cast_default<int>(fields[0]);
result.g = lexical_cast_default<int>(fields[1]);
result.b = lexical_cast_default<int>(fields[2]);
result.a = 0;
return result;
}
}
return font::NORMAL_COLOR;
}
std::vector<std::string> split_in_width(const std::string &s, const int font_size,
const unsigned width, int style)
{
std::vector<std::string> res;
try {
// [see remark#24]
size_t pos = s.find("\n");
if (pos == std::string::npos) {
unsigned unsplit_width = font::line_size(s, font_size, style).w;
if (unsplit_width <= width) {
res.push_back(s);
return res;
}
} else {
const std::string line_str = s.substr(0, pos);
unsigned unsplit_width = font::line_size(line_str, font_size, style).w;
if (unsplit_width <= width) {
res.push_back(line_str);
res.push_back(s.substr(pos));
return res;
}
}
const std::string& first_line = font::word_wrap_text(s, font_size, width, -1, 1, true);
// [see remark#21]
if (!first_line.empty()) {
res.push_back(first_line);
if(s.size() > first_line.size()) {
res.push_back(s.substr(first_line.size()));
}
} else {
res.push_back(s);
}
} catch (utils::invalid_utf8_exception&) {
throw parse_error (_("corrupted original file"));
}
return res;
}
std::string remove_first_space(const std::string& text)
{
if (text.length() > 0 && text[0] == ' ') {
return text.substr(1);
}
return text;
}
std::string get_first_word(const std::string &s)
{
size_t first_word_start = s.find_first_not_of(' ');
if (first_word_start == std::string::npos) {
return s;
}
size_t first_word_end = s.find_first_of(" \n", first_word_start);
if( first_word_end == first_word_start ) {
// This word is '\n'.
first_word_end = first_word_start+1;
}
//if no gap(' ' or '\n') found, test if it is CJK character
std::string re = s.substr(0, first_word_end);
utils::utf8_iterator ch(re);
if (ch == utils::utf8_iterator::end(re))
return re;
wchar_t firstchar = *ch;
if (font::is_cjk_char(firstchar)) {
// [see remark#23]
std::string re1 = utils::wchar_to_string(firstchar);
wchar_t previous = firstchar;
for (++ ch; ch != utils::utf8_iterator::end(re); ++ch) {
if (font::can_break(previous, *ch)) {
break;
}
re1.append(ch.substr().first, ch.substr().second);
previous = *ch;
}
return re1;
}
return re;
}
//
// book part
//
// All sections and topics not referenced from the default toplevel.
section hidden_sections;
const config* game_cfg = NULL;
gamemap* map = NULL;
bool editor = false;
section* book_toplevel = NULL;
void init_book(const config* _game_cfg, gamemap* _map, bool _editor)
{
game_cfg = _game_cfg;
map = _map;
editor = _editor;
}
void clear_book()
{
game_cfg = NULL;
map = NULL;
hidden_sections.clear();
}
const config dummy_cfg;
const int max_section_level = 15;
// The topic to open by default when opening the help dialog.
const std::string default_show_topic = "introduction_topic";
const std::string unknown_unit_topic = ".unknown_unit";
const std::string unit_prefix = "unit_";
const std::string race_prefix = "race_";
const std::string section_topic_prefix = "..";
const int normal_font_size = font::SIZE_SMALL;
/// Recursive function used by parse_config.
bool is_section_topic(const std::string& id)
{
return id.find(section_topic_prefix) == 0;
}
std::string form_section_topic(const std::string& id)
{
return section_topic_prefix + id;
}
std::string extract_section_topic(const std::string& id)
{
return id.substr(section_topic_prefix.size());
}
/// Prepend all chars with meaning inside attributes with a backslash.
std::string escape(const std::string &s)
{
return utils::escape(s, "'\\");
}
// id starting with '.' are hidden
std::string hidden_symbol(bool hidden)
{
return (hidden ? "." : "");
}
static bool is_visible_id(const std::string &id) {
return (id.empty() || id[0] != '.');
}
/// Return true if the id is valid for user defined topics and
/// sections. Some IDs are special, such as toplevel and may not be
/// be defined in the config.
static bool is_valid_id(const std::string &id) {
if (id == "toplevel") {
return false;
}
if (id.find(unit_prefix) == 0 || id.find(hidden_symbol() + unit_prefix) == 0) {
return false;
}
if (id.find("ability_") == 0) {
return false;
}
if (id.find("weaponspecial_") == 0) {
return false;
}
if (id == "hidden") {
return false;
}
return true;
}
/// Class to be used as a function object when generating the about
/// text. Translate the about dialog formatting to format suitable
/// for the help dialog.
class about_text_formatter {
public:
std::string operator()(const std::string &s) {
if (s.empty()) return s;
// Format + as headers, and the rest as normal text.
if (s[0] == '+')
return " \n<header>text='" + escape(s.substr(1)) + "'</header>";
if (s[0] == '-')
return s.substr(1);
return s;
}
};
class treserve_section
{
public:
treserve_section(const std::string& id, const std::string& generator)
: id(id)
, generator_str(generator)
{}
std::string id;
std::string generator_str;
};
std::map<std::string, treserve_section> reserve_sections;
void fill_reserve_sections()
{
if (!reserve_sections.empty()) {
return;
}
reserve_sections.insert(std::make_pair("units", treserve_section("units", "sections_generator = races")));
reserve_sections.insert(std::make_pair("abilities_section", treserve_section("abilities_section", "generator = abilities")));
reserve_sections.insert(std::make_pair("weapon_specials", treserve_section("weapon_specials", "generator = weapon_specials")));
reserve_sections.insert(std::make_pair("factions_section", treserve_section("factions_section", "generator = factions")));
reserve_sections.insert(std::make_pair("about", treserve_section("about", "generator = about")));
}
bool is_reserve_section(const std::string& id)
{
return reserve_sections.count(id) > 0;
}
topic_text::~topic_text()
{
if (generator_ && --generator_->count == 0)
delete generator_;
}
topic_text::topic_text(topic_text const &t):
parsed_text_(t.parsed_text_)
, generator_(t.generator_)
, from_textdomain_(t.from_textdomain_)
{
if (generator_)
++generator_->count;
}
topic_text &topic_text::operator=(topic_generator *g)
{
if (generator_ && --generator_->count == 0)
delete generator_;
generator_ = g;
from_textdomain_ = false;
return *this;
}
const t_string& topic_text::parsed_text() const
{
if (generator_) {
parsed_text_ = (*generator_)();
if (--generator_->count == 0)
delete generator_;
generator_ = NULL;
}
return parsed_text_;
}
void topic_text::set_parsed_text(const t_string& str)
{
VALIDATE(!generator_, "generator_ must be nul!");
parsed_text_ = str;
}
bool topic_text::operator==(const topic_text& that) const
{
if (generator_ || that.generator_) {
// generate automaticly, no one standard.
return true;
}
return parsed_text_ == that.parsed_text_;
}
bool topic::operator==(const topic &t) const
{
return t.id == id && t.title == title && t.text == text;
}
void topic::generate(std::stringstream& strstr, const std::string& prefix, const std::string& default_textdomain, section& toplevel) const
{
strstr << prefix << "[topic]\n";
strstr << prefix << "\tid = " << id << "\n";
std::vector<t_string_base::trans_str> trans = title.valuex();
if (!trans.empty()) {
if (!trans[0].td.empty() && trans[0].td != default_textdomain) {
strstr << "#textdomain " << trans[0].td << "\n";
}
strstr << prefix << "\ttitle = _ \"" << trans[0].str << "\"\n";
if (!trans[0].td.empty() && trans[0].td != default_textdomain) {
strstr << "#textdomain " << default_textdomain << "\n";
}
}
if (!text.parsed_text().empty()) {
trans = text.parsed_text().valuex();
if (!trans.empty()) {
strstr << prefix << "\ttext = _ \"" << trans[0].str << "\"\n";
}
}
if (is_section_topic(id)) {
const std::string extracted_id = id.substr(section_topic_prefix.size());
const section* sec = NULL;
if (!is_reserve_section(extracted_id)) {
sec = find_section(toplevel, extracted_id);
}
strstr << prefix << "\tgenerator = \"contents:";
if (sec && sec->sections.empty()) {
strstr << extracted_id;
} else {
strstr << "generated";
}
strstr << "\"\n";
} else if (is_reserve_section(id)) {
std::map<std::string, treserve_section>::const_iterator it = reserve_sections.find(id);
strstr << prefix << "\t" << it->second.generator_str << "\n";
}
strstr << prefix << "[/topic]\n";
}
void generate_pot(std::set<std::string>& msgids, const t_string& tstr, const std::string& default_textdomain)
{
if (tstr.str().empty()) {
return;
}
std::vector<t_string_base::trans_str> trans = tstr.valuex();
if (!trans.empty()) {
if (trans[0].td.empty() || trans[0].td == default_textdomain) {
msgids.insert(trans[0].str);
}
}
return;
}
void topic::generate_pot(std::set<std::string>& msgids, const std::string& default_textdomain) const
{
if (!is_section_topic(id)) {
help::generate_pot(msgids, title, default_textdomain);
}
if (!text.generator()) {
help::generate_pot(msgids, text.parsed_text(), default_textdomain);
}
}
section::~section()
{
std::for_each(sections.begin(), sections.end(), delete_section());
}
section::section(const section &sec) :
title(sec.title),
id(sec.id),
topics(sec.topics),
sections(),
level(sec.level)
{
std::transform(sec.sections.begin(), sec.sections.end(),
std::back_inserter(sections), create_section());
}
section& section::operator=(const section &sec)
{
title = sec.title;
id = sec.id;
level = sec.level;
std::copy(sec.topics.begin(), sec.topics.end(), std::back_inserter(topics));
std::transform(sec.sections.begin(), sec.sections.end(),
std::back_inserter(sections), create_section());
return *this;
}
bool section::operator==(const section &sec) const
{
if (sec.id != id || sec.title != title) {
return false;
}
if (sec.topics != topics) {
return false;
}
if (sec.sections.size() != sections.size()) {
return false;
}
for (size_t n = 0; n < sections.size(); n ++) {
if (*sec.sections[n] != *sections[n]) {
return false;
}
}
return true;
}
void section::add_section(const section& s, int pos)
{
// after pos
pos ++;
if (pos < 0 || pos >= (int)sections.size()) {
sections.push_back(new section(s));
} else {
section_list::iterator it = sections.begin();
std::advance(it, pos);
sections.insert(it, new section(s));
}
}
void section::erase_section(const section& s)
{
section_list::iterator it = std::find(sections.begin(), sections.end(), &s);
delete *it;
sections.erase(it);
}
void section::add_topic(const topic& t, int pos)
{
// after pos
pos ++;
if (pos < 0 || pos >= (int)topics.size()) {
topics.push_back(t);
} else {
topic_list::iterator it = topics.begin();
std::advance(it, pos);
topics.insert(it, t);
}
}
void section::erase_topic(const topic& t)
{
topic_list::iterator it = std::find_if(topics.begin(), topics.end(), has_id(t.id));
topics.erase(it);
}
void section::move(const topic& t, bool up)
{
topic_list::iterator it = std::find_if(topics.begin(), topics.end(), has_id(t.id));
int n = std::distance(topics.begin(), it);
topic_list::iterator it2;
if (up) {
topic t = *it;
topics.erase(it);
it = topics.begin();
std::advance(it, n - 1);
topics.insert(it, t);
} else {
topic_list::iterator it2 = topics.begin();
std::advance(it2, n + 1);
topic t = *it2;
topics.erase(it2);
topics.insert(it, t);
}
}
void section::move(const section& s, bool up)
{
section_list::iterator it = std::find_if(sections.begin(), sections.end(), has_id(s.id));
int n = std::distance(sections.begin(), it);
section_list::iterator it2;
if (up) {
section* s = *it;
sections.erase(it);
it = sections.begin();
std::advance(it, n - 1);
sections.insert(it, s);
} else {
section_list::iterator it2 = sections.begin();
std::advance(it2, n + 1);
section* s = *it2;
sections.erase(it2);
sections.insert(it, s);
}
}
void section::clear()
{
id.clear();
topics.clear();
std::for_each(sections.begin(), sections.end(), delete_section());
sections.clear();
}
void section::generate(std::stringstream& strstr, const std::string& prefix, const std::string& default_textdomain, section& toplevel) const
{
strstr << prefix << "[" << (!level? "toplevel": "section") << "]\n";
if (level) {
strstr << prefix << "\tid = " << id << "\n";
std::vector<t_string_base::trans_str> trans = title.valuex();
if (!trans.empty()) {
if (!trans[0].td.empty() && trans[0].td != default_textdomain) {
strstr << "#textdomain " << trans[0].td << "\n";
}
strstr << prefix << "\ttitle = _ \"" << trans[0].str << "\"\n";
if (!trans[0].td.empty() && trans[0].td != default_textdomain) {
strstr << "#textdomain " << default_textdomain << "\n";
}
}
}
if (!sections.empty()) {
strstr << prefix << "\tsections = ";
for (section_list::const_iterator it = sections.begin(); it != sections.end(); ++ it) {
const section& sec = **it;
if (it != sections.begin()) {
strstr << ", ";
}
strstr << sec.id;
}
strstr << "\n";
}
if (!topics.empty()) {
strstr << prefix << "\ttopics = ";
for (topic_list::const_iterator it = topics.begin(); it != topics.end(); ++ it) {
const topic& t = *it;
if (it != topics.begin()) {
strstr << ", ";
}
strstr << t.id;
}
strstr << "\n";
}
std::map<std::string, treserve_section>::const_iterator it = reserve_sections.find(id);
if (it != reserve_sections.end()) {
strstr << prefix << "\t" << it->second.generator_str << "\n";
}
strstr << prefix << "[/" << (!level? "toplevel": "section") << "]\n";
for (section_list::const_iterator it = sections.begin(); it != sections.end(); ++ it) {
strstr << "\n";
const section& sec = **it;
sec.generate(strstr, prefix, default_textdomain, toplevel);
}
for (topic_list::const_iterator it = topics.begin(); it != topics.end(); ++ it) {
strstr << "\n";
const topic& t = *it;
t.generate(strstr, prefix, default_textdomain, toplevel);
}
}
void section::generate_pot(std::set<std::string>& msgids, const std::string& default_textdomain) const
{
if (!sections.empty()) {
for (section_list::const_iterator it = sections.begin(); it != sections.end(); ++ it) {
const section& sec = **it;
help::generate_pot(msgids, sec.title, default_textdomain);
}
}
for (section_list::const_iterator it = sections.begin(); it != sections.end(); ++ it) {
const section& sec = **it;
sec.generate_pot(msgids, default_textdomain);
}
for (topic_list::const_iterator it = topics.begin(); it != topics.end(); ++ it) {
const topic& t = *it;
t.generate_pot(msgids, default_textdomain);
}
}
std::string generate_about_text()
{
std::vector<std::string> about_lines;
// std::vector<std::string> about_lines = about::get_text();
std::vector<std::string> res_lines;
std::transform(about_lines.begin(), about_lines.end(), std::back_inserter(res_lines),
about_text_formatter());
res_lines.erase(std::remove(res_lines.begin(), res_lines.end(), ""), res_lines.end());
std::string text = utils::join(res_lines, "\n");
return text;
}
std::string generate_separate_text_links()
{
std::stringstream strstr;
strstr << "\n\n";
return strstr.str();
}
std::string generate_contents_links(const std::string& section_name, config const *help_cfg)
{
config const §ion_cfg = help_cfg->find_child("section", "id", section_name);
if (!section_cfg) {
return std::string();
}
std::ostringstream res;
std::vector<std::string> topics = utils::quoted_split(section_cfg["topics"]);
// we use an intermediate structure to allow a conditional sorting
typedef std::pair<std::string,std::string> link;
std::vector<link> topics_links;
std::vector<std::string>::iterator t;
// Find all topics in this section.
for (t = topics.begin(); t != topics.end(); ++t) {
if (config const &topic_cfg = help_cfg->find_child("topic", "id", *t)) {
std::string id = topic_cfg["id"];
if (is_visible_id(id))
topics_links.push_back(link(topic_cfg["title"], id));
}
}
if (section_cfg["sort_topics"] == "yes") {
std::sort(topics_links.begin(),topics_links.end());
}
if (!topics_links.empty()) {
res << generate_separate_text_links();
}
std::vector<link>::iterator l;
for (l = topics_links.begin(); l != topics_links.end(); ++l) {
std::string link = "<ref>text='" + escape(l->first) + "' dst='" + escape(l->second) + "'</ref>";
res << link <<"\n";
}
return res.str();
}
std::string generate_contents_links(const section &sec, const std::vector<topic>& topics)
{
std::stringstream res;
if (!sec.sections.empty() || !topics.empty()) {
res << generate_separate_text_links();
}
section_list::const_iterator s;
for (s = sec.sections.begin(); s != sec.sections.end(); ++s) {
if (is_visible_id((*s)->id)) {
std::string link = "<ref>text='" + escape((*s)->title) + "' dst='.." + escape((*s)->id) + "'</ref>";
res << link <<"\n";
}
}
std::vector<topic>::const_iterator t;
for (t = topics.begin(); t != topics.end(); ++t) {
if (is_visible_id(t->id)) {
std::string link = "<ref>text='" + escape(t->title) + "' dst='" + escape(t->id) + "'</ref>";
res << link <<"\n";
}
}
return res.str();
}
std::string generate_topic_text(const std::string &generator, const config *help_cfg, const section &sec, const std::vector<topic>& generated_topics)
{
std::string empty_string = "";
if (editor || generator == "") {
return empty_string;
} else if (generator == "about") {
return generate_about_text();
} else {
std::vector<std::string> parts = utils::split(generator, ':');
if (parts.size()>1 && parts[0] == "contents") {
if (parts[1] == "generated") {
return generate_contents_links(sec, generated_topics);
} else {
return generate_contents_links(parts[1], help_cfg);
}
}
}
return empty_string;
}
topic* find_topic(section &sec, const std::string &id)
{
topic_list::iterator tit =
std::find_if(sec.topics.begin(), sec.topics.end(), has_id(id));
if (tit != sec.topics.end()) {
return &(*tit);
}
section_list::iterator sit;
for (sit = sec.sections.begin(); sit != sec.sections.end(); ++sit) {
topic *t = find_topic(*(*sit), id);
if (t != NULL) {
return t;
}
}
return NULL;
}
section* find_section(section &sec, const std::string &id)
{
section_list::iterator sit =
std::find_if(sec.sections.begin(), sec.sections.end(), has_id(id));
if (sit != sec.sections.end()) {
return *sit;
}
for (sit = sec.sections.begin(); sit != sec.sections.end(); ++sit) {
section *s = find_section(*(*sit), id);
if (s != NULL) {
return s;
}
}
return NULL;
}
std::pair<section*, int> find_parent(section& sec, const std::string& id)
{
section_list::iterator sit =
std::find_if(sec.sections.begin(), sec.sections.end(), has_id(id));
if (sit != sec.sections.end()) {
return std::make_pair(&sec, std::distance(sec.sections.begin(), sit));
}
topic_list::iterator tit =
std::find_if(sec.topics.begin(), sec.topics.end(), has_id(id));
if (tit != sec.topics.end()) {
return std::make_pair(&sec, std::distance(sec.topics.begin(), tit));
}
std::pair<section*, int> ret(reinterpret_cast<section*>(NULL), -1);
for (sit = sec.sections.begin(); sit != sec.sections.end(); ++sit) {
ret = find_parent(*(*sit), id);
if (ret.first != NULL) {
return ret;
}
}
return ret;
}
/// Return true if the section with id section_id is referenced from
/// another section in the config, or the toplevel.
bool section_is_referenced(const std::string §ion_id, const config &cfg)
{
if (const config &toplevel = cfg.child("toplevel"))
{
const std::vector<std::string> toplevel_refs
= utils::quoted_split(toplevel["sections"]);
if (std::find(toplevel_refs.begin(), toplevel_refs.end(), section_id)
!= toplevel_refs.end()) {
return true;
}
}
BOOST_FOREACH (const config §ion, cfg.child_range("section"))
{
const std::vector<std::string> sections_refd
= utils::quoted_split(section["sections"]);
if (std::find(sections_refd.begin(), sections_refd.end(), section_id)
!= sections_refd.end()) {
return true;
}
}
return false;
}
/// Return true if the topic with id topic_id is referenced from
/// another section in the config, or the toplevel.
bool topic_is_referenced(const std::string &topic_id, const config &cfg)
{
if (const config &toplevel = cfg.child("toplevel"))
{
const std::vector<std::string> toplevel_refs
= utils::quoted_split(toplevel["topics"]);
if (std::find(toplevel_refs.begin(), toplevel_refs.end(), topic_id)
!= toplevel_refs.end()) {
return true;
}
}
BOOST_FOREACH (const config §ion, cfg.child_range("section"))
{
const std::vector<std::string> topics_refd
= utils::quoted_split(section["topics"]);
if (std::find(topics_refd.begin(), topics_refd.end(), topic_id)
!= topics_refd.end()) {
return true;
}
}
return false;
}
void parse_config_internal(gui2::tbook* book, const config *help_cfg, const config *section_cfg,
section &sec, int level)
{
if (level > max_section_level) {
std::cerr << "Maximum section depth has been reached. Maybe circular dependency?"
<< std::endl;
}
else if (section_cfg != NULL) {
const std::vector<std::string> sections = utils::quoted_split((*section_cfg)["sections"]);
sec.level = level;
std::string id = level == 0 ? "toplevel" : (*section_cfg)["id"].str();
if (level != 0) {
if (!is_valid_id(id)) {
std::stringstream ss;
ss << "Invalid ID, used for internal purpose: '" << id << "'";
throw help::parse_error(ss.str());
}
}
t_string title = level == 0 ? "" : (*section_cfg)["title"].t_str();
sec.id = id;
sec.title = title;
std::vector<std::string>::const_iterator it;
// Find all child sections.
for (it = sections.begin(); it != sections.end(); ++it) {
if (const config &child_cfg = help_cfg->find_child("section", "id", *it))
{
section child_section;
parse_config_internal(book, help_cfg, &child_cfg, child_section, level + 1);
sec.add_section(child_section);
}
else {
std::stringstream ss;
ss << "Help-section '" << *it << "' referenced from '"
<< id << "' but could not be found.";
throw help::parse_error(ss.str());
}
}
if (book) {
book->generate_sections(help_cfg, (*section_cfg)["sections_generator"], sec, level);
}
//TODO: harmonize topics/sections sorting
if ((*section_cfg)["sort_sections"] == "yes") {
std::sort(sec.sections.begin(),sec.sections.end(), section_less());
}
bool sort_topics = false;
bool sort_generated = true;
if ((*section_cfg)["sort_topics"] == "yes") {
sort_topics = true;
sort_generated = false;
} else if ((*section_cfg)["sort_topics"] == "no") {
sort_topics = false;
sort_generated = false;
} else if ((*section_cfg)["sort_topics"] == "generated") {
sort_topics = false;
sort_generated = true;
} else if ((*section_cfg)["sort_topics"] != "") {
std::stringstream ss;
ss << "Invalid sort option: '" << (*section_cfg)["sort_topics"] << "'";
throw help::parse_error(ss.str());
}
std::vector<topic> generated_topics;
if (book) {
generated_topics = book->generate_topics(sort_generated,(*section_cfg)["generator"]);
}
const std::vector<std::string> topics_id = utils::quoted_split((*section_cfg)["topics"]);
std::vector<topic> topics;
// Find all topics in this section.
for (it = topics_id.begin(); it != topics_id.end(); ++it) {
if (const config &topic_cfg = help_cfg->find_child("topic", "id", *it))
{
t_string text = topic_cfg["text"].t_str();
text += generate_topic_text(topic_cfg["generator"], help_cfg, sec, generated_topics);
topic child_topic(topic_cfg["title"], topic_cfg["id"], text);
if (!is_valid_id(child_topic.id)) {
std::stringstream ss;
ss << "Invalid ID, used for internal purpose: '" << id << "'";
throw help::parse_error(ss.str());
}
topics.push_back(child_topic);
}
else {
std::stringstream ss;
ss << "Help-topic '" << *it << "' referenced from '" << id
<< "' but could not be found." << std::endl;
throw help::parse_error(ss.str());
}
}
if (sort_topics) {
std::sort(topics.begin(),topics.end(), title_less());
std::sort(generated_topics.begin(),
generated_topics.end(), title_less());
std::merge(generated_topics.begin(),
generated_topics.end(),topics.begin(),topics.end()
,std::back_inserter(sec.topics),title_less());
}
else {
std::copy(topics.begin(), topics.end(),
std::back_inserter(sec.topics));
std::copy(generated_topics.begin(),
generated_topics.end(),
std::back_inserter(sec.topics));
}
}
}
section parse_config(gui2::tbook* book, const config *cfg)
{
section sec;
if (cfg != NULL) {
config const &toplevel_cfg = cfg->child("toplevel");
parse_config_internal(book, cfg, toplevel_cfg ? &toplevel_cfg : NULL, sec);
}
return sec;
}
void generate_contents(gui2::tbook* book, const std::string& tag, section& toplevel)
{
toplevel.clear();
hidden_sections.clear();
const config *help_config = &game_cfg->find_child("book", "id", tag);
if (!*help_config) {
help_config = &dummy_cfg;
}
try {
toplevel = parse_config(book, help_config);
// Create a config object that contains everything that is
// not referenced from the toplevel element. Read this
// config and save these sections and topics so that they
// can be referenced later on when showing help about
// specified things, but that should not be shown when
// opening the help browser in the default manner.
config hidden_toplevel;
std::stringstream ss;
BOOST_FOREACH (const config §ion, help_config->child_range("section"))
{
const std::string id = section["id"];
if (find_section(toplevel, id) == NULL) {
// This section does not exist referenced from the
// toplevel. Hence, add it to the hidden ones if it
// is not referenced from another section.
if (!section_is_referenced(id, *help_config)) {
if (ss.str() != "") {
ss << ",";
}
ss << id;
}
}
}
hidden_toplevel["sections"] = ss.str();
ss.str("");
BOOST_FOREACH (const config &topic, help_config->child_range("topic"))
{
const std::string id = topic["id"];
if (find_topic(toplevel, id) == NULL) {
if (!topic_is_referenced(id, *help_config)) {
if (ss.str() != "") {
ss << ",";
}
ss << id;
}
}
}
hidden_toplevel["topics"] = ss.str();
config hidden_cfg = *help_config;
// Change the toplevel to our new, custom built one.
hidden_cfg.clear_children("toplevel");
hidden_cfg.add_child("toplevel", hidden_toplevel);
hidden_sections = parse_config(book, &hidden_cfg);
}
catch (help::parse_error e) {
std::stringstream msg;
msg << "Parse error when parsing help text: '" << e.message << "'";
VALIDATE(false, msg.str());
}
}
} // End namespace help.
std::string single_digit_image(int digit)
{
if (digit < 0 || digit > 9) {
return null_str;
}
std::stringstream strstr;
strstr << "misc/digit.png~CROP(" << 8 * digit << ", 0, 8, 12)";
return strstr.str();
}
std::string multi_digit_image_str(int integer)
{
if (integer < 0) {
return null_str;
}
std::vector<int> digits;
digits.push_back(integer % 10);
int descend = integer / 10;
while (descend) {
digits.push_back(descend % 10);
descend /= 10;
}
std::stringstream img, strstr;
for (std::vector<int>::const_reverse_iterator it = digits.rbegin(); it != digits.rend(); ++ it) {
int digit = *it;
img.str("");
img << "misc/digit.png~CROP(" << 8 * digit << ", 0, 8, 12)";
strstr << tintegrate::generate_img(img.str());
}
return strstr.str();
}
SDL_Point multi_digit_image_size(int integer)
{
int digits = 1;
int descend = integer / 10;
while (descend) {
digits ++;
descend /= 10;
}
SDL_Point ret;
ret.x = 8 * digits;
ret.y = 12;
return ret;
} | [
"ancientcc@gmail.com"
] | ancientcc@gmail.com |
041be98441ab83c76d9f870115002ccd8052b464 | 27c917a12edbfd2dba4f6ce3b09aa2e3664d3bb1 | /Tree/array_to_BST.cpp | 2e2345db1c9314994badcf7c23c5079e95d822a0 | [] | no_license | Spetsnaz-Dev/CPP | 681ba9be0968400e00b5b2cb9b52713f947c66f8 | 88991e3b7164dd943c4c92784d6d98a3c9689653 | refs/heads/master | 2023-06-24T05:32:30.087866 | 2021-07-15T19:33:02 | 2021-07-15T19:33:02 | 193,662,717 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,344 | cpp | #include<iostream>
using namespace std;
struct Node{
int data;
Node* right;
Node* left;
};
Node* newNode(int x)
{
Node* ptr = (Node*)malloc(sizeof(Node*));
ptr->data =x;
ptr->left = NULL;
ptr->right = NULL;
return ptr;
}
Node *buildBST(int arr[], int low, int high)
{
int mid = (low+high)/2;
Node *root = newNode(arr[mid]);
buildBST(arr, low, mid-1);
buildBST(arr, mid+1, high);
return root;
}
void preorder(Node *root){
if(!root)
return;
cout<<root->data<<" ";
preorder(root->left);
preorder(root->right);
}
int main()
{
int t;
cin>>t;
while(t--) {
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
Node *root = buildBST(arr, 0, n-1);
preorder(root);
cout<<"\n";
}
return 0;
}
//Method 2
TreeNode *buildBST(TreeNode* &root, int ele) {
if(!root)
return root = new TreeNode(ele);
if(root->val > ele)
root->left = buildBST(root->left, ele);
else
root->right = buildBST(root->right, ele);
return root;
}
TreeNode* bstFromPreorder(vector<int>& pre) {
TreeNode *root = NULL;
for(auto x : pre)
buildBST(root, x);
return root;
} | [
"ravindrafk@gmail.com"
] | ravindrafk@gmail.com |
78160b9794a37ad495158e98d9fb6021fbd9097b | cf91c0b8248ad922a58b756cd94ac6d7c72a0881 | /ESC.ino | dca0a23e864d5391d659714d52642d6ca27e77bf | [] | no_license | yasirfaizahmed/Arduino_repository | f20288bf0b91b10130ef23965490559f12bc5b6d | 5cb0563fa455269e813ca74e26c4f93ea044e71b | refs/heads/master | 2020-05-15T19:06:46.111792 | 2019-12-28T13:42:05 | 2019-12-28T13:42:05 | 182,446,657 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 531 | ino | #include <Servo.h>
Servo ESC; // create servo object to control the ESC
int potValue; // value from the analog pin
void setup() {
// Attach the ESC on pin 9
ESC.attach(9,1000,2000); // (pin, min pulse width, max pulse width in microseconds)
}
void loop() {
potValue = analogRead(A0); // reads the value of the potentiometer (value between 0 and 1023)
potValue = map(potValue, 0, 1023, 0, 180); // scale it to use it with the servo library (value between 0 and 180)
ESC.write(potValue); // Send the signal to the ESC
}
| [
"noreply@github.com"
] | yasirfaizahmed.noreply@github.com |
175be1719b2a04ab851a40fb2dc411f85b87f774 | a5ea23ee7cd18bde94b8ae26bdf3224f64ebc70f | /C++/Day-1/Day-1-B.cpp | a9a73fab5772d861a7c982ab85325bc7128f9a19 | [] | no_license | Back-Log/AITH-CP-Club | f8c9f59c85bf6bc9d4a05ad0525b908a4dacdc35 | 164b4bca8a427c9608a891d3d684f49424f1b0ea | refs/heads/main | 2023-02-18T15:25:59.513175 | 2021-01-23T17:00:27 | 2021-01-23T17:00:27 | 332,251,508 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 143 | cpp | #include<bits/stdc++.h>
using namespace std;
int main() {
int n;
cin>>n;
cout<<(((n%2==0) and (n!=2))?"YES":"NO");
return 0;
}
| [
"64234448+Back-Log-Pratyush@users.noreply.github.com"
] | 64234448+Back-Log-Pratyush@users.noreply.github.com |
3c4237f37b509e8bde03ecc435459419c7b57fb0 | 006ac2f948ad3cf5e7ca646daa1a2130d23c42dd | /c++/《OpenCV图像处理编程实例-源码-20160801/chapter2/2-11.cpp | 0889a54f248573248dc443072ff28c512e7f8e0d | [] | no_license | gitgaoqian/OpenCv | 610463e2bc8bfdb648cf4378ebe6f6891803c3c3 | 2f86037969f002bb7787364deabcb4ea7e753830 | refs/heads/master | 2020-04-10T22:05:44.031755 | 2018-12-11T10:15:52 | 2018-12-11T10:15:52 | 161,315,015 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,573 | cpp | // 功能:代码 2-11 旋转变换
// 作者:朱伟 zhu1988wei@163.com
// 来源:《OpenCV图像处理编程实例》
// 博客:http://blog.csdn.net/zhuwei1988
// 更新:2016-8-1
// 说明:版权所有,引用或摘录请联系作者,并按照上面格式注明出处,谢谢。
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>
#include <cmath>
using namespace cv;
using namespace std;
cv::Mat angelRotate(cv::Mat& src, int angle)
{
// 角度转换
float alpha = angle * CV_PI / 180;
// 构造旋转矩阵
float rotateMat[3][3] = {
{cos(alpha), -sin(alpha), 0},
{sin(alpha), cos(alpha), 0},
{0, 0, 1} };
int nSrcRows = src.rows;
int nSrcCols = src.cols;
// 计算旋转后图像矩阵各个顶点位置
float a1 = nSrcCols * rotateMat[0][0] ;
float b1 = nSrcCols * rotateMat[1][0] ;
float a2 = nSrcCols * rotateMat[0][0] +
nSrcRows * rotateMat[0][1];
float b2 = nSrcCols * rotateMat[1][0] +
nSrcRows * rotateMat[1][1];
float a3 = nSrcRows * rotateMat[0][1];
float b3 = nSrcRows * rotateMat[1][1];
// 计算出极值点
float kxMin = min( min( min(0.0f,a1), a2 ), a3);
float kxMax = max( max( max(0.0f,a1), a2 ), a3);
float kyMin = min( min( min(0.0f,b1), b2 ), b3);
float kyMax = max( max( max(0.0f,b1), b2 ), b3);
// 计算输出矩阵的尺寸
int nRows = abs(kxMax - kxMin);
int nCols = abs(kyMax - kyMin);
cv::Mat dst(nRows, nCols, src.type(),cv::Scalar::all(0));
for( int i = 0; i < nRows; ++i)
{
for (int j = 0; j < nCols; ++j)
{
// 旋转坐标转换
int x = (j + kxMin) * rotateMat[0][0] -
(i + kyMin) * rotateMat[0][1] ;
int y = -(j + kxMin) * rotateMat[1][0] +
(i + kyMin) * rotateMat[1][1] ;
if( (x >= 0) && (x < nSrcCols) &&
(y >= 0) && (y < nSrcRows) )
{
dst.at<cv::Vec3b>(i,j) =
src.at<cv::Vec3b>(y,x);
}
}
}
return dst;
}
int main()
{
cv::Mat srcImage = cv::imread("..\\images\\pool.jpg");
if(!srcImage.data)
return -1;
cv::imshow("srcImage", srcImage);
int angle = 30;
cv::Mat resultImage = angelRotate(srcImage, angle);
imshow("resultImage", resultImage);
cv::waitKey(0);
return 0;
}
| [
"734756851@qq.com"
] | 734756851@qq.com |
5824ef7db52242bad8e07095fdd4ceb727cc48e1 | 2134298eaeedc3d0efe98939676b41b17a8db7c8 | /RoutTableAdder.h | b96c87f43530e76eb0fca7664f2d6f2eadf6643b | [] | no_license | CSEKimDoYeon/DC-RouterTestApp | dfd26454f8c55a42d3a97d81dc0c3cb63d86f620 | ab16209eb5078d7d1f23781ef008185809213806 | refs/heads/master | 2020-04-07T16:11:43.652915 | 2018-11-21T08:57:59 | 2018-11-21T08:57:59 | 158,519,255 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,212 | h | #pragma once
#include "afxcmn.h"
#include "afxwin.h"
// CRoutTableAdder 대화 상자입니다.
class CRoutTableAdder : public CDialog
{
DECLARE_DYNAMIC(CRoutTableAdder)
public:
CRoutTableAdder(); // 표준 생성자입니다.
virtual ~CRoutTableAdder();
// 대화 상자 데이터입니다.
enum { IDD = IDD_ROUTE_ADD_DLG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다.
DECLARE_MESSAGE_MAP()
public:
CString d1,d2;
void setDeviceList(CString dev1,CString dev2);
unsigned char dest_ip[4];
unsigned char net_ip[4];
unsigned char gate_ip[4];
unsigned char flag;
int router_interface;
// routetableDestination
CIPAddressCtrl m_add_dest;
CIPAddressCtrl m_add_netmask;
CIPAddressCtrl m_gateway;
CComboBox m_add_interface;
CButton m_flag_u;
CButton m_flag_g;
CButton m_flag_h;
afx_msg void OnBnClickedOk();
afx_msg void OnBnClickedCancel();
// get destination
unsigned char * GetDestIp(void);
// get netmask
unsigned char * GetNetmask(void);
// get Gateway
unsigned char * GetGateway(void);
// get inter face
int GetInterface(void);
// get metric
int GetMetric(void);
// get flag
unsigned char GetFlag(void);
int m_metric;
};
| [
"ehdus0008@naver.com"
] | ehdus0008@naver.com |
c0438cdda1973aafa615c41d320d263519658c28 | b3c47795e8b6d95ae5521dcbbb920ab71851a92f | /Leetcode/Algorithm/cpp/00026-Remove Duplicates from Sorted Array.cc | 655b71eb697768dccb78d54fd76c76a7bf9632df | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | Wizmann/ACM-ICPC | 6afecd0fd09918c53a2a84c4d22c244de0065710 | 7c30454c49485a794dcc4d1c09daf2f755f9ecc1 | refs/heads/master | 2023-07-15T02:46:21.372860 | 2023-07-09T15:30:27 | 2023-07-09T15:30:27 | 3,009,276 | 51 | 23 | null | null | null | null | UTF-8 | C++ | false | false | 276 | cc | class Solution {
public:
int removeDuplicates(int A[], int n) {
int ptr = 0;
for (int i = 0; i < n; i++) {
if (i && A[i] == A[i - 1]) {
continue;
}
A[ptr++] = A[i];
}
return ptr;
}
};
| [
"mail.kuuy@gmail.com"
] | mail.kuuy@gmail.com |
d62f08a68dae57354f14046bfc572f2d1682234d | cb3fff5404fc151e064a586895245e796f025425 | /assignment2/salestax.cpp | ce718424a877990f7328d39206b1f57dd91b0bd0 | [] | no_license | hkumar01/interterm2021-c- | 5dd5b70bb30d633e6ed29f570387a25439d1d411 | a63b53d98b5aff2bbe85d3ae00b6a51b003efb17 | refs/heads/main | 2023-02-25T14:07:23.616171 | 2021-01-29T12:28:22 | 2021-01-29T12:28:22 | 333,880,268 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 480 | cpp | #include <iostream>
using namespace std;
float addTax(float cost, float taxRate)
{
cost = cost + (cost * taxRate);
return cost;
}
int main(int argc, char**argv)
{
float totalCost;
float salesTax;
cout << "Enter total cost: " << endl;
cin >> totalCost;
cout << "Enter sales tax rate as decimal value: " << endl;
cin >> salesTax;
totalCost = addTax(totalCost, salesTax);
cout << "Total cost with tax is: " << totalCost << endl;
}
| [
"hkumar@chapman.edu"
] | hkumar@chapman.edu |
e3b94f1ef8574a3e2ba28b683ace27d98c980702 | 50af63dc9be5ca24a6fca484148314496ca68816 | /Components/XNOR3.cpp | 56291cfaeedef5dda5f99a17ffe20095486dd3bc | [] | no_license | Shaalan31/LogicGatesSimulator | 055e52e62fc6ead692b2bd2a0d24b4d3b225c88f | 854556897f8060a6f82dc9459ffabb1b8ae5719a | refs/heads/master | 2021-01-25T00:47:56.713881 | 2017-06-18T14:45:05 | 2017-06-18T14:45:05 | 94,691,266 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,745 | cpp | #include "XNOR3.h"
XNOR3::XNOR3(const GraphicsInfo &r_GfxInfo, int r_FanOut) :Gate(3, r_FanOut)
{
selected = false;
type = XNOR3gate;
m_GfxInfo.x1 = r_GfxInfo.x1;
m_GfxInfo.y1 = r_GfxInfo.y1;
m_GfxInfo.x2 = r_GfxInfo.x2;
m_GfxInfo.y2 = r_GfxInfo.y2;
}
void XNOR3::Operate()
{
//caclulate the output status as the ANDing of the two input pins
//Add you code here
if (m_InputPins[0].getStatus() == HIGH && m_InputPins[1].getStatus() == HIGH && m_InputPins[2].getStatus() == HIGH)
m_OutputPin.setStatus(HIGH);
else if (m_InputPins[0].getStatus() == HIGH && m_InputPins[1].getStatus() == HIGH && m_InputPins[2].getStatus() == LOW)
m_OutputPin.setStatus(HIGH);
else if (m_InputPins[0].getStatus() == HIGH && m_InputPins[1].getStatus() == LOW && m_InputPins[2].getStatus() == HIGH)
m_OutputPin.setStatus(HIGH);
else if (m_InputPins[0].getStatus() == LOW && m_InputPins[1].getStatus() == HIGH && m_InputPins[2].getStatus() == HIGH)
m_OutputPin.setStatus(HIGH);
else if (m_InputPins[0].getStatus() == LOW && m_InputPins[1].getStatus() == LOW && m_InputPins[2].getStatus() == HIGH)
m_OutputPin.setStatus(HIGH);
else
m_OutputPin.setStatus(LOW);
}
int XNOR3::getXcoordiantescorner1()
{
return m_GfxInfo.x1;
}
int XNOR3::getYcoordiantescorner1()
{
return m_GfxInfo.y1;
}
int XNOR3::getXcoordiantescorner2()
{
return m_GfxInfo.x2;
}
bool XNOR3::checkempty(int x, int y, GraphicsInfo GI)
{
int xedge1, xedge2, yedge1, yedge2;
xedge1 = x - 25;
xedge2 = x + 25;
yedge1 = y - 25;
yedge2 = y + 25;
if (((xedge1 >= GI.x1) && (xedge1 <= GI.x2)) || ((yedge2 >= GI.y1) && (yedge2 <= GI.y2)))
{
return false;
}
return true;
}
bool XNOR3::checkArea(int x, int y)
{
if ((x >= getXcoordiantescorner1()) && (y >= getYcoordiantescorner1()) && (x <= getXcoordiantescorner2()) && (y <= getYcoordiantescorner2()))
{
return true;
}
return false;
}
int XNOR3::getYcoordiantescorner2()
{
return m_GfxInfo.y2;
}
// Function Draw
// Draws 2-input AND gate
void XNOR3::Draw(Output* pOut)
{
//Call output class and pass gate drawing info to it.
pOut->DrawXNOR(m_GfxInfo);
pOut->PrintMsg("REMEMBER TO MAKE IT 3 INPUT");
pOut->PrintString(getXcoordiantescorner1(), getYcoordiantescorner1() - 20, m_Label);
}
//returns status of outputpin
int XNOR3::GetOutPinStatus()
{
return m_OutputPin.getStatus();
}
//returns status of Inputpin #n
int XNOR3::GetInputPinStatus(int n)
{
return m_InputPins[n - 1].getStatus(); //n starts from 1 but array index starts from 0.
}
//Set status of an input pin ot HIGH or LOW
void XNOR3::setInputPinStatus(int n, STATUS s)
{
m_InputPins[n - 1].setStatus(s);
}
| [
"noreply@github.com"
] | Shaalan31.noreply@github.com |
dcd0fda16086cfbb13f904d4aa7edb316d66319a | 1393b088958301a6c2f6766df2864c61365e9d4b | /Testing/TU/Code/Algorithms/L2/AtmosphericAbsorptionCorrection/vnsWaterAmountImageGeneratorNew.cxx | 432f0c391a166b9ed9c0017293d6c563fdb02ce3 | [
"Apache-2.0"
] | permissive | alexgoussev/maja_gitlab | f6727468cb70e210d3c09453de22fee58ed9d656 | 9688780f8dd8244e60603e1f11385e1fadc90cb4 | refs/heads/develop | 2023-02-24T05:37:38.769452 | 2021-01-21T16:47:54 | 2021-01-21T16:47:54 | 332,269,078 | 0 | 0 | Apache-2.0 | 2021-01-23T18:17:25 | 2021-01-23T17:33:18 | C++ | UTF-8 | C++ | false | false | 5,437 | cxx | /*
* Copyright (C) 2020 Centre National d'Etudes Spatiales (CNES)
*
* 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.
*
*/
/************************************************************************************************************
* *
* ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo *
* o *
* o *
* o *
* o *
* o ooooooo ooooooo o o oo *
* o o o o o o o o o o *
* o o o o o o o o o o *
* o o o o o o o o o o *
* o o o oooo o o o o o o *
* o o o o o o o o o *
* o o o o o o o o o o *
* oo oooooooo o o o oooooo o oooo *
* o *
* o *
* o o *
* o o oooo o o oooo *
* o o o o o o *
* o o ooo o o ooo *
* o o o o o *
* ooooo oooo o ooooo oooo *
* o *
* *
************************************************************************************************************
* *
* Author: CS Systemes d'Information (France) *
* *
************************************************************************************************************
* HISTORIQUE *
* *
* VERSION : 1-0-0 : <TypeFT> : <NumFT> : 9 avr. 2010 : Creation
* *
* FIN-HISTORIQUE *
* *
* $Id$
* *
************************************************************************************************************/
#include "itkMacro.h"
#include "vnsWaterAmountImageGenerator.h"
#include "otbVectorImage.h"
#include "otbImage.h"
#include "vnsLookUpTable.h"
int vnsWaterAmountImageGeneratorNew(int /*argc*/, char * /*argv*/[])
{
typedef double PixelType;
typedef otb::VectorImage<PixelType> VectorInpuImageType;
typedef otb::Image<PixelType> ImageType;
typedef vns::LookUpTable<double, 2> LUTType;
typedef vns::WaterAmountImageGenerator<VectorInpuImageType,ImageType,LUTType> WaterAmountImageGeneratorType;
// Instantiating object
WaterAmountImageGeneratorType::Pointer object = WaterAmountImageGeneratorType::New();
return EXIT_SUCCESS;
}
| [
"julie.brossard@c-s.fr"
] | julie.brossard@c-s.fr |
3211bc94d9280920198f3c8840d58597b848c6b2 | bf023953b735f3c877e5af047526688e88e17bb3 | /demos/simple-udp/playground/net_stream.h | e90b7a1358298eeff1ce9c6516034215bb59ea52 | [] | no_license | puma10100505/documents | f38d37496602009deb1910d55a91bbaee27e82dd | c1b8b69d1109403de4215852e6768370a5bd214b | refs/heads/master | 2020-11-26T05:39:59.094822 | 2020-09-04T12:13:32 | 2020-09-04T12:13:32 | 228,979,105 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,298 | h | /*
Simple Network Library from "Networking for Game Programmers"
http://www.gaffer.org/networking-for-game-programmers
Author: Glenn Fiedler <gaffer@gaffer.org>
*/
#ifndef NET_STREAM_H
#define NET_STREAM_H
#include <assert.h>
#include <string.h>
#include <algorithm>
namespace net
{
// bitpacker class
// + read and write non-8 multiples of bits efficiently
class BitPacker
{
public:
enum Mode
{
Read,
Write
};
BitPacker( Mode mode, void * buffer, int bytes )
{
assert( bytes >= 0 );
this->mode = mode;
this->buffer = (unsigned char*) buffer;
this->ptr = (unsigned char*) buffer;
this->bytes = bytes;
bit_index = 0;
if ( mode == Write )
memset( buffer, 0, bytes );
}
void WriteBits( unsigned int value, int bits = 32 )
{
assert( ptr );
assert( buffer );
assert( bits > 0 );
assert( bits <= 32 );
assert( mode == Write );
if ( bits < 32 )
{
const unsigned int mask = ( 1 << bits ) - 1;
value &= mask;
}
do
{
assert( ptr - buffer < bytes );
*ptr |= (unsigned char) ( value << bit_index );
assert( bit_index < 8 );
const int bits_written = std::min( bits, 8 - bit_index );
assert( bits_written > 0 );
assert( bits_written <= 8 );
bit_index += bits_written;
if ( bit_index >= 8 )
{
ptr++;
bit_index = 0;
value >>= bits_written;
}
bits -= bits_written;
assert( bits >= 0 );
assert( bits <= 32 );
}
while ( bits > 0 );
}
void ReadBits( unsigned int & value, int bits = 32 )
{
assert( ptr );
assert( buffer );
assert( bits > 0 );
assert( bits <= 32 );
assert( mode == Read );
int original_bits = bits;
int value_index = 0;
value = 0;
do
{
assert( ptr - buffer < bytes );
assert( bits >= 0 );
assert( bits <= 32 );
int bits_to_read = std::min( 8 - bit_index, bits );
assert( bits_to_read > 0 );
assert( bits_to_read <= 8 );
value |= ( *ptr >> bit_index ) << value_index;
bits -= bits_to_read;
bit_index += bits_to_read;
value_index += bits_to_read;
assert( value_index >= 0 );
assert( value_index <= 32 );
if ( bit_index >= 8 )
{
ptr++;
bit_index = 0;
}
}
while ( bits > 0 );
if ( original_bits < 32 )
{
const unsigned int mask = ( 1 << original_bits ) - 1;
value &= mask;
}
}
void * GetData()
{
return buffer;
}
int GetBits() const
{
return ( ptr - buffer ) * 8 + bit_index;
}
int GetBytes() const
{
return (int) ( ptr - buffer ) + ( bit_index > 0 ? 1 : 0 );
}
int BitsRemaining() const
{
return bytes * 8 - ( ( ptr - buffer ) * 8 + bit_index );
}
Mode GetMode() const
{
return mode;
}
bool IsValid() const
{
return buffer != NULL;
}
private:
int bit_index;
unsigned char * ptr;
unsigned char * buffer;
int bytes;
Mode mode;
};
// arithmetic coder
// + todo: implement arithmetic coder based on jon blow's game developer article
class ArithmeticCoder
{
public:
enum Mode
{
Read,
Write
};
ArithmeticCoder( Mode mode, void * buffer, unsigned int size )
{
assert( buffer );
assert( size >= 0 );
this->mode = mode;
this->buffer = (unsigned char*) buffer;
this->size = size;
}
bool WriteInteger( unsigned int value, unsigned int minimum = 0, unsigned int maximum = 0xFFFFFFFF )
{
// ...
return false;
}
bool ReadInteger( unsigned int value, unsigned int minimum = 0, unsigned int maximum = 0xFFFFFFFF )
{
// ...
return false;
}
private:
unsigned char * buffer;
int size;
Mode mode;
};
// stream class
// + unifies read and write into a serialize operation
// + provides attribution of stream for debugging purposes
class Stream
{
public:
enum Mode
{
Read,
Write
};
Stream( Mode mode, void * buffer, int bytes, void * journal_buffer = NULL, int journal_bytes = 0 )
: bitpacker( mode == Write ? BitPacker::Write : BitPacker::Read, buffer, bytes ),
journal( mode == Write ? BitPacker::Write : BitPacker::Read, journal_buffer, journal_bytes )
{
}
bool SerializeBoolean( bool & value )
{
unsigned int tmp = (unsigned int) value;
bool result = SerializeBits( tmp, 1 );
value = (bool) tmp;
return result;
}
bool SerializeByte( char & value, char min = -127, char max = +128 )
{
// wtf: why do I have to do this!?
unsigned int tmp = (unsigned int) ( value + 127 );
bool result = SerializeInteger( tmp, (unsigned int ) ( min + 127 ), ( max + 127 ) );
value = ( (char) tmp ) - 127;
return result;
}
bool SerializeByte( signed char & value, signed char min = -127, signed char max = +128 )
{
unsigned int tmp = (unsigned int) ( value + 127 );
bool result = SerializeInteger( tmp, (unsigned int ) ( min + 127 ), ( max + 127 ) );
value = ( (signed char) tmp ) - 127;
return result;
}
bool SerializeByte( unsigned char & value, unsigned char min = 0, unsigned char max = 0xFF )
{
unsigned int tmp = (unsigned int) value;
bool result = SerializeInteger( tmp, min, max );
value = (unsigned char) tmp;
return result;
}
bool SerializeShort( signed short & value, signed short min = -32767, signed short max = +32768 )
{
unsigned int tmp = (unsigned int) ( value + 32767 );
bool result = SerializeInteger( tmp, (unsigned int ) ( min + 32767 ), ( max + 32767 ) );
value = ( (signed short) tmp ) - 32767;
return result;
}
bool SerializeShort( unsigned short & value, unsigned short min = 0, unsigned short max = 0xFFFF )
{
unsigned int tmp = (unsigned int) value;
bool result = SerializeInteger( tmp, min, max );
value = (unsigned short) tmp;
return result;
}
bool SerializeInteger( signed int & value, signed int min = -2147483646, signed int max = +2147483647 )
{
unsigned int tmp = (unsigned int) ( value + 2147483646 );
bool result = SerializeInteger( tmp, (unsigned int ) ( min + 2147483646 ), ( max + 2147483646 ) );
value = ( (signed int) tmp ) - 2147483646;
return result;
}
bool SerializeInteger( unsigned int & value, unsigned int min = 0, unsigned int max = 0xFFFFFFFF )
{
assert( min < max );
if ( IsWriting() )
{
assert( value >= min );
assert( value <= max );
}
const int bits_required = BitsRequired( min, max );
unsigned int bits = value - min;
bool result = SerializeBits( bits, bits_required );
if ( IsReading() )
{
value = bits + min;
assert( value >= min );
assert( value <= max );
}
return result;
}
bool SerializeFloat( float & value )
{
union FloatInt
{
unsigned int i;
float f;
};
if ( IsReading() )
{
FloatInt floatInt;
if ( !SerializeBits( floatInt.i, 32 ) )
return false;
value = floatInt.f;
return true;
}
else
{
FloatInt floatInt;
floatInt.f = value;
return SerializeBits( floatInt.i, 32 );
}
}
bool SerializeBits( unsigned int & value, int bits )
{
assert( bits >= 1 );
assert( bits <= 32 );
if ( bitpacker.BitsRemaining() < bits )
return false;
if ( journal.IsValid() )
{
unsigned int token = 2 + bits; // note: 0 = end, 1 = checkpoint, [2,34] = n - 2 bits written
if ( IsWriting() )
{
journal.WriteBits( token, 6 );
}
else
{
journal.ReadBits( token, 6 );
int bits_written = token - 2;
if ( bits != bits_written )
{
printf( "desync read/write: attempting to read %d bits when %d bits were written\n", bits, bits_written );
return false;
}
}
}
if ( IsReading() )
bitpacker.ReadBits( value, bits );
else
bitpacker.WriteBits( value, bits );
return true;
}
bool Checkpoint()
{
if ( journal.IsValid() )
{
unsigned int token = 1; // note: 0 = end, 1 = checkpoint, [2,34] = n - 2 bits written
if ( IsWriting() )
{
journal.WriteBits( token, 6 );
}
else
{
journal.ReadBits( token, 6 );
if ( token != 1 )
{
printf( "desync read/write: checkpoint not present in journal\n" );
return false;
}
}
}
unsigned int magic = 0x12345678;
unsigned int value = magic;
if ( bitpacker.BitsRemaining() < 32 )
{
printf( "not enough bits remaining for checkpoint\n" );
return false;
}
if ( IsWriting() )
bitpacker.WriteBits( value, 32 );
else
bitpacker.ReadBits( value, 32 );
if ( value != magic )
{
printf( "checkpoint failed!\n" );
return false;
}
return true;
}
bool IsReading() const
{
return bitpacker.GetMode() == BitPacker::Read;
}
bool IsWriting() const
{
return bitpacker.GetMode() == BitPacker::Write;
}
int GetBitsProcessed() const
{
return bitpacker.GetBits();
}
int GetBitsRemaining() const
{
return bitpacker.BitsRemaining();
}
static int BitsRequired( unsigned int minimum, unsigned int maximum )
{
assert( maximum > minimum );
assert( maximum >= 1 );
if ( maximum - minimum >= 0x7FFFFFF )
return 32;
return BitsRequired( maximum - minimum + 1 );
}
static int BitsRequired( unsigned int distinctValues )
{
assert( distinctValues > 1 );
unsigned int maximumValue = distinctValues - 1;
for ( int index = 0; index < 32; ++index )
{
if ( ( maximumValue & ~1 ) == 0 )
return index + 1;
maximumValue >>= 1;
}
return 32;
}
int GetDataBytes() const
{
return bitpacker.GetBytes();
}
int GetJournalBytes() const
{
return journal.GetBytes();
}
void DumpJournal()
{
if ( journal.IsValid() )
{
printf( "-----------------------------\n" );
printf( "dump journal:\n" );
BitPacker reader( BitPacker::Read, journal.GetData(), journal.GetBytes() );
while ( reader.BitsRemaining() > 6 )
{
unsigned int token = 0;
reader.ReadBits( token, 6 );
if ( token == 0 )
break;
if ( token == 1 )
printf( " (checkpoint)\n" );
else
printf( " + %d bits\n", token - 2 );
}
printf( "-----------------------------\n" );
}
else
printf( "no journal exists!\n" );
}
private:
BitPacker bitpacker;
BitPacker journal;
};
}
#endif | [
"yinpsoft@vip.qq.com"
] | yinpsoft@vip.qq.com |
57925ea0e476b821a17b75d7e104b0d4f1007135 | 4d3b52892720a540e35809c8c3a6925f1b887857 | /src/symboltable.cpp | 2d7652baf3a50c0be8871b9cf866b20ab4426c09 | [
"MIT"
] | permissive | AshOlogn/ash-language-interpreter | f2376785a1bdd09bea982902691c79601e8019ff | add9f2cc76edd3a91e38446fb4c11a1ce1348af0 | refs/heads/master | 2020-03-18T18:22:42.991069 | 2018-08-28T10:32:37 | 2018-08-28T10:32:37 | 135,088,789 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 3,313 | cpp | #include <string>
#include <vector>
#include <iostream>
#include <unordered_map>
#include "parsetoken.h"
#include "symboltable.h"
using namespace std;
SymbolTable::SymbolTable() {
table = new vector<unordered_map<string, ParseData>*>();
table->push_back(new unordered_map<string, ParseData>());
depth = 0;
}
void SymbolTable::enterNewScope() {
//the next time something is added, a new symbol table is created
table->push_back(new unordered_map<string, ParseData>());
depth++;
}
void SymbolTable::leaveScope() {
//leave a scope, so discard "innermost" symbol table
table->pop_back();
depth--;
}
//create new key in innermost scope
void SymbolTable::declare(string var, ParseData value) {
//get symbol table at innermost scope
unordered_map<string, ParseData>* map = table->back();
//add element to the map
(*map)[var] = value;
}
//update value in innermost scope in which it is found
void SymbolTable::update(string var, ParseData value) {
//start at innermost scope and work your way up
vector<unordered_map<string, ParseData>*>::reverse_iterator rit;
for(rit = table->rbegin(); rit != table->rend(); rit++) {
//map at this particular scope
unordered_map<string, ParseData>* map = (*rit);
//if this map contains it, update its value
if(map->find(var) != map->end()) {
(*map)[var] = value;
return;
}
}
}
//returns if variable is already declared in current innermost scope
bool SymbolTable::isDeclaredInScope(string var) {
unordered_map<string, ParseData>* map = *(table->rbegin());
return map->find(var) != map->end();
}
//returns if variable is declared anywhere at all
bool SymbolTable::isDeclared(string var) {
//start at innermost scope and work your way up
vector<unordered_map<string, ParseData>*>::reverse_iterator rit;
for(rit = table->rbegin(); rit != table->rend(); rit++) {
//map at this particular scope
unordered_map<string, ParseData>* map = (*rit);
//if this map contains it, return true
if(map->find(var) != map->end())
return true;
}
return false;
}
ParseData SymbolTable::get(string var) {
//start at innermost scope and work your way up
vector<unordered_map<string, ParseData>*>::reverse_iterator rit;
for(rit = table->rbegin(); rit != table->rend(); rit++) {
//map at this particular scope
unordered_map<string, ParseData>* map = (*rit);
//see if this map contains the variable
unordered_map<string, ParseData>::const_iterator value = map->find(var);
if(value != map->end())
return value->second;
}
//not found, return "invalid" data
ParseData d;
d.type = INVALID_T;
return d;
}
std::string SymbolTable::toString() {
std::string str = "";
//loop through all the hash maps
std::vector<std::unordered_map<string, ParseData>*>::iterator it;
for(it = table->begin(); it != table->end(); it++) {
//loop through the keys in the hash map and print those
std::unordered_map<string, ParseData>::iterator it2;
for(it2 = (*it)->begin(); it2 != (*it)->end(); it2++) {
str.append(it2->first);
str.append(", ");
str.append(toStringParseDataType(it2->second.type));
str.append("\n");
}
str.append("----------------------------\n");
}
str.append("end of table");
return str;
}
| [
"ashwin.dev.pro@gmail.com"
] | ashwin.dev.pro@gmail.com |
d32add1faca3d399b4fc9a128da783ed2909f090 | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/073/272/CWE122_Heap_Based_Buffer_Overflow__sizeof_double_83_bad.cpp | 40722bbb789844d72537f98db016824cfcb70714 | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,431 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE122_Heap_Based_Buffer_Overflow__sizeof_double_83_bad.cpp
Label Definition File: CWE122_Heap_Based_Buffer_Overflow__sizeof.label.xml
Template File: sources-sink-83_bad.tmpl.cpp
*/
/*
* @description
* CWE: 122 Heap Based Buffer Overflow
* BadSource: Initialize the source buffer using the size of a pointer
* GoodSource: Initialize the source buffer using the size of the DataElementType
* Sinks:
* BadSink : Print then free data
* Flow Variant: 83 Data flow: data passed to class constructor and destructor by declaring the class object on the stack
*
* */
#ifndef OMITBAD
#include "std_testcase.h"
#include "CWE122_Heap_Based_Buffer_Overflow__sizeof_double_83.h"
namespace CWE122_Heap_Based_Buffer_Overflow__sizeof_double_83
{
CWE122_Heap_Based_Buffer_Overflow__sizeof_double_83_bad::CWE122_Heap_Based_Buffer_Overflow__sizeof_double_83_bad(double * dataCopy)
{
data = dataCopy;
/* INCIDENTAL: CWE-467 (Use of sizeof() on a pointer type) */
/* FLAW: Using sizeof the pointer and not the data type in malloc() */
data = (double *)malloc(sizeof(data));
*data = 1.7E300;
}
CWE122_Heap_Based_Buffer_Overflow__sizeof_double_83_bad::~CWE122_Heap_Based_Buffer_Overflow__sizeof_double_83_bad()
{
/* POTENTIAL FLAW: Attempt to use data, which may not have enough memory allocated */
printDoubleLine(*data);
free(data);
}
}
#endif /* OMITBAD */
| [
"frank@fischer.com.mt"
] | frank@fischer.com.mt |
5f6fbfc3c1613cd197516de6388c9aca543e42ac | 864f7edac1358c408f89e57d9b87ab848f5ceada | /src/math/wrappers.cpp | 6d660246ee9c6f4bd35d79e78fc768cf3548fc01 | [
"MIT"
] | permissive | xclmj/magmadnn | 59dd3feffbb2cfa40c4ca87f31e194fd4c9b8d34 | ce91152e70eee319168d0fc11f5b4964e577b30a | refs/heads/master | 2021-03-31T17:56:04.082844 | 2020-03-07T23:07:42 | 2020-03-07T23:07:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,841 | cpp | /**
* @file wrappers.h
* @author Florent Lopez
* @version 0.1
* @date 2019-12-04
*
* @copyright Copyright (c) 2019
*/
#include <iostream>
#include "math/wrappers.h"
extern "C" {
// GEMM
void dgemm_(char* transa, char* transb, int* m, int* n, int* k, double* alpha, const double* a, int* lda, const double* b, int* ldb, double *beta, double* c, int* ldc);
void sgemm_(char* transa, char* transb, int* m, int* n, int* k, float* alpha, const float* a, int* lda, const float* b, int* ldb, float *beta, float* c, int* ldc);
// GEMV
void sgemv_(char* trans, int *m, int *n, float* alpha, float const* a, int* lda, const float *x, int const* incx, float *beta, float *y, int const *incy);
void dgemv_(char* trans, int *m, int *n, double* alpha, double const* a, int* lda, const double *x, int const* incx, double *beta, double *y, int const *incy);
// AXPY
void daxpy_(const int *n, const double *a, const double *x, const int *incx, double *y, const int *incy);
void saxpy_(const int *n, const float *a, const float *x, const int *incx, float *y, const int *incy);
// SCAL
void dscal_(int const* n, double const* a, double const* x, int const* incx);
void sscal_(int const* n, float const* a, float const* x, int const* incx);
}
namespace magmadnn {
namespace math {
// DGEMM
template <>
void gemm<double>(
enum operation transa, enum operation transb,
int m, int n, int k, double alpha, const double* a, int lda,
const double* b, int ldb, double beta, double* c, int ldc) {
char ftransa = (transa==OP_N) ? 'N' : 'T';
char ftransb = (transb==OP_N) ? 'N' : 'T';
dgemm_(&ftransa, &ftransb, &m, &n, &k, &alpha, a, &lda, b, &ldb, &beta, c, &ldc);
}
// SGEMM
template <>
void gemm<float>(
enum operation transa, enum operation transb,
int m, int n, int k, float alpha, const float * a, int lda,
const float * b, int ldb, float beta, float* c, int ldc) {
char ftransa = (transa==OP_N) ? 'N' : 'T';
char ftransb = (transb==OP_N) ? 'N' : 'T';
sgemm_(&ftransa, &ftransb, &m, &n, &k, &alpha, a, &lda, b, &ldb, &beta, c, &ldc);
}
// INT
template<>
void gemv<int>(enum operation trans, int m, int n, int alpha, int const* a, int lda,
int const* x, int incx, int beta, int *y, int incy) {
// char ftrans = (trans==OP_N) ? 'N' : 'T';
// sgemv_(&ftrans, &m, &n, &alpha, a, &lda, x, &incx, &beta, y, &incy);
std::cout << "gemv NOT implemented for type int" << std::endl;
}
// SGEMV
template<>
void gemv<float>(enum operation trans, int m, int n, float alpha, float const* a, int lda,
float const* x, int incx, float beta, float *y, int incy) {
char ftrans = (trans==OP_N) ? 'N' : 'T';
sgemv_(&ftrans, &m, &n, &alpha, a, &lda, x, &incx, &beta, y, &incy);
}
// DGEMV
template<>
void gemv<double>(enum operation trans, int m, int n, double alpha, double const* a, int lda,
double const* x, int incx, double beta, double *y, int incy) {
char ftrans = (trans==OP_N) ? 'N' : 'T';
dgemv_(&ftrans, &m, &n, &alpha, a, &lda, x, &incx, &beta, y, &incy);
}
// SAXPY
template<>
void axpy<float>(int n, float a, const float *x, int incx, float *y, int incy) {
saxpy_(&n, &a, x, &incx, y, &incy);
}
// DAXPY
template<>
void axpy<double>(int n, double a, const double *x, int incx, double *y, int incy) {
daxpy_(&n, &a, x, &incx, y, &incy);
}
// SSCAL
template<>
void scal<float>(int n, float a, const float *x, int incx) {
sscal_(&n, &a, x, &incx);
}
// DSCAL
template<>
void scal<double>(int n, double a, const double *x, int incx) {
dscal_(&n, &a, x, &incx);
}
}} // namespace magmadnn::math
| [
"florent.lopez@stfc.ac.uk"
] | florent.lopez@stfc.ac.uk |
7c63e0ef398760ee517e826e76540ca70537ea12 | 6180c9e8278145285dbc2bf880a32cb20ca5a5a0 | /scenargie_simulator/2.2/source/simulator/routing/nuOLSRv2/olsrv2/ibase_n.h | 5ef90cf542b6d302470ff5522801afeba1a4c080 | [] | no_license | superzaxi/DCC | 0c529002e9f84a598247203a015f0f4ee0d61c22 | cd3e5755410a1266d705d74c0b037cc1609000cf | refs/heads/main | 2023-07-15T05:15:31.466339 | 2021-08-10T11:23:42 | 2021-08-10T11:23:42 | 384,296,263 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,170 | h | //
// (N) Neighbor Set
//
#ifndef OLSRV2_IBASE_N_H_
#define OLSRV2_IBASE_N_H_
#include "core/pvector.h"
namespace NuOLSRv2Port { //ScenSim-Port://
/************************************************************//**
* @defgroup ibase_n OLSRv2 :: (N) Neighbor Tuple
* @{
*/
/**
* (N) Neighbor Tuple
*/
typedef struct tuple_n {
struct tuple_n* next; ///< next tuple
struct tuple_n* prev; ///< prev tuple
nu_ip_set_t neighbor_ip_list; ///< N_neighbor_ifaddr_list
nu_bool_t symmetric; ///< N_symmetric
nu_ip_t orig_addr; ///< N_orig_addr
uint8_t willingness; ///< N_willingness
nu_bool_t routing_mpr; ///< N_routing_mpr
nu_bool_t flooding_mpr; ///< N_flooding_mpr
nu_bool_t mpr_selector; ///< N_mpr_selector
nu_bool_t advertised; ///< N_advertised
nu_link_metric_t _in_metric; ///< N_in_metric
nu_link_metric_t _out_metric; ///< N_out_metric
nu_bool_t flooding_mprs; ///< ...
nu_bool_t advertised_save; ///< previous advertised status
nu_bool_t routing_mpr_save; ///< previous mpr status
nu_bool_t flooding_mpr_save; ///< previous mpr status
nu_link_metric_t in_metric_save; ///< previous N_in_metric
nu_link_metric_t out_metric_save; ///< previous N_out_metric
size_t tuple_l_count; ///< # of tuple_l
} tuple_n_t;
/**
* (N) Neighbor Set
*/
typedef struct ibase_n {
tuple_n_t* next; ///< first tuple
tuple_n_t* prev; ///< last tuple
size_t n; ///< size
uint16_t ansn; ///< ANSN
nu_bool_t change; ///< change flag for links
nu_bool_t sym_change; ///< change flag for symmetric links
} ibase_n_t;
////////////////////////////////////////////////////////////////
//
// tuple_n_t
//
PUBLIC nu_bool_t tuple_n_has_symlink(const tuple_n_t*);
PUBLIC nu_bool_t tuple_n_has_link(const tuple_n_t*);
PUBLIC void tuple_n_add_neighbor_ip_list(tuple_n_t*, nu_ip_t);
PUBLIC void tuple_n_set_orig_addr(tuple_n_t*, nu_ip_t);
PUBLIC void tuple_n_set_symmetric(tuple_n_t*, nu_bool_t);
PUBLIC void tuple_n_set_willingness(tuple_n_t*, nu_bool_t);
PUBLIC void tuple_n_set_flooding_mpr(tuple_n_t*, nu_bool_t);
PUBLIC void tuple_n_set_routing_mpr(tuple_n_t*, nu_bool_t);
PUBLIC void tuple_n_set_mpr_selector(tuple_n_t*, nu_bool_t);
PUBLIC void tuple_n_set_advertised(tuple_n_t*, nu_bool_t);
////////////////////////////////////////////////////////////////
//
// ibase_n_t
//
}//namespace// //ScenSim-Port://
#include "olsrv2/ibase_n_.h"
namespace NuOLSRv2Port { //ScenSim-Port://
#undef ibase_n_clear_change_flag
/** Clears the change flag.
*/
#define ibase_n_clear_change_flag() \
do { \
IBASE_N->change = false; \
IBASE_N->sym_change = false; \
} \
while (0)
#undef ibase_n_is_changed
/** Checks whether ibase_n is changed or not.
*/
#define ibase_n_is_changed() (IBASE_N->sym_change || IBASE_N->change)
PUBLIC void ibase_n_init(void);
PUBLIC void ibase_n_destroy(void);
PUBLIC tuple_n_t* ibase_n_add(const nu_ip_set_t*, const nu_ip_t);
PUBLIC tuple_n_t* ibase_n_search_tuple_l(tuple_l_t*);
PUBLIC nu_bool_t ibase_n_contain_symmetric(const nu_ip_t);
PUBLIC nu_bool_t ibase_n_contain_symmetric_without_prefix(const nu_ip_t);
PUBLIC tuple_n_t* ibase_n_iter_remove(tuple_n_t*);
PUBLIC void ibase_n_save_advertised(void);
PUBLIC nu_bool_t ibase_n_commit_advertised(void);
PUBLIC void ibase_n_save_flooding_mpr(void);
PUBLIC void ibase_n_commit_flooding_mpr(void);
PUBLIC void ibase_n_save_routing_mpr(void);
PUBLIC void ibase_n_commit_routing_mpr(void);
PUBLIC void ibase_n_save_advertised(void);
PUBLIC nu_bool_t ibase_n_commit_advertised(void);
PUBLIC void tuple_n_put_log(tuple_n_t*, nu_logger_t*);
PUBLIC void ibase_n_put_log(nu_logger_t*);
/** @} */
}//namespace// //ScenSim-Port://
#endif
| [
"zaki@keio.jp"
] | zaki@keio.jp |
f06d511784be24dc6b015900dbd352a112c38413 | 90af0c01052a34b1405d4a323305db8c7cd2ea13 | /C++/Google Code Jam/flippancakes/flippancaker.cpp | 8140ec0d6e41edaa9ad588260393699c4159d58d | [] | no_license | Aleksandr-Kovalev/CourseworkCode | 705427c41376fa76f78c391bed197fd9f6728d10 | 40ef99e18e490de15cc2dabde0f5c42960bb2f41 | refs/heads/master | 2020-06-04T00:05:58.961858 | 2019-06-13T16:12:54 | 2019-06-13T16:12:54 | 191,787,568 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,171 | cpp | #include <iostream>
#include <fstream>
#include <algorithm>
//https://code.google.com/codejam/contest/3264486/dashboard#s=p0
int main(int argc, char** argv) {
int T, X, K, flips = 0;
std::string row;
std::string flipper;
bool facedown = false;
std::ifstream in("A-large-practice.in");
std::ofstream out("A-large-practice.out");
in >> T;
while(T != 0 ){
std::cout << T << std::endl;
X++;
in >> row;
in >> K;
for(int i = 0; i <= row.length(); i++){
if(row[i] == '-' && i <= row.length()-K){
flipper.assign(row.begin()+i, row.begin()+(i+K));
flipper.resize(K);
for(int z = 0; z < flipper.length(); z++){
if(flipper[z] == '-')
flipper[z] = '+';
else
flipper[z] = '-';
}
flips++;
row.replace(i, K, flipper);
}
if(row[i] == '-' && i > row.length()-K){
flips = -1;
break;
}
}
if(row.find('-') != -1)
flips = -1;
out << "Case #" << X << ": " ;
if(flips == -1)
out << "IMPOSSIBLE" << std::endl;
else
out << flips << std::endl;
T--;
flips = 0;
}
return 0;
}
| [
"noreply@github.com"
] | Aleksandr-Kovalev.noreply@github.com |
065604e07d99010def4f94862e38f35865702061 | 8ce88e6d70a7ba3a10a9aabc6dbe282b4b978d0d | /Other/Borg/Borg/RANGE.H | 2a7c0f2216d0b2b50e09eecb483f16903b9c82f1 | [] | no_license | yodamaster/avdbg | e66a35838d4b9561a53388b13d6cd44889e21fbc | 92157c686ebaadc5565eec5a6e4d9a5a390b1fa9 | refs/heads/master | 2021-01-18T06:33:18.087191 | 2013-01-03T14:21:52 | 2013-01-03T14:21:52 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 285 | h | // range.h
//
#ifndef range_h
#define range_h
#include "common.h"
class range
{
public:
lptr top,bottom;
public:
range();
~range();
bool checkblock(void);
void undefine(void);
void settop(void);
void setbottom(void);
};
extern range blk;
#endif
| [
"Administrator@20111020-1601xyz"
] | Administrator@20111020-1601xyz |
d259118f2d91e8c15d205a8a34766f3ca901b8bb | 7d7f343413368fa68ddd123b67f1cb9aee09f481 | /tests/mock_arduino.h | 28fdd9ca90451f89f9387410e92c90d8b4dbe2c8 | [] | no_license | arthursw/tipibot | 8779282e8d95fe1d857c9300407d976b75aaee79 | 08237ea9b56cccc6294bc3eb5f5a549f0df1ed23 | refs/heads/master | 2021-01-23T03:33:55.826549 | 2017-04-15T17:14:09 | 2017-04-15T17:14:09 | 86,091,855 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,916 | h | /*
DSM2_tx implements the serial communication protocol used for operating
the RF modules that can be found in many DSM2-compatible transmitters.
Copyrigt (C) 2012 Erik Elmore <erik@ironsavior.net>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <iostream>
#include <climits>
#include <math.h>
using namespace std;
#define OUTPUT 0
#define INPUT 1
#define constrain(amt,low,high) ((amt)<(low)?(low):((amt)>(high)?(high):(amt)))
#define lowByte(w) ((unsigned char) ((w) & 0xff))
#define highByte(w) ((unsigned char) ((w) >> 8))
typedef unsigned char byte;
typedef unsigned short int word;
void delay(unsigned long ms) {
}
unsigned long millis(){
return 0;
}
std::chrono::high_resolution_clock::time_point start = std::chrono::high_resolution_clock::now();
unsigned long micros(){
std::chrono::high_resolution_clock::duration elapsed = std::chrono::high_resolution_clock::now() - start;
return std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
}
// WMath.cpp
long map(long, long, long, long, long);
void initialize_mock_arduino();
void pinMode(int pin, int mode){
cout << "Set pin " << pin << " to mode " << mode << endl;
}
//void digitalWrite(int pin, int value) {
// cout << "Digital write: pin: " << pin << ", value: " << value << endl;
//}
#include "fake_serial.h"
| [
"arthur.sw@gmail.com"
] | arthur.sw@gmail.com |
619829e0d2bd6c51878ee695caa1dbb90e4e09b4 | 34f4521d997cedbfdef457392d32136b402e6889 | /spot_light.cpp | cfbe3667b8afa76816ae25db079c7e7e9bb725cb | [] | no_license | nicmc9/spot_light | db9d45825ba25dbd2ca8763c32a969135e3ddc7d | 8a1be8494b7f76b8bea9acd1d7a02414bf778109 | refs/heads/master | 2022-12-06T06:37:10.688843 | 2020-08-31T13:22:35 | 2020-08-31T13:22:35 | 274,055,933 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,550 | cpp | #include <iostream>
#define GLEW_STATIC
#include <GL/glew.h>
// GLFW
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <stb_image.h>
#include <filesystem>
#include "shader_m.h"
#include "camera.h"
using namespace std;
void framebuffer_size_callback(GLFWwindow* window, int width, int height);
void mouse_callback(GLFWwindow* window, double xpos, double ypos);
void processInput(GLFWwindow* window);
GLuint loadTexture(char const* path);
// settings
const unsigned int SCR_WIDTH = 800;
const unsigned int SCR_HEIGHT = 600;
// camera
Camera camera(glm::vec3(0.0f, 0.0f, 3.0f));
string project_path = std::filesystem::current_path().string();
bool blinn = false;
bool blinnKeyPressed = false;
bool plain = false;
// yaw is initialized to -90.0 degrees since a yaw of 0.0 results in a direction vector pointing
// to the right so we initially rotate a bit to the left.
float yaw = -90.0f;
float pitch = 0.0f;
float lastX = 800.0f / 2.0;
float lastY = 600.0 / 2.0;
GLfloat deltaTime = 0.0f;
GLfloat lastFrame = 0.0f;
int main()
{
glfwInit();
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "Spot_light", nullptr, nullptr);
if (window == nullptr)
{
std::cout << "Failed to create GLFW window" << std::endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
glfwSetCursorPosCallback(window, mouse_callback);
glfwSetCursorPos(window, lastX, lastY);
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glewExperimental = GL_TRUE;
if (glewInit() != GLEW_OK)
{
std::cout << "Failed to initialize GLEW" << std::endl;
return -1;
}
glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);
Shader shader("shaders/cube.vert", "shaders/cube.frag");
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
GLfloat vertices[] = {
// positions // normals // texture coords
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f
};
// positions all containers
glm::vec3 cubePositions[] = {
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(2.0f, 5.0f, -15.0f),
glm::vec3(-1.5f, -2.2f, -2.5f),
glm::vec3(-3.8f, -2.0f, -12.3f),
glm::vec3(2.4f, -0.4f, -3.5f),
glm::vec3(-1.7f, 3.0f, -7.5f),
glm::vec3(1.3f, -2.0f, -2.5f),
glm::vec3(1.5f, 2.0f, -2.5f),
glm::vec3(1.5f, 0.2f, -1.5f),
glm::vec3(-1.3f, 1.0f, -1.5f)
};
GLuint VBO, cubeVAO;
glGenVertexArrays(1, &cubeVAO);
glGenBuffers(1, &VBO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
glBindVertexArray(cubeVAO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (void*)0);
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (void*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (void*)(6 * sizeof(GLfloat)));
glEnableVertexAttribArray(2);
// set up vertex data (and buffer(s)) and configure vertex attributes
// ------------------------------------------------------------------
float planeVertices[] = {
// positions // normals // texcoords
10.0f, -5.0f, 10.0f, 0.0f, 1.0f, 0.0f, 10.0f, 0.0f,
-10.0f, -5.0f, 10.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
-10.0f, -5.0f, -10.0f, 0.0f, 1.0f, 0.0f, 0.0f, 10.0f,
10.0f, -5.0f, 10.0f, 0.0f, 1.0f, 0.0f, 10.0f, 0.0f,
-10.0f, -5.0f, -10.0f, 0.0f, 1.0f, 0.0f, 0.0f, 10.0f,
10.0f, -5.0f, -10.0f, 0.0f, 1.0f, 0.0f, 10.0f, 10.0f
};
// plane VAO
GLuint planeVAO, planeVBO;
glGenVertexArrays(1, &planeVAO);
glGenBuffers(1, &planeVBO);
glBindVertexArray(planeVAO);
glBindBuffer(GL_ARRAY_BUFFER, planeVBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(planeVertices), planeVertices, GL_STATIC_DRAW);
glEnableVertexAttribArray(0);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)0);
glEnableVertexAttribArray(1);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(2);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(float), (void*)(6 * sizeof(float)));
glBindVertexArray(0);
glEnable(GL_DEPTH_TEST);
/// load textures
GLuint diffuseMap = loadTexture((project_path + "/resources/textures/container2.png").c_str());
GLuint specularMap = loadTexture((project_path + "/resources/textures/container2_specular.png").c_str());
GLuint floorTexture = loadTexture((project_path + "/resources/textures/wood.png").c_str());
shader.use();
shader.setVec3("light.ambient", 0.1f, 0.1f, 0.1f);
shader.setVec3("light.diffuse", 0.8f, 0.8f, 0.8f);
shader.setVec3("light.specular", 1.0f, 1.0f, 1.0f);
shader.setFloat("light.cutOff", glm::cos(glm::radians(12.5f)));
shader.setFloat("light.outerCutOff", glm::cos(glm::radians(17.5f)));
shader.setFloat("light.constant", 1.0f);
shader.setFloat("light.linear", 0.09f);
shader.setFloat("light.quadratic", 0.032f);
shader.setFloat("material.shininess", 32.0f);
shader.setInt("material.diffuse", 0);
shader.setInt("material.specular", 1);
shader.setInt("blinn", blinn);
shader.setInt("plain", plain);
// projection transformations
glm::mat4 projection = glm::perspective(glm::radians(camera.zoom_), (float)SCR_WIDTH / (float)SCR_HEIGHT, 0.1f, 100.0f);
shader.setMat4("projection", projection);
while (!glfwWindowShouldClose(window))
{
// per-frame time logic
float currentFrame = glfwGetTime();
deltaTime = currentFrame - lastFrame;
lastFrame = currentFrame;
glfwPollEvents();
// input
processInput(window);
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// be sure to activate shader when setting uniforms/drawing objects
shader.use();
// bind diffuse map
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, diffuseMap);
// bind specular map
glActiveTexture(GL_TEXTURE1);
glBindTexture(GL_TEXTURE_2D, specularMap);
plain = false;
shader.setVec3("viewPos", camera.position_);
shader.setVec3("light.direction", camera.front_);
shader.setVec3("light.position", camera.position_);
glm::mat4 view = camera.GetViewMatrix();
shader.setMat4("view", view);
// world transformation
glm::mat4 model = glm::mat4(1.0f);
// render the cube
glBindVertexArray(cubeVAO);
for (unsigned int i = 0; i < 10; i++)
{
// calculate the model matrix for each object and pass it to shader before drawing
model = glm::mat4(1.0f);
model = glm::translate(model, cubePositions[i]);
float angle = 20.0f * i;
model = glm::rotate(model, glm::radians(angle), glm::vec3(1.0f, 0.3f, 0.5f));
shader.setMat4("model", model);
glDrawArrays(GL_TRIANGLES, 0, 36);
}
model = glm::mat4(1.0f);
shader.setMat4("model", model);
plain = true;
shader.setInt("plain", plain);
glBindVertexArray(planeVAO);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, floorTexture);
glDrawArrays(GL_TRIANGLES, 0, 6);
glfwSwapBuffers(window);
}
glfwTerminate();
return 0;
}
GLuint loadTexture(char const* path)
{
GLuint textureID;
glGenTextures(1, &textureID);
int width, height, nrComponents;
unsigned char* data = stbi_load(path, &width, &height, &nrComponents, 0);
if (data)
{
GLenum format = GL_RGB;
if (nrComponents == 1)
format = GL_RED;
else if (nrComponents == 3)
format = GL_RGB;
else if (nrComponents == 4)
format = GL_RGBA;
glBindTexture(GL_TEXTURE_2D, textureID);
glTexImage2D(GL_TEXTURE_2D, 0, format, width, height, 0, format, GL_UNSIGNED_BYTE, data);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
stbi_image_free(data);
}
else
{
std::cout << "Texture failed to load at path: " << path << std::endl;
stbi_image_free(data);
}
return textureID;
}
// process all input: query GLFW whether relevant keys are pressed/released this frame and react accordingly
// ---------------------------------------------------------------------------------------------------------
void processInput(GLFWwindow* window)
{
if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS)
glfwSetWindowShouldClose(window, true);
if (glfwGetKey(window, GLFW_KEY_W) == GLFW_PRESS)
camera.ProcessKeyboard(FORWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_S) == GLFW_PRESS)
camera.ProcessKeyboard(BACKWARD, deltaTime);
if (glfwGetKey(window, GLFW_KEY_A) == GLFW_PRESS)
camera.ProcessKeyboard(LEFT, deltaTime);
if (glfwGetKey(window, GLFW_KEY_D) == GLFW_PRESS)
camera.ProcessKeyboard(RIGHT, deltaTime);
if (glfwGetKey(window, GLFW_KEY_B) == GLFW_PRESS && !blinnKeyPressed)
{
blinn = !blinn;
blinnKeyPressed = true;
std::cout << (blinn ? "Blinn-Phong" : "Phong") << std::endl;
}
if (glfwGetKey(window, GLFW_KEY_B) == GLFW_RELEASE)
{
blinnKeyPressed = false;
}
}
// glfw: whenever the window size changed (by OS or user resize) this callback function executes
// ---------------------------------------------------------------------------------------------
void framebuffer_size_callback(GLFWwindow* window, int width, int height)
{
// make sure the viewport matches the new window dimensions; note that width and
// height will be significantly larger than specified on retina displays.
glViewport(0, 0, width, height);
}
// glfw: whenever the mouse moves, this callback is called
// -------------------------------------------------------
void mouse_callback(GLFWwindow* window, double xpos, double ypos)
{
float xoffset = xpos - lastX;
float yoffset = lastY - ypos; // reversed since y-coordinates go from bottom to top
lastX = xpos;
lastY = ypos;
camera.ProcessMouseMovement(xoffset, yoffset);
} | [
"nicmc9@gmail.com"
] | nicmc9@gmail.com |
9772588f38f00aed1ac377d730ee83213890faec | d51e54dccbb594a056005cb50a9dbad472ddb034 | /Volume_12/Number_4/Eisemann2007/ray.cpp | e7327e343130fd5ad25c654bba8a16cf3e991ec9 | [
"MIT"
] | permissive | skn123/jgt-code | 4aa8d39d6354a1ede9b141e5e7131e403465f4f7 | 1c80455c8aafe61955f61372380d983ce7453e6d | refs/heads/master | 2023-08-30T22:54:09.412136 | 2023-08-28T20:54:09 | 2023-08-28T20:54:09 | 217,573,703 | 0 | 0 | MIT | 2023-08-29T02:29:29 | 2019-10-25T16:27:56 | MATLAB | UTF-8 | C++ | false | false | 2,955 | cpp | /******************************************************************************
This source code accompanies the Journal of Graphics Tools paper:
"Fast Ray / Axis-Aligned Bounding Box Overlap Tests using Ray Slopes"
by Martin Eisemann, Thorsten Grosch, Stefan Müller and Marcus Magnor
Computer Graphics Lab, TU Braunschweig, Germany and
University of Koblenz-Landau, Germany
Parts of this code are taken from
"Fast Ray-Axis Aligned Bounding Box Overlap Tests With Pluecker Coordinates"
by Jeffrey Mahovsky and Brian Wyvill
Department of Computer Science, University of Calgary
This source code is public domain, but please mention us if you use it.
******************************************************************************/
#include <math.h>
#include "ray.h"
void make_ray(float x, float y, float z, float i, float j, float k, ray *r)
{
//common variables
r->x = x;
r->y = y;
r->z = z;
r->i = i;
r->j = j;
r->k = k;
r->ii = 1.0f/i;
r->ij = 1.0f/j;
r->ik = 1.0f/k;
//ray slope
r->ibyj = r->i * r->ij;
r->jbyi = r->j * r->ii;
r->jbyk = r->j * r->ik;
r->kbyj = r->k * r->ij;
r->ibyk = r->i * r->ik;
r->kbyi = r->k * r->ii;
r->c_xy = r->y - r->jbyi * r->x;
r->c_xz = r->z - r->kbyi * r->x;
r->c_yx = r->x - r->ibyj * r->y;
r->c_yz = r->z - r->kbyj * r->y;
r->c_zx = r->x - r->ibyk * r->z;
r->c_zy = r->y - r->jbyk * r->z;
//ray slope classification
if(i < 0)
{
if(j < 0)
{
if(k < 0)
{
r->classification = MMM;
}
else if(k > 0){
r->classification = MMP;
}
else//(k >= 0)
{
r->classification = MMO;
}
}
else//(j >= 0)
{
if(k < 0)
{
r->classification = MPM;
if(j==0)
r->classification = MOM;
}
else//(k >= 0)
{
if((j==0) && (k==0))
r->classification = MOO;
else if(k==0)
r->classification = MPO;
else if(j==0)
r->classification = MOP;
else
r->classification = MPP;
}
}
}
else//(i >= 0)
{
if(j < 0)
{
if(k < 0)
{
r->classification = PMM;
if(i==0)
r->classification = OMM;
}
else//(k >= 0)
{
if((i==0) && (k==0))
r->classification = OMO;
else if(k==0)
r->classification = PMO;
else if(i==0)
r->classification = OMP;
else
r->classification = PMP;
}
}
else//(j >= 0)
{
if(k < 0)
{
if((i==0) && (j==0))
r->classification = OOM;
else if(i==0)
r->classification = OPM;
else if(j==0)
r->classification = POM;
else
r->classification = PPM;
}
else//(k > 0)
{
if(i==0)
{
if(j==0)
r->classification = OOP;
else if(k==0)
r->classification = OPO;
else
r->classification = OPP;
}
else
{
if((j==0) && (k==0))
r->classification = POO;
else if(j==0)
r->classification = POP;
else if(k==0)
r->classification = PPO;
else
r->classification = PPP;
}
}
}
}
}
| [
"erich@acm.org"
] | erich@acm.org |
27c5e73daf86b86408d735139b8e7d9d21a60fc4 | 2deb946f9a78674b47b1ff474fc59191b12f28eb | /test/testCrossCorrelationPlot.cpp | be13047bec89da872cc84894dbec473adab66ff1 | [
"MIT"
] | permissive | dogjin/PlotLib | 292b60b6065172db2d6071bab539ac556bc738c3 | 36439335362b74ae002ce7e446d233c580b63d1a | refs/heads/master | 2020-04-25T04:49:17.163629 | 2018-06-01T11:40:21 | 2018-06-01T11:40:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,205 | cpp | /**
* @cond ___LICENSE___
*
* Copyright (c) 2016-2018 Zefiros Software.
*
* 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.
*
* @endcond
*/
#include "plot/plotting.h"
#include "helper.h"
TEST(CrossCorrelationPlot, CrossCorrelationPlot)
{
TestPlot< CrossCorrelationPlot >("CrossCorrelationPlot", []()
{
vec xVec = randu(200);
vec yVec = randu(200);
CrossCorrelationPlot f(xVec, yVec);
return f;
});
}
TEST(CrossCorrelationPlot, CrossCorrelationPlot2)
{
TestPlot< CrossCorrelationPlot >("CrossCorrelationPlot_SetHold", []()
{
vec xVec = randu(200);
vec yVec = randu(200);
CrossCorrelationPlot f(xVec, yVec);
f.SetLineWidth(3)
.SetColour("b")
.Normed(true);
return f;
});
}
TEST(CrossCorrelationPlot, SetVLines)
{
TestPlot< CrossCorrelationPlot >("CrossCorrelationPlot_SetVLines", []()
{
vec xVec = randu(200);
vec yVec = randu(200);
CrossCorrelationPlot f(xVec, yVec);
f.SetMarker(".")
.VLines(false)
.SetMaxLags(100)
.SetDetrend(CrossCorrelationPlot::Detrend::Linear);
return f;
});
} | [
"paul.pev@hotmail.com"
] | paul.pev@hotmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.