blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e066977e861878f6c8b7dd833dfaf0a05a43be8e | 568c9ec7b41c75868db423d1d680d718af0a0e73 | /src/Gallina2.h | ccc5c3c1fa70b9a6249136888e1c7128c6ac99d7 | [] | no_license | lydiavega/Trabajo_informatica | 9ed05426ef9d738752d002b740614e6b55558f89 | 6cbd49d2fc60fffe5b0c28ea5de8f42a58bce8c6 | refs/heads/master | 2020-06-03T11:07:49.100642 | 2019-06-14T09:56:48 | 2019-06-14T09:56:48 | 191,544,855 | 0 | 0 | null | 2019-06-14T09:56:49 | 2019-06-12T09:55:30 | C | UTF-8 | C++ | false | false | 490 | h | #pragma once
#include <stdlib.h>
#include "ETSIDI.h"
#include <stdio.h>
#include "glut.h"
#include "Vector2D.h"
using ETSIDI::SpriteSequence;
class Gallina2
{
friend class Interaccion;
private:
float ancho, alto;
Vector2D posicion;
Vector2D velocidad;
SpriteSequence* animacion;
public:
Gallina2(void);
~Gallina2(void);
void Mueve(float t);
void Dibuja(void);
void SetPos(float ix, float iy);
void SetVel(float ix, float iy);
void SetDims(float anch, float alt);
};
| [
"[email protected]"
] | |
90a001e210e13887af3003ade1e17825d58d0dca | 1b5087f0263d03c8b541cc9563c5081b45e218c0 | /cudatetris/HitableList.h | f239f0629f79ab4a8fe7375541704a78c747f468 | [] | no_license | TuckerBMorgan/CudaTetris | 578d54ba380814fd00b682e22c9cc74ce04d75a6 | 3a9fc1ef44250caa308fa4f0275e1cb381c84ed4 | refs/heads/master | 2020-04-02T00:45:35.579902 | 2018-10-19T17:52:47 | 2018-10-19T17:52:47 | 153,820,523 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 685 | h | #pragma once
#include "Hitable.h"
class HitableList : public Hitable {
public :
HitableList() {};
HitableList(Hitable** l, int n) { list = l; list_size = n; };
virtual bool hit(const Ray& ray, float tmin, float tmax, hit_record& rec) const;
Hitable** list;
int list_size;
};
bool HitableList::hit(const Ray& r, float t_min, float t_max, hit_record& rec) const {
hit_record temp_rec;
bool hit_anything = false;
double closest_so_far = t_max;
for (int i = 0; i < list_size; i++) {
if (list[i]->hit(r, t_min, closest_so_far, temp_rec)) {
hit_anything = true;
closest_so_far = temp_rec.t;
rec = temp_rec;
}
}
return hit_anything;
} | [
"[email protected]"
] | |
4dfa12ac554a9a0066bb7678312157e6a910c470 | 85ec0860a0a9f5c0c0f0d81ce3cc0baf4b2a812e | /sngcpp20/test/source/0_preprocessor/include_locale.cpp | 3899395da250dd1b6383ca813af37a0d691a73c0 | [] | no_license | slaakko/soulng | 3218185dc808fba63e2574b3a158fa1a9f0b2661 | a128a1190ccf71794f1bcbd420357f2c85fd75f1 | refs/heads/master | 2022-07-27T07:30:20.813581 | 2022-04-30T14:22:44 | 2022-04-30T14:22:44 | 197,632,580 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18 | cpp | #include <locale>
| [
"[email protected]"
] | |
8ac8bbbb4f2f8ec127630665fc07bf0b899fc89b | cf163adcec62cc637ae17fcfa1acafede2436d60 | /OFtemplate/0/include/frontBackUpperPatches | 4ce0e6a773251040313fe44d2a09e53be175e868 | [] | no_license | TianliHao/OFrunner | 033c535b14127d46aaf1034235885fec8a4ff18e | 00737f7aac204caffa97abde9deba1dbd73e8993 | refs/heads/master | 2020-08-25T07:15:15.138838 | 2019-12-17T03:30:56 | 2019-12-17T03:30:56 | 216,980,195 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 535 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 7
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
"(front|back|upperWall|lowerWall)"
{
type symmetryPlane;
}
// ************************************************************************* //
| [
"[email protected]"
] | ||
872c4c6360d0957a72c01899d94239398aa79d3a | f1bc5fda1cc7ca5ce0338a02eac8d3a316227346 | /src/UniverseAdvanced/EclipsePlus/EclipseAddin.cpp | 862b578fef4c43923c757a10a0227a787a257a1e | [] | no_license | CycCoder/OpenUniverse | bd489d2be99665ce702c31b1aae74c66f8ab7490 | 75a92d5d5ad46e06566deb272b433863473a894a | refs/heads/main | 2023-04-03T00:43:09.523448 | 2021-02-04T00:21:41 | 2021-02-04T00:21:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,983 | cpp | /********************************************************************************
* Web Runtime for Application - Version 1.0.0.202102030023 *
********************************************************************************
* Copyright (C) 2002-2021 by Tangram Team. All Rights Reserved.
* There are Three Key Features of Webruntime:
* 1. Built-in Modern Web Browser: Independent Browser Window and Browser Window
* as sub windows of other windows are supported in the application process;
* 2. DOM Plus: DOMPlus is a natural extension of the standard DOM system.
* It allows the application system to support a kind of generalized web pages,
* which are composed of standard DOM elements and binary components supported
* by the application system;
* 3. JavaScript for Application: Similar to VBA in MS office, JavaScript will
* become a built-in programmable language in the application system, so that
* the application system can be expanded and developed for the Internet based
* on modern javscript/Web technology.
* Use of this source code is governed by a BSD-style license that
* can be found in the LICENSE file.
*
* CONTACT INFORMATION:
* mailto:[email protected] or mailto:[email protected]
* https://www.tangram.dev
*******************************************************************************/
//https://github.com/eclipse/rt.equinox.framework/tree/master/features/org.eclipse.equinox.executable.feature
#include "../stdafx.h"
#include "../UniverseApp.h"
#include "../Xobj.h"
#include "../Galaxy.h"
#include "../CosmosCtrl.h"
#include "../GridWnd.h"
#include "EclipseAddin.h"
#include "atlcom.h"
extern jstring newJavaString(JNIEnv *env, _TCHAR * str);
CEclipseExtender::CEclipseExtender()
{
}
CEclipseExtender::~CEclipseExtender()
{
}
STDMETHODIMP CEclipseExtender::Close()
{
delete this;
return S_OK;
}
STDMETHODIMP CEclipseExtender::get_ActiveWorkBenchWindow(BSTR bstrID, IWorkBenchWindow** pVal)
{
CString strID = OLE2T(bstrID);
strID.Trim();
if (strID==_T(""))
{
if (g_pCosmos->m_pActiveEclipseWnd)
{
*pVal = (IWorkBenchWindow*)g_pCosmos->m_pActiveEclipseWnd;
(*pVal)->AddRef();
}
}
else
{
ICosmos* pCosmos = nullptr;
g_pCosmos->get_RemoteCosmos(bstrID, &pCosmos);
if (pCosmos)
{
IWorkBenchWindow* pRet = nullptr;
ICosmosExtender* pExtender = nullptr;
pCosmos->get_Extender(&pExtender);
if (pExtender)
{
CComQIPtr<IEclipseExtender> pEclipse(pExtender);
if(pEclipse)
pEclipse->get_ActiveWorkBenchWindow(bstrID, &pRet);
if (pRet)
{
*pVal = pRet;
(*pVal)->AddRef();
}
}
}
}
return S_OK;
}
CEclipseWnd::CEclipseWnd(void)
{
m_pGalaxy = nullptr;
m_pCurXobj = nullptr;
m_pHostXobj = nullptr;
m_strXml = _T("");
m_strPath = _T("");
m_strAppProxyID = _T("");
m_strNodeName = _T("");
m_strDocKey = _T("");
m_strFrameID = _T("");
m_pAppProxy = nullptr;
m_pGalaxyCluster = nullptr;
g_pCosmos->m_pActiveEclipseWnd = this;
}
CEclipseWnd::~CEclipseWnd(void)
{
if (m_pGalaxyCluster)
{
HWND hWnd = m_pGalaxyCluster->m_hWnd;
auto it = g_pCosmos->m_mapWindowPage.find(hWnd);
if (it != g_pCosmos->m_mapWindowPage.end())
delete m_pGalaxyCluster;
}
ATLTRACE(_T("delete CEclipseWnd:%x\n"), this);
}
void CEclipseWnd::OnFinalMessage(HWND hWnd)
{
auto it = g_pCosmos->m_mapWorkBenchWnd.find(hWnd);
if (it != g_pCosmos->m_mapWorkBenchWnd.end())
g_pCosmos->m_mapWorkBenchWnd.erase(it);
if (g_pCosmos->m_pCLRProxy)
{
g_pCosmos->m_pCLRProxy->ReleaseCosmosObj((IWorkBenchWindow*)this);
}
CWindowImpl::OnFinalMessage(hWnd);
delete this;
}
void CEclipseWnd::CreatePage(BOOL bSaveToConfigFile)
{
if (m_pGalaxyCluster == nullptr)
{
IGalaxyCluster* pGalaxyCluster = nullptr;
g_pCosmos->CreateGalaxyCluster((LONGLONG)m_hWnd, &pGalaxyCluster);
if (pGalaxyCluster == nullptr)
return;
m_pGalaxyCluster = (CGalaxyCluster*)pGalaxyCluster;
HMENU hMenu = ::GetMenu(m_hWnd);
if (hMenu)
{
MENUITEMINFO mii;
mii.fMask = MIIM_STRING;
mii.cbSize = sizeof(MENUITEMINFO);
int nCount = ::GetMenuItemCount(hMenu);
for (int i = nCount - 1; i >0; i--)
{
mii.cch = 256;
mii.fType = MFT_STRING;
mii.dwTypeData = g_pCosmos->m_szBuffer;
GetMenuItemInfo(hMenu, i, true, &mii);
CString str = mii.dwTypeData;
if (str == _T("&Window"))
{
HMENU hSubMenu = ::GetSubMenu(hMenu, i);
int nCount = ::GetMenuItemCount(hSubMenu);
for (int i = 0; i<nCount; i++)
{
mii.fMask = MIIM_STRING | MIIM_ID;
mii.cch = 256;
mii.dwTypeData = g_pCosmos->m_szBuffer;
GetMenuItemInfo(hSubMenu, i, true, &mii);
str = mii.dwTypeData;
if (str == _T("&New Window"))
{
m_nNewWinCmdID = mii.wID;
break;
}
}
break;
}
}
}
if (::IsWindowVisible(m_hWnd))
{
m_strDocKey = g_pCosmos->m_strCurrentEclipsePagePath;
g_pCosmos->m_strCurrentEclipsePagePath = _T("");
Show(m_strDocKey);
auto it2 = g_pCosmos->m_mapValInfo.find(_T("newmdtframe"));
if (it2 != g_pCosmos->m_mapValInfo.end())
{
m_strFrameID = OLE2T(it2->second.bstrVal);
g_pCosmos->m_mapValInfo.erase(it2);
}
}
}
}
STDMETHODIMP CEclipseWnd::get_Count(long* pCount)
{
*pCount = (long)m_mapCtrl.size();
return S_OK;
}
STDMETHODIMP CEclipseWnd::get_Ctrl(VARIANT vIndex, IEclipseCtrl **ppCtrl)
{
if (vIndex.vt == VT_I4)
{
long lCount = m_mapCtrl.size();
int iIndex = vIndex.lVal;
if (iIndex < 0 || iIndex >= lCount) return E_INVALIDARG;
auto it = m_mapCtrl.begin();
int iPos = 0;
while (it != m_mapCtrl.end())
{
if (iPos == iIndex) break;
iPos++;
it++;
}
*ppCtrl = it->second;
return S_OK;
}
return S_OK;
}
STDMETHODIMP CEclipseWnd::CloseTangramUI()
{
if (m_pGalaxy)
{
HWND _hWnd = ::CreateWindowEx(NULL, _T("Cosmos Xobj Class"), L"", WS_CHILD, 0, 0, 0, 0, g_pCosmos->m_hHostWnd, NULL, AfxGetInstanceHandle(), NULL);
HWND _hChildWnd = ::CreateWindowEx(NULL, _T("Cosmos Xobj Class"), L"", WS_CHILD, 0, 0, 0, 0, (HWND)_hWnd, NULL, AfxGetInstanceHandle(), NULL);
if (::IsWindow(m_hWnd))
{
m_pGalaxy->ModifyHost((LONGLONG)_hChildWnd);
::DestroyWindow(_hWnd);
}
m_pGalaxy = nullptr;
delete m_pGalaxyCluster;
m_pGalaxyCluster = nullptr;
}
return S_OK;
}
STDMETHODIMP CEclipseWnd::get__NewEnum(IUnknown** ppVal)
{
typedef CComEnum<IEnumVARIANT, &IID_IEnumVARIANT, VARIANT, _Copy<VARIANT>>
CComEnumVariant;
CComObject<CComEnumVariant> *pe = 0;
HRESULT hr = pe->CreateInstance(&pe);
if (SUCCEEDED(hr))
{
pe->AddRef();
long nLen = (long)m_mapCtrl.size();
VARIANT* rgvar = new VARIANT[nLen];
ZeroMemory(rgvar, sizeof(VARIANT)*nLen);
VARIANT* pItem = rgvar;
for (auto it : m_mapCtrl)
{
IUnknown* pDisp = nullptr;
CEclipseCtrl* pObj = it.second;
hr = pObj->QueryInterface(IID_IUnknown, (void**)&pDisp);
pItem->vt = VT_UNKNOWN;
pItem->punkVal = pDisp;
if (pItem->punkVal != nullptr)
pItem->punkVal->AddRef();
pItem++;
pDisp->Release();
}
hr = pe->Init(rgvar, &rgvar[nLen], 0, AtlFlagTakeOwnership);
if (SUCCEEDED(hr))
hr = pe->QueryInterface(IID_IUnknown, (void**)ppVal);
pe->Release();
}
return S_OK;
}
STDMETHODIMP CEclipseWnd::get_Handle(LONGLONG* pVal)
{
*pVal = (LONGLONG)m_hClient;
return S_OK;
}
STDMETHODIMP CEclipseWnd::get_GalaxyCluster(IGalaxyCluster** pVal)
{
if (m_pGalaxyCluster)
*pVal = m_pGalaxyCluster;
return S_OK;
}
STDMETHODIMP CEclipseWnd::get_Galaxy(IGalaxy** pVal)
{
if (m_pGalaxy)
*pVal = m_pGalaxy;
return S_OK;
}
STDMETHODIMP CEclipseWnd::Observe(BSTR bstrKey, BSTR bstrXml, IXobj** ppXobj)
{
CString strKey = OLE2T(bstrKey);
strKey.Trim();
HRESULT hr = S_FALSE;
if (m_hClient == NULL)
return S_FALSE;
if (m_pGalaxyCluster == nullptr)
{
IGalaxyCluster* pGalaxyCluster = nullptr;
g_pCosmos->CreateGalaxyCluster((LONGLONG)m_hWnd, &pGalaxyCluster);
if (pGalaxyCluster == nullptr)
return S_FALSE;
m_pGalaxyCluster = (CGalaxyCluster*)pGalaxyCluster;
if (m_pGalaxy == nullptr)
{
IGalaxy* pGalaxy = nullptr;
m_pGalaxyCluster->CreateGalaxy(CComVariant(0), CComVariant((LONGLONG)m_hClient), CComBSTR(L"default"), &pGalaxy);
if (pGalaxy == nullptr)
{
delete m_pGalaxyCluster;
m_pGalaxyCluster = nullptr;
}
m_pGalaxy = (CGalaxy*)pGalaxy;
}
}
else
{
m_pGalaxy = (CGalaxy*)::SendMessage(m_hClient, WM_HUBBLE_DATA, 0, 1992);
if (m_pGalaxy == nullptr)
{
auto it = m_pGalaxyCluster->m_mapGalaxy.find(m_hClient);
if (it != m_pGalaxyCluster->m_mapGalaxy.end())
m_pGalaxy = it->second;
else
{
IGalaxy* pGalaxy = nullptr;
m_pGalaxyCluster->CreateGalaxy(CComVariant(0), CComVariant((LONGLONG)m_hClient), CComBSTR(L"default"), &pGalaxy);
if (pGalaxy == nullptr)
{
delete m_pGalaxyCluster;
m_pGalaxyCluster = nullptr;
}
m_pGalaxy = (CGalaxy*)pGalaxy;
}
}
}
if (m_pGalaxy)
{
hr = m_pGalaxy->Observe(bstrKey, bstrXml, ppXobj);
if (*ppXobj)
{
m_pCurXobj = (CXobj*)*ppXobj;
}
}
return hr;
}
STDMETHODIMP CEclipseWnd::ObserveEx(BSTR bstrKey, BSTR bstrXml, IXobj** ppXobj)
{
HRESULT hr = Observe(bstrKey, bstrXml, ppXobj);
if (*ppXobj)
{
m_pCurXobj = (CXobj*)*ppXobj;
m_pCurXobj->put_SaveToConfigFile(true);
}
return hr;
}
STDMETHODIMP CEclipseWnd::ObserveInView(int nIndex, BSTR bstrKey, BSTR bstrXml, IXobj** ppRetXobj)
{
IEclipseCtrl* pCtrl = nullptr;
get_Ctrl(CComVariant((int)nIndex), &pCtrl);
if (pCtrl)
{
IXobj* pXobj = nullptr;
return pCtrl->Observe(CComBSTR(L"EclipseView"), bstrKey, bstrXml, ppRetXobj);
}
return S_OK;
}
STDMETHODIMP CEclipseWnd::Active()
{
SetFocus();
return S_OK;
}
STDMETHODIMP CEclipseWnd::get_CosmosCtrl(LONGLONG hWnd, IEclipseCtrl** pVal)
{
auto it = m_mapCtrl.find((HWND)hWnd);
if (it != m_mapCtrl.end())
{
*pVal = it->second;
(*pVal)->AddRef();
}
return S_OK;
}
void CEclipseWnd::Show(CString strID)
{
LONG_PTR data = 0;
if(::IsWindow(m_hClient))
data = ::GetWindowLongPtr(m_hClient, GWLP_USERDATA);
if (g_pCosmos->m_bIsEclipseInit == false)
g_pCosmos->m_bIsEclipseInit = true;
if (data==0&&g_pCosmos->m_pUniverseAppProxy)
{
m_strPath = strID;
if (::IsChild(m_hWnd, m_hClient))
{
m_strAppProxyID = _T("");
auto it = g_pCosmos->m_mapWindowPage.find(m_hWnd);
if (m_pGalaxyCluster == nullptr)
{
if (it != g_pCosmos->m_mapWindowPage.end())
m_pGalaxyCluster = (CGalaxyCluster*)it->second;
else
{
m_pGalaxyCluster = new CComObject<CGalaxyCluster>();
m_pGalaxyCluster->m_hWnd = m_hWnd;
g_pCosmos->m_mapWindowPage[m_hWnd] = m_pGalaxyCluster;
for (auto it : g_pCosmos->m_mapCosmosAppProxy)
{
CGalaxyClusterProxy* pCosmosProxy = it.second->OnGalaxyClusterCreated(m_pGalaxyCluster);
if (pCosmosProxy)
m_pGalaxyCluster->m_mapGalaxyClusterProxy[it.second] = pCosmosProxy;
}
}
}
if (m_strPath == _T("")||::PathFileExists(m_strPath)==false)
{
auto it = g_pCosmos->m_mapCreatingWorkBenchInfo.find(strID);
if (it != g_pCosmos->m_mapCreatingWorkBenchInfo.end())
{
m_strDocKey = m_strXml = it->second;
g_pCosmos->m_mapCreatingWorkBenchInfo.erase(it);
}
else
m_strDocKey = m_strXml = m_strPath = g_pCosmos->m_strDefaultWorkBenchXml;
}
else
{
m_strDocKey = m_strXml = m_strPath;
CTangramXmlParse m_Parse;
if (m_Parse.LoadFile(m_strDocKey))
{
m_strAppProxyID = m_Parse.attr(_T("styleproxyid"), _T(""));
}
}
if (m_strAppProxyID != _T(""))
{
m_pAppProxy = nullptr;
auto it = g_pCosmos->m_mapCosmosAppProxy.find(m_strAppProxyID.MakeLower());
if (it != g_pCosmos->m_mapCosmosAppProxy.end())
m_pAppProxy = it->second;
else
{
CString strPath = g_pCosmos->m_strAppPath;
HMODULE hHandle = nullptr;
CString strAppName = _T("");
int nPos = m_strAppProxyID.Find(_T("."));
if (nPos != -1)
strAppName = m_strAppProxyID.Left(nPos);
CString strdll = strPath + m_strAppProxyID + _T("\\") + strAppName + _T(".dll");
if (::PathFileExists(strdll))
hHandle = ::LoadLibrary(strdll);
if (hHandle)
{
it = g_pCosmos->m_mapCosmosAppProxy.find(m_strAppProxyID.MakeLower());
if (it != g_pCosmos->m_mapCosmosAppProxy.end())
{
m_pAppProxy = it->second;
}
}
}
if (m_pAppProxy)
{
g_pCosmos->m_pActiveAppProxy = m_pAppProxy;
m_pAppProxy->m_hCreatingView = m_hClient;
::SetWindowText(m_hClient, g_pCosmos->m_strAppKey);
::SetWindowLongPtr(m_hClient, GWLP_USERDATA, (LONG_PTR)1);
}
}
else if(strID !=_T(""))
{
IGalaxy* pGalaxy = nullptr;
m_pGalaxyCluster->CreateGalaxy(CComVariant(0), CComVariant((LONGLONG)m_hClient), CComBSTR(L"default"), &pGalaxy);
if (pGalaxy)
{
m_pGalaxy = (CGalaxy*)pGalaxy;
m_pGalaxyCluster->m_mapNeedSaveGalaxy[m_hClient] = m_pGalaxy;
CString strKey = _T("default");
if (m_strDocKey == _T(""))
{
m_strDocKey = m_strXml = m_strPath = g_pCosmos->m_strAppDataPath + _T("default.workbench");
}
else
{
strKey = strID;
if (g_pCosmos->m_nAppType == APP_ECLIPSE)
m_strDocKey = g_pCosmos->m_strStartupURL;
}
IXobj* pXobj = nullptr;
pGalaxy->Observe(CComBSTR(strKey), CComBSTR(m_strDocKey), &pXobj);
if (pXobj == nullptr)
{
delete m_pGalaxy;
m_pGalaxy = nullptr;
m_pGalaxyCluster = nullptr;
}
}
}
}
}
}
LRESULT CEclipseWnd::OnShowWindow(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& )
{
if (g_pCosmos->m_strWorkBenchStrs != _T(""))
{
int nPos = g_pCosmos->m_strWorkBenchStrs.Find(_T("|"));
m_strDocKey = g_pCosmos->m_strWorkBenchStrs.Left(nPos);
g_pCosmos->m_strWorkBenchStrs = g_pCosmos->m_strWorkBenchStrs.Mid(nPos + 1);
}
if (g_pCosmos->m_strCurrentEclipsePagePath != _T(""))
{
m_strDocKey = g_pCosmos->m_strCurrentEclipsePagePath;
g_pCosmos->m_strCurrentEclipsePagePath = _T("");
}
if (::IsWindow(m_hClient)/*&& m_strDocKey!=_T("")*/)
{
Show(m_strDocKey);
}
LRESULT lRes = DefWindowProc(uMsg, wParam, lParam);
return lRes;
}
LRESULT CEclipseWnd::OnCommand(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL&)
{
if (wParam == m_nNewWinCmdID)
{
if (g_pCosmos->m_strCurrentEclipsePagePath == _T(""))
{
CComBSTR bstrTemplate(L"");
g_pCosmos->m_strCurrentEclipsePagePath = OLE2T(bstrTemplate);
}
if (g_pCosmos->m_strCurrentEclipsePagePath == _T("")&& m_pGalaxy)
{
IXobj* pXobj = nullptr;
m_pGalaxy->Observe(CComBSTR(L"newdocument"), g_pCosmos->m_strNewDocXml.AllocSysString(), &pXobj);
if (pXobj)
return 0;
}
}
LRESULT lRes = DefWindowProc(uMsg, wParam, lParam);
return lRes;
}
LRESULT CEclipseWnd::OnCosmosGetXml(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL&)
{
CString strGalaxyName = (LPCTSTR)wParam;
CString currentKey = (LPCTSTR)lParam;
CString strIndex = strGalaxyName + L"_" + currentKey;
CTangramXmlParse parse;
if (parse.LoadXml(m_strXml) || parse.LoadFile(m_strXml))
{
CTangramXmlParse* pParse = parse.GetChild(strGalaxyName);
if (pParse)
{
CTangramXmlParse* pParse2 = pParse->GetChild(currentKey);
if (pParse2)
{
auto it = g_pCosmos->m_mapValInfo.find(strIndex);
if (it != g_pCosmos->m_mapValInfo.end())
{
g_pCosmos->m_mapValInfo.erase(it);
}
g_pCosmos->m_mapValInfo[strIndex] = CComVariant(pParse2->xml());
return 1;
}
}
}
LRESULT lRes = DefWindowProc(uMsg, wParam, lParam);
return lRes;
}
LRESULT CEclipseWnd::OnCosmosMsg(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& )
{
switch (wParam)
{
case 1963:
{
return ::SendMessage(::GetParent(m_hClient), WM_QUERYAPPPROXY, wParam, 0);
}
break;
case 20190305:
{
return (LRESULT)this;
}
break;
case 19820911:
{
if (lParam == 0)
{
::PostMessage(m_hWnd, WM_COSMOSMSG, 19820911, 1);
}
if (lParam == 1)
{
CGalaxy* pGalaxy = (CGalaxy*)::SendMessage(m_hClient, WM_HUBBLE_DATA, 0, 1992);
if (pGalaxy)
{
pGalaxy->m_nGalaxyType = EclipseWorkBenchGalaxy;
pGalaxy->m_pWorkBenchFrame = this;
}
else
{
if (g_pCosmos->m_strWorkBenchStrs != _T(""))
{
int nPos = g_pCosmos->m_strWorkBenchStrs.Find(_T("|"));
m_strDocKey = g_pCosmos->m_strWorkBenchStrs.Left(nPos);
g_pCosmos->m_strWorkBenchStrs = g_pCosmos->m_strWorkBenchStrs.Mid(nPos + 1);
}
if (g_pCosmos->m_strCurrentEclipsePagePath != _T(""))
{
m_strDocKey = g_pCosmos->m_strCurrentEclipsePagePath;
g_pCosmos->m_strCurrentEclipsePagePath = _T("");
}
LONG_PTR data = 0;
if (::IsWindow(m_hClient)/*&& m_strDocKey!=_T("")*/)
{
data = ::GetWindowLongPtr(m_hClient, GWLP_USERDATA);
if (data == 0)
{
Show(m_strDocKey);
break;
}
}
}
}
}
break;
}
LRESULT lRes = DefWindowProc(uMsg, wParam, lParam);
return lRes;
}
LRESULT CEclipseWnd::OnClose(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& )
{
m_strPath = g_pCosmos->m_strAppDataPath + _T("default.workbench");
if (m_strPath != _T(""))
{
LRESULT lRes = ::SendMessage(::GetParent(m_hClient),WM_QUERYAPPPROXY,0,19631222);
if (lRes == 0)
{
CTangramXmlParse m_Parse;
if (m_pGalaxyCluster)
{
m_strXml = _T("<eclipseplus>");
for (auto it : m_pGalaxyCluster->m_mapGalaxy)
{
CGalaxy* pGalaxy = it.second;
for (auto it2 : pGalaxy->m_mapXobj)
{
CXobj* pWndXobj = (CXobj*)it2.second;
if (pWndXobj)
{
if (pWndXobj->m_pWindow)
{
if (pWndXobj->m_nActivePage > 0)
{
CString strVal = _T("");
strVal.Format(_T("%d"), pWndXobj->m_nActivePage);
pWndXobj->m_pHostParse->put_attr(_T("activepage"), strVal);
}
pWndXobj->m_pWindow->Save();
}
if (pWndXobj->m_nViewType == Grid)
{
((CGridWnd*)pWndXobj->m_pHostWnd)->Save();
}
g_pCosmos->UpdateXobj(pWndXobj);
for (auto it2 : pWndXobj->m_vChildNodes)
{
g_pCosmos->UpdateXobj(it2);
}
}
}
}
for (auto it : m_pGalaxyCluster->m_mapNeedSaveGalaxy)
{
CGalaxy* pGalaxy = it.second;
auto it2 = pGalaxy->m_mapXobj.find(_T("default"));
if (it2 != pGalaxy->m_mapXobj.end())
{
CXobj* _pXobj = (CXobj*)it2->second;
if (pGalaxy->m_strGalaxyName.Find(_T("@")) == -1)
{
CString strXml = _pXobj->m_pXobjShareData->m_pCosmosParse->xml();
strXml.Replace(_T("/><"), _T("/>\r\n<"));
strXml.Replace(_T("/>"), _T("></xobj>"));
CString s = _T("");
s.Format(_T("<%s>%s</%s>"), pGalaxy->m_strGalaxyName, strXml, pGalaxy->m_strGalaxyName);
m_strXml += s;
}
}
}
m_strXml += _T("</eclipseplus>");
}
bool bSave = false;
if (m_Parse.LoadXml(m_strXml))
{
if (m_pAppProxy)
{
m_Parse.put_attr(_T("styleproxyid"), m_strAppProxyID);
}
bSave = m_Parse.SaveFile(m_strPath);
}
}
}
LRESULT lRes = DefWindowProc(uMsg, wParam, lParam);
return lRes;
}
LRESULT CEclipseWnd::OnDestroy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& )
{
CTangramXmlParse xmlParse;
if (xmlParse.LoadFile(g_pCosmos->m_strConfigDataFile))
{
CTangramXmlParse* pParse = xmlParse.GetChild(_T("openedworkbench"));
if (pParse == nullptr)
{
pParse = xmlParse.AddNode(_T("openedworkbench"));
}
if (pParse)
{
CString strWorkBenchStrs = m_strDocKey + _T("|");
strWorkBenchStrs += pParse->text();
pParse->put_text(strWorkBenchStrs);
xmlParse.SaveFile(g_pCosmos->m_strConfigDataFile);
}
}
if (g_pCosmos->m_pActiveEclipseWnd == this)
g_pCosmos->m_pActiveEclipseWnd = nullptr;
auto it = g_pCosmos->m_mapWorkBenchWnd.find(m_hWnd);
if (it != g_pCosmos->m_mapWorkBenchWnd.end())
{
g_pCosmos->m_mapWorkBenchWnd.erase(it);
//if (g_pCosmos->m_mapWorkBenchWnd.size()==0)
//{
// if(::IsWindow(g_pCosmos->m_hHostWnd))
// ::DestroyWindow(g_pCosmos->m_hHostWnd);
//}
}
LRESULT lRes = DefWindowProc(uMsg, wParam, lParam);
if (g_pCosmos->m_mapWorkBenchWnd.size() == 0)
{
if (::GetModuleHandle(L"chrome_elf.dll"))
{
if (g_pCosmos)
{
if (g_pCosmos->m_mapBrowserWnd.size())
{
g_pCosmos->m_bChromeNeedClosed = true;
auto it = g_pCosmos->m_mapBrowserWnd.begin();
((CBrowser*)it->second)->SendMessageW(WM_CLOSE, 0, 0);
}
}
}
if (::IsWindow(g_pCosmos->m_hHostWnd))
::DestroyWindow(g_pCosmos->m_hHostWnd);
}
return lRes;
}
LRESULT CEclipseWnd::OnActivate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& )
{
LRESULT lRes = DefWindowProc(uMsg, wParam, lParam);
if (LOWORD(wParam) != WA_INACTIVE)
{
g_pCosmos->m_pActiveEclipseWnd = this;
g_pCosmos->m_pActiveAppProxy = m_pAppProxy;
}
return lRes;
}
LRESULT CEclipseWnd::OnQueryAppProxy(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& )
{
LRESULT lRes = ::SendMessage(::GetParent(m_hClient), uMsg, wParam, 19631992);
if (lRes)
{
if (m_pAppProxy==nullptr)
m_pAppProxy = (IUniverseAppProxy*)lRes;
return lRes;
}
lRes = DefWindowProc(uMsg, wParam, lParam);
return lRes;
}
CEclipseCtrl::CEclipseCtrl()
{
m_varTag.vt = VT_BSTR;
m_varTag.bstrVal = ::SysAllocString(L"");
m_hEclipseViewWnd = NULL;
m_pCurXobj = nullptr;
m_pEclipseWnd = nullptr;
m_pGalaxyClusterProxy = nullptr;
}
STDMETHODIMP CEclipseCtrl::get_AppKeyValue(BSTR bstrKey, VARIANT* pVal)
{
if (g_pCosmos)
{
return g_pCosmos->get_AppKeyValue(bstrKey, pVal);
}
return S_FALSE;
}
STDMETHODIMP CEclipseCtrl::put_AppKeyValue(BSTR bstrKey, VARIANT newVal)
{
if (g_pCosmos)
{
return g_pCosmos->put_AppKeyValue(bstrKey, newVal);
}
return S_OK;
}
STDMETHODIMP CEclipseCtrl::get_tag(VARIANT* pVal)
{
*pVal = m_varTag;
return S_OK;
}
STDMETHODIMP CEclipseCtrl::put_tag(VARIANT newVal)
{
::VariantClear(&m_varTag);
m_varTag = newVal;
return S_OK;
}
HRESULT CEclipseCtrl::Fire_GalaxyClusterLoaded(IDispatch* sender, BSTR url)
{
HRESULT hr = S_OK;
int cConnections = m_vec.GetSize();
if (cConnections)
{
CComVariant avarParams[2];
avarParams[1] = sender;
avarParams[1].vt = VT_DISPATCH;
avarParams[0] = url;
avarParams[0].vt = VT_BSTR;
DISPPARAMS params = { avarParams, NULL, 2, 0 };
for (int iConnection = 0; iConnection < cConnections; iConnection++)
{
g_pCosmos->Lock();
CComPtr<IUnknown> punkConnection = m_vec.GetAt(iConnection);
g_pCosmos->Unlock();
IDispatch * pConnection = static_cast<IDispatch *>(punkConnection.p);
if (pConnection)
{
CComVariant varResult;
hr = pConnection->Invoke(1, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, ¶ms, &varResult, NULL, NULL);
}
}
}
if (m_pGalaxyClusterProxy)
m_pGalaxyClusterProxy->OnGalaxyClusterLoaded(sender, OLE2T(url));
return hr;
}
HRESULT CEclipseCtrl::Fire_NodeCreated(IXobj * pXobjCreated)
{
HRESULT hr = S_OK;
int cConnections = m_vec.GetSize();
if (cConnections)
{
CComVariant avarParams[1];
avarParams[0] = pXobjCreated;
avarParams[0].vt = VT_DISPATCH;
DISPPARAMS params = { avarParams, NULL, 1, 0 };
for (int iConnection = 0; iConnection < cConnections; iConnection++)
{
g_pCosmos->Lock();
IUnknown* punkConnection = m_vec.GetAt(iConnection);
g_pCosmos->Unlock();
IDispatch * pConnection = static_cast<IDispatch *>(punkConnection);
if (pConnection)
{
CComVariant varResult;
hr = pConnection->Invoke(2, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, ¶ms, &varResult, NULL, NULL);
}
}
}
if (m_pGalaxyClusterProxy)
m_pGalaxyClusterProxy->OnXobjCreated(pXobjCreated);
return hr;
}
HRESULT CEclipseCtrl::Fire_AddInCreated(IXobj * pRootXobj, IDispatch * pAddIn, BSTR bstrID, BSTR bstrAddInXml)
{
HRESULT hr = S_OK;
int cConnections = m_vec.GetSize();
if (cConnections)
{
CComVariant avarParams[4];
avarParams[3] = pRootXobj;
avarParams[2] = pAddIn;
avarParams[2].vt = VT_DISPATCH;
avarParams[1] = bstrID;
avarParams[1].vt = VT_BSTR;
avarParams[0] = bstrAddInXml;
avarParams[0].vt = VT_BSTR;
DISPPARAMS params = { avarParams, NULL, 4, 0 };
for (int iConnection = 0; iConnection < cConnections; iConnection++)
{
g_pCosmos->Lock();
IUnknown* punkConnection = m_vec.GetAt(iConnection);
g_pCosmos->Unlock();
IDispatch * pConnection = static_cast<IDispatch *>(punkConnection);
if (pConnection)
{
CComVariant varResult;
hr = pConnection->Invoke(3, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, ¶ms, &varResult, NULL, NULL);
}
}
}
if (m_pGalaxyClusterProxy)
m_pGalaxyClusterProxy->OnAddInCreated(pRootXobj, pAddIn, OLE2T(bstrID), OLE2T(bstrAddInXml));
return hr;
}
HRESULT CEclipseCtrl::Fire_BeforeOpenXml(BSTR bstrXml, LONGLONG hWnd)
{
HRESULT hr = S_OK;
int cConnections = m_vec.GetSize();
if (cConnections)
{
CComVariant avarParams[2];
avarParams[1] = bstrXml;
avarParams[1].vt = VT_BSTR;
avarParams[0] = hWnd;
avarParams[0].vt = VT_I8;
DISPPARAMS params = { avarParams, NULL, 2, 0 };
for (int iConnection = 0; iConnection < cConnections; iConnection++)
{
g_pCosmos->Lock();
IUnknown* punkConnection = m_vec.GetAt(iConnection);
g_pCosmos->Unlock();
IDispatch * pConnection = static_cast<IDispatch *>(punkConnection);
if (pConnection)
{
CComVariant varResult;
hr = pConnection->Invoke(4, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, ¶ms, &varResult, NULL, NULL);
}
}
}
if (m_pGalaxyClusterProxy)
m_pGalaxyClusterProxy->OnBeforeOpenXml(OLE2T(bstrXml), (HWND)hWnd);
return hr;
}
HRESULT CEclipseCtrl::Fire_OpenXmlComplete(BSTR bstrXml, LONGLONG hWnd, IXobj * pRetRootNode)
{
HRESULT hr = S_OK;
int cConnections = m_vec.GetSize();
if (cConnections)
{
CComVariant avarParams[3];
avarParams[2] = bstrXml;
avarParams[2].vt = VT_BSTR;
avarParams[1] = hWnd;
avarParams[1].vt = VT_I8;
avarParams[0] = pRetRootNode;
avarParams[0].vt = VT_DISPATCH;
DISPPARAMS params = { avarParams, NULL, 3, 0 };
for (int iConnection = 0; iConnection < cConnections; iConnection++)
{
g_pCosmos->Lock();
IUnknown* punkConnection = m_vec.GetAt(iConnection);
g_pCosmos->Unlock();
IDispatch * pConnection = static_cast<IDispatch *>(punkConnection);
if (pConnection)
{
CComVariant varResult;
hr = pConnection->Invoke(5, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, ¶ms, &varResult, NULL, NULL);
}
}
}
if (m_pGalaxyClusterProxy)
m_pGalaxyClusterProxy->OnOpenXmlComplete(OLE2T(bstrXml), (HWND)hWnd, pRetRootNode);
return hr;
}
HRESULT CEclipseCtrl::Fire_Destroy()
{
HRESULT hr = S_OK;
int cConnections = m_vec.GetSize();
if (cConnections)
{
DISPPARAMS params = { NULL, NULL, 0, 0 };
for (int iConnection = 0; iConnection < cConnections; iConnection++)
{
g_pCosmos->Lock();
IUnknown* punkConnection = m_vec.GetAt(iConnection);
g_pCosmos->Unlock();
IDispatch * pConnection = static_cast<IDispatch *>(punkConnection);
if (pConnection)
{
CComVariant varResult;
hr = pConnection->Invoke(6, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, ¶ms, &varResult, NULL, NULL);
}
}
}
if (m_pGalaxyClusterProxy)
m_pGalaxyClusterProxy->OnDestroy();
return hr;
}
HRESULT CEclipseCtrl::Fire_NodeMouseActivate(IXobj * pActiveNode)
{
HRESULT hr = S_OK;
int cConnections = m_vec.GetSize();
if (cConnections)
{
CComVariant avarParams[1];
avarParams[0] = pActiveNode;
avarParams[0].vt = VT_DISPATCH;
DISPPARAMS params = { avarParams, NULL, 1, 0 };
for (int iConnection = 0; iConnection < cConnections; iConnection++)
{
g_pCosmos->Lock();
CComPtr<IUnknown> punkConnection = m_vec.GetAt(iConnection);
g_pCosmos->Unlock();
IDispatch * pConnection = static_cast<IDispatch *>(punkConnection.p);
if (pConnection)
{
CComVariant varResult;
hr = pConnection->Invoke(7, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, ¶ms, &varResult, NULL, NULL);
}
}
}
if (m_pGalaxyClusterProxy)
m_pGalaxyClusterProxy->OnNodeMouseActivate(pActiveNode);
return hr;
}
HRESULT CEclipseCtrl::Fire_ClrControlCreated(IXobj * Node, IDispatch * Ctrl, BSTR CtrlName, LONGLONG CtrlHandle)
{
HRESULT hr = S_OK;
int cConnections = m_vec.GetSize();
if (cConnections)
{
CComVariant avarParams[4];
avarParams[3] = Node;
avarParams[3].vt = VT_DISPATCH;
avarParams[2] = Ctrl;
avarParams[2].vt = VT_DISPATCH;
avarParams[1] = CtrlName;
avarParams[1].vt = VT_BSTR;
avarParams[0] = CtrlHandle;
avarParams[0].vt = VT_I8;
DISPPARAMS params = { avarParams, NULL, 4, 0 };
for (int iConnection = 0; iConnection < cConnections; iConnection++)
{
g_pCosmos->Lock();
IUnknown* punkConnection = m_vec.GetAt(iConnection);
g_pCosmos->Unlock();
IDispatch * pConnection = static_cast<IDispatch *>(punkConnection);
if (pConnection)
{
CComVariant varResult;
hr = pConnection->Invoke(8, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, ¶ms, &varResult, NULL, NULL);
}
}
}
if (m_pGalaxyClusterProxy)
m_pGalaxyClusterProxy->OnClrControlCreated(Node, Ctrl, OLE2T(CtrlName), (HWND)CtrlHandle);
return hr;
}
HRESULT CEclipseCtrl::Fire_TabChange(IXobj* sender, LONG ActivePage, LONG OldPage)
{
HRESULT hr = S_OK;
int cConnections = m_vec.GetSize();
if (cConnections)
{
CComVariant avarParams[3];
avarParams[2] = sender;
avarParams[2].vt = VT_DISPATCH;
avarParams[1] = ActivePage;
avarParams[1].vt = VT_I4;
avarParams[0] = OldPage;
avarParams[0].vt = VT_I4;
DISPPARAMS params = { avarParams, NULL, 3, 0 };
for (int iConnection = 0; iConnection < cConnections; iConnection++)
{
g_pCosmos->Lock();
IUnknown* punkConnection = m_vec.GetAt(iConnection);
g_pCosmos->Unlock();
IDispatch * pConnection = static_cast<IDispatch *>(punkConnection);
if (pConnection)
{
CComVariant varResult;
hr = pConnection->Invoke(9, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, ¶ms, &varResult, NULL, NULL);
}
}
}
if (m_pGalaxyClusterProxy)
m_pGalaxyClusterProxy->OnTabChange(sender, ActivePage, OldPage);
return hr;
}
HRESULT CEclipseCtrl::Fire_Event(IXobj* sender, IDispatch* EventArg)
{
HRESULT hr = S_OK;
int cConnections = m_vec.GetSize();
if (cConnections)
{
CComVariant avarParams[2];
avarParams[1] = sender;
avarParams[1].vt = VT_DISPATCH;
avarParams[0] = EventArg;
avarParams[0].vt = VT_DISPATCH;
DISPPARAMS params = { avarParams, NULL, 2, 0 };
for (int iConnection = 0; iConnection < cConnections; iConnection++)
{
g_pCosmos->Lock();
IUnknown* punkConnection = m_vec.GetAt(iConnection);
g_pCosmos->Unlock();
IDispatch * pConnection = static_cast<IDispatch *>(punkConnection);
if (pConnection)
{
CComVariant varResult;
hr = pConnection->Invoke(10, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, ¶ms, &varResult, NULL, NULL);
}
}
}
return hr;
}
HRESULT CEclipseCtrl::Fire_ControlNotify(IXobj * sender, LONG NotifyCode, LONG CtrlID, LONGLONG CtrlHandle, BSTR CtrlClassName)
{
HRESULT hr = S_OK;
int cConnections = m_vec.GetSize();
if (cConnections)
{
CComVariant avarParams[5];
avarParams[4] = sender;
avarParams[4].vt = VT_DISPATCH;
avarParams[3] = NotifyCode;
avarParams[3].vt = VT_I4;
avarParams[2] = CtrlID;
avarParams[2].vt = VT_I4;
avarParams[1] = CtrlHandle;
avarParams[1].vt = VT_I8;
avarParams[0] = CtrlClassName;
avarParams[0].vt = VT_BSTR;
DISPPARAMS params = { avarParams, NULL, 5, 0 };
for (int iConnection = 0; iConnection < cConnections; iConnection++)
{
g_pCosmos->Lock();
CComPtr<IUnknown> punkConnection = m_vec.GetAt(iConnection);
g_pCosmos->Unlock();
IDispatch * pConnection = static_cast<IDispatch *>(punkConnection.p);
if (pConnection)
{
CComVariant varResult;
hr = pConnection->Invoke(11, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, ¶ms, &varResult, NULL, NULL);
}
}
}
if (m_pGalaxyClusterProxy)
m_pGalaxyClusterProxy->OnControlNotify(sender, NotifyCode, CtrlID, (HWND)CtrlHandle, OLE2T(CtrlClassName));
return hr;
}
HRESULT CEclipseCtrl::Fire_CosmosEvent(ICosmosEventObj* pEventObj)
{
HRESULT hr = S_OK;
int cConnections = m_vec.GetSize();
if (cConnections)
{
CComVariant avarParams[1];
avarParams[0] = pEventObj;
avarParams[0].vt = VT_DISPATCH;
DISPPARAMS params = { avarParams, NULL, 1, 0 };
for (int iConnection = 0; iConnection < cConnections; iConnection++)
{
g_pCosmos->Lock();
IUnknown* punkConnection = m_vec.GetAt(iConnection);
g_pCosmos->Unlock();
IDispatch * pConnection = static_cast<IDispatch *>(punkConnection);
if (pConnection)
{
CComVariant varResult;
hr = pConnection->Invoke(12, IID_NULL, LOCALE_USER_DEFAULT, DISPATCH_METHOD, ¶ms, &varResult, NULL, NULL);
}
}
}
if (m_pGalaxyClusterProxy)
m_pGalaxyClusterProxy->OnCosmosEvent(pEventObj);
return hr;
}
STDMETHODIMP CEclipseCtrl::InitCtrl(BSTR bstrXml)
{
CString strXml = OLE2T(bstrXml);
if (strXml != _T(""))
{
CTangramXmlParse m_Parse;
if (!m_Parse.LoadXml(strXml))
{
CString strPath = g_pCosmos->m_strAppPath + strXml;
if (m_Parse.LoadFile(strPath) == false)
return S_OK;
}
int nCount = m_Parse.GetCount();
CTangramXmlParse* pChild = nullptr;
for (int i = 0; i < nCount; i++)
{
pChild = m_Parse.GetChild(i);
CString strName = pChild->name();
strName.MakeLower();
auto it = m_mapCosmosInfo.find(strName);
if (it == m_mapCosmosInfo.end())
{
m_mapCosmosInfo[strName] = pChild->xml();
}
}
}
return S_OK;
}
STDMETHODIMP CEclipseCtrl::put_Handle(BSTR bstrHandleName, LONGLONG newVal)
{
CString strName = OLE2T(bstrHandleName);
HWND hWnd = (HWND)newVal;
if (strName != _T("") && ::IsWindow(hWnd))
{
auto it = m_mapCosmosHandle.find(strName);
if (it != m_mapCosmosHandle.end())
m_mapCosmosHandle.erase(strName);
m_mapCosmosHandle[strName] = hWnd;
}
return S_OK;
}
STDMETHODIMP CEclipseCtrl::Observe(BSTR bstrGalaxyName, BSTR bstrKey, BSTR bstrXml, IXobj** ppXobj)
{
CString strGalaxyName = OLE2T(bstrGalaxyName);
if (strGalaxyName == _T(""))
strGalaxyName = _T("EclipseView");
if (strGalaxyName.CompareNoCase(_T("TopView")) == 0)
{
return m_pEclipseWnd->Observe(bstrKey, bstrXml, ppXobj);
}
auto it = m_mapCosmosHandle.find(strGalaxyName);
if (it == m_mapCosmosHandle.end())
return S_FALSE;
HWND hWnd = it->second;
CString strKey = OLE2T(bstrKey);
if (strKey == _T(""))
strKey= _T("default");
CString strXml = OLE2T(bstrXml);
IXobj* pXobj = nullptr;
auto it2 = m_mapGalaxy.find(strGalaxyName);
if (it2 == m_mapGalaxy.end())
{
HWND hTop = ::GetAncestor(m_hWnd, GA_ROOT);
IGalaxyCluster* pGalaxyCluster = nullptr;
g_pCosmos->CreateGalaxyCluster((LONGLONG)hTop, &pGalaxyCluster);
if (pGalaxyCluster == nullptr)
return S_OK;
//m_pGalaxyCluster = (CGalaxyCluster*)pGalaxyCluster;m_pEclipseWnd->m_
IGalaxy* pGalaxy = nullptr;
pGalaxyCluster->CreateGalaxy(CComVariant(0), CComVariant((long)hWnd), bstrGalaxyName, &pGalaxy);
if (pGalaxy == nullptr)
{
return S_FALSE;
}
m_mapGalaxy[strGalaxyName] = (CGalaxy*)pGalaxy;
HRESULT hr = pGalaxy->Observe(bstrKey, bstrXml, ppXobj);
if (hr == S_OK&&strGalaxyName.CompareNoCase(_T("EclipseView")) == 0)
{
if (strGalaxyName.CompareNoCase(_T("EclipseView")) == 0)
{
((CGalaxy*)pGalaxy)->m_nGalaxyType = EclipseViewGalaxy;
}
else
((CGalaxy*)pGalaxy)->m_nGalaxyType = EclipseSWTGalaxy;
(*ppXobj)->put_SaveToConfigFile(true);
}
return hr;
}
HRESULT hr = it2->second->Observe(bstrKey, bstrXml, ppXobj);
if(hr==S_OK&&strGalaxyName.CompareNoCase(_T("EclipseView")) == 0)
(*ppXobj)->put_SaveToConfigFile(true);
return hr;
}
STDMETHODIMP CEclipseCtrl::ObserveEx(BSTR bstrGalaxyName, BSTR bstrKey, BSTR bstrXml, IXobj** ppXobj)
{
HRESULT hr = Observe(bstrGalaxyName, bstrKey, bstrXml, ppXobj);
if (hr == S_OK&&*ppXobj != nullptr)
(*ppXobj)->put_SaveToConfigFile(true);
return S_OK;
}
void CEclipseCtrl::OnFinalMessage(HWND hWnd)
{
::VariantClear(&m_varTag);
if (m_pEclipseWnd)
{
auto it = m_pEclipseWnd->m_mapCtrl.find(hWnd);
if (it != m_pEclipseWnd->m_mapCtrl.end())
m_pEclipseWnd->m_mapCtrl.erase(it);
}
__super::OnFinalMessage(hWnd);
if (g_pCosmos->m_bEclipse)
Release();
}
STDMETHODIMP CEclipseCtrl::get_EclipseViewHandle(LONGLONG* pVal)
{
*pVal = (LONGLONG)m_hEclipseViewWnd;
return S_OK;
}
LRESULT CEclipseCtrl::OnCreate(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL&)
{
LRESULT lr = DefWindowProc(uMsg, wParam, lParam);
HWND hTop = ::GetAncestor(m_hWnd, GA_ROOT);
HWND hClient = ::GetWindow(hTop, GW_CHILD);
m_mapCosmosHandle[_T("TopView")] = hClient;
m_hEclipseViewWnd = ::GetParent(::GetParent(::GetParent(m_hWnd)));
m_mapCosmosHandle[_T("EclipseView")] = m_hEclipseViewWnd;
::PostMessage(m_hWnd, WM_COSMOSMSG, 0, 0);
return lr;
}
LRESULT CEclipseCtrl::OnCosmosMsg(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL&)
{
LRESULT lr = DefWindowProc(uMsg, wParam, lParam);
HWND hTop = ::GetAncestor(m_hWnd, GA_ROOT);
auto it = g_pCosmos->m_mapWorkBenchWnd.find(hTop);
if (it != g_pCosmos->m_mapWorkBenchWnd.end())
{
m_pEclipseWnd = (CEclipseWnd*)it->second;
auto it2 = m_pEclipseWnd->m_mapCtrl.find(m_hWnd);
if (it2 == m_pEclipseWnd->m_mapCtrl.end())
m_pEclipseWnd->m_mapCtrl[m_hWnd] = this;
if (m_pEclipseWnd->m_pGalaxyCluster)
{
auto it = m_pEclipseWnd->m_pGalaxyCluster->m_mapNotifyCtrl.find(m_hWnd);
if (it == m_pEclipseWnd->m_pGalaxyCluster->m_mapNotifyCtrl.end())
m_pEclipseWnd->m_pGalaxyCluster->m_mapNotifyCtrl[m_hWnd] = this;
}
}
return lr;
}
STDMETHODIMP CEclipseCtrl::get_HWND(LONGLONG* pVal)
{
*pVal = (LONGLONG)m_hWnd;
return S_OK;
}
STDMETHODIMP CEclipseCtrl::get_Cosmos(ICosmos** pVal)
{
*pVal = g_pCosmos;
return S_OK;
}
STDMETHODIMP CEclipseCtrl::get_GalaxyCluster(IGalaxyCluster** pVal)
{
if (m_pEclipseWnd->m_pGalaxyCluster)
*pVal = m_pEclipseWnd->m_pGalaxyCluster;
return S_OK;
}
STDMETHODIMP CEclipseCtrl::get_WorkBenchWindow(IWorkBenchWindow** pVal)
{
if (m_pEclipseWnd)
*pVal = m_pEclipseWnd;
return S_OK;
}
STDMETHODIMP CEclipseCtrl::get_TopGalaxyCluster(IGalaxyCluster** pVal)
{
if (m_pEclipseWnd)
{
*pVal = m_pEclipseWnd->m_pGalaxyCluster;
}
return S_OK;
}
STDMETHODIMP CEclipseCtrl::get_TopGalaxy(IGalaxy** pVal)
{
if (m_pEclipseWnd)
{
*pVal = m_pEclipseWnd->m_pGalaxy;
}
return S_OK;
}
STDMETHODIMP CEclipseCtrl::get_ActiveTopXobj(IXobj** pVal)
{
if (m_pEclipseWnd)
{
*pVal = m_pEclipseWnd->m_pGalaxy->m_pWorkXobj;
}
return S_OK;
}
HRESULT CEclipseCtrl::FinalConstruct()
{
CString strKey = _T("startdata");
auto it = g_pCosmos->m_mapValInfo.find(strKey);
if (it != g_pCosmos->m_mapValInfo.end())
{
CString strData = OLE2T(it->second.bstrVal);
int nPos = strData.Find(_T("|"));
if (nPos != -1)
{
g_pCosmos->m_strStartView = strData.Left(nPos);
g_pCosmos->m_strStartXml = strData.Mid(nPos + 1);
if (::IsWindow(g_pCosmos->m_hHostWnd))
{
::PostMessage(g_pCosmos->m_hHostWnd, WM_HUBBLE_APPQUIT, 0, 0);
}
}
::VariantClear(&it->second);
g_pCosmos->m_mapValInfo.erase(it);
}
return S_OK;
}
| [
"[email protected]"
] | |
1a4bf1512a29473c968448dc28768c77e652b8ce | d62d179f9ad43ed22cee561a97c589c90c178cec | /modules/core/linalg/unit/functions/orthog.cpp | 5401aec5769135adc274403a0887d7d9d0e970f5 | [
"BSL-1.0"
] | permissive | timblechmann/nt2 | 89385373c14add7e2df48c9114a93e37a8e6e0cf | 6c71f7063ca4e5975c9c019877e6b2fe07c9e4ce | refs/heads/master | 2021-01-16T23:49:00.220699 | 2013-03-11T09:31:23 | 2013-03-11T09:31:23 | 8,702,183 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,367 | cpp | //==============================================================================
// Copyright 2003 - 2012 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2012 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#define NT2_UNIT_MODULE "nt2 linalg toolbox - orthog function"
#include <nt2/table.hpp>
#include <nt2/include/functions/orthog.hpp>
#include <nt2/include/functions/cons.hpp>
#include <nt2/include/functions/transpose.hpp>
#include <nt2/include/functions/cast.hpp>
#include <nt2/sdk/unit/tests/ulp.hpp>
#include <nt2/sdk/unit/module.hpp>
#include <boost/mpl/int.hpp>
NT2_TEST_CASE_TPL ( orthog, NT2_REAL_TYPES)
{
typedef typename std::complex<T> cT;
typedef typename nt2::meta::as_<T> ta_t;
nt2::table<T> m31 =nt2::trans(nt2::cons(nt2::of_size(3, 3),
T(0.500000000000000), T( 0.707106781186548), T( 0.500000000000000),
T(0.707106781186548), T( 0.000000000000000), T(-0.707106781186548),
T(0.500000000000000), T(-0.707106781186548), T( 0.500000000000000)
));
nt2::table<T> m32 =nt2::trans(nt2::cons(nt2::of_size(3, 3),
T(0.591009048506103), T( 0.736976229099578), T( 0.327985277605682),
T(0.736976229099578), T(-0.327985277605682), T(-0.591009048506104),
T(0.327985277605682), T(-0.591009048506104), T( 0.736976229099578)
));
nt2::table<cT> m33 =nt2::trans(nt2::cons(nt2::of_size(3, 3),
cT(0.577350269189626), cT( 0.577350269189626 ), cT( 0.577350269189626 ),
cT(0.577350269189626), cT(-0.288675134594813, 0.5), cT(-0.288675134594813, - 0.5),
cT(0.577350269189626), cT(-0.288675134594813,-0.5), cT(-0.288675134594812, + 0.5)
));
nt2::table<T> m34 =nt2::trans(nt2::cons(nt2::of_size(3, 3),
T(0.577350269189626), T( 0.577350269189626), T(0.577350269189626),
T(0.707106781186547), T(-0.707106781186547), T( 0),
T(0.408248290463863), T( 0.408248290463863), -T(0.816496580927726)
));
nt2::table<T> m35 =nt2::trans(nt2::cons(nt2::of_size(3, 3),
T(0.577350269189626), T( 0.577350269189626), T( 0.577350269189626),
T(0.577350269189626), T( 0.211324865405187), T(-0.788675134594813),
T(0.577350269189626), T(-0.788675134594813), T( 0.211324865405188)
));
nt2::table<T> m36 =nt2::trans(nt2::cons(nt2::of_size(3, 3),
T(0.788675134594813), T( 0.577350269189626), T( 0.211324865405187),
T(0.577350269189626), T(-0.577350269189626), T(-0.577350269189626),
T(0.211324865405187), T(-0.577350269189626), T( 0.788675134594813)
));
nt2::table<T> m3m1 =nt2::trans(nt2::cons(nt2::of_size(3, 3),
T(1), T(1), T(1),
T(1), T(0), T(-1),
T(1), T(-1), T(1)
));
nt2::table<T> m3m2 =nt2::trans(nt2::cons(nt2::of_size(3, 3),
T(1), T(1), T(1),
T( 0.866025403784439), T(0), T(-0.866025403784438),
T(0.5), T(-1), T(0.5)
));
NT2_TEST_ULP_EQUAL((nt2::orthog1(3, ta_t())), m31, 2);
NT2_TEST_ULP_EQUAL((nt2::orthog2(3, ta_t())), m32, 4);
NT2_TEST_ULP_EQUAL((nt2::orthog3(3, ta_t())), m33, 4);
NT2_TEST_ULP_EQUAL((nt2::orthog4(3, ta_t())), m34, 10);
NT2_TEST_ULP_EQUAL((nt2::orthog5(3, ta_t())), m35, 10);
NT2_TEST_ULP_EQUAL((nt2::orthog6(3, ta_t())), m36, 10);
NT2_TEST_ULP_EQUAL((nt2::orthog7(3, ta_t())), m35, 16);
NT2_TEST_ULP_EQUAL((nt2::orthogm1(3, ta_t())), m3m1, 16);
NT2_TEST_ULP_EQUAL((nt2::orthogm2(3, ta_t())), m3m2, 16);
NT2_TEST_ULP_EQUAL((nt2::orthog<1, T>(3)), m31,2);
NT2_TEST_ULP_EQUAL((nt2::orthog<2, T>(3)), m32,4);
NT2_TEST_ULP_EQUAL((nt2::orthog<3, T>(3)), m33,4);
NT2_TEST_ULP_EQUAL((nt2::orthog<4, T>(3)), m34,4);
NT2_TEST_ULP_EQUAL((nt2::orthog<5, T>(3)), m35,10);
NT2_TEST_ULP_EQUAL((nt2::orthog<6, T>(3)), m36,10);
NT2_TEST_ULP_EQUAL((nt2::orthog<7, T>(3)), m35,16);
NT2_TEST_ULP_EQUAL((nt2::orthog<-1, T>(3)), m3m1,16);
NT2_TEST_ULP_EQUAL((nt2::orthog<-2, T>(3)), m3m2,16);
}
| [
"[email protected]"
] | |
88f7253f8e33e093cea52e4f4847cec7208cd521 | 2b72d0a3cae37935841f4737c696f02b29d5650b | /pa1.h | e0e44604ec7b7974b63fab84ecd5aec411b60e5b | [] | no_license | kevdaci/cop3502 | 495ca350307bf17f4bd788a229b3516bce19678d | 0488e689ebcaebf9b4ee5345656ba67b78c1ec19 | refs/heads/master | 2020-04-01T15:18:00.757646 | 2018-10-16T18:05:57 | 2018-10-16T18:05:57 | 153,330,658 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,038 | h | #include <iostream>
#include <cstdio>
#include <string>
#include <vector>
#include <cstdlib>
#ifndef PA1_H
#define PA1_H
using namespace std;
class MagicSquare{
private:
int square_dimension;
vector<vector<int> > magic_square;
void produce_numbers()
{
vector<int> one_d;
bool if_dec = false;
int number;
for(int i = 0; i < square_dimension; ++i){
for(int j = 0; j < square_dimension; j++){
number = rand()%10;
//while(
for(int k = 0; k < j; k++){
if(number == one_d[k])
if_dec = true;
}
if(!if_dec)
one_d.push_back(number);
}
magic_square.push_back(one_d);
one_d.clear();
}
}
public:
MagicSquare(int dimesions)
{
square_dimension = dimesions;
}
void printSquare()
{
produce_numbers();
for(unsigned int i = 0; i < magic_square.size(); ++i){
for(unsigned int j = 0; j < magic_square[i].size(); j++){
cout<<magic_square[i][j]<< " ";
}
cout << endl;
}
}
};
#endif
| [
"[email protected]"
] | |
0d9ef7b0f000e4c9c7d38c1a92a5e31a625e6e56 | 37d08c745caee39da991debb54635065df1a8e2a | /src/dgetrs_nopiv_gpu.cpp | fb95b2da30626256c3fc11cf235238e03f28dc26 | [] | no_license | kjbartel/magma | c936cd4838523779f31df418303c6bebb063aecd | 3f0dd347d2e230c8474d1e22e05b550fa233c7a3 | refs/heads/master | 2020-06-06T18:12:56.286615 | 2015-06-04T17:20:40 | 2015-06-04T17:20:40 | 36,885,326 | 23 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 3,720 | cpp | /*
-- MAGMA (version 1.6.1) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date January 2015
@author Adrien REMY
@generated from zgetrs_nopiv_gpu.cpp normal z -> d, Fri Jan 30 19:00:14 2015
*/
#include "common_magma.h"
/**
Purpose
-------
Solves a system of linear equations
A * X = B, A**T * X = B, or A**H * X = B
with a general N-by-N matrix A using the LU factorization computed by DGETRF_NOPIV_GPU.
Arguments
---------
@param[in]
trans magma_trans_t
Specifies the form of the system of equations:
- = MagmaNoTrans: A * X = B (No transpose)
- = MagmaTrans: A**T * X = B (Transpose)
- = MagmaConjTrans: A**H * X = B (Conjugate transpose)
@param[in]
n INTEGER
The order of the matrix A. N >= 0.
@param[in]
nrhs INTEGER
The number of right hand sides, i.e., the number of columns
of the matrix B. NRHS >= 0.
@param[in]
dA DOUBLE_PRECISION array on the GPU, dimension (LDA,N)
The factors L and U from the factorization A = P*L*U as computed
by DGETRF_GPU.
@param[in]
ldda INTEGER
The leading dimension of the array A. LDA >= max(1,N).
param[in,out]
dB DOUBLE_PRECISION array on the GPU, dimension (LDB,NRHS)
On entry, the right hand side matrix B.
On exit, the solution matrix X.
@param[in]
lddb INTEGER
The leading dimension of the array B. LDB >= max(1,N).
@param[out]
info INTEGER
- = 0: successful exit
- < 0: if INFO = -i, the i-th argument had an illegal value
@ingroup magma_dgesv_comp
********************************************************************/
extern "C" magma_int_t
magma_dgetrs_nopiv_gpu(
magma_trans_t trans, magma_int_t n, magma_int_t nrhs,
magmaDouble_ptr dA, magma_int_t ldda,
magmaDouble_ptr dB, magma_int_t lddb,
magma_int_t *info)
{
double c_one = MAGMA_D_ONE;
int notran = (trans == MagmaNoTrans);
*info = 0;
if ( (! notran) &&
(trans != MagmaTrans) &&
(trans != MagmaConjTrans) ) {
*info = -1;
} else if (n < 0) {
*info = -2;
} else if (nrhs < 0) {
*info = -3;
} else if (ldda < max(1,n)) {
*info = -5;
} else if (lddb < max(1,n)) {
*info = -7;
}
if (*info != 0) {
magma_xerbla( __func__, -(*info) );
return *info;
}
/* Quick return if possible */
if (n == 0 || nrhs == 0) {
return *info;
}
if (notran) {
/* Solve A * X = B. */
if ( nrhs == 1) {
magma_dtrsv(MagmaLower, MagmaNoTrans, MagmaUnit, n, dA, ldda, dB, 1 );
magma_dtrsv(MagmaUpper, MagmaNoTrans, MagmaNonUnit, n, dA, ldda, dB, 1 );
} else {
magma_dtrsm(MagmaLeft, MagmaLower, MagmaNoTrans, MagmaUnit, n, nrhs, c_one, dA, ldda, dB, lddb );
magma_dtrsm(MagmaLeft, MagmaUpper, MagmaNoTrans, MagmaNonUnit, n, nrhs, c_one, dA, ldda, dB, lddb );
}
} else {
/* Solve A**T * X = B or A**H * X = B. */
if ( nrhs == 1) {
magma_dtrsv(MagmaUpper, trans, MagmaNonUnit, n, dA, ldda, dB, 1 );
magma_dtrsv(MagmaLower, trans, MagmaUnit, n, dA, ldda, dB, 1 );
} else {
magma_dtrsm(MagmaLeft, MagmaUpper, trans, MagmaNonUnit, n, nrhs, c_one, dA, ldda, dB, lddb );
magma_dtrsm(MagmaLeft, MagmaLower, trans, MagmaUnit, n, nrhs, c_one, dA, ldda, dB, lddb );
}
}
return *info;
}
| [
"[email protected]"
] | |
329b94f868d6b6f9a7cbd303d5f46bb289885c84 | 42c193448118f9db1aa460ab099f3d7e179b4aa3 | /Interactive_Application/Interactive_Application/Source/Lab3Model.cpp | 400d82aacaf4a6648681001627aa82e6444419c7 | [] | no_license | NavneethRaj/CS7033-Real-Time-Animation | 939f4fdb7e0bc0f5aeef241d4ea9b66019eb6d66 | 548e373992f35e87d8c179d28f49509e66171173 | refs/heads/master | 2016-09-13T15:46:37.745844 | 2016-04-22T14:01:39 | 2016-04-22T14:01:39 | 56,593,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,458 | cpp | #include "Lab3Model.h"
Lab3Model::Lab3Model(void)
{
m_setup = new Setup();
m_shader = new Shader();
m_shader_loader = new Shader();
m_objectBuffer = new ObjectBuffer(36);
m_camera = new Camera(m_setup);
point_count = 0;
humanSkeleton = new HumanSkeleton(m_setup);
plane = new Cylinder();
armSkeleton = new ArmSkeleton(m_setup);
thirdCamera = false;
thirdCamera_2 = false;
followBallCamera = false;
drawCircleCamera = false;
animationState = false;
m_mesh = new Mesh();
m_effect = new SkinningTechnique();
floor_mesh = new Mesh();
floor_effect = new SkinningTechnique();
football_mesh = new Mesh();
football_effect = new SkinningTechnique();
charRot = 0.0f;
startTime = GetCurrentTimeMillis();
targetPos = glm::vec3(0,0,0);
conterAni = 0.0f;
timeFlag = false;
deltaTime = 0.0f;
cameraPath = true;
camTime = 0.01f;
}
Lab3Model::~Lab3Model(void)
{
}
void Lab3Model::run(void)
{
m_setup->setupGlfwGlew();
//initShaders();
initLoaderShaders();
if (!m_effect->Init(m_shader_loader->GetProgramID()))
{
printf("Error initializing the lighting technique\n");
}
m_effect->SetColorTextureUnit(COLOR_TEXTURE_UNIT_INDEX);
std::string mainName = "../Models/soccer_pass_1/soccer_pass_1.dae";
if (!m_mesh->LoadMesh(mainName))
{
cout << "Main Character Load Failed" << endl;
}
//floor
if (!floor_effect->Init(m_shader_loader->GetProgramID()))
{
printf("Error initializing the lighting technique\n");
}
floor_effect->SetColorTextureUnit(COLOR_TEXTURE_UNIT_INDEX);
std::string floorName = "../Models/untitled.dae";
if (!floor_mesh->LoadMesh(floorName))
{
cout << "Main Character Load Failed" << endl;
}
//football
if (!football_effect->Init(m_shader_loader->GetProgramID()))
{
printf("Error initializing the lighting technique\n");
}
football_effect->SetColorTextureUnit(COLOR_TEXTURE_UNIT_INDEX);
std::string footName = "../Models/walking_6/walking_6.dae";
if (!football_mesh->LoadMesh(footName))
{
cout << "Main Character Load Failed" << endl;
}
humanSkeleton->createHumanNode();
humanSkeleton->drawHumanMesh(m_shader_loader->GetProgramID());
humanSkeleton->createArmNode();
humanSkeleton->drawArmMesh(m_shader_loader->GetProgramID());
createGate();
plane = new Cylinder(100, 50, 50, glm::vec4(0.2, 0.6, 0.3, 1.0), glm::vec4(0.2, 0.6, 0.3, 1.0), 2);
plane->generateObjectBuffer(m_shader_loader->GetProgramID());
stag[0] = new Cylinder(3, 0.5, 0.5, glm::vec4(0.2, 0.6, 0.3, 1.0), glm::vec4(0.2, 0.6, 0.3, 1.0), 2);
stag[0]->generateObjectBuffer(m_shader_loader->GetProgramID());
stag[1] = new Cylinder(2, 1, 0, glm::vec4(0.2, 0.6, 0.3, 1.0), glm::vec4(0.2, 0.6, 0.3, 1.0), 2);
stag[1]->generateObjectBuffer(m_shader_loader->GetProgramID());
do{
m_setup->preDraw();
//glUseProgram(m_shader->GetProgramID());
glUseProgram(m_shader_loader->GetProgramID());
armSkeleton->createArmNode();
armSkeleton->drawArmMesh(m_shader_loader->GetProgramID());
m_camera->computeMatricesFromInputs();
//GLuint modelLoc = glGetUniformLocation(m_shader->GetProgramID(), "model");
//GLuint viewLoc = glGetUniformLocation(m_shader->GetProgramID(), "view");
//GLuint projLoc = glGetUniformLocation(m_shader->GetProgramID(), "projection");
GLuint modelLoaderLoc = glGetUniformLocation(m_shader_loader->GetProgramID(), "model");
GLuint viewLoaderLoc = glGetUniformLocation(m_shader_loader->GetProgramID(), "view");
GLuint projLoaderLoc = glGetUniformLocation(m_shader_loader->GetProgramID(), "projection");
/*
vector<Matrix4f> Transforms;
glm::mat4 animationMan;
if (animationState)
{
bool tm = false;
float RunningTime = GetRunningTime();
m_mesh->BoneTransform(RunningTime,Transforms);
for (GLuint i = 0 ; i < Transforms.size() ; i++)
{
m_effect->SetBoneTransform(i, Transforms[i]);
if (i+1 == Transforms.size() )
{
tm = true;
}
}
animationMan = glm::translate(animationMan,glm::vec3(50,0,20));
animationMan = glm::rotate(convertAssimpMatrix(m_mesh->m_GlobalInverseTransform), 180.0f, glm::vec3(0,1,0));
animationMan = glm::scale(animationMan,glm::vec3(0.05f,0.05f,0.05f));
m_mesh->Update(modelLoaderLoc,animationMan);
m_mesh->Render();
if (tm)
{
animationState = false;
}
}
else
{
animationMan = glm::translate(animationMan,glm::vec3(50,0,20));
animationMan = glm::rotate(convertAssimpMatrix(m_mesh->m_GlobalInverseTransform),180.0f, glm::vec3(0,1,0));
animationMan = glm::scale(animationMan,glm::vec3(0.05f,0.05f,0.05f));
m_mesh->Update(modelLoaderLoc,animationMan);
m_mesh->Render();
}
*/
glm::mat4 animationMat;
vector<Matrix4f> Transforms;
if (thirdCamera_2)
{
if(glfwGetKey(m_setup->getWindow(), GLFW_KEY_W) == GLFW_PRESS)
{
targetPos.z -=0.1;
animationMat = glm::translate(animationMat,targetPos);
animationMat = glm::rotate(animationMat,180.0f, glm::vec3(0,1,0));
animationMat = glm::scale(animationMat,glm::vec3(0.05f,0.05f,0.05f));
m_mesh->Update(modelLoaderLoc,animationMat);
m_mesh->Render();
}
if(glfwGetKey(m_setup->getWindow(), GLFW_KEY_S) == GLFW_PRESS)
{
targetPos.z +=0.1;
animationMat = glm::translate(animationMat,targetPos);
animationMat = glm::rotate(animationMat,180.0f, glm::vec3(0,1,0));
animationMat = glm::scale(animationMat,glm::vec3(0.05f,0.05f,0.05f));
m_mesh->Update(modelLoaderLoc,animationMat);
m_mesh->Render();
}
if(glfwGetKey(m_setup->getWindow(), GLFW_KEY_A) == GLFW_PRESS)
{
targetPos.x -=0.1;
animationMat = glm::translate(animationMat,targetPos);
animationMat = glm::rotate(animationMat,180.0f, glm::vec3(0,1,0));
animationMat = glm::scale(animationMat,glm::vec3(0.05f,0.05f,0.05f));
m_mesh->Update(modelLoaderLoc,animationMat);
m_mesh->Render();
}
if(glfwGetKey(m_setup->getWindow(), GLFW_KEY_D) == GLFW_PRESS)
{
targetPos.x +=0.1;
animationMat = glm::translate(animationMat,targetPos);
animationMat = glm::rotate(animationMat,180.0f, glm::vec3(0,1,0));
animationMat = glm::scale(animationMat,glm::vec3(0.05f,0.05f,0.05f));
m_mesh->Update(modelLoaderLoc,animationMat);
m_mesh->Render();
}
}
if (humanSkeleton->hAnimation)
{
float RunningTime = this->GetRunningTime();
m_mesh->BoneTransform(RunningTime,Transforms);
for (GLuint i = 0 ; i < Transforms.size() ; i++)
{
m_effect->SetBoneTransform(i, Transforms[i]);
}
conterAni += 0.01f;
if (conterAni > 0.75f)
{
humanSkeleton->hAnimation = false;
conterAni = 0.0f;
}
}
else
{
m_mesh->BoneTransform(0,Transforms);
for (GLuint i = 0 ; i < Transforms.size() ; i++)
{
m_effect->SetBoneTransform(i, Transforms[i]);
}
}
animationMat = glm::translate(animationMat,targetPos);
animationMat = glm::rotate(animationMat,180.0f, glm::vec3(0,1,0));
animationMat = glm::scale(animationMat,glm::vec3(0.05f,0.05f,0.05f));
m_mesh->Update(modelLoaderLoc,animationMat);
m_mesh->Render();
humanSkeleton->hModelMat = animationMat;
//floor
glm::mat4 floors = glm::translate(floors,glm::vec3(0,0,-50));
floors = glm::rotate(glm::mat4(1), 90.0f, glm::vec3(-1,0,0));
floors = glm::scale(floors,glm::vec3(100.0f,100.0f,100.0f));
floor_mesh->Update(modelLoaderLoc,floors);
floor_mesh->Render();
//football
glm::mat4 mans = glm::translate(glm::mat4(1),glm::vec3(0,-1000,0));
mans = glm::scale(mans,glm::vec3(0.01f,0.01f,0.01f));
football_mesh->Update(modelLoaderLoc,mans);
football_mesh->Render();
timeKeyControl();
if (cameraPath)
{
camTime+=0.01f;
if(camTime >= 3)
{
camTime = 0;
cameraPath = false;
}
pathPos = humanSkeleton->interpolateCubic(camTime,glm::vec3(-100,50,-100),glm::vec3(100,50,-100),
glm::vec3(100,50,100),glm::vec3(-100,50,100));
m_camera->cameraUpdate(pathPos, glm::vec3(0,20,0));
}
m_camera->handleMVP(modelLoaderLoc, viewLoaderLoc, projLoaderLoc);
drawGate();
staging();
humanSkeleton->keyControl(m_shader_loader->GetProgramID());
humanSkeleton->updateBallPos(m_shader_loader->GetProgramID());
humanSkeleton->calculateInverseKinematics();
humanSkeleton->updateStar(m_shader_loader->GetProgramID());
humanSkeleton->calcGlobalTransformation();
humanSkeleton->updateHumanMesh(m_shader_loader->GetProgramID());
humanSkeleton->updateArmMesh(m_shader_loader->GetProgramID());
// armSkeleton->updateArmTarget(m_shader->GetProgramID());
// armSkeleton->calculateInverseKinematics();
humanSkeleton->updateArmMesh(m_shader_loader->GetProgramID());
// glUseProgram(m_shader->GetProgramID());
// glBindVertexArray(vao);
// glDrawArrays(GL_TRIANGLES, 0, point_count);
// Swap buffers
glfwSwapBuffers(m_setup->getWindow());
glfwPollEvents();
} // Check if the ESC key was pressed or the window was closed
while( glfwGetKey(m_setup->getWindow(), GLFW_KEY_ESCAPE ) != GLFW_PRESS &&
glfwWindowShouldClose(m_setup->getWindow()) == 0 );
}
void Lab3Model::initShaders()
{
std::string vertexShaderSourceCode,fragmentShaderSourceCode;
m_shader->readShaderFile("skinning.vs",vertexShaderSourceCode);
m_shader->readShaderFile("diffuse.ps",fragmentShaderSourceCode);
GLuint vertexShaderID = m_shader->makeShader(vertexShaderSourceCode.c_str(), GL_VERTEX_SHADER);
GLuint fragmentShaderID = m_shader->makeShader(fragmentShaderSourceCode.c_str(), GL_FRAGMENT_SHADER);
m_shader->makeShaderProgram(vertexShaderID,fragmentShaderID);
printf("vertexShaderID is %d\n",vertexShaderID);
printf("fragmentShaderID is %d\n",fragmentShaderID);
printf("shaderProgramID is %d\n",m_shader->GetProgramID());
}
glm::mat4 Lab3Model::convertAssimpMatrix (Matrix4f m)
{
glm::mat4 to;
to[0][0] = m.m[0][0]; to[0][1] = m.m[1][0]; to[0][2] = m.m[2][0]; to[0][3] = m.m[3][0];
to[1][0] = m.m[0][1]; to[1][1] = m.m[1][1]; to[1][2] = m.m[2][1]; to[1][3] = m.m[3][1];
to[2][0] = m.m[0][2]; to[2][1] = m.m[1][2]; to[2][2] = m.m[2][2]; to[2][3] = m.m[3][2];
to[3][0] = m.m[0][3]; to[3][1] = m.m[1][3]; to[3][2] = m.m[2][3]; to[3][3] = m.m[3][3];
return to;
}
void Lab3Model::drawGate()
{
glm::mat4 gateMat40 = glm::translate(glm::rotate(glm::mat4(1), 90.0f, glm::vec3(0,0,1)),glm::vec3(10,0,-100));
//gateMat40 = glm::rotate(glm::mat4(1), 90.0f, glm::vec3(0,0,1));
gate[0]->update(gateMat40, m_shader_loader->GetProgramID());
gate[0]->draw();
glm::mat4 gateMat41 = glm::translate(glm::rotate(glm::mat4(1), -90.0f, glm::vec3(0,0,1)),glm::vec3(-10,0,-100));
//gateMat40 = glm::rotate(glm::mat4(1), 90.0f, glm::vec3(0,0,1));
gate[1]->update(gateMat41, m_shader_loader->GetProgramID());
gate[1]->draw();
glm::mat4 gateMat42 = glm::translate(glm::mat4(1),glm::vec3(-15,0,-100));
gate[2]->update(gateMat42, m_shader_loader->GetProgramID());
gate[2]->draw();
glm::mat4 gateMat43 = glm::translate(glm::mat4(1),glm::vec3(15,0,-100));
gate[3]->update(gateMat43, m_shader_loader->GetProgramID());
gate[3]->draw();
glm::mat4 gateMat44 = glm::translate(glm::mat4(1),glm::vec3(-15,10,-100));
glm::mat4 offset0 = gateMat44;
gateMat44 = glm::rotate(offset0, -90.0f, glm::vec3(1,0,0));
gate[4]->update(gateMat44, m_shader_loader->GetProgramID());
gate[4]->draw();
glm::mat4 gateMat45 = glm::translate(glm::mat4(1),glm::vec3(15,10,-100));
glm::mat4 offset1 = gateMat45;
gateMat45 = glm::rotate(offset1, -90.0f, glm::vec3(1,0,0));
gate[5]->update(gateMat45, m_shader_loader->GetProgramID());
gate[5]->draw();
glm::mat4 gateMat46 = glm::translate(glm::mat4(1),glm::vec3(15,0,-110));
glm::mat4 offset2 = gateMat46;
gateMat46 = glm::rotate(offset2, 27.0f, glm::vec3(1,0,0));
gate[6]->update(gateMat46, m_shader_loader->GetProgramID());
gate[6]->draw();
glm::mat4 gateMat47 = glm::translate(glm::mat4(1),glm::vec3(-15,0,-110));
glm::mat4 offset3 = gateMat47;
gateMat47 = glm::rotate(offset3, 27.0f, glm::vec3(1,0,0));
gate[7]->update(gateMat47, m_shader_loader->GetProgramID());
gate[7]->draw();
}
void Lab3Model::createGate()
{
gate[0] = new Cylinder(15, 0.4, 0.4, glm::vec4(1.0, 0.1, 0.1, 1.0), glm::vec4(0.1, 0.1, 1.0, 1.0), 16);
gate[0]->generateObjectBuffer(m_shader_loader->GetProgramID());
gate[1] = new Cylinder(15, 0.4, 0.4, glm::vec4(1.0, 0.1, 0.1, 1.0), glm::vec4(0.1, 0.1, 1.0, 1.0), 16);
gate[1]->generateObjectBuffer(m_shader_loader->GetProgramID());
gate[2] = new Cylinder(10, 0.4, 0.4, glm::vec4(1.0, 0.1, 0.1, 1.0), glm::vec4(0.1, 0.1, 1.0, 1.0), 16);
gate[2]->generateObjectBuffer(m_shader_loader->GetProgramID());
gate[3] = new Cylinder(10, 0.4, 0.4, glm::vec4(1.0, 0.1, 0.1, 1.0), glm::vec4(0.1, 0.1, 1.0, 1.0), 16);
gate[3]->generateObjectBuffer(m_shader_loader->GetProgramID());
gate[4] = new Cylinder(5, 0.4, 0.4, glm::vec4(1.0, 0.1, 0.1, 1.0), glm::vec4(0.1, 0.1, 1.0, 1.0), 16);
gate[4]->generateObjectBuffer(m_shader_loader->GetProgramID());
gate[5] = new Cylinder(5, 0.4, 0.4, glm::vec4(1.0, 0.1, 0.1, 1.0), glm::vec4(0.1, 0.1, 1.0, 1.0), 16);
gate[5]->generateObjectBuffer(m_shader_loader->GetProgramID());
gate[6] = new Cylinder(11.5, 0.4, 0.4, glm::vec4(1.0, 0.1, 0.1, 1.0), glm::vec4(0.1, 0.1, 1.0, 1.0), 16);
gate[6]->generateObjectBuffer(m_shader_loader->GetProgramID());
gate[7] = new Cylinder(11.5, 0.4, 0.4, glm::vec4(1.0, 0.1, 0.1, 1.0), glm::vec4(0.1, 0.1, 1.0, 1.0), 16);
gate[7]->generateObjectBuffer(m_shader_loader->GetProgramID());
}
void Lab3Model::timeKeyControl()
{
if (glfwGetKey( m_setup->getWindow(), GLFW_KEY_R ) == GLFW_PRESS){
thirdCamera = true;
thirdCamera_2 = false;
humanSkeleton->cModel = true;
humanSkeleton->hModel = false;
//humanSkeleton->cball = true;
//humanSkeleton->hball = false;
}
if (glfwGetKey( m_setup->getWindow(), GLFW_KEY_V ) == GLFW_PRESS){
thirdCamera_2 = true;
thirdCamera = false;
humanSkeleton->hModel = true;
humanSkeleton->cModel = false;
//humanSkeleton->cball = false;
//humanSkeleton->hball = true;
}
if (glfwGetKey( m_setup->getWindow(), GLFW_KEY_G ) == GLFW_PRESS){
thirdCamera_2 = false;
thirdCamera = false;
followBallCamera = true;
}
if (glfwGetKey( m_setup->getWindow(), GLFW_KEY_V ) == GLFW_PRESS){
thirdCamera_2 = true;
thirdCamera = false;
humanSkeleton->hModel = true;
humanSkeleton->cModel = false;
// humanSkeleton->cball = false;
// humanSkeleton->hball = true;
}
if (glfwGetKey( m_setup->getWindow(), GLFW_KEY_F ) == GLFW_PRESS)
{
thirdCamera = false;
thirdCamera_2 = false;
followBallCamera = false;
//m_camera->setPosition(humanSkeleton->slerp(m_camera->position,glm::vec3(0,10,-20),0.1));
}
if (thirdCamera)
{
thirdCamera_2 = false;
followBallCamera = false;
// Move forward
if (glfwGetKey( m_setup->getWindow(), GLFW_KEY_W ) == GLFW_PRESS){
if (!humanSkeleton->kick)
{
humanSkeleton->humanNode[0]->localTransformation[3][2] -= 0.05;
humanSkeleton->walking = true;
}
}
// Move backward
if (glfwGetKey( m_setup->getWindow(), GLFW_KEY_S ) == GLFW_PRESS){
if (!humanSkeleton->kick)
{
humanSkeleton->humanNode[0]->localTransformation[3][2] += 0.05;
humanSkeleton->walking = true;
}
}
// Strafe right
if (glfwGetKey( m_setup->getWindow(), GLFW_KEY_D ) == GLFW_PRESS){
if (!humanSkeleton->kick)
{
// charRot += 0.5f;
// glm::mat4 rots = glm::rotate(humanSkeleton->humanNode[0]->offset, charRot, m_camera->up);
// humanSkeleton->humanNode[0]->localTransformation = rots;
// m_camera->ViewMatrix = rots;
humanSkeleton->humanNode[0]->localTransformation[3][0] += 0.05;
humanSkeleton->walking = true;
}
}
// Strafe left
if (glfwGetKey( m_setup->getWindow(), GLFW_KEY_A ) == GLFW_PRESS){
if (!humanSkeleton->kick)
{
// charRot -= 0.5f;
// glm::mat4 rots = glm::rotate(humanSkeleton->humanNode[0]->offset, charRot, m_camera->up);
// humanSkeleton->humanNode[0]->localTransformation = rots;
// m_camera->ViewMatrix = rots;
humanSkeleton->humanNode[0]->localTransformation[3][0] -= 0.05;
humanSkeleton->walking = true;
}
}
//humanSkeleton->walking = false;
//humanSkeleton->humanNode[0]->localTransformation = glm::lookAt(humanSkeleton->humanNode[0]->pos,humanSkeleton->humanNode[0]->pos+m_camera->direction,m_camera->up);
//m_camera->cameraUpdate(glm::vec3(humanSkeleton->humanNode[0]->pos.x, humanSkeleton->humanNode[0]->pos.y+3.0f, humanSkeleton->humanNode[0]->pos.z + 15.0f), humanSkeleton->humanNode[0]->pos);
m_camera->cameraUpdate(glm::vec3(humanSkeleton->humanNode[0]->pos.x, humanSkeleton->humanNode[0]->pos.y+3.0f, humanSkeleton->humanNode[0]->pos.z + 15.0f),
glm::vec3(humanSkeleton->humanNode[0]->globalTransformation[3][0], humanSkeleton->humanNode[0]->globalTransformation[3][1], humanSkeleton->humanNode[0]->globalTransformation[3][2]));
}
if (thirdCamera_2)
{
thirdCamera = false;
followBallCamera = false;
glm::mat4 temp = humanSkeleton->hModelMat;
m_camera->cameraUpdate(glm::vec3(temp[3][0]-3, temp[3][1]+10.0f, temp[3][2]+18.0f), glm::vec3(temp[3][0], temp[3][1]+6.0f, temp[3][2]));
}
if (followBallCamera)
{
thirdCamera = false;
thirdCamera_2 = false;
//humanSkeleton->humanNode[0]->localTransformation = glm::lookAt(humanSkeleton->humanNode[0]->pos,humanSkeleton->humanNode[0]->pos+m_camera->direction,m_camera->up);
m_camera->cameraUpdate(glm::vec3(humanSkeleton->armTargetPos.x, humanSkeleton->armTargetPos.y+3.0f, humanSkeleton->armTargetPos.z + 15.0f), humanSkeleton->armTargetPos);
}
}
void Lab3Model::initLoaderShaders()
{
std::string vertexShaderSourceCode,fragmentShaderSourceCode;
m_shader_loader->readShaderFile("skinning.vs",vertexShaderSourceCode);
m_shader_loader->readShaderFile("skinning.fs",fragmentShaderSourceCode);
GLuint vertexShaderID = m_shader_loader->makeShader(vertexShaderSourceCode.c_str(), GL_VERTEX_SHADER);
GLuint fragmentShaderID = m_shader_loader->makeShader(fragmentShaderSourceCode.c_str(), GL_FRAGMENT_SHADER);
m_shader_loader->makeShaderProgram(vertexShaderID,fragmentShaderID);
printf("vertexShaderID is %d\n",vertexShaderID);
printf("fragmentShaderID is %d\n",fragmentShaderID);
printf("shaderProgramID is %d\n",m_shader_loader->GetProgramID());
}
float Lab3Model::GetRunningTime()
{
return (float)((double) GetCurrentTimeMillis() - startTime) / 1000.0f;
}
void Lab3Model::staging()
{
if(!timeFlag){
deltaTime += 0.001f;
if (deltaTime > 10)
{
timeFlag = true;
}
}
if (timeFlag){
deltaTime -= 0.001f;
if (deltaTime < 0)
{
timeFlag = false;
}
}
if (thirdCamera)
{
glm::mat4 stag1 = glm::translate(glm::mat4(1),glm::vec3(humanSkeleton->cModelPos.x,humanSkeleton->cModelPos.y+11+deltaTime,humanSkeleton->cModelPos.z+3));
stag[0]->update(stag1, m_shader_loader->GetProgramID());
stag[0]->draw();
glm::mat4 stag2 = glm::translate(glm::mat4(1),glm::vec3(humanSkeleton->cModelPos.x,humanSkeleton->cModelPos.y+9+deltaTime,humanSkeleton->cModelPos.z+3));
stag[1]->update(stag2, m_shader_loader->GetProgramID());
stag[1]->draw();
}
if (thirdCamera_2)
{
glm::mat4 stag1 = glm::translate(glm::mat4(1),glm::vec3(humanSkeleton->hModelPos.x,humanSkeleton->hModelPos.y+12+deltaTime,humanSkeleton->hModelPos.z));
stag[0]->update(stag1, m_shader_loader->GetProgramID());
stag[0]->draw();
glm::mat4 stag2 = glm::translate(glm::mat4(1),glm::vec3(humanSkeleton->hModelPos.x,humanSkeleton->hModelPos.y+10+deltaTime,humanSkeleton->hModelPos.z));
stag[1]->update(stag2, m_shader_loader->GetProgramID());
stag[1]->draw();
}
} | [
"[email protected]"
] | |
f500869db2154eb2fbdb320b93c4b20e780c8450 | d16347eb621e1688418ff3e2dfb30a73e99c7a1a | /origin_question/ini_parser/ini_parser.cc | aea97f34042a208519682ec18eab299cd927e7e4 | [] | no_license | YinWenForInterview/360Search | ac9964243fb70ec4ccbd37e5c80ba5fe1fcc938c | bedc51f974da5982ea448fe18700559b40a3f89f | refs/heads/master | 2021-01-20T04:30:00.830418 | 2015-09-05T19:17:26 | 2015-09-05T19:17:26 | 41,811,523 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 43 | cc | #include "ini_parser.h"
namespace qh
{
} | [
"[email protected]"
] | |
fdedb294efc7fd3130399a87aa7abe100371b351 | 6be45665a98a5dd1d78ea56d6d67068d819f9127 | /CH02_Polygons/Polygons_6_3.cpp | 5bbc3329b38a313e3f2016e1bea286066ced05b7 | [] | no_license | YeeYoungHan/Math-and-Physics-in-Moving-3D-Games | ea167abb734a76eb4e705173980fcb076efbd061 | ebe314859e45d8eaa73edbf69158a6214e3e34ee | refs/heads/master | 2021-06-18T10:11:26.199195 | 2021-05-18T04:44:06 | 2021-05-18T04:44:06 | 207,729,806 | 1 | 0 | null | null | null | null | UHC | C++ | false | false | 21,127 | cpp | //------------------------------------------------------------
// Polygons_6_3.cpp
// 정점 인덱스로 구 그리기
//
//------------------------------------------------------------
#include <D3DX11.h>
#include <D3Dcompiler.h>
#include <xnamath.h>
#define VIEW_WIDTH 800 // 화면너비
#define VIEW_HEIGHT 600 // 화면높이
#define PI 3.1415927f // 원주율
#define ROT_SPEED ( PI / 100.0f ) // 회전속도
#define R 2.0f // 도형 크기
#define CORNER_NUM 20 // 각의 수
// 정점 구조체
struct CUSTOMVERTEX
{
XMFLOAT4 v4Pos;
XMFLOAT4 v4Color;
};
int DrawIndexed3DPolygons( CUSTOMVERTEX *pVertices, int nVertexNum, WORD *pIndices, int nPolygonNum );
// 인덱스된 3D폴리곤 그리기 // 3D 폴리곤 그리기
//월드 행렬 생성
XMMATRIX CreateWorldMatrix( void )
{
float fAngleY; // y축 중심 회전각
static float fAngleX = 0.0f; // x축 중심 회전각
XMMATRIX matRot_Y; // y축 중심 회전행렬
XMMATRIX matRot_X; // x축 중심 회전행렬
// 강제 회전
fAngleY = 2.0f * PI * (float)( timeGetTime() % 2000 ) / 2000.0f;
// 키입력으로 회전
if( GetAsyncKeyState( VK_UP ) )
{
fAngleX += ROT_SPEED;
}
if( GetAsyncKeyState( VK_DOWN ) )
{
fAngleX -= ROT_SPEED;
}
// 행렬 작성
matRot_Y = XMMatrixRotationY( fAngleY );
matRot_X = XMMatrixRotationX( fAngleX );
return matRot_Y * matRot_X; // 회전의 합성
}
// 이미지 그리기
// 정점 인덱스를 사용하는 경우 정점을 놓는 부분은 단순해진다
// 단순히 특정 위도, 경도 부분(위도와 경도의 교점부분)에 정점을 놓아가면 된다
// 폴리곤 형성의 복잡함은 정점 인덱스 생성 부분으로 옮긴다
int DrawChangingPictures( void )
{
int i, j;
CUSTOMVERTEX Vertices[CORNER_NUM * ( CORNER_NUM / 2 + 1 )]; // 정점 데이터
WORD wIndices[CORNER_NUM * CORNER_NUM / 2 * 2 * 3]; // 인덱스 데이터
float fTheta;
float fPhi;
float fAngleDelta;
int nIndex; // 데이터의 인덱스
int nIndexY; // y방향 인덱스
// 정점 데이터 작성
fAngleDelta = 2.0f * PI / CORNER_NUM;
nIndex = 0;
fTheta = 0.0f;
for( i = 0; i < CORNER_NUM / 2 + 1; i++ )
{
fPhi = 0.0f;
for( j = 0; j < CORNER_NUM; j++ )
{
Vertices[nIndex].v4Pos = XMFLOAT4( R * sinf( fTheta ) * cosf( fPhi ), R * cosf( fTheta ), R * sinf( fTheta ) * sinf( fPhi ), 1.0f );
Vertices[nIndex].v4Color = XMFLOAT4( 0.0f, (float)( i & 1 ), (float)( ( i + 1 ) & 1 ), 1.0f );
nIndex++;
fPhi += fAngleDelta;
}
fTheta += fAngleDelta;
}
// 인덱스 데이터 작성
nIndex = 0;
for( i = 0; i < CORNER_NUM / 2; i++ )
{
nIndexY = i * CORNER_NUM;
for( j = 0; j < CORNER_NUM; j++ )
{
wIndices[nIndex] = nIndexY + j;
wIndices[nIndex + 1] = nIndexY + CORNER_NUM + j;
wIndices[nIndex + 2] = nIndexY + ( ( j + 1 ) % CORNER_NUM );
nIndex += 3;
wIndices[nIndex] = nIndexY + ( ( j + 1 ) % CORNER_NUM );
wIndices[nIndex + 1] = nIndexY + CORNER_NUM + j;
wIndices[nIndex + 2] = nIndexY + CORNER_NUM + ( ( j + 1 ) % CORNER_NUM );
nIndex += 3;
}
}
// 정점 인덱스를 써서 그린다
DrawIndexed3DPolygons( Vertices, CORNER_NUM * ( CORNER_NUM / 2 + 1 ), wIndices, CORNER_NUM * CORNER_NUM / 2 * 2 * 3 );
return 0;
}
//------------------------------------------------------------
// 아래는 DirectX로 표시하는 프로그램
#include <stdio.h>
#include <tchar.h> // Unicode 멀티바이트 문자 관계
#include <windows.h>
#define MAX_BUFFER_VERTEX 10000 // 최대 버퍼 정점 수
#define MAX_BUFFER_INDEX 20000 // 최대 버퍼 인덱스 수
// 링크 라이브러리
#pragma comment( lib, "d3d11.lib" ) // D3D11 라이브러리
#pragma comment( lib, "d3dx11.lib" )
#pragma comment( lib, "winmm.lib" )
// 세이프 릴리스 매크로
#ifndef SAFE_RELEASE
#define SAFE_RELEASE( p ) \
{ \
if( p ) \
{ \
( p )->Release(); \
( p ) = NULL; \
} \
}
#endif
// 셰이더 상수 구조체
struct CBNeverChanges
{
XMMATRIX mView;
};
// 글로벌 변수
UINT g_nClientWidth; // 그리는 영역의 너비
UINT g_nClientHeight; // 그리는 영역의 높이
HWND g_hWnd; // 윈도우 핸들
ID3D11Device *g_pd3dDevice; // 디바이스
IDXGISwapChain *g_pSwapChain; // DXGI 스왑체인
ID3D11DeviceContext *g_pImmediateContext; // 디바이스 컨텍스트
ID3D11RasterizerState *g_pRS; // 래스터라이저
ID3D11RenderTargetView *g_pRTV; // 렌더링 타깃
ID3D11Texture2D *g_pDepthStencil = NULL; // Z버퍼
ID3D11DepthStencilView *g_pDepthStencilView = NULL; // Z버퍼의 뷰
D3D_FEATURE_LEVEL g_FeatureLevel; // 피쳐 레벨
ID3D11Buffer *g_pVertexBuffer;
ID3D11Buffer *g_pIndexBuffer;
ID3D11BlendState *g_pbsAlphaBlend;
ID3D11VertexShader *g_pVertexShader;
ID3D11PixelShader *g_pPixelShader;
ID3D11InputLayout *g_pInputLayout;
ID3D11SamplerState *g_pSamplerState;
ID3D11Buffer *g_pCBNeverChanges = NULL;
// 그리기 정점 버퍼
CUSTOMVERTEX g_cvVertices[MAX_BUFFER_VERTEX];
int g_nVertexNum = 0;
WORD g_wIndices[MAX_BUFFER_INDEX];
int g_nIndexNum = 0;
ID3D11ShaderResourceView *g_pNowTexture = NULL;
// Direct3D 초기화
HRESULT InitD3D( void )
{
HRESULT hr = S_OK;
D3D_FEATURE_LEVEL FeatureLevelsRequested[6] = { D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0,
D3D_FEATURE_LEVEL_9_3, D3D_FEATURE_LEVEL_9_2, D3D_FEATURE_LEVEL_9_1 };
UINT numLevelsRequested = 6;
D3D_FEATURE_LEVEL FeatureLevelsSupported;
// 디바이스 생성
hr = D3D11CreateDevice( NULL, D3D_DRIVER_TYPE_HARDWARE, NULL, 0, FeatureLevelsRequested, numLevelsRequested, D3D11_SDK_VERSION, &g_pd3dDevice, &FeatureLevelsSupported,
&g_pImmediateContext );
if( FAILED( hr ) )
{
return hr;
}
// 패토리 취득
IDXGIDevice *pDXGIDevice;
hr = g_pd3dDevice->QueryInterface( __uuidof( IDXGIDevice ), (void **)&pDXGIDevice );
IDXGIAdapter *pDXGIAdapter;
hr = pDXGIDevice->GetParent( __uuidof( IDXGIAdapter ), (void **)&pDXGIAdapter );
IDXGIFactory *pIDXGIFactory;
pDXGIAdapter->GetParent( __uuidof( IDXGIFactory ), (void **)&pIDXGIFactory );
// 스왑체인 생성
DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory( &sd, sizeof( sd ) );
sd.BufferCount = 1;
sd.BufferDesc.Width = g_nClientWidth;
sd.BufferDesc.Height = g_nClientHeight;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = g_hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
hr = pIDXGIFactory->CreateSwapChain( g_pd3dDevice, &sd, &g_pSwapChain );
pDXGIDevice->Release();
pDXGIAdapter->Release();
pIDXGIFactory->Release();
if( FAILED( hr ) )
{
return hr;
}
// 렌데링 타깃 생성
ID3D11Texture2D *pBackBuffer = NULL;
D3D11_TEXTURE2D_DESC BackBufferSurfaceDesc;
hr = g_pSwapChain->GetBuffer( 0, __uuidof( ID3D11Texture2D ), (LPVOID *)&pBackBuffer );
if( FAILED( hr ) )
{
MessageBox( NULL, _T( "Can't get backbuffer." ), _T( "Error" ), MB_OK );
return hr;
}
pBackBuffer->GetDesc( &BackBufferSurfaceDesc );
hr = g_pd3dDevice->CreateRenderTargetView( pBackBuffer, NULL, &g_pRTV );
SAFE_RELEASE( pBackBuffer );
if( FAILED( hr ) )
{
MessageBox( NULL, _T( "Can't create render target view." ), _T( "Error" ), MB_OK );
return hr;
}
// *** Create depth stencil texture ***
D3D11_TEXTURE2D_DESC descDepth;
RECT rc;
GetClientRect( g_hWnd, &rc );
ZeroMemory( &descDepth, sizeof( descDepth ) );
descDepth.Width = rc.right - rc.left;
descDepth.Height = rc.bottom - rc.top;
descDepth.MipLevels = 1;
descDepth.ArraySize = 1;
descDepth.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
descDepth.SampleDesc.Count = 1;
descDepth.SampleDesc.Quality = 0;
descDepth.Usage = D3D11_USAGE_DEFAULT;
descDepth.BindFlags = D3D11_BIND_DEPTH_STENCIL;
descDepth.CPUAccessFlags = 0;
descDepth.MiscFlags = 0;
hr = g_pd3dDevice->CreateTexture2D( &descDepth, NULL, &g_pDepthStencil );
if( FAILED( hr ) )
return hr;
// *** Create the depth stencil view ***
D3D11_DEPTH_STENCIL_VIEW_DESC descDSV;
ZeroMemory( &descDSV, sizeof( descDSV ) );
descDSV.Format = descDepth.Format;
descDSV.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D;
descDSV.Texture2D.MipSlice = 0;
hr = g_pd3dDevice->CreateDepthStencilView( g_pDepthStencil, &descDSV, &g_pDepthStencilView );
if( FAILED( hr ) )
return hr;
// *** 렌더링 타깃 설정 ***
g_pImmediateContext->OMSetRenderTargets( 1, &g_pRTV, g_pDepthStencilView );
// g_pImmediateContext->OMSetRenderTargets( 1, &g_pRTV, NULL );
// 래스터라이저 설정
D3D11_RASTERIZER_DESC drd;
ZeroMemory( &drd, sizeof( drd ) );
drd.FillMode = D3D11_FILL_SOLID;
drd.CullMode = D3D11_CULL_NONE;
drd.FrontCounterClockwise = FALSE;
drd.DepthClipEnable = TRUE;
hr = g_pd3dDevice->CreateRasterizerState( &drd, &g_pRS );
if( FAILED( hr ) )
{
MessageBox( NULL, _T( "Can't create rasterizer state." ), _T( "Error" ), MB_OK );
return hr;
}
g_pImmediateContext->RSSetState( g_pRS );
// 뷰포트 설정
D3D11_VIEWPORT vp;
vp.Width = (FLOAT)g_nClientWidth;
vp.Height = (FLOAT)g_nClientHeight;
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = 0.0f;
vp.TopLeftY = 0.0f;
g_pImmediateContext->RSSetViewports( 1, &vp );
return S_OK;
}
// 프로그래머블 셰이더 작성
HRESULT MakeShaders( void )
{
HRESULT hr;
ID3DBlob *pVertexShaderBuffer = NULL;
ID3DBlob *pPixelShaderBuffer = NULL;
ID3DBlob *pError = NULL;
DWORD dwShaderFlags = 0;
#ifdef _DEBUG
dwShaderFlags |= D3DCOMPILE_DEBUG;
#endif
// 컴파일
hr = D3DX11CompileFromFile( _T( "Basic_3D_Color.fx" ), NULL, NULL, "VS", "vs_4_0_level_9_1", dwShaderFlags, 0, NULL, &pVertexShaderBuffer, &pError, NULL );
if( FAILED( hr ) )
{
MessageBox( NULL, _T( "Can't open Basic_3D_Color.fx" ), _T( "Error" ), MB_OK );
SAFE_RELEASE( pError );
return hr;
}
hr = D3DX11CompileFromFile( _T( "Basic_3D_Color.fx" ), NULL, NULL, "PS", "ps_4_0_level_9_1", dwShaderFlags, 0, NULL, &pPixelShaderBuffer, &pError, NULL );
if( FAILED( hr ) )
{
SAFE_RELEASE( pVertexShaderBuffer );
SAFE_RELEASE( pError );
return hr;
}
SAFE_RELEASE( pError );
// VertexShader 생성
hr = g_pd3dDevice->CreateVertexShader( pVertexShaderBuffer->GetBufferPointer(), pVertexShaderBuffer->GetBufferSize(), NULL, &g_pVertexShader );
if( FAILED( hr ) )
{
SAFE_RELEASE( pVertexShaderBuffer );
SAFE_RELEASE( pPixelShaderBuffer );
return hr;
}
// PixelShader 생성
hr = g_pd3dDevice->CreatePixelShader( pPixelShaderBuffer->GetBufferPointer(), pPixelShaderBuffer->GetBufferSize(), NULL, &g_pPixelShader );
if( FAILED( hr ) )
{
SAFE_RELEASE( pVertexShaderBuffer );
SAFE_RELEASE( pPixelShaderBuffer );
return hr;
}
// 입력버퍼의 입력형식
D3D11_INPUT_ELEMENT_DESC layout[] = {
{ "POSITION", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 },
{ "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 16, D3D11_INPUT_PER_VERTEX_DATA, 0 },
// { "TEXTURE", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 32, D3D11_INPUT_PER_VERTEX_DATA, 0 },
};
UINT numElements = ARRAYSIZE( layout );
// 입력버퍼의 입력형식 생성
hr = g_pd3dDevice->CreateInputLayout( layout, numElements, pVertexShaderBuffer->GetBufferPointer(), pVertexShaderBuffer->GetBufferSize(), &g_pInputLayout );
SAFE_RELEASE( pVertexShaderBuffer );
SAFE_RELEASE( pPixelShaderBuffer );
if( FAILED( hr ) )
{
return hr;
}
// 셰이더 상수 버퍼 생성
D3D11_BUFFER_DESC bd;
ZeroMemory( &bd, sizeof( bd ) );
bd.Usage = D3D11_USAGE_DEFAULT;
bd.ByteWidth = sizeof( CBNeverChanges );
bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER;
bd.CPUAccessFlags = 0;
hr = g_pd3dDevice->CreateBuffer( &bd, NULL, &g_pCBNeverChanges );
if( FAILED( hr ) )
return hr;
// 변환행렬
CBNeverChanges cbNeverChanges;
XMMATRIX mScreen;
mScreen = XMMatrixIdentity();
mScreen._11 = 2.0f / g_nClientWidth;
mScreen._22 = -2.0f / g_nClientHeight;
mScreen._41 = -1.0f;
mScreen._42 = 1.0f;
cbNeverChanges.mView = XMMatrixTranspose( mScreen );
g_pImmediateContext->UpdateSubresource( g_pCBNeverChanges, 0, NULL, &cbNeverChanges, 0, 0 );
return S_OK;
}
// 그리기 모드 오브젝트 초기화
int InitDrawModes( void )
{
HRESULT hr;
// 블렌드 스테이트
D3D11_BLEND_DESC BlendDesc;
BlendDesc.AlphaToCoverageEnable = FALSE;
BlendDesc.IndependentBlendEnable = FALSE;
BlendDesc.RenderTarget[0].BlendEnable = TRUE;
BlendDesc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;
BlendDesc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;
BlendDesc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;
BlendDesc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;
BlendDesc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;
BlendDesc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;
BlendDesc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
hr = g_pd3dDevice->CreateBlendState( &BlendDesc, &g_pbsAlphaBlend );
if( FAILED( hr ) )
{
return hr;
}
// 샘플러
D3D11_SAMPLER_DESC samDesc;
ZeroMemory( &samDesc, sizeof( samDesc ) );
samDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
samDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
samDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
samDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
samDesc.ComparisonFunc = D3D11_COMPARISON_ALWAYS;
samDesc.MaxLOD = D3D11_FLOAT32_MAX;
hr = g_pd3dDevice->CreateSamplerState( &samDesc, &g_pSamplerState );
if( FAILED( hr ) )
{
return hr;
}
return S_OK;
}
// 지오메트리 초기화
HRESULT InitGeometry( void )
{
HRESULT hr = S_OK;
// 정점 버퍼 생성
D3D11_BUFFER_DESC BufferDesc;
BufferDesc.Usage = D3D11_USAGE_DYNAMIC;
BufferDesc.ByteWidth = sizeof( CUSTOMVERTEX ) * MAX_BUFFER_VERTEX;
BufferDesc.BindFlags = D3D11_BIND_VERTEX_BUFFER;
BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
BufferDesc.MiscFlags = 0;
D3D11_SUBRESOURCE_DATA SubResourceData;
SubResourceData.pSysMem = g_cvVertices;
SubResourceData.SysMemPitch = 0;
SubResourceData.SysMemSlicePitch = 0;
hr = g_pd3dDevice->CreateBuffer( &BufferDesc, &SubResourceData, &g_pVertexBuffer );
if( FAILED( hr ) )
{
return hr;
}
// 인덱스 버퍼 생성
BufferDesc.Usage = D3D11_USAGE_DYNAMIC;
BufferDesc.ByteWidth = sizeof( WORD ) * MAX_BUFFER_INDEX;
BufferDesc.BindFlags = D3D11_BIND_INDEX_BUFFER;
BufferDesc.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE;
BufferDesc.MiscFlags = 0;
SubResourceData.pSysMem = g_wIndices;
hr = g_pd3dDevice->CreateBuffer( &BufferDesc, &SubResourceData, &g_pIndexBuffer );
if( FAILED( hr ) )
return hr;
return S_OK;
}
// 종료처리
int Cleanup( void )
{
SAFE_RELEASE( g_pVertexBuffer );
SAFE_RELEASE( g_pIndexBuffer );
SAFE_RELEASE( g_pSamplerState );
SAFE_RELEASE( g_pbsAlphaBlend );
SAFE_RELEASE( g_pInputLayout );
SAFE_RELEASE( g_pPixelShader );
SAFE_RELEASE( g_pVertexShader );
SAFE_RELEASE( g_pCBNeverChanges );
SAFE_RELEASE( g_pRS ); // 래스터라이저
// 스테이터스 클리어
if( g_pImmediateContext )
{
g_pImmediateContext->ClearState();
g_pImmediateContext->Flush();
}
SAFE_RELEASE( g_pRTV ); // 렌더링 타깃
SAFE_RELEASE( g_pDepthStencil ); // Z버퍼
SAFE_RELEASE( g_pDepthStencilView ); // Z버퍼의 뷰
// 스왑체인
if( g_pSwapChain != NULL )
{
g_pSwapChain->SetFullscreenState( FALSE, 0 );
}
SAFE_RELEASE( g_pSwapChain );
SAFE_RELEASE( g_pImmediateContext ); // 디바이스 컨텍스트
SAFE_RELEASE( g_pd3dDevice ); // 디바이스
return 0;
}
// 윈도우 프로시저
LRESULT WINAPI MsgProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
switch( msg )
{
case WM_DESTROY:
PostQuitMessage( 0 );
return 0;
}
return DefWindowProc( hWnd, msg, wParam, lParam );
}
// 그리기 대기행렬 플러시
int FlushDrawingPictures( void )
{
HRESULT hr;
if( g_nVertexNum > 0 )
{
D3D11_MAPPED_SUBRESOURCE mappedResource;
hr = g_pImmediateContext->Map( g_pVertexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource );
if( SUCCEEDED( hr ) )
{
CopyMemory( mappedResource.pData, &( g_cvVertices[0] ), sizeof( CUSTOMVERTEX ) * g_nVertexNum );
g_pImmediateContext->Unmap( g_pVertexBuffer, 0 );
hr = g_pImmediateContext->Map( g_pIndexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &mappedResource );
if( SUCCEEDED( hr ) )
{
CopyMemory( mappedResource.pData, &( g_wIndices[0] ), sizeof( WORD ) * g_nIndexNum );
g_pImmediateContext->Unmap( g_pIndexBuffer, 0 );
g_pImmediateContext->DrawIndexed( g_nIndexNum, 0, 0 );
}
}
}
g_nVertexNum = 0;
g_nIndexNum = 0;
return 0;
}
// 인덱스된 3D 폴리곤 그리기
int DrawIndexed3DPolygons( CUSTOMVERTEX *pVertices, int nVertexNum, WORD *pIndices, int nIndexNum )
{
int i;
CopyMemory( &g_cvVertices[0], pVertices, sizeof( CUSTOMVERTEX ) * nVertexNum );
for( i = 0; i < nIndexNum; i++ )
{
g_wIndices[g_nIndexNum + i] = *( pIndices + i ) + g_nVertexNum;
}
g_nVertexNum += nVertexNum;
g_nIndexNum += nIndexNum;
return 0;
}
// 렌더링
HRESULT Render( void )
{
// 화면 클리어
XMFLOAT4 v4Color = XMFLOAT4( 0.0f, 0.0f, 0.0f, 1.0f );
g_pImmediateContext->ClearRenderTargetView( g_pRTV, (float *)&v4Color );
// *** Z버퍼 클리어 ***
g_pImmediateContext->ClearDepthStencilView( g_pDepthStencilView, D3D11_CLEAR_DEPTH, 1.0f, 0 );
// 샘플러, 래스터라이저 설정
g_pImmediateContext->PSSetSamplers( 0, 1, &g_pSamplerState );
g_pImmediateContext->RSSetState( g_pRS );
// 그리기 설정
UINT nStrides = sizeof( CUSTOMVERTEX );
UINT nOffsets = 0;
g_pImmediateContext->IASetVertexBuffers( 0, 1, &g_pVertexBuffer, &nStrides, &nOffsets );
g_pImmediateContext->IASetIndexBuffer( g_pIndexBuffer, DXGI_FORMAT_R16_UINT, 0 );
g_pImmediateContext->IASetPrimitiveTopology( D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST );
g_pImmediateContext->IASetInputLayout( g_pInputLayout );
// 셰이더 설정
g_pImmediateContext->VSSetShader( g_pVertexShader, NULL, 0 );
g_pImmediateContext->VSSetConstantBuffers( 0, 1, &g_pCBNeverChanges );
g_pImmediateContext->PSSetShader( g_pPixelShader, NULL, 0 );
// 변환행렬
CBNeverChanges cbNeverChanges;
XMMATRIX mWorld;
XMMATRIX mView;
XMMATRIX mProjection;
mWorld = CreateWorldMatrix();
// Initialize the view matrix
XMVECTOR Eye = XMVectorSet( 0.0f, 3.0f, -5.0f, 0.0f );
XMVECTOR At = XMVectorSet( 0.0f, 0.0f, 0.0f, 0.0f );
XMVECTOR Up = XMVectorSet( 0.0f, 1.0f, 0.0f, 0.0f );
mView = XMMatrixLookAtLH( Eye, At, Up );
// Initialize the projection matrix
mProjection = XMMatrixPerspectiveFovLH( XM_PIDIV4, VIEW_WIDTH / (FLOAT)VIEW_HEIGHT, 0.01f, 100.0f );
cbNeverChanges.mView = XMMatrixTranspose( mWorld * mView * mProjection );
g_pImmediateContext->UpdateSubresource( g_pCBNeverChanges, 0, NULL, &cbNeverChanges, 0, 0 );
// 그리기
g_pImmediateContext->OMSetBlendState( NULL, NULL, 0xFFFFFFFF );
DrawChangingPictures();
// 표시
FlushDrawingPictures();
return S_OK;
}
// 엔트리 포인트
int WINAPI _tWinMain( HINSTANCE hInst, HINSTANCE, LPTSTR, int )
{
LARGE_INTEGER nNowTime, nLastTime; // 현재와 직전 시각
LARGE_INTEGER nTimeFreq; // 시간 단위
// 화면 크기
g_nClientWidth = VIEW_WIDTH; // 너비
g_nClientHeight = VIEW_HEIGHT; // 높이
// Register the window class
WNDCLASSEX wc = { sizeof( WNDCLASSEX ), CS_CLASSDC, MsgProc, 0L, 0L, GetModuleHandle( NULL ), NULL, NULL, NULL, NULL, _T( "D3D Sample" ), NULL };
RegisterClassEx( &wc );
RECT rcRect;
SetRect( &rcRect, 0, 0, g_nClientWidth, g_nClientHeight );
AdjustWindowRect( &rcRect, WS_OVERLAPPEDWINDOW, FALSE );
g_hWnd = CreateWindow( _T( "D3D Sample" ), _T( "Polygons_6_3" ), WS_OVERLAPPEDWINDOW, 100, 20, rcRect.right - rcRect.left, rcRect.bottom - rcRect.top, GetDesktopWindow(), NULL,
wc.hInstance, NULL );
// Initialize Direct3D
if( SUCCEEDED( InitD3D() ) && SUCCEEDED( MakeShaders() ) )
{
// Create the shaders
if( SUCCEEDED( InitDrawModes() ) )
{
if( SUCCEEDED( InitGeometry() ) )
{ // 지오메트리 작성
// Show the window
ShowWindow( g_hWnd, SW_SHOWDEFAULT );
UpdateWindow( g_hWnd );
QueryPerformanceFrequency( &nTimeFreq ); // 시간단위
QueryPerformanceCounter( &nLastTime ); // 1프레임전 시각 초기화
// Enter the message loop
MSG msg;
ZeroMemory( &msg, sizeof( msg ) );
while( msg.message != WM_QUIT )
{
Render();
do
{
if( PeekMessage( &msg, NULL, 0U, 0U, PM_REMOVE ) )
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
QueryPerformanceCounter( &nNowTime );
} while( ( ( nNowTime.QuadPart - nLastTime.QuadPart ) < ( nTimeFreq.QuadPart / 90 ) ) && ( msg.message != WM_QUIT ) );
while( ( ( nNowTime.QuadPart - nLastTime.QuadPart ) < ( nTimeFreq.QuadPart / 60 ) ) && ( msg.message != WM_QUIT ) )
{
QueryPerformanceCounter( &nNowTime );
}
nLastTime = nNowTime;
g_pSwapChain->Present( 0, 0 ); // 표시
}
}
}
}
// Clean up everything and exit the app
Cleanup();
UnregisterClass( _T( "D3D Sample" ), wc.hInstance );
return 0;
}
| [
"[email protected]"
] | |
ebb64a7272d7e8e2ea15cb116db987441ac51d5a | 6b40e9dccf2edc767c44df3acd9b626fcd586b4d | /NT/net/tapi/skywalker/tapi3/hash.h | e5daf4c340dce8cf73d1dd128f129777469cefdf | [] | no_license | jjzhang166/WinNT5_src_20201004 | 712894fcf94fb82c49e5cd09d719da00740e0436 | b2db264153b80fbb91ef5fc9f57b387e223dbfc2 | refs/heads/Win2K3 | 2023-08-12T01:31:59.670176 | 2021-10-14T15:14:37 | 2021-10-14T15:14:37 | 586,134,273 | 1 | 0 | null | 2023-01-07T03:47:45 | 2023-01-07T03:47:44 | null | UTF-8 | C++ | false | false | 9,449 | h | /*++
Copyright (c) 1998-1999 Microsoft Corporation
Module Name:
hash.h
Abstract:
Declaration of the CHashTable class
Author:
mquinton 04-28-98
Notes:
Revision History:
--*/
#ifndef __HASH_H__
#define __HASH_H__
typedef struct _TABLEENTRY
{
ULONG_PTR HashKey;
ULONG_PTR Element;
CTAPI * pTapiObj;
} TABLEENTRY;
typedef struct _TABLEHEADER
{
DWORD dwUsedElements;
TABLEENTRY * pEntries;
} TABLEHEADER;
class CHashTable
{
private:
CRITICAL_SECTION m_cs;
DWORD m_dwTables;
DWORD m_dwEntriesPerTable;
TABLEHEADER * m_pTables;
public:
CHashTable()
{
InitializeCriticalSection( &m_cs );
}
~CHashTable()
{
DeleteCriticalSection( &m_cs );
}
DECLARE_TRACELOG_CLASS(CHashTable)
void Lock()
{
//LOG((TL_INFO,"Hash Table locking......"));
EnterCriticalSection( &m_cs );
//LOG((TL_INFO,"Hash Table locked"));
}
void Unlock()
{
//LOG((TL_INFO,"Hash Table Unlocking......"));
LeaveCriticalSection( &m_cs );
//LOG((TL_INFO,"Hash Table Unlocked"));
}
HRESULT Initialize( DWORD dwEntries )
{
DWORD dwCount;
BYTE * pStart;
m_dwTables = 31;
m_dwEntriesPerTable = dwEntries;
m_pTables = (TABLEHEADER *)ClientAlloc( sizeof(TABLEHEADER) * m_dwTables );
if ( NULL == m_pTables )
{
return E_OUTOFMEMORY;
}
pStart = (BYTE *)ClientAlloc( sizeof(TABLEENTRY) * m_dwTables * m_dwEntriesPerTable );
if ( NULL == pStart )
{
ClientFree( m_pTables );
return E_OUTOFMEMORY;
}
for ( dwCount = 0; dwCount < m_dwTables; dwCount++ )
{
m_pTables[dwCount].pEntries = (TABLEENTRY *)&( pStart[dwCount *
m_dwEntriesPerTable * sizeof (TABLEENTRY)] );
m_pTables[dwCount].dwUsedElements = 0;
}
return S_OK;
}
HRESULT Insert( ULONG_PTR HashKey, ULONG_PTR Element , CTAPI *pTapiObj = 0)
{
DWORD dwHashIndex;
DWORD dwCount = 0;
TABLEHEADER * pTableHeader;
if ( HashKey == 0 )
return S_OK;
dwHashIndex = Hash( HashKey );
pTableHeader = &(m_pTables[dwHashIndex]);
if (pTableHeader->dwUsedElements == m_dwEntriesPerTable)
{
HRESULT hr;
hr = Resize();
if ( !SUCCEEDED(hr) )
{
return hr;
}
}
while ( 0 != pTableHeader->pEntries[dwCount].HashKey )
{
dwCount ++;
}
if (dwCount >= m_dwEntriesPerTable)
{
LOG((TL_ERROR,"Hash Table insert: dwCount >= m_dwEntriesPerTable"));
}
pTableHeader->pEntries[dwCount].HashKey = HashKey;
pTableHeader->pEntries[dwCount].Element = Element;
pTableHeader->pEntries[dwCount].pTapiObj = pTapiObj;
pTableHeader->dwUsedElements++;
LOG((TL_INFO,"Hash Table insert: key %p - obj %p - tapi %p", HashKey, Element, pTapiObj));
#ifdef DBG
CheckForDups( pTableHeader );
#endif
return S_OK;
}
#ifdef DBG
HRESULT CheckForDups( TABLEHEADER * pTableHeader )
{
DWORD dwCount;
DWORD dwInner;
for ( dwCount = 0; dwCount < m_dwEntriesPerTable; dwCount++ )
{
if (pTableHeader->pEntries[dwCount].HashKey == 0)
continue;
for ( dwInner = dwCount+1; dwInner < m_dwEntriesPerTable; dwInner++ )
{
if ( pTableHeader->pEntries[dwCount].HashKey ==
pTableHeader->pEntries[dwInner].HashKey )
{
LOG((TL_ERROR, "HashTable - dup entry"));
LOG((TL_ERROR, " dwCount = %lx, dwInner = %lx", dwCount,dwInner));
LOG((TL_ERROR, " dwHash = %p", pTableHeader->pEntries[dwCount].HashKey));
LOG(( TL_ERROR, "HashTable - dup entry"));
LOG(( TL_ERROR, " dwCount = %lx, dwInner = %lx", dwCount,dwInner));
LOG(( TL_ERROR, " HashKey = %p", pTableHeader->pEntries[dwCount].HashKey));
DebugBreak();
}
}
}
return 0;
}
#endif // DBG
HRESULT Remove( ULONG_PTR HashKey )
{
DWORD dwHashIndex;
DWORD dwCount;
TABLEHEADER * pTableHeader;
LOG((TL_INFO,"Hash Table Remove: key %p ", HashKey));
if ( HashKey == 0 )
return S_OK;
dwHashIndex = Hash( HashKey );
pTableHeader = &(m_pTables[dwHashIndex]);
for ( dwCount = 0; dwCount < m_dwEntriesPerTable; dwCount++ )
{
if ( HashKey == pTableHeader->pEntries[dwCount].HashKey )
{
LOG((TL_INFO,"Hash Table Remove: key %p - obj %p",HashKey,pTableHeader->pEntries[dwCount].Element));
LOG(( TL_TRACE, "Hash Table Remove: key %p - obj %p",HashKey,pTableHeader->pEntries[dwCount].Element));
break;
}
}
if ( dwCount == m_dwEntriesPerTable )
{
return E_FAIL;
}
pTableHeader->pEntries[dwCount].HashKey = 0;
pTableHeader->pEntries[dwCount].pTapiObj = 0;
pTableHeader->dwUsedElements--;
return S_OK;
}
HRESULT Find( ULONG_PTR HashKey, ULONG_PTR * pElement )
{
DWORD dwHashIndex;
TABLEHEADER * pTableHeader;
DWORD dwCount;
if ( HashKey == 0 )
{
LOG((TL_INFO,"Find - Hash Table returning E_FAIL on Find(NULL)"));
return E_FAIL;
// return S_OK;
}
dwHashIndex = Hash( HashKey );
pTableHeader = &(m_pTables[dwHashIndex]);
for (dwCount = 0; dwCount < m_dwEntriesPerTable; dwCount++ )
{
if ( HashKey == pTableHeader->pEntries[dwCount].HashKey )
{
break;
}
}
if ( dwCount == m_dwEntriesPerTable )
{
return E_FAIL;
}
*pElement = pTableHeader->pEntries[dwCount].Element;
LOG((TL_INFO,"Find - Hash Table found: key %p - obj %p",HashKey,*pElement));
return S_OK;
}
DWORD Hash( ULONG_PTR HashKey )
{
return (DWORD)((HashKey >> 4) % m_dwTables);
}
HRESULT Resize()
{
BYTE * pNewTable;
BYTE * pOldTable;
DWORD dwCount;
DWORD dwNumEntries;
dwNumEntries = 2 * m_dwEntriesPerTable;
pNewTable = (BYTE *)ClientAlloc( sizeof(TABLEENTRY) * m_dwTables * dwNumEntries );
if ( NULL == pNewTable )
{
return E_OUTOFMEMORY;
}
pOldTable = (BYTE *)(m_pTables[0].pEntries);
for ( dwCount = 0; dwCount < m_dwTables; dwCount ++ )
{
CopyMemory(
pNewTable,
m_pTables[dwCount].pEntries,
sizeof(TABLEENTRY) * m_dwEntriesPerTable
);
m_pTables[dwCount].pEntries = (TABLEENTRY*)pNewTable;
pNewTable += sizeof(TABLEENTRY) * dwNumEntries;
}
ClientFree( pOldTable );
m_dwEntriesPerTable = dwNumEntries;
return S_OK;
}
void Shutdown()
{
ClientFree( m_pTables[0].pEntries );
ClientFree( m_pTables );
}
HRESULT Flush( CTAPI * pTapiObj )
{
DWORD dwOuterCount;
DWORD dwInnerCount;
TABLEHEADER * pTableHeader;
Lock();
for ( dwOuterCount = 0; dwOuterCount < m_dwTables; dwOuterCount++ )
{
pTableHeader = &(m_pTables[dwOuterCount]);
for ( dwInnerCount = 0; dwInnerCount < m_dwEntriesPerTable; dwInnerCount++ )
{
if ( pTapiObj == pTableHeader->pEntries[dwInnerCount].pTapiObj )
{
LOG((TL_INFO,"Hash Table Flush: key %p - obj %p - tapi %p",pTableHeader->pEntries[dwInnerCount].HashKey,pTableHeader->pEntries[dwInnerCount].Element, pTapiObj));
LOG(( TL_ERROR, "Hash Table Flush: key %p - obj %p - tapi %p",pTableHeader->pEntries[dwInnerCount].HashKey,pTableHeader->pEntries[dwInnerCount].Element, pTapiObj));
pTableHeader->pEntries[dwInnerCount].HashKey = 0;
pTableHeader->pEntries[dwInnerCount].pTapiObj = 0;
pTableHeader->dwUsedElements--;
}
} // end for dwInnerCount
} // end for dwOuterCount
Unlock();
return S_OK;
}
};
#endif
| [
"[email protected]"
] | |
34806718af0ae57c6dca93d3bc3c8d1a82cbd84e | 5562c602016e51e2f1949875b6bbeb9e33ef0b1c | /RLModding/Controllers/XboxController.cpp | bd33343526ce111d6f0039d3cbb0c39765b609fb | [] | no_license | TaylorSasser/RLModding | e6331cd02baa9d93b63934944d3ddf082357ac9e | ddb71d0fe386edf609778f26f45b0717133f445d | refs/heads/master | 2019-07-14T03:55:15.176463 | 2017-11-09T04:18:42 | 2017-11-09T04:18:42 | 92,780,260 | 3 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 911 | cpp | #include "XboxController.h"
XboxController::XboxController() {}
XboxController::XboxController(int playerNum) {
_controllerNum = playerNum;
}
XINPUT_STATE XboxController::GetState() {
ZeroMemory(&_controllerNum, sizeof(XINPUT_STATE));
XInputGetState(_controllerNum, &_controllerState);
return _controllerState;
}
bool XboxController::IsConnected() {
ZeroMemory(&_controllerNum, sizeof(XINPUT_STATE));
// Get the state
DWORD Result = XInputGetState(_controllerNum, &_controllerState);
return Result == ERROR_SUCCESS;
}
void XboxController::Vibrate(int leftVal, int rightVal)
{
// Create a Vibraton State
XINPUT_VIBRATION Vibration;
// Zeroise the Vibration
ZeroMemory(&Vibration, sizeof(XINPUT_VIBRATION));
// Set the Vibration Values
Vibration.wLeftMotorSpeed = leftVal;
Vibration.wRightMotorSpeed = rightVal;
// Vibrate the controller
XInputSetState(_controllerNum, &Vibration);
}
| [
"[email protected]"
] | |
65adc9880ef068e83a0dece99b6b26c2de85d5cf | 1942a0d16bd48962e72aa21fad8d034fa9521a6c | /aws-cpp-sdk-dynamodb/include/aws/dynamodb/model/StreamSpecification.h | 1a0d765b23d7d3b8ceddeac72c190c0a0d66c5e6 | [
"Apache-2.0",
"JSON",
"MIT"
] | permissive | yecol/aws-sdk-cpp | 1aff09a21cfe618e272c2c06d358cfa0fb07cecf | 0b1ea31e593d23b5db49ee39d0a11e5b98ab991e | refs/heads/master | 2021-01-20T02:53:53.557861 | 2018-02-11T11:14:58 | 2018-02-11T11:14:58 | 83,822,910 | 0 | 1 | null | 2017-03-03T17:17:00 | 2017-03-03T17:17:00 | null | UTF-8 | C++ | false | false | 6,753 | h | /*
* Copyright 2010-2016 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/dynamodb/DynamoDB_EXPORTS.h>
#include <aws/dynamodb/model/StreamViewType.h>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace DynamoDB
{
namespace Model
{
/**
* <p>Represents the DynamoDB Streams configuration for a table in
* DynamoDB.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/dynamodb-2012-08-10/StreamSpecification">AWS
* API Reference</a></p>
*/
class AWS_DYNAMODB_API StreamSpecification
{
public:
StreamSpecification();
StreamSpecification(const Aws::Utils::Json::JsonValue& jsonValue);
StreamSpecification& operator=(const Aws::Utils::Json::JsonValue& jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>Indicates whether DynamoDB Streams is enabled (true) or disabled (false) on
* the table.</p>
*/
inline bool GetStreamEnabled() const{ return m_streamEnabled; }
/**
* <p>Indicates whether DynamoDB Streams is enabled (true) or disabled (false) on
* the table.</p>
*/
inline void SetStreamEnabled(bool value) { m_streamEnabledHasBeenSet = true; m_streamEnabled = value; }
/**
* <p>Indicates whether DynamoDB Streams is enabled (true) or disabled (false) on
* the table.</p>
*/
inline StreamSpecification& WithStreamEnabled(bool value) { SetStreamEnabled(value); return *this;}
/**
* <p> When an item in the table is modified, <code>StreamViewType</code>
* determines what information is written to the stream for this table. Valid
* values for <code>StreamViewType</code> are:</p> <ul> <li> <p>
* <code>KEYS_ONLY</code> - Only the key attributes of the modified item are
* written to the stream.</p> </li> <li> <p> <code>NEW_IMAGE</code> - The entire
* item, as it appears after it was modified, is written to the stream.</p> </li>
* <li> <p> <code>OLD_IMAGE</code> - The entire item, as it appeared before it was
* modified, is written to the stream.</p> </li> <li> <p>
* <code>NEW_AND_OLD_IMAGES</code> - Both the new and the old item images of the
* item are written to the stream.</p> </li> </ul>
*/
inline const StreamViewType& GetStreamViewType() const{ return m_streamViewType; }
/**
* <p> When an item in the table is modified, <code>StreamViewType</code>
* determines what information is written to the stream for this table. Valid
* values for <code>StreamViewType</code> are:</p> <ul> <li> <p>
* <code>KEYS_ONLY</code> - Only the key attributes of the modified item are
* written to the stream.</p> </li> <li> <p> <code>NEW_IMAGE</code> - The entire
* item, as it appears after it was modified, is written to the stream.</p> </li>
* <li> <p> <code>OLD_IMAGE</code> - The entire item, as it appeared before it was
* modified, is written to the stream.</p> </li> <li> <p>
* <code>NEW_AND_OLD_IMAGES</code> - Both the new and the old item images of the
* item are written to the stream.</p> </li> </ul>
*/
inline void SetStreamViewType(const StreamViewType& value) { m_streamViewTypeHasBeenSet = true; m_streamViewType = value; }
/**
* <p> When an item in the table is modified, <code>StreamViewType</code>
* determines what information is written to the stream for this table. Valid
* values for <code>StreamViewType</code> are:</p> <ul> <li> <p>
* <code>KEYS_ONLY</code> - Only the key attributes of the modified item are
* written to the stream.</p> </li> <li> <p> <code>NEW_IMAGE</code> - The entire
* item, as it appears after it was modified, is written to the stream.</p> </li>
* <li> <p> <code>OLD_IMAGE</code> - The entire item, as it appeared before it was
* modified, is written to the stream.</p> </li> <li> <p>
* <code>NEW_AND_OLD_IMAGES</code> - Both the new and the old item images of the
* item are written to the stream.</p> </li> </ul>
*/
inline void SetStreamViewType(StreamViewType&& value) { m_streamViewTypeHasBeenSet = true; m_streamViewType = value; }
/**
* <p> When an item in the table is modified, <code>StreamViewType</code>
* determines what information is written to the stream for this table. Valid
* values for <code>StreamViewType</code> are:</p> <ul> <li> <p>
* <code>KEYS_ONLY</code> - Only the key attributes of the modified item are
* written to the stream.</p> </li> <li> <p> <code>NEW_IMAGE</code> - The entire
* item, as it appears after it was modified, is written to the stream.</p> </li>
* <li> <p> <code>OLD_IMAGE</code> - The entire item, as it appeared before it was
* modified, is written to the stream.</p> </li> <li> <p>
* <code>NEW_AND_OLD_IMAGES</code> - Both the new and the old item images of the
* item are written to the stream.</p> </li> </ul>
*/
inline StreamSpecification& WithStreamViewType(const StreamViewType& value) { SetStreamViewType(value); return *this;}
/**
* <p> When an item in the table is modified, <code>StreamViewType</code>
* determines what information is written to the stream for this table. Valid
* values for <code>StreamViewType</code> are:</p> <ul> <li> <p>
* <code>KEYS_ONLY</code> - Only the key attributes of the modified item are
* written to the stream.</p> </li> <li> <p> <code>NEW_IMAGE</code> - The entire
* item, as it appears after it was modified, is written to the stream.</p> </li>
* <li> <p> <code>OLD_IMAGE</code> - The entire item, as it appeared before it was
* modified, is written to the stream.</p> </li> <li> <p>
* <code>NEW_AND_OLD_IMAGES</code> - Both the new and the old item images of the
* item are written to the stream.</p> </li> </ul>
*/
inline StreamSpecification& WithStreamViewType(StreamViewType&& value) { SetStreamViewType(value); return *this;}
private:
bool m_streamEnabled;
bool m_streamEnabledHasBeenSet;
StreamViewType m_streamViewType;
bool m_streamViewTypeHasBeenSet;
};
} // namespace Model
} // namespace DynamoDB
} // namespace Aws
| [
"[email protected]"
] | |
cd6c8b344aabea8b19229db05123371a02233ce5 | 9afb07f448fb492a5b862b23902abf350657bd3e | /DSA_ass3/prm2.cpp | 477e66a520c766fd23962730e5a416f7350e95a2 | [] | no_license | saru-d2/DSA_asses | e4fba08c6dfb78bcebe7a316b0470124189f82ff | 0629ef1adc60af878577c628e013655b448e7642 | refs/heads/master | 2022-12-29T06:17:32.748786 | 2020-04-28T05:36:01 | 2020-04-28T05:36:01 | 259,540,635 | 1 | 1 | null | 2020-10-06T04:52:33 | 2020-04-28T05:30:21 | C++ | UTF-8 | C++ | false | false | 3,253 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long int lint;
lint n, m, x, y, z;
int flag[2000], flag2[2000];
vector<pair<lint, pair<lint, lint>>> edges;
pair<lint, lint> dis[1005];
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
lint t;
cin >> t;
while (t--)
{
while (!edges.empty())
edges.pop_back();
cin >> n >> m;
for (lint i = 1; i <= n; i++)
dis[i].first = 0, dis[i].second = 0, flag[i] = 0, flag2[i] = 0;
while (m--)
{
cin >> x >> y >> z;
edges.push_back(make_pair(z, make_pair(x, y)));
}
for (lint i = 0; i < n; i++)
{
// for (lint i = 1; i <= n; i++)
// cout << "(" << dis[i].first << "," << dis[i].second << ") ";
// cout << endl;
for (auto p : edges)
{
x = p.second.first;
y = p.second.second;
z = p.first;
//dis[i].first is dis *till* that pt, second is dis *frm* that pt
if (dis[y].first > dis[x].first + z)
{
dis[y].first = dis[x].first + z;
}
if (dis[x].second > dis[y].second + z)
{
dis[x].second = dis[y].second + z;
}
}
}
// for (lint i = 0; i < n; i++)
for (auto p : edges)
{
x = p.second.first;
y = p.second.second;
z = p.first;
//dis[i].first is dis *till* that pt, second is dis *frm* that pt
if (dis[y].first > dis[x].first + z)
{
flag[y] = 1;
// flag[x] = 1;
dis[y].first = dis[x].first + z;
}
if (dis[x].second > dis[y].second + z)
{
flag2[x] = 1;
// flag[y] = 1;
dis[x].second = dis[y].second + z;
}
}
for (lint i = 0; i <= n; i++)
cout << flag[i] << "," << flag2[i] << " ";
cout << endl;
int chg = 0;
for (lint i = 1; i <= n; i++)
{
chg = 0;
for (auto p : edges)
{
x = p.second.first;
y = p.second.second;
z = p.first;
if ((flag[x] == 0 && flag2[y] == 1) || (flag[y] == 0 && flag2[x] == 0))
{
// cout<<x<<" "<<y<<endl;
flag[x] = 1;
flag2[y] = 1;
chg = 1;
}
}
if (chg == 0)
break;
}
// for (lint i = 0; i <= n; i++)
// cout << flag[i] << "," << flag2[i] << " ";
// cout << endl;
// for (lint i = 1; i <= n; i++)
// cout << "(" << dis[i].first << "," << dis[i].second << "," << flag[i] << ") ";
// cout << endl;
for (lint i = 1; i <= n; i++)
{
if (flag[i] != 0 || flag2[i] != 0)
cout << "INF\n";
else
cout << dis[i].first + dis[i].second << endl;
}
}
}
| [
"[email protected]"
] | |
abc6b0d199fb52a35d257118040939c1076373d5 | 89da35b3e856143de6ad83da8b38dbf6c2911694 | /MpcDlg_chl_ruanzhu/MpcDlg_chl_ruanzhu/IMC_Generic/IMC_GenericDlg.cpp | 3c977fd93e855eba086762677f01bc5a284914af | [] | no_license | chenhuili1/test1Repository | e2e5d08710eab7af6ea38955d2a84ef201297f73 | afc20d18e6fcea4625cd14cf20a9c74e391dbe51 | refs/heads/master | 2023-03-16T19:55:03.446014 | 2021-03-03T10:08:48 | 2021-03-03T10:08:48 | 331,535,955 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 36,774 | cpp | // IMC_GenericDlg.cpp : 实现文件
//
#include "stdafx.h"
#include "IMC_Generic.h"
#include "IMC_GenericDlg.h"
#include "MyPassWord.h"
#include "math.h"
#if defined(WINCE)
#include "sip.h"
#include "SIPAPI.H"
#endif
#include "LogoInfo.h"
CLogoInfo *g_pinfodlg = NULL;
enum{
MACHIN_STEP,
MACHIN_SINGLE,
MACHIN_LOOP,
};
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// CIMC_GenericDlg 对话框
CIMC_GenericDlg::CIMC_GenericDlg(CWnd* pParent /*=NULL*/)
: CDialog(CIMC_GenericDlg::IDD, pParent)
{
m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
m_isInit = FALSE;
m_bChange = FALSE;
m_curdlg = 0;
m_timeTotal = 0;
m_matchinNum = 0;
m_threadPause = FALSE;
m_threadRun = FALSE; //线程是否正在运行
m_EmstopRun = FALSE; //线程是否正在运行
m_threadStop = FALSE; //控制线程停止
m_threadReset = FALSE; //控制线程复位,即立即退出线程
m_threadStep = FALSE;
m_machinMode = 2; //循环
m_errRunT = FALSE;
g_isTestV = FALSE;
g_cmdStr[CMD_NULL] =_T("");
g_cmdStr[CMD_LINKAGE] =_T("启动多轴联动");
g_cmdStr[CMD_ARC] =_T("启动圆弧动作");
g_cmdStr[CMD_OUTPUT] =_T("开关量输出");
g_cmdStr[CMD_INPUT] =_T("开关量输入");
g_cmdStr[CMD_JUMP] =_T("跳转");
// g_cmdStr[CMD_IF] =_T("条件");
g_cmdStr[CMD_LOOP] =_T("循环开始");
g_cmdStr[CMD_WEND] =_T("循环结束");
g_cmdStr[CMD_DELAY] =_T("延时");
g_cmdStr[CMD_END] =_T("程序结束");
g_cmdStr[CMD_GOHOME] =_T("回零操作");
g_cmdStr[CMD_GHWHIRL] =_T("旋转轴回零");
g_cmdStr[CMD_VEL] =_T("启动连续运动");
g_cmdStr[CMD_POS] =_T("启动单轴点位");
g_cmdStr[CMD_WAIT] =_T("等待");
g_AxisName[MAP_X] = _T("X轴");
g_AxisName[MAP_Y] = _T("Y轴");
g_AxisName[MAP_Z] = _T("Z轴");
g_AxisName[MAP_A] = _T("A轴");
g_AxisName[MAP_B] = _T("B轴");
g_AxisName[MAP_C] = _T("C轴");
g_AxisName[MAP_D] = _T("D轴");
g_AxisName[MAP_E] = _T("E轴");
g_AxisName[MAP_F] = _T("F轴");
g_AxisName[MAP_G] = _T("G轴");
g_AxisName[MAP_H] = _T("H轴");
g_AxisName[MAP_I] = _T("I轴");
g_AxisName[MAP_J] = _T("J轴");
g_AxisName[MAP_K] = _T("K轴");
g_AxisName[MAP_L] = _T("L轴");
g_AxisName[MAP_M] = _T("M轴");
g_Naxis = 4;
memset(&g_factcfg, 0, sizeof(FACT_CFG));
memset(&g_cfg, 0, sizeof(SYS_CFG));
int i;
g_cfg.machinSel = 1;
g_cfg.locusVel = 10;
g_cfg.locusFastVel = 20;
g_cfg.locusAcc = 10;
for(i=0; i<MAX_NAXIS; i++){
g_cfg.workVel[i] = 10;
g_cfg.fastVel[i] = 20;
g_cfg.jogVel[i] = 10;
g_cfg.homeVel[i] = 10;
g_cfg.homeDir[i] = 1;
g_cfg.accel[i] = 20;
g_cfg.decel[i] = 20;
g_factcfg.distFac[i] = 10000;
g_factcfg.timeFac[i] = 1000;
g_factcfg.steptime[i] = 200;
g_factcfg.g_mapAxis[i] = i;
g_factcfg.encpfac[i] = 1.0;
memcpy(g_factcfg.Unit[i], _T("cm"), sizeof(_T("cm")));
m_axis[i] = i;
m_encp[i] = 0;
m_error[i] = 0;
}
g_factcfg.Naxis = 4;
#ifdef errrrrr
#else
memcpy(g_factcfg.sysName, _T("可编程通用运动控制系统"), sizeof(_T("可编程通用运动控制系统")));
memcpy(g_factcfg.factName, _T("广州研为电子科技有限公司"), sizeof(_T("广州研为电子科技有限公司")));
memcpy(g_factcfg.web, _T("www.gzyanwei.com"), sizeof(_T("www.gzyanwei.com")));
memcpy(g_factcfg.phone, _T("020-39337878"), sizeof(_T("020-39337878")));
memcpy(g_factcfg.address, _T("广州市大学城外环东路232号研发东区A432"), sizeof(_T("广州市大学城外环东路232号研发东区A432")));
#endif
for(i=0; i<INPUT_NUM; i++){
g_iomap.mapI[i].bit = i;
g_iomap.mapI[i].loc = i > 15 ? gin2Loc : gin1Loc;
g_iomap.mapI[i].axis = 0;
}
for(i=0; i<OUTPUT_NUM; i++){
g_iomap.mapO[i].bit = i;
g_iomap.mapO[i].loc = i > 15 ? gout2Loc : gout1Loc;
g_iomap.mapO[i].axis = 0;
}
/* for(i=0; i<LED_NUM; i++){
g_factcfg.mapLed[i].bit = i;
g_factcfg.mapLed[i].loc = gout2Loc;
g_factcfg.mapLed[i].axis = 0;
}
for(i=0; i<KEY_NUM; i++){
g_factcfg.mapKey[i].bit = i;
g_factcfg.mapKey[i].loc = gin2Loc;
g_factcfg.mapKey[i].axis = 0;
m_key[i] = SW_INPUT_OPEN;
}*/
g_fn14 = new CFont;
g_fn14->CreateFont(30, // nHeight 字体的高度
0, // nWidth 字体的宽度。
0, // nEscapement 字体的倾斜角
0, // nOrientation 字体的倾斜角
FW_BOLD, // nWeight 字体的粗细。
FALSE, // bItalic 字体是否斜体。
FALSE, // bUnderline 字体是否有下划线。
0, // cStrikeOut 字体是否有删除线
GB2312_CHARSET, // nCharSet 字体使用的字符集。
OUT_DEFAULT_PRECIS, // nOutPrecision 如何选择合适的字体。
CLIP_DEFAULT_PRECIS, // nClipPrecision 用来确定裁剪的精度。
DEFAULT_QUALITY, // nQuality 怎么样跟选择的字体相符合。
DEFAULT_PITCH | FF_SWISS, // nPitchAndFamily 间距标志和属性标志
_T("隶书")); //_T("Arial")); // lpszFac字体的名称。
}
CIMC_GenericDlg::~CIMC_GenericDlg()
{
delete g_fn14;
}
void CIMC_GenericDlg::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
}
BEGIN_MESSAGE_MAP(CIMC_GenericDlg, CDialog)
// ON_WM_PAINT()
ON_WM_QUERYDRAGICON()
ON_WM_SIZE()
ON_WM_CLOSE()
ON_WM_CTLCOLOR()
ON_WM_TIMER()
#if defined(_DEVICE_RESOLUTION_AWARE) && !defined(WIN32_PLATFORM_WFSP)
ON_WM_SIZE()
#endif
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
#define MY_BKCOLOR RGB(0,0,230)
// CIMC_GenericDlg 消息处理程序
BOOL CIMC_GenericDlg::OnInitDialog()
{
CDialog::OnInitDialog();
// 设置此对话框的图标。当应用程序主窗口不是对话框时,框架将自动
// 执行此操作
SetIcon(m_hIcon, TRUE); // 设置大图标
SetIcon(m_hIcon, FALSE); // 设置小图标
m_brush.CreateSolidBrush(MY_BKCOLOR);
//让程序全屏
#if defined(WINCE)
int iFullWidth = GetSystemMetrics(SM_CXSCREEN) + 6;
int iFullHeight = GetSystemMetrics(SM_CYSCREEN) + 6;
::SetWindowPos(this->m_hWnd, HWND_TOPMOST, -3, -3, iFullWidth, iFullHeight, SWP_NOOWNERZORDER|SWP_SHOWWINDOW|WS_EX_TOPMOST);
#else
LONG lStyle = ::GetWindowLong(this->m_hWnd, GWL_STYLE);
::SetWindowLong(this->m_hWnd, GWL_STYLE, lStyle | WS_CAPTION | WS_MINIMIZEBOX | WS_SYSMENU);
// ::SetWindowPos(this->m_hWnd, NULL, 0, 0, 0, 0,
// SWP_NOSIZE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED);
#endif
//************************************************************************************************************
// TODO: 在此添加额外的初始化代码
#if defined(WINCE)
SipShowIM(SIPF_OFF);
#endif
CreateSysDir();
ReadFactCfg();
ReadFactPolar();
ReadIOMap();
ReadWarn();
ReadCfg();
g_Naxis = g_factcfg.Naxis;
StartLogo();
#if defined(WINCE)
GetDlgItem(IDC_STATIC_TITLE)->SetFont(g_fn14);
GetDlgItem(IDC_STATIC_TITLE)->SetWindowText(g_factcfg.sysName);
CString str;
m_sysTime = CTime::GetCurrentTime();
UINT ret = SetTimer(TIMER_SYSTIME,60000, NULL);
str = m_sysTime.Format(_T("%H:%M"));
SetDlgItemText(IDC_STATIC_SYS_TIME, str);
#else
GetDlgItem(IDC_STATIC_TITLE)->ShowWindow(SW_HIDE);
GetDlgItem(IDC_STATIC_SYS_TIME)->ShowWindow(SW_HIDE);
SetWindowText(g_factcfg.sysName);
#endif
m_maindlg.SetMainDlgPtr(this);
m_FactoryDlg.SetMainDlgPtr(this);
m_SysDlg.SetMainDlgPtr(this);
m_homeDlg.SetMainDlgPtr(this);
m_sinfoDlg.SetMainDlgPtr(this);
m_fileDlg.SetMainDlgPtr(this);
m_debugDlg.SetMainDlgPtr(this);
m_maindlg.Create(IDD_DLG_MAIN, this);
m_FactoryDlg.Create(IDD_DLG_FACT, this);
m_SysDlg.Create(IDD_DLG_SYS, this);
m_homeDlg.Create(IDD_DLG_FIND_HOME, this);
m_sinfoDlg.Create(IDD_DLG_SYS_INFO, this);
m_fileDlg.Create(IDD_DLG_FILE, this);
m_debugDlg.Create(IDD_DLG_DEBUG, this);
m_maindlg.ShowWindow(SW_HIDE);
m_FactoryDlg.ShowWindow(SW_HIDE);
m_SysDlg.ShowWindow(SW_HIDE);
m_homeDlg.ShowWindow(SW_HIDE);
m_sinfoDlg.ShowWindow(SW_HIDE);
m_fileDlg.ShowWindow(SW_HIDE);
m_debugDlg.ShowWindow(SW_HIDE);
//
MoveDlg();
if(!m_imc.OpenDev()){
StartOpenTimer();
// title += _T(" - 设备没有连接");
}else{
if(!DebugVersion()){
CString title;
m_imc.CloseDev();
title += _T(" - 试用版已到期");
#if defined(WINCE)
GetDlgItem(IDC_STATIC_TITLE)->SetWindowText(title);
#else
SetWindowText(title);
#endif
}
}
// CString title = g_factcfg.sysName;
if(m_imc.IsOpen()){
//SetTimer(TIMER_GET_ENCP, 40, NULL);
SetTimer(TIMER_KEY_INPUT, 1000, NULL);
}
if(!IsPasswordOK(MY_PW_LOGIN))
exit(0);
WCHAR srcpath[256];
if(ReadCurFile(srcpath))
m_maindlg.LoadSGCfile(srcpath);
if(g_pinfodlg) g_pinfodlg->OnCancel();
m_maindlg.ShowWindow(SW_SHOW);
return TRUE; // 除非将焦点设置到控件,否则返回 TRUE
}
void CIMC_GenericDlg::StartOpenTimer()
{
SetTimer(TIMER_DEV_OPEN, 1000, NULL);
}
#if defined(_DEVICE_RESOLUTION_AWARE) && !defined(WIN32_PLATFORM_WFSP)
void CIMC_GenericDlg::OnSize(UINT /*nType*/, int /*cx*/, int /*cy*/)
{
if (AfxIsDRAEnabled())
{
DRA::RelayoutDialog(
AfxGetResourceHandle(),
this->m_hWnd,
DRA::GetDisplayMode() != DRA::Portrait ?
MAKEINTRESOURCE(IDD_IMC_GENERIC_DIALOG_WIDE) :
MAKEINTRESOURCE(IDD_IMC_GENERIC_DIALOG));
}
}
#endif
void CIMC_GenericDlg::StartLogo()
{
g_pinfodlg = new CLogoInfo;
g_pinfodlg->Create(IDD_DLG_LOGO,this);
g_pinfodlg->ShowWindow(SW_SHOW);
}
//防止使用Input Panel时任务栏出现*******************************************************************
void CIMC_GenericDlg::OnActivate(UINT nState, CWnd* pWndOther, BOOL bMinimized)
{
CWnd::OnActivate(nState, pWndOther, bMinimized); //注意这里从CWnd继承
// SHFullScreen( this->m_hWnd, SHFS_HIDETASKBAR);////隐藏任务栏
}
void CIMC_GenericDlg::MoveDlg()
{
CRect rc,rc1, rcb,rct;
GetClientRect(&rc);
// GetWindowRect(&rc);
#if defined(WINCE)
GetDlgItem(IDC_STATIC_TITLE)->GetWindowRect(&rcb);
GetDlgItem(IDC_STATIC_SYS_TIME)->GetWindowRect(&rct);
int width = rct.Width();
rct.right = rc.right;
rct.left = rc.right - width;
rcb.right = rct.left - 2;
GetDlgItem(IDC_STATIC_TITLE)->MoveWindow(&rcb);
GetDlgItem(IDC_STATIC_SYS_TIME)->MoveWindow(&rct);
rc.top = rcb.bottom + 4;
#endif
m_maindlg.MoveWindow(rc);
m_SysDlg.MoveWindow(rc);
m_FactoryDlg.MoveWindow(rc);
m_homeDlg.MoveWindow(rc);
m_fileDlg.MoveWindow(rc);
m_sinfoDlg.MoveWindow(rc);
m_debugDlg.MoveWindow(rc);
m_isInit = TRUE;
}
HBRUSH CIMC_GenericDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CDialog::OnCtlColor(pDC, pWnd, nCtlColor);
// TODO: 在此更改 DC 的任何特性
if(nCtlColor == CTLCOLOR_STATIC ) {
pDC->SetTextColor(RGB(250,250,250));
// return m_brush; //返加刷子
}
pDC->SetBkColor(MY_BKCOLOR);
return m_brush; //返加刷子
// TODO: 如果默认的不是所需画笔,则返回另一个画笔
return hbr;
}
void CIMC_GenericDlg::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
// TODO: 在此处添加消息处理程序代码
// if(m_isInit)
// MoveDlg();
}
void CIMC_GenericDlg::ShowDlg(int dlg)
{
if(GetThreadSt()) return;
if(m_curdlg == dlg) return;
switch(m_curdlg)
{
case JM_MAIN: m_maindlg.ShowWindow(SW_HIDE); break;
case JM_SYS: m_SysDlg.ShowWindow(SW_HIDE); break;
case JM_FACT: m_FactoryDlg.ShowWindow(SW_HIDE); break;
case JM_HOME: m_homeDlg.ShowWindow(SW_HIDE); break;
case JM_SINFO: m_sinfoDlg.ShowWindow(SW_HIDE); break;
case JM_FILE: m_fileDlg.MyHideWindow(); break;
case JM_DEBUG: m_debugDlg.MyHideWindow(); break;
default: return;
}
m_curdlg = dlg;
switch(m_curdlg)
{
case JM_MAIN: m_maindlg.ShowEncpDlg(); m_maindlg.ShowWindow(SW_SHOW); m_maindlg.SetFocus(); break;
case JM_SYS: m_SysDlg.UpdateCtr(); m_SysDlg.ShowWindow(SW_SHOW); m_SysDlg.SetFocus(); break;
case JM_FACT: m_FactoryDlg.ShowWindow(SW_SHOW); m_FactoryDlg.ShowDlg(FACT_AXIS); break;
case JM_HOME: m_homeDlg.UpdateCtr(); m_homeDlg.ShowWindow(SW_SHOW); m_homeDlg.SetFocus(); break;
case JM_SINFO: m_sinfoDlg.UpdateInfo(); m_sinfoDlg.ShowWindow(SW_SHOW); break;
case JM_FILE: m_fileDlg.MyShowWindow(); break;
case JM_DEBUG: m_debugDlg.UpdateCtr(); m_debugDlg.ShowWindow(SW_SHOW); break;
}
}
void CIMC_GenericDlg::OnClose()
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
if(m_bChange){
int res = MessageBox(_T("是否保存程序?"), _T("提示"), MB_YESNOCANCEL);
if(res == IDYES){
m_maindlg.OnBnClickedBnSaveFile();
}else if(res == IDCANCEL)
return;
}
m_maindlg.DeleteAllProgramData();
CDialog::OnClose();
}
BOOL CIMC_GenericDlg::IsPasswordOK(int type)
{
switch(type)
{
case MY_PW_FACT: if(g_factcfg.PWfact[0] == 0) return TRUE; break;
case MY_PW_LOGIN: if(g_cfg.PWlogin[0] == 0) return TRUE; break;
case MY_PW_EDIT: if(g_cfg.PWEdit[0] == 0) return TRUE; break;
case MY_PW_SYS: if(g_cfg.PWSys[0] == 0) return TRUE; break;
case MY_PW_RUN: if(g_cfg.PWRun[0] == 0) return TRUE; break;
default: return FALSE;
}
CMyPassWord dlg;
dlg.SetType(type);
int nResponse = dlg.DoModal();
if (nResponse == IDOK)
return TRUE;
return FALSE;
}
//************************************************************************************************
//文件相关
//************************************************************************************************
BOOL CIMC_GenericDlg::IsFileDirExist(CString dir)
{//判断文件或目录是否存在
WIN32_FIND_DATA fd;
HANDLE hd = INVALID_HANDLE_VALUE;
hd=::FindFirstFile(dir,&fd);
if(INVALID_HANDLE_VALUE != hd)
return TRUE;
return FALSE;
}
BOOL CIMC_GenericDlg::CreateSysDir()
{//创建目录
CString dir, file;
SECURITY_ATTRIBUTES attrib;
attrib.bInheritHandle = FALSE;
attrib.lpSecurityDescriptor = NULL;
attrib.nLength = sizeof(SECURITY_ATTRIBUTES);
#if defined(WINCE)
dir = SYS_FILE_DIR;
#else
dir = GetMyMFCDir();
#endif
if(!IsFileDirExist(dir))
{
::CreateDirectory(dir, &attrib);
}
#if defined(WINCE)
file = CFG_FILE_DIR;
#else
file = dir + CFG_FILE_DIR;
#endif
if(!IsFileDirExist(file))
{
::CreateDirectory(file, &attrib);
}
#if defined(WINCE)
file = SAV_FILE_DIR;
#else
file = dir + SAV_FILE_DIR;
#endif
if(!IsFileDirExist(file))
{
::CreateDirectory(file, &attrib);
}
return TRUE;
}
void CIMC_GenericDlg::OnTimer(UINT_PTR nIDEvent)
{
// TODO: 在此添加消息处理程序代码和/或调用默认值
CString title;
switch(nIDEvent)
{
case TIMER_SYSTIME:
#if defined(WINCE)
{
CString str;
m_sysTime = CTime::GetCurrentTime();
str = m_sysTime.Format(_T("%H:%M"));
SetDlgItemText(IDC_STATIC_SYS_TIME, str);
}
#endif
break;
case TIMER_DEV_OPEN:
title = g_factcfg.sysName;
if(m_imc.OpenDev()){
KillTimer(TIMER_DEV_OPEN);
if(!DebugVersion()){
m_imc.CloseDev();
title += _T(" - 试用版已到期");
GetDlgItem(IDC_STATIC_TITLE)->SetWindowText(title);
break;
}
//SetTimer(TIMER_GET_ENCP, 40, NULL);
SetTimer(TIMER_KEY_INPUT, 1000, NULL);
#if defined(WINCE)
GetDlgItem(IDC_STATIC_TITLE)->SetWindowText(title);
#else
SetWindowText(title);
#endif
// m_maindlg.m_TStatusdlg.SetEncpTimer();
// g_Naxis = m_imc.m_Naxis;
}else{
title += _T(" - 设备没有连接");
#if defined(WINCE)
GetDlgItem(IDC_STATIC_TITLE)->SetWindowText(title);
#else
SetWindowText(title);
#endif
}
break;
case TIMER_GET_ENCP:
m_imc.GetEncp(m_encp, m_axis, g_Naxis);
break;
case TIMER_KEY_INPUT:
short key[KEY_NUM];
KillTimer(TIMER_KEY_INPUT);
if(m_imc.KeyInPut(key)== IMC_OK){
if(m_key[KEY_RUN] != key[KEY_RUN]){
if(key[KEY_RUN] == SW_INPUT_CLOSE){
if(m_curdlg == JM_MAIN)
m_maindlg.OnBnClickedBnRun();
}
m_key[KEY_RUN] = key[KEY_RUN];
}
if(m_key[KEY_PAUSE] != key[KEY_PAUSE]){
if(key[KEY_PAUSE] == SW_INPUT_CLOSE){
if(m_curdlg == JM_MAIN)
m_maindlg.OnBnClickedBnPause();
}
m_key[KEY_PAUSE] = key[KEY_PAUSE];
}
if(m_key[KEY_EMSTOP] != key[KEY_EMSTOP])
{
if(key[KEY_EMSTOP] == SW_INPUT_CLOSE){
//RedLedOn();
//m_maindlg.MahinEndTip(3);
if(m_curdlg == JM_MAIN)
m_maindlg.OnBnClickedBnEmstop();//急停
}
else
{
//RedLedOff();
//m_maindlg.MahinEndTip(0);
}
m_key[KEY_EMSTOP] = key[KEY_EMSTOP];
}
if(m_key[KEY_RESET] != key[KEY_RESET]){
if(key[KEY_RESET] == SW_INPUT_CLOSE){
if(m_curdlg == JM_MAIN)
m_maindlg.OnBnClickedBnReset();//复位
}
m_key[KEY_RESET] = key[KEY_RESET];
}
}
EmstopInput();
ErrorShow();
SetTimer(TIMER_KEY_INPUT, GET_KEY_INPUT_TIME, NULL);
break;
case TIMER_MACHIN_TIMING:
m_time ++;
m_timeTotal ++;
m_maindlg.ShowMachinTime(m_time);
m_maindlg.ShowMachinTimeTotal(m_timeTotal);
}
CDialog::OnTimer(nIDEvent);
}
void CIMC_GenericDlg::GetCurEncp(long *encp)
{
memcpy(encp, m_encp, sizeof(long) *g_Naxis);
}
UINT ErrorThread(PVOID param)
{
CIMC_GenericDlg *pdlg = (CIMC_GenericDlg*)param;
CString str, tmp;
BOOL isOk = TRUE, isclr[16];
WORD *err;
pdlg->m_errRunT = TRUE;
for(int i=0; i<16; i++)
isclr[i] = TRUE;
// while(1)
{
str = _T("");
err = pdlg->GetErrorVal();
for(int i=0; i<g_Naxis; i++)
{
if(err[i]){
if(err[i] & 0x80){
isOk = FALSE;
tmp.Format(_T("%s 位置误差超限\r\n"), g_AxisName[i]);
str += tmp;
}else
if(err[i] & 0x2000){
isOk = FALSE;
tmp.Format(_T("%s 速度超限\r\n"), g_AxisName[i]);
str += tmp;
}else
if(err[i] & 0x4000){
isOk = FALSE;
tmp.Format(_T("%s 加速度超限\r\n"), g_AxisName[i]);
str += tmp;
}else
if(err[i] & 0x40){//伺服报警
isOk = FALSE;
tmp.Format(_T("%s 伺服报警\r\n"), g_AxisName[i]);
str += tmp;
}
if(err[i] & 0x01){//正限位
tmp.Format(_T("%s 正方向限位\r\n"), g_AxisName[i]);
pdlg->m_maindlg.MahinEndTip(tmp);
isclr[i] = FALSE;
}else
if(err[i] & 0x02){//负限位
tmp.Format(_T("%s 负方向限位\r\n"), g_AxisName[i]);
pdlg->m_maindlg.MahinEndTip(tmp);
isclr[i] = FALSE;
}
}else{
if(!isclr[i]){
pdlg->m_maindlg.MahinEndTip(_T(""));
isclr[i] = TRUE;
}
}
}
if(isOk == FALSE){
AfxMessageBox(str);
isOk = TRUE;
}
Sleep(100);
}
pdlg->m_errRunT = FALSE;
return 0;
}
WORD *CIMC_GenericDlg::GetErrorVal()
{
return m_error;
}
void CIMC_GenericDlg::ErrorShow()
{
if( m_imc.GetError(m_error, m_axis, g_Naxis) == IMC_OK){
/* if(m_errRunT == FALSE){
m_errRunT = TRUE;
AfxBeginThread(ErrorThread, this);
}*/
ErrorThread(this);
}
}
void CIMC_GenericDlg::EmstopInput()
{//按下急停开关
short key;
if(IMC_OK == m_imc.GetEmstop(&key)){
if(key != m_emstopkey){
m_emstopkey = key;
if(m_emstopkey/* == SW_INPUT_OPEN*/){//急停键按下,停止所有程序
m_maindlg.OnBnClickedBnEmstop();
// m_warndlg.SetWarnText(_T("急停开关已按下!\r\n\r\n放开急停开关恢复!"));
m_maindlg.MahinEndTip(2);
RedLedOn();
}else/* if(m_emstopkey == SW_INPUT_CLOSE)*/{//急停键放开,恢复所有程序
m_imc.ReEnaAxis();
m_maindlg.MahinEndTip(0);
RedLedOff();
}
}
}
}
//*************************************************************************************************************
//
//*************************************************************************************************************
//UINT ThreadRun(PVOID param);
UINT ThreadRun_new(PVOID param);
BOOL CIMC_GenericDlg::GetThreadSt()
{//返回线程运行状态
return m_threadRun;
}
BOOL CIMC_GenericDlg::IsPause()
{
return m_threadPause;
}
void CIMC_GenericDlg::StartMatchin(BOOL mode)
{//启动线程
m_machinMode = mode;
if(m_threadPause){
m_threadPause = FALSE;
m_imc.SetPauseStatus(FALSE);
m_maindlg.EnableRunKey();
YellowLedOff();
}else if(m_threadStep){
// m_threadStep = FALSE;
m_threadPause = FALSE;
}else if(!GetThreadSt()){
m_threadPause = FALSE;
m_threadReset = FALSE;
m_threadStop = FALSE;
m_imc.StopFun(FALSE);
if(m_machinMode == MACHIN_STEP)
m_threadStep = TRUE;
else
m_threadStep = FALSE;
YellowLedOff();
RedLedOff();
SetTimer(TIMER_MACHIN_TIMING, 1000, NULL);
AfxBeginThread(ThreadRun_new, this);
}else
StopMatchin();
}
void CIMC_GenericDlg::PauseMatchin()
{//加工完当前行后暂停线程
if(!GetThreadSt()) return;
m_threadPause = TRUE;
m_imc.SetPauseStatus(TRUE);
YellowLedOn();
m_maindlg.EnableRunKey();
}
void CIMC_GenericDlg::StopMatchin()
{//加工完最后一条后退出线程
m_threadPause = FALSE;
m_threadStop = TRUE;
m_maindlg.MahinEndTip(1);
}
UINT EmstopThreadRun(PVOID param);
void CIMC_GenericDlg::EmstopMatchin()
{//立即退出线程
if(!GetThreadSt()) return;
BOOL step = m_threadPause;
m_threadPause = FALSE;
m_threadReset = TRUE;
m_imc.StopFun(TRUE);//停止循环,如果有的话
m_imc.StopDev();//急停
if(!m_EmstopRun && !step && m_machinMode != MACHIN_STEP)
AfxBeginThread(EmstopThreadRun, this);
DoEvents();
Sleep(200);
m_imc.StopReset();
}
UINT ResetThreadRun(PVOID param);
void CIMC_GenericDlg::ResetMatchin()
{
if(!GetThreadSt()){
m_threadReset = FALSE;
m_imc.StopFun(FALSE);
AfxBeginThread(ResetThreadRun, this);
}else{
EmstopMatchin();
}
}
void CIMC_GenericDlg::RedLedOn()
{
m_maindlg.SetBmpVal(2, 1);
m_imc.LedCtr(LED_RED, LED_ON, SEL_PFIFO1);
}
void CIMC_GenericDlg::RedLedOff()
{
m_maindlg.SetBmpVal(2, 0);
m_imc.LedCtr(LED_RED, LED_OFF, SEL_PFIFO1);
}
void CIMC_GenericDlg::YellowLedOn()
{
m_maindlg.SetBmpVal(1, 1);
m_imc.LedCtr(LED_YELLOW, LED_ON, SEL_PFIFO1);
}
void CIMC_GenericDlg::YellowLedOff()
{
m_maindlg.SetBmpVal(1, 0);
m_imc.LedCtr(LED_YELLOW, LED_OFF, SEL_PFIFO1);
}
void CIMC_GenericDlg::GreedLedOn()
{
m_maindlg.SetBmpVal(0, 1);
m_imc.LedCtr(LED_GREED, LED_ON, SEL_PFIFO1);
}
void CIMC_GenericDlg::GreedLedOff()
{
m_maindlg.SetBmpVal(0, 0);
m_imc.LedCtr(LED_GREED, LED_OFF, SEL_PFIFO1);
}
void CIMC_GenericDlg::SetCurLine(int line)
{
m_curLine = line;
}
int CIMC_GenericDlg::GetCurLine()
{
return m_curLine;
}
PROGRAM_DATA *g_phead = NULL;
int g_cmdNum = 0;
UINT ThreadRun_new(PVOID param)
{
CIMC_GenericDlg* pdlg = (CIMC_GenericDlg*)param;
PROGRAM_DATA *pdata; //编程数据
short count;
int line;
int matchinNum = 0;
BOOL ispause = FALSE;
pdlg->m_threadRun = TRUE;
pdlg->m_maindlg.EnableRunKey();
pdlg->m_maindlg.ShowMachinStatus();
pdlg->m_imc.SetPauseStatus(FALSE);
pdlg->GreedLedOn();
pdlg->YellowLedOff();
g_phead = pdlg->m_maindlg.GetRunData(&g_cmdNum);
while(!pdlg->m_threadStop && !pdlg->m_threadReset && g_cmdNum > 0)
{//加工完最后一个动作后退出
pdlg->SetCurLine(0);
pdata = g_phead + pdlg->GetCurLine();
count = 0;
pdlg->m_time = 0;
matchinNum ++;
pdlg->m_imc.SetData16(startpath1Loc, -1, SEL_IFIFO);
while(pdata != NULL && !pdlg->m_threadReset)
{
line = pdlg->GetCurLine();
if(line >= g_cmdNum) break;
if(pdata->type == CMD_END) break;
pdlg->m_maindlg.SetShow(line);
pdlg->SetCurLine(line + 1);
// pdlg->m_imc.SetData16(user16b0Loc, count, SEL_PFIFO1);
pdata->isWT = 0;
while(!pdlg->RunAll(pdata)){
if(pdlg->m_threadReset) break;
Sleep(10);
};
/* while(!pdlg->m_threadReset){
pdlg->m_imc.GetData16(user16b0Loc, &count1);
if(count1 == count) break;
else Sleep(50);
}*/
if(pdlg->m_machinMode == MACHIN_STEP){//单步的时候暂停
pdlg->PauseMatchin();
}
if(pdlg->m_threadPause){
pdlg->m_maindlg.EnableRunKey();
ispause = TRUE;
}
while(pdlg->m_threadPause && !pdlg->m_threadStop && !pdlg->m_threadReset){
Sleep(50);//暂停
}
if(ispause){
pdlg->m_maindlg.EnableRunKey();
pdlg->m_imc.SetPauseStatus(FALSE);
ispause = FALSE;
}
count ++;
pdata = g_phead + pdlg->GetCurLine();
}
pdlg->WaitAllOver();//等待运动完成
if(pdlg->m_machinMode == MACHIN_STEP)//单步
break;//不计数
pdlg->m_matchinNum ++;
pdlg->m_maindlg.ShowMachinNum(pdlg->m_matchinNum);
Sleep(500);//等待200毫秒后再重新开始
if(pdlg->m_machinMode == MACHIN_SINGLE)//单步
break;//计数后跳出
}
if(pdlg->m_machinMode == MACHIN_STEP)
{
pdlg->m_maindlg.ShowStepStart(pdlg->GetCurLine());
}
pdlg->m_threadStep = FALSE;
pdlg->m_threadRun = FALSE;
pdlg->KillTimer(TIMER_MACHIN_TIMING);
pdlg->m_maindlg.EnableRunKey();
pdlg->m_maindlg.ShowMachinStatus();
pdlg->GreedLedOff();
pdlg->YellowLedOn();
if(!pdlg->m_emstopkey)
pdlg->m_maindlg.MahinEndTip(0);
if(g_phead) delete [] g_phead;
g_phead = NULL;
return 0;
}
//复位线程
UINT ResetThreadRun(PVOID param)
{
CIMC_GenericDlg* pdlg = (CIMC_GenericDlg*)param;
PROGRAM_DATA *pdata; //编程数据
int line;
int matchinNum = 0;
BOOL ispause = FALSE;
pdlg->m_threadRun = TRUE;
g_phead = pdlg->m_maindlg.GetResetData(&g_cmdNum);
pdlg->m_maindlg.EnaResetBn(FALSE);
pdlg->m_imc.SetPauseStatus(FALSE);
pdlg->GreedLedOn();
pdlg->YellowLedOff();
pdlg->SetCurLine(0);
pdata = g_phead + pdlg->GetCurLine();
pdlg->m_imc.SetData16(startpath1Loc, -1, SEL_IFIFO);
while(pdata != NULL && !pdlg->m_threadReset)
{
line = pdlg->GetCurLine();
if(line >= g_cmdNum) break;
pdata = g_phead + line;
if(pdata->type == CMD_END) break;
pdlg->SetCurLine(line + 1);
pdata->isWT = 0;
while(!pdlg->RunAll(pdata)){
if(pdlg->m_threadReset) break;
Sleep(10);
};
}
pdlg->WaitAllOver();//等待运动完成
pdlg->m_threadRun = FALSE;
if(g_phead) delete [] g_phead;
g_phead = NULL;
pdlg->m_maindlg.EnaResetBn(TRUE);
pdlg->GreedLedOff();
pdlg->YellowLedOn();
return 0;
}
//急停按钮需要执行的线程,不运行运动控制指令
PROGRAM_DATA *g_phead_em;
int g_cmdNum_em;
int g_emLine;
UINT EmstopThreadRun(PVOID param)
{
CIMC_GenericDlg* pdlg = (CIMC_GenericDlg*)param;
PROGRAM_DATA *pdata; //编程数据
int line;
int matchinNum = 0;
BOOL ispause = FALSE;
pdlg->m_EmstopRun = TRUE;
g_phead_em = pdlg->m_maindlg.GetEmstopData(&g_cmdNum_em);
pdlg->m_imc.SetPauseStatus(FALSE);
g_emLine = 0;
pdata = g_phead_em + g_emLine;
pdlg->m_imc.SetData16(startpath1Loc, -1, SEL_IFIFO);
while(pdata != NULL/* && !pdlg->m_threadReset*/)
{
line = g_emLine;
if(line >= g_cmdNum_em) break;
pdata = g_phead_em + line;
if(pdata->type == CMD_END) break;
g_emLine ++;
pdata->isWT = 0;
while(!pdlg->RunEmstop(pdata)){
// if(pdlg->m_threadReset) break;
Sleep(10);
};
}
pdlg->WaitAllOver();//等待运动完成
pdlg->m_EmstopRun = FALSE;
if(g_phead_em) delete [] g_phead_em;
g_phead_em = NULL;
// pdlg->m_maindlg.EnaResetBn(TRUE);
// pdlg->GreedLedOff();
// pdlg->YellowLedOn();
return 0;
}
BOOL CIMC_GenericDlg::RunAll(PROGRAM_DATA *pdata)
{
switch(pdata->type)
{
case CMD_LINKAGE: return LineMulFun(pdata); //多轴联动
case CMD_ARC: return ArcFun(pdata); //圆弧
case CMD_OUTPUT: return OutputFun(pdata); //输出
case CMD_INPUT: return InputFun(pdata); //输入
case CMD_JUMP: SetCurLine(pdata->jumpLine-1); return TRUE;//跳转
case CMD_LOOP: return LoopFun(pdata); //循环开始
case CMD_DELAY: return DelayFun(pdata); //延时
case CMD_GOHOME: return GohomeFun(pdata); //回零
case CMD_GHWHIRL: return WhirlFun(pdata); //回零
case CMD_VEL: return VelFun(pdata); //匀速
case CMD_POS: return PosFun(pdata); //点位
case CMD_WAIT: return WaitFun(pdata); //等待
case CMD_END: break;//程序结束
case CMD_WEND: break;//循环结束
}
return TRUE;
}
BOOL CIMC_GenericDlg::RunEmstop(PROGRAM_DATA *pdata)
{
switch(pdata->type)
{
// case CMD_LINKAGE: return LineMulFun(pdata); //多轴联动
// case CMD_ARC: return ArcFun(pdata); //圆弧
case CMD_OUTPUT: return OutputFun(pdata); //输出
case CMD_INPUT: return InputFun(pdata); //输入
case CMD_JUMP: g_emLine = pdata->jumpLine-1; return TRUE;//跳转
case CMD_LOOP: return LoopFun_em(pdata); //循环开始
// case CMD_DELAY: return DelayFun(pdata); //延时
// case CMD_GOHOME: return GohomeFun(pdata); //回零
// case CMD_GHWHIRL: return WhirlFun(pdata); //回零
// case CMD_VEL: return VelFun(pdata); //匀速
// case CMD_POS: return PosFun(pdata); //点位
// case CMD_WAIT: return WaitFun(pdata); //等待
case CMD_END: break;//程序结束
case CMD_WEND: break;//循环结束
}
return TRUE;
}
int CIMC_GenericDlg::GetUseFIFO(PROGRAM_DATA *pdata)
{
return SEL_PFIFO1;
}
BOOL CIMC_GenericDlg::WaitAllOver()
{//等待所有运动结束
short count[MAX_NAXIS], count1, axis, i;
int isOk;
Sleep(100);
while(!m_threadReset){//等待运动完成
if(m_imc.GetData16(PFIFOcnt1Loc, &count1) == IMC_OK){
if(count1 == 0) break;
}
while(m_threadPause && !m_threadStop && !m_threadReset){
Sleep(50);//暂停
}
Sleep(50);
}
while(!m_threadReset){//等待运动完成
isOk = TRUE;
if(m_imc.GetMoving(count) == IMC_OK)
{
for(i=0; i<g_Naxis; i++){
axis = g_factcfg.g_mapAxis[i];
if(count[axis]) isOk = FALSE;
}
if(isOk)
break;
}
while(m_threadPause && !m_threadStop && !m_threadReset){
Sleep(50);//暂停
}
Sleep(50);
}
return TRUE;
}
BOOL CIMC_GenericDlg::DelayFun(PROGRAM_DATA *pdata)
{
long time;
WaitAllOver();
time = pdata->delay;
while(time > 0){
if(time > 500){
Sleep(500);
time -= 500;
}else{
Sleep(time);
time = 0;
}
}
return TRUE;
int fifo = GetUseFIFO(pdata);
if(m_imc.WaitTime(pdata->delay, fifo) == IMC_OK)
return TRUE;
return FALSE;
}
BOOL CIMC_GenericDlg::LoopFun(PROGRAM_DATA *pdata)
{
DWORD i, index;
PROGRAM_DATA * pd;
for(i=0; i<pdata->loopNum; i++)
{
index = pdata->jumpLine-1;
pd = g_phead + index;
while(pd && !m_threadReset && index < g_cmdNum)
{
if(pd->type == CMD_WEND) break;
while(!RunAll(pd)){
if(m_threadReset) break;
Sleep(10);
}
index ++;
pd = g_phead + index;
}
}
return TRUE;
}
BOOL CIMC_GenericDlg::LoopFun_em(PROGRAM_DATA *pdata)
{
DWORD i, index;
PROGRAM_DATA * pd;
for(i=0; i<pdata->loopNum; i++)
{
index = pdata->jumpLine-1;
pd = g_phead_em + index;
while(pd/* && !m_threadReset */&& index < g_cmdNum_em)
{
if(pd->type == CMD_WEND) break;
while(!RunEmstop(pd)){
if(m_threadReset) break;
Sleep(10);
}
index ++;
pd = g_phead_em + index;
}
}
return TRUE;
}
BOOL CIMC_GenericDlg::isInterP()
{
if((GetCurLine() + 1) >= g_cmdNum)
return FALSE;
else{
PROGRAM_DATA *ptmp = g_phead + (GetCurLine() + 1);
// if(ptmp->type == CMD_LINKAGE || ptmp->type == CMD_ARC)
if(ptmp->type == CMD_WAIT || ptmp->type == CMD_DELAY)
return FALSE;
else return TRUE;
}
}
BOOL CIMC_GenericDlg::LineMulFun(PROGRAM_DATA *pdata)
{
int fifo = GetUseFIFO(pdata);
BOOL isP = isInterP();
if(m_imc.LineMulCtrl(pdata, fifo, isP) == IMC_OK)
return TRUE;
return FALSE;
}
BOOL CIMC_GenericDlg::ArcFun(PROGRAM_DATA *pdata)
{
int fifo = GetUseFIFO(pdata);
BOOL isP = isInterP();
if(m_imc.ArcCtrl(pdata, fifo, isP) == IMC_OK)
return TRUE;
return FALSE;
}
BOOL CIMC_GenericDlg::OutputFun(PROGRAM_DATA *pdata)
{
int fifo = GetUseFIFO(pdata);
LONGLONG time;
if(m_imc.OutPutCtrl(pdata, fifo) == IMC_OK){
if(pdata->InSel & 0xFF){
StartTimes();
while(1)
{
time = GetTimems();
if(time > pdata->delay){//超时
#ifdef CHANGE_DATA_0
if(m_imc.OutPutCtrl(pdata->OutputBit, ((pdata->InSel>>8) & 0xFF), fifo) == IMC_OK)
#else
if(m_imc.OutPutCtrl((pdata->Output>> 8) & 0xFF, ((pdata->InSel>>8) & 0xFF), fifo) == IMC_OK)
#endif
return TRUE;
else return FALSE;
}else Sleep(10);
}
}
return TRUE;
}
return FALSE;
}
BOOL CIMC_GenericDlg::InputFun(PROGRAM_DATA *pdata)
{
IMC_STATUS status;
LONGLONG time;
StartTimes();
short val, sel;
while(1){
status = m_imc.InPutCtrl(pdata, &val);
if(status == IMC_OK){
#ifdef CHANGE_DATA_0
if(pdata->InputVal){//联通
#else
if(pdata->Input & 0xFF){//联通
#endif
if(val == 0) break;
}else {//断开
if(val) break;
}
}
time = GetTimems();
if(time > pdata->delay){//超时
if((pdata->InSel>> 8) & 0xFF){//开报警灯
m_imc.LedCtr(LED_RED, LED_ON, SEL_PFIFO1);
}
sel = (pdata->InSel & 0xFF);
if(sel == 0){//暂停
PauseMatchin();
}else if(sel == 1){//跳转
SetCurLine(pdata->jumpLine-1);
}else if(sel == 2){//无动作
}
if(pdata->homeMode){
if(pdata->homeBit <= g_warnNum && pdata->homeBit > 0)
MessageBox(g_warn[pdata->homeBit - 1].warn, _T("提示"));
}
break;
}else
Sleep(20);
}
return TRUE;
}
BOOL CIMC_GenericDlg::GohomeFun(PROGRAM_DATA *pdata)
{
long i, k=0, axis[MAX_NAXIS];
int fifo = GetUseFIFO(pdata);
if(pdata->homeMode == 0)//直接回零
{
// m_imc.GohomeSynCtrl(pdata, fifo);
m_imc.GohomeSortCtrl(pdata, fifo);
}else if(pdata->homeMode == 1)//搜零
{
if(pdata->homeBit == 0) return TRUE;
short data,n, sort[MAX_NAXIS];
for(i=0; i<g_Naxis; i++){
if(pdata->homeBit & (1<<i)){
axis[k] = i;
sort[k++] = pdata->homeSort[i];
}
}
for(n=0; n<g_Naxis; n++){
for(i=0; i<k; i++){
if(sort[i] == n){//查找回零顺序相同的轴号
// m_imc.SetData16(homedLoc, 0, g_factcfg.g_mapAxis[axis[i]]);
if(m_imc.IsOfHomed(axis[i])){
if(g_cfg.homeDir[axis[i]])//往负方向搜零,需要往正方向移动一点点
m_imc.Jog(MOVE_HOMED_VEL, axis[i]);
else
m_imc.Jog(-(MOVE_HOMED_VEL), axis[i]);
while(m_imc.IsOfHomed(axis[i]) && !m_threadReset);
m_imc.Jog(0, axis[i]);
}
m_imc.FindHome(g_cfg.homeDir[axis[i]], axis[i]);
}
}
Sleep(10);
for(i=0; i<k; i++){
if(sort[i] == n){//查找回零顺序相同的轴号
data = 1;
while(!m_threadReset){
// if(m_imc.GetData16(homedLoc, &data, g_factcfg.g_mapAxis[axis[i]]) == IMC_OK){
if(m_imc.GetData16(movingLoc, &data, g_factcfg.g_mapAxis[axis[i]]) == IMC_OK){
if(data == 0)
break;
else
Sleep(10);
}else Sleep(10);
}
}
}
}
m_imc.SetData16(startpath1Loc, -1, SEL_IFIFO);
m_imc.SetData16(startpath2Loc, -1, SEL_IFIFO);
}else if(pdata->homeMode == 2)//
{
for(i=0; i<g_Naxis; i++)
{
if(pdata->homeBit & (1<<i)){
axis[k++] = g_factcfg.g_mapAxis[i];
}
}
for(i=0; i<k; i++)
m_imc.SetCurHome(axis[i]);
}
return TRUE;
}
BOOL CIMC_GenericDlg::WhirlFun(PROGRAM_DATA *pdata)
{
short data = 0;
if(pdata->isWT == 0){
int fifo = GetUseFIFO(pdata);
m_imc.GetData16(aioLoc, &data, pdata->homeMode);
if(data & 0x4){//常开
m_imc.FindHomeWhirl((pdata->homeBit >> 16) & 0xFF, (pdata->homeBit >> 24) & 0xFF, pdata->homeMode, fifo);
}else{//常闭
m_imc.FindHomeWhirl(pdata->homeBit & 0xFF, (pdata->homeBit >> 8) & 0xFF, pdata->homeMode, fifo);
}
pdata->isWT = 1;
}
if(pdata->isWT == 1){
m_imc.GetData16(homedLoc, &data, pdata->homeMode);
if(data == 0)
return FALSE;
pdata->isWT = 0;
}
return TRUE;
}
BOOL CIMC_GenericDlg::VelFun(PROGRAM_DATA *pdata)
{
int fifo = GetUseFIFO(pdata);
m_imc.VelCtrl(pdata, fifo);
return TRUE;
}
BOOL CIMC_GenericDlg::PosFun(PROGRAM_DATA *pdata)
{
int fifo = GetUseFIFO(pdata);
m_imc.PosCtrl(pdata, fifo);
return TRUE;
}
BOOL CIMC_GenericDlg::WaitFun(PROGRAM_DATA *pdata)
{
// short count;
short count[MAX_NAXIS], axis, ok = TRUE;
// m_count ++;
// int fifo = GetUseFIFO(pdata);
// m_imc.SetData16(user16b1Loc, m_count, fifo);
/* if(pdata->WTbit == 0){//等待插补停止
while(!m_threadReset){
if(IMC_OK == m_imc.GetData16(pathmoving1Loc, &count[0], 0)){
if(0 == count[0]) break;
}
Sleep(50);
}
}else if(pdata->WTbit == 1){//等待点到点运动停止*/
/* while(!m_threadReset){
for(int i=0; i<g_Naxis; i++){
long axis = g_factcfg.g_mapAxis[i];
m_imc.GetData16(mcsgoLoc, &count[i], axis);
}
for(int i=0; i<g_Naxis; i++){
if(count[i]) break;//只要有1个开始运行就退出
}
}*/
while(!m_threadReset){
ok = TRUE;
Sleep(50);
if(m_imc.GetMoving(count) == IMC_OK)
{
for(int i=0; i<g_Naxis; i++){
axis = g_factcfg.g_mapAxis[i];
if(count[axis]) ok = FALSE;
}
if(ok)
break;
}
while(m_threadPause && !m_threadStop && !m_threadReset){
Sleep(50);//暂停
}
}
// }
// Sleep(50);
return TRUE;
}
BOOL CIMC_GenericDlg::DebugVersion()
{
#ifdef TRY_VERSION
#endif
return TRUE;
}
void CIMC_GenericDlg::gotoPos_singleAxis(long axis,long velType,WORD velRatio,double pos)
{
PROGRAM_DATA pdata;
pdata.vel = velType;
pdata.velRatio = velRatio;
pdata.axis = axis;
pdata.pos[0] = pos;
// pdata->isWT = ((CButton*)GetDlgItem(IDC_CHECK1))->GetCheck();
pdata.InSel = 0;
PosFun(&pdata);
}
void CIMC_GenericDlg::gotoPos_MultiAxis(char cmdType,double velRatio,double X,double Y,double Z)
{
PROGRAM_DATA pdata;
memset(&pdata, 0, sizeof(PROGRAM_DATA));
pdata.type = CMD_LINKAGE;
pdata.vel = cmdType;//G00,G01
pdata.velRatio = velRatio;
pdata.InSel = 0;//绝对位置0,相对位置1
pdata.posBit = 0;
for(int j=0; j<3; j++)
{
//if(j==4)
// continue;
pdata.posBit |= (1 << j);
}
pdata.pos[0] = X;
pdata.pos[1] = Y;//-343.5+36.22
pdata.pos[2] = Z;
pdata.pos[3] = 0;
pdata.pos[4] = 0;
pdata.pos[5] = 0;
LineMulFun(&pdata);
}
| [
"[email protected]"
] | |
6b86a34e79cd0f344935b8938b8403debff5479e | 863f94592b40965a10893fa14ee35037160c3c1f | /IML/Operations/OperationParam.cpp | 9264e44924d5cddc78b19f277388c261b88bcbe2 | [] | no_license | ihristova11/IML | 9fa5cb339841d1f8dc5f684cf435538dbd454b1f | ae6594ff22aad31d1ca116542fd91eccc1ccc060 | refs/heads/main | 2023-02-13T22:21:20.237106 | 2021-01-09T16:43:44 | 2021-01-09T16:43:44 | 324,556,678 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 589 | cpp | #include "OperationParam.h"
OperationParam::OperationParam()
: arguments(), attributes() { }
OperationParam::OperationParam(std::vector<double> args, std::vector<std::string> attributes)
:arguments(args), attributes(attributes) { }
std::vector<double> OperationParam::getArguments() const
{
return this->arguments;
}
std::vector<std::string> OperationParam::getAttributes() const
{
return this->attributes;
}
void OperationParam::addArg(double arg)
{
this->arguments.push_back(arg);
}
void OperationParam::addAttr(const std::string& attr)
{
this->attributes.push_back(attr);
}
| [
"[email protected]"
] | |
f38f5f0153a8af78027d698edbdcae9a6d0e20d5 | d25ce8e431af70e699ca420dd6f0968cf82afea0 | /Programmers/Level1/Gym_suit.cpp | cdf029e7004c98d7d1bd3a73b290ef061bc65db0 | [] | no_license | taehee-kim-dev/Problem-solving | d30fe67673056ba75cdb14ae4ec68be040afeea7 | c0fb94500a0a43fafcf0a5878ae4e6e3f362ec27 | refs/heads/master | 2021-09-28T10:47:43.286288 | 2021-09-14T17:05:09 | 2021-09-14T17:05:09 | 203,376,052 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,113 | cpp | #include <string>
#include <vector>
using namespace std;
int solution(int n, vector<int> lost, vector<int> reserve) {
int answer = 0;
// 전체 학생 크기 + 1 만큼 lost, reserve에 관한 bool 벡터를 모두 false로 초기화하여 만든다.
vector<bool> lost_vec(n + 1, false);
vector<bool> reserve_vec(n + 1, false);
// lost vector, reserve vector 각각에 존재하는 학생번호를
// bool vector의 인덱스로 하여 true값으로 바꿈.
for(int i = 0; i < lost.size(); i++){
lost_vec[lost[i]] = true;
}
for(int i = 0; i < reserve.size(); i++){
reserve_vec[reserve[i]] = true;
}
// 여벌 체육복을 가져온 학생중에서 체육복을 도난당한 학생은,
// 결국 도난당하지도 않고, 여벌 체육복을 가져오지도 않은 학생과 입장이 같다.
// 따라서, lost_vec과 reserve_vec에서 같은 인덱스에서 모두 true값이면,
// false로 둘다 바꿔준다.
for(int i = 1; i <= n; i++){
if(lost_vec[i] == true && reserve_vec[i] == true){
lost_vec[i] = false;
reserve_vec[i] = false;
}
}
// 이제 여벌 체육복을 가져온 학생과 체육복을 도난당한 학생중에 겹치는 학생은 없다.
/*
체육복을 도난당한 학생들을 검사한다.
case 1) 체육복을 도난당한 학생의 번호 - 1 학생이 여벌 체육복을 가져왔는지 먼저 확인하고,
가져왔다면 빌린다.
즉, reserve_vec, lost_vec에서 빌린 학생의 번호와 빌려준 학생의 번호를 각각 인덱스로하여
false값으로 바꾼다.
빌렸다면 체육복을 도난당한 다음 학생을 검사한다.
case 2) 만약 체육복을 도난당한 학생의 번호 - 1 학생이 여벌 체육복을 가져오지 않았다면,
체육복을 도난당한 학생의 번호 + 1 학생이 여벌 체육복을 가져왔는지 확인한다.
가져왔다면 빌린다.
빌렸다면 체육복을 도난당한 다음 학생을 검사한다.
case 3) 위 두 케이스에 해당하지 않으면, 체육복을 도난당한 다음 학생을 검사한다.
*/
for(int i = 1; i <= n; i++){
if(lost_vec[i] == true){
if(reserve_vec[i - 1] == true){
reserve_vec[i - 1] = false;
lost_vec[i] = false;
continue;
}
if(reserve_vec[i + 1] == true){
reserve_vec[i + 1] = false;
lost_vec[i] = false;
continue;
}
}
}
// 체육수업을 들을 수 있는 학생의 최댓값 = 전체 학생 수 n으로 놓는다.
answer = n;
// lost_vec을 처음부터 끝까지 검사하면서,
// 체육복을 도난당했으나 빌리지 못한 학생을 만날 때 마다 answer의 값을 1씩 감소시킨다.
for(int i = 1; i <= n; i++){
if(lost_vec[i] == true)
answer--;
}
return answer;
} | [
"[email protected]"
] | |
c67115edbdbd31e3f8f386dca3ad00742ef3d2db | 61e0508243e8bec1a4bfd420b724df0b99e9779e | /Day2/4.24choices.cpp | eb6eec2f914a78e36f5b3b874e799b438ceeda5e | [] | no_license | zyrainy/New | 014f6b24f8bcd25ac4112ff8337229774f96eb53 | 2d4ff9a05fc96f492d0175b407ed5fe432f555bd | refs/heads/master | 2022-11-22T01:38:32.860725 | 2020-07-28T09:35:56 | 2020-07-28T09:35:56 | 275,969,941 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 789 | cpp | //choices.cpp -- array variations
#include <iostream>
#include<vector>
#include<array>
int main()
{
using namespace std;
double a1[4] = { 1.2,2.4,3.6,4.8 };
vector<double>a2(4);
a2[0] = 1.0 / 3.0;
a2[1] = 1.0 / 5.0;
a2[2] = 1.0 / 7.0;
a2[3] = 1.0 / 9.0;
array<double, 4> a3 = { 3.14,2.72,1.62,1.41 };
array<double, 4> a4;
a4 = a3;
cout << "a1[2]: " << a1[2] << " at " << &a1[2] << endl;
cout << "a2[2]: " << a2[2] << " at " << &a2[2] << endl;
cout << "a3[2]: " << a3[2] << " at " << &a3[2] << endl;
cout << "a4[2]: " << a4[2] << " at " << &a4[2] << endl;
a1[-2] = 20.2;
cout << "a1[-2]: " << a1[-2] << " at " << &a1[-2] << endl;
cout << "a3[2]: " << a3[2] << " at " << &a3[2] << endl;
cout << "a4[2]: " << a4[2] << " at " << &a4[2] << endl;
system("pause");
return 0;
} | [
"[email protected]"
] | |
7e53d8005624c1878954f78543efdd966857b33a | 8c8a8af67076b2b7ac9808d614be8e40728d7854 | /jni/Graphics/Camera/Camera2D.hpp | 7f2be70d01afd35a81f214610af20984bab5a1c9 | [] | no_license | MihaiBabiac/Framework | 694d5185c6a394c0a453f9812db327550612eb67 | ad97160286a7fb69d9f3667e2ed736c0a2a0dbfe | refs/heads/master | 2021-05-28T10:14:12.218635 | 2013-07-25T09:51:31 | 2013-07-25T09:51:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,085 | hpp | #ifndef CAMERA2D_HPP
#define CAMERA2D_HPP
#include "Object.hpp"
#include "Maths.hpp"
#include <vector>
using namespace std;
using namespace Math;
class Camera2D
{
public:
Camera2D();
~Camera2D();
void Update(GLfloat delta);
void Transform(Vector2f &vertex) const;
void Link(Object *target=NULL);
void SetIdealPosition(const Vector2f &idealPosition);
Vector2f GetIdealPosition() const;
void SetPosition(const Vector2f &position);
Vector2f GetPosition() const;
void EnableSpringSystem();
void DisableSpringSystem();
void SetSpringConstant(const GLfloat &springConstant);
void SetScale(const GLfloat &scale);
GLfloat GetScale() const;
void RotateDirection(const GLfloat &angle);
void SetDirection(const Vector2f &direction);
Vector2f GetDirection() const;
static void UpdateAll(GLfloat delta);
private:
Vector2f m_position,m_velocity;
Vector2f m_idealPosition;
Object *m_target;
GLfloat m_springConstant,m_dampingConstant;
bool m_useSpringSystem;
GLfloat m_scale;
Vector2f m_direction;
static vector<Camera2D*> s_cameras;
};
#endif
| [
"[email protected]"
] | |
acada27d1ace88c439e8ca6c153c3d4aea3969f8 | 49f88ff91aa582e1a9d5ae5a7014f5c07eab7503 | /gen/third_party/blink/renderer/bindings/modules/v8/v8_input_device_info.cc | fa848353287879b162e31caf1bacb97567d45e53 | [] | no_license | AoEiuV020/kiwibrowser-arm64 | b6c719b5f35d65906ae08503ec32f6775c9bb048 | ae7383776e0978b945e85e54242b4e3f7b930284 | refs/heads/main | 2023-06-01T21:09:33.928929 | 2021-06-22T15:56:53 | 2021-06-22T15:56:53 | 379,186,747 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,818 | cc | // Copyright 2014 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.
// This file has been auto-generated from the Jinja2 template
// third_party/blink/renderer/bindings/templates/interface.cpp.tmpl
// by the script code_generator_v8.py.
// DO NOT MODIFY!
// clang-format off
#include "third_party/blink/renderer/bindings/modules/v8/v8_input_device_info.h"
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/bindings/core/v8/exception_state.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.h"
#include "third_party/blink/renderer/bindings/modules/v8/v8_media_track_capabilities.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/platform/bindings/runtime_call_stats.h"
#include "third_party/blink/renderer/platform/bindings/v8_object_constructor.h"
#include "third_party/blink/renderer/platform/wtf/get_ptr.h"
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo V8InputDeviceInfo::wrapperTypeInfo = {
gin::kEmbedderBlink,
V8InputDeviceInfo::domTemplate,
nullptr,
"InputDeviceInfo",
&V8MediaDeviceInfo::wrapperTypeInfo,
WrapperTypeInfo::kWrapperTypeObjectPrototype,
WrapperTypeInfo::kObjectClassId,
WrapperTypeInfo::kNotInheritFromActiveScriptWrappable,
};
#if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__)
#pragma clang diagnostic pop
#endif
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in InputDeviceInfo.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// platform/bindings/ScriptWrappable.h.
const WrapperTypeInfo& InputDeviceInfo::wrapper_type_info_ = V8InputDeviceInfo::wrapperTypeInfo;
// not [ActiveScriptWrappable]
static_assert(
!std::is_base_of<ActiveScriptWrappableBase, InputDeviceInfo>::value,
"InputDeviceInfo inherits from ActiveScriptWrappable<>, but is not specifying "
"[ActiveScriptWrappable] extended attribute in the IDL file. "
"Be consistent.");
static_assert(
std::is_same<decltype(&InputDeviceInfo::HasPendingActivity),
decltype(&ScriptWrappable::HasPendingActivity)>::value,
"InputDeviceInfo is overriding hasPendingActivity(), but is not specifying "
"[ActiveScriptWrappable] extended attribute in the IDL file. "
"Be consistent.");
namespace InputDeviceInfoV8Internal {
static void getCapabilitiesMethod(const v8::FunctionCallbackInfo<v8::Value>& info) {
InputDeviceInfo* impl = V8InputDeviceInfo::ToImpl(info.Holder());
MediaTrackCapabilities result;
impl->getCapabilities(result);
V8SetReturnValue(info, result);
}
} // namespace InputDeviceInfoV8Internal
void V8InputDeviceInfo::getCapabilitiesMethodCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_InputDeviceInfo_getCapabilities");
InputDeviceInfoV8Internal::getCapabilitiesMethod(info);
}
static const V8DOMConfiguration::MethodConfiguration V8InputDeviceInfoMethods[] = {
{"getCapabilities", V8InputDeviceInfo::getCapabilitiesMethodCallback, 0, v8::None, V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kDoNotCheckAccess, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAllWorlds},
};
static void installV8InputDeviceInfoTemplate(
v8::Isolate* isolate,
const DOMWrapperWorld& world,
v8::Local<v8::FunctionTemplate> interfaceTemplate) {
// Initialize the interface object's template.
V8DOMConfiguration::InitializeDOMInterfaceTemplate(isolate, interfaceTemplate, V8InputDeviceInfo::wrapperTypeInfo.interface_name, V8MediaDeviceInfo::domTemplate(isolate, world), V8InputDeviceInfo::internalFieldCount);
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interfaceTemplate);
ALLOW_UNUSED_LOCAL(signature);
v8::Local<v8::ObjectTemplate> instanceTemplate = interfaceTemplate->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instanceTemplate);
v8::Local<v8::ObjectTemplate> prototypeTemplate = interfaceTemplate->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototypeTemplate);
// Register IDL constants, attributes and operations.
V8DOMConfiguration::InstallMethods(
isolate, world, instanceTemplate, prototypeTemplate, interfaceTemplate,
signature, V8InputDeviceInfoMethods, arraysize(V8InputDeviceInfoMethods));
// Custom signature
V8InputDeviceInfo::InstallRuntimeEnabledFeaturesOnTemplate(
isolate, world, interfaceTemplate);
}
void V8InputDeviceInfo::InstallRuntimeEnabledFeaturesOnTemplate(
v8::Isolate* isolate,
const DOMWrapperWorld& world,
v8::Local<v8::FunctionTemplate> interface_template) {
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template);
ALLOW_UNUSED_LOCAL(signature);
v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instance_template);
v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototype_template);
// Register IDL constants, attributes and operations.
// Custom signature
}
v8::Local<v8::FunctionTemplate> V8InputDeviceInfo::domTemplate(v8::Isolate* isolate, const DOMWrapperWorld& world) {
return V8DOMConfiguration::DomClassTemplate(isolate, world, const_cast<WrapperTypeInfo*>(&wrapperTypeInfo), installV8InputDeviceInfoTemplate);
}
bool V8InputDeviceInfo::hasInstance(v8::Local<v8::Value> v8Value, v8::Isolate* isolate) {
return V8PerIsolateData::From(isolate)->HasInstance(&wrapperTypeInfo, v8Value);
}
v8::Local<v8::Object> V8InputDeviceInfo::findInstanceInPrototypeChain(v8::Local<v8::Value> v8Value, v8::Isolate* isolate) {
return V8PerIsolateData::From(isolate)->FindInstanceInPrototypeChain(&wrapperTypeInfo, v8Value);
}
InputDeviceInfo* V8InputDeviceInfo::ToImplWithTypeCheck(v8::Isolate* isolate, v8::Local<v8::Value> value) {
return hasInstance(value, isolate) ? ToImpl(v8::Local<v8::Object>::Cast(value)) : nullptr;
}
InputDeviceInfo* NativeValueTraits<InputDeviceInfo>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) {
InputDeviceInfo* nativeValue = V8InputDeviceInfo::ToImplWithTypeCheck(isolate, value);
if (!nativeValue) {
exceptionState.ThrowTypeError(ExceptionMessages::FailedToConvertJSValue(
"InputDeviceInfo"));
}
return nativeValue;
}
} // namespace blink
| [
"[email protected]"
] | |
ac56c28990aa115e4afb65f1fb70da7687aa67d8 | 6d7f2381b8f1c5c0e0d96156ae36cac12be3017b | /atcoder/abc112/D/main.cpp | 7c2cbeba7b988107b4d038ee44064d841fe74834 | [
"Unlicense"
] | permissive | Johniel/contests | 708ccf944d6aeb0ef0404eec47e8ff7819ea00f0 | 15d465b08cac56e394509bcf8f24764e3dc6ca7d | refs/heads/master | 2023-09-04T07:32:49.822786 | 2023-09-02T13:44:28 | 2023-09-02T13:44:50 | 48,701,889 | 0 | 0 | null | 2019-10-25T09:21:20 | 2015-12-28T16:38:38 | C++ | UTF-8 | C++ | false | false | 996 | cpp | #include <bits/stdc++.h>
#define each(i, c) for (auto& i : c)
#define unless(cond) if (!(cond))
using namespace std;
typedef long long int lli;
typedef unsigned long long ull;
typedef complex<double> point;
template<typename P, typename Q>
ostream& operator << (ostream& os, pair<P, Q> p)
{
os << "(" << p.first << "," << p.second << ")";
return os;
}
template<typename T>
ostream& operator << (ostream& os, vector<T> v)
{
os << "(";
each (i, v) os << i << ",";
os << ")";
return os;
}
int main(int argc, char *argv[])
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, m;
while (cin >> n >> m) {
vector<int> v;
for (int i = 1; i * i < m; ++i) {
if (m % i == 0) {
v.push_back(i);
v.push_back(m / i);
}
}
int x = 1;
each (i, v) {
int y = i * (m / i / n);
if (y) {
int z = y;
if ((m / i) % n) z += i;
x = max(x, __gcd(y, z));
}
}
cout << x << endl;
}
return 0;
}
| [
"[email protected]"
] | |
0539f21914da3f29cddd311cd4a5a00fc0937964 | d939ea588d1b215261b92013e050993b21651f9a | /bda/src/v20200324/model/SegmentCustomizedPortraitPicRequest.cpp | 34814e87710e043b2f5524df90adfaa299fbaa7e | [
"Apache-2.0"
] | permissive | chenxx98/tencentcloud-sdk-cpp | 374e6d1349f8992893ded7aa08f911dd281f1bda | a9e75d321d96504bc3437300d26e371f5f4580a0 | refs/heads/master | 2023-03-27T05:35:50.158432 | 2021-03-26T05:18:10 | 2021-03-26T05:18:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,331 | cpp | /*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <tencentcloud/bda/v20200324/model/SegmentCustomizedPortraitPicRequest.h>
#include <tencentcloud/core/utils/rapidjson/document.h>
#include <tencentcloud/core/utils/rapidjson/writer.h>
#include <tencentcloud/core/utils/rapidjson/stringbuffer.h>
using namespace TencentCloud::Bda::V20200324::Model;
using namespace rapidjson;
using namespace std;
SegmentCustomizedPortraitPicRequest::SegmentCustomizedPortraitPicRequest() :
m_segmentationOptionsHasBeenSet(false),
m_imageHasBeenSet(false),
m_urlHasBeenSet(false)
{
}
string SegmentCustomizedPortraitPicRequest::ToJsonString() const
{
Document d;
d.SetObject();
Document::AllocatorType& allocator = d.GetAllocator();
if (m_segmentationOptionsHasBeenSet)
{
Value iKey(kStringType);
string key = "SegmentationOptions";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(kObjectType).Move(), allocator);
m_segmentationOptions.ToJsonObject(d[key.c_str()], allocator);
}
if (m_imageHasBeenSet)
{
Value iKey(kStringType);
string key = "Image";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_image.c_str(), allocator).Move(), allocator);
}
if (m_urlHasBeenSet)
{
Value iKey(kStringType);
string key = "Url";
iKey.SetString(key.c_str(), allocator);
d.AddMember(iKey, Value(m_url.c_str(), allocator).Move(), allocator);
}
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
return buffer.GetString();
}
SegmentationOptions SegmentCustomizedPortraitPicRequest::GetSegmentationOptions() const
{
return m_segmentationOptions;
}
void SegmentCustomizedPortraitPicRequest::SetSegmentationOptions(const SegmentationOptions& _segmentationOptions)
{
m_segmentationOptions = _segmentationOptions;
m_segmentationOptionsHasBeenSet = true;
}
bool SegmentCustomizedPortraitPicRequest::SegmentationOptionsHasBeenSet() const
{
return m_segmentationOptionsHasBeenSet;
}
string SegmentCustomizedPortraitPicRequest::GetImage() const
{
return m_image;
}
void SegmentCustomizedPortraitPicRequest::SetImage(const string& _image)
{
m_image = _image;
m_imageHasBeenSet = true;
}
bool SegmentCustomizedPortraitPicRequest::ImageHasBeenSet() const
{
return m_imageHasBeenSet;
}
string SegmentCustomizedPortraitPicRequest::GetUrl() const
{
return m_url;
}
void SegmentCustomizedPortraitPicRequest::SetUrl(const string& _url)
{
m_url = _url;
m_urlHasBeenSet = true;
}
bool SegmentCustomizedPortraitPicRequest::UrlHasBeenSet() const
{
return m_urlHasBeenSet;
}
| [
"[email protected]"
] | |
1f6df1f784762929ce8172de05850556ac3832a5 | 207d550014d763922f35240601230644032abba8 | /src/RotatableToolBar.cpp | 08bac296e1bbcf472d07638c8d967fe2ee504f30 | [
"BSD-3-Clause"
] | permissive | neurocod/Qqt | 2101dcb6d7e36ef56844cdecbc5024f256bc77df | 41a73880b2e86114a35e29927549d7503a1c3732 | refs/heads/master | 2022-02-10T22:10:06.693162 | 2022-01-26T21:11:17 | 2022-01-26T21:11:17 | 7,391,315 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,406 | cpp | //RotatableToolBar.cpp by Kostya Kozachuck as neurocod
//BSD license https://github.com/neurocod/Qqt
#include "pch.h"
#include "RotatableToolBar.h"
#ifdef USE_QXT
#include <qxtlabel.h>
#endif
RotatableToolBar::RotatableToolBar(const QString & title, QWidget * parent): QToolBar(title, parent) {
init();
}
RotatableToolBar::RotatableToolBar(QWidget * parent): QToolBar(parent) {
init();
}
void RotatableToolBar::init() {
connect(this, SIGNAL(orientationChanged(Qt::Orientation)), SLOT(onOrientationChanged(Qt::Orientation)));
}
void RotatableToolBar::onOrientationChanged(Qt::Orientation orientation) {
foreach(QAction*act, actions()) {
QWidgetAction*wa = qobject_cast<QWidgetAction*>(act);
if(wa) {
QWidget*w = wa->defaultWidget();
maybeRotate(w, orientation);
}
}
}
void RotatableToolBar::maybeRotate(QWidget*w, Qt::Orientation orientation) {
if(!w)
return;
QSlider*slider = qobject_cast<QSlider*>(w);
if(slider) {
slider->setOrientation(orientation);
return;
}
QTabBar*tabBar = qobject_cast<QTabBar*>(w);
if(tabBar) {
tabBar->setShape(Qt::Vertical==orientation ?
QTabBar::RoundedEast: QTabBar::RoundedNorth);
return;
}
#ifdef USE_QXT
QxtLabel*qxtLabel = qobject_cast<QxtLabel*>(w);
if(qxtLabel) {
qxtLabel->setRotation(Qt::Horizontal==orientation ?
Qxt::NoRotation: Qxt::Clockwise);
return;
}
#endif
} | [
"[email protected]"
] | |
15cb4855d1245776be3f065ff6a6a36e7054f193 | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/git/hunk_6934.cpp | c03f096e852feb89fc40656d5cc315a30c8fd196 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 591 | cpp | args[i++] = path;
args[i] = NULL;
- if (run_command_v_opt_cd_env(args, 0, NULL, env))
- die("There was a problem with the editor %s.", editor);
+ failed = run_command_v_opt_cd_env(args, 0, NULL, env);
strbuf_release(&arg0);
+ if (failed)
+ return error("There was a problem with the editor '%s'.",
+ editor);
}
if (!buffer)
- return;
+ return 0;
if (strbuf_read_file(buffer, path, 0) < 0)
- die("could not read message file '%s': %s",
- path, strerror(errno));
+ return error("could not read file '%s': %s",
+ path, strerror(errno));
+ return 0;
}
| [
"[email protected]"
] | |
7125178bfcabe84ec659a54efddd88b4a57436e3 | a4b50a3cb08a6b88cd6415c805101df344b1b365 | /download.cpp | a5fccdd7ae5f19deab5a08ef1ce12d19700f8192 | [] | no_license | akw0088/openssl | 30b9ba7132a117b85fca6168f780847419a880fd | 9212b9de3da978da69222b0ed9444025f881b70d | refs/heads/master | 2020-11-27T14:51:38.345150 | 2020-01-02T04:07:45 | 2020-01-02T04:07:45 | 229,498,688 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,534 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <errno.h>
#ifdef WIN32
#include <windows.h>
#include <winsock.h>
#pragma comment(lib, "wsock32.lib")
typedef int socklen_t;
#else
#include <unistd.h>
#include <fcntl.h>
#include <dlfcn.h>
#include <sys/select.h>
#include <sys/types.h>
#include <sys/time.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define closesocket close
typedef int SOCKET;
#define SOCKET_ERROR -1
#define INVALID_SOCKET -1
#endif
#define MAX(x,y) (x) > (y) ? (x) : (y)
#define MIN(x,y) (x) < (y) ? (x) : (y)
char *get_file(char *filename, unsigned int *size)
{
FILE *file;
char *buffer;
int file_size, bytes_read;
file = fopen(filename, "rb");
if (file == NULL)
return 0;
fseek(file, 0, SEEK_END);
file_size = ftell(file);
fseek(file, 0, SEEK_SET);
buffer = new char [file_size + 1];
bytes_read = (int)fread(buffer, sizeof(char), file_size, file);
if (bytes_read != file_size)
{
delete [] buffer;
fclose(file);
return 0;
}
fclose(file);
buffer[file_size] = '\0';
if (size != NULL)
{
*size = file_size;
}
return buffer;
}
int write_file(char *filename, const char *bytes, int size)
{
FILE *fp = fopen(filename, "wb");
int ret;
if (fp == NULL)
{
perror("Unable to open file for writing");
return -1;
}
ret = fwrite(bytes, sizeof(char), size, fp);
if (ret != size)
{
printf("fwrite didnt write all data\n");
fclose(fp);
return -1;
}
fclose(fp);
return 0;
}
int file_download(char *ip_str, unsigned short int port, char *response, int size, unsigned int *download_size, char *file_name)
{
struct sockaddr_in servaddr;
SOCKET sock;
int ret;
sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
memset(&servaddr, 0, sizeof(struct sockaddr_in));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(ip_str);
servaddr.sin_port = htons(port);
// 3 way handshake
printf("Attempting to connect to %s\n", ip_str);
ret = connect(sock, (struct sockaddr *)&servaddr, sizeof(struct sockaddr_in));
if (ret == SOCKET_ERROR)
{
#ifdef _WIN32
ret = WSAGetLastError();
switch (ret)
{
case WSAETIMEDOUT:
printf("Fatal Error: Connection timed out.\n");
break;
case WSAECONNREFUSED:
printf("Fatal Error: Connection refused\n");
break;
case WSAEHOSTUNREACH:
printf("Fatal Error: Router sent ICMP packet (destination unreachable)\n");
break;
default:
printf("Fatal Error: %d\n", ret);
break;
}
#else
ret = errno;
switch(ret)
{
case ENETUNREACH:
printf("Fatal Error: The network is unreachable from this host at this time.\n(Bad IP address)\n");
break;
case ETIMEDOUT:
printf("Fatal Error: Connecting timed out.\n");
break;
case ECONNREFUSED:
printf("Fatal Error: Connection refused\n");
break;
case EHOSTUNREACH:
printf("Fatal Error: router sent ICMP packet (destination unreachable)\n");
break;
default:
printf("Fatal Error: %d\n", ret);
break;
}
#endif
return -1;
}
printf("TCP handshake completed\n");
memset(response, 0, size);
int expected_size = 0;
recv(sock, (char *)&expected_size, 4, 0);
recv(sock, (char *)file_name, 128, 0);
while (*download_size < expected_size)
{
*download_size += recv(sock, &response[*download_size], expected_size - *download_size, 0);
}
closesocket(sock);
return 0;
}
int file_upload(char *file, unsigned short port)
{
int connfd;
unsigned int size = sizeof(struct sockaddr_in);
struct sockaddr_in servaddr, client;
time_t ticks;
int listenfd;
#ifdef _WIN32
WSADATA WSAData;
WSAStartup(MAKEWORD(2, 0), &WSAData);
#endif
listenfd = socket(AF_INET, SOCK_STREAM, 0);
if (listenfd == -1)
{
perror("socket error");
return -1;
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(port);
if ((::bind(listenfd, (struct sockaddr *)&servaddr, sizeof(servaddr))) == -1)
{
perror("bind error");
return 0;
}
printf("Server listening on: %s:%d\n", inet_ntoa(servaddr.sin_addr), htons(servaddr.sin_port));
if (listen(listenfd, 3) == -1)
{
perror("listen error");
return -1;
}
for (;;)
{
char response[1024] = { 0 };
printf("listening for connections...\n");
connfd = accept(listenfd, (struct sockaddr *)&client, (socklen_t *)&size);
if (connfd == INVALID_SOCKET)
continue;
ticks = time(NULL);
snprintf(response, sizeof(response), "%.24s\r\n", ctime(&ticks));
printf("Client: %s - %s", inet_ntoa(client.sin_addr), response);
unsigned int file_size = 0;
char *data = get_file(file, &file_size);
char file_name[128] = { 0 };
memcpy(file_name, file, MIN(127, strlen(file)));
send(connfd, (char *)&file_size, sizeof(int), 0);
send(connfd, (char *)&file_name, 128, 0);
send(connfd, data, file_size, 0);
closesocket(connfd);
}
return 0;
}
void StripChars(const char *in, char *out, char *stripc)
{
while (*in)
{
bool flag = false;
int length = strlen(stripc);
for(int i = 0; i < length; i++)
{
if (*in == stripc[i])
{
flag = true;
break;
}
}
if (flag)
{
in++;
continue;
}
*out++ = *in++;
}
*out = 0;
}
int main(int argc, char *argv[])
{
unsigned short port = 65535;
unsigned int size = 0;
if (argc < 4)
{
printf("Usage: download ip port max_size\r\n");
return 0;
}
port = atoi(argv[2]);
size = atoi(argv[3]);
printf("Allocating %d bytes\r\n", size);
char *response = (char *)malloc(size);
if (response == NULL)
{
perror("malloc failed");
}
unsigned int download_size = 0;
char file_name[128] = {0};
printf("Attempting to download file from ip %s port %d\r\n", argv[1], (int)port);
int ret = file_download(argv[1], port, response, size, &download_size, file_name);
if (ret != 0)
{
printf("Download failed\r\n");
return 0;
}
printf("Download complete\r\n");
printf("Got %d bytes file name %s\r\n", download_size, file_name);
char new_filename[256] = {0};
char strip_filename[256] = {0};
StripChars(file_name, strip_filename, (char *)".\\/;:*?\"<>|");
sprintf(new_filename, "downloaded_%s", strip_filename);
printf("Saving as file name %s\r\n", new_filename);
write_file(new_filename, response, download_size);
return 0;
}
| [
"[email protected]"
] | |
dfd59dd73bfaa3c6c7b71e6b7c8fd2b76543008f | 8dee139b732fd1ac1f7299211d89508d9485c962 | /Lab1/Lab1PartB/Lab1PartB/Main.cpp | cb1bc9dc121f14e40398d67c7bd8089db3aa260c | [] | no_license | DylanNelson99/Algorithim-Computation4thYear | 95a0cc137c44c14e05daf627eb5de9e0ff2c669a | d6f3ec70c0a409474458c7b9d667679bd53647b4 | refs/heads/master | 2023-05-08T18:24:05.161416 | 2021-06-02T21:15:24 | 2021-06-02T21:15:24 | 350,771,228 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,879 | cpp | //Dylan Nelson - X00144862
//No.8 When you remove virtual in Person class and re-run it ,
//uses the base class printName function.
#include "Customer.h"
#include "Employee.h"
#include <iostream>
void printArray(Person* []);
int main() {
Employee* employee = new Employee("Tom", 34000.00);
cout << employee->printname() << "\n";
Customer* customer = new Customer("Adam", "and I want to make a complaint");
cout << customer->printname() << "\n";
Person* peopleArray[6];
peopleArray[0] = employee;
peopleArray[1] = customer;
peopleArray[2] = new Employee("Tod", 15000);
peopleArray[3] = new Employee("Dylan", 10000);
peopleArray[4] = new Customer("Michael", "and I want to make a complaint");
peopleArray[5] = new Customer("David", "and I want to make a complaint");
cout << "\n unsorted\n\n";
printArray(peopleArray);
Person* duplicateUnsortedArray[6];
for (int i = 0; i < 6; i++) {
duplicateUnsortedArray[i] = peopleArray[i];
}
Person* personHolder;
for (int i = 0; i < 6; i++) {
for (int j = i + 1; j < 6; j++) {
if (peopleArray[i]->operator>(peopleArray[j])) {
personHolder = peopleArray[i];
peopleArray[i] = peopleArray[j];
peopleArray[j] = personHolder;
}
}
}
cout << "\nArray sorted using operator overloading\n\n";
printArray(peopleArray);
for (int i = 0; i < 6; i++) {
for (int j = i + 1; j < 6; j++) {
if (duplicateUnsortedArray[i]->getName() > duplicateUnsortedArray[j]->getName()) {
personHolder = duplicateUnsortedArray[i];
duplicateUnsortedArray[i] = duplicateUnsortedArray[j];
duplicateUnsortedArray[j] = personHolder;
}
}
}
cout << "\nArray sorted not using operator overloading\n\n";
printArray(duplicateUnsortedArray);
system("pause");
return(0);
}
void printArray(Person* peopleArray[]) {
for (int i = 0; i < 6; i++) {
cout << peopleArray[i]->printname() << "\n";
}
} | [
"[email protected]"
] | |
3a581a660f01acc898798d22d1cde2e419fe39ce | b9575b7d4299110e663a7432381ce7534c234b40 | /4_ExtLib/4.4_GuiFrameworks/4.4.2_HaxeUI/4.4.2.1_SimpleGui/4.4.2.1.1_HaxeuiBackends/4.4.2.1.1.2_haxeui-hxwidgets/4.4.2.1.1.2.3_Dialogs/SimpleMessageDialog/Export/cpp/debug/include/haxe/ui/components/ButtonDefaultTextBehaviour.h | 7b06f5e33ad50adb6ca725be6437c0afb161e646 | [] | no_license | R3D9477/haxe-basics | dc912670731ac891f359c73db68f1a683af03f6a | cd12a1cb250447afa877fc30cf671f00e62717ef | refs/heads/master | 2021-09-02T12:22:55.398965 | 2018-01-02T15:29:40 | 2018-01-02T15:29:40 | 72,667,406 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,280 | h | // GeneratedByHaxe
#ifndef INCLUDED_haxe_ui_components_ButtonDefaultTextBehaviour
#define INCLUDED_haxe_ui_components_ButtonDefaultTextBehaviour
#ifndef HXCPP_H
#include <hxcpp.h>
#endif
#ifndef INCLUDED_haxe_ui_core_Behaviour
#include <haxe/ui/core/Behaviour.h>
#endif
HX_DECLARE_CLASS3(haxe,ui,backend,ComponentBase)
HX_DECLARE_CLASS3(haxe,ui,components,ButtonDefaultTextBehaviour)
HX_DECLARE_CLASS3(haxe,ui,core,Behaviour)
HX_DECLARE_CLASS3(haxe,ui,core,Component)
HX_DECLARE_CLASS3(haxe,ui,core,IClonable)
HX_DECLARE_CLASS3(haxe,ui,core,IComponentBase)
HX_DECLARE_CLASS3(haxe,ui,util,VariantType)
HX_DECLARE_CLASS3(haxe,ui,validation,IValidating)
namespace haxe{
namespace ui{
namespace components{
class HXCPP_CLASS_ATTRIBUTES ButtonDefaultTextBehaviour_obj : public ::haxe::ui::core::Behaviour_obj
{
public:
typedef ::haxe::ui::core::Behaviour_obj super;
typedef ButtonDefaultTextBehaviour_obj OBJ_;
ButtonDefaultTextBehaviour_obj();
public:
enum { _hx_ClassId = 0x01e78abd };
void __construct( ::haxe::ui::core::Component component);
inline void *operator new(size_t inSize, bool inContainer=true,const char *inName="haxe.ui.components.ButtonDefaultTextBehaviour")
{ return hx::Object::operator new(inSize,inContainer,inName); }
inline void *operator new(size_t inSize, int extra)
{ return hx::Object::operator new(inSize+extra,true,"haxe.ui.components.ButtonDefaultTextBehaviour"); }
static hx::ObjectPtr< ButtonDefaultTextBehaviour_obj > __new( ::haxe::ui::core::Component component);
static hx::ObjectPtr< ButtonDefaultTextBehaviour_obj > __alloc(hx::Ctx *_hx_ctx, ::haxe::ui::core::Component component);
static void * _hx_vtable;
static Dynamic __CreateEmpty();
static Dynamic __Create(hx::DynamicArray inArgs);
//~ButtonDefaultTextBehaviour_obj();
HX_DO_RTTI_ALL;
hx::Val __Field(const ::String &inString, hx::PropertyAccess inCallProp);
static void __register();
bool _hx_isInstanceOf(int inClassId);
::String __ToString() const { return HX_HCSTRING("ButtonDefaultTextBehaviour","\x81","\x51","\x2c","\xb8"); }
void set( ::haxe::ui::util::VariantType value);
};
} // end namespace haxe
} // end namespace ui
} // end namespace components
#endif /* INCLUDED_haxe_ui_components_ButtonDefaultTextBehaviour */
| [
"[email protected]"
] | |
7580f0e4479ed15e452716463c113b02d0c81442 | aecf7d390dea95e2d5dbf16c0d84b0ae88f774bb | /mockcpp/tests/3rdparty/testngpp/src/runner/win32/GetLastError.cpp | 355eb5893b5273dac468b69ebde6bd673caa6a37 | [
"Apache-2.0"
] | permissive | AllenWang0217/Testngpp | d92dab8f52db6eb487a27a2b28fe6d34002feedb | c5e809cf5601064d5b15e4a219dce365233400c1 | refs/heads/master | 2020-12-02T23:55:03.133027 | 2017-07-01T11:41:34 | 2017-07-01T11:41:34 | 95,960,251 | 6 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 568 | cpp |
#if defined(_MSC_VER)
#include <windows.h>
#include <testngpp/internal/Error.h>
TESTNGPP_NS_START
void throwLastError()
{
LPVOID lpMsgBuf;
DWORD dw = GetLastError();
FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR) &lpMsgBuf,
0, NULL );
std::string errorMsg((const char*)lpMsgBuf);
LocalFree(lpMsgBuf);
throw Error(errorMsg);
}
TESTNGPP_NS_END
#endif
| [
"[email protected]"
] | |
cb99a4dae8dd652fff95fcdab04b3fa50ad1aabd | b66fa1937db01c5246f38eaeb8415f19f7c87585 | /reverseCLL.cpp | 5599bfe4a466c92ef400d60ebbf51ba68fbe4a3c | [] | no_license | greatsharma/Cpp-Mess | a3db8f0424f1adf1878a84b26ffef372df241a31 | a1c1d084d8d487ee3e6e25590b2fdfd0d2397ffc | refs/heads/master | 2022-11-21T03:28:09.609082 | 2020-07-22T12:31:26 | 2020-07-22T12:31:26 | 281,670,555 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,833 | cpp | #include <iostream>
using namespace std;
class Node
{
private:
int data;
Node *next;
friend class CLL;
public:
Node(int data, Node *next = 0) : data(data), next(next) {}
~Node() {}
};
class CLL
{
private:
static Node *head;
Node *tail;
public:
CLL() : tail(0) {}
void insertAtTail(int);
void reverse();
void reverseIter(Node *curr = head);
void showHeadTail() { cout << " head : " << head << " tail : " << tail; }
int lengthCLL(Node *curr = head, int count = 0);
void display();
void displayReverse(Node *curr = head)
{
if (curr != tail)
{
displayReverse(curr->next);
cout << " " << curr->data;
}
else
cout << " " << curr->data;
}
~CLL() {}
};
Node *CLL::head = 0;
void CLL::insertAtTail(int data)
{
Node *node = new Node(data, head);
if (head)
{
tail->next = node;
tail = node;
}
else
head = tail = node;
}
void CLL::reverse()
{
if (head)
{
Node *curr = head;
Node *temp;
while (curr && curr != tail)
{
temp = curr->next;
if (curr != head)
curr->next = head;
else
{
curr->next = tail;
tail = head;
}
head = curr;
curr = temp;
}
}
}
void CLL::reverseIter(Node *curr)
{
if (curr && curr != tail)
{
Node *temp = curr->next;
if (curr != head)
curr->next = head;
else
{
curr->next = tail;
tail = head;
}
head = curr;
reverseIter(temp);
}
}
int CLL::lengthCLL(Node *curr, int count)
{
if (curr)
{
++count;
lengthCLL(curr->next, count);
}
else
return count;
}
void CLL::display()
{
if (head)
{
Node *curr = head;
while (true)
{
cout << " " << curr->data;
if (curr == tail)
break;
curr = curr->next;
}
}
}
int main()
{
int data;
char ch;
CLL l;
cout << "\nEnter CLL : ";
do
{
cout << "\nEnter node data : ";
cin >> data;
l.insertAtTail(data);
cout << "\nenter 0 to exit : ";
cin >> ch;
} while (ch != '0');
cout << "\nl : ";
l.display();
l.showHeadTail();
// l.reverseIter();
// cout << "\nl it: ";
// l.display();
// l.showHeadTail();
// cout << "\nlength : " << l.lengthCLL();
cout << "\nrev : ";
l.displayReverse();
return 0;
} | [
"[email protected]"
] | |
ab243dbf060cbcd1b88b9e2f18549242e9265e93 | 0e0ce609f762168b37cbf19e40438393ee50e907 | /3D_Demo/Box.h | 3826e4f05899fe80b29cd51c44ab9225d4fc558e | [] | no_license | Vampire-Z-V/D3D11_Demo | 9d37c4571398a482d29ee04f19eb164cf2d96ebe | 54fda29a324ab90a7c5185c83a8ad1c9fe77b797 | refs/heads/master | 2021-01-17T06:28:53.473114 | 2016-08-06T19:18:05 | 2016-08-06T19:18:05 | 64,775,632 | 0 | 0 | null | 2016-08-05T11:30:03 | 2016-08-02T16:58:35 | C++ | UTF-8 | C++ | false | false | 787 | h | #pragma once
#include "D3DApplication.h"
#include "MathHelper.h"
class Box :
public D3DApplication
{
public:
Box(HINSTANCE hInstance);
~Box();
bool Init();
void OnResize();
void UpdateScence(float dt);
void DrawScence();
void OnMouseDown(WPARAM btnState, int x, int y);
void OnMouseUp(WPARAM btnState, int x, int y);
void OnMouseMove(WPARAM btnState, int x, int y);
private:
void BuildGeometryBuffers();
void BuildFX();
void BuildVertexLayout();
private:
ID3D11Buffer *mBoxVB;
ID3D11Buffer *mBoxIB;
ID3DX11Effect *mFX;
ID3DX11EffectTechnique *mTech;
ID3DX11EffectMatrixVariable *mfxWorldViewProj;
ID3D11InputLayout *mInputLayout;
XMFLOAT4X4 mWorld;
XMFLOAT4X4 mView;
XMFLOAT4X4 mProj;
float mTheta;
float mPhi;
float mRadius;
POINT mLastMousePos;
};
| [
"[email protected]"
] | |
1664aab9758e858380b8d23d24b91b361c586a3f | e8d19f6754fd4c3a1506c96ace3015e8c562e23e | /xmas_star_to_and_fro/xmas_star_to_and_fro.ino | f2a976b0047a57565c8dd981fe7f8a0614992a04 | [
"Apache-2.0"
] | permissive | benejo/arduino_stepper_A4988 | 7f326a295ce9113b989e58cd6de875ddec874e64 | 166013845e7fbdd849eab929ffe12c651a3ded1e | refs/heads/master | 2021-08-30T19:19:12.401503 | 2017-12-19T04:46:30 | 2017-12-19T04:46:30 | 114,361,908 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,193 | ino |
// User variables
int revs = 10;
int _fast = 200;
int index_value = 800;
// Constants
int i = 0;
int index;
int motion = 0;
int count = 0;
int halfrevs = revs / 2;
int _slow = _fast * 2;
int delay_speed;
char cw_dir = HIGH;
char acw_dir = LOW;
char set_dir;
char previous_motion = digitalRead(10);
void setup()
{
pinMode(6, OUTPUT); //Enable
pinMode(5, OUTPUT); //Step
pinMode(4, OUTPUT); //Direction
pinMode(10, INPUT); //Motion
digitalWrite(6,LOW);
}
void _direction(char set_dir) {
digitalWrite(4,set_dir);
}
void _motion(int delay_speed)
{
for(index = 0; index < index_value; index++)
{
digitalWrite(5,HIGH);
delayMicroseconds(delay_speed);
digitalWrite(5,LOW);
delayMicroseconds(delay_speed);
}
}
void gradual_motion(int delay_speed)
{
float delay_fraction = (float)delay_speed / (float)index_value;
for(index = 0; index < index_value; index++)
{
float actual_delay = (float)index * (float)delay_fraction;
digitalWrite(5,HIGH);
delayMicroseconds(actual_delay);
digitalWrite(5,LOW);
delayMicroseconds(actual_delay);
Serial.println(actual_delay);
//Serial.println(index_value);
}
}
void loop()
{
Serial.begin(9600);
if (count < revs) {
motion = digitalRead(10);
Serial.println(motion);
if (count < halfrevs) {
if (motion == HIGH) {
Serial.println("TO - Fast motion detected!");
count = count +1;
Serial.println(count);
_direction(cw_dir);
_motion(_fast);
/*
if (motion == previous_motion) {
_motion(_fast);
} else {
gradual_motion(_fast);
}
*/
} else {
Serial.println("TO - Slow motion detected!");
count = count +1;
Serial.println(count);
_direction(cw_dir);
_motion(_slow);
/*
if (motion == previous_motion) {
_motion(_slow);
} else {
gradual_motion(_slow);
}
*/
}
}
if (count == halfrevs) {
delay(1000);
_direction(acw_dir);
count = count +1;
Serial.println("Changing only direction in this step");
Serial.println(count);
}
if (count > halfrevs) {
if (motion == HIGH) {
Serial.println("FRO - Fast motion detected!");
count = count +1;
Serial.println(count);
_direction(acw_dir);
_motion(_fast);
/*
if (motion == previous_motion) {
_motion(_fast);
} else {
gradual_motion(_fast);
}
*/
} else {
Serial.println("FRO - Slow motion detected!");
count = count +1;
Serial.println(count);
_direction(acw_dir);
_motion(_slow);
/*
if (motion == previous_motion) {
_motion(_slow);
} else {
gradual_motion(_slow);
}
*/
}
}
if (count == revs) {
delay(1000);
_direction(cw_dir);
count = count +1;
Serial.println("Changing only direction in this step");
Serial.println(count);
}
previous_motion = motion;
} else {
count = 0;
}
}
| [
"[email protected]"
] | |
2d8e83f2dfcb45c31a62f8c99ca8f8429c3f8f2e | 814fecb981bd3939c44be7d8e66f8a3ea0b90364 | /freeglut project 3D/Malla.cpp | 87c7a10734e5985c02c300b73420e3a6722270a9 | [] | no_license | DavidGonzalezJ/PhysxD | 31ee87ce91348ca44cfb0bd4679088a44b07015b | fd0c862c46b45337cdfb02a5624293f36a8778de | refs/heads/master | 2020-05-16T07:11:04.976490 | 2018-01-19T08:51:35 | 2018-01-19T08:51:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 515 | cpp |
#include "Malla.h"
void Malla::dibuja() {
glMatrixMode(GL_MODELVIEW);
for (int i = 0; i<numeroCaras; i++) {
if (mode)
glBegin(GL_POLYGON);
else
glBegin(GL_LINE_STRIP);
for (int j = 0; j<cara->at(i).getNumeroVertices(); j++) {
int iN = cara->at(i).getIndiceNormalK(j);
int iV = cara->at(i).getIndiceVerticeK(j);
glNormal3f(normales->at(iN).x, normales->at(iN).y, normales->at(iN).z);
glVertex3f(vertices->at(iV).x, vertices->at(iV).y, vertices->at(iV).z);
}
glEnd();
}
}
| [
"[email protected]"
] | |
18c26ab0c60053986ef88759886738ec797d4fc1 | a8fae6cd526b3e63608eed2f11c3b6c07249049e | /torch/csrc/jit/python_ir.cpp | 534297aa3f174adb053a6ebaf36034ab252a10de | [
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"Apache-2.0",
"BSD-2-Clause"
] | permissive | HYU-GradProj/pytorch-run-length-impl-cpp | e6c37f5b461ee677bdc4f4d5ae5b5ac601cdeedc | 07e018e225b9b86ad7e0ec0faabb4541cf6e9841 | refs/heads/master | 2022-11-22T08:01:12.797987 | 2018-09-27T08:21:14 | 2018-09-27T08:21:14 | 150,549,634 | 1 | 1 | NOASSERTION | 2022-11-04T01:27:01 | 2018-09-27T07:50:52 | C++ | UTF-8 | C++ | false | false | 16,730 | cpp | #include "torch/csrc/python_headers.h"
#include "torch/csrc/jit/ir.h"
#include "torch/csrc/jit/import.h"
#include "torch/csrc/jit/pybind.h"
#include "torch/csrc/jit/python_tracer.h"
#include "torch/csrc/utils/pybind.h"
#include "torch/csrc/jit/export.h"
#include "torch/csrc/jit/passes/shape_analysis.h"
#include "torch/csrc/jit/argument_spec.h"
#include "torch/csrc/utils/auto_gil.h"
#include "torch/csrc/utils/python_strings.h"
#include <iostream>
#include <sstream>
namespace torch { namespace jit {
std::string getPythonName(const PyObject* obj_) {
AutoGIL gil;
PyObject* obj = const_cast<PyObject*>(obj_);
auto v = py::getattr(obj, "__name__", py::str("<python_value>"));
// if this was a autograd.Function recover the name of the class
return py::str(v);
}
std::ostream& printPyObject(std::ostream & out, const THPObjectPtr& obj) {
AutoGIL gil;
auto pyobj = py::handle(const_cast<PyObject*>(obj.get()));
if (py::isinstance<py::tuple>(pyobj)) {
// This special-case for printing tuples handles a problem where
// str((2L, 3L)) outputs "(2L, 3L)" in Python 2 but "(2, 3)"
// in Python 3. In order to suppress the L-suffix, we must
// manually print the string ourselves, calling str() on the
// sub-elements.
//
// This is a fairly fragile fix (What if you have nested tuples
// in tuples? What if you have dictionaries?) but it seems to hit
// the cases that are triggered in practice in onnx-pytorch. Revisit
// this code if this is not the case.
//
// By the way, one non-solution for this problem is to monkeypatch
// tuple.__str__; this doesn't work because Python doesn't allow
// monkeypatching methods of built-in types.
auto pytuple = pyobj.cast<py::tuple>();
out << "(";
size_t i = 0;
for (auto& o : pytuple) {
if (i > 0) {
out << ", ";
}
THPObjectPtr str(py::str(o).release().ptr());
out << THPUtils_unpackString(str.get());
i++;
}
if (i == 1) {
out << ",";
}
out << ")";
return out;
} else {
return out << THPUtils_unpackString(py::str(pyobj).ptr());
}
}
// execute a Python function, used for Ops we can't optimize but that we want to optimize around
struct ConcretePythonOp : public PythonOp {
ConcretePythonOp(Graph * graph)
: PythonOp(graph) {}
virtual std::string name() const override {
AutoGIL gil;
if(auto autograd = autogradFunction()) {
return getPythonName(autograd->get());
} else {
return getPythonName(pyobj.get());
}
}
virtual void cloneFrom(Node * other_) override {
Node::cloneFrom(other_);
auto other = other_->cast<PythonOp>();
this->cconv = other->cconv;
Py_INCREF(other->pyobj.get());
this->pyobj = THPObjectPtr(other->pyobj.get());
for(auto & sa : other->scalar_args) {
Py_INCREF(sa.get());
this->scalar_args.emplace_back(sa.get());
}
}
virtual Node * allocNewInstance(Graph * g) override {
return new ConcretePythonOp(g);
}
// recover the autograd.Function instance, if this PythonOp's function
// was originally SomeFunction.apply
// used in ONNX for discovering symbolics
virtual at::optional<THPObjectPtr> autogradFunction() const override {
AutoGIL gil;
py::handle obj = const_cast<PyObject*>(pyobj.get());
auto r = py::getattr(obj, "__self__", py::none());
if(r.is_none())
return at::nullopt;
auto apply = py::getattr(r, "apply", py::none());
if(apply.is_none())
return at::nullopt;
auto c = PyObject_RichCompareBool(apply.ptr(), obj.ptr(), Py_NE);
if(PyErr_Occurred())
throw py::error_already_set();
if(c)
return at::nullopt;
return THPObjectPtr(r.release().ptr());
}
virtual void writeScalars(std::ostream& out) const override {
out << "(";
int i = 0;
for (auto& scalar : scalar_args) {
if (i++ > 0)
out << ", ";
printPyObject(out, scalar);
}
out << ")";
}
};
PythonOp* pythonAllocPythonOp(Graph* g) {
return new ConcretePythonOp(g);
}
void initPythonIRBindings(PyObject * module_) {
setAllocPythonOp(pythonAllocPythonOp);
auto m = py::handle(module_).cast<py::module>();
#define GS(name) \
def(#name,&Graph :: name)
py::class_<Graph,std::shared_ptr<Graph>>(m,"Graph")
.def(py::init<>())
.def("__repr__",[](Graph & g) {
std::stringstream ss;
ss << g;
return ss.str();
})
.def("propagate_shapes", [](Graph& g, std::vector<at::Tensor> inputs, bool with_grad) {
PropagateInputShapes(g, ArgumentSpec(with_grad, variable_tensor_list(std::move(inputs))));
})
.def("export", [](const std::shared_ptr<Graph> g, const std::vector<at::Tensor>& initializers,
int64_t onnx_opset_version, bool defer_weight_export,
::torch::onnx::OperatorExportTypes operator_export_type) {
std::string graph;
RawDataExportMap export_map;
std::tie(graph, export_map) = ExportGraph(
g, initializers, onnx_opset_version, defer_weight_export, operator_export_type);
std::unordered_map<std::string, py::bytes> python_serialized_export_map;
for (auto& kv : export_map) {
auto t = kv.second;
size_t copy_bytes = t.type().elementSizeInBytes() * t.numel();
// TODO: this is an unecessary copy. In theory we can directly return
// the map from identifier to Tensor, but we need some API in Python
// to get raw `bytes` containing the raw tensor data.
python_serialized_export_map[kv.first] = py::bytes(static_cast<const char*>(t.data_ptr()), copy_bytes);
}
return std::make_tuple(py::bytes(graph), python_serialized_export_map);
}, py::arg("initializers"),
py::arg("onnx_opset_version")=0,
py::arg("defer_weight_export")=false,
py::arg("operator_export_type")=::torch::onnx::OperatorExportTypes::ONNX)
.def("prettyPrintExport", [](const std::shared_ptr<Graph> g, const std::vector<at::Tensor>& initializers,
int64_t onnx_opset_version, bool defer_weight_export,
::torch::onnx::OperatorExportTypes operator_export_type) {
return PrettyPrintExportedGraph(
g, initializers, onnx_opset_version, defer_weight_export, operator_export_type);
}, py::arg("initializers"),
py::arg("onnx_opset_version")=0,
py::arg("defer_weight_export")=false,
py::arg("operator_export_type")=::torch::onnx::OperatorExportTypes::ONNX)
.def("wrapPyFuncWithSymbolic", [](Graph &g, py::function func, std::vector<Value*> inputs, size_t n_outputs, py::function symbolic) {
// This function should be used for situations where we have a Python function
// that should have different behavior when exporting for JIT interpreter
// execution v.s. for ONNX export. For example, nn.utils.rnn.pack_padded_sequence
// emits a placeholder under ONNX export, but we want to keep the ability to
// run this in the interpreter, thus we emit a PythonOp for that use case.
// Concretely, this function emits a PythonOp wrapping the passed-in
// parameter `func`, while storing the function `symbolic` for use by the
// ONNX export
std::string cconv(inputs.size(), 't');
func.attr("symbolic") = symbolic;
Node* new_node = g.insertNode(g.createPythonOp(
THPObjectPtr(func.release().ptr()), cconv, {}));
for (auto i : inputs)
new_node->addInput(i);
std::vector<Value*> outputs;
for (size_t i = 0; i < n_outputs; ++i)
new_node->addOutput();
auto sl = std::make_shared<StringSourceLocation>(tracer::getPythonInterpreterStackTrace());
new_node->setSourceLocation(sl);
return py::make_iterator(new_node->outputs().begin(), new_node->outputs().end());
}, py::return_value_policy::reference_internal)
.def("inputs",[](Graph &g) {
return py::make_iterator(g.inputs().begin(), g.inputs().end());
})
.def("outputs",[](Graph &g) {
return py::make_iterator(g.outputs().begin(), g.outputs().end());
})
// TODO: Iterator invalidation might make this hazardous
.def("nodes",[](Graph &g) {
return py::make_iterator(g.nodes().begin(), g.nodes().end());
})
.def("addInput",[](Graph &g) { return g.addInput(); })
.def("copy",[](Graph &g) {
return g.copy();
})
.GS(advanceStage)
.GS(stage)
.GS(eraseInput)
.GS(registerOutput)
.def("create",[](Graph & g, const char * str) {
return g.create(Symbol::fromQualString(str));
})
.def("create",[](Graph & g, const char * str, size_t noutputs) {
return g.create(Symbol::fromQualString(str), noutputs);
})
.def("create",[](Graph & g, const char * str, const std::vector<Value*> & inputs) {
return g.create(Symbol::fromQualString(str),inputs);
})
.def("create",[](Graph & g, const char * str, const std::vector<Value*> & inputs, size_t noutputs) {
return g.create(Symbol::fromQualString(str),inputs, noutputs);
})
.def("param_node", [](Graph &g) {
return g.block()->param_node();
})
.def("return_node", [](Graph &g) {
return g.block()->return_node();
})
.GS(createConstant)
.GS(createFusionGroup)
.def("createClone",[](Graph & g, Node * n, py::object fn) {
return g.createClone(n, [&](Value * e) {
return fn(e).cast<Value*>();
});
})
.GS(appendNode)
.GS(prependNode)
.GS(lint)
.GS(insertNode)
;
#undef GS
#define VS(name) \
def(#name,&Value :: name)
py::class_<Value,std::unique_ptr<Value, py::nodelete>>(m,"Value")
.def("__repr__",[](Value & n) {
std::stringstream ss;
ss << n.uniqueName() << " defined in (" << *n.node() << ")";
return ss.str();
})
.VS(type)
.VS(setType)
.VS(inferTypeFrom)
// skip owningGraph because it returns a raw pointer to a otherwise
// std::shared_ptr stored graph object, and would cause a double free
.VS(unique)
.VS(uniqueName)
.VS(setUniqueName)
.VS(setStage)
.VS(stage)
.VS(offset)
.VS(uses)
.VS(replaceAllUsesWith)
.def("node",[](Value &v) { return v.node(); })
.def("setTypeAs", [](Value * node, Value * other) {
node->setType(other->type());
return node;
})
.VS(copyMetadata)
.VS(isTensor)
;
#undef VS
py::class_<Block, std::unique_ptr<Block, py::nodelete>>(m, "Block");
#define NS(name) \
def(#name,&Node :: name)
py::class_<Node,std::unique_ptr<Node, py::nodelete>>(m,"Node")
.def("__repr__",[](Node & n) {
std::stringstream ss;
ss << n;
return ss.str();
})
.def("hasMultipleOutputs",[](Node&n) {
return n.outputs().size() > 1;
})
.def("outputsSize",[](Node &n) {
return n.outputs().size();
})
.NS(kind)
.NS(stage)
.NS(setStage)
.def("inputs",[](Node &n) {
return py::make_iterator(n.inputs().begin(), n.inputs().end());
})
.def("outputs",[](Node &n) {
return py::make_iterator(n.outputs().begin(), n.outputs().end());
})
.NS(output)
.NS(addInput)
.NS(replaceInput)
.NS(replaceInputWith)
.NS(replaceAllUsesWith)
.NS(insertBefore)
.NS(insertAfter)
.NS(moveAfter)
.NS(moveBefore)
.NS(removeInput)
.NS(removeAllInputs)
.NS(destroy)
.NS(hasUses)
.NS(eraseOutput)
.NS(addOutput)
.NS(scopeName)
.def("blocks", [](Node& n) {
return py::make_iterator(n.blocks().begin(), n.blocks().end());
})
.NS(addBlock)
#define AS(name) def(#name,&Attributes<Node> :: name)
// methods from Attributes
.AS(copyAttributes)
.AS(hasAttributes)
#undef AS
#define AS(name) def(#name,&Attributes<Node> :: name ## S)
// The default method names take Symbol, but the string conversion for
// Symbol you to qualify with attr::. This is not very user friendly
// for attributes, so expose the string variants instead.
.AS(hasAttribute)
.AS(kindOf)
.AS(removeAttribute)
.AS(attributeNames)
#undef AS
#define CREATE_ACCESSOR(Kind,method) \
def(#method "_",[](Node & n, const char * name, Kind##Attr::ValueType v) { \
return n . method ## _(Symbol::attr(name), std::move(v)); \
}) \
.def(#method, [](Node & n, const char * name) { \
return n.method(Symbol::attr(name)); \
})
.CREATE_ACCESSOR(Float,f)
.CREATE_ACCESSOR(Floats,fs)
.CREATE_ACCESSOR(String,s)
.CREATE_ACCESSOR(Strings,ss)
.CREATE_ACCESSOR(Int,i)
.CREATE_ACCESSOR(Ints,is)
.CREATE_ACCESSOR(Graph,g)
.CREATE_ACCESSOR(Graphs,gs)
#undef CREATE_ACCESSOR
// Tensor (t_) -- manually written to unwrap the variable into a tensor.
.def("t_",[](Node & n, const char * name, torch::autograd::Variable v) {
return n.t_(Symbol::attr(name), std::move(v.data()));
})
.def("t", [](Node & n, const char * name) {
return torch::autograd::make_variable(n.t(Symbol::attr(name)), /*requires_grad=*/false);
})
// Tensors (ts_) -- manually written to unwrap variables into tensors.
.def("ts_",[](Node & n, const char * name, std::vector<torch::autograd::Variable> vs) {
std::vector<at::Tensor> tensors;
tensors.reserve(vs.size());
for (auto& variable : vs) {
tensors.push_back(std::move(variable.data()));
}
return n.ts_(Symbol::attr(name), std::move(tensors));
})
.def("ts", [](Node & n, const char * name) {
auto tensors = n.ts(Symbol::attr(name));
std::vector<torch::autograd::Variable> variables;
variables.reserve(tensors.size());
for (auto& tensor : tensors) {
variables.push_back(torch::autograd::make_variable(
std::move(tensor), /*requires_grad=*/false));
}
return variables;
})
.def("z_",[](Node & n, const char * name, at::Tensor v) {
return n.t_(Symbol::attr(name), autograd::Variable(v.view({})).data());
})
.def("z",[](Node & n, const char * name) {
return n.t(Symbol::attr(name));
})
.def("zs_",[](Node & n, const char * name, TensorsAttr::ValueType v) {
for (size_t i = 0; i < v.size(); ++ i) {
v[i] = autograd::Variable(v[i].view({})).data();
}
return n.ts_(Symbol::attr(name), std::move(v));
})
.def("zs",[](Node & n, const char * name) {
return n.ts(Symbol::attr(name));
})
.def("pyobj",[](Node & n) {
return py::handle(n.expect<PythonOp>()->pyobj.get()).cast<py::object>();
})
.def("cconv",[](Node & n) {
return n.expect<PythonOp>()->cconv;
})
.def("pyname",[](Node & n) {
return n.expect<PythonOp>()->name();
})
.def("scalar_args",[](Node & n) {
auto op = n.expect<PythonOp>();
auto scalars = py::list();
auto append = scalars.attr("append");
for(auto & arg : op->scalar_args) {
append(py::handle(arg.get()));
}
return scalars;
})
;
py::class_<Type,std::shared_ptr<Type>>(m,"Type")
.def("__repr__",[](Type & t) {
return t.str();
})
.def("kind",[](Type& t_) {
Type * t = &t_;
switch(t->kind()) {
case TypeKind::DynamicType:
return "DynamicType";
case TypeKind::TensorType:
return "TensorType";
case TypeKind::TupleType:
return "TupleType";
default:
torch::barf("unknown type kind");
return "";
}
})
.def("sizes",[](Type& t) {
return t.expect<TensorType>()->sizes();
})
.def("strides",[](Type& t) {
return t.expect<TensorType>()->strides();
})
.def("contiguous",[](Type& t) {
return t.expect<TensorType>()->contiguous();
})
.def("scalarType",[](Type& t) {
return at::toString(t.expect<TensorType>()->scalarType());
})
;
py::class_<DynamicType, Type, std::shared_ptr<DynamicType>>(m, "DynamicType")
.def(py::init<>());
py::class_<TupleType, Type, std::shared_ptr<TupleType>>(m, "TupleType")
.def(py::init<std::vector<TypePtr>>());
py::class_<Use>(m,"Use")
.def_readonly("user",&Use::user)
.def_readonly("offset",&Use::offset);
m.def("_jit_import_graph", [](const std::string& serialized_graph) {
std::vector<at::Tensor> initializers;
auto graph = ImportIRGraph(serialized_graph, initializers);
std::vector<torch::autograd::Variable> variables;
variables.reserve(initializers.size());
for (auto& tensor : initializers) {
variables.push_back(torch::autograd::make_variable(
std::move(tensor), /*requires_grad=*/false));
}
return std::make_tuple(graph, variables);
});
m.def("_jit_is_tracing", [](const autograd::Variable& var) {
return tracer::isTracing(var);
});
}
}}
| [
"[email protected]"
] | |
337f80dfb114755a6b5a61d8844dd23e88a24254 | 86acd48da71f0faa0642c99173b9cf31b51ca5e5 | /examples/A. Modul IO Aktif High/10. Monitor Data/O3_Monitor_Variabel_Counter/O3_Monitor_Variabel_Counter.ino | 0a7df985dc3381d7459613083a2a1a8ceebcf7aa | [] | no_license | dianartanto/PLCArduinoku | 3b48af462f567247a768d72cf544f5637c12649d | 968e515f429659de1d180aaea2cb3348b87d8893 | refs/heads/master | 2021-01-19T08:59:28.804031 | 2015-04-14T05:52:40 | 2015-04-14T05:52:40 | 33,913,346 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,196 | ino | /*
1.Rangkaian:
Modul Input Output Aktif High.
Kaki Input : X1, X2, X3, X4 (kaki A0, A1, A2 dan A3 Arduino)
Kaki Output : Y1, Y2 (kaki D2 dan D3 Arduino)
Alat Input : Tombol 4x
Alat Output : Relay 2x
2.Program:
Program berikut ini sangat diperlukan untuk mengetahui
apa yang terjadi pada program, khususnya ketika program
tidak bekerja sesuai dengan yang diharapkan.
Program ini akan memonitor nilai variabel Counter,
yaitu menampilkan nilai Counter saat itu dan nilai preset Counter,
pada program Examples, CountUpDown.
Untuk menampilkan nilai counter gunakan variabel namacounter.count().
Untuk menampilkan nilai preset gunakan variabel namacounter.presetValue().
*/
#include <PLCArduinoku.h>
Counter C1(12);
unsigned long T1, T2;
void setup() {
setupku();
outLow();
Serial.begin(9600);
}
void loop() {
in(X1); timerOn(T1,10); C1.countUp();
in(X2); timerOn(T2,10); C1.countDown();
in(X3); C1.clear();
in(X4); C1.preset();
C1.lowerQ(); out(Y1);
C1.upperQ(); out(Y2);
Serial.print(C1.count());
Serial.print(',');
Serial.println(C1.presetValue());
}
| [
"[email protected]"
] | |
3759989d14706f747abbc16c9f74f2ca60f80264 | 05c97a6eca0627dbfae004dd407e71c2d6a2ea46 | /src/database/kernels/pad/pad_16.hpp | 521da15b6ff63764a7771c788b24e6a0cfdca0dc | [
"Apache-2.0"
] | permissive | honggui/CLBlast | 45ae0c2e6b6e1b26c5efdc218c9b49a44fda68f4 | 1573f7d3040ddb6005e71bf4f770566f627236d2 | refs/heads/master | 2023-05-10T18:23:51.581234 | 2023-03-25T20:25:41 | 2023-03-25T20:25:41 | 78,117,601 | 0 | 0 | null | 2017-01-05T14:00:10 | 2017-01-05T14:00:09 | null | UTF-8 | C++ | false | false | 4,516 | hpp |
// =================================================================================================
// This file is part of the CLBlast project. The project is licensed under Apache Version 2.0. It
// is auto-generated by the 'scripts/database/database.py' Python script.
//
// This file populates the database with best-found tuning parameters for the 'Pad16' kernels.
//
// =================================================================================================
namespace clblast {
namespace database {
const DatabaseEntry PadHalf = {
"Pad", Precision::kHalf, {"PAD_DIMX", "PAD_DIMY", "PAD_WPTX", "PAD_WPTY"}, {
{ // AMD GPUs
kDeviceTypeGPU, "AMD", {
{ "Ellesmere", {
{ Name{"AMD Radeon RX 480 "}, Params{ 16, 8, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 16, 8, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "Vega", {
{ Name{"Radeon RX Vega "}, Params{ 16, 16, 1, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 16, 16, 1, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "default", {
{ kDeviceNameDefault , Params{ 16, 8, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "gfx1030", {
{ Name{"AMD Radeon RX 6800 XT "}, Params{ 32, 8, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 32, 8, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "gfx1034", {
{ Name{"AMD Radeon RX 6500 XT "}, Params{ 32, 8, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 32, 8, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
}
},
{ // ARM GPUs
kDeviceTypeGPU, "ARM", {
{ "default", {
{ Name{"Mali-T628 "}, Params{ 8, 32, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ Name{"Mali-T760 "}, Params{ 8, 8, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 8, 8, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
}
},
{ // Intel GPUs
kDeviceTypeGPU, "Intel", {
{ "default", {
{ Name{"Intel(R) HD Graphics 5500 BroadWell U-Processor GT"}, Params{ 8, 8, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ Name{"Intel(R) HD Graphics 620 "}, Params{ 16, 8, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ Name{"Intel(R) HD Graphics Skylake ULT GT2 "}, Params{ 8, 32, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 8, 8, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
}
},
{ // QUALCOMM GPUs
kDeviceTypeGPU, "QUALCOMM", {
{ "default", {
{ Name{"QUALCOMM Adreno(TM) "}, Params{ 8, 8, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 32, 8, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "OpenCL C 3.0 Adreno(TM) 730", {
{ Name{"QUALCOMM Adreno(TM) "}, Params{ 32, 32, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 32, 32, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
{ "OpenCL C 3.0 Adreno(TM) 740", {
{ Name{"QUALCOMM Adreno(TM) "}, Params{ 16, 32, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
{ kDeviceNameDefault , Params{ 16, 32, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
}
},
{ // Default
kDeviceTypeAll, "default", {
{ "default", {
{ kDeviceNameDefault , Params{ 8, 8, 4, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } },
} },
}
},
}
};
} // namespace database
} // namespace clblast
| [
"[email protected]"
] | |
0d7458e1b9efd5f44e72821fe22f5b060e7d037d | 3b1d08997d0dc9c444f2bdaaab55a8606c60d332 | /IOCMain/Share/JumpMon.cpp | 4a9f3612636a12532edf0df11d86aa4e5fdba094 | [] | no_license | zjsaisi/sm2000 | 8303ece373516c871694d382bb3daef9f5129d1a | 0fa74cdb7566621162e1845dd4558723182a49ac | refs/heads/master | 2020-04-16T09:22:12.797424 | 2019-01-23T10:31:07 | 2019-01-23T10:31:07 | 165,461,667 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,553 | cpp | /* JumpMon.cpp
* Author: Zheng Miao
* $Header: JumpMon.cpp 1.1 2008/06/02 15:37:18PDT Zheng Miao (zmiao) Exp $
*/
#include "JumpMon.h"
#include "comm.h"
#include <stdio.h>
#define MIN_VALUE -2147483648L
#define MAX_VALUE 2147483647L
CJumpMon::CJumpMon(int size)
{
m_size = size;
m_pMin = new int32[size];
m_pMax = new int32[size];
m_current = 0;
m_min = MAX_VALUE;
m_max = MIN_VALUE;
m_tail = 0;
m_running = 1;
m_cnt = 0;
}
CJumpMon::~CJumpMon()
{
delete []m_pMin;
delete []m_pMax;
}
void CJumpMon::Update(int32 value)
{
if (!m_running) return;
if (m_min > value) m_min = value;
if (m_max < value) m_max = value;
m_current= value;
}
void CJumpMon::GoNext(void)
{
if (!m_running) return;
m_pMin[m_tail] = m_min;
m_pMax[m_tail] = m_max;
m_min = m_current;
m_max = m_current;
m_tail++;
if (m_tail >= m_size) {
m_tail = 0;
}
if (m_cnt < (m_size - 1)) {
m_cnt++;
}
}
void CJumpMon::JumpMonHack(Ccomm *pComm, uint32 *param)
{
int cnt;
int i;
char buff[100];
int index;
int32 min;
int32 max;
min = MAX_VALUE;
max = MIN_VALUE;
int32 limit;
if (m_running) {
sprintf(buff, "Efc data running: %d seconds\r\n", m_cnt);
pComm->Send(buff);
} else {
sprintf(buff, "Efc data stopped: %d seconds\r\n", m_cnt);
pComm->Send(buff);
}
if ((param[0] == 3) && (param[2] == 1)) {
cnt = param[3];
index = m_tail + m_size - cnt - 1;
for (i = 0; i < cnt;) {
index++;
index %= m_size;
i++;
sprintf(buff, "[%08ld,%08ld]", m_pMin[index], m_pMax[index]);
pComm->Send(buff);
if (m_pMin[index] < min) {
min = m_pMin[index];
}
if (m_pMax[index] > max) {
max = m_pMax[index];
}
if ((i & 3) == 0) {
pComm->Send("\r\n");
}
}
if (i & 3) {
pComm->Send("\r\n");
}
sprintf(buff, "Min: %08ld Max: %08ld\r\n", min, max);
pComm->Send(buff);
return;
}
if ((param[0] == 4) && (param[2] == 2)) {
int32 diff;
int outCnt = 0;
cnt = param[3];
limit = param[4];
index = m_tail + m_size - cnt - 1;
for (i = 0; i < cnt;) {
i++;
index++;
index %= m_size;
diff = m_pMax[index] - m_pMin[index];
if (diff > limit) {
sprintf(buff, "%d: Min=%ld Max=%ld\r\n"
, i, m_pMin[index], m_pMax[index]);
pComm->Send(buff);
outCnt++;
}
}
sprintf(buff, "%d seconds out of limit\r\n", outCnt);
pComm->Send(buff);
return;
}
if ((param[0] == 3) && (param[2] == 3)) {
if (param[3]) {
m_running = 1;
pComm->Send("EFC monitor started\r\n");
} else {
m_running = 0;
pComm->Send("EFC monitor stopped\r\n");
}
return;
}
}
| [
"[email protected]"
] | |
656b31d155c2f635f8d5b4e4274238918cd0f937 | bd4288a7931a5416553a813f86e431f383337c1f | /Code/IO/src/sitkImageReaderBase.cxx | ff38c8e0838c748e9f6b1a6d8fadb97ef7142190 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | aihardman/SimpleElastix | 698b52d9e6a4b5d514df1b88670c012936c230e6 | 9dfa8cb7c99e78b36f64bb6600b084b70960f166 | refs/heads/master | 2020-03-15T00:27:15.715690 | 2017-11-08T17:23:19 | 2017-11-08T17:23:19 | 131,868,751 | 1 | 0 | null | 2018-05-02T15:14:49 | 2018-05-02T15:14:49 | null | UTF-8 | C++ | false | false | 9,620 | cxx | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "sitkImageReaderBase.h"
#include "sitkMacro.h"
#include "sitkExceptionObject.h"
#include <itksys/SystemTools.hxx>
// Include the Transform IO here, so that the IO factory registration
// will occour.
#include <itkTransformFileReader.h>
#include <itkTransformFileWriter.h>
#include <string>
#include <itkImage.h>
#include <itkImageIOBase.h>
#include <itkImageIOFactory.h>
#include <itkGDCMImageIO.h>
namespace itk {
namespace simple {
ImageReaderBase
::ImageReaderBase()
: m_OutputPixelType(sitkUnknown),
m_LoadPrivateTags(false)
{
}
std::string
ImageReaderBase
::ToString() const
{
std::ostringstream out;
out << " OutputPixelType: ";
this->ToStringHelper(out, this->m_OutputPixelType) << std::endl;
out << " LoadPrivateTags: ";
this->ToStringHelper(out, this->m_LoadPrivateTags) << std::endl;
out << ProcessObject::ToString();
return out.str();
}
itk::SmartPointer<ImageIOBase>
ImageReaderBase
::GetImageIOBase(const std::string &fileName)
{
itk::ImageIOBase::Pointer iobase =
itk::ImageIOFactory::CreateImageIO( fileName.c_str(), itk::ImageIOFactory::ReadMode);
if ( iobase.IsNull() )
{
if ( !itksys::SystemTools::FileExists( fileName.c_str() ) )
{
sitkExceptionMacro( "The file \"" << fileName << "\" does not exist." );
}
if ( !bool(std::ifstream( fileName.c_str() )) )
{
sitkExceptionMacro( "Unable to open \"" << fileName << "\" for reading." );
}
sitkExceptionMacro( "Unable to determine ImageIO reader for \"" << fileName << "\"" );
}
// Try additional parameters
GDCMImageIO *ioGDCMImage = dynamic_cast<GDCMImageIO*>(iobase.GetPointer());
if (ioGDCMImage)
{
ioGDCMImage->SetLoadPrivateTags(this->m_LoadPrivateTags);
}
// Read the image information
iobase->SetFileName( fileName );
iobase->ReadImageInformation();
return iobase;
}
ImageReaderBase::Self&
ImageReaderBase
::SetOutputPixelType( PixelIDValueEnum pixelID )
{
this->m_OutputPixelType = pixelID;
return *this;
}
PixelIDValueEnum
ImageReaderBase
::GetOutputPixelType( void ) const
{
return this->m_OutputPixelType;
}
ImageReaderBase::Self&
ImageReaderBase
::SetLoadPrivateTags(bool loadPrivateTags)
{
this->m_LoadPrivateTags = loadPrivateTags;
return *this;
}
bool
ImageReaderBase
::GetLoadPrivateTags() const
{
return this->m_LoadPrivateTags;
}
void
ImageReaderBase
::LoadPrivateTagsOn()
{
this->SetLoadPrivateTags(true);
}
void
ImageReaderBase
::LoadPrivateTagsOff()
{
this->SetLoadPrivateTags(false);
}
void
ImageReaderBase
::GetPixelIDFromImageIO( const std::string &fileName,
PixelIDValueType &outPixelType,
unsigned int & outDimensions )
{
itk::ImageIOBase::Pointer iobase = this->GetImageIOBase(fileName);
this->GetPixelIDFromImageIO(iobase, outPixelType, outDimensions);
}
void
ImageReaderBase
::GetPixelIDFromImageIO( ImageIOBase *iobase,
PixelIDValueType &outPixelType,
unsigned int & outDimensions )
{
// get output information about input image
unsigned int dimension = iobase->GetNumberOfDimensions();
itk::ImageIOBase::IOComponentType componentType = iobase->GetComponentType();
itk::ImageIOBase::IOPixelType pixelType = iobase->GetPixelType();
unsigned int numberOfComponents = iobase->GetNumberOfComponents();
outDimensions = dimension;
if (numberOfComponents == 1 &&
( pixelType == itk::ImageIOBase::SCALAR || pixelType == itk::ImageIOBase::COMPLEX ) )
{
outPixelType = this->ExecuteInternalReadScalar( componentType );
return;
}
// we try to load anything else into a VectorImage
else if (pixelType == itk::ImageIOBase::RGB ||
pixelType == itk::ImageIOBase::RGBA ||
pixelType == itk::ImageIOBase::VECTOR ||
pixelType == itk::ImageIOBase::COVARIANTVECTOR ||
pixelType == itk::ImageIOBase::FIXEDARRAY ||
pixelType == itk::ImageIOBase::POINT ||
pixelType == itk::ImageIOBase::OFFSET )
{
outPixelType = this->ExecuteInternalReadVector( componentType );
return;
}
else if ( pixelType == itk::ImageIOBase::COMPLEX )
{
outPixelType = this->ExecuteInternalReadComplex( componentType );
return;
}
else
{
sitkExceptionMacro( "Unknown PixelType: " << (int) componentType );
}
sitkExceptionMacro( "Unable to load image." );
}
unsigned int
ImageReaderBase
::GetDimensionFromImageIO( itk::ImageIOBase* iobase, unsigned int i)
{
return iobase->GetDimensions(i);
}
unsigned int
ImageReaderBase
::GetDimensionFromImageIO(const std::string &filename, unsigned int i)
{
itk::ImageIOBase::Pointer iobase = this->GetImageIOBase(filename);
return this->GetDimensionFromImageIO(iobase.GetPointer(), i);
}
PixelIDValueType
ImageReaderBase
::ExecuteInternalReadScalar( int componentType )
{
const unsigned int UnusedDimension = 2;
switch(componentType)
{
case itk::ImageIOBase::CHAR:
return ImageTypeToPixelIDValue< itk::Image<int8_t, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::UCHAR:
return ImageTypeToPixelIDValue< itk::Image<uint8_t, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::SHORT:
return ImageTypeToPixelIDValue< itk::Image<int16_t, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::USHORT:
return ImageTypeToPixelIDValue< itk::Image<uint16_t, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::INT:
return ImageTypeToPixelIDValue< itk::Image<int32_t, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::UINT:
return ImageTypeToPixelIDValue< itk::Image<uint32_t, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::LONG:
return ImageTypeToPixelIDValue< itk::Image<long, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::ULONG:
return ImageTypeToPixelIDValue< itk::Image<unsigned long, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::FLOAT:
return ImageTypeToPixelIDValue< itk::Image<float, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::DOUBLE:
return ImageTypeToPixelIDValue< itk::Image<double, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
default:
assert( false ); // should never get here unless we forgot a type
sitkExceptionMacro( "Logic error!" );
}
}
PixelIDValueType
ImageReaderBase
::ExecuteInternalReadComplex( int componentType )
{
const unsigned int UnusedDimension = 2;
switch(componentType)
{
case itk::ImageIOBase::FLOAT:
return ImageTypeToPixelIDValue< itk::Image<std::complex<float>, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::DOUBLE:
return ImageTypeToPixelIDValue< itk::Image<std::complex<double>, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
default:
sitkExceptionMacro( "Only Complex image with float and double are supported!" );
}
}
PixelIDValueType
ImageReaderBase
::ExecuteInternalReadVector( int componentType )
{
const unsigned int UnusedDimension = 2;
switch(componentType)
{
case itk::ImageIOBase::CHAR:
return ImageTypeToPixelIDValue< itk::VectorImage<signed char, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::UCHAR:
return ImageTypeToPixelIDValue< itk::VectorImage<unsigned char, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::SHORT:
return ImageTypeToPixelIDValue< itk::VectorImage<int16_t, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::USHORT:
return ImageTypeToPixelIDValue< itk::VectorImage<uint16_t, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::INT:
return ImageTypeToPixelIDValue< itk::VectorImage<int32_t, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::UINT:
return ImageTypeToPixelIDValue< itk::VectorImage<uint32_t, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::LONG:
return ImageTypeToPixelIDValue< itk::VectorImage<long, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::ULONG:
return ImageTypeToPixelIDValue< itk::VectorImage<unsigned long, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::FLOAT:
return ImageTypeToPixelIDValue< itk::VectorImage<float, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::DOUBLE:
return ImageTypeToPixelIDValue< itk::VectorImage<double, UnusedDimension> >::Result;
break;
case itk::ImageIOBase::UNKNOWNCOMPONENTTYPE:
default:
assert( false ); // should never get here unless we forgot a type
sitkExceptionMacro( "Logic error!" );
}
}
}
}
| [
"[email protected]"
] | |
918a8563b131386f6b4cddfdf860f873a439b4c9 | 8567438779e6af0754620a25d379c348e4cd5a5d | /net/spdy/spdy_protocol_test_utils.cc | a91a55f0c6b52e0c4cac020283d1ce66741a7b61 | [
"BSD-3-Clause"
] | permissive | thngkaiyuan/chromium | c389ac4b50ccba28ee077cbf6115c41b547955ae | dab56a4a71f87f64ecc0044e97b4a8f247787a68 | refs/heads/master | 2022-11-10T02:50:29.326119 | 2017-04-08T12:28:57 | 2017-04-08T12:28:57 | 84,073,924 | 0 | 1 | BSD-3-Clause | 2022-10-25T19:47:15 | 2017-03-06T13:04:15 | null | UTF-8 | C++ | false | false | 7,192 | cc | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stdint.h>
#include "net/spdy/spdy_protocol_test_utils.h"
namespace net {
namespace test {
// TODO(jamessynge): Where it makes sense in these functions, it would be nice
// to make use of the existing gMock matchers here, instead of rolling our own.
::testing::AssertionResult VerifySpdyFrameWithHeaderBlockIREquals(
const SpdyFrameWithHeaderBlockIR& expected,
const SpdyFrameWithHeaderBlockIR& actual) {
DVLOG(1) << "VerifySpdyFrameWithHeaderBlockIREquals";
if (actual.header_block() != expected.header_block())
return ::testing::AssertionFailure();
return ::testing::AssertionSuccess();
}
::testing::AssertionResult VerifySpdyFrameIREquals(const SpdyAltSvcIR& expected,
const SpdyAltSvcIR& actual) {
if (expected.stream_id() != actual.stream_id())
return ::testing::AssertionFailure();
if (expected.origin() != actual.origin())
return ::testing::AssertionFailure();
if (actual.altsvc_vector() != expected.altsvc_vector())
return ::testing::AssertionFailure();
return ::testing::AssertionSuccess();
}
::testing::AssertionResult VerifySpdyFrameIREquals(
const SpdyContinuationIR& expected,
const SpdyContinuationIR& actual) {
return ::testing::AssertionFailure()
<< "VerifySpdyFrameIREquals SpdyContinuationIR not yet implemented";
}
::testing::AssertionResult VerifySpdyFrameIREquals(const SpdyDataIR& expected,
const SpdyDataIR& actual) {
DVLOG(1) << "VerifySpdyFrameIREquals SpdyDataIR";
if (expected.stream_id() != actual.stream_id())
return ::testing::AssertionFailure();
if (expected.fin() != actual.fin())
return ::testing::AssertionFailure();
if (expected.data_len() != actual.data_len())
return ::testing::AssertionFailure();
if (expected.data() == nullptr && actual.data() != nullptr)
return ::testing::AssertionFailure();
if (base::StringPiece(expected.data(), expected.data_len()) !=
base::StringPiece(actual.data(), actual.data_len()))
return ::testing::AssertionFailure();
if (!VerifySpdyFrameWithPaddingIREquals(expected, actual))
return ::testing::AssertionFailure();
return ::testing::AssertionSuccess();
}
::testing::AssertionResult VerifySpdyFrameIREquals(const SpdyGoAwayIR& expected,
const SpdyGoAwayIR& actual) {
DVLOG(1) << "VerifySpdyFrameIREquals SpdyGoAwayIR";
if (expected.last_good_stream_id() != actual.last_good_stream_id())
return ::testing::AssertionFailure();
if (expected.error_code() != actual.error_code())
return ::testing::AssertionFailure();
if (expected.description() != actual.description())
return ::testing::AssertionFailure();
return ::testing::AssertionSuccess();
}
::testing::AssertionResult VerifySpdyFrameIREquals(
const SpdyHeadersIR& expected,
const SpdyHeadersIR& actual) {
DVLOG(1) << "VerifySpdyFrameIREquals SpdyHeadersIR";
if (expected.stream_id() != actual.stream_id())
return ::testing::AssertionFailure();
if (expected.fin() != actual.fin())
return ::testing::AssertionFailure();
if (!VerifySpdyFrameWithHeaderBlockIREquals(expected, actual))
return ::testing::AssertionFailure();
if (expected.has_priority() != actual.has_priority())
return ::testing::AssertionFailure();
if (expected.has_priority()) {
if (!VerifySpdyFrameWithPriorityIREquals(expected, actual))
return ::testing::AssertionFailure();
}
if (!VerifySpdyFrameWithPaddingIREquals(expected, actual))
return ::testing::AssertionFailure();
return ::testing::AssertionSuccess();
}
::testing::AssertionResult VerifySpdyFrameIREquals(const SpdyPingIR& expected,
const SpdyPingIR& actual) {
DVLOG(1) << "VerifySpdyFrameIREquals SpdyPingIR";
if (expected.id() != actual.id())
return ::testing::AssertionFailure();
if (expected.is_ack() != actual.is_ack())
return ::testing::AssertionFailure();
return ::testing::AssertionSuccess();
}
::testing::AssertionResult VerifySpdyFrameIREquals(
const SpdyPriorityIR& expected,
const SpdyPriorityIR& actual) {
DVLOG(1) << "VerifySpdyFrameIREquals SpdyPriorityIR";
if (expected.stream_id() != actual.stream_id())
return ::testing::AssertionFailure();
if (!VerifySpdyFrameWithPriorityIREquals(expected, actual))
return ::testing::AssertionFailure();
return ::testing::AssertionSuccess();
}
::testing::AssertionResult VerifySpdyFrameIREquals(
const SpdyPushPromiseIR& expected,
const SpdyPushPromiseIR& actual) {
DVLOG(1) << "VerifySpdyFrameIREquals SpdyPushPromiseIR";
if (expected.stream_id() != actual.stream_id())
return ::testing::AssertionFailure();
if (!VerifySpdyFrameWithPaddingIREquals(expected, actual))
return ::testing::AssertionFailure();
if (expected.promised_stream_id() != actual.promised_stream_id())
return ::testing::AssertionFailure();
if (!VerifySpdyFrameWithHeaderBlockIREquals(expected, actual))
return ::testing::AssertionFailure();
return ::testing::AssertionSuccess();
}
::testing::AssertionResult VerifySpdyFrameIREquals(
const SpdyRstStreamIR& expected,
const SpdyRstStreamIR& actual) {
DVLOG(1) << "VerifySpdyFrameIREquals SpdyRstStreamIR";
if (expected.stream_id() != actual.stream_id())
return ::testing::AssertionFailure();
if (expected.error_code() != actual.error_code())
return ::testing::AssertionFailure();
return ::testing::AssertionSuccess();
}
::testing::AssertionResult VerifySpdyFrameIREquals(
const SpdySettingsIR& expected,
const SpdySettingsIR& actual) {
DVLOG(1) << "VerifySpdyFrameIREquals SpdySettingsIR";
// Note, ignoring non-HTTP/2 fields such as clear_settings.
if (expected.is_ack() != actual.is_ack())
return ::testing::AssertionFailure();
if (expected.values().size() != actual.values().size())
return ::testing::AssertionFailure();
for (const auto& entry : expected.values()) {
const auto& param = entry.first;
auto actual_itr = actual.values().find(param);
if (actual_itr == actual.values().end()) {
DVLOG(1) << "actual doesn't contain param: " << param;
return ::testing::AssertionFailure();
}
uint32_t expected_value = entry.second;
uint32_t actual_value = actual_itr->second;
if (expected_value != actual_value) {
DVLOG(1) << "Values don't match for parameter: " << param;
return ::testing::AssertionFailure();
}
}
return ::testing::AssertionSuccess();
}
::testing::AssertionResult VerifySpdyFrameIREquals(
const SpdyWindowUpdateIR& expected,
const SpdyWindowUpdateIR& actual) {
DVLOG(1) << "VerifySpdyFrameIREquals SpdyWindowUpdateIR";
if (expected.stream_id() != actual.stream_id())
return ::testing::AssertionFailure();
if (expected.delta() != actual.delta())
return ::testing::AssertionFailure();
return ::testing::AssertionSuccess();
}
} // namespace test
} // namespace net
| [
"[email protected]"
] | |
93129b7dcbbc78ca5c574142ba9ae677b8534a0b | dc2385d0e3f06f762fd949e3f8bb4821d8ce9480 | /Tools/Pan_tilt_controller/structs.h | 0776551d045fc03c4be9561b32577498b0d6f2a6 | [] | no_license | yisea123/PanTilt | 8a3f0b4927fcc04649ee265a3d9e4c4f2bc70e16 | 5e89df3ba610817715c8cfcd9ad8937e14b9af82 | refs/heads/master | 2020-12-04T18:41:12.851921 | 2015-05-21T15:56:47 | 2015-05-21T15:56:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 97 | h | #pragma once
#include <cstdint>
struct coordinate
{
int16_t x;
int16_t y;
bool reset;
};
| [
"[email protected]"
] | |
56e54ae669ce19083afd4f096c0f8875a54bccc4 | 6e99d81cfbcb84c1757b806693c47ab18b9f75ff | /Tetris/Classes/I_TetrisBlockType.h | 702e2beef565c27740816f6c00b61eddbb0207d5 | [] | no_license | kidchen2012/cocos2dx | 8ad7f5903729935868a1493622fc9fa62847f93b | 930cc521603de7aedfc17c60beeb3189e90555ce | refs/heads/master | 2021-01-19T00:08:36.607150 | 2013-09-02T08:20:13 | 2013-09-02T08:20:13 | 12,533,709 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 458 | h | #ifndef _I_TETRIS_BLOCK_TYPE_H_
#define _I_TETRIS_BLOCK_TYPE_H_
#include "TetrisBlockType.h"
class I_TetrisBlockType : public TetrisBlockType
{
public:
virtual void init();
virtual bool T_checkLeftMove();
virtual void T_leftMove();
virtual bool T_checkRightMove();
virtual void T_rightMove();
virtual bool T_checkDropDown();
virtual void T_dropDown();
virtual void T_rotate();
virtual void T_updateTetrisStateArray(int _value);
};
#endif | [
"[email protected]"
] | |
fe6e3d62375cd53cc2360771d96e5c0cc498217f | 6635e36036c8942acfc5eed03f57ff2cab4d068a | /computer_graphics/glengine2/ge2compositor.cpp | 199c9ae939d38d3317319300825f86d9b988dada | [] | no_license | asgeir/old-school-projects | c30d302a72898cb3d30a5c5f5ca44e70a34c5754 | 96a502589c627e4556f9ee14fc1dc21ed53ce28a | refs/heads/master | 2022-03-08T14:00:41.541988 | 2022-02-11T12:11:16 | 2022-02-11T12:11:16 | 46,489,074 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,992 | cpp | #include "ge2compositor.h"
#include "ge2common.h"
#include "ge2framebuffer.h"
#include "ge2fsquad.h"
#include "ge2material.h"
#include "ge2resourcemgr.h"
#include "ge2shader.h"
#include "ge2texture2d.h"
#include <iostream>
using namespace ge2;
namespace {
const std::string kAdditiveBlendShader = R"(
#version 150
in vec2 textureCoordinates;
uniform sampler2D colorData1;
uniform sampler2D colorData2;
out vec4 ge_fragmentColor;
void main()
{
ge_fragmentColor = texture(colorData1, textureCoordinates) + texture(colorData2, textureCoordinates);
}
)";
const std::string kDisplayShader = R"(
#version 150
in vec2 textureCoordinates;
uniform sampler2D colorData;
out vec4 ge_fragmentColor;
void main()
{
ge_fragmentColor = texture(colorData, textureCoordinates);
}
)";
// http://fabiensanglard.net/lightScattering/index.php
const std::string kCrepuscularRaysShader = R"(
#version 150
in vec2 textureCoordinates;
uniform float exposure;
uniform float decay;
uniform float density;
uniform float weight;
uniform vec2 lightPositionOnScreen;
uniform sampler2D lightStencil;
out vec4 ge_fragmentColor;
const int NUM_SAMPLES = 25;
void main()
{
vec2 deltaTextCoord = vec2(textureCoordinates - lightPositionOnScreen);
vec2 sampleCoordinates = textureCoordinates;
deltaTextCoord *= 1.0 / float(NUM_SAMPLES) * density;
float illuminationDecay = 1.0;
for(int i = 0; i < NUM_SAMPLES ; i++)
{
sampleCoordinates -= deltaTextCoord;
vec4 sample = texture(lightStencil, sampleCoordinates);
sample *= illuminationDecay * weight;
ge_fragmentColor += sample;
illuminationDecay *= decay;
}
ge_fragmentColor *= exposure;
}
)";
const std::string kDrawTextureShader = R"(
#version 150
in vec2 textureCoordinates;
uniform sampler2D colorData;
out vec4 ge_fragmentColor;
void main()
{
ge_fragmentColor = texture(colorData, textureCoordinates);
}
)";
// http://rastergrid.com/blog/2010/09/efficient-gaussian-blur-with-linear-sampling
const std::string kGaussianBlurLinearSamplingShader = R"(
#version 150
in vec2 textureCoordinates;
uniform bool horizontalBlur;
uniform sampler2D colorData;
uniform vec2 screenSize;
out vec4 ge_fragmentColor;
const float offset[3] = float[]( 0.0, 1.3846153846, 3.2307692308 );
const float weight[3] = float[]( 0.2270270270, 0.3162162162, 0.0702702703 );
void main(void)
{
ge_fragmentColor = texture(colorData, textureCoordinates) * weight[0];
for (int i = 1; i < 3; ++i) {
vec2 samplePos = vec2(0.0, 0.0);
if (horizontalBlur) {
samplePos.x = offset[i] / screenSize.x;
} else {
samplePos.y = offset[i] / screenSize.y;
}
ge_fragmentColor += texture(colorData, textureCoordinates + samplePos) * weight[i];
ge_fragmentColor += texture(colorData, textureCoordinates - samplePos) * weight[i];
}
}
)";
}
Compositor::Compositor(Compositor &&rhs)
{
swap(rhs);
}
Compositor::~Compositor()
{
}
Compositor &Compositor::operator=(Compositor rhs)
{
swap(rhs);
return *this;
}
void Compositor::construct(int width, int height)
{
destruct();
m_inputFramebuffer = new Framebuffer;
m_inputFramebuffer->construct(width, height, true, { FragmentBuffer::Color, FragmentBuffer::Glow, FragmentBuffer::CrepuscularRays });
m_fullBuffer.front = new Framebuffer;
m_fullBuffer.back = new Framebuffer;
m_quarterBuffer.front = new Framebuffer;
m_quarterBuffer.back = new Framebuffer;
m_fullBuffer.front->construct(width, height, false, { FragmentBuffer::Color });
m_fullBuffer.back->construct(width, height, false, { FragmentBuffer::Color });
m_quarterBuffer.front->construct(width/2, height/2, false, { FragmentBuffer::Color });
m_quarterBuffer.back->construct(width/2, height/2, false, { FragmentBuffer::Color });
m_displayMaterial = geResourceMgr->compositorMaterial("_ge_internal_compositor_display");
if (!m_displayMaterial) {
m_displayMaterial = geResourceMgr->loadCompositorMaterialFromString(
"_ge_internal_compositor_display",
kDisplayShader,
{ "colorData" });
}
m_displayQuad = new FullscreenQuad(m_displayMaterial);
m_additiveBlendEffect = geResourceMgr->compositorMaterial("std::additiveBlend");
if (!m_additiveBlendEffect) {
m_additiveBlendEffect = geResourceMgr->loadCompositorMaterialFromString(
"std::additiveBlend",
kAdditiveBlendShader,
{ "colorData1", "colorData2" });
}
m_crepuscularRaysEffect = geResourceMgr->compositorMaterial("std::crepuscularRays");
if (!m_crepuscularRaysEffect) {
m_crepuscularRaysEffect = geResourceMgr->loadCompositorMaterialFromString(
"std::crepuscularRays",
kCrepuscularRaysShader,
{ "decay", "density", "exposure", "lightPositionOnScreen", "lightStencil", "weight" });
}
m_drawTextureEffect = geResourceMgr->compositorMaterial("std::drawTexture");
if (!m_drawTextureEffect) {
m_drawTextureEffect = geResourceMgr->loadCompositorMaterialFromString(
"std::drawTexture",
kDrawTextureShader,
{ "colorData" });
}
m_gaussianBlurEffect = geResourceMgr->compositorMaterial("std::gaussianBlurLinearSampling");
if (!m_gaussianBlurEffect) {
m_gaussianBlurEffect = geResourceMgr->loadCompositorMaterialFromString(
"std::gaussianBlurLinearSampling",
kGaussianBlurLinearSamplingShader,
{ "horizontalBlur", "colorData", "screenSize" });
}
}
void Compositor::destruct()
{
delete m_inputFramebuffer;
m_inputFramebuffer = nullptr;
delete m_fullBuffer.front; m_fullBuffer.front = nullptr;
delete m_fullBuffer.back; m_fullBuffer.back = nullptr;
delete m_quarterBuffer.front; m_quarterBuffer.front = nullptr;
delete m_quarterBuffer.back; m_quarterBuffer.back = nullptr;
delete m_displayQuad;
m_displayQuad = nullptr;
m_displayMaterial = nullptr;
}
void Compositor::bindInputFramebuffer()
{
m_inputFramebuffer->bind();
}
void Compositor::unbindInputFramebuffer()
{
m_inputFramebuffer->unbind();
}
void Compositor::compose(const CompositorEffectList &effects)
{
bool isFirstEffect = true;
for (auto effect : effects) {
effect->compose(this, isFirstEffect);
isFirstEffect = false;
}
clear();
m_displayMaterial->setUniform("colorData", buffer(CompositorBuffer::Full));
m_displayMaterial->bind();
m_displayQuad->draw();
m_displayMaterial->unbind();
}
Texture2D *Compositor::inputColorBuffer(FragmentBuffer buffer)
{
return m_inputFramebuffer->colorBuffer(buffer);
}
Texture2D *Compositor::inputDepthBuffer()
{
return m_inputFramebuffer->depthBuffer();
}
Texture2D *Compositor::buffer(CompositorBuffer buf)
{
switch (buf) {
case CompositorBuffer::Full:
return m_fullBuffer.back->colorBuffer(FragmentBuffer::Color);
case CompositorBuffer::Quarter:
return m_quarterBuffer.back->colorBuffer(FragmentBuffer::Color);
default:
std::cerr << "Compositor::buffer - Unhandled compositor buffer" << std::endl;
return nullptr;
}
}
void Compositor::drawEffect(CompositorBuffer buffer, Material *material)
{
bindBuffer(buffer);
material->bind();
m_displayQuad->draw();
material->unbind();
unbindBuffer(buffer);
}
void Compositor::additiveBlendFilter(CompositorBuffer buf, Texture2D *tex1, Texture2D *tex2)
{
m_additiveBlendEffect->setUniform("colorData1", tex1);
m_additiveBlendEffect->setUniform("colorData2", tex2);
drawEffect(buf, m_additiveBlendEffect);
}
void Compositor::drawCrepuscularRaysFilter(const glm::vec2 &screenSpacePosition, Texture2D *lightStencil, float decay, float density, float exposure, float weight)
{
drawTextureFilter(CompositorBuffer::Quarter, lightStencil);
gaussianBlurFilter(CompositorBuffer::Quarter);
m_crepuscularRaysEffect->setUniform("decay", decay);
m_crepuscularRaysEffect->setUniform("density", density);
m_crepuscularRaysEffect->setUniform("exposure", exposure);
m_crepuscularRaysEffect->setUniform("lightPositionOnScreen", screenSpacePosition);
m_crepuscularRaysEffect->setUniform("lightStencil", buffer(CompositorBuffer::Quarter));
m_crepuscularRaysEffect->setUniform("weight", weight);
drawEffect(CompositorBuffer::Quarter, m_crepuscularRaysEffect);
additiveBlendFilter(CompositorBuffer::Full, buffer(CompositorBuffer::Full), buffer(CompositorBuffer::Quarter));
}
void Compositor::drawTextureFilter(CompositorBuffer buf, Texture2D *data)
{
m_drawTextureEffect->setUniform("colorData", data);
drawEffect(buf, m_drawTextureEffect);
}
void Compositor::gaussianBlurFilter(CompositorBuffer buf)
{
glm::vec2 screenSize{(float)buffer(buf)->width(), (float)buffer(buf)->height()};
m_gaussianBlurEffect->setUniform("screenSize", screenSize);
m_gaussianBlurEffect->setUniform("horizontalBlur", true);
m_gaussianBlurEffect->setUniform("colorData", buffer(buf));
drawEffect(buf, m_gaussianBlurEffect);
m_gaussianBlurEffect->setUniform("horizontalBlur", false);
m_gaussianBlurEffect->setUniform("colorData", buffer(buf));
drawEffect(buf, m_gaussianBlurEffect);
}
void Compositor::clear()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT|GL_STENCIL_BUFFER_BIT);
}
void Compositor::bindBuffer(CompositorBuffer buffer)
{
switch (buffer) {
case CompositorBuffer::Full:
m_fullBuffer.front->bind();
break;
case CompositorBuffer::Quarter:
m_quarterBuffer.front->bind();
break;
default:
std::cerr << "Compositor::bindBuffer - Unhandled compositor buffer" << std::endl;
break;
}
clear();
}
void Compositor::unbindBuffer(CompositorBuffer buffer)
{
switch (buffer) {
case CompositorBuffer::Full:
m_fullBuffer.front->unbind();
std::swap(m_fullBuffer.front, m_fullBuffer.back);
break;
case CompositorBuffer::Quarter:
m_quarterBuffer.front->unbind();
std::swap(m_quarterBuffer.front, m_quarterBuffer.back);
break;
default:
std::cerr << "Compositor::bindBuffer - Unhandled compositor buffer" << std::endl;
break;
}
}
void Compositor::swap(Compositor &rhs)
{
std::swap(m_inputFramebuffer, rhs.m_inputFramebuffer);
std::swap(m_fullBuffer, rhs.m_fullBuffer);
std::swap(m_quarterBuffer, rhs.m_quarterBuffer);
std::swap(m_displayMaterial, rhs.m_displayMaterial);
std::swap(m_displayQuad, rhs.m_displayQuad);
}
| [
"[email protected]"
] | |
29b228439f7645711e04c13903eb812ecb61bb8b | c5602d4032c2fbcb8c66b793264ee9e81e3ac9de | /01Bag/c++/src/BagDPBuilder.h | e4d3b87d42c070319c4d97bc230e6dcd6ade0ef1 | [] | no_license | rwbzx/algorithm | 58a44e6d622a51a952fce63734339fc4c8447839 | ca035924eb618ae86810e4afb3189329fe365de5 | refs/heads/master | 2021-01-20T12:29:21.828900 | 2017-05-24T16:07:28 | 2017-05-24T16:10:56 | 90,371,513 | 0 | 0 | null | 2017-05-24T16:10:58 | 2017-05-05T12:04:02 | C++ | UTF-8 | C++ | false | false | 292 | h | #pragma once
#include "ExportHeader.h"
class BagInput;
class DLL_API BagDPBuilder : public BagBuilder
{
public:
BagDPBuilder();
virtual ~BagDPBuilder();
virtual void StartBag();
private:
int * m_transform_state;
int * m_current_state;
int * m_last_state;
void DoBag(BagInput *);
};
| [
"[email protected]"
] | |
c1a5a71b756b5b26e3d9d3aeb36ad24b2fe5e29e | 490d1d88ff793ecaf8a26c5c577c72cc1eb93c0a | /nodes/Node_v10/Sound.h | 2aae32aa0208119ff488a3d6f254825d742fe6ef | [] | no_license | shannongatta1/GetALife | 9d371f0429e4f46cf48fe7fd6bd923db594e54d6 | d052b440840694a558b7761a61464288c1c57401 | refs/heads/master | 2023-03-12T18:29:47.105939 | 2021-03-04T06:43:54 | 2021-03-04T06:43:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 583 | h | #ifndef Sound_h
#define Sound_h
#include <Arduino.h>
#include <NonBlockingRtttl.h>
#include <Streaming.h>
// https://www.wemos.cc/en/latest/d1_mini_shiled/buzzer.html
#define PIN_BUZZER D5
enum songList {
// OS-level
boot,
// better not go there
morningTrain,
AxelF,
RickRoll,
CrazyTrain,
// expressions; 3-5 notes that... express
Joyful,
Powerful,
Peaceful,
Sad,
Mad,
Scared,
N_SOUNDS
};
class Sound {
public:
void begin();
boolean update();
void play(songList song, boolean blocking=false);
private:
};
#endif
| [
"[email protected]"
] | |
852f8864ff4c1b3c7a5e2af57503a76063bb0f57 | 94b6f593d16c0d691806b76b44b7e9be4501d9eb | /flat_world/grid_world.h | ab33d913998016d24e6c4836d7c4b0574a980b11 | [] | no_license | leol15/oreo3d | e0c711ef966cc7280d71d1a8a12ab2ffb94eeedf | ef5f7c22ddc0af441c076dcefd1be21e6da2f580 | refs/heads/master | 2023-03-27T21:18:11.346750 | 2021-04-03T06:30:31 | 2021-04-03T06:30:31 | 351,677,471 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,004 | h | #ifndef GRID_WORLD_H_
#define GRID_WORLD_H_
#include <glm/glm.hpp>
#include <vector>
#include <map>
enum CellType {
SAND,
WATER,
STONE,
EMPTY
};
struct Cell {
CellType type;
};
class GridWorld {
public:
GridWorld(int width, int height);
~GridWorld();
// interaction
void addCell(int row, int column, int size);
void setCellType(CellType newType) { current_type_ = newType; }
// update
void update();
void reset();
// show w/ gl shader program
void draw(GLuint program_id);
private:
// the grid to collect the structs
int width_, height_;
Cell ** grid_;
// grid_[i][j] == nullptr
CellType current_type_;
// for ogl 2D drawing
GLuint vao_;
GLuint position_vbo_;
GLuint indices_vbo_;
// actual data, positon data
std::vector<glm::vec2> grid_vecticies_;
// element type : (vector, valid size)
std::map<CellType, std::pair<std::vector<unsigned int>, int>> type_to_idx_arr_map_;
void collectGridToVectexArr();
// helpers
bool cellEmpty(int row, int col);
};
#endif | [
"[email protected]"
] | |
49c03e25e41209107fa1b423f4e0f77d04fd4864 | 58ac7ce414dcbe875e26bb6fae692e3c74f39c4e | /net/socket/transport_client_socket_unittest.cc | d40d569a27d5b23255e51b422e985a524248999c | [] | no_license | markthomas93/tempwork | f4ba7b4620c1cb806aef40a66692115140b42c90 | 93c852f3d14c95b2d73077b00e7284ea6f416d84 | refs/heads/master | 2021-12-10T10:35:39.230466 | 2016-08-11T12:00:33 | 2016-08-11T12:00:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,406 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <memory>
#include <string>
#include "base/bind.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "net/base/address_list.h"
#include "net/base/io_buffer.h"
#include "net/base/ip_address.h"
#include "net/base/net_errors.h"
#include "net/base/test_completion_callback.h"
#include "net/dns/mock_host_resolver.h"
#include "net/log/net_log.h"
#include "net/log/test_net_log.h"
#include "net/log/test_net_log_entry.h"
#include "net/log/test_net_log_util.h"
#include "net/socket/client_socket_factory.h"
#include "net/socket/tcp_client_socket.h"
#include "net/socket/tcp_server_socket.h"
#include "net/test/gtest_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"
using net::test::IsError;
using net::test::IsOk;
namespace net {
namespace {
const char kServerReply[] = "HTTP/1.1 404 Not Found";
enum ClientSocketTestTypes { TCP, SCTP };
} // namespace
class TransportClientSocketTest
: public ::testing::TestWithParam<ClientSocketTestTypes> {
public:
TransportClientSocketTest()
: listen_port_(0),
socket_factory_(ClientSocketFactory::GetDefaultFactory()),
close_server_socket_on_next_send_(false) {}
virtual ~TransportClientSocketTest() {}
// Testcase hooks
void SetUp() override;
void CloseServerSocket() {
// delete the connected_sock_, which will close it.
connected_sock_.reset();
}
void AcceptCallback(int res) {
ASSERT_THAT(res, IsOk());
connect_loop_.Quit();
}
int DrainClientSocket(IOBuffer* buf,
uint32_t buf_len,
uint32_t bytes_to_read,
TestCompletionCallback* callback);
// Establishes a connection to the server.
void EstablishConnection(TestCompletionCallback* callback);
// Sends a request from the client to the server socket. Makes the server read
// the request and send a response.
void SendRequestAndResponse();
// Makes |connected_sock_| to read |expected_bytes_read| bytes. Returns the
// the data read as a string.
std::string ReadServerData(int expected_bytes_read);
// Sends server response.
void SendServerResponse();
void set_close_server_socket_on_next_send(bool close) {
close_server_socket_on_next_send_ = close;
}
protected:
base::RunLoop connect_loop_;
uint16_t listen_port_;
TestNetLog net_log_;
ClientSocketFactory* const socket_factory_;
std::unique_ptr<StreamSocket> sock_;
std::unique_ptr<StreamSocket> connected_sock_;
private:
std::unique_ptr<TCPServerSocket> listen_sock_;
bool close_server_socket_on_next_send_;
};
void TransportClientSocketTest::SetUp() {
::testing::TestWithParam<ClientSocketTestTypes>::SetUp();
// Open a server socket on an ephemeral port.
listen_sock_.reset(new TCPServerSocket(NULL, NetLog::Source()));
IPEndPoint local_address(IPAddress::IPv4Localhost(), 0);
ASSERT_THAT(listen_sock_->Listen(local_address, 1), IsOk());
// Get the server's address (including the actual port number).
ASSERT_THAT(listen_sock_->GetLocalAddress(&local_address), IsOk());
listen_port_ = local_address.port();
listen_sock_->Accept(&connected_sock_,
base::Bind(&TransportClientSocketTest::AcceptCallback,
base::Unretained(this)));
AddressList addr;
// MockHostResolver resolves everything to 127.0.0.1.
std::unique_ptr<HostResolver> resolver(new MockHostResolver());
HostResolver::RequestInfo info(HostPortPair("localhost", listen_port_));
TestCompletionCallback callback;
std::unique_ptr<HostResolver::Request> request;
int rv = resolver->Resolve(info, DEFAULT_PRIORITY, &addr, callback.callback(),
&request, BoundNetLog());
CHECK_EQ(ERR_IO_PENDING, rv);
rv = callback.WaitForResult();
CHECK_EQ(rv, OK);
sock_ = socket_factory_->CreateTransportClientSocket(addr, NULL, &net_log_,
NetLog::Source());
}
int TransportClientSocketTest::DrainClientSocket(
IOBuffer* buf,
uint32_t buf_len,
uint32_t bytes_to_read,
TestCompletionCallback* callback) {
int rv = OK;
uint32_t bytes_read = 0;
while (bytes_read < bytes_to_read) {
rv = sock_->Read(buf, buf_len, callback->callback());
EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
rv = callback->GetResult(rv);
EXPECT_GT(rv, 0);
bytes_read += rv;
}
return static_cast<int>(bytes_read);
}
void TransportClientSocketTest::EstablishConnection(
TestCompletionCallback* callback) {
int rv = sock_->Connect(callback->callback());
// Wait for |listen_sock_| to accept a connection.
connect_loop_.Run();
// Now wait for the client socket to accept the connection.
EXPECT_THAT(callback->GetResult(rv), IsOk());
}
void TransportClientSocketTest::SendRequestAndResponse() {
// Send client request.
const char request_text[] = "GET / HTTP/1.0\r\n\r\n";
int request_len = strlen(request_text);
scoped_refptr<DrainableIOBuffer> request_buffer(
new DrainableIOBuffer(new IOBuffer(request_len), request_len));
memcpy(request_buffer->data(), request_text, request_len);
int bytes_written = 0;
while (request_buffer->BytesRemaining() > 0) {
TestCompletionCallback write_callback;
int write_result =
sock_->Write(request_buffer.get(), request_buffer->BytesRemaining(),
write_callback.callback());
write_result = write_callback.GetResult(write_result);
ASSERT_GT(write_result, 0);
ASSERT_LE(bytes_written + write_result, request_len);
request_buffer->DidConsume(write_result);
bytes_written += write_result;
}
ASSERT_EQ(request_len, bytes_written);
// Confirm that the server receives what client sent.
std::string data_received = ReadServerData(bytes_written);
ASSERT_TRUE(connected_sock_->IsConnectedAndIdle());
ASSERT_EQ(request_text, data_received);
// Write server response.
SendServerResponse();
}
void TransportClientSocketTest::SendServerResponse() {
// TODO(dkegel): this might not be long enough to tickle some bugs.
int reply_len = strlen(kServerReply);
scoped_refptr<DrainableIOBuffer> write_buffer(
new DrainableIOBuffer(new IOBuffer(reply_len), reply_len));
memcpy(write_buffer->data(), kServerReply, reply_len);
int bytes_written = 0;
while (write_buffer->BytesRemaining() > 0) {
TestCompletionCallback write_callback;
int write_result = connected_sock_->Write(write_buffer.get(),
write_buffer->BytesRemaining(),
write_callback.callback());
write_result = write_callback.GetResult(write_result);
ASSERT_GE(write_result, 0);
ASSERT_LE(bytes_written + write_result, reply_len);
write_buffer->DidConsume(write_result);
bytes_written += write_result;
}
if (close_server_socket_on_next_send_)
CloseServerSocket();
}
std::string TransportClientSocketTest::ReadServerData(int expected_bytes_read) {
int bytes_read = 0;
scoped_refptr<IOBufferWithSize> read_buffer(
new IOBufferWithSize(expected_bytes_read));
while (bytes_read < expected_bytes_read) {
TestCompletionCallback read_callback;
int rv = connected_sock_->Read(read_buffer.get(),
expected_bytes_read - bytes_read,
read_callback.callback());
EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
rv = read_callback.GetResult(rv);
EXPECT_GE(rv, 0);
bytes_read += rv;
}
EXPECT_EQ(expected_bytes_read, bytes_read);
return std::string(read_buffer->data(), bytes_read);
}
// TODO(leighton): Add SCTP to this list when it is ready.
INSTANTIATE_TEST_CASE_P(StreamSocket,
TransportClientSocketTest,
::testing::Values(TCP));
TEST_P(TransportClientSocketTest, Connect) {
TestCompletionCallback callback;
EXPECT_FALSE(sock_->IsConnected());
int rv = sock_->Connect(callback.callback());
// Wait for |listen_sock_| to accept a connection.
connect_loop_.Run();
TestNetLogEntry::List net_log_entries;
net_log_.GetEntries(&net_log_entries);
EXPECT_TRUE(
LogContainsBeginEvent(net_log_entries, 0, NetLog::TYPE_SOCKET_ALIVE));
EXPECT_TRUE(
LogContainsBeginEvent(net_log_entries, 1, NetLog::TYPE_TCP_CONNECT));
// Now wait for the client socket to accept the connection.
if (rv != OK) {
ASSERT_EQ(rv, ERR_IO_PENDING);
rv = callback.WaitForResult();
EXPECT_EQ(rv, OK);
}
EXPECT_TRUE(sock_->IsConnected());
net_log_.GetEntries(&net_log_entries);
EXPECT_TRUE(
LogContainsEndEvent(net_log_entries, -1, NetLog::TYPE_TCP_CONNECT));
sock_->Disconnect();
EXPECT_FALSE(sock_->IsConnected());
}
TEST_P(TransportClientSocketTest, IsConnected) {
scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
TestCompletionCallback callback;
uint32_t bytes_read;
EXPECT_FALSE(sock_->IsConnected());
EXPECT_FALSE(sock_->IsConnectedAndIdle());
EstablishConnection(&callback);
EXPECT_TRUE(sock_->IsConnected());
EXPECT_TRUE(sock_->IsConnectedAndIdle());
// Send the request and wait for the server to respond.
SendRequestAndResponse();
// Drain a single byte so we know we've received some data.
bytes_read = DrainClientSocket(buf.get(), 1, 1, &callback);
ASSERT_EQ(bytes_read, 1u);
// Socket should be considered connected, but not idle, due to
// pending data.
EXPECT_TRUE(sock_->IsConnected());
EXPECT_FALSE(sock_->IsConnectedAndIdle());
bytes_read =
DrainClientSocket(buf.get(), 4096, strlen(kServerReply) - 1, &callback);
ASSERT_EQ(bytes_read, strlen(kServerReply) - 1);
// After draining the data, the socket should be back to connected
// and idle.
EXPECT_TRUE(sock_->IsConnected());
EXPECT_TRUE(sock_->IsConnectedAndIdle());
// This time close the server socket immediately after the server response.
set_close_server_socket_on_next_send(true);
SendRequestAndResponse();
bytes_read = DrainClientSocket(buf.get(), 1, 1, &callback);
ASSERT_EQ(bytes_read, 1u);
// As above because of data.
EXPECT_TRUE(sock_->IsConnected());
EXPECT_FALSE(sock_->IsConnectedAndIdle());
bytes_read =
DrainClientSocket(buf.get(), 4096, strlen(kServerReply) - 1, &callback);
ASSERT_EQ(bytes_read, strlen(kServerReply) - 1);
// Once the data is drained, the socket should now be seen as not
// connected.
if (sock_->IsConnected()) {
// In the unlikely event that the server's connection closure is not
// processed in time, wait for the connection to be closed.
int rv = sock_->Read(buf.get(), 4096, callback.callback());
EXPECT_EQ(0, callback.GetResult(rv));
EXPECT_FALSE(sock_->IsConnected());
}
EXPECT_FALSE(sock_->IsConnectedAndIdle());
}
TEST_P(TransportClientSocketTest, Read) {
TestCompletionCallback callback;
EstablishConnection(&callback);
SendRequestAndResponse();
scoped_refptr<IOBuffer> buf(new IOBuffer(4096));
uint32_t bytes_read =
DrainClientSocket(buf.get(), 4096, strlen(kServerReply), &callback);
ASSERT_EQ(bytes_read, strlen(kServerReply));
ASSERT_EQ(std::string(kServerReply), std::string(buf->data(), bytes_read));
// All data has been read now. Read once more to force an ERR_IO_PENDING, and
// then close the server socket, and note the close.
int rv = sock_->Read(buf.get(), 4096, callback.callback());
ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
CloseServerSocket();
EXPECT_EQ(0, callback.WaitForResult());
}
TEST_P(TransportClientSocketTest, Read_SmallChunks) {
TestCompletionCallback callback;
EstablishConnection(&callback);
SendRequestAndResponse();
scoped_refptr<IOBuffer> buf(new IOBuffer(1));
uint32_t bytes_read = 0;
while (bytes_read < strlen(kServerReply)) {
int rv = sock_->Read(buf.get(), 1, callback.callback());
EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
rv = callback.GetResult(rv);
ASSERT_EQ(1, rv);
bytes_read += rv;
}
// All data has been read now. Read once more to force an ERR_IO_PENDING, and
// then close the server socket, and note the close.
int rv = sock_->Read(buf.get(), 1, callback.callback());
ASSERT_THAT(rv, IsError(ERR_IO_PENDING));
CloseServerSocket();
EXPECT_EQ(0, callback.WaitForResult());
}
TEST_P(TransportClientSocketTest, Read_Interrupted) {
TestCompletionCallback callback;
EstablishConnection(&callback);
SendRequestAndResponse();
// Do a partial read and then exit. This test should not crash!
scoped_refptr<IOBuffer> buf(new IOBuffer(16));
int rv = sock_->Read(buf.get(), 16, callback.callback());
EXPECT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
rv = callback.GetResult(rv);
EXPECT_NE(0, rv);
}
TEST_P(TransportClientSocketTest, FullDuplex_ReadFirst) {
TestCompletionCallback callback;
EstablishConnection(&callback);
// Read first. There's no data, so it should return ERR_IO_PENDING.
const int kBufLen = 4096;
scoped_refptr<IOBuffer> buf(new IOBuffer(kBufLen));
int rv = sock_->Read(buf.get(), kBufLen, callback.callback());
EXPECT_THAT(rv, IsError(ERR_IO_PENDING));
const int kWriteBufLen = 64 * 1024;
scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kWriteBufLen));
char* request_data = request_buffer->data();
memset(request_data, 'A', kWriteBufLen);
TestCompletionCallback write_callback;
int bytes_written = 0;
while (true) {
rv = sock_->Write(request_buffer.get(), kWriteBufLen,
write_callback.callback());
ASSERT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
if (rv == ERR_IO_PENDING) {
ReadServerData(bytes_written);
SendServerResponse();
rv = write_callback.WaitForResult();
break;
}
bytes_written += rv;
}
// At this point, both read and write have returned ERR_IO_PENDING, and the
// write callback has executed. We wait for the read callback to run now to
// make sure that the socket can handle full duplex communications.
rv = callback.WaitForResult();
EXPECT_GE(rv, 0);
}
// FLaky on Win 10 Tests x64 builder: http://crbug/552053
TEST_P(TransportClientSocketTest, DISABLED_FullDuplex_WriteFirst) {
TestCompletionCallback callback;
EstablishConnection(&callback);
const int kWriteBufLen = 64 * 1024;
scoped_refptr<IOBuffer> request_buffer(new IOBuffer(kWriteBufLen));
char* request_data = request_buffer->data();
memset(request_data, 'A', kWriteBufLen);
TestCompletionCallback write_callback;
int bytes_written = 0;
while (true) {
int rv = sock_->Write(request_buffer.get(), kWriteBufLen,
write_callback.callback());
ASSERT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
if (rv == ERR_IO_PENDING)
break;
bytes_written += rv;
}
// Now we have the Write() blocked on ERR_IO_PENDING. It's time to force the
// Read() to block on ERR_IO_PENDING too.
const int kBufLen = 4096;
scoped_refptr<IOBuffer> buf(new IOBuffer(kBufLen));
while (true) {
int rv = sock_->Read(buf.get(), kBufLen, callback.callback());
ASSERT_TRUE(rv >= 0 || rv == ERR_IO_PENDING);
if (rv == ERR_IO_PENDING)
break;
}
// At this point, both read and write have returned ERR_IO_PENDING. Now we
// run the write and read callbacks to make sure they can handle full duplex
// communications.
ReadServerData(bytes_written);
SendServerResponse();
int rv = write_callback.WaitForResult();
EXPECT_GE(rv, 0);
// It's possible the read is blocked because it's already read all the data.
// Close the server socket, so there will at least be a 0-byte read.
CloseServerSocket();
rv = callback.WaitForResult();
EXPECT_GE(rv, 0);
}
} // namespace net
| [
"[email protected]"
] | |
29c38297f3f47e4f49605cb84d9b60a9eed692d3 | 40525c30da6c26a1cbbc46c7cd64977bb1e25233 | /desktop/src/utility/omPrimeNumbers.cpp | f4e3f01752b50e364e08b60899034a9d98e29113 | [] | no_license | seung-lab/omni.play | e17f5c977c9458a71062c1383d63baedf8ef6458 | a4f1220e9df499f05457aaaee5bc68c2b66d4d54 | refs/heads/master | 2021-03-24T12:36:23.997379 | 2016-08-11T15:09:01 | 2016-08-11T15:09:01 | 3,678,095 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 384 | cpp | #include "utility/omPrimeNumbers.hpp"
#include "common/exception.h"
int om::constants::getNextBiggestPrime(const int num) {
const int* nextBiggestPrime =
std::lower_bound(first1000Primes.begin(), first1000Primes.end(), num);
if (nextBiggestPrime == first1000Primes.end()) {
throw om::IoException("couldn't find next biggest prime");
}
return *nextBiggestPrime;
}
| [
"[email protected]"
] | |
200287a4c70e207f790faf141b5f2bac486e57e3 | cae0243512e1614fc9ef945713c9499d1a56d389 | /src/expressions/singleton_expression.cpp | 425ef055ab3d4425fdf96f33ff4ab64444e78e87 | [] | no_license | alejandro-reyesamaro/POSL | 15b5b58a9649234fa9bedbca4393550d38a69e7d | 0b3b7cf01a0392fc76394bbc04c52070637b3009 | refs/heads/master | 2021-04-15T11:10:24.998562 | 2016-09-06T15:10:54 | 2016-09-06T15:10:54 | 33,991,084 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 432 | cpp | #include "singleton_expression.h"
#include "../tools/tools.h"
#include "../tools/tokens_definition.h"
using namespace std;
SingletonExpression::SingletonExpression()
: executed(false)
{}
bool SingletonExpression::evaluate(shared_ptr<PSP>)
{
if(!executed)
{
executed = true;
return true;
}
else return false;
}
string SingletonExpression::codeToSend()
{
return string(BE_SINGLETON_TOK);
}
| [
"[email protected]"
] | |
9f675bde49723e7919b3340d28b28166e4e8d790 | 66213c48da0b752dc6c350789935fe2b2b9ef5ca | /abc/273/d.cpp | 993ca47714f3c12d9788a2cf2df5b713f5139a85 | [] | no_license | taketakeyyy/atcoder | 28c58ae52606ba85852687f9e726581ab2539b91 | a57067be27b27db3fee008cbcfe639f5309103cc | refs/heads/master | 2023-09-04T16:53:55.172945 | 2023-09-04T07:25:59 | 2023-09-04T07:25:59 | 123,848,306 | 0 | 0 | null | 2019-04-21T07:39:45 | 2018-03-05T01:37:20 | Python | UTF-8 | C++ | false | false | 2,948 | cpp | #define _USE_MATH_DEFINES // M_PI等のフラグ
#include <bits/stdc++.h>
#define MOD 1000000007
#define COUNTOF(array) (sizeof(array)/sizeof(array[0]))
#define rep(i,n) for (int i = 0; i < (n); ++i)
#define intceil(a,b) ((a+(b-1))/b)
using namespace std;
using ll = long long;
using pii = pair<int,int>;
using pll = pair<long,long>;
const long long INF = LONG_LONG_MAX - 1001001001001001;
void chmax(int& x, int y) { x = max(x,y); }
void chmin(int& x, int y) { x = min(x,y); }
string vs = "URDL"; // 上右下左
vector<ll> vy = { -1, 0, 1, 0 };
vector<ll> vx = { 0, 1, 0, -1 };
void solve() {
ll H, W, rs, cs; cin >> H >> W >> rs >> cs;
// vector<vector<ll>> grid(H, vector<ll>(W, 0)); // H, Wはデカすぎ大丈夫?
ll N; cin >> N; // 10^5
map<ll,vector<ll>> RWall; // RWall[i] := 行iにある壁の位置
map<ll,vector<ll>> CWall; // CWall[i] := 列iにある壁の位置
for(ll i=0; i<N; i++) {
ll r, c; cin >> r >> c;
// grid[r][c] = 1;
RWall[r].push_back(c);
CWall[c].push_back(r);
}
for(auto [key, ignore]: RWall) {
sort(RWall[key].begin(), RWall[key].end());
}
for(auto [key, ignore]: CWall) {
sort(CWall[key].begin(), CWall[key].end());
}
// クエリ
{
ll r = rs, c = cs;
ll Q; cin >> Q; // 10^5
for(ll q=0; q<Q; q++) {
char d; cin >> d;
ll l; cin >> l;
if (d == 'U') {
ll idx = lower_bound(CWall[c].begin(), CWall[c].end(), r) - CWall[c].begin();
if (idx == 0) {
r = max(r-l, 1LL);
}
else {
r = max(r-l, CWall[c][idx-1]+1);
}
}
if (d == 'D') {
ll idx = lower_bound(CWall[c].begin(), CWall[c].end(), r) - CWall[c].begin();
if (idx == (ll)CWall[c].size()) {
r = min(r+l, H);
}
else {
r = min(r+l, CWall[c][idx]-1);
}
}
if (d == 'L') {
ll idx = lower_bound(RWall[r].begin(), RWall[r].end(), c) - RWall[r].begin();
if (idx == 0) {
c = max(c-l, 1LL);
}
else {
c = max(c-l, RWall[r][idx-1]+1);
}
}
if (d == 'R') {
ll idx = lower_bound(RWall[r].begin(), RWall[r].end(), c) - RWall[r].begin();
if (idx == (ll)RWall[r].size()) {
c = min(c+l, W);
}
else {
c = min(c+l, RWall[r][idx]-1);
}
}
// 出力
cout << r << " " << c << endl;
}
}
}
int main() {
solve();
return 0;
} | [
"[email protected]"
] | |
4733584e1a294d753d17f3066c8100b11a59ca0e | 46eb609f59289b65b9480d7b1e2c482f416bb355 | /Algo Notes/DP/MinNoOFSquares.cpp | 8e36da3b80c1f85e5d3d63e235b0be3032c425dc | [] | no_license | sivagirish81/Algorithms | af15be52db79ba7fb2dd687ed7ebc14686c74b19 | 03f64ba8c93da8f29cb08dc36f00c5e8124529e7 | refs/heads/master | 2021-07-12T20:05:51.202204 | 2020-05-22T07:42:09 | 2020-05-22T07:42:09 | 134,872,524 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 545 | cpp | #include <iostream>
#include <bits/stdc++.h>
using namespace std;
int mini(int a,int b)
{
return (a>b)?b:a;
}
int getMinSquares(int N)
{
int DP[N+1];
DP[0]=0;
DP[1]=1;
DP[2]=2;
DP[3]=3;
int Min;
for (int i=4;i<=N;i++)
{
DP[i]=i;
for (int j=1;j<=sqrt(i);j++)
{
DP[i]=mini(1+DP[i-(j*j)],DP[i]);
}
}
return DP[N];
}
int main() {
//code
int T;
cin >> T;
int N;
for (int i=0;i<T;i++)
{
cin >> N;
cout << getMinSquares(N)<<"\n";
}
return 0;
} | [
"[email protected]"
] | |
dff96983e6b692e0f7b7bc267874f18aa2f76294 | 9bdadc7121dd035f3612324a5db20515e9c48440 | /Hand.cpp | 1ea2ad5a4308bf524adbd55085add34178cc2901 | [] | no_license | keselme90/PokerHomeAssignment | e0f7c6a6e0329b47a7db48786d988795bd04c9cd | 99f47bd6ea255edf03aad422445d2342bfe6cdc1 | refs/heads/master | 2021-08-23T21:51:48.358933 | 2017-12-06T18:20:06 | 2017-12-06T18:20:06 | 110,849,158 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 806 | cpp | #include "Hand.h"
/*
Constructor
Receives a string that represents the Cards.
Parse the string and creates a vector of cards.
*/
Hand::Hand(std::string cards) {
cards = cards.substr(cards.find(":") + 1);
while (cards.size() != 2) {
Card card(cards.substr(0, cards.find("-")));
myCards.push_back(card);
cards = cards.substr(cards.find("-") + 1);
}
Card card(cards);
myCards.push_back(card);
}
/**
Returns a specific card from the vector according a given index.
*/
const Card Hand::getCard(int index) const {
return myCards[index];
}
/**
* Prints the deck of cards to the screen
*/
void Hand::printHand(){
std::cout << "My hand is: ";
for (std::vector<Card>::iterator it = myCards.begin(); it != myCards.end(); it++)
std::cout << it->toString() << " ";
std::cout << std::endl;
}
| [
"[email protected]"
] | |
d154812310df0a2189dee4eee45bf7af968ac571 | e45ffa7500070ceae1a92847195077b960323e48 | /StealthGame/Source/FPSGame/Private/FPSObjectiveActor.cpp | 93e855d6b8071322f55143eef9d67a410d8337bd | [] | no_license | luvtin/UE_Training | eaf18e2a5703147a24af269886ce4b4f39583dd4 | dd9f311dd86f8d6f624fae3223aea41df7f8235d | refs/heads/main | 2023-01-20T20:42:55.472071 | 2020-12-03T07:49:43 | 2020-12-03T07:49:43 | 317,104,131 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,458 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "FPSObjectiveActor.h"
#include "Components/StaticMeshComponent.h"
#include "Components/SphereComponent.h"
#include "Kismet/GameplayStatics.h"
#include "FPSCharacter.h"
// Sets default values
AFPSObjectiveActor::AFPSObjectiveActor()
{
PrimaryActorTick.bCanEverTick = true;
MeshComp = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("MeshComp"));
MeshComp->SetCollisionEnabled(ECollisionEnabled::NoCollision);
RootComponent = MeshComp;
SphereComp = CreateDefaultSubobject<USphereComponent>(TEXT("SphereComp"));
SphereComp->SetCollisionEnabled(ECollisionEnabled::QueryOnly);
SphereComp->SetCollisionResponseToAllChannels(ECR_Ignore);
SphereComp->SetCollisionResponseToChannel(ECC_Pawn, ECR_Overlap);
SphereComp->SetupAttachment(MeshComp);
//服务器同步设置
SetReplicates(true);
}
// Called when the game starts or when spawned
void AFPSObjectiveActor::BeginPlay()
{
Super::BeginPlay();
PlayEffects();
}
void AFPSObjectiveActor::PlayEffects()
{
UGameplayStatics::SpawnEmitterAtLocation(this, PickupFX, GetActorLocation());
}
void AFPSObjectiveActor::NotifyActorBeginOverlap(AActor* OtherActor)
{
Super::NotifyActorBeginOverlap(OtherActor);
PlayEffects();
if (HasAuthority())
{
AFPSCharacter* MyCharacter = Cast<AFPSCharacter>(OtherActor);
if (MyCharacter)
{
MyCharacter->bIsCarryingObjective = true;
Destroy();
}
}
}
| [
"[email protected]"
] | |
8b9c5ee56c1c4714e70d03007736ff9950f20401 | efd7adff589e37ca98d2e3eb245aaeb23f64496e | /src/plugins/coreplugin/fancyactionbar.cpp | a5afc6d78a7b530ab1246441bb126116c0cacce0 | [] | no_license | Andersbakken/CPlusPlus | 3cf03c28968243587fa1d4661e7e5a388e62eb43 | 400f0b8f19de1c3fc9b794228c7aeec2259fce81 | refs/heads/master | 2021-01-10T20:24:54.067140 | 2013-05-28T03:46:50 | 2013-05-28T03:46:50 | 9,491,173 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,501 | cpp | /****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "fancyactionbar.h"
#include "coreconstants.h"
#include <utils/hostosinfo.h>
#include <utils/stylehelper.h>
#include <utils/stringutils.h>
#include <utils/tooltip/tooltip.h>
#include <utils/tooltip/tipcontents.h>
#include <QPainter>
#include <QVBoxLayout>
#include <QAction>
#include <QStyle>
#include <QStyleOption>
#include <QMouseEvent>
#include <QEvent>
#include <QPropertyAnimation>
#include <QDebug>
using namespace Core;
using namespace Internal;
FancyToolButton::FancyToolButton(QWidget *parent)
: QToolButton(parent), m_fader(0)
{
m_hasForceVisible = false;
setAttribute(Qt::WA_Hover, true);
setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
}
void FancyToolButton::forceVisible(bool visible)
{
m_hasForceVisible = true;
setVisible(visible);
}
bool FancyToolButton::event(QEvent *e)
{
switch (e->type()) {
case QEvent::Enter:
{
QPropertyAnimation *animation = new QPropertyAnimation(this, "fader");
animation->setDuration(125);
animation->setEndValue(1.0);
animation->start(QAbstractAnimation::DeleteWhenStopped);
}
break;
case QEvent::Leave:
{
QPropertyAnimation *animation = new QPropertyAnimation(this, "fader");
animation->setDuration(125);
animation->setEndValue(0.0);
animation->start(QAbstractAnimation::DeleteWhenStopped);
}
break;
case QEvent::ToolTip:
{
QHelpEvent *he = static_cast<QHelpEvent *>(e);
Utils::ToolTip::instance()->show(mapToGlobal(he->pos()), Utils::TextContent(toolTip()), this);
return true;
}
default:
return QToolButton::event(e);
}
return false;
}
static QVector<QString> splitInTwoLines(const QString &text, const QFontMetrics &fontMetrics,
qreal availableWidth)
{
// split in two lines.
// this looks if full words can be split off at the end of the string,
// to put them in the second line. First line is drawn with ellipsis,
// second line gets ellipsis if it couldn't split off full words.
QVector<QString> splitLines(2);
QRegExp rx(QLatin1String("\\s+"));
int splitPos = -1;
int nextSplitPos = text.length();
do {
nextSplitPos = rx.lastIndexIn(text,
nextSplitPos - text.length() - 1);
if (nextSplitPos != -1) {
int splitCandidate = nextSplitPos + rx.matchedLength();
if (fontMetrics.width(text.mid(splitCandidate)) <= availableWidth)
splitPos = splitCandidate;
else
break;
}
} while (nextSplitPos > 0 && fontMetrics.width(text.left(nextSplitPos)) > availableWidth);
// check if we could split at white space at all
if (splitPos < 0) {
splitLines[0] = fontMetrics.elidedText(text, Qt::ElideRight,
availableWidth);
QString common = Utils::commonPrefix(QStringList()
<< splitLines[0] << text);
splitLines[1] = text.mid(common.length());
// elide the second line even if it fits, since it is cut off in mid-word
while (fontMetrics.width(QChar(0x2026) /*'...'*/ + splitLines[1]) > availableWidth
&& splitLines[1].length() > 3
/*keep at least three original characters (should not happen)*/) {
splitLines[1].remove(0, 1);
}
splitLines[1] = QChar(0x2026) /*'...'*/ + splitLines[1];
} else {
splitLines[0] = fontMetrics.elidedText(text.left(splitPos).trimmed(), Qt::ElideRight, availableWidth);
splitLines[1] = text.mid(splitPos);
}
return splitLines;
}
void FancyToolButton::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QPainter painter(this);
// draw borders
bool isTitledAction = defaultAction()->property("titledAction").toBool();
if (!Utils::HostOsInfo::isMacHost() // Mac UIs usually don't hover
&& m_fader > 0 && isEnabled() && !isDown() && !isChecked()) {
painter.save();
int fader = int(40 * m_fader);
QLinearGradient grad(rect().topLeft(), rect().topRight());
grad.setColorAt(0, Qt::transparent);
grad.setColorAt(0.5, QColor(255, 255, 255, fader));
grad.setColorAt(1, Qt::transparent);
painter.fillRect(rect(), grad);
painter.setPen(QPen(grad, 1.0));
painter.drawLine(rect().topLeft(), rect().topRight());
painter.drawLine(rect().bottomLeft(), rect().bottomRight());
painter.restore();
} else if (isDown() || isChecked()) {
painter.save();
QLinearGradient grad(rect().topLeft(), rect().topRight());
grad.setColorAt(0, Qt::transparent);
grad.setColorAt(0.5, QColor(0, 0, 0, 50));
grad.setColorAt(1, Qt::transparent);
painter.fillRect(rect(), grad);
painter.setPen(QPen(grad, 1.0));
painter.drawLine(rect().topLeft(), rect().topRight());
painter.drawLine(rect().topLeft(), rect().topRight());
painter.drawLine(rect().topLeft() + QPoint(0,1), rect().topRight() + QPoint(0,1));
painter.drawLine(rect().bottomLeft(), rect().bottomRight());
painter.drawLine(rect().bottomLeft(), rect().bottomRight());
painter.drawLine(rect().topLeft() - QPoint(0,1), rect().topRight() - QPoint(0,1));
painter.restore();
}
QPixmap borderPixmap;
QMargins margins;
QRect iconRect(0, 0, Core::Constants::TARGET_ICON_SIZE, Core::Constants::TARGET_ICON_SIZE);
// draw popup texts
if (isTitledAction) {
QFont normalFont(painter.font());
QRect centerRect = rect();
normalFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
QFont boldFont(normalFont);
boldFont.setBold(true);
QFontMetrics fm(normalFont);
QFontMetrics boldFm(boldFont);
int lineHeight = boldFm.height();
int textFlags = Qt::AlignVCenter|Qt::AlignHCenter;
const QString projectName = defaultAction()->property("heading").toString();
if (!projectName.isNull())
centerRect.adjust(0, lineHeight + 4, 0, 0);
centerRect.adjust(0, 0, 0, -lineHeight*2 - 4);
iconRect.moveCenter(centerRect.center());
Utils::StyleHelper::drawIconWithShadow(icon(), iconRect, &painter, isEnabled() ? QIcon::Normal : QIcon::Disabled);
painter.setFont(normalFont);
QPoint textOffset = centerRect.center() - QPoint(iconRect.width()/2, iconRect.height()/2);
textOffset = textOffset - QPoint(0, lineHeight + 4);
QRectF r(0, textOffset.y(), rect().width(), lineHeight);
QColor penColor;
if (isEnabled())
penColor = Qt::white;
else
penColor = Qt::gray;
painter.setPen(penColor);
// draw project name
const int margin = 6;
const qreal availableWidth = r.width() - margin;
QString ellidedProjectName = fm.elidedText(projectName, Qt::ElideMiddle, availableWidth);
if (isEnabled()) {
const QRectF shadowR = r.translated(0, 1);
painter.setPen(QColor(30, 30, 30, 80));
painter.drawText(shadowR, textFlags, ellidedProjectName);
painter.setPen(penColor);
}
painter.drawText(r, textFlags, ellidedProjectName);
// draw build configuration name
textOffset = iconRect.center() + QPoint(iconRect.width()/2, iconRect.height()/2);
QRectF buildConfigRect[2];
buildConfigRect[0] = QRectF(0, textOffset.y() + 5, rect().width(), lineHeight);
buildConfigRect[1] = QRectF(0, textOffset.y() + 5 + lineHeight, rect().width(), lineHeight);
painter.setFont(boldFont);
QVector<QString> splitBuildConfiguration(2);
const QString buildConfiguration = defaultAction()->property("subtitle").toString();
if (boldFm.width(buildConfiguration) <= availableWidth) {
// text fits in one line
splitBuildConfiguration[0] = buildConfiguration;
} else {
splitBuildConfiguration = splitInTwoLines(buildConfiguration, boldFm, availableWidth);
}
// draw the two lines for the build configuration
for (int i = 0; i < 2; ++i) {
if (splitBuildConfiguration[i].isEmpty())
continue;
if (isEnabled()) {
const QRectF shadowR = buildConfigRect[i].translated(0, 1);
painter.setPen(QColor(30, 30, 30, 80));
painter.drawText(shadowR, textFlags, splitBuildConfiguration[i]);
painter.setPen(penColor);
}
painter.drawText(buildConfigRect[i], textFlags, splitBuildConfiguration[i]);
}
// pop up arrow next to icon
if (!icon().isNull()) {
QStyleOption opt;
opt.initFrom(this);
opt.rect = rect().adjusted(rect().width() - 16, 0, -8, 0);
Utils::StyleHelper::drawArrow(QStyle::PE_IndicatorArrowRight, &painter, &opt);
}
} else {
iconRect.moveCenter(rect().center());
Utils::StyleHelper::drawIconWithShadow(icon(), iconRect, &painter, isEnabled() ? QIcon::Normal : QIcon::Disabled);
}
}
void FancyActionBar::paintEvent(QPaintEvent *event)
{
QPainter painter(this);
Q_UNUSED(event)
QColor light = Utils::StyleHelper::sidebarHighlight();
QColor dark = Utils::StyleHelper::sidebarShadow();
painter.setPen(dark);
painter.drawLine(rect().topLeft(), rect().topRight());
painter.setPen(light);
painter.drawLine(rect().topLeft() + QPoint(1,1), rect().topRight() + QPoint(0,1));
}
QSize FancyToolButton::sizeHint() const
{
QSizeF buttonSize = iconSize().expandedTo(QSize(64, 38));
if (defaultAction()->property("titledAction").toBool()) {
QFont boldFont(font());
boldFont.setPointSizeF(Utils::StyleHelper::sidebarFontSize());
boldFont.setBold(true);
QFontMetrics fm(boldFont);
qreal lineHeight = fm.height();
const QString projectName = defaultAction()->property("heading").toString();
buttonSize += QSizeF(0, 10);
if (!projectName.isEmpty())
buttonSize += QSizeF(0, lineHeight + 2);
buttonSize += QSizeF(0, lineHeight*2 + 2);
}
return buttonSize.toSize();
}
QSize FancyToolButton::minimumSizeHint() const
{
return QSize(8, 8);
}
void FancyToolButton::actionChanged()
{
// the default action changed in some way, e.g. it might got hidden
// since we inherit a tool button we won't get invisible, so do this here
if (!m_hasForceVisible) {
if (QAction* action = defaultAction())
setVisible(action->isVisible());
}
}
FancyActionBar::FancyActionBar(QWidget *parent)
: QWidget(parent)
{
setObjectName(QLatin1String("actionbar"));
m_actionsLayout = new QVBoxLayout;
QVBoxLayout *spacerLayout = new QVBoxLayout;
spacerLayout->addLayout(m_actionsLayout);
int sbh = 8;
spacerLayout->addSpacing(sbh);
spacerLayout->setMargin(0);
spacerLayout->setSpacing(0);
setLayout(spacerLayout);
setContentsMargins(0,2,0,0);
}
void FancyActionBar::addProjectSelector(QAction *action)
{
FancyToolButton* toolButton = new FancyToolButton(this);
toolButton->setDefaultAction(action);
connect(action, SIGNAL(changed()), toolButton, SLOT(actionChanged()));
m_actionsLayout->insertWidget(0, toolButton);
}
void FancyActionBar::insertAction(int index, QAction *action)
{
FancyToolButton *toolButton = new FancyToolButton(this);
toolButton->setDefaultAction(action);
connect(action, SIGNAL(changed()), toolButton, SLOT(actionChanged()));
m_actionsLayout->insertWidget(index, toolButton);
}
QLayout *FancyActionBar::actionsLayout() const
{
return m_actionsLayout;
}
QSize FancyActionBar::minimumSizeHint() const
{
return sizeHint();
}
| [
"[email protected]"
] | |
b1dff3574b2f4b576f97a4243ca683e040320c90 | 228fcc5b80d7c76330b9093dac1af5fdce22c68f | /ch07/ex-7.12.h | 0e0925c7b806620d06fe3e349b39af0d215d698d | [] | no_license | carrordeng/Cpp | e5b61e712c4d8fbde04d295635b67025430cec91 | 7a04445f3529901d4c5d6f6b5737b6a25dfe5818 | refs/heads/master | 2020-05-24T07:01:50.089485 | 2019-09-14T09:19:12 | 2019-09-14T09:19:12 | 163,169,407 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,587 | h | #ifndef EX_7_12_H
#define EX_7_12_H
#include <iostream>
#include <string>
struct Sales_data;
std::istream &read(std::istream &is, Sales_data &data);
struct Sales_data
{
std::string bookNo;
std::string bookName;
unsigned units_sold = 0;
double price = 0.0;
double revenue = 0.0;
//add constructors
Sales_data() = default;
Sales_data(const std::string &No, const std::string &Name) : bookNo(No), bookName(Name) {}
Sales_data(const std::string &No, const std::string &Name, const unsigned &us, const double &p) : bookNo(No), bookName(Name), units_sold(us), price(p) { calRevenue(); }
Sales_data(std::istream &is)
{
read(is, *this);
calRevenue();
}
//member functions
inline void calRevenue() { revenue = units_sold * price; }
std::string isbn() const { return bookNo; }
Sales_data &combine(const Sales_data &data);
};
//nonmember functions
Sales_data add(const Sales_data &lhs, const Sales_data &rhs)
{
Sales_data sum = lhs;
return sum.combine(rhs);
}
std::istream &read(std::istream &is, Sales_data &data)
{
is >> data.bookNo >> data.bookName >> data.units_sold >> data.price;
data.calRevenue();
return is;
}
std::ostream &print(std::ostream &os, const Sales_data &data)
{
os << data.bookNo << " " << data.bookName << " "
<< data.units_sold << " " << data.price << " " << data.revenue;
return os;
}
//member functions
Sales_data &Sales_data::combine(const Sales_data &data)
{
units_sold += data.units_sold;
revenue += data.revenue;
return *this;
}
#endif | [
"[email protected]"
] | |
15677e37058403c3588ce0c51921e3c7792e1d92 | 06f0b4758414e058ac66b87c959651d3d087aee6 | /JuceLibraryCode/modules/juce_events/messages/juce_ApplicationBase.cpp | ac6e8e164521ed3a30026318531654e9a94be844 | [] | no_license | nllve/SimpleScope | 404c2a21f342b8282c5a2bf54656fcb6eb8d87fc | 4fbb5edc97c6de65c50f0e51cbef29f720c81cf7 | refs/heads/master | 2021-01-19T20:47:50.044467 | 2017-04-17T19:06:08 | 2017-04-17T19:06:08 | 88,554,327 | 0 | 1 | null | 2017-04-17T21:57:28 | 2017-04-17T21:57:28 | null | UTF-8 | C++ | false | false | 9,525 | cpp | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2016 - ROLI Ltd.
Permission is granted to use this software under the terms of the ISC license
http://www.isc.org/downloads/software-support-policy/isc-license/
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
OF THIS SOFTWARE.
-----------------------------------------------------------------------------
To release a closed-source product which uses other parts of JUCE not
licensed under the ISC terms, commercial licenses are available: visit
www.juce.com for more information.
==============================================================================
*/
JUCEApplicationBase::CreateInstanceFunction JUCEApplicationBase::createInstance = 0;
JUCEApplicationBase* JUCEApplicationBase::appInstance = nullptr;
JUCEApplicationBase::JUCEApplicationBase()
: appReturnValue (0),
stillInitialising (true)
{
jassert (isStandaloneApp() && appInstance == nullptr);
appInstance = this;
}
JUCEApplicationBase::~JUCEApplicationBase()
{
jassert (appInstance == this);
appInstance = nullptr;
}
void JUCEApplicationBase::setApplicationReturnValue (const int newReturnValue) noexcept
{
appReturnValue = newReturnValue;
}
// This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
void JUCEApplicationBase::appWillTerminateByForce()
{
JUCE_AUTORELEASEPOOL
{
{
const ScopedPointer<JUCEApplicationBase> app (appInstance);
if (app != nullptr)
app->shutdownApp();
}
DeletedAtShutdown::deleteAll();
MessageManager::deleteInstance();
}
}
void JUCEApplicationBase::quit()
{
MessageManager::getInstance()->stopDispatchLoop();
}
void JUCEApplicationBase::sendUnhandledException (const std::exception* const e,
const char* const sourceFile,
const int lineNumber)
{
if (JUCEApplicationBase* const app = JUCEApplicationBase::getInstance())
app->unhandledException (e, sourceFile, lineNumber);
}
//==============================================================================
#if ! (JUCE_IOS || JUCE_ANDROID)
#define JUCE_HANDLE_MULTIPLE_INSTANCES 1
#endif
#if JUCE_HANDLE_MULTIPLE_INSTANCES
struct JUCEApplicationBase::MultipleInstanceHandler : public ActionListener
{
public:
MultipleInstanceHandler (const String& appName)
: appLock ("juceAppLock_" + appName)
{
}
bool sendCommandLineToPreexistingInstance()
{
if (appLock.enter (0))
return false;
JUCEApplicationBase* const app = JUCEApplicationBase::getInstance();
jassert (app != nullptr);
MessageManager::broadcastMessage (app->getApplicationName()
+ "/" + app->getCommandLineParameters());
return true;
}
void actionListenerCallback (const String& message) override
{
if (JUCEApplicationBase* const app = JUCEApplicationBase::getInstance())
{
const String appName (app->getApplicationName());
if (message.startsWith (appName + "/"))
app->anotherInstanceStarted (message.substring (appName.length() + 1));
}
}
private:
InterProcessLock appLock;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MultipleInstanceHandler)
};
bool JUCEApplicationBase::sendCommandLineToPreexistingInstance()
{
jassert (multipleInstanceHandler == nullptr); // this must only be called once!
multipleInstanceHandler = new MultipleInstanceHandler (getApplicationName());
return multipleInstanceHandler->sendCommandLineToPreexistingInstance();
}
#else
struct JUCEApplicationBase::MultipleInstanceHandler {};
#endif
//==============================================================================
#if JUCE_ANDROID
StringArray JUCEApplicationBase::getCommandLineParameterArray() { return {}; }
String JUCEApplicationBase::getCommandLineParameters() { return {}; }
#else
#if JUCE_WINDOWS && ! defined (_CONSOLE)
String JUCE_CALLTYPE JUCEApplicationBase::getCommandLineParameters()
{
return CharacterFunctions::findEndOfToken (CharPointer_UTF16 (GetCommandLineW()),
CharPointer_UTF16 (L" "),
CharPointer_UTF16 (L"\"")).findEndOfWhitespace();
}
StringArray JUCE_CALLTYPE JUCEApplicationBase::getCommandLineParameterArray()
{
StringArray s;
int argc = 0;
if (LPWSTR* const argv = CommandLineToArgvW (GetCommandLineW(), &argc))
{
s = StringArray (argv + 1, argc - 1);
LocalFree (argv);
}
return s;
}
#else
#if JUCE_IOS
extern int juce_iOSMain (int argc, const char* argv[], void* classPtr);
#endif
#if JUCE_MAC
extern void initialiseNSApplication();
#endif
#if JUCE_WINDOWS
const char* const* juce_argv = nullptr;
int juce_argc = 0;
#else
extern const char* const* juce_argv; // declared in juce_core
extern int juce_argc;
#endif
String JUCEApplicationBase::getCommandLineParameters()
{
String argString;
for (int i = 1; i < juce_argc; ++i)
{
String arg (juce_argv[i]);
if (arg.containsChar (' ') && ! arg.isQuotedString())
arg = arg.quoted ('"');
argString << arg << ' ';
}
return argString.trim();
}
StringArray JUCEApplicationBase::getCommandLineParameterArray()
{
return StringArray (juce_argv + 1, juce_argc - 1);
}
int JUCEApplicationBase::main (int argc, const char* argv[], void* customDelegate)
{
JUCE_AUTORELEASEPOOL
{
juce_argc = argc;
juce_argv = argv;
#if JUCE_MAC
initialiseNSApplication();
#endif
#if JUCE_IOS
return juce_iOSMain (argc, argv, customDelegate);
#else
ignoreUnused (customDelegate);
return JUCEApplicationBase::main();
#endif
}
}
#endif
//==============================================================================
int JUCEApplicationBase::main()
{
ScopedJuceInitialiser_GUI libraryInitialiser;
jassert (createInstance != nullptr);
const ScopedPointer<JUCEApplicationBase> app (createInstance());
jassert (app != nullptr);
if (! app->initialiseApp())
return app->shutdownApp();
JUCE_TRY
{
// loop until a quit message is received..
MessageManager::getInstance()->runDispatchLoop();
}
JUCE_CATCH_EXCEPTION
return app->shutdownApp();
}
#endif
//==============================================================================
bool JUCEApplicationBase::initialiseApp()
{
#if JUCE_HANDLE_MULTIPLE_INSTANCES
if ((! moreThanOneInstanceAllowed()) && sendCommandLineToPreexistingInstance())
{
DBG ("Another instance is running - quitting...");
return false;
}
#endif
#if JUCE_WINDOWS && JUCE_STANDALONE_APPLICATION && (! defined (_CONSOLE)) && (! JUCE_MINGW)
if (AttachConsole (ATTACH_PARENT_PROCESS) != 0)
{
// if we've launched a GUI app from cmd.exe or PowerShell, we need this to enable printf etc.
// However, only reassign stdout, stderr, stdin if they have not been already opened by
// a redirect or similar.
FILE* ignore;
if (_fileno(stdout) < 0) freopen_s (&ignore, "CONOUT$", "w", stdout);
if (_fileno(stderr) < 0) freopen_s (&ignore, "CONOUT$", "w", stderr);
if (_fileno(stdin) < 0) freopen_s (&ignore, "CONIN$", "r", stdin);
}
#endif
// let the app do its setting-up..
initialise (getCommandLineParameters());
stillInitialising = false;
if (MessageManager::getInstance()->hasStopMessageBeenSent())
return false;
#if JUCE_HANDLE_MULTIPLE_INSTANCES
if (multipleInstanceHandler != nullptr)
MessageManager::getInstance()->registerBroadcastListener (multipleInstanceHandler);
#endif
return true;
}
int JUCEApplicationBase::shutdownApp()
{
jassert (JUCEApplicationBase::getInstance() == this);
#if JUCE_HANDLE_MULTIPLE_INSTANCES
if (multipleInstanceHandler != nullptr)
MessageManager::getInstance()->deregisterBroadcastListener (multipleInstanceHandler);
#endif
JUCE_TRY
{
// give the app a chance to clean up..
shutdown();
}
JUCE_CATCH_EXCEPTION
multipleInstanceHandler = nullptr;
return getApplicationReturnValue();
}
| [
"[email protected]"
] | |
7b68ab553578b04f767dad87ea12b366bae9e1d3 | 57c3f826d8943d448aefe05f464ac50e2642e2bf | /desctable.hpp | 00721462f6c8e9bb2fbee81203f2098d8f5fe0a9 | [] | no_license | uchan-nos/seccamp-os | 36ddc9e8c9d1b7e9678a331e9adaf7207d4744cb | da14bdce4b306c7fbbaf1771733618b7d687faf6 | refs/heads/master | 2021-01-16T19:37:07.661160 | 2017-08-13T14:36:18 | 2017-08-13T14:36:18 | 100,182,107 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 774 | hpp | #ifndef DESCTABLE_HPP_
#define DESCTABLE_HPP_
#include <stddef.h>
#include <stdint.h>
#include "errorcode.hpp"
namespace bitnos
{
struct DescriptorTableRegister
{
uint16_t limit;
uint64_t base;
};
DescriptorTableRegister GetGDTR();
DescriptorTableRegister GetIDTR();
constexpr uint16_t MakeIDTAttr(
uint8_t p, uint8_t dpl, uint8_t type, uint8_t ist)
{
return static_cast<uint16_t>(p) << 15
| static_cast<uint16_t>(dpl) << 13
| static_cast<uint16_t>(type) << 8
| ist;
}
Error SetIDTEntry(
DescriptorTableRegister idtr, size_t index,
uint64_t offset, uint16_t attr, uint16_t selector);
}
#endif // DESCTABLE_HPP_
| [
"[email protected]"
] | |
326ece91b3acb6a7051c203a67b037e8776f49fd | fe3bc924e354ea2f8ccf4dc166ae2cd2ad151fd3 | /src/THcScintillatorPlane.h | ce546684471fefb9bc8a518b01ef22f4a7bba198 | [] | no_license | jonstelz/hcana | 40ccff65a01a11dbc9b1a3e9f6e64a39f2b93285 | 49b16a642f1cb1d9adf1a12dbb33620b7ad1cddb | refs/heads/master | 2021-01-16T21:49:30.373046 | 2012-05-03T22:09:49 | 2012-05-03T22:09:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 995 | h | #ifndef ROOT_THcScintillatorPlane
#define ROOT_THcScintillatorPlane
//////////////////////////////////////////////////////////////////////////////
//
// THcScintillatorPlane
//
// A Hall C scintillator plane
//
// May want to later inherit from a THcPlane class if there are similarities
// in what a plane is shared with other detector types (shower, etc.)
//
//////////////////////////////////////////////////////////////////////////////
#include "THaNonTrackingDetector.h"
class THcScintillatorPlane : public THaNonTrackingDetector {
public:
virtual ~THcScintillatorPlane();
THcScintillatorPlane( const char* name, const char* description,
THaApparatus* a = NULL);
virtual Int_t CoarseProcess( TClonesArray& tracks ) = 0;
virtual Int_t FineProcess( TClonesArray& tracks ) = 0;
Bool_t IsTracking() { return kFALSE; }
virtual Bool_t IsPid() { return kFALSE; }
protected:
ClassDef(THcScintillatorPlane,0)
};
#endif
| [
"[email protected]"
] | |
9d84611dd9bb646560f300404cb0cc807c1a87e8 | 831a587acc73b3a4a3b5c09db4f6ecd11acfb3a4 | /Pacman/pacman/InputManager.h | cd101205e2b9daf8cb22dbb17ed47158ae35504b | [
"MIT"
] | permissive | Pocoder/arduino-pacman | 4b342d31fc9b8481a573b67051dade95256c2b90 | c56376b9b9a0ea6139231d7e158f230707449fce | refs/heads/master | 2022-04-08T18:01:23.908950 | 2020-03-02T13:15:49 | 2020-03-02T13:15:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 435 | h | #pragma once
#include <TouchScreen.h>
#include "Adafruit_GFX.h"
#include <MCUFRIEND_kbv.h>
#define MINPRESSURE 200
#define MAXPRESSURE 1000
class InputManager {
public:
InputManager(MCUFRIEND_kbv* p, TouchScreen* tscreen);
TSPoint get();
private:
const int TS_LEFT = 919, TS_RT = 194, TS_TOP = 185, TS_BOT = 915; //Calibrated
MCUFRIEND_kbv* tft;
TouchScreen* ts;
TSPoint tp;
int16_t xpos, ypos; //screen coordinates
};
| [
"[email protected]"
] | |
697d770019b3a64b74368e75139caaf6f94233d3 | 941ddcb9a01de873e51a253c68dcaa7b35544c52 | /inferui/inferui/model/syn_helper.h | a319c0058d90f5dd3fbe787e5cbc19c63839d27c | [] | no_license | eth-sri/inferui | b3ace5155483685876a413afa5b27e8d3b3c99b1 | 2e74a37547360a3571c005a10bbdd41e8805bf19 | refs/heads/master | 2023-03-07T05:27:55.602093 | 2021-02-14T21:21:17 | 2021-02-14T21:21:17 | 338,894,697 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,106 | h | /*
Copyright 2018 Software Reliability Lab, ETH Zurich
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#ifndef CC_SYNTHESIS_SYN_HELPER_H
#define CC_SYNTHESIS_SYN_HELPER_H
#include "inferui/model/model.h"
#include "inferui/layout_solver/solver.h"
// Try to fix inconsistencies of z3 solver and the Android layout solver by adjusting margins
// @returns true if rendering synthesized layout (in ref_app) using solver leads to same positions
bool TryFixInconsistencies(App* ref_app, Solver& solver);
// Try to replace margings (1,0) with (0,0)
void NormalizeMargins(App* ref_app, Solver& solver);
Json::Value DeviceToJson(const Device& device);
class JsonAppSerializer {
public:
static std::vector<Json::Value> readDirectory(const std::string& path);
static std::vector<Json::Value> readFile(const std::string& path);
static int JsonToApps(const Json::Value& request,
App& app, std::vector<App>& apps,
Device& ref_device, std::vector<Device>& devices);
static Json::Value ToJson(const App& app, const std::vector<App>& apps,
const Device& ref_device, const std::vector<Device>& devices);
static Json::Value ScreenToJson(const App& app, const Device& device);
static void AddScreenToJson(const App& app, const Device& device, Json::Value* data);
};
App EmptyApp(const App& ref, const Device& device);
App EmptyApp(const App& ref);
App KeepFirstNViews(const App& ref, int num_views);
bool ViewMatch(const View& A, const View& B);
bool AppMatch(const App& ref_app, const App& syn_app);
View JsonToView(const Json::Value& value);
App JsonToApp(const Json::Value& layout);
Json::Value ScaleApp(Json::Value value, double factor);
void ScaleAttributes(App& app, double scaling_factor);
double askOracle(
const App& candidate, //the candidate for which the probability should be predicted
Solver& solver,
const Device device, //the device on which the candidate coordinates are valid on
const std::string oracleType, //the type of oracle to be selected for the evaluation
const std::string dataset, //name of the dataset on which we are evaluation/generating data on
const std::string filename, //name of the file for which we generated a candidate
const App& targetApp, //complete app on the specified device (with all views)
const App& originalApp //app with coordinates on the original device
);
void writeAppData(std::string targetPath, std::string name, const std::vector<std::vector<App>>& all_candidateDeviceApps, const std::vector<App>& targetApps, const App& originalApp);
#endif //CC_SYNTHESIS_SYN_HELPER_H
| [
"[email protected]"
] | |
fb4665dd063416f124d8ad847fbe5d8aeacdaca2 | 25245cdad68304c439d7bb15f6efc80dc431df54 | /Learn_Game/GameState.h | 14ae4c2f7d1a1559ffb942c1d6b393f29adf4f83 | [] | no_license | ArturKnopik/Game | f25dc52f7d5b4e3c99bab9a5c02f53f9c00c4c24 | a6e49532097523acbd39bba967a81c9eaed3aafc | refs/heads/master | 2023-02-24T17:26:13.255822 | 2021-02-02T17:49:37 | 2021-02-02T17:49:37 | 166,843,827 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 303 | h | #pragma once
#include "Game.h"
//#include <memory>
class GameState {
protected :
std::shared_ptr<sf::Event> event;
std::shared_ptr<Game> game;
public:
GameState();
virtual void draw() = 0;
virtual void update(const double dt) = 0;
virtual void input() = 0;
virtual ~GameState()=default;
};
| [
"[email protected]"
] | |
d8f919f95bd5876363eb9de6d8331327231574a5 | c5fed927a7c40520c4c1a7e4064332781709a611 | /EmployeeManagement/Manager_main.cpp | 91f074b84f76463aa875248a8ebc6bf8d3a378bc | [] | no_license | BomengBomeng/WorkSpace | 1123019d376056bfd8fef641edcaf287c4c6cadf | d37499074ac66a98bc2b8a030080779d7e710991 | refs/heads/master | 2023-07-30T14:17:57.719410 | 2021-09-29T07:42:07 | 2021-09-29T07:42:07 | 340,826,273 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,325 | cpp | #include<iostream>
#include"WorkerManager.h"
#include"Worker.h"
#include"Employee.h"
#include"Manager.h"
#include"Boss.h"
using namespace std;
void test01(WorkerManager mv){
Worker *w = new Employee(128,"zhangsan",0);
w->ShowInfo();
Worker *x = new Manager(127,"zgsan",1);
x->ShowInfo();
Worker *y = new Boss(126,"zhann",3);
y->ShowInfo();
for(int i=0; i<mv.m_EmpNum; i++)
cout << mv.m_EmpArry[i]->m_Id << mv.m_EmpArry[i]->m_Name << mv.m_EmpArry[i]->m_DeptId << endl;
cout << "-------------------" << mv.m_EmpNum << " " << mv.m_FileIsEmpty << endl;
}
int main(){
system("clear");
WorkerManager mv;
//test01(mv);
int choice;
char ch;
while(true){
mv.Show_Menu();
cout << "please choose the operatioin: ";
cin >> choice;
switch(choice){
case 0:
mv.ExitSystem();
break;
case 1: mv.Add_Emp();
mv.save();
cout << endl << "input anything to go back: ";
cin>>ch;
break;
case 2: mv.show_Emp();
cout << endl << "input anything to go back: ";
cin>>ch;
break;
case 3: { int numb;
cout << "intput the id you want to delet: ";
cin >> numb;
mv.Del_Emp(numb);
mv.save();
cout << endl << "input anything to go back: ";
cin >> ch;
break;
}
case 4: {
int numb;
cout << "intput the id you want to medify: ";
cin >> numb;
mv.Medify_Emp(numb);
mv.save();
cout << endl << "input anything to go back: ";
cin >> ch;
break;
}
case 5:
{
int mode;
cout << "choose search mode (0.ID 1.name): ";
point:cin >> mode;
switch(mode){
case 0: {
int id;
cout << "please input the id: ";
cin >> id;
mv.search_by_ID(id);
break;
}
case 1: {
string name;
cout << "please intput the name: ";
cin >> name;
mv.search_by_Name(name);
break;
}
default:cout << "input error! try againe ";
goto point;
}
cout << endl << "input anything to go back: ";
cin >> ch;
break;
}
case 6: mv.Sort_by_ID();
mv.save();
cout << endl << "input anything to go back: ";
cin >> ch;
break;
case 7: {
mv.Clean();
cout << endl << "input anything to go back: ";
cin >> ch;
break;
}
}
system("clear");
}
return 0;
}
| [
"[email protected]"
] | |
a0300e55e039d8480b3c8c26e29bfb8a5b892e8e | 99cac5c821d967bcb6e2d5cc186b72117ee3a22c | /C++/NetEngine/Mutex.h | fed24901727281681c848d4cd5836bcb3c0e4c14 | [] | no_license | jbluepolarbear/Misc | 194578efb5a4fec2ae497403cd0873aad4c01d43 | 130ce090c0775e54c5449b75a8f877a012edabb1 | refs/heads/master | 2020-04-30T10:56:01.338334 | 2011-05-25T04:16:41 | 2011-05-25T04:16:41 | 1,796,450 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 228 | h | #pragma once
#ifndef HANDLE
typedef void *HANDLE;
#endif
class Mutex
{
public:
Mutex( bool Owned = false );
~Mutex();
bool Synchronize();
bool Release();
private:
HANDLE mutex;
bool owned;
};
| [
"[email protected]"
] | |
fa8fd947090d71534abbeb192ba22cea97352a4e | 2e5be7a7292596400c11f125d221fe59bca51fcb | /mainwindow.cpp | 48c530524dc980ea5c8b7e85ad0d894d44ebdf94 | [] | no_license | SenaliSiriwardhana/CheckMath | 357c583328deb3cced5a58bc41a57b3c7e866089 | cea514e39a7990e2c70c4608c893c8344a7adc08 | refs/heads/main | 2023-06-21T14:25:58.612691 | 2021-07-25T07:08:10 | 2021-07-25T07:08:10 | 389,284,911 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 377 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_Start_clicked()
{
hide();
cmg=new CheckMathGame(this);
cmg->show();
}
void MainWindow::on_Quit_clicked()
{
close();
}
| [
"[email protected]"
] | |
a758a5722dded5ed1b1f22c65cb844e9d3aa868e | 03b20afd312ba32e375d8a2619a070971f3e31f5 | /Coursera/Art of Development in Modern C++ Specialization/Red Belt/Week3/tasks/object_pool.cpp | ad06d67bd334df1c0c3a022a41a8934ae5a8c64e | [] | no_license | AndrewShkrob/Courses | 9c368e107786ba7c19a1744072d6f50bc332efbb | c5d95e468ac8ee0d38a6af7119c1d9c1962c4941 | refs/heads/master | 2022-10-05T02:48:38.388577 | 2020-06-06T14:25:27 | 2020-06-06T14:25:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,091 | cpp | #include <bits/stdc++.h>
using namespace std;
template<class T>
class ObjectPool {
public:
T *Allocate() {
if (deallocated.empty()) {
auto it = allocated.insert(new T);
return *(it.first);
}
return alloc();
}
T *TryAllocate() {
if (deallocated.empty())
return nullptr;
return alloc();
}
void Deallocate(T *object) {
auto it = allocated.find(object);
if (it == allocated.end())
throw invalid_argument("deallocate");
allocated.erase(it);
deallocated.push(object);
}
~ObjectPool() {
for (T *object : allocated) {
delete object;
}
while (!deallocated.empty()) {
T *object = deallocated.front();
deallocated.pop();
delete object;
}
}
private:
set<T *> allocated;
queue<T *> deallocated;
T *alloc() {
auto obj = deallocated.front();
deallocated.pop();
auto it = allocated.insert(obj);
return *(it.first);
}
};
| [
"[email protected]"
] | |
0b2e7e5a79412ad53f1d6cb48007e6603ea00192 | a5c8941d7f8face4962f506a584edb0efbd16ca6 | /develop/uvplus/uvbook-examples/lib-hello/hello.cpp | bb44b17f2c3f4b13ea6ac11c414ef9192e2d1568 | [
"MIT"
] | permissive | motoyang/sf315 | 3e365bc1c9dd91d7913a65aaeccf2594e95c3eae | 9ed5affd2c815068793e24932af877cc4aad86c1 | refs/heads/master | 2023-06-27T09:10:27.821676 | 2020-01-04T15:20:22 | 2020-01-04T15:20:22 | 119,141,655 | 1 | 1 | MIT | 2023-06-14T16:07:58 | 2018-01-27T07:02:33 | C++ | UTF-8 | C++ | false | false | 113 | cpp | #include <iostream>
extern "C" void initialize() {
std::cout << "initialize libhello plugin." << std::endl;
}
| [
"[email protected]"
] | |
ef7cc9ec0ef7abd2dd8393f464cb343d2f4df766 | 8104232777587882d47c45289040978787e727cc | /Math/Mod64.cpp | 56c67031a1bb689e6dbb1bd95d821a67cc9c2ce5 | [] | no_license | transcompany/chemthan | 1eea96be1498c81812dab4bcc6c6da4f37a904a5 | 15d9cb49d44011802c9f757d73a22e65a958ea02 | refs/heads/master | 2021-01-12T20:40:38.075394 | 2016-05-16T14:08:58 | 2016-05-16T14:08:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 669 | cpp | #include <bits/stdc++.h>
using namespace std;
#define T long long
T mulmod64(T a, T b, T p) {
a %= p; b %= p;
T r = 0;
int block = 1;
T base = 1LL << block;
for (; b; b >>= block) {
r = (r + a * (b & (base - 1))) % p;
a = a * base % p;
}
return r;
}
T powmod64(T n, T k, T p) {
if (!n) return 0;
T r = 1;
for (; k; k >>= 1) {
if (k & 1) r = mulmod64(r, n, p);
n = mulmod64(n, n, p);
}
return r;
}
int main() {
T a = (T) 1e15 + 2311;
T b = (T) 1e16 + 1992;
T p = (T) 1e18 + 2016;
cout<<mulmod64(a, b, p)<<"\n"; //Expect 81840000004553112
cout<<powmod64(a, b, p)<<"\n"; //Expect 457363391775234913
return 0;
}
| [
"[email protected]"
] | |
ba5d49085facaffd29816dc52ef015f0fcba3866 | da6d0c83c02032b041ddf748457c8c30baea68a4 | /Lista LLPI 1/Pessoa/Pessoa.cpp | 99d802b2a97a958c2a47c1918cda06d4e31998d6 | [] | no_license | Kcardas/Programing-Language-I | ef842279b567418db950e55409bbe85a685a8111 | bff31056a5b98eb47b3606920df4e81f0f272c4e | refs/heads/master | 2020-06-17T22:55:18.096965 | 2019-12-05T13:18:48 | 2019-12-05T13:18:48 | 196,089,684 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 564 | cpp | #include <iostream>
#include "Pessoa.h"
using namespace std;
Pessoa::Pessoa(){};
Pessoa::Pessoa(string name){
this->name = name;
}
Pessoa::Pessoa(string name, int age, string phone){
this->name = name;
this->age = age;
this->phone = phone;
};
string Pessoa::getName(){
return name;
};
string Pessoa::getPhone(){
return phone;
};
int Pessoa::getAge(){
return age;
};
void Pessoa::setName(string name){
this->name = name;
};
void Pessoa::setPhone(string phone){
this->phone = phone;
};
void Pessoa::setAge(int age){
this->age = age;
};
| [
"[email protected]"
] | |
e6dc36d0f1c106845a6b2a5ac8892714075c17fd | 3cc72e2d2c348a883ea9fedbd9be23c7ff5d9ffa | /CellAuto_Engine_V2/src/Shader.cpp | 5598bd4fe7a7f164c287612d1c1850f5105a3896 | [] | no_license | Qlala/Engine | 4d73a14153dfeb2a10b3b026ea1d9af990c1552e | edeac381fb7ecbd6c5451158854809c6608dc36d | refs/heads/master | 2021-01-20T19:39:30.957902 | 2017-08-28T12:23:07 | 2017-08-28T12:23:07 | 63,822,190 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 28,273 | cpp | #include "Header.h"
ShaderHandler::ShaderHandler(){
ShaderReady=false;
ShaderEnableCheck=true;
//AsyncMode=false;
ShaderDemandAnswered=CreateEvent(NULL, 0, 0, GenStrWithUniqueCode("ShaderDemandAnswered",false));
ShaderDemandSent=CreateEvent(NULL, 0, 0, GenStrWithUniqueCode("ShaderDemandSent"));
}
void ShaderHandler::CreatePipeline(){
glGenProgramPipelines(1,&ProgramPipeline);
GLPipelines.push_back({ProgramPipeline,false,true});
CurrentPipelineIndex=0;
ThreadId=GetCurrentThreadId();
ShaderReady=true;
}
//Synchronous Gestion
int ShaderHandler::ShaderCheckDemand(){
if(ShaderEnableCheck)
if(WaitForSingleObject(ShaderDemandSent,ShaderCheckTime)==WAIT_OBJECT_0){
switch(ShaderDemand){
//addShader
case(3):
IntIndex=InternAddShader(StringArgument,GLuintArgument, IntIndex);
ConsoleEcho("Un message recu");
SetEvent(ShaderDemandAnswered);
return IntIndex;
break;
//set active intern program (porgram stage)
case(5):
InternSetActiveInternProgram((GLuint*)IntArrayArgument,GLuintArrayArgument,IntIndex);
SetEvent(ShaderDemandAnswered);
return 0;
break;
case(4):
InternDeleteProgram(GLuintArgument);
SetEvent(ShaderDemandAnswered);
return 0;
break;
//Uniform Settings
case(6):
memory_fence();
InternSetUniform(GLuintArrayArgument[0],GLuintArrayArgument[1],PointerArgument,GLuintArrayArgument[2],StringArgument);
SetEvent(ShaderDemandAnswered);
return 0;
break;
case(7):
memory_fence();
InternSetUniform(GLuintArrayArgument[0],GLuintArrayArgument[1],PointerArgument,GLuintArrayArgument[2],GLuintArgument);
SetEvent(ShaderDemandAnswered);
return 0;
break;
case(8):
memory_fence();
GLuintArgument=InternGetLocation(StringArgument,GLuintArgument);
SetEvent(ShaderDemandAnswered);
return 0;
break;
case(9):
memory_fence();
AmbivalentUniform* AmbUni2;
*AmbUni2=InternGetAmbivalentLocation(StringArgument,GLuintArgument,GLuintArrayArgument[0],GLuintArrayArgument[1]);
PointerArgument=(void*)AmbUni2;
SetEvent(ShaderDemandAnswered);
return 0;
break;
case(10):
memory_fence();
GLuintArgument=InternCreateNewPipeline();
return 0;
break;
case(11):
memory_fence();
GLuintArgument=InternSwapPipeline(GLuintArgument);
return 0;
break;
case(12):
memory_fence();
InternDeletePipeline(GLuintArgument);
return 0;
break;
case(2):
memory_fence();
InternShaderHandlerDestructor();
SetEvent(ShaderDemandAnswered);
return 0;
}
}
Sleep(ShaderIdleTime);
}
void ShaderHandler::ActivatePipeline(){
if(ShaderReady){
glUseProgram(0);
PipelineBound=true;
glBindProgramPipeline(ProgramPipeline);
}
}
void ShaderHandler::DesactivatePipeline(){
if(ShaderReady){
glUseProgram(0);
PipelineBound=false;
glBindProgramPipeline(0);
}
}
void ShaderHandler::RestorePipelineState(){
if(ShaderReady){
if(PipelineBound){
glUseProgram(0);
glBindProgramPipeline(ProgramPipeline);
}else{
glUseProgram(0);
glBindProgramPipeline(0);
}
}
}
bool ShaderHandler::ValidatePipeline(){
int Status=GL_TRUE;
ConsoleEcho("Validation Pipeline");
glValidateProgramPipeline(ProgramPipeline);
glGetProgramPipelineiv(ProgramPipeline,GL_VALIDATE_STATUS,&Status);
if(Status==GL_TRUE){
ConsoleEcho("Validation réussi");
return true;
}else{
int ErrorLength=0;
glGetProgramPipelineiv(ProgramPipeline,GL_INFO_LOG_LENGTH,&ErrorLength);
//glGetProgramInfoLog(ProgramList[PrgAdress[i]],0,&ErrorLength,0);
char * Error= new char[ErrorLength+30];
char * FullError=new char[ErrorLength+30+100];
glGetProgramPipelineInfoLog(ProgramPipeline,ErrorLength+30,0,Error);
FullError[0]='\0';
FullError=strcat(FullError,"Error Pipeline: \0");
FullError=strcat(FullError,Error);
ConsoleEcho(FullError);
delete Error;
delete FullError;
return false;
}
}
bool ShaderHandler::ValidateProgram(GLuint programA){
if(programA<GLPrograms.size()){
if(!GLPrograms[programA].ValidationState){
int Status1=GL_TRUE;
int Status2=GL_TRUE;
NoticeGlError(true);
ConsoleEcho("Validation et Linking Program:%i",programA);
glUseProgram(0);
glLinkProgram(GLPrograms[programA].Prg);
NoticeGlError(true);
glGetProgramiv(GLPrograms[programA].Prg,GL_LINK_STATUS,&Status1);
NoticeGlError(true);
if(Status1==GL_TRUE){
//Test du Program
glValidateProgram(GLPrograms[programA].Prg);
glGetProgramiv(GLPrograms[programA].Prg,GL_VALIDATE_STATUS,&Status2);
}
if(Status1==GL_FALSE or Status2==GL_FALSE){
if(Status1==GL_FALSE)ConsoleEcho("Lin Error");
else ConsoleEcho("Validation error");
int ErrorLength=0;
glGetProgramiv(GLPrograms[programA].Prg,GL_INFO_LOG_LENGTH,&ErrorLength);
//glGetProgramInfoLog(ProgramList[PrgAdress[i]],0,&ErrorLength,0);
char * Error= new char[ErrorLength+30];
char * FullError=new char[ErrorLength+30+50*GLPrograms[programA].ShaderAttachedType.size()];
char programdetail[10];
FullError[0]='\0';
FullError=strcat(FullError,"Error Prg: \0");
glGetProgramInfoLog(GLPrograms[programA].Prg,ErrorLength+30,0,Error);
FullError=strcat(FullError,Error);
FullError=strcat(FullError,"\n detail du program:");
FullError=strcat(FullError,"\n numéro:");
sprintf(programdetail,"%i",programA);
FullError=strcat(FullError,programdetail);
FullError=strcat(FullError,"\n Type:");
for(std::vector<int>::iterator A=GLPrograms[programA].ShaderAttachedType.begin();A!=GLPrograms[programA].ShaderAttachedType.end();A++){
sprintf(programdetail,"%x\n",*A);
FullError=strcat(FullError,programdetail);
}
ConsoleEcho(FullError);
NoticeError();
delete Error;
delete FullError;
GLPrograms[programA].ValidationState=false;
return false;
}else{
GLPrograms[programA].ValidationState=true;
return true;
}
}else{
return true;
}
}else{
return false;
}
}
void ShaderHandler::InternBindMonoProgram(GLuint PrgAdress){
ShaderProgramSet=true;
glBindProgramPipeline(0);
glLinkProgram(GLPrograms[PrgAdress].Prg);
if(ValidateProgram(PrgAdress))
glUseProgram(GLPrograms[PrgAdress].Prg);
}
GLuint ShaderHandler::CreateNewProgram(){
ConsoleEcho("Création du Program");
if(ShaderReady){
GLuint NewProgram=glCreateProgram();
glProgramParameteri(NewProgram,GL_PROGRAM_SEPARABLE,true);
ConsoleEcho("Tout nouveau prg");
GLProgram NewPRG=GLProgram(NewProgram);
NewPRG.Allocated=true;
GLuint i=0;
std::vector<GLProgram>::iterator Itt;
for(Itt=GLPrograms.begin();Itt!=GLPrograms.end();Itt++){
if(!Itt->Allocated)break;
i++;
}
if(Itt!=GLPrograms.end()){
*Itt=NewPRG;
return i;
}else{
GLPrograms.push_back(NewPRG);
return GLPrograms.size()-1;
}
}
}
bool ShaderHandler::InternDeleteProgram(GLuint n){
if(ShaderReady){
try{
if(n<GLPrograms.size()){
std::vector<GLProgram>::iterator Itt=GLPrograms.begin();
Itt+=n;
glDeleteProgram(Itt->Prg);
Itt->DeleteAllShader();
Itt->Allocated=false;
if(n==GLPrograms.size()-1){
while(GLPrograms.back().Allocated==false){
GLPrograms.erase(GLPrograms.end()-1);
}
}
//GLPrograms.erase(Itt);
}else{
}
}catch(std::runtime_error Err){
ConsoleEcho((char*)Err.what());
return false;
}
}
}
bool ShaderHandler::DeleteProgram(GLuint n){
DWORD Id=GetCurrentThreadId();
if(Id==ThreadId){
return InternDeleteProgram(n);
}else{
return ExternDeleteProgram(n);
}
}
void ShaderHandler::ExternSetActiveInternProgram(GLuint * PrgAdress,GLuint* PrgType,int n){
if(ShaderReady){
ShaderDemand=5;
IntArrayArgument=(int*)PrgAdress;
GLuintArrayArgument=PrgType;
IntIndex=n;
SetEvent(ShaderDemandSent);
WaitForSingleObject(ShaderDemandAnswered,INFINITE);
}
}
void ShaderHandler::SetActiveInternProgram(GLuint * PrgAdress,GLuint* PrgType,int n){
DWORD Id=GetCurrentThreadId();
if(Id==ThreadId){
InternSetActiveInternProgram(PrgAdress,PrgType,n);
}else{
ExternSetActiveInternProgram(PrgAdress,PrgType,n);
}
}
bool ShaderHandler::ExternDeleteProgram(GLuint n){
GLuintArgument=n;
SetEvent(ShaderDemandSent);
WaitForSingleObject(ShaderDemandAnswered,INFINITE);
}
bool ShaderHandler::ExternSetUniform(GLuint Type,GLuint Count,volatile void* Pointer,GLuint StageAdress,string UniformName){
GLuintArrayArgument=new GLuint[3];
GLuintArrayArgument[0]=Type;
GLuintArrayArgument[1]=Count;
GLuintArrayArgument[2]=StageAdress;
PointerArgument=Pointer;
ShaderDemand=6;
StringArgument=UniformName;
SetEvent(ShaderDemandSent);
memory_fence();
WaitForSingleObject(ShaderDemandAnswered,INFINITE);
delete GLuintArrayArgument;
}
bool ShaderHandler::SetUniform(GLuint Type,GLuint Count,volatile void* Pointer,GLuint StageAdress,string UniformName){
DWORD Id=GetCurrentThreadId();
if(Id==ThreadId){
return InternSetUniform(Type,Count,Pointer,StageAdress,UniformName);
}else{
return ExternSetUniform(Type,Count,Pointer,StageAdress,UniformName);
}
}
bool ShaderHandler::ExternSetUniform(GLuint Type,GLuint Count,volatile void* Pointer,GLuint StageAdress,GLuint Location){
GLuintArrayArgument=new GLuint[3];
GLuintArrayArgument[0]=Type;
GLuintArrayArgument[1]=Count;
GLuintArrayArgument[2]=StageAdress;
PointerArgument=Pointer;
ShaderDemand=7;
GLuintArgument=Location;
SetEvent(ShaderDemandSent);
memory_fence();
WaitForSingleObject(ShaderDemandAnswered,INFINITE);
delete GLuintArrayArgument;
}
//bool ShaderHandler::InternMonoUniformSet(GLuint Type,GLuint Count,)
bool ShaderHandler::SetUniform(GLuint Type,GLuint Count,volatile void* Pointer,GLuint StageAdress,GLuint Location){
DWORD Id=GetCurrentThreadId();
if(Id==ThreadId){
return InternSetUniform(Type,Count,Pointer,StageAdress,Location);
}else{
return ExternSetUniform(Type,Count,Pointer,StageAdress,Location);
}
}
bool ShaderHandler::InternSetUniform(GLuint Type,GLuint Count,volatile void* Pointer,GLuint StageAdress,string UniformName){
glBindProgramPipeline(ProgramPipeline);
memory_fence();
GLuint Location;
//float tes[1]={1.0f};
//std::cout<<Adress<<std::endl;
//std::cout<<Adress<<std::endl;
//glLinkProgram(ProgramList[StageAdress]);
//glUseProgram(ProgramList[StageAdress]);
ConsoleEcho(UniformName.c_str());
ConsoleEcho("Stage Adress %i",StageAdress);
Location=glGetUniformLocation(GLPrograms[StageAdress].Prg,UniformName.data());
ConsoleEcho("uniform cation %i",Location);
switch(Type){
case(GL_FLOAT):
std::cout<<*(float*)Pointer<<std::endl;
//std::cout<<0.1<<std::endl;
//glUniform1f(glGetUniformLocation(ProgramList[0],"ColorTest"),1.0f);
glUniform1fv(Location,Count,(const float*)Pointer);
break;
case(GL_INT):
glUniform1iv(Location,Count,(const int*)Pointer);
break;
case(GL_UNSIGNED_INT):
glUniform1uiv(Location,Count,(GLuint*)Pointer);
break;
case(GL_DOUBLE):
glUniform1dv(Location,Count,(GLdouble*)Pointer);
}
RestorePipelineState();
// glUseProgram(NULL);
}
bool ShaderHandler::InternSetUniform(GLuint Type,GLuint Count,volatile void* Pointer,GLuint StageAdress,GLuint Location){
glBindProgramPipeline(ProgramPipeline);
memory_fence();
switch(Type){
case(GL_FLOAT):
std::cout<<*(float*)Pointer<<std::endl;
//std::cout<<0.1<<std::endl;
//glUniform1f(glGetUniformLocation(ProgramList[0],"ColorTest"),1.0f);
glUniform1fv(Location,Count,(const float*)Pointer);
break;
case(GL_INT):
glUniform1iv(Location,Count,(const int*)Pointer);
break;
case(GL_UNSIGNED_INT):
glUniform1uiv(Location,Count,(GLuint*)Pointer);
break;
case(GL_DOUBLE):
glUniform1dv(Location,Count,(GLdouble*)Pointer);
}
// glUseProgram(NULL);
RestorePipelineState();
}
void ShaderHandler::InternSetActiveInternProgram(GLuint * PrgAdress,GLuint* PrgType,int n){
ConsoleEcho("Mise en place du prg");
ShaderProgramSet=true;
ConsoleEcho("Activation du Pipeline");
ActivatePipeline();
for(int i=0;i<n;i++){
if(ValidateProgram(PrgAdress[i])){
ConsoleEcho("mise en places des Stage de rendu");
glUseProgramStages(ProgramPipeline,PrgType[i],GLPrograms[PrgAdress[i]].Prg);
//NoticeGlError(true);
glActiveShaderProgram(ProgramPipeline,GLPrograms[PrgAdress[i]].Prg);
//NoticeGlError(true);
//glUseProgram(ProgramList[PrgAdress[i]]);
}else{
ShaderProgramSet=false;
}
}
if(!ShaderProgramSet || !ValidatePipeline()){
ConsoleEcho("Erreur d'intialisation du Program");
ShaderProgramSet=false;
for(int i=0;i<n;i++){
ConsoleEcho("Program: %i",i);
ConsoleEcho("AdressSoft:%i",PrgAdress[i]);
ConsoleEcho("AdressHard:%i",GLPrograms[PrgAdress[i]].Prg);
ConsoleEcho("Type:%i",PrgType[i]);
}
}else{
ConsoleEcho("Succes de l'activation du Program Intern");
}
}
GLuint ShaderHandler::GetLocation(string Name,GLuint PrgAdress){
DWORD Id=GetCurrentThreadId();
if(Id==ThreadId){
return InternGetLocation(Name,PrgAdress);
}else{
return ExternGetLocation(Name,PrgAdress);
}
}
GLuint ShaderHandler::ExternGetLocation(string Name,GLuint PrgAdress){
if(ShaderReady && PrgAdress<GLPrograms.size()){
if(GLPrograms[PrgAdress].ValidationState){
//code de demande
ShaderDemand=8;
StringArgument=Name;
GLuintArgument=PrgAdress;
//on envoit la demande
SetEvent(ShaderDemandSent);
WaitForSingleObject(ShaderDemandAnswered,INFINITE);
return GLuintArgument;
}else{
return 0;
}
}else{
return 0;
}
}
GLuint ShaderHandler::InternGetLocation(string Name,GLuint PrgAdress){
if(ShaderReady && PrgAdress<GLPrograms.size()){
return GLPrograms[PrgAdress].ValidationState?glGetUniformLocation(GLPrograms[PrgAdress].Prg,Name.c_str()):0;
}else return 0;
}
AmbivalentUniform ShaderHandler::GetAmbivalentLocation(string Name,GLuint PrgAdress,GLuint Type1,GLuint Type2){
DWORD Id=GetCurrentThreadId();
if(Id==ThreadId){
return InternGetAmbivalentLocation(Name,PrgAdress,Type1,Type2);
}else{
return ExternGetAmbivalentLocation(Name,PrgAdress,Type1,Type2);
}
}
AmbivalentUniform ShaderHandler::ExternGetAmbivalentLocation(string Name,GLuint PrgAdress,GLuint Type1,GLuint Type2){
if(ShaderReady && PrgAdress<GLPrograms.size()){
if(GLPrograms[PrgAdress].ValidationState){
//code de demande
ShaderDemand=9;
StringArgument=Name;
PointerArgument=(void*)(new AmbivalentUniform);
GLuintArgument=PrgAdress;
GLuintArrayArgument=new GLuint[2];
GLuintArrayArgument[0]=Type1;
GLuintArrayArgument[1]=Type2;
//on envoit la demande
SetEvent(ShaderDemandSent);
WaitForSingleObject(ShaderDemandAnswered,INFINITE);
delete GLuintArrayArgument;
return *((AmbivalentUniform*)PointerArgument);
delete PointerArgument;
}else{
return {0,0,0,0};
}
}else{
return {0,0,0,0};
}
}
AmbivalentUniform ShaderHandler::InternGetAmbivalentLocation(string Name,GLuint PrgAdress,GLuint Type1,GLuint Type2){
if(ShaderReady && PrgAdress<GLPrograms.size()){
if(GLPrograms[PrgAdress].ValidationState){
AmbivalentUniform AmbUni;
AmbUni.NormalType=Type1;
AmbUni.MSType=Type2;
AmbUni.Normal=glGetUniformLocation(GLPrograms[PrgAdress].Prg,Name.c_str());
AmbUni.MultiSampled=glGetUniformLocation(GLPrograms[PrgAdress].Prg,(Name+MultiSampTag).c_str());
if(AmbUni.Normal==-1){
ConsoleEcho(("Erreur dans la Recherche d'un AmbUni => Normal Non trouvé :"+Name).c_str());
}
if(AmbUni.MultiSampled==-1){
ConsoleEcho(("Erreur dans la Recherche d'un AmbUni => MultiS Non trouvé :"+Name+MultiSampTag).c_str());
}
return AmbUni;
}else{
return {0,0,0,0};
}
}else return {0,0,0,0};
}
GLuint ShaderHandler::CreateNewPipeline(){
DWORD Id=GetCurrentThreadId();
if(Id==ThreadId){
return InternCreateNewPipeline();
}else{
return ExternCreateNewPipeline();
}
}
GLuint ShaderHandler::InternCreateNewPipeline(){
if(ShaderReady){
GLuint newpipe;
glGenProgramPipelines(1,&newpipe);
std::vector<GLPipeline>::iterator Itt;
GLuint i=0;
for(Itt=GLPipelines.begin();Itt!=GLPipelines.end();Itt++){
if(!Itt->Allocated)break;
i++;
}
if(Itt!=GLPipelines.end()){
*Itt=GLPipeline(newpipe,false);
Itt->Allocated=true;
return i;
}else{
GLPipelines.push_back(GLPipeline(newpipe,false,true));
return GLPipelines.size()-1;
}
}else{
return -1;
}
}
GLuint ShaderHandler::ExternCreateNewPipeline(){
if(ShaderReady){
GLuintArgument=0;
ShaderDemand=10;
SetEvent(ShaderDemandSent);
WaitForSingleObject(ShaderDemandAnswered,INFINITE);
return GLuintArgument;
}else{
return -1;
}
}
GLuint ShaderHandler::SwapPipeline(GLuint n){
DWORD Id=GetCurrentThreadId();
if(Id==ThreadId){
return InternSwapPipeline(n);
}else{
return ExternSwapPipeline(n);
}
}
GLuint ShaderHandler::ExternSwapPipeline(GLuint n){
GLuintArgument=n;
ShaderDemand=11;
SetEvent(ShaderDemandSent);
WaitForSingleObject(ShaderDemandAnswered,INFINITE);
return GLuintArgument;
}
GLuint ShaderHandler::InternSwapPipeline(GLuint n){
if(ShaderReady && 0<=n<GLPipelines.size() &&n!=CurrentPipelineIndex){
DesactivatePipeline();
GLPipelines[CurrentPipelineIndex].ProgramSet=ShaderProgramSet;
ProgramPipeline=GLPipelines[n].Pipeline;
ShaderProgramSet=GLPipelines[n].ProgramSet;
CurrentPipelineIndex=n;
return n;
}else{
return CurrentPipelineIndex;
}
}
void ShaderHandler::DeletePipeline(GLuint n){
DWORD Id=GetCurrentThreadId();
if(Id==ThreadId){
return InternDeletePipeline(n);
}else{
return ExternDeletePipeline(n);
}
}
void ShaderHandler::ExternDeletePipeline(GLuint n){
ShaderDemand=12;
GLuintArgument=n;
SetEvent(ShaderDemandSent);
WaitForSingleObject(ShaderDemandAnswered,INFINITE);
}
void ShaderHandler::InternDeletePipeline(GLuint n){
if(ShaderReady && GLPipelines.size()>1 && GLPipelines.size()>n){
if(CurrentPipelineIndex==n){//si le pipeline est déja l'actuelle on le change
SwapPipeline(0);
}
glDeleteProgramPipelines(1,&(GLPipelines[n].Pipeline));
GLPipelines[n].Allocated=false;
if(n==GLPipelines.size()-1){
while((GLPipelines.end()-1)->Allocated==false){
GLPipelines.erase(GLPipelines.end()-1);
}
}
}
}
int ShaderHandler::ExternAddShader(string FileName,GLuint Type,int ProgramIndex){
ConsoleEcho("un message envoyé");
if(ShaderReady){
//Code pour la Demande
ShaderDemand=3;
StringArgument=FileName;
GLuintArgument=Type;
IntIndex=ProgramIndex;
SetEvent(ShaderDemandSent);
WaitForSingleObject(ShaderDemandAnswered,INFINITE);
//ConsoleEcho("On me répond");
return IntIndex;
}
}
int ShaderHandler::AddShader(string FileName,GLuint Type,int ProgramIndex){
DWORD Id=GetCurrentThreadId();
if(Id==ThreadId){
return InternAddShader(FileName,Type,ProgramIndex);
}else{
return ExternAddShader(FileName,Type,ProgramIndex);
}
}
int ShaderHandler::InternAddShader(string FileName,GLuint Type,int ProgramIndex){
if(ShaderReady){
try{
int Size;
FILE* ShadderFile;
char * SourceCode;
ShadderFile = fopen(FileName.c_str(), "r");
if(ShadderFile == NULL){
char buff[255];
strcpy(buff,"AddShader::error file = ");
strcat(buff,FileName.c_str());
throw std::runtime_error(buff);
}
fseek(ShadderFile, 0, SEEK_END);
Size = ftell(ShadderFile);
rewind(ShadderFile);
SourceCode = new char[Size+1];
memset(SourceCode,0,Size+1);
if(SourceCode == NULL){
throw std::runtime_error("Allocation");
fclose(ShadderFile);
}
fread(SourceCode,Size,1,ShadderFile);
SourceCode[Size]= '\0';
const char ** OpenedSourceCode=(const GLchar**)"";
OpenedSourceCode=(const GLchar**)&SourceCode;
fclose(ShadderFile);
GLuint Shader = glCreateShader(Type);
glShaderSource(Shader,1,OpenedSourceCode,NULL);
glCompileShader(Shader);
GLint Status;
glGetShaderiv(Shader,GL_COMPILE_STATUS,&Status);
if(Status==GL_FALSE){
string FullError;
string NameBuff;
string ErrorBuff;
int ErrorLength;
glGetShaderiv(Shader,GL_INFO_LOG_LENGTH,&ErrorLength);
char * ErrorA= new char[ErrorLength];
glGetShaderInfoLog(Shader,ErrorLength,&ErrorLength,ErrorA);
FullError="error compilation du fichier :";
NameBuff=FileName;
ErrorBuff=ErrorA;
FullError+=NameBuff;
FullError+=ErrorBuff;
delete ErrorA;
std::runtime_error ERR =std::runtime_error(FullError);
throw ERR;
}
string Test="Reussite de la compilation:";
Test+=(string)FileName;
ConsoleEcho(Test.c_str());
ConsoleEcho("Shader de type:%x",Type);
//si il met 0 ???? on fait un nouveau programme
if(ProgramIndex<0){
GLuint Index=CreateNewProgram();
glAttachShader(GLPrograms[Index].Prg,Shader);
GLPrograms[Index].ShaderAttachedList.push_back(Shader);
GLPrograms[Index].ShaderAttachedType.push_back(Type);
ConsoleEcho("Envoyé au num:%i",Index);
return Index;
}else{
ConsoleEcho("Envoyé au num:%i",ProgramIndex);
glAttachShader(GLPrograms[ProgramIndex].Prg,Shader);
GLPrograms[ProgramIndex].ShaderAttachedList.push_back(Shader);
GLPrograms[ProgramIndex].ShaderAttachedType.push_back(Type);
return ProgramIndex;
}
delete SourceCode;
}catch(std::runtime_error A){
ConsoleEcho((char*)A.what());
return -1;
}
}
}
ShaderHandler::~ShaderHandler(){
DWORD Id=GetCurrentThreadId();
if(ThreadId==Id){
InternShaderHandlerDestructor();
}else{
ExternShaderHandlerDestructor();
}
}
void ShaderHandler::ExternShaderHandlerDestructor(){
if(ShaderReady){
ShaderDemand=2;
SetEvent(ShaderDemandSent);
ConsoleEcho("J'essaye de te detruire");
WaitForSingleObject(ShaderDemandAnswered,INFINITE);
ConsoleEcho("J'y suis arrivé");
}
}
void ShaderHandler::InternShaderHandlerDestructor(){
if(ShaderReady){
std::cout<<ProgramPipeline<<std::endl;
glBindProgramPipeline(0);
glDeleteProgramPipelines(1,&ProgramPipeline);
ConsoleEcho("je détuit tout");
for(GLuint i=0;i<GLPrograms.size();i++){
std::cout<<i<<std::endl;
glDeleteProgram(GLPrograms[i].Prg);
GLPrograms[i].DeleteAllShader();
}
for(std::vector<GLPipeline>::iterator Itt=GLPipelines.begin();Itt!=GLPipelines.end();Itt++){
glDeleteProgramPipelines(1,&(Itt->Pipeline));
}
ShaderReady=false;
//RestorePipelineState();
}
//delete ProgramList;
//delete ShaderAttachedList;
//delete ShaderAttachedType;
}
GLuint LoadShader(unsigned int Type,char* FileName, GLuint Program){
try{
int Size;
FILE* ShadderFile;
char * SourceCode;
ShadderFile = fopen(FileName, "r");
if(ShadderFile == NULL) throw "error file";
fseek(ShadderFile, 0, SEEK_END);
Size = ftell(ShadderFile);
rewind(ShadderFile);
SourceCode = new char[Size+1];
memset(SourceCode,0,Size+1);
if(SourceCode == NULL){
throw"Allocation";
fclose(ShadderFile);
}
fread(SourceCode,Size,1,ShadderFile);
SourceCode[Size]= '/0';
const char ** OpenedSourceCode=(const GLchar**)"";
OpenedSourceCode=(const GLchar**)&SourceCode;
fclose(ShadderFile);
GLuint Shader = glCreateShader(Type);
glShaderSource(Shader,1,OpenedSourceCode,NULL);
glCompileShader(Shader);
GLint Status;
glGetShaderiv(Shader,GL_COMPILE_STATUS,&Status);
if(Status==GL_FALSE){
string FullError;
string NameBuff;
string ErrorBuff;
int ErrorLength;
glGetShaderiv(Shader,GL_INFO_LOG_LENGTH,&ErrorLength);
char * ErrorA= new char[ErrorLength];
glGetShaderInfoLog(Shader,ErrorLength,&ErrorLength,ErrorA);
FullError="error compilation du fichier :";
NameBuff=FileName;
ErrorBuff=ErrorA;
FullError+=NameBuff;
FullError+=ErrorBuff;
delete ErrorA;
std::runtime_error ERR =std::runtime_error(FullError);
delete SourceCode;
throw ERR;
}
string Test="Reussite de la compilation:";
Test+=(string)FileName;
ConsoleEcho(Test.c_str());
glAttachShader(Program,Shader);
delete SourceCode;
return Shader;
}catch(std::runtime_error A){
ConsoleEcho((char*)A.what());
return 0;
}
}
| [
"[email protected]"
] | |
ba5ae7396b43057132ca34519ad63a314dcc916e | 099f2524dd5bd1ac4951fdca72045f99183c0b70 | /src/qt/bitcoingui.cpp | 8786724726c490f450252b6fc7bf3197567916d7 | [
"MIT"
] | permissive | zhenzhengy/ETHERCOINPAY | 176de6f16c6129f188a893b8923b3a65210ed4c7 | ef86f943a6898311c945c51bcdc0f250210dfbdb | refs/heads/master | 2021-01-01T10:41:02.253546 | 2017-07-18T08:06:59 | 2017-07-18T08:06:59 | 97,541,382 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,049 | cpp | /*
* Qt4 bitcoin GUI.
*
* W.J. van der Laan 2011-2012
* The Bitcoin Developers 2011-2012
*/
#include "bitcoingui.h"
#include "transactiontablemodel.h"
#include "addressbookpage.h"
#include "sendcoinsdialog.h"
#include "signverifymessagedialog.h"
#include "optionsdialog.h"
#include "aboutdialog.h"
#include "clientmodel.h"
#include "walletmodel.h"
#include "editaddressdialog.h"
#include "optionsmodel.h"
#include "transactiondescdialog.h"
#include "addresstablemodel.h"
#include "transactionview.h"
#include "overviewpage.h"
#include "bitcoinunits.h"
#include "guiconstants.h"
#include "askpassphrasedialog.h"
#include "notificator.h"
#include "guiutil.h"
#include "rpcconsole.h"
#ifdef Q_OS_MAC
#include "macdockiconhandler.h"
#endif
#include <QApplication>
#include <QMainWindow>
#include <QMenuBar>
#include <QMenu>
#include <QIcon>
#include <QTabWidget>
#include <QVBoxLayout>
#include <QToolBar>
#include <QStatusBar>
#include <QLabel>
#include <QLineEdit>
#include <QPushButton>
#include <QLocale>
#include <QMessageBox>
#include <QProgressBar>
#include <QStackedWidget>
#include <QDateTime>
#include <QMovie>
#include <QFileDialog>
#include <QDesktopServices>
#include <QTimer>
#include <QDragEnterEvent>
#include <QUrl>
#include <QStyle>
#include <iostream>
BitcoinGUI::BitcoinGUI(QWidget *parent):
QMainWindow(parent),
clientModel(0),
walletModel(0),
encryptWalletAction(0),
changePassphraseAction(0),
aboutQtAction(0),
trayIcon(0),
notificator(0),
rpcConsole(0)
{
resize(850, 550);
setWindowTitle(tr("ETHERCOINPAY") + " - " + tr("Wallet"));
#ifndef Q_OS_MAC
qApp->setWindowIcon(QIcon(":icons/bitcoin"));
setWindowIcon(QIcon(":icons/bitcoin"));
#else
setUnifiedTitleAndToolBarOnMac(true);
QApplication::setAttribute(Qt::AA_DontShowIconsInMenus);
#endif
// Accept D&D of URIs
setAcceptDrops(true);
// Create actions for the toolbar, menu bar and tray/dock icon
createActions();
// Create application menu bar
createMenuBar();
// Create the toolbars
createToolBars();
// Create the tray icon (or setup the dock icon)
createTrayIcon();
// Create tabs
overviewPage = new OverviewPage();
transactionsPage = new QWidget(this);
QVBoxLayout *vbox = new QVBoxLayout();
transactionView = new TransactionView(this);
vbox->addWidget(transactionView);
transactionsPage->setLayout(vbox);
addressBookPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::SendingTab);
receiveCoinsPage = new AddressBookPage(AddressBookPage::ForEditing, AddressBookPage::ReceivingTab);
sendCoinsPage = new SendCoinsDialog(this);
signVerifyMessageDialog = new SignVerifyMessageDialog(this);
centralWidget = new QStackedWidget(this);
centralWidget->addWidget(overviewPage);
centralWidget->addWidget(transactionsPage);
centralWidget->addWidget(addressBookPage);
centralWidget->addWidget(receiveCoinsPage);
centralWidget->addWidget(sendCoinsPage);
setCentralWidget(centralWidget);
// Create status bar
statusBar();
// Status bar notification icons
QFrame *frameBlocks = new QFrame();
frameBlocks->setContentsMargins(0,0,0,0);
frameBlocks->setMinimumWidth(56);
frameBlocks->setMaximumWidth(56);
QHBoxLayout *frameBlocksLayout = new QHBoxLayout(frameBlocks);
frameBlocksLayout->setContentsMargins(3,0,3,0);
frameBlocksLayout->setSpacing(3);
labelEncryptionIcon = new QLabel();
labelConnectionsIcon = new QLabel();
labelBlocksIcon = new QLabel();
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelEncryptionIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelConnectionsIcon);
frameBlocksLayout->addStretch();
frameBlocksLayout->addWidget(labelBlocksIcon);
frameBlocksLayout->addStretch();
// Progress bar and label for blocks download
progressBarLabel = new QLabel();
progressBarLabel->setVisible(false);
progressBar = new QProgressBar();
progressBar->setAlignment(Qt::AlignCenter);
progressBar->setVisible(false);
// Override style sheet for progress bar for styles that have a segmented progress bar,
// as they make the text unreadable (workaround for issue #1071)
// See https://qt-project.org/doc/qt-4.8/gallery.html
QString curStyle = qApp->style()->metaObject()->className();
if(curStyle == "QWindowsStyle" || curStyle == "QWindowsXPStyle")
{
progressBar->setStyleSheet("QProgressBar { background-color: #e8e8e8; border: 1px solid grey; border-radius: 7px; padding: 1px; text-align: center; } QProgressBar::chunk { background: QLinearGradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #FF8000, stop: 1 orange); border-radius: 7px; margin: 0px; }");
}
statusBar()->addWidget(progressBarLabel);
statusBar()->addWidget(progressBar);
statusBar()->addPermanentWidget(frameBlocks);
syncIconMovie = new QMovie(":/movies/update_spinner", "mng", this);
// this->setStyleSheet("background-color: #ceffee;");
// Clicking on a transaction on the overview page simply sends you to transaction history page
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), this, SLOT(gotoHistoryPage()));
connect(overviewPage, SIGNAL(transactionClicked(QModelIndex)), transactionView, SLOT(focusTransaction(QModelIndex)));
// Double-clicking on a transaction on the transaction history page shows details
connect(transactionView, SIGNAL(doubleClicked(QModelIndex)), transactionView, SLOT(showDetails()));
rpcConsole = new RPCConsole(this);
connect(openRPCConsoleAction, SIGNAL(triggered()), rpcConsole, SLOT(show()));
// Clicking on "Verify Message" in the address book sends you to the verify message tab
connect(addressBookPage, SIGNAL(verifyMessage(QString)), this, SLOT(gotoVerifyMessageTab(QString)));
// Clicking on "Sign Message" in the receive coins page sends you to the sign message tab
connect(receiveCoinsPage, SIGNAL(signMessage(QString)), this, SLOT(gotoSignMessageTab(QString)));
gotoOverviewPage();
}
BitcoinGUI::~BitcoinGUI()
{
if(trayIcon) // Hide tray icon, as deleting will let it linger until quit (on Ubuntu)
trayIcon->hide();
#ifdef Q_OS_MAC
delete appMenuBar;
#endif
}
void BitcoinGUI::createActions()
{
QActionGroup *tabGroup = new QActionGroup(this);
overviewAction = new QAction(QIcon(":/icons/overview"), tr("&Overview"), this);
overviewAction->setToolTip(tr("Show general overview of wallet"));
overviewAction->setCheckable(true);
overviewAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_1));
tabGroup->addAction(overviewAction);
sendCoinsAction = new QAction(QIcon(":/icons/send"), tr("&Send coins"), this);
sendCoinsAction->setToolTip(tr("Send coins to a ETHERCOINPAY address"));
sendCoinsAction->setCheckable(true);
sendCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_2));
tabGroup->addAction(sendCoinsAction);
receiveCoinsAction = new QAction(QIcon(":/icons/receiving_addresses"), tr("&Receive coins"), this);
receiveCoinsAction->setToolTip(tr("Show the list of addresses for receiving payments"));
receiveCoinsAction->setCheckable(true);
receiveCoinsAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_3));
tabGroup->addAction(receiveCoinsAction);
historyAction = new QAction(QIcon(":/icons/history"), tr("&Transactions"), this);
historyAction->setToolTip(tr("Browse transaction history"));
historyAction->setCheckable(true);
historyAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_4));
tabGroup->addAction(historyAction);
addressBookAction = new QAction(QIcon(":/icons/address-book"), tr("&Address Book"), this);
addressBookAction->setToolTip(tr("Edit the list of stored addresses and labels"));
addressBookAction->setCheckable(true);
addressBookAction->setShortcut(QKeySequence(Qt::ALT + Qt::Key_5));
tabGroup->addAction(addressBookAction);
connect(overviewAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(overviewAction, SIGNAL(triggered()), this, SLOT(gotoOverviewPage()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(sendCoinsAction, SIGNAL(triggered()), this, SLOT(gotoSendCoinsPage()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(receiveCoinsAction, SIGNAL(triggered()), this, SLOT(gotoReceiveCoinsPage()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(historyAction, SIGNAL(triggered()), this, SLOT(gotoHistoryPage()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(showNormalIfMinimized()));
connect(addressBookAction, SIGNAL(triggered()), this, SLOT(gotoAddressBookPage()));
quitAction = new QAction(QIcon(":/icons/quit"), tr("E&xit"), this);
quitAction->setToolTip(tr("Quit application"));
quitAction->setShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q));
quitAction->setMenuRole(QAction::QuitRole);
aboutAction = new QAction(QIcon(":/icons/bitcoin"), tr("&About ETHERCOINPAY"), this);
aboutAction->setToolTip(tr("Show information about ETHERCOINPAY"));
aboutAction->setMenuRole(QAction::AboutRole);
aboutQtAction = new QAction(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"), tr("About &Qt"), this);
aboutQtAction->setToolTip(tr("Show information about Qt"));
aboutQtAction->setMenuRole(QAction::AboutQtRole);
optionsAction = new QAction(QIcon(":/icons/options"), tr("&Options..."), this);
optionsAction->setToolTip(tr("Modify configuration options for ETHERCOINPAY"));
optionsAction->setMenuRole(QAction::PreferencesRole);
toggleHideAction = new QAction(QIcon(":/icons/bitcoin"), tr("&Show / Hide"), this);
encryptWalletAction = new QAction(QIcon(":/icons/lock_closed"), tr("&Encrypt Wallet..."), this);
encryptWalletAction->setToolTip(tr("Encrypt or decrypt wallet"));
encryptWalletAction->setCheckable(true);
backupWalletAction = new QAction(QIcon(":/icons/filesave"), tr("&Backup Wallet..."), this);
backupWalletAction->setToolTip(tr("Backup wallet to another location"));
changePassphraseAction = new QAction(QIcon(":/icons/key"), tr("&Change Passphrase..."), this);
changePassphraseAction->setToolTip(tr("Change the passphrase used for wallet encryption"));
signMessageAction = new QAction(QIcon(":/icons/edit"), tr("Sign &message..."), this);
verifyMessageAction = new QAction(QIcon(":/icons/transaction_0"), tr("&Verify message..."), this);
exportAction = new QAction(QIcon(":/icons/export"), tr("&Export..."), this);
exportAction->setToolTip(tr("Export the data in the current tab to a file"));
openRPCConsoleAction = new QAction(QIcon(":/icons/debugwindow"), tr("&Debug window"), this);
openRPCConsoleAction->setToolTip(tr("Open debugging and diagnostic console"));
connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));
connect(aboutAction, SIGNAL(triggered()), this, SLOT(aboutClicked()));
connect(aboutQtAction, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(optionsAction, SIGNAL(triggered()), this, SLOT(optionsClicked()));
connect(toggleHideAction, SIGNAL(triggered()), this, SLOT(toggleHidden()));
connect(encryptWalletAction, SIGNAL(triggered(bool)), this, SLOT(encryptWallet(bool)));
connect(backupWalletAction, SIGNAL(triggered()), this, SLOT(backupWallet()));
connect(changePassphraseAction, SIGNAL(triggered()), this, SLOT(changePassphrase()));
connect(signMessageAction, SIGNAL(triggered()), this, SLOT(gotoSignMessageTab()));
connect(verifyMessageAction, SIGNAL(triggered()), this, SLOT(gotoVerifyMessageTab()));
}
void BitcoinGUI::createMenuBar()
{
#ifdef Q_OS_MAC
// Create a decoupled menu bar on Mac which stays even if the window is closed
appMenuBar = new QMenuBar();
#else
// Get the main window's menu bar on other platforms
appMenuBar = menuBar();
#endif
// Configure the menus
QMenu *file = appMenuBar->addMenu(tr("&File"));
file->addAction(backupWalletAction);
file->addAction(exportAction);
file->addAction(signMessageAction);
file->addAction(verifyMessageAction);
file->addSeparator();
file->addAction(quitAction);
QMenu *settings = appMenuBar->addMenu(tr("&Settings"));
settings->addAction(encryptWalletAction);
settings->addAction(changePassphraseAction);
settings->addSeparator();
settings->addAction(optionsAction);
QMenu *help = appMenuBar->addMenu(tr("&Help"));
help->addAction(openRPCConsoleAction);
help->addSeparator();
help->addAction(aboutAction);
help->addAction(aboutQtAction);
// QString ss("QMenuBar::item { background-color: #ceffee; color: black }");
// appMenuBar->setStyleSheet(ss);
}
void BitcoinGUI::createToolBars()
{
QToolBar *toolbar = addToolBar(tr("Tabs toolbar"));
toolbar->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar->addAction(overviewAction);
toolbar->addAction(sendCoinsAction);
toolbar->addAction(receiveCoinsAction);
toolbar->addAction(historyAction);
toolbar->addAction(addressBookAction);
QToolBar *toolbar2 = addToolBar(tr("Actions toolbar"));
toolbar2->setToolButtonStyle(Qt::ToolButtonTextBesideIcon);
toolbar2->addAction(exportAction);
}
void BitcoinGUI::setClientModel(ClientModel *clientModel)
{
this->clientModel = clientModel;
if(clientModel)
{
// Replace some strings and icons, when using the testnet
if(clientModel->isTestNet())
{
setWindowTitle(windowTitle() + QString(" ") + tr("[testnet]"));
#ifndef Q_OS_MAC
qApp->setWindowIcon(QIcon(":icons/bitcoin_testnet"));
setWindowIcon(QIcon(":icons/bitcoin_testnet"));
#else
MacDockIconHandler::instance()->setIcon(QIcon(":icons/bitcoin_testnet"));
#endif
if(trayIcon)
{
trayIcon->setToolTip(tr("ETHERCOINPAY client") + QString(" ") + tr("[testnet]"));
trayIcon->setIcon(QIcon(":/icons/toolbar_testnet"));
toggleHideAction->setIcon(QIcon(":/icons/toolbar_testnet"));
}
aboutAction->setIcon(QIcon(":/icons/toolbar_testnet"));
}
// Keep up to date with client
setNumConnections(clientModel->getNumConnections());
connect(clientModel, SIGNAL(numConnectionsChanged(int)), this, SLOT(setNumConnections(int)));
setNumBlocks(clientModel->getNumBlocks(), clientModel->getNumBlocksOfPeers());
connect(clientModel, SIGNAL(numBlocksChanged(int,int)), this, SLOT(setNumBlocks(int,int)));
// Report errors from network/worker thread
connect(clientModel, SIGNAL(error(QString,QString,bool)), this, SLOT(error(QString,QString,bool)));
rpcConsole->setClientModel(clientModel);
addressBookPage->setOptionsModel(clientModel->getOptionsModel());
receiveCoinsPage->setOptionsModel(clientModel->getOptionsModel());
}
}
void BitcoinGUI::setWalletModel(WalletModel *walletModel)
{
this->walletModel = walletModel;
if(walletModel)
{
// Report errors from wallet thread
connect(walletModel, SIGNAL(error(QString,QString,bool)), this, SLOT(error(QString,QString,bool)));
// Put transaction list in tabs
transactionView->setModel(walletModel);
overviewPage->setModel(walletModel);
addressBookPage->setModel(walletModel->getAddressTableModel());
receiveCoinsPage->setModel(walletModel->getAddressTableModel());
sendCoinsPage->setModel(walletModel);
signVerifyMessageDialog->setModel(walletModel);
setEncryptionStatus(walletModel->getEncryptionStatus());
connect(walletModel, SIGNAL(encryptionStatusChanged(int)), this, SLOT(setEncryptionStatus(int)));
// Balloon pop-up for new transaction
connect(walletModel->getTransactionTableModel(), SIGNAL(rowsInserted(QModelIndex,int,int)),
this, SLOT(incomingTransaction(QModelIndex,int,int)));
// Ask for passphrase if needed
connect(walletModel, SIGNAL(requireUnlock()), this, SLOT(unlockWallet()));
}
}
void BitcoinGUI::createTrayIcon()
{
QMenu *trayIconMenu;
#ifndef Q_OS_MAC
trayIcon = new QSystemTrayIcon(this);
trayIconMenu = new QMenu(this);
trayIcon->setContextMenu(trayIconMenu);
trayIcon->setToolTip(tr("ETHERCOINPAY client"));
trayIcon->setIcon(QIcon(":/icons/toolbar"));
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)),
this, SLOT(trayIconActivated(QSystemTrayIcon::ActivationReason)));
trayIcon->show();
#else
// Note: On Mac, the dock icon is used to provide the tray's functionality.
MacDockIconHandler *dockIconHandler = MacDockIconHandler::instance();
trayIconMenu = dockIconHandler->dockMenu();
#endif
// Configuration of the tray icon (or dock icon) icon menu
trayIconMenu->addAction(toggleHideAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(sendCoinsAction);
trayIconMenu->addAction(receiveCoinsAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(signMessageAction);
trayIconMenu->addAction(verifyMessageAction);
trayIconMenu->addSeparator();
trayIconMenu->addAction(optionsAction);
trayIconMenu->addAction(openRPCConsoleAction);
#ifndef Q_OS_MAC // This is built-in on Mac
trayIconMenu->addSeparator();
trayIconMenu->addAction(quitAction);
#endif
notificator = new Notificator(qApp->applicationName(), trayIcon);
}
#ifndef Q_OS_MAC
void BitcoinGUI::trayIconActivated(QSystemTrayIcon::ActivationReason reason)
{
if(reason == QSystemTrayIcon::Trigger)
{
// Click on system tray icon triggers show/hide of the main window
toggleHideAction->trigger();
}
}
#endif
void BitcoinGUI::optionsClicked()
{
if(!clientModel || !clientModel->getOptionsModel())
return;
OptionsDialog dlg;
dlg.setModel(clientModel->getOptionsModel());
dlg.exec();
}
void BitcoinGUI::aboutClicked()
{
AboutDialog dlg;
dlg.setModel(clientModel);
dlg.exec();
}
void BitcoinGUI::setNumConnections(int count)
{
QString icon;
switch(count)
{
case 0: icon = ":/icons/connect_0"; break;
case 1: case 2: case 3: icon = ":/icons/connect_1"; break;
case 4: case 5: case 6: icon = ":/icons/connect_2"; break;
case 7: case 8: case 9: icon = ":/icons/connect_3"; break;
default: icon = ":/icons/connect_4"; break;
}
labelConnectionsIcon->setPixmap(QIcon(icon).pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelConnectionsIcon->setToolTip(tr("%n active connection(s) to ETHERCOINPAY network", "", count));
}
void BitcoinGUI::setNumBlocks(int count, int nTotalBlocks)
{
// don't show / hide progress bar and its label if we have no connection to the network
if (!clientModel || clientModel->getNumConnections() == 0)
{
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
return;
}
QString strStatusBarWarnings = clientModel->getStatusBarWarnings();
QString tooltip;
if(count < nTotalBlocks)
{
int nRemainingBlocks = nTotalBlocks - count;
float nPercentageDone = count / (nTotalBlocks * 0.01f);
if (strStatusBarWarnings.isEmpty())
{
progressBarLabel->setText(tr("Synchronizing with network..."));
progressBarLabel->setVisible(true);
progressBar->setFormat(tr("~%n block(s) remaining", "", nRemainingBlocks));
progressBar->setMaximum(nTotalBlocks);
progressBar->setValue(count);
progressBar->setVisible(true);
}
tooltip = tr("Downloaded %1 of %2 blocks of transaction history (%3% done).").arg(count).arg(nTotalBlocks).arg(nPercentageDone, 0, 'f', 2);
}
else
{
if (strStatusBarWarnings.isEmpty())
progressBarLabel->setVisible(false);
progressBar->setVisible(false);
tooltip = tr("Downloaded %1 blocks of transaction history.").arg(count);
}
// Override progressBarLabel text and hide progress bar, when we have warnings to display
if (!strStatusBarWarnings.isEmpty())
{
progressBarLabel->setText(strStatusBarWarnings);
progressBarLabel->setVisible(true);
progressBar->setVisible(false);
}
tooltip = tr("Current difficulty is %1.").arg(clientModel->GetDifficulty()) + QString("<br>") + tooltip;
QDateTime lastBlockDate = clientModel->getLastBlockDate();
int secs = lastBlockDate.secsTo(QDateTime::currentDateTime());
QString text;
// Represent time from last generated block in human readable text
if(secs <= 0)
{
// Fully up to date. Leave text empty.
}
else if(secs < 60)
{
text = tr("%n second(s) ago","",secs);
}
else if(secs < 60*60)
{
text = tr("%n minute(s) ago","",secs/60);
}
else if(secs < 24*60*60)
{
text = tr("%n hour(s) ago","",secs/(60*60));
}
else
{
text = tr("%n day(s) ago","",secs/(60*60*24));
}
// Set icon state: spinning if catching up, tick otherwise
if(secs < 90*60 && count >= nTotalBlocks)
{
tooltip = tr("Up to date") + QString(".<br>") + tooltip;
labelBlocksIcon->setPixmap(QIcon(":/icons/synced").pixmap(STATUSBAR_ICONSIZE, STATUSBAR_ICONSIZE));
overviewPage->showOutOfSyncWarning(false);
}
else
{
tooltip = tr("Catching up...") + QString("<br>") + tooltip;
labelBlocksIcon->setMovie(syncIconMovie);
syncIconMovie->start();
overviewPage->showOutOfSyncWarning(true);
}
if(!text.isEmpty())
{
tooltip += QString("<br>");
tooltip += tr("Last received block was generated %1.").arg(text);
}
// Don't word-wrap this (fixed-width) tooltip
tooltip = QString("<nobr>") + tooltip + QString("</nobr>");
labelBlocksIcon->setToolTip(tooltip);
progressBarLabel->setToolTip(tooltip);
progressBar->setToolTip(tooltip);
}
void BitcoinGUI::error(const QString &title, const QString &message, bool modal)
{
// Report errors from network/worker thread
if(modal)
{
QMessageBox::critical(this, title, message, QMessageBox::Ok, QMessageBox::Ok);
} else {
notificator->notify(Notificator::Critical, title, message);
}
}
void BitcoinGUI::changeEvent(QEvent *e)
{
QMainWindow::changeEvent(e);
#ifndef Q_OS_MAC // Ignored on Mac
if(e->type() == QEvent::WindowStateChange)
{
if(clientModel && clientModel->getOptionsModel()->getMinimizeToTray())
{
QWindowStateChangeEvent *wsevt = static_cast<QWindowStateChangeEvent*>(e);
if(!(wsevt->oldState() & Qt::WindowMinimized) && isMinimized())
{
QTimer::singleShot(0, this, SLOT(hide()));
e->ignore();
}
}
}
#endif
}
void BitcoinGUI::closeEvent(QCloseEvent *event)
{
if(clientModel)
{
#ifndef Q_OS_MAC // Ignored on Mac
if(!clientModel->getOptionsModel()->getMinimizeToTray() &&
!clientModel->getOptionsModel()->getMinimizeOnClose())
{
qApp->quit();
}
#endif
}
QMainWindow::closeEvent(event);
}
void BitcoinGUI::askFee(qint64 nFeeRequired, bool *payFee)
{
QString strMessage =
tr("This transaction is over the size limit. You can still send it for a fee of %1, "
"which goes to the nodes that process your transaction and helps to support the network. "
"Do you want to pay the fee?").arg(
BitcoinUnits::formatWithUnit(BitcoinUnits::BTC, nFeeRequired));
QMessageBox::StandardButton retval = QMessageBox::question(
this, tr("Confirm transaction fee"), strMessage,
QMessageBox::Yes|QMessageBox::Cancel, QMessageBox::Yes);
*payFee = (retval == QMessageBox::Yes);
}
void BitcoinGUI::incomingTransaction(const QModelIndex & parent, int start, int end)
{
if(!walletModel || !clientModel)
return;
TransactionTableModel *ttm = walletModel->getTransactionTableModel();
qint64 amount = ttm->index(start, TransactionTableModel::Amount, parent)
.data(Qt::EditRole).toULongLong();
if(!clientModel->inInitialBlockDownload())
{
// On new transaction, make an info balloon
// Unless the initial block download is in progress, to prevent balloon-spam
QString date = ttm->index(start, TransactionTableModel::Date, parent)
.data().toString();
QString type = ttm->index(start, TransactionTableModel::Type, parent)
.data().toString();
QString address = ttm->index(start, TransactionTableModel::ToAddress, parent)
.data().toString();
QIcon icon = qvariant_cast<QIcon>(ttm->index(start,
TransactionTableModel::ToAddress, parent)
.data(Qt::DecorationRole));
notificator->notify(Notificator::Information,
(amount)<0 ? tr("Sent transaction") :
tr("Incoming transaction"),
tr("Date: %1\n"
"Amount: %2\n"
"Type: %3\n"
"Address: %4\n")
.arg(date)
.arg(BitcoinUnits::formatWithUnit(walletModel->getOptionsModel()->getDisplayUnit(), amount, true))
.arg(type)
.arg(address), icon);
}
}
void BitcoinGUI::gotoOverviewPage()
{
overviewAction->setChecked(true);
centralWidget->setCurrentWidget(overviewPage);
exportAction->setEnabled(false);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
}
void BitcoinGUI::gotoHistoryPage()
{
historyAction->setChecked(true);
centralWidget->setCurrentWidget(transactionsPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), transactionView, SLOT(exportClicked()));
}
void BitcoinGUI::gotoAddressBookPage()
{
addressBookAction->setChecked(true);
centralWidget->setCurrentWidget(addressBookPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), addressBookPage, SLOT(exportClicked()));
}
void BitcoinGUI::gotoReceiveCoinsPage()
{
receiveCoinsAction->setChecked(true);
centralWidget->setCurrentWidget(receiveCoinsPage);
exportAction->setEnabled(true);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
connect(exportAction, SIGNAL(triggered()), receiveCoinsPage, SLOT(exportClicked()));
}
void BitcoinGUI::gotoSendCoinsPage()
{
sendCoinsAction->setChecked(true);
centralWidget->setCurrentWidget(sendCoinsPage);
exportAction->setEnabled(false);
disconnect(exportAction, SIGNAL(triggered()), 0, 0);
}
void BitcoinGUI::gotoSignMessageTab(QString addr)
{
// call show() in showTab_SM()
signVerifyMessageDialog->showTab_SM(true);
if(!addr.isEmpty())
signVerifyMessageDialog->setAddress_SM(addr);
}
void BitcoinGUI::gotoVerifyMessageTab(QString addr)
{
// call show() in showTab_VM()
signVerifyMessageDialog->showTab_VM(true);
if(!addr.isEmpty())
signVerifyMessageDialog->setAddress_VM(addr);
}
void BitcoinGUI::dragEnterEvent(QDragEnterEvent *event)
{
// Accept only URIs
if(event->mimeData()->hasUrls())
event->acceptProposedAction();
}
void BitcoinGUI::dropEvent(QDropEvent *event)
{
if(event->mimeData()->hasUrls())
{
int nValidUrisFound = 0;
QList<QUrl> uris = event->mimeData()->urls();
foreach(const QUrl &uri, uris)
{
if (sendCoinsPage->handleURI(uri.toString()))
nValidUrisFound++;
}
// if valid URIs were found
if (nValidUrisFound)
gotoSendCoinsPage();
else
notificator->notify(Notificator::Warning, tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid ETHERCOINPAY address or malformed URI parameters."));
}
event->acceptProposedAction();
}
void BitcoinGUI::handleURI(QString strURI)
{
// URI has to be valid
if (sendCoinsPage->handleURI(strURI))
{
showNormalIfMinimized();
gotoSendCoinsPage();
}
else
notificator->notify(Notificator::Warning, tr("URI handling"), tr("URI can not be parsed! This can be caused by an invalid ETHERCOINPAY address or malformed URI parameters."));
}
void BitcoinGUI::setEncryptionStatus(int status)
{
switch(status)
{
case WalletModel::Unencrypted:
labelEncryptionIcon->hide();
encryptWalletAction->setChecked(false);
changePassphraseAction->setEnabled(false);
encryptWalletAction->setEnabled(true);
break;
case WalletModel::Unlocked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_open").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>unlocked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
case WalletModel::Locked:
labelEncryptionIcon->show();
labelEncryptionIcon->setPixmap(QIcon(":/icons/lock_closed").pixmap(STATUSBAR_ICONSIZE,STATUSBAR_ICONSIZE));
labelEncryptionIcon->setToolTip(tr("Wallet is <b>encrypted</b> and currently <b>locked</b>"));
encryptWalletAction->setChecked(true);
changePassphraseAction->setEnabled(true);
encryptWalletAction->setEnabled(false); // TODO: decrypt currently not supported
break;
}
}
void BitcoinGUI::encryptWallet(bool status)
{
if(!walletModel)
return;
AskPassphraseDialog dlg(status ? AskPassphraseDialog::Encrypt:
AskPassphraseDialog::Decrypt, this);
dlg.setModel(walletModel);
dlg.exec();
setEncryptionStatus(walletModel->getEncryptionStatus());
}
void BitcoinGUI::backupWallet()
{
QString saveDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation);
QString filename = QFileDialog::getSaveFileName(this, tr("Backup Wallet"), saveDir, tr("Wallet Data (*.dat)"));
if(!filename.isEmpty()) {
if(!walletModel->backupWallet(filename)) {
QMessageBox::warning(this, tr("Backup Failed"), tr("There was an error trying to save the wallet data to the new location."));
}
}
}
void BitcoinGUI::changePassphrase()
{
AskPassphraseDialog dlg(AskPassphraseDialog::ChangePass, this);
dlg.setModel(walletModel);
dlg.exec();
}
void BitcoinGUI::unlockWallet()
{
if(!walletModel)
return;
// Unlock wallet when requested by wallet model
if(walletModel->getEncryptionStatus() == WalletModel::Locked)
{
AskPassphraseDialog dlg(AskPassphraseDialog::Unlock, this);
dlg.setModel(walletModel);
dlg.exec();
}
}
void BitcoinGUI::showNormalIfMinimized(bool fToggleHidden)
{
// activateWindow() (sometimes) helps with keyboard focus on Windows
if (isHidden())
{
show();
activateWindow();
}
else if (isMinimized())
{
showNormal();
activateWindow();
}
else if (GUIUtil::isObscured(this))
{
raise();
activateWindow();
}
else if(fToggleHidden)
hide();
}
void BitcoinGUI::toggleHidden()
{
showNormalIfMinimized(true);
}
| [
"[email protected]"
] | |
764b7dc4956b6c22151334c5adf983b21d668af3 | 47ebc7c4de25bb798f328b2be2fd02382ab0daaf | /OpenCLSpy/OpenCLSpy.cpp | abeddbb6495d7b83f36b6333057d8f427857313b | [] | no_license | GabrieleCocco/OpenCLMonitor | c7412803d61a0efa7afc988ba9498c939e143bb6 | af26dc28192c2036313130d31caa2310a960e8cd | refs/heads/master | 2021-01-10T00:53:28.177545 | 2012-06-05T17:44:48 | 2012-06-05T17:44:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,413 | cpp | // OpenCLSpy.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include "OpenCLSpy.h"
#ifdef NO_PRINT
#define printf(A) printf("")
#endif
NTSTATUS (NTAPI *pNtQueryInformationProcess)(HANDLE, DWORD, PVOID, ULONG, PULONG) = NULL;
int enable_debug_privilege() {
LPCTSTR psz_privilege = SE_DEBUG_NAME;
HANDLE hToken = 0;
TOKEN_PRIVILEGES tkp = {0};
// Get a token for this process.
if (!OpenProcessToken(GetCurrentProcess(),
TOKEN_ADJUST_PRIVILEGES |
TOKEN_QUERY, &hToken))
return -1;
// Get the LUID for the privilege.
if(LookupPrivilegeValue(NULL, psz_privilege,
&tkp.Privileges[0].Luid))
{
tkp.PrivilegeCount = 1; // one privilege to set
tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
// Set the privilege for this process.
AdjustTokenPrivileges(hToken, FALSE, &tkp, 0,
(PTOKEN_PRIVILEGES)NULL, 0);
if (GetLastError() != ERROR_SUCCESS)
return -1;
return 0;
}
return -1;
}
int inject_dll(char *dllname, DWORD procID)
{
char buf[MAX_PATH];
LPVOID dllNameMem;
HANDLE hProcess, hThread[2];
LPVOID loadlibaddr, stringaddr;
HMODULE findoff;
DWORD exitcode, modfunc;
int nStatus = 0;
wchar_t w_dllname[MAX_PATH];
mbstowcs(w_dllname, dllname, MAX_PATH);
if((hProcess = OpenProcess(PROCESS_VM_WRITE | PROCESS_VM_READ | PROCESS_CREATE_THREAD, FALSE, procID))){
loadlibaddr = (LPVOID)GetProcAddress(GetModuleHandle(L"kernel32.dll"), "LoadLibraryA");
if(loadlibaddr){
dllNameMem = (LPVOID)VirtualAllocEx(hProcess, NULL, strlen(dllname), MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
WriteProcessMemory(hProcess, (LPVOID)dllNameMem, dllname, strlen(dllname), NULL);
hThread[0] = CreateRemoteThread(hProcess, NULL, 0, (LPTHREAD_START_ROUTINE)loadlibaddr, (LPVOID)dllNameMem, NULL, NULL);
if(hThread[0]){
WaitForSingleObject(hThread[0], INFINITE);
GetExitCodeThread(hThread[0], &exitcode);
findoff = LoadLibrary(w_dllname);
if(findoff){
modfunc = (DWORD)GetProcAddress(findoff, (LPSTR)1);
exitcode += modfunc - (DWORD)findoff;
hThread[1] = CreateRemoteThread(hProcess, NULL, NULL, (LPTHREAD_START_ROUTINE)exitcode, NULL, NULL, NULL);
if(hThread[1]) nStatus = 1;
}
}
}
CloseHandle(hProcess);
}
return nStatus;
}
PPEB get_peb(HANDLE process) {
NTSTATUS status;
PROCESS_BASIC_INFORMATION pbi;
PPEB pPeb;
memset(&pbi, 0, sizeof(pbi));
status = pNtQueryInformationProcess(
process,
ProcessBasicInformation,
&pbi,
sizeof(pbi),
NULL);
pPeb = NULL;
if (NT_SUCCESS(status))
pPeb = pbi.PebBaseAddress;
return pPeb;
}
int main(int argc, char* argv[])
{
if(argc < 2) {
printf("Usage:\nOpenCLSpy <exepath> [args]\n");
return 0;
}
char* exe_path = argv[1];
wchar_t w_exe_path[MAX_PATH];
mbstowcs(w_exe_path, exe_path, MAX_PATH);
STARTUPINFO process_startup_info;
PROCESS_INFORMATION process_information;
PROCESS_BASIC_INFORMATION process_basic_information;
HANDLE process = INVALID_HANDLE_VALUE;
process_startup_info.cb = sizeof(STARTUPINFO);
ZeroMemory(&process_startup_info, sizeof(STARTUPINFO));
ZeroMemory(&process_information, sizeof(PROCESS_INFORMATION));
ZeroMemory(&process_basic_information, sizeof(PROCESS_BASIC_INFORMATION));
//Enabling debug privilege
printf("%-40s", "Enabling debug privilege...");
if(enable_debug_privilege() != 0) {
printf("FAIL!");
return -1;
}
printf("DONE\n");
//Loading ntdll
printf("%-40s", "Dynamically loading ntdll.dll...");
pNtQueryInformationProcess = (NTSTATUS(NTAPI*)(HANDLE, DWORD, PVOID, ULONG, PULONG))
GetProcAddress(
GetModuleHandle(TEXT("ntdll.dll")),
"NtQueryInformationProcess");
if (pNtQueryInformationProcess == NULL)
{
printf("FAIL! (error 0x%08X)", GetLastError());
return -1;
}
printf("DONE\n");
//Create process in suspended state
printf("%-40s", "Creating process in suspended state...", exe_path);
bool status = CreateProcess(
w_exe_path,
NULL,
NULL,
NULL,
false,
CREATE_SUSPENDED,
NULL,
NULL,
&process_startup_info,
&process_information);
if(!status) {
printf("FAIL!");
return -1;
}
printf("DONE\n");
//Query process information
printf("%-40s", "Retrieving process basic info...");
PPEB peb = get_peb(process);
if(peb == NULL) {
printf("FAIL!");
return -1;
}
printf("DONE\n");
printf("- PEB base address = 0x%08X\n", peb);
//Get DOS header
printf("Retrieving process DOS header...");
SIZE_T bytes_read = 0;
IMAGE_DOS_HEADER dos_header;
IMAGE_NT_HEADERS nt_headers;
status = ReadProcessMemory(process,
(LPCVOID)peb->Reserved3[1],
&dos_header,
sizeof(IMAGE_DOS_HEADER),
&bytes_read);
if(!status) {
printf("FAIL!");
return -1;
}
printf("DONE\n");
//Get NT headers
printf("Retrieving process NT headers..");
status = ReadProcessMemory(
process,
(LPCVOID)(((DWORD)peb->Reserved3[1]) + dos_header.e_lfanew),
&nt_headers,
sizeof(IMAGE_NT_HEADERS),
&bytes_read);
if(!status) {
printf("FAIL!");
return -1;
}
printf("DONE\n");
printf("Allocating and reading process image...");
PCHAR image_memory = (PCHAR)GlobalAlloc(GMEM_FIXED | GMEM_ZEROINIT, nt_headers.OptionalHeader.SizeOfImage);
status = ReadProcessMemory(
process,
(LPCVOID)(peb->Reserved3[1]),
image_memory,
nt_headers.OptionalHeader.SizeOfImage,
&bytes_read);
if(!status) {
printf("FAIL!");
return -1;
}
printf("DONE\n");
printf("- Image size = %lu bytes\n", nt_headers.OptionalHeader.SizeOfImage);
printf("- Image base address = 0x%08X\n", nt_headers.OptionalHeader.ImageBase);
printf("- Addess of entry point = 0x%08X (absolute 0x%08X)\n", nt_headers.OptionalHeader.AddressOfEntryPoint, nt_headers.OptionalHeader.ImageBase + nt_headers.OptionalHeader.AddressOfEntryPoint);
printf("Reading first two bytes of instructions...");
char buffer[2];
status = ReadProcessMemory(
process,
(LPCVOID)(nt_headers.OptionalHeader.ImageBase + nt_headers.OptionalHeader.AddressOfEntryPoint),
(LPVOID)buffer,
2,
&bytes_read);
if(!status) {
printf("FAIL!");
return -1;
}
printf("DONE\n");
printf("Patching first two bytes of instructions...");
status = WriteProcessMemory(
process,
(LPVOID)(nt_headers.OptionalHeader.ImageBase + nt_headers.OptionalHeader.AddressOfEntryPoint),
(LPVOID)"\xEB\xFE",
2,
&bytes_read);
if(!status) {
printf("FAIL!");
return -1;
}
printf("DONE\n");
//Get thread context
printf("Retrieving thread context...");
CONTEXT thread_context;
status = GetThreadContext(process_information.hThread, &thread_context);
if(!status) {
printf("FAIL!");
return -1;
}
printf("DONE\n");
//Redirecting thread to the entrypoint
printf("Redirecting thread to the entrypoint...");
thread_context.Eip = nt_headers.OptionalHeader.AddressOfEntryPoint;
status = SetThreadContext(process_information.hThread, &thread_context);
if(!status) {
printf("FAIL!");
return -1;
}
printf("DONE\n");
printf("Resuming thread...");
ResumeThread(process_information.hThread);
GlobalFree(image_memory);
//TerminateThread(process_information.hThread, 0);
//TerminateProcess(process, 0);
CloseHandle(process);
return 0;
}
| [
"[email protected]"
] | |
7f1a3cfde07a2e730d6e2587c6985cc4260d8dac | cfc4e219d7c0c3fceb3bc032b79b2d45f90e7efd | /abc041/a/a.cpp | 2d3eb7c8a67f8d4424046a620d0152c71d4d0346 | [] | no_license | nuts3745/atcoder | 4f756ff7a1ee9747e086bf67aa8e9c75daabb4e1 | 854f26fa73524b0bf30d3ebe73cc3e8e9c8e6fa5 | refs/heads/master | 2023-04-02T04:00:30.441384 | 2021-04-11T14:00:57 | 2021-04-11T14:00:57 | 298,011,025 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 244 | cpp | #include <bits/stdc++.h>
#define rep(i,n) for (int i = 0; i < (n); ++i)
using namespace std;
using ll = long long;
using P = pair<int,int>;
int main() {
string s;
int i;
cin >> s >> i;
cout << s.at(i-1) << endl;
return 0;
} | [
"[email protected]"
] | |
068bff418270d7c5b31d4597a221b37816635def | f67629586414cfe28929c10f30e09ce82ea342bc | /Benchmark Engineering Tool/example/BenchmarkLib/src-gen/benchmark_experiment.cpp | 5f3c24b2be96a7ece846c820049c4ddbd78fdf52 | [] | no_license | Mohamedgalil/plug-and-bench | cb259258fbb9a09a7ed084d395ca5a49d17c8a6b | 44d02a6eb0eb7de289364e2dffe5dc0d63cc9516 | refs/heads/master | 2020-04-25T15:31:23.868541 | 2019-04-16T07:20:24 | 2019-04-16T07:20:24 | 172,881,559 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 370 | cpp | // -*- mode: c++; c-basic-style: "bsd"; c-basic-offset: 4; -*-
/*
* benchmark_experiment.cpp
* This file was created by EMF4CPP 2.0.0 and is copyrighted by the
* respective user and/or provider of the processed ECORE model.
*
* EMF4CPP is free software. You can obtain it from
* https://github.com/catedrasaes-umu/emf4cpp
*/
#include "benchmark_experiment.hpp"
| [
"[email protected]"
] | |
cf831f119f9790357c76657ca8a064aac7a206fb | 0b15c7a046d703e153b6e6054cb57a0664a2d4df | /RobWork/ext/fcl/fcl/include/fcl/narrowphase/gjk.h | 3c9e14173b588691cf2034b865cca21da5e3bbe2 | [
"Apache-2.0",
"BSD-3-Clause"
] | permissive | skyellen/robwork-mirror | bf5d97ce19775c2928432854a93fb87ab2f7cd26 | 5a74a49d9ef98eff7c75f48fe48c2e655480e9b3 | refs/heads/master | 2020-04-16T06:10:11.359979 | 2018-09-06T09:26:01 | 2018-09-06T09:26:01 | 165,335,340 | 4 | 0 | null | 2019-01-12T02:01:40 | 2019-01-12T02:01:40 | null | UTF-8 | C++ | false | false | 8,690 | h | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011-2014, Willow Garage, Inc.
* Copyright (c) 2014-2016, Open Source Robotics Foundation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Open Source Robotics Foundation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/** \author Jia Pan */
#ifndef FCL_GJK_H
#define FCL_GJK_H
#include "fcl/shape/geometric_shapes.h"
#include "fcl/math/transform.h"
namespace fcl
{
namespace details
{
/// @brief the support function for shape
Vec3f getSupport(const ShapeBase* shape, const Vec3f& dir);
/// @brief Minkowski difference class of two shapes
struct MinkowskiDiff
{
/// @brief points to two shapes
const ShapeBase* shapes[2];
/// @brief rotation from shape0 to shape1
Matrix3f toshape1;
/// @brief transform from shape1 to shape0
Transform3f toshape0;
MinkowskiDiff() { }
/// @brief support function for shape0
inline Vec3f support0(const Vec3f& d) const
{
return getSupport(shapes[0], d);
}
/// @brief support function for shape1
inline Vec3f support1(const Vec3f& d) const
{
return toshape0.transform(getSupport(shapes[1], toshape1 * d));
}
/// @brief support function for the pair of shapes
inline Vec3f support(const Vec3f& d) const
{
return support0(d) - support1(-d);
}
/// @brief support function for the d-th shape (d = 0 or 1)
inline Vec3f support(const Vec3f& d, size_t index) const
{
if(index)
return support1(d);
else
return support0(d);
}
/// @brief support function for translating shape0, which is translating at velocity v
inline Vec3f support0(const Vec3f& d, const Vec3f& v) const
{
if(d.dot(v) <= 0)
return getSupport(shapes[0], d);
else
return getSupport(shapes[0], d) + v;
}
/// @brief support function for the pair of shapes, where shape0 is translating at velocity v
inline Vec3f support(const Vec3f& d, const Vec3f& v) const
{
return support0(d, v) - support1(-d);
}
/// @brief support function for the d-th shape (d = 0 or 1), where shape0 is translating at velocity v
inline Vec3f support(const Vec3f& d, const Vec3f& v, size_t index) const
{
if(index)
return support1(d);
else
return support0(d, v);
}
};
/// @brief class for GJK algorithm
struct GJK
{
struct SimplexV
{
/// @brief support direction
Vec3f d;
/// @brieg support vector (i.e., the furthest point on the shape along the support direction)
Vec3f w;
};
struct Simplex
{
/// @brief simplex vertex
SimplexV* c[4];
/// @brief weight
FCL_REAL p[4];
/// @brief size of simplex (number of vertices)
size_t rank;
Simplex() : rank(0) {}
};
enum Status {Valid, Inside, Failed};
MinkowskiDiff shape;
Vec3f ray;
FCL_REAL distance;
Simplex simplices[2];
GJK(unsigned int max_iterations_, FCL_REAL tolerance_) : max_iterations(max_iterations_),
tolerance(tolerance_)
{
initialize();
}
void initialize();
/// @brief GJK algorithm, given the initial value guess
Status evaluate(const MinkowskiDiff& shape_, const Vec3f& guess);
/// @brief apply the support function along a direction, the result is return in sv
void getSupport(const Vec3f& d, SimplexV& sv) const;
/// @brief apply the support function along a direction, the result is return is sv, here shape0 is translating at velocity v
void getSupport(const Vec3f& d, const Vec3f& v, SimplexV& sv) const;
/// @brief discard one vertex from the simplex
void removeVertex(Simplex& simplex);
/// @brief append one vertex to the simplex
void appendVertex(Simplex& simplex, const Vec3f& v);
/// @brief whether the simplex enclose the origin
bool encloseOrigin();
/// @brief get the underlying simplex using in GJK, can be used for cache in next iteration
inline Simplex* getSimplex() const
{
return simplex;
}
/// @brief get the guess from current simplex
Vec3f getGuessFromSimplex() const;
private:
SimplexV store_v[4];
SimplexV* free_v[4];
size_t nfree;
size_t current;
Simplex* simplex;
Status status;
unsigned int max_iterations;
FCL_REAL tolerance;
};
static const size_t EPA_MAX_FACES = 128;
static const size_t EPA_MAX_VERTICES = 64;
static const FCL_REAL EPA_EPS = 0.000001;
static const size_t EPA_MAX_ITERATIONS = 255;
/// @brief class for EPA algorithm
struct EPA
{
private:
typedef GJK::SimplexV SimplexV;
struct SimplexF
{
Vec3f n;
FCL_REAL d;
SimplexV* c[3]; // a face has three vertices
SimplexF* f[3]; // a face has three adjacent faces
SimplexF* l[2]; // the pre and post faces in the list
size_t e[3];
size_t pass;
};
struct SimplexList
{
SimplexF* root;
size_t count;
SimplexList() : root(NULL), count(0) {}
void append(SimplexF* face)
{
face->l[0] = NULL;
face->l[1] = root;
if(root) root->l[0] = face;
root = face;
++count;
}
void remove(SimplexF* face)
{
if(face->l[1]) face->l[1]->l[0] = face->l[0];
if(face->l[0]) face->l[0]->l[1] = face->l[1];
if(face == root) root = face->l[1];
--count;
}
};
static inline void bind(SimplexF* fa, size_t ea, SimplexF* fb, size_t eb)
{
fa->e[ea] = eb; fa->f[ea] = fb;
fb->e[eb] = ea; fb->f[eb] = fa;
}
struct SimplexHorizon
{
SimplexF* cf; // current face in the horizon
SimplexF* ff; // first face in the horizon
size_t nf; // number of faces in the horizon
SimplexHorizon() : cf(NULL), ff(NULL), nf(0) {}
};
private:
unsigned int max_face_num;
unsigned int max_vertex_num;
unsigned int max_iterations;
FCL_REAL tolerance;
public:
enum Status {Valid, Touching, Degenerated, NonConvex, InvalidHull, OutOfFaces, OutOfVertices, AccuracyReached, FallBack, Failed};
Status status;
GJK::Simplex result;
Vec3f normal;
FCL_REAL depth;
SimplexV* sv_store;
SimplexF* fc_store;
size_t nextsv;
SimplexList hull, stock;
EPA(unsigned int max_face_num_, unsigned int max_vertex_num_, unsigned int max_iterations_, FCL_REAL tolerance_) : max_face_num(max_face_num_),
max_vertex_num(max_vertex_num_),
max_iterations(max_iterations_),
tolerance(tolerance_)
{
initialize();
}
~EPA()
{
delete [] sv_store;
delete [] fc_store;
}
void initialize();
bool getEdgeDist(SimplexF* face, SimplexV* a, SimplexV* b, FCL_REAL& dist);
SimplexF* newFace(SimplexV* a, SimplexV* b, SimplexV* c, bool forced);
/// @brief Find the best polytope face to split
SimplexF* findBest();
Status evaluate(GJK& gjk, const Vec3f& guess);
/// @brief the goal is to add a face connecting vertex w and face edge f[e]
bool expand(size_t pass, SimplexV* w, SimplexF* f, size_t e, SimplexHorizon& horizon);
};
} // details
}
#endif
| [
"[email protected]"
] | |
a1715febd581f3ef5c50ad293fb0c29bd7e8dcf9 | a28685167ce3f9ea86288891667a1afe824b3b8e | /Coronet/include/Coronet/AssetStore.hpp | d54dc5e46fd4b981afa816f76f16f63ebc1d721a | [] | no_license | aoki-marika/coronet | 237acefea8a1727623a7c3f6ce4006df2baaa877 | 8173e79b2495e6aadae8b4e6b10a7e137138dd3e | refs/heads/master | 2020-03-13T03:53:21.562729 | 2018-05-06T01:20:20 | 2018-05-06T01:20:20 | 130,952,597 | 0 | 0 | null | 2018-05-06T01:00:37 | 2018-04-25T04:54:59 | C++ | UTF-8 | C++ | false | false | 1,675 | hpp | #pragma once
#include <string>
#include <sstream>
#include <physfs.h>
#include "Bitmap.hpp"
#include "BitmapSheet.hpp"
#include "TTFFont.hpp"
#include "Utilities.hpp"
namespace Coronet
{
class AssetStore
{
public:
AssetStore();
~AssetStore();
void Mount(std::string path);
std::shared_ptr<Bitmap> GetBitmap(std::string path);
std::shared_ptr<BitmapSheet> GetBitmapSheet(std::string path, int tileWidth, int tileHeight);
std::shared_ptr<TTFFont> GetTTF(std::string path, int ptsize);
template<typename T, typename... Args> std::shared_ptr<T> Get(std::string path, Args&&... args)
{
const char *fullPath = ("assets/" + path).c_str();
PHYSFS_File *file = PHYSFS_openRead(fullPath);
if (file == nullptr)
{
std::stringstream message;
message << "Failed to read file at '" << fullPath << "'";
ThrowPHYSFSException("openRead", message.str());
}
int length = PHYSFS_fileLength(file);
char *buffer[length];
int lengthRead = PHYSFS_readBytes(file, buffer, length);
if (lengthRead == -1)
{
std::stringstream message;
message << "Failed to read file at '" << fullPath << "'";
ThrowPHYSFSException("readBytes", message.str());
}
PHYSFS_close(file);
return std::make_shared<T>(SDL_RWFromMem(buffer, length), args...);
}
};
} | [
"[email protected]"
] | |
0e35a8dc50ce8b45a9124760956b4ad2c7be5eed | 6aeccfb60568a360d2d143e0271f0def40747d73 | /sandbox/assign_v2/boost/assign/v2/ref/aux_/convert_traits/const.hpp | 52b056e5be321b308b4e504a68ac363a9579024a | [] | no_license | ttyang/sandbox | 1066b324a13813cb1113beca75cdaf518e952276 | e1d6fde18ced644bb63e231829b2fe0664e51fac | refs/heads/trunk | 2021-01-19T17:17:47.452557 | 2013-06-07T14:19:55 | 2013-06-07T14:19:55 | 13,488,698 | 1 | 3 | null | 2023-03-20T11:52:19 | 2013-10-11T03:08:51 | C++ | UTF-8 | C++ | false | false | 1,742 | hpp | //////////////////////////////////////////////////////////////////////////////
// Boost.Assign v2 //
// //
// Copyright (C) 2003-2004 Thorsten Ottosen //
// Copyright (C) 2011 Erwann Rogard //
// Use, modification and distribution are subject to the //
// Boost Software License, Version 1.0. (See accompanying file //
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) //
//////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_ASSIGN_V2_REF_CONVERT_TRAITS_CONST_ER_2011_HPP
#define BOOST_ASSIGN_V2_REF_CONVERT_TRAITS_CONST_ER_2011_HPP
#include <boost/assign/v2/ref/aux_/convert_traits/value.hpp>
#include <boost/mpl/or.hpp>
#include <boost/type_traits/add_const.hpp>
#include <boost/type_traits/is_const.hpp>
#include <boost/type_traits/remove_cv.hpp>
namespace boost{
namespace assign{
namespace v2{
namespace ref{
namespace convert_traits{
template<
typename T1, typename T2, bool is_c
= ::boost::mpl::or_<
boost::is_const<T1>,
boost::is_const<T2>
>::value
>
struct const_
{
typedef typename convert_traits::value<
typename boost::remove_cv<T1>::type,
typename boost::remove_cv<T2>::type
>::type type;
};
template<typename T1, typename T2>
struct const_<T1, T2, true> : boost::add_const<
typename const_<T1, T2, false>::type
>{};
}// convert_traits
}// ref
}// v2
}// assign
}// boost
#endif
| [
"[email protected]"
] | |
07894ca5e9633258925fb33282af95d0bfbe468f | 86e3367acf81c30825670ad6b16056056e60cf48 | /ls/Scene/ConfigScene.cpp | 858125a62656b2699e5b6df617159bb1d2b80083 | [
"BSD-3-Clause"
] | permissive | sorcery-p5/Asteraiser | 0bb3e4a2e620f68764ee4e346e99440d1e7818b8 | f27da9e3e262772686245f7e83b800e41c909f0f | refs/heads/master | 2020-03-19T06:25:38.820721 | 2020-02-12T14:15:05 | 2020-02-12T14:15:05 | 136,018,491 | 6 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 23,371 | cpp | #include "stdafx.h"
#include "ConfigScene.h"
#include "TitleScene.h"
#include "App/App.h"
#include "Config/Config.h"
#include "Resource/ResourceManager.h"
#include "Controller/SystemController.h"
#include "Menu/Menu.h"
#include "Menu/MenuData.h"
#include "Menu/MenuLayer.h"
#include "Menu/Object/MenuObject.h"
namespace
{
pstr MENU_PATH = "Data/Menu/Config.xml";
pstr SCENE_TITLE = "Title";
pstr STRING_REVERSE = " REV";
pstr STRING_SETTING_KEY = "Push Setting Key";
pstr STRING_SETTING_PAD = "Push Setting Button";
pstr STRING_SETTING_X_AXIS = "Push Left Direction";
pstr STRING_SETTING_Y_AXIS = "Push Up Direction";
pstr STRING_DEFAULT = "Reset Default Setting?\n Push OK or CANCEL";
pstr HELP_TEXT_STRING_SETTING_KEY = "割り当てるキーを押してください。";
pstr HELP_TEXT_STRING_SETTING_PAD = "割り当てるボタンを押してください。";
pstr HELP_TEXT_STRING_SETTING_X_AXIS = "割り当てるレバーの左を入力してください。";
pstr HELP_TEXT_STRING_SETTING_Y_AXIS = "割り当てるレバーの上を入力してください。";
pstr HELP_TEXT_STRING_DEFAULT = "決定キーで初期化/キャンセルで戻ります。";
const Label LAYER_MAIN = "Main";
const Label LAYER_KEY_CONFIG = "KeyConfig";
const Label LAYER_PAD_CONFIG = "PadConfig";
const Label LAYER_INPUT_WAIT = "InputWait";
const Label OBJECT_SCREEN = "Screen";
const Label OBJECT_BGM = "BGM";
const Label OBJECT_SOUND = "Sound";
const Label OBJECT_PAD = "Pad";
const Label OBJECT_WINDOW = "Window";
const Label OBJECT_FULL = "Full";
const Label OBJECT_BGM_VOL = "BGMVol";
const Label OBJECT_SOUND_VOL = "SoundVol";
const Label OBJECT_AXIS_X = "AxisX";
const Label OBJECT_AXIS_Y = "AxisY";
const Label OBJECT_KEY_X = "KeyX";
const Label OBJECT_KEY_Y = "KeyY";
const Label OBJECT_DEADZONE = "DeadZone";
const Label OBJECT_DEAD_VALUE = "DeadV";
const Label OBJECT_MESSAGE = "Message";
const Label NOTIFY_INPUT = "Input";
const Label NOTIFY_DEFUALT = "Default";
struct INPUT_OBJECT
{
byte Value;
Label ObjectName;
Label TextName;
};
const INPUT_OBJECT BUTTON_OBJECT_TABLE[] =
{
{ CONTROLLER_BLADE, "Blade", "KeyBlade" },
{ CONTROLLER_RELOAD, "Reload", "KeyReload" },
{ CONTROLLER_DASH, "Dash", "KeyDash" },
};
const INPUT_OBJECT SYSTEM_OBJECT_TABLE[] =
{
{ CONTROLLER_SYSTEM_OK, "Ok", "KeyOk" },
{ CONTROLLER_SYSTEM_CANCEL, "Cancel", "KeyCancel" },
{ CONTROLLER_SYSTEM_PAUSE, "Pause", "KeyPause" },
{ CONTROLLER_SYSTEM_EXIT, "Exit", "KeyExit" },
};
const INPUT_OBJECT DIR_OBJECT_TABLE[] =
{
{ CONTROLLER_L - CONTROLLER_DIR_BEGIN, "Left", "KeyLeft" },
{ CONTROLLER_R - CONTROLLER_DIR_BEGIN, "Right", "KeyRight" },
{ CONTROLLER_U - CONTROLLER_DIR_BEGIN, "Up", "KeyUp" },
{ CONTROLLER_D - CONTROLLER_DIR_BEGIN, "Down", "KeyDown" },
};
struct CONCURRENT_OBJECT
{
byte Value[CONCURRENT_NUM];
Label ObjectName;
Label TextName;
};
const CONCURRENT_OBJECT CONCURRENT_OBJECT_TABLE[] =
{
{ { CONTROLLER_BLADE, CONTROLLER_DASH, UCHAR_MAX, UCHAR_MAX }, "Spear", "KeySpear" },
{ { CONTROLLER_RELOAD, CONTROLLER_DASH, UCHAR_MAX, UCHAR_MAX }, "Ruler", "KeyRuler" },
};
//------------------------------------------------------------------------------
// 入力の構造体検索(オブジェクト名)
//------------------------------------------------------------------------------
const INPUT_OBJECT* FindInputObject( const INPUT_OBJECT* pTable, int Num, Label ObjectName )
{
for( int i = 0; i < Num; i++ )
{
if( pTable[i].ObjectName == ObjectName )
{
return &pTable[i];
}
}
return NULL;
}
//------------------------------------------------------------------------------
// 同時押しの構造体検索(キー内容)
//------------------------------------------------------------------------------
const CONCURRENT_OBJECT* FindConcurrentObject( byte* pArray )
{
for( int i = 0; i < ArrayNum(CONCURRENT_OBJECT_TABLE); i++ )
{
bool bFind = true;
for( int j = 0; j < CONCURRENT_NUM; j++ )
{
if( CONCURRENT_OBJECT_TABLE[i].Value[j] != pArray[j] )
{
bFind = false;
break;
}
}
if( bFind )
{
return &CONCURRENT_OBJECT_TABLE[i];
}
}
return NULL;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// タイトルシーン
//
///////////////////////////////////////////////////////////////////////////////
ConfigScene::ConfigScene( Label Name )
:Scene( Name )
{
m_pMenuRes = NULL;
m_pMenu = NULL;
m_bChangeScreen = false;
}
ConfigScene::~ConfigScene()
{
SafeDelete( m_pMenu );
SafeRelease( m_pMenuRes );
}
//*****************************************************************************
// 初期化
//*****************************************************************************
void ConfigScene::OnInit( void )
{
// コンフィグデータの読み出し
Config* pConfig = GetConfig();
m_SystemInfo = pConfig->GetSystemInfo();
m_InputInfo = pConfig->GetInputInfo( 0 );
// メニュー
m_pMenuRes = GetApp()->GetResMng()->LoadResource<MenuResource>( MENU_PATH );
if( m_pMenuRes && m_pMenuRes->GetData() )
{
m_pMenu = new Menu( this );
MEM_CHECK( m_pMenu );
m_pMenu->Init( m_pMenuRes->GetData(), Matrix3::Trans( 0, 0 ) );
}
_ASSERT( m_pMenu );
// 背景色変更
P5::GetGraphix()->GetDevice()->SetScreenColor( Color(0,0,0) );
}
//*****************************************************************************
// 更新
//*****************************************************************************
void ConfigScene::Update( void )
{
if( !m_pMenu ) return;
// 入力待ちの更新
if( !m_InputLayerName.IsEmpty() &&
!m_InputObjectName.IsEmpty() )
{
_UpdateInputWait();
}
// デフォルト待機状態
if( m_bDefaultWait )
{
_UpdateDefaultWait();
}
// パッドのON/OFF
_UpdatePadEnable();
m_pMenu->Update();
// 終了
if( m_pMenu->IsEmpty() )
{
Config* pConfig = GetConfig();
// スクリーンモード
if( m_bChangeScreen &&
m_SystemInfo.bFullScreen != !P5::GetWindow()->IsWindowed() )
{
P5::GetWindow()->ChangeScreenMode();
}
// コンフィグデータ保存
pConfig->SetSystemInfo( m_SystemInfo );
pConfig->SetInputInfo( 0, m_InputInfo );
pConfig->Apply();
pConfig->Save();
ChangeScene( new TitleScene( SCENE_TITLE, GetName() ) );
return;
}
m_pMenu->Draw( Matrix3::Identity() );
}
//******************************************************************************
// レイヤーが開いた
//******************************************************************************
void ConfigScene::OnOpenLayer( MenuLayer* pLayer )
{
// メイン
if( pLayer->GetName() == LAYER_MAIN )
{
// 値の設定
_SetMainLayer( pLayer );
}
// キーコンフィグ
else if( pLayer->GetName() == LAYER_KEY_CONFIG )
{
// 値の設定
_SetKeyLayer( pLayer );
}
// パッドコンフィグ
else if( pLayer->GetName() == LAYER_PAD_CONFIG )
{
// 値の設定
_SetPadLayer( pLayer );
}
// 入力待機
else if( pLayer->GetName() == LAYER_INPUT_WAIT )
{
// キーボード
if( m_InputLayerName == LAYER_KEY_CONFIG )
{
pLayer->SetText( OBJECT_MESSAGE, STRING_SETTING_KEY );
pLayer->ReplaceHelpText( HELP_TEXT_STRING_SETTING_KEY );
}
// パッド
else if( m_InputLayerName == LAYER_PAD_CONFIG )
{
// パッドがない
if( !GetSign()->GetPad( 0 ) )
{
pLayer->Close();
return;
}
// X軸
if( m_InputObjectName == OBJECT_AXIS_X )
{
pLayer->SetText( OBJECT_MESSAGE, STRING_SETTING_X_AXIS );
pLayer->ReplaceHelpText( HELP_TEXT_STRING_SETTING_X_AXIS );
}
// Y軸
else if( m_InputObjectName == OBJECT_AXIS_Y )
{
pLayer->SetText( OBJECT_MESSAGE, STRING_SETTING_Y_AXIS );
pLayer->ReplaceHelpText( HELP_TEXT_STRING_SETTING_Y_AXIS );
}
else
{
pLayer->SetText( OBJECT_MESSAGE, STRING_SETTING_PAD );
pLayer->ReplaceHelpText( HELP_TEXT_STRING_SETTING_PAD );
}
}
// デフォルト
else if( m_bDefaultWait )
{
pLayer->SetText( OBJECT_MESSAGE, STRING_DEFAULT );
pLayer->ReplaceHelpText( HELP_TEXT_STRING_DEFAULT );
}
}
}
//******************************************************************************
// レイヤーが閉じられた
//******************************************************************************
void ConfigScene::OnCloseLayer( MenuLayer* pLayer )
{
// キーorパッドコンフィグ
if( pLayer->GetName() == LAYER_KEY_CONFIG ||
pLayer->GetName() == LAYER_PAD_CONFIG )
{
// コンフィグデータ適用
Config* pConfig = GetConfig();
pConfig->SetInputInfo( 0, m_InputInfo );
pConfig->Apply();
}
// 入力待機
else if( pLayer->GetName() == LAYER_INPUT_WAIT )
{
m_InputLayerName.Clear();
m_InputObjectName.Clear();
m_bDefaultWait = false;
}
}
//******************************************************************************
// メニューからの通知
//******************************************************************************
void ConfigScene::OnObjectNotify( MenuObject* pObject, Label Name, float Param )
{
// 入力設定
if( Name == NOTIFY_INPUT )
{
m_InputLayerName = pObject->GetParent()->GetName();
m_InputObjectName = pObject->GetName();
}
// デフォルト
if( Name == NOTIFY_DEFUALT )
{
m_bDefaultWait = true;
}
}
//******************************************************************************
// メニューの値変更
//******************************************************************************
void ConfigScene::OnObjectChangeValue( MenuObject* pObject )
{
Config* pConfig = GetConfig();
// スクリーンモード
if( pObject->GetName() == OBJECT_SCREEN )
{
m_SystemInfo.bFullScreen = pObject->GetSelectName() == OBJECT_FULL;
pConfig->SetSystemInfo( m_SystemInfo );
m_bChangeScreen = true;
}
// BGM
else if( pObject->GetName() == OBJECT_BGM )
{
m_SystemInfo.BGMVolume = pObject->GetValue() / 100.0f;
pObject->GetParent()->SetText( OBJECT_BGM_VOL, "%.0f", m_SystemInfo.BGMVolume * 100.0f );
pConfig->SetSystemInfo( m_SystemInfo );
GetTone()->SetChannelVolume( SOUND_CHANNEL_BGM, m_SystemInfo.BGMVolume );
}
// サウンド
else if( pObject->GetName() == OBJECT_SOUND )
{
m_SystemInfo.SoundVolume = pObject->GetValue() / 100.0f;
pObject->GetParent()->SetText( OBJECT_SOUND_VOL, "%.0f", m_SystemInfo.SoundVolume * 100.0f );
pConfig->SetSystemInfo( m_SystemInfo );
GetTone()->SetChannelVolume( SOUND_CHANNEL_SE, m_SystemInfo.SoundVolume );
}
// レバー:デッドゾーン
else if( pObject->GetName() == OBJECT_DEADZONE )
{
m_InputInfo.PadDeadzone = (uint)pObject->GetValue();
pObject->GetParent()->SetText( OBJECT_DEAD_VALUE, "%d", m_InputInfo.PadDeadzone );
}
}
//------------------------------------------------------------------------------
// 入力待ち状態の更新
//------------------------------------------------------------------------------
void ConfigScene::_UpdateInputWait( void )
{
MenuLayer* pLayer = m_pMenu->GetCurLayer();
if( !pLayer || pLayer->GetName() != LAYER_INPUT_WAIT ) return;
MenuLayer* pParent = m_pMenu->GetLayer( m_InputLayerName );
if( !pParent ) return;
if( !pLayer->IsWait() ) return;
Keyboard* pKeyboard = GetSign()->GetKeyboard();
Pad* pPad = GetSign()->GetPad( 0 );
_ASSERT( pKeyboard );
// キーボード
if( m_InputLayerName == LAYER_KEY_CONFIG )
{
byte KeyCode = pKeyboard->GetInputKey( INPUT_TRIG );
// 対応するキーかどうか
if( !KeyCode || Config::KeycodeToStr(KeyCode).empty() ) return;
bool bChange = false;
const INPUT_OBJECT* pObject = NULL;
// 方向
pObject = FindInputObject( DIR_OBJECT_TABLE, ArrayNum(DIR_OBJECT_TABLE), m_InputObjectName );
if( pObject )
{
_SolveKeyDuplication( m_InputInfo.aKeyDir[ pObject->Value ], KeyCode, INPUT_DIR );
m_InputInfo.aKeyDir[ pObject->Value ] = KeyCode;
bChange = true;
}
// システムキー
pObject = FindInputObject( SYSTEM_OBJECT_TABLE, ArrayNum(SYSTEM_OBJECT_TABLE), m_InputObjectName );
if( pObject )
{
_SolveKeyDuplication( m_InputInfo.aKeySystem[ pObject->Value ], KeyCode, INPUT_SYSTEM );
m_InputInfo.aKeySystem[ pObject->Value ] = KeyCode;
bChange = true;
}
// ボタン
pObject = FindInputObject( BUTTON_OBJECT_TABLE, ArrayNum(BUTTON_OBJECT_TABLE), m_InputObjectName );
if( pObject )
{
_SolveKeyDuplication( m_InputInfo.aKeyButton[ pObject->Value ], KeyCode, INPUT_BUTTON );
m_InputInfo.aKeyButton[ pObject->Value ] = KeyCode;
bChange = true;
}
// 同時押し
for( int i = 0; i < (int)m_InputInfo.vKeyConcurrent.size(); i++ )
{
const CONCURRENT_OBJECT* pCuncurrent = FindConcurrentObject( m_InputInfo.vKeyConcurrent[i].Array );
if( pCuncurrent && pCuncurrent->ObjectName == m_InputObjectName )
{
_SolveKeyDuplication( m_InputInfo.vKeyConcurrent[i].Button, KeyCode, INPUT_BUTTON );
m_InputInfo.vKeyConcurrent[i].Button = KeyCode;
bChange = true;
break;
}
}
// メニュー反映
if( bChange )
{
_SetKeyLayer( pParent );
pLayer->Close();
}
}
// パッド
else if( m_InputLayerName == LAYER_PAD_CONFIG )
{
// パッドがない
if( !pPad )
{
pLayer->Close();
return;
}
bool bChange = false;
// 軸
if( m_InputObjectName == OBJECT_AXIS_X || m_InputObjectName == OBJECT_AXIS_Y )
{
PAD_AXIS PadAxis = PAD_AXIS_X;
bool bRev = false;
for( int i = 0; i < PAD_AXIS_NUM; i++ )
{
float Value = pPad->GetAxis( PAD_AXIS(i), INPUT_TRIG );
if( Value == 0.0f ) continue;
bRev = Value > 0.0f;
PadAxis = PAD_AXIS(i);
// X軸
if( m_InputObjectName == OBJECT_AXIS_X )
{
_SolveAxisDuplication( m_InputInfo.PadAxisX, m_InputInfo.bPadAxisXRev, PadAxis );
m_InputInfo.PadAxisX = PadAxis;
m_InputInfo.bPadAxisXRev = bRev;
bChange = true;
}
// Y軸
else if( m_InputObjectName == OBJECT_AXIS_Y )
{
_SolveAxisDuplication( m_InputInfo.PadAxisY, m_InputInfo.bPadAxisYRev, PadAxis );
m_InputInfo.bPadAxisYRev = bRev;
m_InputInfo.PadAxisY = PadAxis;
bChange = true;
}
}
}
else
{
byte Button = pPad->GetInputButton( INPUT_TRIG );
if( Button == UCHAR_MAX ) return;
const INPUT_OBJECT* pObject = NULL;
// システムキー
pObject = FindInputObject( SYSTEM_OBJECT_TABLE, ArrayNum(SYSTEM_OBJECT_TABLE), m_InputObjectName );
if( pObject )
{
_SolvePadDuplication( m_InputInfo.aPadSystem[ pObject->Value ], Button, INPUT_SYSTEM );
m_InputInfo.aPadSystem[ pObject->Value ] = Button;
bChange = true;
}
// ボタン
pObject = FindInputObject( BUTTON_OBJECT_TABLE, ArrayNum(BUTTON_OBJECT_TABLE), m_InputObjectName );
if( pObject )
{
_SolvePadDuplication( m_InputInfo.aPadButton[ pObject->Value ], Button, INPUT_BUTTON );
m_InputInfo.aPadButton[ pObject->Value ] = Button;
bChange = true;
}
// 同時押し
for( int i = 0; i < (int)m_InputInfo.vPadConcurrent.size(); i++ )
{
const CONCURRENT_OBJECT* pCuncurrent = FindConcurrentObject( m_InputInfo.vPadConcurrent[i].Array );
if( pCuncurrent && pCuncurrent->ObjectName == m_InputObjectName )
{
_SolvePadDuplication( m_InputInfo.vPadConcurrent[ i ].Button, Button, INPUT_BUTTON );
m_InputInfo.vPadConcurrent[i].Button = Button;
bChange = true;
break;
}
}
}
// メニュー反映
if( bChange )
{
_SetPadLayer( pParent );
pLayer->Close();
}
}
}
//------------------------------------------------------------------------------
// デフォルト待機状態
//------------------------------------------------------------------------------
void ConfigScene::_UpdateDefaultWait( void )
{
MenuLayer* pLayer = m_pMenu->GetCurLayer();
if( !pLayer || pLayer->GetName() != LAYER_INPUT_WAIT ) return;
SystemController Ctrl;
if( Ctrl.IsInput( CONTROLLER_SYSTEM_OK, INPUT_TRIG ) )
{
// リセットする
m_SystemInfo.Default();
m_InputInfo.Default(0);
// 適用
Config* pConfig = GetConfig();
pConfig->SetSystemInfo( m_SystemInfo );
pConfig->SetInputInfo( 0, m_InputInfo );
pConfig->Apply();
_SetMainLayer( m_pMenu->GetLayer( LAYER_MAIN ) );
pLayer->Close();
m_bDefaultWait = false;
m_bChangeScreen = true;
}
else if( Ctrl.IsInput( CONTROLLER_SYSTEM_CANCEL, INPUT_TRIG ) )
{
pLayer->Close();
m_bDefaultWait = false;
}
}
//------------------------------------------------------------------------------
// パッドのON/OFFを設定する
//------------------------------------------------------------------------------
void ConfigScene::_UpdatePadEnable( void )
{
MenuLayer* pLayer = m_pMenu->GetCurLayer();
if( !pLayer || pLayer->GetName() != LAYER_MAIN ) return;
pLayer->SetColor( OBJECT_PAD, GetSign()->GetPad(0) != NULL? Color::White() : Color::Gray(128) );
}
//------------------------------------------------------------------------------
// キー設定の重複を解決する
//------------------------------------------------------------------------------
void ConfigScene::_SolveKeyDuplication( byte OldValue, byte NewValue, INPUT InputType )
{
// 方向
for( int i = 0; i < CONTROLLER_DIR_NUM; i++ )
{
if( m_InputInfo.aKeyDir[i] == NewValue )
{
m_InputInfo.aKeyDir[i] = OldValue;
}
}
if( InputType != INPUT_BUTTON )
{
// システムキー
for( int i = 0; i < CONTROLLER_SYSTEM_KEY_NUM; i++ )
{
if( m_InputInfo.aKeySystem[i] == NewValue )
{
m_InputInfo.aKeySystem[i] = OldValue;
}
}
}
if( InputType != INPUT_SYSTEM )
{
// ボタン
for( int i = 0; i < CONTROLLER_BUTTON_NUM; i++ )
{
if( m_InputInfo.aKeyButton[i] == NewValue )
{
m_InputInfo.aKeyButton[i] = OldValue;
}
}
// 同時押し
for( int i = 0; i < (int)m_InputInfo.vKeyConcurrent.size(); i++ )
{
if( m_InputInfo.vKeyConcurrent[i].Button == NewValue )
{
m_InputInfo.vKeyConcurrent[i].Button = OldValue;
}
}
}
}
//------------------------------------------------------------------------------
// パッドボタン設定の重複を解決する
//------------------------------------------------------------------------------
void ConfigScene::_SolvePadDuplication( byte OldValue, byte NewValue, INPUT InputType )
{
if( InputType != INPUT_BUTTON )
{
// システムキー
for( int i = 0; i < CONTROLLER_SYSTEM_KEY_NUM; i++ )
{
if( m_InputInfo.aPadSystem[i] == NewValue )
{
m_InputInfo.aPadSystem[i] = OldValue;
}
}
}
if( InputType != INPUT_SYSTEM )
{
// ボタン
for( int i = 0; i < CONTROLLER_BUTTON_NUM; i++ )
{
if( m_InputInfo.aPadButton[i] == NewValue )
{
m_InputInfo.aPadButton[i] = OldValue;
}
}
// 同時押し
for( int i = 0; i < (int)m_InputInfo.vPadConcurrent.size(); i++ )
{
if( m_InputInfo.vPadConcurrent[i].Button == NewValue )
{
m_InputInfo.vPadConcurrent[i].Button = OldValue;
}
}
}
}
//------------------------------------------------------------------------------
// パッド軸設定の重複を解決する
//------------------------------------------------------------------------------
void ConfigScene::_SolveAxisDuplication( PAD_AXIS OldValue, bool bOldRev, PAD_AXIS NewValue )
{
if( m_InputInfo.PadAxisX == NewValue )
{
m_InputInfo.PadAxisX = OldValue;
m_InputInfo.bPadAxisXRev = bOldRev;
}
if( m_InputInfo.PadAxisY == NewValue )
{
m_InputInfo.PadAxisY = OldValue;
m_InputInfo.bPadAxisYRev = bOldRev;
}
}
//------------------------------------------------------------------------------
// 最上位レイヤーの表示設定
//------------------------------------------------------------------------------
void ConfigScene::_SetMainLayer( MenuLayer* pLayer )
{
if( !pLayer ) return;
// スクリーン
pLayer->SetObjectSelect( OBJECT_SCREEN, m_SystemInfo.bFullScreen? OBJECT_FULL : OBJECT_WINDOW );
// サウンド
pLayer->SetObjectValue( OBJECT_BGM, m_SystemInfo.BGMVolume * 100.0f );
pLayer->SetObjectValue( OBJECT_SOUND, m_SystemInfo.SoundVolume * 100.0f );
pLayer->SetText( OBJECT_BGM_VOL, "%.0f", m_SystemInfo.BGMVolume * 100.0f );
pLayer->SetText( OBJECT_SOUND_VOL, "%.0f", m_SystemInfo.SoundVolume * 100.0f );
// パッド
pLayer->SetObjectEnable( OBJECT_PAD, GetSign()->GetPad(0) != NULL );
}
//------------------------------------------------------------------------------
// キー設定レイヤーの表示設定
//------------------------------------------------------------------------------
void ConfigScene::_SetKeyLayer( MenuLayer* pLayer )
{
if( !pLayer ) return;
// 方向
for( int i = 0; i < CONTROLLER_DIR_NUM; i++ )
{
pLayer->SetText( DIR_OBJECT_TABLE[i].TextName, Config::KeycodeToStr( m_InputInfo.aKeyDir[DIR_OBJECT_TABLE[i].Value] ).c_str() );
}
// システムキー
for( int i = 0; i < CONTROLLER_SYSTEM_KEY_NUM; i++ )
{
pLayer->SetText( SYSTEM_OBJECT_TABLE[i].TextName, Config::KeycodeToStr( m_InputInfo.aKeySystem[SYSTEM_OBJECT_TABLE[i].Value] ).c_str() );
}
// ボタン
for( int i = 0; i < CONTROLLER_BUTTON_NUM; i++ )
{
pLayer->SetText( BUTTON_OBJECT_TABLE[i].TextName, Config::KeycodeToStr( m_InputInfo.aKeyButton[BUTTON_OBJECT_TABLE[i].Value] ).c_str() );
}
// 同時押し
for( int i = 0; i < (int)m_InputInfo.vKeyConcurrent.size(); i++ )
{
const CONCURRENT_OBJECT* pCuncurrent = FindConcurrentObject( m_InputInfo.vKeyConcurrent[i].Array );
if( pCuncurrent )
{
pLayer->SetText( pCuncurrent->TextName, Config::KeycodeToStr( m_InputInfo.vKeyConcurrent[i].Button ).c_str() );
}
}
}
//------------------------------------------------------------------------------
// パッド設定レイヤーの表示設定
//------------------------------------------------------------------------------
void ConfigScene::_SetPadLayer( MenuLayer* pLayer )
{
if( !pLayer ) return;
// 軸
pLayer->SetText( OBJECT_KEY_X, _GetAxisString( m_InputInfo.PadAxisX, m_InputInfo.bPadAxisXRev ).c_str() );
pLayer->SetText( OBJECT_KEY_Y, _GetAxisString( m_InputInfo.PadAxisY, m_InputInfo.bPadAxisYRev ).c_str() );
// レバーデッドゾーン
pLayer->SetObjectValue( OBJECT_DEADZONE, m_InputInfo.PadDeadzone );
pLayer->SetText( OBJECT_DEAD_VALUE, "%d", m_InputInfo.PadDeadzone );
// システムキー
for( int i = 0; i < CONTROLLER_SYSTEM_KEY_NUM; i++ )
{
pLayer->SetText( SYSTEM_OBJECT_TABLE[i].TextName, "%d", m_InputInfo.aPadSystem[SYSTEM_OBJECT_TABLE[i].Value] + 1 );
}
// ボタン
for( int i = 0; i < CONTROLLER_BUTTON_NUM; i++ )
{
pLayer->SetText( BUTTON_OBJECT_TABLE[i].TextName, "%d", m_InputInfo.aPadButton[BUTTON_OBJECT_TABLE[i].Value] + 1 );
}
// 同時押し
for( int i = 0; i < (int)m_InputInfo.vPadConcurrent.size(); i++ )
{
const CONCURRENT_OBJECT* pCuncurrent = FindConcurrentObject( m_InputInfo.vPadConcurrent[i].Array );
if( pCuncurrent )
{
pLayer->SetText( pCuncurrent->TextName, "%d", m_InputInfo.vPadConcurrent[i].Button + 1 );
}
}
}
//------------------------------------------------------------------------------
// 軸を表す文字列を得る
//------------------------------------------------------------------------------
std::string ConfigScene::_GetAxisString( PAD_AXIS Axis, bool bRev ) const
{
std::string Str = Config::PadAxisToStr( Axis );
if( bRev ) Str += STRING_REVERSE;
return Str;
} | [
"[email protected]"
] | |
dc7464dc66f354f80a0c7bd1c81c735c87752871 | 7252ca0228705a1cfd47c6437fa45eec9b19565e | /kimug2145/11729/11729.cpp14.cpp | 8223cf37d0cff976b6c139417750a84d5aedd27e | [] | no_license | seungjae-yu/Algorithm-Solving-BOJ | 1acf12668dc803413af28f8c0dc61f923d6e2e17 | e294d631b2808fdcfc80317bd2b0bccccc7fc065 | refs/heads/main | 2023-08-19T00:30:13.832180 | 2021-10-06T14:49:12 | 2021-10-06T14:49:12 | 414,241,010 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 314 | cpp | #include <iostream>
int N;
void Ha(int n, int from, int mid, int to) {
if (n == 1) printf("%d %d\n", from, to);
else {
Ha(n - 1, from, to, mid);
printf("%d %d\n", from, to);
Ha(n - 1, mid, from, to);
}
}
int main() {
scanf("%d", &N);
printf("%d\n", (1 << N) - 1);
Ha(N, 1, 2, 3);
} | [
"[email protected]"
] | |
59d2856e2a38fc30facc1da1ec3a7f679a1765cb | 349d0eb99c6294e40162e8a07871dbb56666977a | /Assignment2/Q1/hello_world.cc | 4038f2bca6252be65b5e3723e603fe63e2a8e4d8 | [
"MIT"
] | permissive | Gurupradeep/Parallel-Programming | f2b75736463ad9983b43efe43b6aced2a2389387 | fe54eb921f8895518c9d041075a92a5bd1499737 | refs/heads/master | 2021-05-14T03:57:59.428518 | 2018-02-14T04:40:46 | 2018-02-14T04:40:46 | 116,630,568 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 881 | cc | /*
* Basic Hello world program
* Run the program as follows
* (Compilation) mpicxx hello_world.cc
* (Execution) mpirun -n NO_OF_PROCESSES ./a.out
* Arguments
* 1) NO_OF_PROCESES. (Optional Parameter) : no of processes to be created.
*/
#include <stdio.h>
#include <mpi.h>
int main(int argc, char *argv[]) {
//Declaring variables for process_identifier, no of processes and length of the processor name
int rank, size, namelen;
//For name of the processor
char name[100];
//Initialsiing the MPI environment
MPI_Init(NULL, NULL);
//To get no of processes
MPI_Comm_size(MPI_COMM_WORLD, &size);
//To get process id
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
//To get processor name
MPI_Get_processor_name(name, &namelen);
printf ("Hello World. Rank %d out of %d running on %s!\n", rank, size, name);
//Terminate MPI environment
MPI_Finalize();
return 0;
} | [
"[email protected]"
] | |
007fe45e414462020b9d5de4464363e0d5c4879b | 0762bd15b382b5322c51967a707151c749122198 | /inc/config_parser.h | 22eeb513230eb0c686d6833278557556c1b0a2aa | [] | no_license | lumovan/UWB_location | 8a665d85e1d9e0b4333680d43fe419febcae00c0 | 9281e54dcd556ad644513dab2099ea5ac71e70b2 | refs/heads/master | 2022-01-10T01:47:37.864018 | 2019-06-05T00:30:37 | 2019-06-05T00:30:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 759 | h | #pragma once
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <libconfig.h++>
using namespace std;
using namespace libconfig;
class UWBConfigParser{
public:
UWBConfigParser();
bool set_boostar_config_file(const string cfg_file);
void get_boostar_anchor_pos(string *anchor_pos){*anchor_pos=_boostar_param.anchor_pos;}
void get_boostar_solve_param(string *solve_param){*solve_param=_boostar_param.solve_param;}
void get_boostar_input_dev(string *input_dev){*input_dev=_boostar_param.input_dev;}
void get_boostar_output_dev(string *output_dev){*output_dev=_boostar_param.output_dev;}
private:
Config cfg;
struct BOOSTAR_PARAM{
string anchor_pos;
string solve_param;
string input_dev;
string output_dev;
}_boostar_param;
}; | [
"[email protected]"
] | |
5a2c8bd5a3fa4909ce2ccb645514a4aeeb18cad0 | 85b9ce4fb88972d9b86dce594ae4fb3acfcd0a4b | /build/iOS/Release/include/Fuse.Scripting.JavaScriptCore.JSClassRef.h | 3904cae6dec46a68b478d71d14eb87771d646810 | [] | no_license | bgirr/Global-Pot_App | 16431a99e26f1c60dc16223fb388d9fd525cb5fa | c96c5a8fb95acde66fc286bcd9a5cdf160ba8b1b | refs/heads/master | 2021-01-09T06:29:18.255583 | 2017-02-21T23:27:47 | 2017-02-21T23:27:47 | 80,985,681 | 0 | 0 | null | 2017-02-21T23:27:48 | 2017-02-05T10:29:14 | C++ | UTF-8 | C++ | false | false | 923 | h | // This file was generated based on C:\Users\EliteBook-User\AppData\Local\Fusetools\Packages\Fuse.Scripting.JavaScriptCore\0.44.1\$.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.IDisposable.h>
#include <Uno.Object.h>
namespace g{
namespace Fuse{
namespace Scripting{
namespace JavaScriptCore{
// internal extern struct JSClassRef :857
// {
struct JSClassRef_type : uStructType
{
::g::Uno::IDisposable interface0;
};
JSClassRef_type* JSClassRef_typeof();
void JSClassRef__CreateUnoCallback_fn(::JSClassRef* __retval);
void JSClassRef__CreateUnoFinalizer_fn(::JSClassRef* __retval);
void JSClassRef__Dispose_fn(::JSClassRef* __this);
struct JSClassRef
{
void* _dummy;
static void Dispose(::JSClassRef __this);
static ::JSClassRef CreateUnoCallback();
static ::JSClassRef CreateUnoFinalizer();
};
// }
}}}} // ::g::Fuse::Scripting::JavaScriptCore
| [
"[email protected]"
] | |
c4735dac7049f656c820117e7da8b439c38b8248 | fcdea24e6466d4ec8d7798555358a9af8acf9b35 | /Engine/mrayEngine/src/DeviceCapabilites.cpp | eac38da7a78fbacd60f8cadbbc3de2daa05c0b51 | [] | no_license | yingzhang536/mrayy-Game-Engine | 6634afecefcb79c2117cecf3e4e635d3089c9590 | 6b6fcbab8674a6169e26f0f20356d0708620b828 | refs/heads/master | 2021-01-17T07:59:30.135446 | 2014-11-30T16:10:54 | 2014-11-30T16:10:54 | 27,630,181 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,995 | cpp | #include "stdafx.h"
#include "DeviceCapabilites.h"
#include "mraySystem.h"
#include "ILogManager.h"
#include "StringConverter.h"
namespace mray{
namespace video{
std::vector<core::string> DeviceCapabilites::m_vendors;
bool DeviceCapabilites::m_inited=0;
DeviceCapabilites:: DeviceCapabilites(){
mraySystem::memSet(m_features,0,sizeof(m_features));
m_vendor=EGPU_Unkown;
m_MaxTextureUnits=1;
m_MaxWorldMatUnits=1;
m_stencilBufferBits=0;
m_numVertexBlendMat=0;
m_numMultiRenderTargets=0;
initVendors();
}
DeviceCapabilites::~DeviceCapabilites(){
}
void DeviceCapabilites::initVendors(){
if(m_inited)
return;
m_vendors.resize(EGPU_Count);
m_vendors[EGPU_Unkown]=mT("unkown");
m_vendors[EGPU_NVidia]=mT("nvidia");
m_vendors[EGPU_ATI]=mT("ati");
m_vendors[EGPU_Intel]=mT("intel");
m_vendors[EGPU_Matrox]=mT("matrox");
m_vendors[EGPU_3DLabs]=mT("3dlabs");
m_vendors[EGPU_S3]=mT("s3");
}
bool DeviceCapabilites::isFeatureSupported(EDeviceFeature feature)const {
return m_features[feature];
}
void DeviceCapabilites::setFeature(EDeviceFeature feature,bool support){
m_features[feature]=support;
}
core::string DeviceCapabilites::getVendorString(EGPU_Vendor v){
if(!m_inited)
initVendors();
return m_vendors[v];
}
EGPU_Vendor DeviceCapabilites::getVendorFromString(const core::string& v){
if(!m_inited)
initVendors();
core::string s=v;
s.make_lower();
for (int i=0;i<m_vendors.size();i++)
{
if(s==m_vendors[i])
return (EGPU_Vendor)i;
}
return EGPU_Unkown;
}
bool DeviceCapabilites::isShaderProfileSupported(const core::string&p)const {
for (int i=0;i<m_ShaderProfiles.size();i++)
{
if(p.equals_ignore_case(m_ShaderProfiles[i]))
return true;
}
return false;
}
const std::vector<core::string>& DeviceCapabilites::getShaderProfiles()const{
return m_ShaderProfiles;
}
void DeviceCapabilites::logInfo(ILogDevice*log){
log->startSection(mT("Device Capabilities"));
log->log(mT("Device Name : ")+m_deviceName,ELL_INFO);
log->log(mT("Vendor Name : ")+getVendorString(m_vendor),ELL_INFO);
log->log(mT("Max Textures Units : ")+core::StringConverter::toString(m_MaxTextureUnits),ELL_INFO);
log->log(mT("Max World Matrix Units : ")+core::StringConverter::toString(m_MaxWorldMatUnits),ELL_INFO);
log->log(mT("Max Stencil Buffer Bits : ")+core::StringConverter::toString(m_stencilBufferBits),ELL_INFO);
log->log(mT("Max Vertex Blend Matrix : ")+core::StringConverter::toString(m_numVertexBlendMat),ELL_INFO);
log->log(mT("Max MultiRenderTarget Count : ")+core::StringConverter::toString(m_numMultiRenderTargets),ELL_INFO);
log->log(mT("Max Lights Units : ")+core::StringConverter::toString(m_maxLights),ELL_INFO);
log->log(mT("Max Ansitropy : ")+core::StringConverter::toString(m_MaxAnisotropy),ELL_INFO);
log->log(mT("Features: "),ELL_INFO);
log->log(mT("Render To Target : ")+core::StringConverter::toString(isFeatureSupported(EDF_RenderToTarget)),ELL_INFO);
log->log(mT("Bilinear Filter: ")+core::StringConverter::toString(isFeatureSupported(EDF_BilinearFilter)),ELL_INFO);
log->log(mT("Mipmaps: ")+core::StringConverter::toString(isFeatureSupported(EDF_MIPMAP)),ELL_INFO);
log->log(mT("Mipmap auto update: ")+core::StringConverter::toString(isFeatureSupported(EDF_MIPMAP_AUTO_UPDATE)),ELL_INFO);
log->log(mT("Auto Mipmap: ")+core::StringConverter::toString(isFeatureSupported(EDF_AutoMipmap)),ELL_INFO);
log->log(mT("Stencil Buffer: ")+core::StringConverter::toString(isFeatureSupported(EDF_StencilBuffer)),ELL_INFO);
log->log(mT("Vertex Program: ")+core::StringConverter::toString(isFeatureSupported(EDF_VertexProgram)),ELL_INFO);
log->log(mT("Fragment Program: ")+core::StringConverter::toString(isFeatureSupported(EDF_FragmentProgram)),ELL_INFO);
log->log(mT("Geometry Program: ")+core::StringConverter::toString(isFeatureSupported(EDF_GeometryProgram)),ELL_INFO);
log->log(mT("Vertex Buffer Object: ")+core::StringConverter::toString(isFeatureSupported(EDF_VertexBufferObject)),ELL_INFO);
log->log(mT("Textures Non Power of 2: ")+core::StringConverter::toString(isFeatureSupported(EDF_TextureNP2)),ELL_INFO);
log->log(mT("Frame Buffer Object: ")+core::StringConverter::toString(isFeatureSupported(EDF_FrameBufferObject)),ELL_INFO);
log->log(mT("Floating point textures: ")+core::StringConverter::toString(isFeatureSupported(EDF_FloatTexture)),ELL_INFO);
log->log(mT("DXT Compression: ")+core::StringConverter::toString(isFeatureSupported(EDF_DXT_Compression)),ELL_INFO);
log->log(mT("Packed Depth Stencil: ")+core::StringConverter::toString(isFeatureSupported(EDF_PackedDepthStencil)),ELL_INFO);
log->log(mT("Seperate Stencil Buffer: ")+core::StringConverter::toString(isFeatureSupported(EDF_SeperateStencilBuffer)),ELL_INFO);
log->log(mT("Multi Sample: ")+core::StringConverter::toString(isFeatureSupported(EDF_MultiSample)),ELL_INFO);
log->log(mT("Seperate Specular Color: ")+core::StringConverter::toString(isFeatureSupported(EDF_SeparateSpecularColor)),ELL_INFO);
log->log(mT("Cube Mapping: ")+core::StringConverter::toString(isFeatureSupported(EDF_CubeMapping)),ELL_INFO);
log->log(mT("Scissor Test: ")+core::StringConverter::toString(isFeatureSupported(EDF_ScissorTest)),ELL_INFO);
log->log(mT("3D Textures: ")+core::StringConverter::toString(isFeatureSupported(EDF_Texture3D)),ELL_INFO);
log->log(mT("Point Sprites: ")+core::StringConverter::toString(isFeatureSupported(EDF_PointSprites)),ELL_INFO);
log->log(mT("Anisotropy: ")+core::StringConverter::toString(isFeatureSupported(EDF_Anisotropy)),ELL_INFO);
log->log(mT("Occlusion Query: ")+core::StringConverter::toString(isFeatureSupported(EDF_OcclusionQuery)),ELL_INFO);
log->log(mT("DOT3: ")+core::StringConverter::toString(isFeatureSupported(EDF_DOT3)),ELL_INFO);
log->log(mT("Blending: ")+core::StringConverter::toString(isFeatureSupported(EDF_Blending)),ELL_INFO);
log->endSection(true);
}
}
}
| [
"[email protected]"
] | |
c3254d46d070e89679ee9ef7268f98e2305493ec | da86d9f9cf875db42fd912e3366cfe9e0aa392c6 | /2020/solutions/B/DKV-Plovdiv/DKV/brackets.cpp | 039d54141c33569a855972eb342885abcb886c1e | [] | no_license | Alaxe/noi2-ranking | 0c98ea9af9fc3bd22798cab523f38fd75ed97634 | bb671bacd369b0924a1bfa313acb259f97947d05 | refs/heads/master | 2021-01-22T23:33:43.481107 | 2020-02-15T17:33:25 | 2020-02-15T17:33:25 | 85,631,202 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,036 | cpp | #include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <algorithm>
struct commands{
commands(){}
bool multiplication = false;
bool sum = false;
int first = 0;
int last = 0;
bool minusInFront = false;
};
void findbrackets(std::string& text, int index){
int opperandsCount = 0;
while (text[index] != '(' && text[index] != ')'){
if (text[index] == '&')
++opperandsCount;
if (opperandsCount == 2){
}
++index;
}
if (text[index] == '('){
}
else if (text[index] == ')'){
}
}
int main(){
std::string text;
std::cin >> text;
std::stack<commands> stack;
stack.push(commands());
std::vector<int> indecies;
for (int i = 0; i < text.size(); ++i){
if (text[i] == '+' || text[i] == '-'){
stack.top().sum = true;
if (text[i] == '-' && text[i + 1] == '('){
commands newCmd;
newCmd.first = i + 1;
newCmd.minusInFront = true;
stack.push(newCmd);
++i;
}
}
else if (text[i] == '*' || text[i] == '/') {
if (text[i + 1] == '('){
commands newCmd;
newCmd.first = i + 1;
newCmd.multiplication = true;
stack.push(newCmd);
++i;
}
}
else if (text[i] == ')'){
stack.top().last = i;
commands currentCmd = stack.top();
if (currentCmd.sum == false){
indecies.push_back(currentCmd.first);
indecies.push_back(currentCmd.last);
}
else{
if (text.length() > i + 1 && text[i + 1] == '*' || text[i + 1] == '/')
{
}
else if (currentCmd.minusInFront == false && currentCmd.multiplication == false){
indecies.push_back(currentCmd.first);
indecies.push_back(currentCmd.last);
}
}
stack.pop();
}
else if (text[i] == '('){
commands newCmd;
newCmd.first = i;
stack.push(newCmd);
}
}
std::sort(indecies.begin(), indecies.end());
for (int i = indecies.size() - 1; i >= 0; --i){
text.replace(indecies[i], 1, "");
}
std::cout << text << std::endl;
return 0;
} | [
"[email protected]"
] | |
466d1d341c0280187fbef650bed6a6f0f374fc03 | c4c4a47362bdf2f0c2c977ce3a1bdcee78adb659 | /opencv4.1/opencv-bulild/modules/rapid/opencv_rapid_main.cpp | b3ea219360b4aa46578db453626a26c54026c6be | [] | no_license | TJSlovecoding/myc_plus | d05e6fd94506663ea8d8e62491c8a7e23d4da1a4 | d7ed36b830fed2dbc090f0e731f8134a901adf78 | refs/heads/master | 2022-12-11T01:15:09.086120 | 2020-09-14T13:28:00 | 2020-09-14T13:28:07 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 953 | cpp | // This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
#ifndef _WIN32
#error "Build configuration error"
#endif
#ifndef CVAPI_EXPORTS
#error "Build configuration error"
#endif
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#define OPENCV_MODULE_S "opencv_rapid"
namespace cv {
extern __declspec(dllimport) bool __termination; // Details: #12750
}
extern "C"
BOOL WINAPI DllMain(HINSTANCE, DWORD fdwReason, LPVOID lpReserved);
extern "C"
BOOL WINAPI DllMain(HINSTANCE, DWORD fdwReason, LPVOID lpReserved)
{
if (fdwReason == DLL_THREAD_DETACH || fdwReason == DLL_PROCESS_DETACH)
{
if (lpReserved != NULL) // called after ExitProcess() call
{
//printf("OpenCV: terminating: " OPENCV_MODULE_S "\n");
cv::__termination = true;
}
}
return TRUE;
}
| [
"[email protected]"
] | |
2cfb3c1c8f05b8311a0146a621e02c1a69804890 | 7b20ec08c98b7aaf7096533df014692cc61242ec | /11-container-with-most-water/11-container-with-most-water.cpp | 3e3ea533752a2106bf6dd6bb60259d9f2ca6ca42 | [] | no_license | hareeshreddi/Algorithms-Famous-Questions | 2e5d5805a4bd0b6f095bac5ff1834039d177dcc5 | 53625a6b07614f58dc2fe37300a004e87bcbd9a3 | refs/heads/master | 2022-05-19T10:39:47.638272 | 2022-04-05T03:54:34 | 2022-04-05T03:54:34 | 84,583,427 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 296 | cpp | class Solution {
public:
int maxArea(vector<int>& height) {
int ans=0,i=0,j=height.size()-1;
while(i<j){
if(height[i]<height[j])
ans=max((j-i)*height[i++],ans);
else ans=max((j-i)*height[j--],ans);
}
return ans;
}
}; | [
"[email protected]"
] | |
5f30ad1a8015785ec5653359fb6abb4a695fa300 | 26d3688d1839717de6edec3aa6fa60fb1fe3483d | /external/boost_1_60_0/qsboost/phoenix/core/detail/preprocessed/call.hpp | a6f68b9b4e22d36d8203e895d99b931009b742aa | [
"MIT"
] | permissive | wouterboomsma/quickstep | 7d91c8070dca9f0d1d5ac30a38a9e159224a5e13 | a33447562eca1350c626883f21c68125bd9f776c | refs/heads/master | 2021-01-22T19:25:45.689105 | 2017-04-19T09:25:23 | 2017-04-19T09:25:23 | 88,726,115 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,025 | hpp | /*==============================================================================
Copyright (c) 2011 Hartmut Kaiser
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#if !defined(QSBOOST_PHOENIX_PREPROCESSED_CALL)
#define QSBOOST_PHOENIX_PREPROCESSED_CALL
#if QSBOOST_PHOENIX_LIMIT <= 10
#include <qsboost/phoenix/core/detail/preprocessed/call_10.hpp>
#elif QSBOOST_PHOENIX_LIMIT <= 20
#include <qsboost/phoenix/core/detail/preprocessed/call_20.hpp>
#elif QSBOOST_PHOENIX_LIMIT <= 30
#include <qsboost/phoenix/core/detail/preprocessed/call_30.hpp>
#elif QSBOOST_PHOENIX_LIMIT <= 40
#include <qsboost/phoenix/core/detail/preprocessed/call_40.hpp>
#elif QSBOOST_PHOENIX_LIMIT <= 50
#include <qsboost/phoenix/core/detail/preprocessed/call_50.hpp>
#else
#error "BOOST_PHOENIX_LIMIT out of bounds for preprocessed headers"
#endif
#endif
| [
"[email protected]"
] | |
e75c74d9571fe77317f11dc4d276bb5b22ac21ce | f82a47fb66163fd9ab83ff5e9f4f5ef4e52171c7 | /src/main/native/periDevice/I2CCtrl.cpp | 4283e134484caa77027c6e0206b35596206fe210 | [] | no_license | ruby-github/09001color | ffc4afc30a187bcbb5528bd0143976840909d489 | 0c637efced23df8dfde1b0a97d61b51cac0a10a0 | refs/heads/master | 2021-01-18T03:31:19.785131 | 2017-04-01T10:28:03 | 2017-04-01T10:28:03 | 85,908,115 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,868 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <linux/i2c.h>
#include <linux/i2c-dev.h>
#include "Def.h"
#include "periDevice/I2CCtrl.h"
I2CInterface::I2CInterface() {
m_fd = open("/dev/i2c-1",O_RDWR);
if (m_fd < 0) {
PRINTF("open i2c device fail\n");
}
}
I2CInterface::~I2CInterface() {
if ( m_fd >= 0 )
close(m_fd);
}
int I2CInterface::I2CWrite( unsigned char addr, int len ,unsigned char buf[]) {
int ret;
struct i2c_rdwr_ioctl_data ioctl_data;
ioctl_data.nmsgs = 1 ;
ioctl_data.msgs = (struct i2c_msg *)malloc(ioctl_data.nmsgs * sizeof(ioctl_data.msgs));
if (ioctl_data.msgs == NULL) {
PRINTF("malloc mem fail\n");
return -1;;
}
ioctl_data.msgs[0].addr = addr;
ioctl_data.msgs[0].flags = 0;//read_write
ioctl_data.msgs[0].len = len + 1;
ioctl_data.msgs[0].buf = buf;
ret = ioctl(m_fd, I2C_RDWR, (unsigned long)&ioctl_data);
//free(ioctl_data.msgs);
return ret;
}
int I2CInterface::I2CRead( unsigned char addr, unsigned char reg, int len, unsigned char buffer[]) {
int ret;
struct i2c_rdwr_ioctl_data ioctl_data;
struct i2c_msg msgs[2];
unsigned char tmp_reg = reg;
ioctl_data.nmsgs = 2 ;
ioctl_data.msgs = msgs;
ioctl_data.msgs[0].addr = addr;
ioctl_data.msgs[0].flags = 0;//read_write
ioctl_data.msgs[0].len = 1;
ioctl_data.msgs[0].buf = &tmp_reg;
//ioctl_data.msgs[0].buf = (unsigned char*)malloc(1);
//ioctl_data.msgs[0].buf[0] = reg;
ioctl_data.msgs[1].addr = addr;
ioctl_data.msgs[1].flags = I2C_M_RD;//read_write
ioctl_data.msgs[1].len = 1;
ioctl_data.msgs[1].buf = buffer;
ret = ioctl(m_fd, I2C_RDWR, (unsigned long)&ioctl_data);
//free(ioctl_data.msgs[0].buf);
//free(ioctl_data.msgs);
return ret;
}
| [
"[email protected]"
] | |
e3c602d3098b8477975d1bfd7991fda1c45fab8f | 1a93a3b56dc2d54ffe3ee344716654888b0af777 | /env/Library/include/qt/QtDesigner/5.12.9/QtDesigner/private/layout_p.h | 2b97fb8232e7deee7d5033a60ee17b4429d0247a | [
"Python-2.0",
"LicenseRef-scancode-python-cwi",
"GPL-1.0-or-later",
"LicenseRef-scancode-other-copyleft",
"BSD-3-Clause",
"0BSD",
"LicenseRef-scancode-free-unknown",
"GPL-3.0-only",
"GPL-2.0-only"
] | permissive | h4vlik/TF2_OD_BRE | ecdf6b49b0016407007a1a049f0fdb952d58cbac | 54643b6e8e9d76847329b1dbda69efa1c7ae3e72 | refs/heads/master | 2023-04-09T16:05:27.658169 | 2021-02-22T14:59:07 | 2021-02-22T14:59:07 | 327,001,911 | 0 | 0 | BSD-3-Clause | 2021-02-22T14:59:08 | 2021-01-05T13:08:03 | null | UTF-8 | C++ | false | false | 4,156 | h | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt Designer of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
//
// W A R N I N G
// -------------
//
// This file is not part of the Qt API. It exists for the convenience
// of Qt Designer. This header
// file may change from version to version without notice, or even be removed.
//
// We mean it.
//
#ifndef LAYOUT_H
#define LAYOUT_H
#include "shared_global_p.h"
#include "layoutinfo_p.h"
#include <QtCore/qpointer.h>
#include <QtCore/qobject.h>
#include <QtCore/qmap.h>
#include <QtCore/qhash.h>
#include <QtWidgets/qlayout.h>
#include <QtWidgets/qgridlayout.h>
#include <QtWidgets/qwidget.h>
QT_BEGIN_NAMESPACE
class QDesignerFormWindowInterface;
namespace qdesigner_internal {
class QDESIGNER_SHARED_EXPORT Layout : public QObject
{
Q_OBJECT
Q_DISABLE_COPY(Layout)
protected:
Layout(const QWidgetList &wl, QWidget *p, QDesignerFormWindowInterface *fw, QWidget *lb, LayoutInfo::Type layoutType);
public:
static Layout* createLayout(const QWidgetList &widgets, QWidget *parentWidget,
QDesignerFormWindowInterface *fw,
QWidget *layoutBase, LayoutInfo::Type layoutType);
~Layout() override;
virtual void sort() = 0;
virtual void doLayout() = 0;
virtual void setup();
virtual void undoLayout();
virtual void breakLayout();
const QWidgetList &widgets() const { return m_widgets; }
QWidget *parentWidget() const { return m_parentWidget; }
QWidget *layoutBaseWidget() const { return m_layoutBase; }
/* Determines whether instances of QLayoutWidget are unmanaged/hidden
* after breaking a layout. Default is true. Can be turned off when
* morphing */
bool reparentLayoutWidget() const { return m_reparentLayoutWidget; }
void setReparentLayoutWidget(bool v) { m_reparentLayoutWidget = v; }
protected:
virtual void finishLayout(bool needMove, QLayout *layout = 0);
virtual bool prepareLayout(bool &needMove, bool &needReparent);
void setWidgets(const QWidgetList &widgets) { m_widgets = widgets; }
QLayout *createLayout(int type);
void reparentToLayoutBase(QWidget *w);
private slots:
void widgetDestroyed();
private:
QWidgetList m_widgets;
QWidget *m_parentWidget;
typedef QHash<QWidget *, QRect> WidgetGeometryHash;
WidgetGeometryHash m_geometries;
QWidget *m_layoutBase;
QDesignerFormWindowInterface *m_formWindow;
const LayoutInfo::Type m_layoutType;
QPoint m_startPoint;
QRect m_oldGeometry;
bool m_reparentLayoutWidget;
const bool m_isBreak;
};
namespace Utils
{
inline int indexOfWidget(QLayout *layout, QWidget *widget)
{
int index = 0;
while (QLayoutItem *item = layout->itemAt(index)) {
if (item->widget() == widget)
return index;
++index;
}
return -1;
}
} // namespace Utils
} // namespace qdesigner_internal
QT_END_NAMESPACE
#endif // LAYOUT_H
| [
"[email protected]"
] | |
9223d1fb91801260f17e905720531982acfeca5c | 712f44b319108bb540629ced364ad70b463f456a | /TP1/metodos.h | 32419d5a3b30a1c99c76b88fda9b21e826f5ad84 | [] | no_license | sizcovich/TPs-MetodosNumericos | e03325b2a4ac4f37dbdda3210d9b8beee189a09a | a21ef1a7604813360af92d8edb2ce6f19cfae796 | refs/heads/master | 2020-05-18T05:05:21.150553 | 2015-03-02T00:45:30 | 2015-03-02T00:45:30 | 29,919,702 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 950 | h | #ifndef METODOS_
#define METODOS_
#include <cmath>
#include <iostream>
#include <list>
#include "formulas.h"
#include "TFloat.h"
using namespace std;
/*tipoError
* 1 => |f(c)|< error
* 2 => |an - an-1|< error
* 3 => |an - an-1|/|an-1| < error
* 4 => |f(an) - f(an-1)| < error
* 5 => |f(an) - f(an-1)|/|f(an-1)|< error
*/
TFloat newton(int n, list<double>::iterator m, size_t precision, double error, TFloat p0, int tipoError, int maxIteraciones, int *iteracionesQRealiza, double *errorFinal, float *tiempo);
TFloat secante(int n, list<double>::iterator m, size_t precision, double error, TFloat p0, TFloat p1, int tipoError, int maxIteraciones, int *iteracionesQRealiza, double *errorFinal, float *tiempo);
TFloat biseccion(int n, list<double>::iterator m, size_t precision, double error, TFloat a, TFloat b, int tipoError, int maxIteraciones, int *iteracionesQRealiza, double *errorFinal, float *tiempo, TFloat *c2, bool sacarC2);
#endif
| [
"[email protected]"
] | |
2844ac4cc42222f410f9098ca864bb9d74080769 | 0fecb324be8e41cf324c58c0c5c3600976706a27 | /src/qt/bitcoinaddressvalidator.cpp | 15aa74113e4dd2eef3ce4c6a4c41468c43a3990f | [
"MIT"
] | permissive | Stogniev/Tarraf | e0598392cf2ffcdd73dc4457524aac0aa706fc4a | ace0c284a3bbb54a16d7bf3fc9764ea4dc462e91 | refs/heads/master | 2020-03-08T03:03:54.041721 | 2018-08-06T07:23:59 | 2018-08-06T07:23:59 | 126,369,916 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,649 | cpp | // Copyright (c) 2011-2014 The Bitcoin Core developers
// Copyright (c) 2014-2017 The TRF Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoinaddressvalidator.h"
#include "base58.h"
/* Base58 characters are:
"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
This is:
- All numbers except for '0'
- All upper-case letters except for 'I' and 'O'
- All lower-case letters except for 'l'
*/
BitcoinAddressEntryValidator::BitcoinAddressEntryValidator(QObject *parent) :
QValidator(parent)
{
}
QValidator::State BitcoinAddressEntryValidator::validate(QString &input, int &pos) const
{
Q_UNUSED(pos);
// Empty address is "intermediate" input
if (input.isEmpty())
return QValidator::Intermediate;
// Correction
for (int idx = 0; idx < input.size();)
{
bool removeChar = false;
QChar ch = input.at(idx);
// Corrections made are very conservative on purpose, to avoid
// users unexpectedly getting away with typos that would normally
// be detected, and thus sending to the wrong address.
switch(ch.unicode())
{
// Qt categorizes these as "Other_Format" not "Separator_Space"
case 0x200B: // ZERO WIDTH SPACE
case 0xFEFF: // ZERO WIDTH NO-BREAK SPACE
removeChar = true;
break;
default:
break;
}
// Remove whitespace
if (ch.isSpace())
removeChar = true;
// To next character
if (removeChar)
input.remove(idx, 1);
else
++idx;
}
// Validation
QValidator::State state = QValidator::Acceptable;
for (int idx = 0; idx < input.size(); ++idx)
{
int ch = input.at(idx).unicode();
if (((ch >= '0' && ch<='9') ||
(ch >= 'a' && ch<='z') ||
(ch >= 'A' && ch<='Z')) &&
ch != 'l' && ch != 'I' && ch != '0' && ch != 'O')
{
// Alphanumeric and not a 'forbidden' character
}
else
{
state = QValidator::Invalid;
}
}
return state;
}
BitcoinAddressCheckValidator::BitcoinAddressCheckValidator(QObject *parent) :
QValidator(parent)
{
}
QValidator::State BitcoinAddressCheckValidator::validate(QString &input, int &pos) const
{
Q_UNUSED(pos);
// Validate the passed TRF address
CBitcoinAddress addr(input.toStdString());
if (addr.IsValid())
return QValidator::Acceptable;
return QValidator::Invalid;
}
| [
"[email protected]"
] | |
e1e61c792f116719719d459ceb2cec04d462815f | 515d821349bc0cbf72f3d252b9dda42d36033bd3 | /_2_Sensor_to_LCD/_2_Sensor_to_LCD.ino | c655b8a8bf50538a6d472e14cc515564bd4d3049 | [] | no_license | kalopilato/healthy-home-sensor | a356f09bdfdbfda6ff132b89c11621c12e737b2a | 88a8c782288521dbf447ef03273f2b9857500a28 | refs/heads/master | 2021-03-27T16:14:58.496595 | 2016-02-08T09:32:10 | 2016-02-08T09:32:10 | 51,289,430 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,914 | ino | // Example testing sketch for various DHT humidity/temperature sensors
// Written by ladyada, public domain
#include "DHT.h"
#include <LiquidCrystal.h>
#define DHTPIN1 8 // what pin we're connected to
#define DHTPIN2 9 // what pin we're connected to
// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(7, 6, 5, 4, 3, 2);
// Uncomment whatever type you're using!
//#define DHTTYPE DHT11 // DHT 11
#define DHTTYPE DHT22 // DHT 22 (AM2302)
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
DHT dht1(DHTPIN1, DHTTYPE);
DHT dht2(DHTPIN2, DHTTYPE);
void setup() {
// set up the LCD's number of columns and rows:
lcd.begin(16, 2);
// set up DHT22 sensor;
dht1.begin();
dht2.begin();
}
void loop() {
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h1 = dht1.readHumidity();
float t1 = dht1.readTemperature();
float h2 = dht2.readHumidity();
float t2 = dht2.readTemperature();
lcd.clear();
lcd.print("Temp: Humidity:");
// check if returns are valid, if they are NaN (not a number) then something went wrong!
lcd.setCursor(0, 1);
if (isnan(t1) || isnan(h1)) {
lcd.print("Failed to read from DHT");
} else {
lcd.print(t1, 1);
lcd.print("C");
lcd.setCursor(7, 1);
lcd.print(h1, 1);
lcd.print("%");
lcd.setCursor(14, 1);
lcd.print("S1");
delay(2000);
}
lcd.clear();
lcd.print("Temp: Humidity:");
// check if returns are valid, if they are NaN (not a number) then something went wrong!
lcd.setCursor(0, 1);
if (isnan(t2) || isnan(h2)) {
lcd.print("Failed to read from DHT");
} else {
lcd.print(t2, 1);
lcd.print("C");
lcd.setCursor(7, 1);
lcd.print(h2, 1);
lcd.print("%");
lcd.setCursor(14, 1);
lcd.print("S2");
delay(1100);
}
}
| [
"[email protected]"
] | |
bf401bff190460f83dda4cd7a189b41b71553b9c | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_patch_hunk_2059.cpp | 4e91a6d98385142d6fd680b28864a8b8b1506a5d | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,152 | cpp | ap_log_error(APLOG_MARK, APLOG_DEBUG, status, r->server,
"proxy: APR_BUCKET_IS_EOS");
} else {
status = ap_get_brigade(r->input_filters, input_brigade,
AP_MODE_READBYTES,
APR_BLOCK_READ,
- AJP13_MAX_SEND_BODY_SZ);
+ maxsize - AJP_HEADER_SZ);
if (status != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_DEBUG, status,
r->server,
"ap_get_brigade failed");
+ output_failed = 1;
break;
}
- bufsiz = AJP13_MAX_SEND_BODY_SZ;
+ bufsiz = maxsize;
status = apr_brigade_flatten(input_brigade, buff,
&bufsiz);
apr_brigade_cleanup(input_brigade);
if (status != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_DEBUG, status,
r->server,
"apr_brigade_flatten failed");
+ output_failed = 1;
break;
}
}
ajp_msg_reset(msg);
/* will go in ajp_send_data_msg */
status = ajp_send_data_msg(conn->sock, msg, bufsiz);
if (status != APR_SUCCESS) {
ap_log_error(APLOG_MARK, APLOG_DEBUG, status, r->server,
"ajp_send_data_msg failed");
+ backend_failed = 1;
break;
}
conn->worker->s->transferred += bufsiz;
} else {
/*
* something is wrong TC asks for more body but we are
* already at the end of the body data
*/
ap_log_error(APLOG_MARK, APLOG_DEBUG, 0, r->server,
"ap_proxy_ajp_request error read after end");
- isok = 0;
+ backend_failed = 1;
}
break;
case CMD_AJP13_SEND_HEADERS:
/* AJP13_SEND_HEADERS: process them */
status = ajp_parse_header(r, conf, conn->data);
if (status != APR_SUCCESS) {
- isok = 0;
+ backend_failed = 1;
}
break;
case CMD_AJP13_SEND_BODY_CHUNK:
/* AJP13_SEND_BODY_CHUNK: piece of data */
status = ajp_parse_data(r, conn->data, &size, &buff);
if (status == APR_SUCCESS) {
| [
"[email protected]"
] | |
31418248041604633a83ef0e5cf7358f51b4882a | 691d74ae7d6b6769fead7d2a95f94b8453a4acd2 | /Learn Advanced C++ Programming/Passing Functions to Functions/Functors/Functors.cpp | f0228611f2b3cc5721fea8876f36a245f5c99d30 | [] | no_license | karlit0/Learn-Advanced-C-Programming---John-Purcell | fc91dc95e87b6fd318b2d60b8e148b00c40a410a | 3319810e2207e127182619015675df8b19b8fc14 | refs/heads/master | 2023-01-20T04:32:20.584933 | 2020-11-25T19:44:41 | 2020-11-25T19:44:41 | 305,679,747 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 465 | cpp | #include <iostream>
using namespace std;
struct Test
{
virtual bool operator()(string& Text) = 0;
};
struct MatchTest : public Test
{
virtual bool operator()(string& Text) override
{
return Text == "lion";
}
};
void Check(string Text, Test& test)
{
if (test(Text))
{
cout << "Text matches!" << endl;
}
else
{
cout << "No match." << endl;
}
}
int main()
{
MatchTest Pred;
string Value = "lion";
MatchTest m;
Check("lion", m);
return 0;
} | [
"[email protected]"
] | |
a4587d4ccf6064446d438535d1aad2ddf33ceeaa | 84c9664add913cbd7b64dbcff85b5fb44513d9b4 | /src/spork.h | b5468c57ab2c96050e199256eef25abf5f069cd7 | [
"MIT"
] | permissive | NaniteCurrency/Nanite | cbf3affcb44f1f0475052670049a3e5bef7a2ad9 | f30178931f922d088e5317f95522dfdf02c02116 | refs/heads/master | 2021-04-06T01:54:59.218615 | 2018-04-27T07:39:29 | 2018-04-27T07:39:29 | 125,361,873 | 0 | 2 | MIT | 2018-04-10T22:14:18 | 2018-03-15T12:09:36 | C++ | UTF-8 | C++ | false | false | 3,784 | h | // Copyright (c) 2014-2016 The Dash developers
// Copyright (c) 2016-2017 The NANITE developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef SPORK_H
#define SPORK_H
#include "base58.h"
#include "key.h"
#include "main.h"
#include "net.h"
#include "sync.h"
#include "util.h"
#include "crypto/hashx17.h"
#include "obfuscation.h"
#include "protocol.h"
#include <boost/lexical_cast.hpp>
using namespace std;
using namespace boost;
/*
Don't ever reuse these IDs for other sporks
- This would result in old clients getting confused about which spork is for what
Sporks 11,12, and 16 to be removed with 1st zerocoin release
*/
#define SPORK_START 10001
#define SPORK_END 10015
#define SPORK_2_SWIFTTX 10001
#define SPORK_3_SWIFTTX_BLOCK_FILTERING 10002
#define SPORK_5_MAX_VALUE 10004
#define SPORK_7_MASTERNODE_SCANNING 10006
#define SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT 10007
#define SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT 10008
#define SPORK_10_MASTERNODE_PAY_UPDATED_NODES 10009
//#define SPORK_11_LOCK_INVALID_UTXO 10010
//#define SPORK_12_RECONSIDER_BLOCKS 10011
#define SPORK_13_ENABLE_SUPERBLOCKS 10012
#define SPORK_14_NEW_PROTOCOL_ENFORCEMENT 10013
#define SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2 10014
#define SPORK_16_ZEROCOIN_MAINTENANCE_MODE 10015
#define SPORK_2_SWIFTTX_DEFAULT 978307200 //2001-1-1
#define SPORK_3_SWIFTTX_BLOCK_FILTERING_DEFAULT 1424217600 //2015-2-18
#define SPORK_5_MAX_VALUE_DEFAULT 1000 //1000 NTT
#define SPORK_7_MASTERNODE_SCANNING_DEFAULT 978307200 //2001-1-1
#define SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT_DEFAULT 4070908800 //OFF
#define SPORK_9_MASTERNODE_BUDGET_ENFORCEMENT_DEFAULT 4070908800 //OFF
#define SPORK_10_MASTERNODE_PAY_UPDATED_NODES_DEFAULT 4070908800 //OFF
//#define SPORK_11_LOCK_INVALID_UTXO_DEFAULT 4070908800 //OFF - NOTE: this is block height not time!
#define SPORK_13_ENABLE_SUPERBLOCKS_DEFAULT 4070908800 //OFF
#define SPORK_14_NEW_PROTOCOL_ENFORCEMENT_DEFAULT 4070908800 //OFF
#define SPORK_15_NEW_PROTOCOL_ENFORCEMENT_2_DEFAULT 4070908800 //OFF
#define SPORK_16_ZEROCOIN_MAINTENANCE_MODE_DEFAULT 4070908800 //OFF
class CSporkMessage;
class CSporkManager;
extern std::map<uint256, CSporkMessage> mapSporks;
extern std::map<int, CSporkMessage> mapSporksActive;
extern CSporkManager sporkManager;
void LoadSporksFromDB();
void ProcessSpork(CNode* pfrom, std::string& strCommand, CDataStream& vRecv);
int64_t GetSporkValue(int nSporkID);
bool IsSporkActive(int nSporkID);
void ReprocessBlocks(int nBlocks);
//
// Spork Class
// Keeps track of all of the network spork settings
//
class CSporkMessage
{
public:
std::vector<unsigned char> vchSig;
int nSporkID;
int64_t nValue;
int64_t nTimeSigned;
uint256 GetHash()
{
uint256 n = HashX17(BEGIN(nSporkID), END(nTimeSigned));
return n;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(nSporkID);
READWRITE(nValue);
READWRITE(nTimeSigned);
READWRITE(vchSig);
}
};
class CSporkManager
{
private:
std::vector<unsigned char> vchSig;
std::string strMasterPrivKey;
public:
CSporkManager()
{
}
std::string GetSporkNameByID(int id);
int GetSporkIDByName(std::string strName);
bool UpdateSpork(int nSporkID, int64_t nValue);
bool SetPrivKey(std::string strPrivKey);
bool CheckSignature(CSporkMessage& spork);
bool Sign(CSporkMessage& spork);
void Relay(CSporkMessage& msg);
};
#endif
| [
"[email protected]"
] | |
65416b1514d97359f707ff1e10b99f97c7c93b0b | 95c743ec9826ef301028797795214a306031a352 | / cf-B - Saving the City.cpp | aea5d6a88a534fbf245685a60c3d0c8f590d0334 | [] | no_license | kkb-10/Code-Library | eb776ffe0293cb757f4f35753a733c9916794f0d | b1651832057b3f3af11b4b6b6a20812aca761e90 | refs/heads/master | 2023-08-25T02:47:05.081479 | 2021-10-19T17:31:31 | 2021-10-19T17:31:31 | 358,805,482 | 0 | 1 | null | 2021-10-19T17:31:32 | 2021-04-17T06:42:43 | C++ | UTF-8 | C++ | false | false | 1,809 | cpp | #include<bits/stdc++.h>
using namespace std;
#define fastIO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define ll long long int
#define fi first
#define se second
#define pb push_back
#define pi pair<int,int>
#define all(v) (v).begin(), (v).end()
#define rep(i, l, r) for(int i=(int)(l);i<(int)(r);i++)
#define repd(i, l, r) for (int i=(int)(l);i>=(int)(r);i--)
#define clrg(i, l, r) for(int i=(int)(l);i<(int)(r);i++)vis[i]=0,v[i].clear();
ll power(ll x, unsigned ll y){ll res = 1;while (y > 0){ if (y & 1){res = res*x;} y = y>>1;x = x*x;}return res;}
int powermod(int x, unsigned int y, int p){int res = 1;x = x % p;while (y > 0){if (y & 1){res = (res*x) % p;}y = y>>1; x = (x*x) % p;}return res;}
#define print2d(mat,n,m){for(int i=0;i<(int)(n);i++){for(int j=0;j<(m);j++){cout<<mat[i][j]<<" ";}cout<< endl;}}
#define clr(a,x) memset(a,x,sizeof(a))
#define rr(v) for(auto &val:v)
#define print(v) for (const auto itr : v){cout<<itr<<' ';}cout<<"\n";
#define ln length()
#define sz size()
#define mod 1000000007
#define elif else if
#define INF 99999999
int32_t main()
{
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
fastIO;
ll t,n,q,i,j,a,b,c,d,x,k,m,r,w,l,p;
cin>>t;
//t=1;
while(t--)
{
cin>>a>>b;
string s;
cin>>s;
ll f=0;
ll pehla=0;
ll segments=0;
vector <ll> v;
ll zeros=0;
for(i=0;i<s.size();i++)
{
if(s[i]=='1')
{
pehla=1;
if(f==0)
{
f=1;
if(zeros!=0)
{
v.pb(zeros);
}
zeros=0;
segments++;
}
}
else
{
f=0;
if(pehla==1)
{
zeros++;
}
}
}
sort(all(v));
ll ans=segments*a;
ll p=ans;
for(auto it:v)
{
p=p-a+it*b;
ans=min(ans,p);
}
cout<<ans<<endl;
}
return 0;
} | [
"[email protected]"
] | |
05bd01c2d24182e60a0a529e4cb795a9a3031b5e | a7266159d1324e0012dfeab5126c9e945880f3ec | /LearningOpenGL/LearningOpenGL/main.cpp | a2871a321c27b273d4b7dc210555845b64963411 | [] | no_license | Drakon0168/OpenGL | cb91c416bbfc3d6a5356cafa0a925e5ddd13a4ab | cdc1bb057bc0d2db01b3682a23a91d7c2d3cf8d0 | refs/heads/master | 2020-05-09T12:11:12.266158 | 2019-04-25T19:28:12 | 2019-04-25T19:28:12 | 166,296,356 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,553 | cpp | #include "pch.h"
#include "Helper.h"
#include "Point2D.h"
#include "Point3D.h"
#include "loadShader.h"
//typedef basic_ios<char> ios;
//Following a Tutorial, http://www.opengl-tutorial.org/beginners-tutorials/
int main()
{
vector<Point3D> triangle;
triangle.push_back(Point3D(0, 0.5, 0));
triangle.push_back(Point3D(-0.5, -0.5, 0));
triangle.push_back(Point3D(0.5, -0.5, 0));
glewExperimental = true;
if (!glfwInit()) {
cout << "Failed to initialize GLFW" << endl;
return -1;
}
glfwWindowHint(GLFW_SAMPLES, 4); // 4x antialiasing
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // We want OpenGL 3.3
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // We don't want the old OpenGL
GLFWwindow* window;
window = glfwCreateWindow(1024, 768, "Learning OpenGL", NULL, NULL);
if (window == NULL) {
cout << "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials." << endl;
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
glewExperimental = true;
if (glewInit() != GLEW_OK) {
cout << "Failed to initialize GLEW" << endl;
return -1;
}
//Set up the triangle
GLuint VertexArrayID;
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
//Set the points
GLfloat g_vertex_buffer_data[] = {
triangle[0].x, triangle[0].y, triangle[0].z,
triangle[1].x, triangle[1].y, triangle[1].z,
triangle[2].x, triangle[2].y, triangle[2].z,
};
//Setup the buffer
GLuint vertexbuffer;
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data), g_vertex_buffer_data, GL_STATIC_DRAW);
glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);
GLuint programID = LoadShaders("SimpleVertexShader.vertexshader", "SimpleFragmentShader.fragmentshader");
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
do {
//Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(programID);
//Draw
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);
//Swap buffers
glfwSwapBuffers(window);
glfwPollEvents();
} while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS && glfwWindowShouldClose(window) == 0);
} | [
"[email protected]"
] | |
845af8d078ff1e45d6621617017d20730eb5858b | 348a12c66a5e18d11813936f89256ca32a892f6e | /models/channleadapter.h | 75512026790e2dd61ae76f1c36c03c394d61253d | [] | no_license | fassnacht/LivePad | 7d6076facd3516ee0c419163d97bf05c06c2b2e7 | b6a24c3aab8f6f5ea999bd770f4b2502a8fcd2e5 | refs/heads/master | 2020-05-21T16:44:48.348504 | 2016-09-24T22:05:09 | 2016-09-24T22:05:09 | 63,352,247 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 960 | h | #ifndef CHANNLEADAPTER_H
#define CHANNLEADAPTER_H
#include "bases/ListModelBase.h"
#include "channleitem.h"
class ChannleAdapter : public ListModelBase<ChannleItem>
{
Q_OBJECT
Q_PROPERTY(QStringList colorGroups READ colorGroups NOTIFY colorGroupsChanged)
public:
explicit ChannleAdapter(QObject *parent = 0);
enum Roles
{
Name,
Groups,
SendLevel,
Level,
Mute,
Solo,
Record,
Selected,
Pan,
Color,
Midi,
ChannleNumber
};
QVariant data(const QModelIndex &index, int role) const;
QHash<int, QByteArray> roleNames() const;
Q_INVOKABLE int count() const;
QStringList colorGroups() const;
void setColorGroups(const QStringList &colorGroups);
void clearAdapter();
private:
QHash<int, QByteArray> _roles;
QStringList _colorGroups;
signals:
void colorGroupsChanged();
};
#endif // CHANNLEADAPTER_H
| [
"[email protected]"
] | |
b72b2c37613bd448e2574789f7b2f9b59b42998e | 9dac8aa93b8dfca0aecbff4402fa67a99d051d9a | /Hemsleya/base/async_net/writebuff.h | ee8d7161336d8c7d8e6a2a4e1bfd9abe52789863 | [
"MIT"
] | permissive | qianqians/discard | 8678d62ae17850ff1f451a9487688df22eff1bec | d746c2550e967359d249748a737feaa29e9a3c3b | refs/heads/master | 2023-04-13T16:23:34.683015 | 2023-03-30T08:06:56 | 2023-03-30T08:06:56 | 88,745,277 | 2 | 2 | null | 2022-09-27T08:52:29 | 2017-04-19T12:56:33 | Python | UTF-8 | C++ | false | false | 1,157 | h | /*
* writebuff.h
* Created on: 2013-10-2
* Author: qianqians
* async_service
*/
#ifndef _WRITEBUFF_H
#define _WRITEBUFF_H
#include "buffstruct.h"
#include <boost/thread.hpp>
#include <Hemsleya/base/concurrent/abstract_factory/abstract_factory.h>
namespace Hemsleya {
namespace async_net {
class writebuff{
public:
writebuff();
~writebuff();
int write(char * buf, uint32_t len, boost::function<void(const std::vector<buffstruct> * const buff)> fn);
void freebuff(char * buff, uint32_t buflen);
private:
struct writebuffstruct{
writebuffstruct(){
buff = 0;
len = 0;
max = 0;
}
char * buff;
uint32_t len;
uint32_t max;
};
struct buflist{
std::vector<writebuffstruct> * buf;
buflist * next;
};
struct _buff{
char buff[65536];
};
private:
boost::shared_mutex _mutex;
boost::thread_specific_ptr<std::vector<writebuffstruct> > tss_buff;
boost::atomic<buflist*> _list;
abstract_factory::abstract_factory<_buff > _abstract_factory_buff;
abstract_factory::abstract_factory<std::vector<writebuffstruct> > _abstract_factory_vector_buffstruct;
};
} //async_net
} //Hemsleya
#endif //_WRITEBUFF_H
| [
"[email protected]"
] | |
57c91dab3cdc893ebef18896fa5b37632894b1aa | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir7941/dir7942/dir8062/dir8063/dir12766/dir12767/dir13029/dir15097/dir15260/dir15321/dir17628/file17634.cpp | b84aa9693741c62396b94e0120e8da73681cc9a7 | [] | no_license | tgeng/HugeProject | 829c3bdfb7cbaf57727c41263212d4a67e3eb93d | 4488d3b765e8827636ce5e878baacdf388710ef2 | refs/heads/master | 2022-08-21T16:58:54.161627 | 2020-05-28T01:54:03 | 2020-05-28T01:54:03 | 267,468,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | #ifndef file17634
#error "macro file17634 must be defined"
#endif
static const char* file17634String = "file17634"; | [
"[email protected]"
] | |
ebf5ee86ccad51162176c45d9a652112dbc12326 | 75933a7ef9c77ffb3a06a1cecde79205c2b327ab | /util/test/demos/vk/vk_shader_isa.cpp | 45c523e978ef2fd550c472ba3169b77aebbdb883 | [
"BSD-3-Clause",
"MIT",
"Apache-2.0",
"CC-BY-3.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | gvvynplaine/renderdoc | 983aac678006942e938aa9599cc4d58b48e04e21 | efafd0b766ea88b8563c7911dd111cbd0c6ffd65 | refs/heads/v1.x | 2023-01-01T19:32:13.183376 | 2020-07-07T14:40:55 | 2020-07-07T17:15:09 | 278,307,900 | 0 | 0 | MIT | 2020-10-30T12:17:30 | 2020-07-09T08:30:17 | null | UTF-8 | C++ | false | false | 5,454 | cpp | /******************************************************************************
* The MIT License (MIT)
*
* Copyright (c) 2019-2020 Baldur Karlsson
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
******************************************************************************/
#include "vk_test.h"
RD_TEST(VK_Shader_ISA, VulkanGraphicsTest)
{
static constexpr const char *Description =
"Draws a simple triangle with markers indicating which types of shader ISA we expect to be "
"available (i.e. running on AMD or not)";
std::string common = R"EOSHADER(
#version 420 core
struct v2f
{
vec4 pos;
vec4 col;
vec4 uv;
};
)EOSHADER";
const std::string vertex = R"EOSHADER(
layout(location = 0) in vec3 Position;
layout(location = 1) in vec4 Color;
layout(location = 2) in vec2 UV;
layout(location = 0) out v2f vertOut;
void main()
{
vertOut.pos = vec4(Position.xyz*vec3(1,-1,1), 1);
gl_Position = vertOut.pos;
vertOut.col = Color;
vertOut.uv = vec4(UV.xy, 0, 1);
}
)EOSHADER";
const std::string pixel = R"EOSHADER(
layout(location = 0) in v2f vertIn;
layout(location = 0, index = 0) out vec4 Color;
void main()
{
Color = vertIn.col;
}
)EOSHADER";
int main()
{
// initialise, create window, create context, etc
if(!Init())
return 3;
VkPipelineLayout layout = createPipelineLayout(vkh::PipelineLayoutCreateInfo());
vkh::GraphicsPipelineCreateInfo pipeCreateInfo;
pipeCreateInfo.layout = layout;
pipeCreateInfo.renderPass = mainWindow->rp;
pipeCreateInfo.vertexInputState.vertexBindingDescriptions = {vkh::vertexBind(0, DefaultA2V)};
pipeCreateInfo.vertexInputState.vertexAttributeDescriptions = {
vkh::vertexAttr(0, 0, DefaultA2V, pos), vkh::vertexAttr(1, 0, DefaultA2V, col),
vkh::vertexAttr(2, 0, DefaultA2V, uv),
};
pipeCreateInfo.stages = {
CompileShaderModule(common + vertex, ShaderLang::glsl, ShaderStage::vert, "main"),
CompileShaderModule(common + pixel, ShaderLang::glsl, ShaderStage::frag, "main"),
};
VkPipeline pipe = createGraphicsPipeline(pipeCreateInfo);
AllocatedBuffer vb(
this, vkh::BufferCreateInfo(sizeof(DefaultTri), VK_BUFFER_USAGE_VERTEX_BUFFER_BIT |
VK_BUFFER_USAGE_TRANSFER_DST_BIT),
VmaAllocationCreateInfo({0, VMA_MEMORY_USAGE_CPU_TO_GPU}));
vb.upload(DefaultTri);
AllocatedImage offimg(this, vkh::ImageCreateInfo(4, 4, 0, VK_FORMAT_R32G32B32A32_SFLOAT,
VK_IMAGE_USAGE_TRANSFER_DST_BIT),
VmaAllocationCreateInfo({0, VMA_MEMORY_USAGE_GPU_ONLY}));
while(Running())
{
VkCommandBuffer cmd = GetCommandBuffer();
vkBeginCommandBuffer(cmd, vkh::CommandBufferBeginInfo());
VkImage swapimg =
StartUsingBackbuffer(cmd, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_GENERAL);
vkCmdClearColorImage(cmd, swapimg, VK_IMAGE_LAYOUT_GENERAL,
vkh::ClearColorValue(0.2f, 0.2f, 0.2f, 1.0f), 1,
vkh::ImageSubresourceRange());
vkh::cmdPipelineBarrier(
cmd, {
vkh::ImageMemoryBarrier(0, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED,
VK_IMAGE_LAYOUT_GENERAL, offimg.image),
});
vkCmdClearColorImage(cmd, offimg.image, VK_IMAGE_LAYOUT_GENERAL,
vkh::ClearColorValue(0.2f, 0.2f, 0.2f, 1.0f), 1,
vkh::ImageSubresourceRange());
vkCmdBeginRenderPass(
cmd, vkh::RenderPassBeginInfo(mainWindow->rp, mainWindow->GetFB(), mainWindow->scissor),
VK_SUBPASS_CONTENTS_INLINE);
vkCmdBindPipeline(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, pipe);
vkCmdSetViewport(cmd, 0, 1, &mainWindow->viewport);
vkCmdSetScissor(cmd, 0, 1, &mainWindow->scissor);
vkh::cmdBindVertexBuffers(cmd, 0, {vb.buffer}, {0});
if(physProperties.vendorID == PCI_VENDOR_AMD)
setMarker(cmd, "GPU=AMD");
else
setMarker(cmd, "GPU=Other");
vkCmdDraw(cmd, 3, 1, 0, 0);
vkCmdEndRenderPass(cmd);
FinishUsingBackbuffer(cmd, VK_ACCESS_TRANSFER_WRITE_BIT, VK_IMAGE_LAYOUT_GENERAL);
vkEndCommandBuffer(cmd);
Submit(0, 1, {cmd});
Present();
}
return 0;
}
};
REGISTER_TEST();
| [
"[email protected]"
] | |
89aa7b57ab2773e7916f408c7e8024e15f311778 | 9c7a0296af07bf6c475f665fcccb855ccf7a526e | /core/modules/replica/SqlResultSet.cc | ed96046d6e53d1cf462410558dfb3faf0ee4f8cb | [] | no_license | provingground-moe/qserv | 6ecbf227442d335d26dc2238c5e4142a6ae2ea25 | 97016932a752c0e641571538912d309cd3dd461b | refs/heads/master | 2020-06-10T20:45:10.955752 | 2019-05-22T19:59:19 | 2019-05-22T19:59:19 | 136,348,562 | 0 | 0 | null | 2018-06-06T15:27:00 | 2018-06-06T15:26:59 | null | UTF-8 | C++ | false | false | 8,062 | cc | /*
* LSST Data Management System
*
* This product includes software developed by the
* LSST Project (http://www.lsst.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 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 LSST License Statement and
* the GNU General Public License along with this program. If not,
* see <http://www.lsstcorp.org/LegalNotices/>.
*/
// Class header
#include "replica/SqlResultSet.h"
// System headers
#include <stdexcept>
// Third party headers
#include <mysql/mysql.h>
using namespace std;
using json = nlohmann::json;
namespace {
/**
* Add a field to a JSON object
*/
template <typename T>
void addField(json& fieldsJson,
char const* name,
T const& value,
char const* description) {
fieldsJson[name]["value"] = value;
fieldsJson[name]["description"] = description;
}
} // namespace
namespace lsst {
namespace qserv {
namespace replica {
string SqlResultSet::Field::type2string() const {
switch (type) {
case MYSQL_TYPE_DECIMAL: return "MYSQL_TYPE_DECIMAL";
case MYSQL_TYPE_TINY: return "MYSQL_TYPE_TINY";
case MYSQL_TYPE_SHORT: return "MYSQL_TYPE_SHORT";
case MYSQL_TYPE_LONG: return "MYSQL_TYPE_LONG";
case MYSQL_TYPE_FLOAT: return "MYSQL_TYPE_FLOAT";
case MYSQL_TYPE_DOUBLE: return "MYSQL_TYPE_DOUBLE";
case MYSQL_TYPE_NULL: return "MYSQL_TYPE_NULL";
case MYSQL_TYPE_TIMESTAMP: return "MYSQL_TYPE_TIMESTAMP";
case MYSQL_TYPE_LONGLONG: return "MYSQL_TYPE_LONGLONG";
case MYSQL_TYPE_INT24: return "MYSQL_TYPE_INT24";
case MYSQL_TYPE_DATE: return "MYSQL_TYPE_DATE";
case MYSQL_TYPE_TIME: return "MYSQL_TYPE_TIME";
case MYSQL_TYPE_DATETIME: return "MYSQL_TYPE_DATETIME";
case MYSQL_TYPE_YEAR: return "MYSQL_TYPE_YEAR";
case MYSQL_TYPE_NEWDATE: return "MYSQL_TYPE_NEWDATE";
case MYSQL_TYPE_VARCHAR: return "MYSQL_TYPE_VARCHAR";
case MYSQL_TYPE_BIT: return "MYSQL_TYPE_BIT";
case MYSQL_TYPE_TIMESTAMP2: return "MYSQL_TYPE_TIMESTAMP2";
case MYSQL_TYPE_DATETIME2: return "MYSQL_TYPE_DATETIME2";
case MYSQL_TYPE_TIME2: return "MYSQL_TYPE_TIME2";
case MYSQL_TYPE_JSON: return "MYSQL_TYPE_JSON";
case MYSQL_TYPE_NEWDECIMAL: return "MYSQL_TYPE_NEWDECIMAL";
case MYSQL_TYPE_ENUM: return "MYSQL_TYPE_ENUM";
case MYSQL_TYPE_SET: return "MYSQL_TYPE_SET";
case MYSQL_TYPE_TINY_BLOB: return "MYSQL_TYPE_TINY_BLOB";
case MYSQL_TYPE_MEDIUM_BLOB: return "MYSQL_TYPE_MEDIUM_BLOB";
case MYSQL_TYPE_LONG_BLOB: return "MYSQL_TYPE_LONG_BLOB";
case MYSQL_TYPE_BLOB: return "MYSQL_TYPE_BLOB";
case MYSQL_TYPE_VAR_STRING: return "MYSQL_TYPE_VAR_STRING";
case MYSQL_TYPE_STRING: return "MYSQL_TYPE_STRING";
case MYSQL_TYPE_GEOMETRY: return "MYSQL_TYPE_GEOMETRY";
default:
return "MYSQL_TYPE_UNKNOWN";
}
}
SqlResultSet::Field::Field(ProtocolResponseSqlField const& field)
: name( field.name()),
orgName( field.org_name()),
table( field.table()),
orgTable( field.org_table()),
db( field.db()),
catalog( field.catalog()),
def( field.def()),
length( field.length()),
maxLength(field.max_length()),
flags( field.flags()),
decimals( field.decimals()),
type( field.type()) {
}
SqlResultSet::Row::Row(ProtocolResponseSqlRow const& row) {
for (int i = 0; i < row.cells_size(); ++i) {
cells.push_back(row.cells(i));
nulls.push_back(row.nulls(i) ? 1 : 0);
}
}
void SqlResultSet::set(ProtocolResponseSql const& message) {
error = message.error();
charSetName = message.char_set_name();
hasResult = message.has_result();
// Translate fields
fields.clear();
for (int i = 0; i < message.fields_size(); ++i) {
fields.emplace_back(message.fields(i));
}
// Translate rows
rows.clear();
for (int i = 0; i < message.rows_size(); ++i) {
rows.emplace_back(message.rows(i));
}
}
json SqlResultSet::toJson() const {
json resultJson;
resultJson["error"] = error;
resultJson["char_set_name"] = charSetName;
resultJson["has_result"] = hasResult;
for (size_t columnIdx = 0; columnIdx < fields.size(); ++columnIdx) {
auto const& field = fields[columnIdx];
auto&& fieldsJson = resultJson["fields"][columnIdx];
addField(fieldsJson, "name", field.name, "The name of the column");
addField(fieldsJson, "orgName", field.orgName, "The original name of the column");
addField(fieldsJson, "table", field.table, "The name of the table");
addField(fieldsJson, "orgTable", field.orgTable, "The original name of the table");
addField(fieldsJson, "db", field.db, "The name of the database (schema)");
addField(fieldsJson, "catalog", field.catalog, "The catalog name (always 'def')");
addField(fieldsJson, "def", field.def, "default value");
addField(fieldsJson, "length", field.length, "The length (width) of the column definition");
addField(fieldsJson, "maxLength", field.maxLength, "The maximum length of the column value");
addField(fieldsJson, "flags", field.flags, "Flags");
addField(fieldsJson, "decimals", field.decimals, "Number of decimals");
addField(fieldsJson, "type", field.type, "Field type (see MySQL headers for enum enum_field_types)");
addField(fieldsJson, "typeName", field.type2string(), "Field type name (see MySQL headers for enum enum_field_types)");
}
for (auto&& row : rows) {
json rowJson;
rowJson["cells"] = row.cells;
rowJson["nulls"] = row.nulls;
resultJson["rows"].push_back(rowJson);
}
return resultJson;
}
util::ColumnTablePrinter SqlResultSet::toColumnTable(string const& caption,
string const& indent,
bool verticalSeparator) const {
if (not hasResult) {
throw logic_error("SqlResultSet::" + string(__func__) + " no result set for the query");
}
// Package input data into columns
size_t const numRows = rows.size();
size_t const numColumns = fields.size();
vector<shared_ptr<vector<string>>> tableColumns;
tableColumns.reserve(numColumns);
for (size_t columnIdx = 0; columnIdx < numColumns; ++columnIdx) {
auto tableColumnPtr = make_shared<vector<string>>();
tableColumnPtr->reserve(numRows);
tableColumns.push_back(tableColumnPtr);
}
for (auto&& row : rows) {
for (size_t columnIdx = 0; columnIdx < numColumns; ++columnIdx) {
tableColumns[columnIdx]->push_back(
row.nulls.at(columnIdx) ? "NULL" : row.cells.at(columnIdx));
}
}
// Build the table
util::ColumnTablePrinter table(caption, indent, verticalSeparator);
for (size_t columnIdx = 0; columnIdx < numColumns; ++columnIdx) {
table.addColumn(fields[columnIdx].name,
*(tableColumns[columnIdx]),
util::ColumnTablePrinter::LEFT);
}
return table;
}
}}} // namespace lsst::qserv::replica
| [
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.