blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 986
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 145
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 122
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f9941f3a4b08fc56ac8bf74b85a3b3a7276b5d73 | 5838cf8f133a62df151ed12a5f928a43c11772ed | /NT/shell/osshell/accesory/wordpad/wordpdoc.cpp | f6339a0a3a488632d7d920ae99f5b31d2ce77b0f | [] | no_license | proaholic/Win2K3 | e5e17b2262f8a2e9590d3fd7a201da19771eb132 | 572f0250d5825e7b80920b6610c22c5b9baaa3aa | refs/heads/master | 2023-07-09T06:15:54.474432 | 2021-08-11T09:09:14 | 2021-08-11T09:09:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 22,814 | cpp | // wordpdoc.cpp : implementation of the CWordPadDoc class
//
// Copyright (C) 1992-1999 Microsoft Corporation
// All rights reserved.
#include "stdafx.h"
#include "wordpad.h"
#include "wordpdoc.h"
#include "wordpvw.h"
#include "cntritem.h"
#include "srvritem.h"
#include "formatba.h"
#include "mainfrm.h"
#include "ipframe.h"
#include "helpids.h"
#include "strings.h"
#include "unitspag.h"
#include "docopt.h"
#include "optionsh.h"
#include "multconv.h"
#include "fixhelp.h"
BOOL AskAboutFormatLoss(CWordPadDoc *pDoc) ;
//
// These defines are from ..\shell\userpri\uconvert.h
//
#define REVERSE_BYTE_ORDER_MARK 0xFFFE
#define BYTE_ORDER_MARK 0xFEFF
BOOL CheckForUnicodeTextFile(LPCTSTR lpszPathName) ;
#ifdef _DEBUG
#undef THIS_FILE
static char BASED_CODE THIS_FILE[] = __FILE__;
#endif
extern BOOL AFXAPI AfxFullPath(LPTSTR lpszPathOut, LPCTSTR lpszFileIn);
extern UINT AFXAPI AfxGetFileTitle(LPCTSTR lpszPathName, LPTSTR lpszTitle, UINT nMax);
#ifndef OFN_EXPLORER
#define OFN_EXPLORER 0x00080000L
#endif
//
// This small class implements the "This is an unsupported save format" dialog.
// It's main purpose is to provide a place to hang the "always convert to RTF"
// checkbox.
//
class UnsupportedSaveFormatDialog : public CDialog
{
public:
UnsupportedSaveFormatDialog()
: CDialog(TEXT("UnsupportedSaveFormatDialog")),
m_always_convert_to_rtf(false)
{
}
BOOL ShouldAlwaysConvertToRTF() {return m_always_convert_to_rtf;}
protected:
BOOL m_always_convert_to_rtf;
void DoDataExchange(CDataExchange *pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Check(pDX, IDC_ALWAYS_RTF, m_always_convert_to_rtf);
}
};
/////////////////////////////////////////////////////////////////////////////
// CWordPadDoc
IMPLEMENT_DYNCREATE(CWordPadDoc, CRichEdit2Doc)
BEGIN_MESSAGE_MAP(CWordPadDoc, CRichEdit2Doc)
//{{AFX_MSG_MAP(CWordPadDoc)
ON_COMMAND(ID_VIEW_OPTIONS, OnViewOptions)
ON_UPDATE_COMMAND_UI(ID_OLE_VERB_POPUP, OnUpdateOleVerbPopup)
ON_COMMAND(ID_FILE_SEND_MAIL, OnFileSendMail)
ON_UPDATE_COMMAND_UI(ID_FILE_NEW, OnUpdateIfEmbedded)
ON_UPDATE_COMMAND_UI(ID_FILE_OPEN, OnUpdateIfEmbedded)
ON_UPDATE_COMMAND_UI(ID_FILE_SAVE, OnUpdateIfEmbedded)
ON_UPDATE_COMMAND_UI(ID_FILE_PRINT, OnUpdateIfEmbedded)
ON_UPDATE_COMMAND_UI(ID_FILE_PRINT_DIRECT, OnUpdateIfEmbedded)
ON_UPDATE_COMMAND_UI(ID_FILE_PRINT_PREVIEW, OnUpdateIfEmbedded)
//}}AFX_MSG_MAP
ON_UPDATE_COMMAND_UI(ID_FILE_SEND_MAIL, OnUpdateFileSendMail)
ON_COMMAND(ID_OLE_EDIT_LINKS, OnEditLinks)
ON_UPDATE_COMMAND_UI(ID_OLE_VERB_FIRST, CRichEdit2Doc::OnUpdateObjectVerbMenu)
ON_UPDATE_COMMAND_UI(ID_OLE_EDIT_CONVERT, CRichEdit2Doc::OnUpdateObjectVerbMenu)
ON_UPDATE_COMMAND_UI(ID_OLE_EDIT_LINKS, CRichEdit2Doc::OnUpdateEditLinksMenu)
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CWordPadDoc construction/destruction
CWordPadDoc::CWordPadDoc()
{
m_nDocType = -1;
m_nNewDocType = -1;
m_short_filename = NULL;
}
BOOL CWordPadDoc::OnNewDocument()
{
if (!CRichEdit2Doc::OnNewDocument())
return FALSE;
//correct type already set in theApp.m_nNewDocType;
int nDocType = (IsEmbedded()) ? RD_EMBEDDED : theApp.m_nNewDocType;
GetView()->SetDefaultFont(IsTextType(nDocType));
SetDocType(nDocType);
return TRUE;
}
void CWordPadDoc::ReportSaveLoadException(LPCTSTR lpszPathName,
CException* e, BOOL bSaving, UINT nIDP)
{
if (!m_bDeferErrors && e != NULL)
{
ASSERT_VALID(e);
if (e->IsKindOf(RUNTIME_CLASS(CFileException)))
{
switch (((CFileException*)e)->m_cause)
{
case CFileException::fileNotFound:
case CFileException::badPath:
nIDP = AFX_IDP_FAILED_INVALID_PATH;
break;
case CFileException::diskFull:
nIDP = AFX_IDP_FAILED_DISK_FULL;
break;
case CFileException::accessDenied:
nIDP = AFX_IDP_FILE_ACCESS_DENIED;
if (((CFileException*)e)->m_lOsError == ERROR_WRITE_PROTECT)
nIDP = IDS_WRITEPROTECT;
break;
case CFileException::tooManyOpenFiles:
nIDP = IDS_TOOMANYFILES;
break;
case CFileException::directoryFull:
nIDP = IDS_DIRFULL;
break;
case CFileException::sharingViolation:
nIDP = IDS_SHAREVIOLATION;
break;
case CFileException::lockViolation:
case CFileException::badSeek:
case CFileException::generic:
case CFileException::invalidFile:
case CFileException::hardIO:
nIDP = bSaving ? AFX_IDP_FAILED_IO_ERROR_WRITE :
AFX_IDP_FAILED_IO_ERROR_READ;
break;
default:
break;
}
CString prompt;
AfxFormatString1(prompt, nIDP, lpszPathName);
AfxMessageBox(prompt, MB_ICONEXCLAMATION, nIDP);
return;
}
}
CRichEdit2Doc::ReportSaveLoadException(lpszPathName, e, bSaving, nIDP);
return;
}
BOOL CheckForUnicodeTextFile(LPCTSTR lpszPathName)
{
BOOL fRet = FALSE ;
HANDLE hFile = (HANDLE) 0 ;
WORD wBOM ;
DWORD dwBytesRead = 0 ;
BOOL bTmp ;
if (lpszPathName == NULL)
{
return FALSE ;
}
hFile = CreateFile(
lpszPathName,
GENERIC_READ,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL) ;
if (hFile == INVALID_HANDLE_VALUE)
{
return FALSE ;
}
bTmp = ReadFile(
hFile,
&wBOM,
sizeof(WORD),
&dwBytesRead,
NULL) ;
if (bTmp)
{
if (dwBytesRead == sizeof(WORD))
{
if ( (wBOM == BYTE_ORDER_MARK) ||
(wBOM == REVERSE_BYTE_ORDER_MARK) )
{
fRet = TRUE ;
}
}
}
CloseHandle(hFile) ;
return fRet ;
}
BOOL CWordPadDoc::OnOpenDocument2(LPCTSTR lpszPathName, bool defaultToText, BOOL* pbAccessDenied)
{
if (pbAccessDenied)
*pbAccessDenied = FALSE;
if (m_lpRootStg != NULL) // we are embedded
{
// we really want to use the converter on this storage
m_nNewDocType = RD_EMBEDDED;
}
else
{
if (theApp.cmdInfo.m_bForceTextMode)
m_nNewDocType = RD_TEXT;
else
{
CFileException fe;
m_nNewDocType = GetDocTypeFromName(lpszPathName, fe, defaultToText);
if (m_nNewDocType == -1)
{
if (defaultToText)
{
ReportSaveLoadException(lpszPathName, &fe, FALSE,
AFX_IDP_FAILED_TO_OPEN_DOC);
}
return FALSE;
}
if (RD_FEWINWORD5 == m_nNewDocType)
{
AfxMessageBox(IDS_FEWINWORD5_DOC, MB_OK, MB_ICONINFORMATION);
if (pbAccessDenied)
*pbAccessDenied = TRUE;
return FALSE;
}
if (m_nNewDocType == RD_TEXT && theApp.m_bForceOEM)
m_nNewDocType = RD_OEMTEXT;
}
ScanForConverters();
if (!doctypes[m_nNewDocType].bRead || DocTypeDisabled(m_nNewDocType))
{
CString str;
CString strName = doctypes[m_nNewDocType].GetString(DOCTYPE_DOCTYPE);
AfxFormatString1(str, IDS_CANT_LOAD, strName);
AfxMessageBox(str, MB_OK|MB_ICONINFORMATION);
if (pbAccessDenied)
*pbAccessDenied = TRUE;
return FALSE;
}
}
if (RD_TEXT == m_nNewDocType)
{
if (CheckForUnicodeTextFile(lpszPathName))
m_nNewDocType = RD_UNICODETEXT;
}
if (!CRichEdit2Doc::OnOpenDocument(lpszPathName))
return FALSE;
// Update any Ole links
COleUpdateDialog(this).DoModal();
return TRUE;
}
BOOL CWordPadDoc::OnOpenDocument(LPCTSTR lpszPathName)
{
BOOL bAccessDenied = FALSE;
if (OnOpenDocument2(lpszPathName, NO_DEFAULT_TO_TEXT, &bAccessDenied))
{
delete [] m_short_filename;
m_short_filename = NULL;
return TRUE;
}
// if we know we failed, don't try the short name
if (bAccessDenied)
return FALSE;
LPTSTR short_filename = new TCHAR[MAX_PATH];
if (NULL == short_filename)
AfxThrowMemoryException();
if (0 == ::GetShortPathName(lpszPathName, short_filename, MAX_PATH))
{
delete [] short_filename;
if (ERROR_FILE_NOT_FOUND == GetLastError())
{
CFileException fe(CFileException::fileNotFound);
ReportSaveLoadException(lpszPathName, &fe, FALSE,
AFX_IDP_FAILED_TO_OPEN_DOC);
return FALSE;
}
AfxThrowFileException(
CFileException::generic,
GetLastError(),
lpszPathName);
}
if (OnOpenDocument2(short_filename))
{
delete [] m_short_filename;
m_short_filename = short_filename;
return TRUE;
}
delete [] short_filename;
return FALSE;
}
void CWordPadDoc::Serialize(CArchive& ar)
{
COleMessageFilter* pFilter = AfxOleGetMessageFilter();
ASSERT(pFilter != NULL);
pFilter->EnableBusyDialog(FALSE);
if (ar.IsLoading())
SetDocType(m_nNewDocType);
//
// Strip (or output) the byte order mark if this is a Unicode file
//
if (m_bUnicode)
{
if (ar.IsLoading())
{
WORD byte_order_mark;
ar >> byte_order_mark;
// No support for byte-reversed files
ASSERT(BYTE_ORDER_MARK == byte_order_mark);
}
else
{
ar << (WORD) BYTE_ORDER_MARK;
}
}
CRichEdit2Doc::Serialize(ar);
pFilter->EnableBusyDialog(TRUE);
}
BOOL AskAboutFormatLoss(CWordPadDoc *pDoc)
{
UNREFERENCED_PARAMETER(pDoc);
return (IDYES == AfxMessageBox(IDS_SAVE_FORMAT_TEXT, MB_YESNO));
}
BOOL CWordPadDoc::DoSave(LPCTSTR pszPathName, BOOL bReplace /*=TRUE*/)
// Save the document data to a file
// pszPathName = path name where to save document file
// if pszPathName is NULL then the user will be prompted (SaveAs)
// note: pszPathName can be different than 'm_strPathName'
// if 'bReplace' is TRUE will change file name if successful (SaveAs)
// if 'bReplace' is FALSE will not change path name (SaveCopyAs)
{
if (NULL != pszPathName)
if (pszPathName == m_strPathName && NULL != m_short_filename)
pszPathName = m_short_filename;
CString newName = pszPathName;
int nOrigDocType = m_nDocType; //saved in case of SaveCopyAs or failure
int nDocType ;
// newName bWrite type result
// empty TRUE - SaveAs dialog
// empty FALSE - SaveAs dialog
// notempty TRUE - nothing
// notempty FALSE W6 warn (change to wordpad, save as, cancel)
// notempty FALSE other warn (save as, cancel)
BOOL bModified = IsModified();
ScanForConverters();
BOOL bSaveAs = FALSE;
if (newName.IsEmpty())
{
bSaveAs = TRUE;
}
else if (!doctypes[m_nDocType].bWrite)
{
if (!theApp.ShouldAlwaysConvertToRTF())
{
UnsupportedSaveFormatDialog dialog;
if (IDOK != dialog.DoModal())
return FALSE;
if (dialog.ShouldAlwaysConvertToRTF())
theApp.SetAlwaysConvertToRTF();
}
m_nDocType = RD_RICHTEXT;
}
if (m_lpRootStg == NULL && IsTextType(m_nDocType) &&
!bSaveAs && !GetView()->IsFormatText())
{
if (!AskAboutFormatLoss(this))
bSaveAs = TRUE;
}
GetView()->GetParentFrame()->RecalcLayout();
if (bSaveAs)
{
newName = m_strPathName;
if (bReplace && newName.IsEmpty())
{
newName = m_strTitle;
int iBad = newName.FindOneOf(_T(" #%;/\\")); // dubious filename
if (iBad != -1)
newName.ReleaseBuffer(iBad);
// append the default suffix if there is one
newName += GetExtFromType(m_nDocType);
}
nDocType = m_nDocType;
promptloop:
if (!theApp.PromptForFileName(newName,
bReplace ? AFX_IDS_SAVEFILE : AFX_IDS_SAVEFILECOPY,
OFN_HIDEREADONLY | OFN_PATHMUSTEXIST, FALSE, &nDocType))
{
SetDocType(nOrigDocType, TRUE);
return FALSE; // don't even try to save
}
else
{
//
// If we are transitioning from non-text to text, we need
// to warn the user if there is any formatting / graphics
// that will be lost
//
if (IsTextType(nDocType))
{
if (m_lpRootStg == NULL && !GetView()->IsFormatText())
{
if (!AskAboutFormatLoss(this))
goto promptloop;
}
}
}
SetDocType(nDocType, TRUE);
}
BeginWaitCursor();
if (!OnSaveDocument(newName))
{
//
// The original code deleted the file if an error occurred, on the
// assumption that if we tried to save a file and something went wrong
// but there was a file there after the save, the file is probably
// bogus. This fails if there is an existing file that doesn't have
// write access but does have delete access. How can this happen?
// The security UI does not remove delete access when you remove
// write access.
//
// restore orginal document type
SetDocType(nOrigDocType, TRUE);
EndWaitCursor();
return FALSE;
}
EndWaitCursor();
if (bReplace)
{
int nType = m_nDocType;
SetDocType(nOrigDocType, TRUE);
SetDocType(nType);
// Reset the title and change the document name
if (NULL == m_short_filename
|| 0 != newName.CompareNoCase(m_short_filename))
{
SetPathName(newName, TRUE);
// If we saved to a new filename, reset the short name
if (bSaveAs)
{
delete [] m_short_filename;
m_short_filename = NULL;
}
}
}
else // SaveCopyAs
{
SetDocType(nOrigDocType, TRUE);
SetModifiedFlag(bModified);
}
return TRUE; // success
}
class COIPF : public COleIPFrameWnd
{
public:
CFrameWnd* GetMainFrame() { return m_pMainFrame;}
CFrameWnd* GetDocFrame() { return m_pDocFrame;}
};
void CWordPadDoc::OnDeactivateUI(BOOL bUndoable)
{
if (GetView()->m_bDelayUpdateItems)
UpdateAllItems(NULL);
SaveState(m_nDocType);
CRichEdit2Doc::OnDeactivateUI(bUndoable);
COIPF* pFrame = (COIPF*)m_pInPlaceFrame;
if (pFrame != NULL)
{
if (pFrame->GetMainFrame() != NULL)
ForceDelayed(pFrame->GetMainFrame());
if (pFrame->GetDocFrame() != NULL)
ForceDelayed(pFrame->GetDocFrame());
}
}
void CWordPadDoc::ForceDelayed(CFrameWnd* pFrameWnd)
{
ASSERT_VALID(this);
ASSERT_VALID(pFrameWnd);
POSITION pos = pFrameWnd->m_listControlBars.GetHeadPosition();
while (pos != NULL)
{
// show/hide the next control bar
CControlBar* pBar =
(CControlBar*)pFrameWnd->m_listControlBars.GetNext(pos);
BOOL bVis = pBar->GetStyle() & WS_VISIBLE;
UINT swpFlags = 0;
if ((pBar->m_nStateFlags & CControlBar::delayHide) && bVis)
swpFlags = SWP_HIDEWINDOW;
else if ((pBar->m_nStateFlags & CControlBar::delayShow) && !bVis)
swpFlags = SWP_SHOWWINDOW;
pBar->m_nStateFlags &= ~(CControlBar::delayShow|CControlBar::delayHide);
if (swpFlags != 0)
{
pBar->SetWindowPos(NULL, 0, 0, 0, 0, swpFlags|
SWP_NOMOVE|SWP_NOSIZE|SWP_NOZORDER|SWP_NOACTIVATE);
}
}
}
/////////////////////////////////////////////////////////////////////////////
// CWordPadDoc Attributes
CLSID CWordPadDoc::GetClassID()
{
return (m_pFactory == NULL) ? CLSID_NULL : m_pFactory->GetClassID();
}
void CWordPadDoc::SetDocType(int nNewDocType, BOOL bNoOptionChange)
{
ASSERT(nNewDocType != -1);
if (nNewDocType == m_nDocType)
return;
m_bRTF = !IsTextType(nNewDocType);
m_bUnicode = (nNewDocType == RD_UNICODETEXT);
if (bNoOptionChange)
m_nDocType = nNewDocType;
else
{
SaveState(m_nDocType);
m_nDocType = nNewDocType;
RestoreState(m_nDocType);
}
}
CWordPadView* CWordPadDoc::GetView()
{
POSITION pos = GetFirstViewPosition();
return (CWordPadView* )GetNextView( pos );
}
/////////////////////////////////////////////////////////////////////////////
// CWordPadDoc Operations
CFile* CWordPadDoc::GetFile(LPCTSTR pszPathName, UINT nOpenFlags, CFileException* pException)
{
CTrackFile* pFile = NULL;
CFrameWnd* pWnd = GetView()->GetParentFrame();
#ifdef CONVERTERS
ScanForConverters();
// if writing use current doc type otherwise use new doc type
int nType = (nOpenFlags & CFile::modeReadWrite) ? m_nDocType : m_nNewDocType;
// m_nNewDocType will be same as m_nDocType except when opening a new file
if (doctypes[nType].pszConverterName != NULL)
pFile = new CConverter(doctypes[nType].pszConverterName, pWnd);
else
#endif
if (nType == RD_OEMTEXT)
pFile = new COEMFile(pWnd);
else
pFile = new CTrackFile(pWnd);
if (!pFile->Open(pszPathName, nOpenFlags, pException))
{
delete pFile;
return NULL;
}
if (nOpenFlags & (CFile::modeWrite | CFile::modeReadWrite))
pFile->m_dwLength = 0; // can't estimate this
else
pFile->m_dwLength = pFile->GetLength();
return pFile;
}
CRichEdit2CntrItem* CWordPadDoc::CreateClientItem(REOBJECT* preo) const
{
// cast away constness of this
return new CWordPadCntrItem(preo, (CWordPadDoc*)this);
}
/////////////////////////////////////////////////////////////////////////////
// CWordPadDoc server implementation
COleServerItem* CWordPadDoc::OnGetEmbeddedItem()
{
// OnGetEmbeddedItem is called by the framework to get the COleServerItem
// that is associated with the document. It is only called when necessary.
CEmbeddedItem* pItem = new CEmbeddedItem(this);
ASSERT_VALID(pItem);
return pItem;
}
/////////////////////////////////////////////////////////////////////////////
// CWordPadDoc serialization
/////////////////////////////////////////////////////////////////////////////
// CWordPadDoc diagnostics
#ifdef _DEBUG
void CWordPadDoc::AssertValid() const
{
CRichEdit2Doc::AssertValid();
}
void CWordPadDoc::Dump(CDumpContext& dc) const
{
CRichEdit2Doc::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CWordPadDoc commands
int CWordPadDoc::MapType(int nType)
{
if (nType == RD_OEMTEXT || nType == RD_UNICODETEXT)
nType = RD_TEXT;
else if (!IsInPlaceActive() && nType == RD_EMBEDDED)
nType = RD_RICHTEXT;
return nType;
}
void CWordPadDoc::OnViewOptions()
{
int nType = MapType(m_nDocType);
int nFirstPage = 3;
if (nType == RD_TEXT)
nFirstPage = 1;
else if (nType == RD_RICHTEXT)
nFirstPage = 2;
else if (nType == RD_WRITE)
nFirstPage = 4;
else if (nType == RD_EMBEDDED)
nFirstPage = 5;
SaveState(nType);
COptionSheet sheet(IDS_OPTIONS, NULL, nFirstPage);
if (sheet.DoModal() == IDOK)
{
CWordPadView* pView = GetView();
if (theApp.m_bWordSel)
pView->GetRichEditCtrl().SetOptions(ECOOP_OR, ECO_AUTOWORDSELECTION);
else
{
pView->GetRichEditCtrl().SetOptions(ECOOP_AND,
~(DWORD)ECO_AUTOWORDSELECTION);
}
RestoreState(nType);
}
}
void CWordPadDoc::OnUpdateOleVerbPopup(CCmdUI* pCmdUI)
{
pCmdUI->m_pParentMenu = pCmdUI->m_pMenu;
CRichEdit2Doc::OnUpdateObjectVerbMenu(pCmdUI);
}
BOOL CWordPadDoc::OnCmdMsg(UINT nID, int nCode, void* pExtra, AFX_CMDHANDLERINFO* pHandlerInfo)
{
if (nCode == CN_COMMAND && nID == ID_OLE_VERB_POPUP)
nID = ID_OLE_VERB_FIRST;
return CRichEdit2Doc::OnCmdMsg(nID, nCode, pExtra, pHandlerInfo);
}
void CWordPadDoc::SaveState(int nType)
{
if (nType == -1)
return;
nType = MapType(nType);
CWordPadView* pView = GetView();
if (pView != NULL)
{
CFrameWnd* pFrame = pView->GetParentFrame();
ASSERT(pFrame != NULL);
// save current state
pFrame->SendMessage(WPM_BARSTATE, 0, nType);
theApp.GetDocOptions(nType).m_nWordWrap = pView->m_nWordWrap;
}
}
void CWordPadDoc::RestoreState(int nType)
{
if (nType == -1)
return;
nType = MapType(nType);
CWordPadView* pView = GetView();
if (pView != NULL)
{
CFrameWnd* pFrame = pView->GetParentFrame();
ASSERT(pFrame != NULL);
// set new state
pFrame->SendMessage(WPM_BARSTATE, 1, nType);
int nWrapNew = theApp.GetDocOptions(nType).m_nWordWrap;
if (pView->m_nWordWrap != nWrapNew)
{
pView->m_nWordWrap = nWrapNew;
pView->WrapChanged();
}
}
}
void CWordPadDoc::OnCloseDocument()
{
SaveState(m_nDocType);
CRichEdit2Doc::OnCloseDocument();
}
void CWordPadDoc::PreCloseFrame(CFrameWnd* pFrameArg)
{
CRichEdit2Doc::PreCloseFrame(pFrameArg);
SaveState(m_nDocType);
}
void CWordPadDoc::OnFileSendMail()
{
if (m_strTitle.Find('.') == -1)
{
// add the extension because the default extension will be wrong
CString strOldTitle = m_strTitle;
m_strTitle += GetExtFromType(m_nDocType);
CRichEdit2Doc::OnFileSendMail();
m_strTitle = strOldTitle;
}
else
CRichEdit2Doc::OnFileSendMail();
}
void CWordPadDoc::OnUpdateIfEmbedded(CCmdUI* pCmdUI)
{
pCmdUI->Enable(!IsEmbedded());
}
void CWordPadDoc::OnEditLinks()
{
g_fDisableStandardHelp = TRUE ;
SetHelpFixHook() ;
COleLinksDialog dlg(this, GetRoutingView_());
dlg.m_el.dwFlags |= ELF_DISABLECANCELLINK;
dlg.DoModal();
RemoveHelpFixHook() ;
g_fDisableStandardHelp = FALSE ;
}
| [
"blindtiger@foxmail.com"
] | blindtiger@foxmail.com |
12dd2dc288d9e7ccaccdbf68cfbc3a5d8b295337 | 2fcc9ad89cf0c85d12fa549f969973b6f4c68fdc | /LibMathematics/Intersection/Wm5IntrSegment2Box2.h | bd7d2872542672c52d96f02cea50f227f3f725d4 | [
"BSL-1.0"
] | permissive | nmnghjss/WildMagic | 9e111de0a23d736dc5b2eef944f143ca84e58bc0 | b1a7cc2140dde23d8d9a4ece52a07bd5ff938239 | refs/heads/master | 2022-04-22T09:01:12.909379 | 2013-05-13T21:28:18 | 2013-05-13T21:28:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,383 | h | // Geometric Tools, LLC
// Copyright (c) 1998-2012
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.1 (2010/10/01)
#ifndef WM5INTRSEGMENT2BOX2_H
#define WM5INTRSEGMENT2BOX2_H
#include "Wm5MathematicsLIB.h"
#include "Wm5Intersector.h"
#include "Wm5Segment2.h"
#include "Wm5Box2.h"
namespace Wm5
{
template <typename Real>
class WM5_MATHEMATICS_ITEM IntrSegment2Box2
: public Intersector<Real,Vector2<Real> >
{
public:
IntrSegment2Box2 (const Segment2<Real>& segment,
const Box2<Real>& box, bool solid);
// Object access.
const Segment2<Real>& GetSegment () const;
const Box2<Real>& GetBox () const;
// Static intersection queries.
virtual bool Test ();
virtual bool Find ();
// The intersection set.
int GetQuantity () const;
const Vector2<Real>& GetPoint (int i) const;
private:
using Intersector<Real,Vector2<Real> >::mIntersectionType;
// The objects to intersect.
const Segment2<Real>* mSegment;
const Box2<Real>* mBox;
bool mSolid;
// Information about the intersection set.
int mQuantity;
Vector2<Real> mPoint[2];
};
typedef IntrSegment2Box2<float> IntrSegment2Box2f;
typedef IntrSegment2Box2<double> IntrSegment2Box2d;
}
#endif
| [
"bazhenovc@bazhenovc-laptop"
] | bazhenovc@bazhenovc-laptop |
7bce24ebadc8f5209c3fbf9f3f97b416aac066f1 | 04b531f93ff74bfc484769971f1b8a010dc9ea7a | /src/Pointillism/inclusion.cpp | e3cb1b696bbbc1c64feb5917ba62627498f22ad9 | [
"Apache-2.0"
] | permissive | roshrestha/TS2CG | 6b79ef46532bbda3f67cd460ffe78ae812343255 | 6882d635ecf9f6bd48714e30ec18b96a200dd7bb | refs/heads/master | 2022-06-27T17:21:45.259608 | 2020-05-08T12:48:13 | 2020-05-08T12:48:13 | 262,395,616 | 1 | 0 | Apache-2.0 | 2020-05-08T18:12:57 | 2020-05-08T18:12:56 | null | UTF-8 | C++ | false | false | 4,018 | cpp | #if !defined(AFX_inclusion_CPP_7F4A21C7_C13Q_8823_BF2E_124095086234__INCLUDED_)
#define AFX_inclusion_CPP_7F4A21C7_C13Q_8823_BF2E_124095086234__INCLUDED_
#include <stdio.h>
#include "inclusion.h"
#include "vertex.h"
#include "Nfunction.h"
inclusion::inclusion(int id)
{
m_ID=id;
m_TypeID = 0;
m_NSymmetry = 0;
m_Type = "Pro";
}
inclusion::~inclusion()
{
}
void inclusion::UpdateC0(double c0,double c1,double c2)
{
m_C0.clear();
m_C0.push_back(c0);
m_C0.push_back(c1);
m_C0.push_back(c2);
}
void inclusion::UpdateKappa(double k1,double k2,double k3,double k4)
{
m_kappa.clear();
m_kappa.push_back(k1);
m_kappa.push_back(k2);
m_kappa.push_back(k3);
m_kappa.push_back(k4);
}
void inclusion::UpdateType(std::string type, int inctypeid)
{
m_Type=type;
m_TypeID = inctypeid;
}
void inclusion::Updatevertex(vertex * v)
{
m_pvertex = v;
}
void inclusion::UpdateNSymmetry(int n)
{
m_NSymmetry = n;
}
void inclusion::UpdateLocalDirection(Vec3D v)
{
m_LDirection = v;
}
/*void inclusion::UpdateGlobalDirection(Vec3D v)
{
m_GDirection = v;
}*/
void inclusion::ReadInclusionFromFile(std::ifstream *inputfile,std::vector <vertex *> pv)
{
int id,n;
double x,y,z,k1,k2,k3,k4,c0,c1,c2;
std::string word,name;
bool readok=true;
// getline((*inputfile),name);
// getline((*inputfile),name);
(*inputfile)>>word>>id;
if(id!=m_ID || word!="Inclusion")
{
#if TEST_MODE == Enabled
std::cout<<word<<" != Inclusion \n";
std::cout<<word<<" this could be because of different complilers \n";
#endif
readok=false;
}
(*inputfile)>>word>>name>>id;
if( word!="Type")
readok=false;
m_Type = name;
m_TypeID = id;
(*inputfile)>>word>>n;
if( word!="m_NSymmetry")
readok=false;
m_NSymmetry=n;
(*inputfile)>>word>>x>>y>>z;
if( word!="LocalDirection")
readok=false;
m_LDirection(0)=x;
m_LDirection(1)=y;
m_LDirection(2)=z;
(*inputfile)>>word>>k1>>k2>>k3;
if( word!="Kappa")
readok=false;
//==== to check if the trajectory belong to old version or new
Nfunction f;
std::getline((*inputfile),word);
m_kappa.clear();
if(word.size()==0)
{
m_kappa.push_back(k1);
m_kappa.push_back(0);
m_kappa.push_back(k2);
m_kappa.push_back(k3);
}
else
{
m_kappa.push_back(k1);
m_kappa.push_back(k2);
m_kappa.push_back(k3);
m_kappa.push_back(f.String_to_Double(word));
}
(*inputfile)>>word>>c0>>c1>>c2;
if(word!="Curvature")
readok=false;
m_C0.clear();
m_C0.push_back(c0);
m_C0.push_back(c1);
m_C0.push_back(c2);
(*inputfile)>>word>>n;
if( word!="Vertex")
readok=false;
m_pvertex = pv.at(n);
if(readok!=true)
{
std::cout<<"Error: wrong Inclusion id in reading the file: perhpas the file is broken \n";
}
}
void inclusion::WriteInclusionToFile(std::ofstream *output)
{
(*output)<<std::fixed;
(*output)<<std::setprecision( Precision );
// (*output)<<"====================================================== \n";
(*output)<<"Inclusion "<<m_ID<<"\n";
(*output)<<"Type "<<m_Type<<" "<<m_TypeID<<"\n";
(*output)<<"m_NSymmetry "<<m_NSymmetry<<"\n";
(*output)<<"LocalDirection "<<m_LDirection(0)<<" "<<m_LDirection(1)<<" "<<m_LDirection(2)<<"\n";
(*output)<<"Kappa "<<m_kappa.at(0)<<" "<<m_kappa.at(1)<<" "<<m_kappa.at(2)<<" "<<m_kappa.at(3)<<"\n";
(*output)<<"Curvature "<<m_C0.at(0)<<" "<<m_C0.at(1)<<" "<<m_C0.at(2)<<"\n";
(*output)<<"Vertex "<<m_pvertex->GetVID()<<"\n";
}
void inclusion::WriteInclusion()
{
std::cout<<std::fixed;
std::cout<<std::setprecision( Precision );
std::cout<<"Inclusion "<<m_ID<<"\n";
std::cout<<"Type "<<m_Type<<" "<<m_TypeID<<"\n";
std::cout<<"m_NSymmetry "<<m_NSymmetry<<"\n";
}
#endif
| [
"tsjerkw@gmail.com"
] | tsjerkw@gmail.com |
6235f945f1a4322bb5f595054d9efc9b726475d6 | 53f3f38eac3ed44f23f8f58d34aa8bd89555eaef | /src/msvc/include/AutoGemmKernelSources/sgemm_Col_TN_B1_ML080_NL080_KX08_src.cpp | c276115af8df31b93dee02d9dde807d7fd5666e3 | [
"Apache-2.0"
] | permissive | gajgeospatial/clBLAS-1.10 | 16039ddfad67b6c26a00767f33911e7c6fe374dc | 2f5f1347e814e23b93262cd6fa92ec1d228963ac | refs/heads/master | 2022-06-27T09:08:34.399452 | 2020-05-12T16:50:46 | 2020-05-12T16:50:46 | 263,172,549 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,718 | cpp | /*******************************************************************************
* This file was auto-generated using the AutoGemm.py python script.
* DO NOT modify this file! Instead, make changes to scripts in
* clBLAS/src/library/blas/AutoGemm/ then re-generate files
* (otherwise local changes will be lost after re-generation).
******************************************************************************/
#ifndef KERNEL_SGEMM_COL_TN_B1_ML080_NL080_KX08_SRC_H
#define KERNEL_SGEMM_COL_TN_B1_ML080_NL080_KX08_SRC_H
const unsigned int sgemm_Col_TN_B1_ML080_NL080_KX08_workGroupNumRows = 16;
const unsigned int sgemm_Col_TN_B1_ML080_NL080_KX08_workGroupNumCols = 16;
const unsigned int sgemm_Col_TN_B1_ML080_NL080_KX08_microTileNumRows = 5;
const unsigned int sgemm_Col_TN_B1_ML080_NL080_KX08_microTileNumCols = 5;
const unsigned int sgemm_Col_TN_B1_ML080_NL080_KX08_unroll = 8;
const char * const sgemm_Col_TN_B1_ML080_NL080_KX08_src ="\n"
"/* sgemm_Col_TN_B1_ML080_NL080_KX08 */\n"
"\n"
"/* kernel parameters */\n"
"#define WG_NUM_ROWS 16\n"
"#define WG_NUM_COLS 16\n"
"#define MICRO_TILE_NUM_ROWS 5\n"
"#define MICRO_TILE_NUM_COLS 5\n"
"#define MACRO_TILE_NUM_ROWS 80\n"
"#define MACRO_TILE_NUM_COLS 80\n"
"#define NUM_UNROLL_ITER 8\n"
"\n"
"#define LOCAL_ROW_PAD 0\n"
"#define LOCAL_COL_PAD 0\n"
"\n"
"/* global memory indices */\n"
"#define GET_GLOBAL_INDEX_A(ROW,COL) ((ROW)*lda+(COL))\n"
"#define GET_GLOBAL_INDEX_B(ROW,COL) ((COL)*ldb+(ROW))\n"
"#define GET_GLOBAL_INDEX_C(ROW,COL) ((COL)*ldc+(ROW))\n"
"\n"
"/* local memory indices */\n"
"#define GET_LOCAL_INDEX_A(ROW,COL) ((ROW) + (COL)*((MACRO_TILE_NUM_ROWS)+(LOCAL_COL_PAD)) )\n"
"#define GET_LOCAL_INDEX_B(ROW,COL) ((COL) + (ROW)*((MACRO_TILE_NUM_COLS)+(LOCAL_ROW_PAD)) )\n"
"\n"
"/* data types */\n"
"#define DATA_TYPE_STR float\n"
"#define TYPE_MAD(MULA,MULB,DST) DST = mad(MULA,MULB,DST);\n"
"#define TYPE_MAD_WRITE(DST,ALPHA,REG,BETA) DST = (ALPHA)*(REG) + (BETA)*(DST);\n"
"\n"
"/* 5x5 micro-tile */\n"
"#define MICRO_TILE \\\n"
" rA[0] = localA[offA + 0*WG_NUM_ROWS]; \\\n"
" rA[1] = localA[offA + 1*WG_NUM_ROWS]; \\\n"
" rA[2] = localA[offA + 2*WG_NUM_ROWS]; \\\n"
" rA[3] = localA[offA + 3*WG_NUM_ROWS]; \\\n"
" rA[4] = localA[offA + 4*WG_NUM_ROWS]; \\\n"
" rB[0] = localB[offB + 0*WG_NUM_COLS]; \\\n"
" rB[1] = localB[offB + 1*WG_NUM_COLS]; \\\n"
" rB[2] = localB[offB + 2*WG_NUM_COLS]; \\\n"
" rB[3] = localB[offB + 3*WG_NUM_COLS]; \\\n"
" rB[4] = localB[offB + 4*WG_NUM_COLS]; \\\n"
" offA += (MACRO_TILE_NUM_ROWS+LOCAL_COL_PAD); \\\n"
" offB += (MACRO_TILE_NUM_COLS+LOCAL_ROW_PAD); \\\n"
" TYPE_MAD(rA[0],rB[0],rC[0][0]); \\\n"
" TYPE_MAD(rA[0],rB[1],rC[0][1]); \\\n"
" TYPE_MAD(rA[0],rB[2],rC[0][2]); \\\n"
" TYPE_MAD(rA[0],rB[3],rC[0][3]); \\\n"
" TYPE_MAD(rA[0],rB[4],rC[0][4]); \\\n"
" TYPE_MAD(rA[1],rB[0],rC[1][0]); \\\n"
" TYPE_MAD(rA[1],rB[1],rC[1][1]); \\\n"
" TYPE_MAD(rA[1],rB[2],rC[1][2]); \\\n"
" TYPE_MAD(rA[1],rB[3],rC[1][3]); \\\n"
" TYPE_MAD(rA[1],rB[4],rC[1][4]); \\\n"
" TYPE_MAD(rA[2],rB[0],rC[2][0]); \\\n"
" TYPE_MAD(rA[2],rB[1],rC[2][1]); \\\n"
" TYPE_MAD(rA[2],rB[2],rC[2][2]); \\\n"
" TYPE_MAD(rA[2],rB[3],rC[2][3]); \\\n"
" TYPE_MAD(rA[2],rB[4],rC[2][4]); \\\n"
" TYPE_MAD(rA[3],rB[0],rC[3][0]); \\\n"
" TYPE_MAD(rA[3],rB[1],rC[3][1]); \\\n"
" TYPE_MAD(rA[3],rB[2],rC[3][2]); \\\n"
" TYPE_MAD(rA[3],rB[3],rC[3][3]); \\\n"
" TYPE_MAD(rA[3],rB[4],rC[3][4]); \\\n"
" TYPE_MAD(rA[4],rB[0],rC[4][0]); \\\n"
" TYPE_MAD(rA[4],rB[1],rC[4][1]); \\\n"
" TYPE_MAD(rA[4],rB[2],rC[4][2]); \\\n"
" TYPE_MAD(rA[4],rB[3],rC[4][3]); \\\n"
" TYPE_MAD(rA[4],rB[4],rC[4][4]); \\\n"
" mem_fence(CLK_LOCAL_MEM_FENCE);\n"
"\n"
"__attribute__((reqd_work_group_size(WG_NUM_COLS,WG_NUM_ROWS,1)))\n"
"__kernel void sgemm_Col_TN_B1_ML080_NL080_KX08(\n"
" __global DATA_TYPE_STR const * restrict A,\n"
" __global DATA_TYPE_STR const * restrict B,\n"
" __global DATA_TYPE_STR * C,\n"
" DATA_TYPE_STR const alpha,\n"
" DATA_TYPE_STR const beta,\n"
" uint const M,\n"
" uint const N,\n"
" uint const K,\n"
" uint const lda,\n"
" uint const ldb,\n"
" uint const ldc,\n"
" uint const offsetA,\n"
" uint const offsetB,\n"
" uint const offsetC\n"
") {\n"
"\n"
" /* apply offsets */\n"
" A += offsetA;\n"
" B += offsetB;\n"
" C += offsetC;\n"
"\n"
" /* allocate registers */\n"
" DATA_TYPE_STR rC[MICRO_TILE_NUM_ROWS][MICRO_TILE_NUM_COLS] = { {0} };\n"
" DATA_TYPE_STR rA[MICRO_TILE_NUM_ROWS];\n"
" DATA_TYPE_STR rB[MICRO_TILE_NUM_COLS];\n"
"\n"
" /* allocate local memory */\n"
" __local DATA_TYPE_STR localA[NUM_UNROLL_ITER*(MACRO_TILE_NUM_ROWS+LOCAL_COL_PAD)];\n"
" __local DATA_TYPE_STR localB[NUM_UNROLL_ITER*(MACRO_TILE_NUM_COLS+LOCAL_ROW_PAD)];\n"
"\n"
" /* work item indices */\n"
" uint groupRow = M / 80; // last row\n"
" uint groupCol = N / 80; // last column\n"
" uint localRow = get_local_id(0);\n"
" uint localCol = get_local_id(1);\n"
" uint localSerial = localRow + localCol*WG_NUM_ROWS;\n"
"\n"
" /* global indices being loaded */\n"
"#define globalARow(LID) (groupRow*MACRO_TILE_NUM_ROWS + (localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)/NUM_UNROLL_ITER)\n"
"#define globalACol(LID) ((localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)%NUM_UNROLL_ITER)\n"
"#define globalBRow(LID) ((localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)%NUM_UNROLL_ITER)\n"
"#define globalBCol(LID) (groupCol*MACRO_TILE_NUM_COLS + (localSerial+(LID)*WG_NUM_ROWS*WG_NUM_COLS)/NUM_UNROLL_ITER)\n"
"\n"
" /* loop over k */\n"
" uint block_k = K / NUM_UNROLL_ITER;\n"
" do {\n"
"\n"
" /* local indices being written */\n"
"#define localARow (localSerial / NUM_UNROLL_ITER)\n"
"#define localACol (localSerial % NUM_UNROLL_ITER)\n"
"#define localAStride (WG_NUM_ROWS*WG_NUM_COLS/NUM_UNROLL_ITER)\n"
"#define localBRow ( localSerial % NUM_UNROLL_ITER )\n"
"#define localBCol ( localSerial / NUM_UNROLL_ITER )\n"
"#define localBStride (WG_NUM_ROWS*WG_NUM_COLS/NUM_UNROLL_ITER)\n"
" __local DATA_TYPE_STR *lA = localA + GET_LOCAL_INDEX_A(localARow, localACol);\n"
" __local DATA_TYPE_STR *lB = localB + GET_LOCAL_INDEX_B(localBRow, localBCol);\n"
" barrier(CLK_LOCAL_MEM_FENCE);\n"
"\n"
" /* load global -> local */\n"
" lA[ 0*localAStride ] = ( globalARow(0) >= M) ? 0.0 : A[ GET_GLOBAL_INDEX_A( globalARow(0), globalACol(0) ) ];\n"
" lA[ 1*localAStride ] = ( globalARow(1) >= M) ? 0.0 : A[ GET_GLOBAL_INDEX_A( globalARow(1), globalACol(1) ) ];\n"
" if ( localSerial + 2*WG_NUM_ROWS*WG_NUM_COLS < (WG_NUM_ROWS*MICRO_TILE_NUM_ROWS*NUM_UNROLL_ITER) ) {\n"
" lA[ 2*localAStride ] = ( globalARow(2) >= M) ? 0.0 : A[ GET_GLOBAL_INDEX_A( globalARow(2), globalACol(2) ) ];\n"
" }\n"
" lB[ 0*localBStride ] = ( globalBCol(0) >= N) ? 0.0 : B[ GET_GLOBAL_INDEX_B( globalBRow(0), globalBCol(0) ) ];\n"
" lB[ 1*localBStride ] = ( globalBCol(1) >= N) ? 0.0 : B[ GET_GLOBAL_INDEX_B( globalBRow(1), globalBCol(1) ) ];\n"
" if ( localSerial + 2*WG_NUM_ROWS*WG_NUM_COLS < (WG_NUM_COLS*MICRO_TILE_NUM_COLS*NUM_UNROLL_ITER) ) {\n"
" lB[ 2*localBStride ] = (globalBCol(2) >= N) ? 0.0 : B[ GET_GLOBAL_INDEX_B( globalBRow(2), globalBCol(2) ) ];\n"
" }\n"
" barrier(CLK_LOCAL_MEM_FENCE);\n"
" uint offA = localRow;\n"
" uint offB = localCol;\n"
"\n"
" /* do mads */\n"
" MICRO_TILE\n"
" MICRO_TILE\n"
" MICRO_TILE\n"
" MICRO_TILE\n"
" MICRO_TILE\n"
" MICRO_TILE\n"
" MICRO_TILE\n"
" MICRO_TILE\n"
"\n"
" /* shift to next k block */\n"
" A += NUM_UNROLL_ITER;\n"
" B += NUM_UNROLL_ITER;\n"
"\n"
" } while (--block_k > 0);\n"
"\n"
"\n"
" /* which global Cij index */\n"
" uint globalCRow = groupRow * MACRO_TILE_NUM_ROWS + localRow;\n"
" uint globalCCol = groupCol * MACRO_TILE_NUM_COLS + localCol;\n"
"\n"
" /* write global Cij */\n"
" if (globalCRow+0*WG_NUM_ROWS < M) if (globalCCol+0*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[0][0], beta )}\n"
" if (globalCRow+0*WG_NUM_ROWS < M) if (globalCCol+1*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+1*WG_NUM_COLS) ], alpha, rC[0][1], beta )}\n"
" if (globalCRow+0*WG_NUM_ROWS < M) if (globalCCol+2*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+2*WG_NUM_COLS) ], alpha, rC[0][2], beta )}\n"
" if (globalCRow+0*WG_NUM_ROWS < M) if (globalCCol+3*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+3*WG_NUM_COLS) ], alpha, rC[0][3], beta )}\n"
" if (globalCRow+0*WG_NUM_ROWS < M) if (globalCCol+4*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+0*WG_NUM_ROWS, globalCCol+4*WG_NUM_COLS) ], alpha, rC[0][4], beta )}\n"
" if (globalCRow+1*WG_NUM_ROWS < M) if (globalCCol+0*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+1*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[1][0], beta )}\n"
" if (globalCRow+1*WG_NUM_ROWS < M) if (globalCCol+1*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+1*WG_NUM_ROWS, globalCCol+1*WG_NUM_COLS) ], alpha, rC[1][1], beta )}\n"
" if (globalCRow+1*WG_NUM_ROWS < M) if (globalCCol+2*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+1*WG_NUM_ROWS, globalCCol+2*WG_NUM_COLS) ], alpha, rC[1][2], beta )}\n"
" if (globalCRow+1*WG_NUM_ROWS < M) if (globalCCol+3*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+1*WG_NUM_ROWS, globalCCol+3*WG_NUM_COLS) ], alpha, rC[1][3], beta )}\n"
" if (globalCRow+1*WG_NUM_ROWS < M) if (globalCCol+4*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+1*WG_NUM_ROWS, globalCCol+4*WG_NUM_COLS) ], alpha, rC[1][4], beta )}\n"
" if (globalCRow+2*WG_NUM_ROWS < M) if (globalCCol+0*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+2*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[2][0], beta )}\n"
" if (globalCRow+2*WG_NUM_ROWS < M) if (globalCCol+1*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+2*WG_NUM_ROWS, globalCCol+1*WG_NUM_COLS) ], alpha, rC[2][1], beta )}\n"
" if (globalCRow+2*WG_NUM_ROWS < M) if (globalCCol+2*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+2*WG_NUM_ROWS, globalCCol+2*WG_NUM_COLS) ], alpha, rC[2][2], beta )}\n"
" if (globalCRow+2*WG_NUM_ROWS < M) if (globalCCol+3*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+2*WG_NUM_ROWS, globalCCol+3*WG_NUM_COLS) ], alpha, rC[2][3], beta )}\n"
" if (globalCRow+2*WG_NUM_ROWS < M) if (globalCCol+4*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+2*WG_NUM_ROWS, globalCCol+4*WG_NUM_COLS) ], alpha, rC[2][4], beta )}\n"
" if (globalCRow+3*WG_NUM_ROWS < M) if (globalCCol+0*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+3*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[3][0], beta )}\n"
" if (globalCRow+3*WG_NUM_ROWS < M) if (globalCCol+1*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+3*WG_NUM_ROWS, globalCCol+1*WG_NUM_COLS) ], alpha, rC[3][1], beta )}\n"
" if (globalCRow+3*WG_NUM_ROWS < M) if (globalCCol+2*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+3*WG_NUM_ROWS, globalCCol+2*WG_NUM_COLS) ], alpha, rC[3][2], beta )}\n"
" if (globalCRow+3*WG_NUM_ROWS < M) if (globalCCol+3*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+3*WG_NUM_ROWS, globalCCol+3*WG_NUM_COLS) ], alpha, rC[3][3], beta )}\n"
" if (globalCRow+3*WG_NUM_ROWS < M) if (globalCCol+4*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+3*WG_NUM_ROWS, globalCCol+4*WG_NUM_COLS) ], alpha, rC[3][4], beta )}\n"
" if (globalCRow+4*WG_NUM_ROWS < M) if (globalCCol+0*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+4*WG_NUM_ROWS, globalCCol+0*WG_NUM_COLS) ], alpha, rC[4][0], beta )}\n"
" if (globalCRow+4*WG_NUM_ROWS < M) if (globalCCol+1*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+4*WG_NUM_ROWS, globalCCol+1*WG_NUM_COLS) ], alpha, rC[4][1], beta )}\n"
" if (globalCRow+4*WG_NUM_ROWS < M) if (globalCCol+2*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+4*WG_NUM_ROWS, globalCCol+2*WG_NUM_COLS) ], alpha, rC[4][2], beta )}\n"
" if (globalCRow+4*WG_NUM_ROWS < M) if (globalCCol+3*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+4*WG_NUM_ROWS, globalCCol+3*WG_NUM_COLS) ], alpha, rC[4][3], beta )}\n"
" if (globalCRow+4*WG_NUM_ROWS < M) if (globalCCol+4*WG_NUM_COLS < N){ TYPE_MAD_WRITE( C[ GET_GLOBAL_INDEX_C( globalCRow+4*WG_NUM_ROWS, globalCCol+4*WG_NUM_COLS) ], alpha, rC[4][4], beta )}\n"
"\n"
"}\n"
"";
#else
#endif
| [
"glen.johnson@gaj-geospatial.com"
] | glen.johnson@gaj-geospatial.com |
47dc44ded13db14126bef403fe5a40e4e7b3a3ff | 879681c994f1ca9c8d2c905a4e5064997ad25a27 | /root-2.3.0/run/tutorials/multiphase/twoPhaseEulerFoam/RAS/fluidisedBed/1.46/pMean | 21aebe0667ba65d0dd6ffc1074b67c028707417a | [] | no_license | MizuhaWatanabe/OpenFOAM-2.3.0-with-Ubuntu | 3828272d989d45fb020e83f8426b849e75560c62 | daeb870be81275e8a81f5cbac4ca1906a9bc69c0 | refs/heads/master | 2020-05-17T16:36:41.848261 | 2015-04-18T09:29:48 | 2015-04-18T09:29:48 | 34,159,882 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 46,374 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 2.3.0 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "1.46";
object pMean;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [1 -1 -2 0 0 0 0];
internalField nonuniform List<scalar>
6000
(
106354
106353
106352
106350
106349
106348
106349
106349
106349
106350
106351
106351
106351
106351
106352
106354
106355
106354
106354
106354
106353
106353
106352
106353
106354
106356
106358
106358
106359
106360
106285
106284
106282
106280
106279
106279
106279
106278
106278
106279
106280
106279
106279
106279
106280
106282
106283
106283
106283
106282
106282
106281
106280
106279
106281
106283
106286
106287
106288
106290
106235
106234
106233
106231
106231
106231
106230
106230
106231
106232
106232
106232
106231
106230
106231
106233
106235
106236
106236
106236
106235
106232
106230
106229
106231
106233
106236
106237
106237
106238
106182
106180
106178
106179
106179
106179
106179
106179
106180
106181
106181
106181
106180
106180
106181
106183
106186
106187
106187
106186
106184
106181
106178
106177
106178
106180
106182
106183
106182
106183
106127
106126
106124
106125
106126
106127
106127
106128
106130
106130
106130
106130
106129
106131
106133
106135
106137
106138
106137
106135
106133
106130
106128
106126
106126
106126
106128
106128
106128
106129
106073
106072
106071
106071
106072
106074
106076
106077
106078
106079
106079
106079
106081
106084
106086
106088
106089
106088
106086
106084
106082
106080
106078
106075
106073
106072
106072
106073
106073
106075
106019
106018
106018
106017
106019
106023
106025
106027
106027
106028
106029
106031
106034
106037
106040
106040
106038
106037
106036
106034
106032
106030
106027
106024
106021
106018
106017
106018
106020
106023
105966
105965
105964
105964
105968
105973
105976
105977
105978
105978
105980
105983
105987
105990
105991
105990
105987
105986
105985
105983
105981
105979
105977
105975
105971
105968
105966
105967
105970
105973
105914
105912
105911
105913
105918
105924
105928
105930
105930
105930
105932
105936
105939
105941
105941
105939
105937
105935
105934
105933
105932
105931
105930
105927
105924
105920
105919
105920
105924
105927
105863
105861
105860
105863
105869
105876
105881
105884
105884
105883
105885
105889
105891
105891
105891
105889
105887
105886
105886
105885
105885
105884
105883
105880
105877
105874
105874
105877
105881
105884
105813
105811
105811
105815
105820
105827
105834
105838
105838
105837
105839
105842
105843
105842
105841
105840
105839
105839
105838
105838
105838
105837
105836
105834
105831
105830
105831
105835
105840
105843
105766
105764
105764
105767
105772
105779
105787
105791
105792
105791
105792
105793
105794
105794
105793
105792
105793
105793
105792
105791
105791
105790
105788
105786
105786
105786
105789
105794
105799
105802
105720
105719
105719
105721
105725
105732
105739
105744
105745
105745
105744
105745
105745
105746
105746
105746
105746
105746
105745
105744
105743
105741
105739
105738
105739
105742
105746
105752
105758
105761
105677
105676
105676
105677
105680
105686
105692
105696
105699
105698
105697
105696
105697
105699
105699
105700
105700
105699
105698
105697
105695
105692
105689
105688
105691
105695
105701
105708
105714
105717
105634
105634
105634
105634
105637
105641
105646
105650
105653
105653
105650
105649
105650
105652
105653
105654
105654
105652
105651
105648
105645
105641
105638
105637
105640
105646
105654
105660
105665
105668
105592
105592
105592
105593
105594
105597
105600
105604
105607
105607
105605
105603
105604
105606
105607
105608
105607
105606
105604
105600
105597
105593
105590
105589
105592
105597
105604
105610
105614
105616
105551
105551
105552
105552
105552
105554
105556
105559
105562
105562
105560
105558
105558
105560
105561
105562
105561
105560
105558
105555
105551
105547
105544
105544
105546
105551
105556
105560
105563
105565
105510
105511
105511
105512
105511
105512
105513
105515
105517
105518
105516
105514
105513
105514
105515
105516
105516
105515
105513
105510
105506
105502
105500
105500
105502
105505
105509
105512
105514
105516
105469
105470
105470
105471
105470
105470
105471
105471
105472
105474
105473
105471
105470
105470
105470
105470
105470
105470
105468
105465
105461
105457
105455
105455
105457
105459
105462
105464
105465
105467
105427
105427
105428
105429
105429
105428
105428
105428
105428
105429
105429
105428
105427
105426
105426
105425
105425
105424
105423
105419
105416
105413
105412
105411
105412
105414
105416
105417
105418
105420
105384
105384
105385
105386
105386
105386
105385
105385
105384
105384
105384
105384
105383
105382
105381
105380
105379
105379
105377
105374
105371
105369
105368
105368
105368
105369
105370
105372
105373
105374
105340
105340
105342
105342
105343
105343
105342
105341
105340
105340
105340
105341
105340
105339
105338
105336
105335
105334
105331
105328
105326
105326
105325
105324
105324
105324
105326
105328
105329
105329
105296
105297
105298
105299
105300
105300
105299
105297
105296
105296
105297
105297
105297
105297
105295
105292
105290
105289
105286
105283
105281
105281
105281
105280
105280
105280
105282
105284
105284
105284
105252
105252
105254
105256
105257
105257
105256
105254
105254
105254
105254
105255
105255
105254
105252
105249
105247
105244
105240
105237
105235
105235
105235
105235
105235
105235
105237
105239
105239
105238
105209
105209
105210
105213
105215
105214
105212
105211
105211
105212
105212
105212
105212
105211
105209
105207
105203
105199
105195
105191
105188
105188
105188
105189
105189
105190
105191
105192
105191
105190
105166
105166
105167
105170
105171
105171
105169
105168
105169
105169
105170
105170
105170
105168
105166
105164
105159
105154
105149
105145
105143
105142
105142
105142
105142
105143
105143
105143
105141
105140
105124
105124
105125
105126
105128
105127
105126
105126
105126
105127
105128
105128
105127
105125
105123
105120
105115
105110
105105
105102
105099
105098
105098
105097
105096
105095
105095
105093
105092
105091
105082
105082
105082
105083
105083
105083
105082
105083
105083
105085
105086
105085
105084
105081
105079
105076
105071
105067
105063
105060
105057
105056
105055
105054
105052
105051
105049
105047
105045
105044
105039
105039
105039
105039
105039
105039
105039
105039
105040
105041
105042
105042
105040
105037
105034
105031
105028
105026
105022
105018
105015
105014
105013
105011
105008
105006
105004
105001
104999
104998
104997
104995
104995
104994
104994
104995
104995
104995
104996
104998
104999
104998
104996
104993
104990
104988
104986
104984
104981
104976
104973
104971
104969
104966
104963
104961
104958
104956
104954
104953
104955
104953
104952
104950
104951
104951
104952
104952
104953
104954
104955
104955
104953
104950
104947
104945
104943
104942
104938
104933
104929
104926
104924
104920
104918
104915
104913
104910
104908
104908
104912
104911
104909
104908
104908
104909
104909
104909
104910
104911
104912
104912
104910
104907
104904
104902
104900
104899
104895
104890
104885
104882
104878
104875
104872
104870
104867
104865
104863
104863
104870
104869
104867
104867
104867
104868
104868
104868
104869
104870
104870
104870
104868
104866
104863
104860
104857
104855
104851
104845
104841
104837
104833
104830
104827
104825
104823
104821
104819
104819
104827
104826
104825
104825
104825
104826
104827
104827
104828
104828
104829
104828
104827
104825
104821
104817
104814
104811
104806
104801
104797
104793
104789
104786
104785
104783
104780
104778
104776
104775
104783
104783
104783
104783
104784
104785
104786
104787
104787
104788
104787
104787
104785
104783
104779
104775
104771
104767
104762
104757
104754
104750
104746
104744
104744
104741
104739
104736
104733
104732
104740
104739
104740
104741
104743
104744
104746
104746
104747
104746
104746
104745
104743
104740
104737
104732
104728
104723
104718
104714
104711
104707
104705
104704
104703
104700
104697
104693
104690
104690
104696
104696
104697
104699
104701
104703
104705
104706
104705
104705
104704
104702
104700
104697
104693
104689
104684
104680
104675
104671
104668
104666
104665
104664
104662
104658
104653
104649
104647
104647
104653
104654
104654
104656
104659
104662
104664
104664
104664
104662
104661
104660
104657
104654
104650
104646
104641
104637
104633
104629
104626
104624
104624
104624
104621
104615
104610
104606
104604
104604
104611
104612
104612
104614
104616
104620
104623
104623
104621
104620
104619
104617
104614
104611
104607
104603
104599
104594
104590
104587
104584
104583
104584
104582
104578
104572
104567
104563
104562
104562
104570
104570
104570
104571
104574
104578
104581
104580
104579
104577
104576
104574
104572
104569
104565
104561
104557
104552
104548
104545
104543
104542
104542
104540
104535
104529
104524
104521
104520
104520
104528
104528
104528
104529
104532
104535
104538
104538
104536
104534
104533
104531
104529
104526
104522
104518
104514
104509
104506
104503
104501
104501
104501
104498
104492
104486
104482
104479
104478
104478
104486
104486
104486
104488
104490
104493
104495
104495
104494
104492
104490
104489
104486
104483
104480
104476
104472
104467
104463
104461
104459
104459
104458
104455
104450
104445
104441
104438
104437
104437
104444
104443
104444
104446
104448
104451
104453
104453
104451
104449
104447
104445
104443
104440
104437
104433
104429
104425
104421
104419
104418
104417
104416
104412
104408
104403
104400
104397
104396
104396
104401
104401
104402
104404
104407
104409
104410
104409
104408
104406
104404
104402
104399
104396
104393
104389
104386
104382
104379
104377
104376
104375
104373
104370
104366
104362
104359
104357
104355
104355
104359
104360
104361
104363
104365
104366
104367
104366
104365
104362
104361
104358
104355
104352
104349
104345
104342
104339
104336
104335
104335
104333
104330
104327
104324
104321
104318
104316
104315
104314
104319
104319
104320
104322
104323
104324
104324
104323
104321
104319
104317
104314
104311
104307
104304
104301
104298
104295
104293
104293
104292
104290
104287
104285
104282
104280
104277
104275
104274
104274
104278
104279
104280
104281
104282
104281
104281
104279
104277
104275
104272
104269
104266
104262
104259
104256
104254
104252
104250
104249
104249
104247
104245
104243
104240
104238
104235
104234
104233
104233
104238
104238
104239
104240
104239
104239
104237
104235
104233
104230
104226
104223
104220
104216
104214
104211
104209
104207
104206
104205
104204
104203
104201
104200
104197
104195
104193
104192
104192
104192
104197
104197
104198
104197
104197
104195
104193
104190
104186
104182
104178
104175
104173
104170
104168
104166
104164
104162
104161
104161
104160
104159
104157
104156
104153
104151
104150
104150
104150
104150
104155
104155
104155
104154
104153
104151
104147
104143
104138
104133
104129
104127
104124
104123
104121
104120
104119
104118
104117
104117
104115
104114
104112
104111
104108
104106
104106
104106
104106
104106
104112
104112
104111
104109
104107
104104
104100
104094
104087
104082
104080
104078
104076
104076
104075
104074
104073
104073
104073
104073
104071
104068
104066
104064
104062
104061
104061
104062
104062
104062
104067
104066
104064
104062
104059
104056
104051
104043
104036
104032
104030
104029
104029
104029
104029
104029
104028
104029
104029
104029
104026
104022
104019
104017
104016
104015
104015
104016
104017
104017
104018
104016
104014
104012
104010
104006
104001
103993
103986
103983
103982
103983
103984
103984
103983
103983
103983
103984
103985
103983
103979
103975
103972
103970
103969
103969
103969
103971
103971
103970
103967
103966
103964
103962
103960
103957
103951
103944
103939
103937
103937
103938
103939
103939
103939
103938
103938
103939
103938
103936
103932
103928
103924
103923
103922
103922
103923
103924
103924
103924
103918
103916
103915
103913
103911
103908
103904
103898
103895
103894
103895
103895
103895
103895
103894
103893
103892
103891
103890
103888
103884
103880
103877
103876
103876
103876
103877
103878
103877
103877
103869
103869
103868
103866
103864
103862
103859
103855
103854
103853
103853
103853
103852
103852
103850
103849
103846
103843
103841
103839
103835
103833
103831
103830
103830
103830
103831
103831
103830
103830
103824
103824
103823
103821
103820
103818
103816
103814
103813
103812
103812
103811
103810
103808
103806
103804
103800
103795
103792
103791
103788
103786
103785
103784
103784
103784
103784
103784
103783
103783
103781
103780
103779
103778
103777
103776
103775
103774
103772
103771
103771
103770
103768
103766
103763
103759
103754
103750
103746
103745
103743
103741
103740
103740
103739
103739
103738
103737
103737
103737
103739
103737
103736
103735
103734
103735
103735
103734
103733
103731
103730
103728
103726
103723
103719
103715
103710
103707
103704
103702
103700
103698
103697
103696
103695
103693
103691
103690
103690
103690
103696
103694
103693
103692
103692
103694
103695
103695
103693
103691
103689
103687
103684
103680
103677
103672
103668
103665
103663
103660
103657
103656
103655
103653
103651
103648
103646
103644
103644
103645
103652
103651
103651
103650
103650
103653
103654
103654
103653
103651
103648
103645
103641
103638
103634
103631
103627
103624
103622
103618
103616
103615
103613
103611
103608
103604
103601
103599
103599
103600
103608
103607
103607
103607
103608
103611
103613
103613
103612
103609
103606
103603
103599
103596
103593
103589
103586
103583
103580
103576
103574
103573
103571
103568
103565
103561
103557
103556
103556
103556
103562
103562
103562
103563
103564
103567
103570
103570
103570
103568
103564
103561
103557
103554
103551
103548
103544
103541
103538
103534
103532
103531
103528
103525
103522
103518
103514
103513
103513
103513
103515
103516
103516
103518
103520
103522
103525
103526
103526
103525
103521
103518
103514
103511
103508
103505
103502
103498
103495
103492
103489
103487
103484
103481
103478
103474
103471
103471
103470
103470
103468
103468
103469
103471
103473
103475
103478
103479
103480
103479
103476
103473
103470
103467
103464
103461
103458
103455
103452
103449
103446
103443
103439
103436
103433
103430
103427
103426
103426
103425
103420
103420
103421
103423
103425
103427
103429
103431
103431
103431
103429
103426
103423
103421
103419
103416
103413
103410
103408
103405
103401
103397
103393
103390
103387
103383
103381
103380
103379
103379
103372
103372
103372
103374
103375
103377
103379
103380
103381
103380
103379
103377
103374
103372
103371
103369
103367
103365
103362
103359
103354
103350
103346
103342
103339
103336
103334
103332
103331
103331
103324
103323
103323
103324
103325
103327
103328
103329
103329
103329
103328
103326
103323
103321
103321
103320
103319
103318
103315
103311
103306
103301
103297
103293
103291
103288
103285
103283
103283
103283
103276
103275
103275
103274
103275
103276
103277
103276
103276
103275
103274
103273
103271
103269
103269
103269
103269
103268
103265
103261
103256
103251
103247
103244
103242
103239
103237
103235
103233
103233
103228
103227
103226
103225
103225
103225
103225
103224
103222
103221
103220
103218
103216
103215
103216
103217
103217
103217
103214
103209
103204
103200
103197
103195
103193
103191
103188
103186
103184
103184
103180
103179
103178
103177
103176
103175
103173
103171
103168
103166
103164
103162
103161
103160
103161
103163
103164
103163
103160
103156
103151
103149
103147
103146
103145
103143
103141
103138
103136
103136
103129
103130
103129
103127
103126
103124
103121
103117
103113
103109
103106
103105
103104
103104
103106
103108
103109
103109
103106
103102
103099
103097
103097
103098
103098
103097
103094
103091
103089
103089
103077
103078
103077
103076
103074
103071
103068
103063
103057
103051
103048
103047
103047
103049
103051
103053
103054
103054
103051
103048
103046
103045
103047
103050
103051
103050
103049
103046
103044
103044
103022
103023
103023
103022
103020
103018
103014
103008
103001
102995
102993
102992
102993
102995
102997
102999
103000
103000
102997
102995
102993
102994
102998
103002
103004
103005
103004
103002
103000
102999
102966
102967
102967
102966
102964
102962
102958
102953
102946
102942
102940
102940
102941
102944
102946
102948
102948
102947
102945
102942
102941
102943
102948
102953
102957
102960
102960
102959
102957
102956
102910
102910
102910
102909
102908
102906
102902
102897
102893
102891
102890
102891
102893
102895
102897
102898
102897
102896
102894
102891
102890
102892
102897
102904
102909
102913
102915
102915
102914
102912
102854
102854
102854
102853
102852
102850
102847
102843
102841
102841
102842
102843
102845
102847
102849
102849
102849
102847
102844
102841
102840
102841
102847
102854
102860
102865
102868
102869
102868
102867
102799
102799
102799
102798
102797
102796
102794
102792
102792
102793
102794
102796
102799
102801
102802
102803
102802
102800
102796
102793
102792
102794
102798
102804
102811
102815
102818
102820
102821
102819
102746
102746
102746
102745
102744
102744
102744
102744
102744
102746
102749
102751
102753
102755
102756
102757
102756
102753
102750
102748
102747
102749
102751
102756
102761
102766
102768
102769
102770
102770
102694
102694
102694
102694
102694
102694
102695
102697
102699
102702
102704
102707
102709
102710
102710
102710
102709
102707
102705
102703
102703
102705
102707
102709
102713
102716
102718
102718
102719
102720
102642
102642
102642
102643
102644
102645
102647
102650
102654
102657
102660
102662
102663
102663
102663
102662
102661
102660
102659
102658
102659
102661
102662
102663
102665
102668
102669
102669
102668
102668
102591
102590
102591
102593
102595
102596
102598
102602
102607
102611
102614
102615
102615
102615
102615
102614
102613
102612
102612
102613
102614
102616
102618
102618
102618
102619
102620
102619
102618
102618
102539
102539
102540
102543
102546
102547
102550
102554
102559
102563
102566
102567
102568
102568
102567
102566
102565
102565
102565
102566
102569
102571
102572
102572
102571
102570
102570
102570
102568
102567
102487
102487
102489
102492
102495
102498
102502
102506
102510
102514
102517
102519
102520
102520
102519
102518
102518
102517
102518
102520
102522
102524
102525
102524
102522
102521
102520
102519
102517
102517
102435
102436
102438
102441
102444
102447
102452
102456
102460
102464
102467
102469
102471
102472
102472
102471
102470
102470
102472
102473
102474
102475
102475
102474
102473
102471
102469
102467
102466
102465
102383
102384
102386
102389
102392
102395
102399
102404
102409
102413
102416
102419
102421
102422
102423
102422
102422
102423
102424
102425
102425
102425
102426
102425
102423
102421
102419
102416
102415
102414
102331
102332
102334
102337
102339
102342
102346
102352
102357
102361
102364
102368
102370
102372
102373
102373
102374
102375
102375
102375
102375
102376
102376
102375
102373
102371
102369
102366
102365
102363
102278
102280
102282
102284
102286
102288
102293
102299
102305
102309
102313
102316
102319
102321
102323
102324
102325
102325
102325
102325
102326
102326
102326
102325
102323
102321
102319
102316
102314
102313
102225
102226
102228
102230
102232
102234
102240
102247
102253
102258
102262
102265
102268
102270
102273
102274
102274
102274
102274
102275
102276
102276
102276
102275
102273
102271
102268
102266
102264
102263
102171
102172
102173
102175
102177
102181
102187
102194
102200
102206
102210
102213
102216
102218
102220
102222
102222
102222
102223
102225
102227
102228
102227
102226
102224
102221
102218
102215
102213
102212
102116
102117
102118
102120
102123
102129
102135
102142
102148
102153
102157
102160
102163
102165
102167
102168
102169
102170
102173
102176
102179
102180
102179
102177
102175
102172
102168
102165
102163
102162
102062
102062
102063
102066
102071
102078
102084
102090
102096
102100
102104
102107
102109
102111
102113
102115
102116
102119
102123
102127
102130
102132
102131
102129
102125
102122
102118
102116
102114
102113
102007
102008
102009
102013
102019
102026
102033
102038
102043
102047
102050
102053
102055
102057
102059
102062
102064
102067
102072
102076
102079
102081
102081
102079
102075
102071
102068
102066
102065
102065
101953
101954
101956
101960
101966
101973
101980
101985
101990
101993
101996
101998
102001
102003
102006
102008
102011
102015
102020
102024
102027
102029
102029
102027
102024
102021
102018
102017
102016
102016
101900
101901
101902
101906
101912
101919
101926
101932
101936
101939
101941
101943
101945
101948
101951
101954
101958
101962
101967
101971
101975
101976
101976
101975
101973
101970
101968
101966
101966
101967
101847
101847
101848
101852
101857
101865
101872
101877
101882
101885
101887
101888
101889
101891
101894
101898
101903
101908
101914
101919
101922
101924
101924
101923
101922
101919
101917
101915
101915
101915
101793
101793
101795
101798
101804
101811
101817
101823
101828
101831
101832
101833
101834
101834
101837
101841
101847
101853
101860
101865
101869
101871
101871
101871
101870
101867
101865
101863
101862
101861
101740
101740
101742
101745
101752
101758
101765
101770
101775
101777
101779
101780
101780
101780
101781
101785
101791
101798
101805
101811
101815
101817
101818
101818
101817
101814
101811
101808
101806
101805
101688
101688
101690
101695
101701
101707
101713
101718
101723
101725
101727
101728
101728
101728
101728
101731
101735
101742
101749
101756
101760
101763
101764
101764
101763
101760
101755
101751
101748
101746
101639
101640
101643
101647
101653
101658
101664
101669
101673
101676
101677
101678
101678
101678
101679
101680
101682
101687
101695
101701
101706
101709
101710
101710
101708
101705
101699
101695
101690
101687
101593
101595
101598
101603
101608
101613
101618
101622
101626
101628
101630
101630
101631
101632
101632
101632
101633
101636
101642
101649
101654
101656
101657
101657
101654
101650
101645
101639
101634
101630
101549
101551
101554
101559
101564
101569
101573
101576
101579
101581
101582
101583
101584
101585
101586
101587
101587
101588
101592
101597
101601
101604
101605
101603
101600
101596
101590
101585
101580
101577
101506
101507
101511
101516
101521
101524
101528
101530
101532
101533
101535
101536
101537
101539
101540
101541
101541
101541
101543
101547
101550
101551
101552
101550
101547
101541
101536
101531
101527
101525
101462
101463
101467
101471
101476
101479
101481
101483
101485
101486
101487
101488
101489
101491
101493
101494
101494
101495
101495
101497
101499
101499
101499
101497
101493
101487
101481
101477
101476
101475
101418
101419
101422
101426
101429
101432
101434
101436
101438
101438
101438
101438
101439
101441
101443
101445
101446
101447
101447
101448
101448
101448
101447
101445
101441
101435
101430
101427
101426
101426
101373
101374
101376
101379
101382
101384
101386
101388
101390
101389
101388
101388
101388
101389
101391
101393
101395
101396
101398
101398
101398
101397
101396
101393
101389
101384
101381
101379
101378
101378
101327
101328
101330
101332
101335
101336
101338
101340
101340
101339
101337
101335
101335
101335
101337
101339
101341
101343
101346
101347
101346
101346
101345
101343
101340
101337
101335
101333
101332
101331
101281
101281
101283
101284
101286
101287
101288
101290
101289
101287
101284
101282
101281
101281
101283
101285
101287
101290
101292
101293
101295
101295
101294
101294
101293
101291
101290
101288
101287
101286
101235
101235
101235
101236
101237
101238
101238
101237
101236
101233
101231
101230
101229
101230
101231
101232
101235
101237
101238
101240
101243
101244
101245
101245
101245
101245
101244
101243
101242
101241
101189
101188
101188
101188
101188
101186
101184
101183
101181
101180
101179
101179
101180
101182
101183
101184
101185
101187
101188
101189
101192
101194
101196
101196
101197
101198
101199
101198
101197
101197
101142
101141
101139
101138
101136
101133
101130
101129
101129
101129
101130
101132
101134
101135
101137
101138
101139
101140
101141
101142
101143
101145
101147
101148
101148
101148
101150
101151
101151
101151
101094
101092
101090
101087
101084
101081
101079
101079
101080
101082
101084
101087
101089
101091
101093
101094
101095
101095
101096
101096
101096
101098
101100
101100
101100
101099
101100
101101
101103
101104
101044
101043
101040
101036
101034
101032
101031
101032
101035
101038
101041
101043
101046
101048
101050
101051
101052
101052
101051
101051
101050
101051
101053
101054
101053
101051
101050
101051
101052
101054
100993
100992
100990
100987
100986
100986
100987
100989
100992
100996
100998
101001
101004
101006
101008
101009
101009
101009
101007
101006
101005
101005
101007
101008
101007
101006
101004
101003
101003
101004
100944
100944
100942
100941
100942
100944
100946
100948
100952
100954
100957
100960
100962
100964
100966
100966
100966
100965
100964
100962
100960
100960
100961
100962
100962
100961
100960
100958
100957
100957
100897
100899
100898
100898
100900
100903
100906
100909
100912
100914
100916
100919
100920
100922
100923
100923
100923
100922
100920
100918
100916
100915
100915
100916
100917
100917
100916
100915
100913
100912
100856
100856
100856
100857
100860
100864
100867
100870
100872
100874
100876
100877
100878
100879
100880
100880
100879
100878
100876
100873
100871
100870
100869
100870
100871
100871
100871
100870
100868
100866
100816
100816
100815
100816
100820
100825
100828
100831
100833
100834
100835
100835
100836
100836
100836
100836
100834
100833
100830
100828
100826
100824
100822
100822
100823
100824
100824
100823
100822
100820
100775
100775
100775
100777
100780
100785
100789
100791
100793
100793
100793
100793
100793
100793
100792
100791
100789
100787
100784
100782
100780
100777
100775
100774
100774
100774
100775
100774
100773
100772
100734
100734
100735
100736
100739
100744
100748
100750
100751
100751
100751
100750
100750
100750
100749
100747
100744
100741
100739
100736
100733
100731
100728
100726
100725
100724
100724
100724
100723
100723
100692
100692
100693
100694
100696
100701
100705
100708
100709
100709
100709
100708
100707
100707
100705
100703
100700
100696
100694
100691
100688
100685
100682
100679
100677
100676
100675
100674
100674
100675
100651
100651
100652
100653
100654
100658
100662
100665
100666
100666
100666
100665
100665
100664
100662
100659
100656
100653
100650
100647
100645
100642
100638
100634
100631
100630
100629
100628
100628
100628
100610
100610
100610
100611
100613
100616
100619
100622
100623
100624
100624
100623
100623
100622
100620
100617
100614
100610
100607
100605
100602
100600
100596
100591
100589
100587
100586
100584
100584
100584
100571
100571
100571
100571
100572
100574
100577
100579
100581
100582
100583
100583
100582
100581
100579
100577
100573
100570
100567
100564
100562
100560
100556
100552
100549
100546
100545
100543
100542
100542
100533
100532
100532
100532
100532
100533
100536
100538
100540
100542
100543
100543
100543
100542
100540
100538
100535
100531
100528
100526
100524
100522
100518
100514
100510
100508
100506
100504
100503
100503
100496
100495
100494
100493
100493
100494
100495
100498
100501
100503
100505
100505
100505
100504
100503
100500
100498
100495
100492
100489
100487
100485
100482
100478
100474
100471
100468
100467
100466
100466
100459
100458
100456
100455
100455
100455
100457
100459
100462
100465
100467
100468
100468
100468
100466
100464
100462
100459
100456
100453
100451
100449
100447
100442
100438
100435
100433
100431
100430
100431
100423
100421
100420
100418
100417
100418
100420
100423
100426
100429
100431
100433
100433
100433
100432
100430
100427
100425
100422
100419
100416
100414
100412
100408
100404
100400
100398
100396
100396
100397
100387
100386
100384
100382
100382
100383
100385
100389
100393
100396
100398
100400
100400
100400
100399
100398
100395
100392
100389
100386
100383
100380
100378
100375
100370
100367
100365
100364
100363
100364
100352
100351
100350
100348
100349
100350
100353
100357
100362
100365
100368
100370
100370
100369
100369
100367
100365
100362
100358
100354
100351
100348
100346
100343
100339
100336
100334
100333
100332
100332
100319
100318
100318
100317
100318
100320
100323
100327
100332
100336
100339
100341
100341
100341
100340
100339
100337
100333
100329
100325
100320
100317
100315
100313
100310
100307
100305
100304
100302
100300
100288
100288
100288
100289
100290
100292
100295
100299
100304
100309
100312
100313
100314
100314
100313
100312
100310
100306
100302
100297
100292
100288
100285
100283
100282
100280
100278
100275
100272
100270
100261
100261
100261
100261
100263
100265
100268
100273
100278
100283
100286
100288
100289
100288
100288
100287
100284
100280
100276
100271
100266
100262
100257
100255
100253
100252
100249
100246
100243
100241
100235
100234
100234
100235
100237
100239
100243
100248
100253
100258
100261
100263
100264
100264
100264
100262
100260
100256
100251
100246
100241
100236
100232
100228
100225
100222
100219
100217
100215
100214
100209
100209
100209
100210
100212
100215
100219
100225
100230
100234
100238
100240
100241
100241
100241
100239
100236
100232
100228
100222
100217
100212
100207
100203
100198
100194
100191
100190
100190
100190
100185
100185
100186
100188
100190
100193
100198
100203
100208
100212
100215
100218
100219
100219
100219
100217
100214
100210
100205
100200
100195
100189
100184
100179
100174
100169
100166
100166
100167
100168
100164
100164
100165
100167
100170
100174
100178
100183
100188
100192
100195
100197
100198
100198
100198
100196
100193
100189
100185
100180
100174
100169
100163
100158
100152
100147
100145
100145
100146
100147
100145
100145
100147
100149
100152
100155
100160
100164
100169
100173
100176
100178
100179
100179
100178
100177
100174
100170
100166
100161
100156
100150
100145
100139
100134
100129
100126
100126
100127
100128
100128
100128
100130
100132
100135
100138
100142
100147
100152
100155
100158
100160
100161
100161
100160
100158
100156
100152
100148
100144
100139
100133
100128
100123
100117
100113
100111
100111
100111
100111
100113
100113
100114
100117
100120
100123
100126
100131
100135
100139
100141
100143
100144
100144
100143
100141
100139
100136
100132
100128
100123
100118
100113
100108
100104
100100
100098
100098
100097
100097
100100
100100
100101
100103
100106
100108
100111
100115
100119
100123
100126
100127
100128
100128
100127
100125
100124
100121
100117
100114
100109
100104
100100
100096
100092
100090
100088
100087
100086
100085
100089
100089
100089
100091
100092
100095
100097
100100
100104
100108
100111
100112
100113
100113
100112
100111
100109
100107
100104
100100
100096
100092
100088
100085
100082
100080
100078
100077
100076
100075
100079
100079
100079
100079
100081
100082
100084
100087
100091
100095
100097
100099
100100
100100
100099
100098
100096
100094
100091
100087
100084
100080
100078
100075
100072
100070
100068
100067
100066
100065
100069
100069
100069
100069
100070
100072
100073
100076
100079
100082
100085
100086
100087
100087
100087
100086
100084
100082
100079
100076
100073
100070
100067
100065
100062
100060
100059
100057
100056
100056
100060
100060
100059
100060
100061
100062
100064
100065
100068
100071
100073
100075
100075
100076
100075
100074
100072
100070
100068
100065
100062
100059
100057
100055
100052
100050
100049
100047
100047
100047
100051
100051
100051
100051
100052
100053
100055
100056
100058
100060
100062
100064
100064
100064
100064
100063
100061
100059
100057
100054
100052
100049
100047
100045
100043
100041
100039
100039
100038
100038
100043
100043
100043
100043
100044
100045
100047
100048
100050
100051
100053
100054
100054
100054
100053
100052
100051
100049
100046
100044
100042
100040
100038
100036
100034
100033
100031
100031
100030
100031
100036
100035
100035
100035
100037
100038
100040
100041
100042
100043
100044
100044
100044
100044
100043
100042
100040
100038
100036
100035
100033
100032
100030
100029
100027
100026
100024
100023
100023
100024
100029
100029
100029
100029
100030
100032
100033
100034
100035
100036
100036
100036
100036
100035
100034
100033
100031
100029
100028
100026
100025
100024
100023
100022
100021
100020
100018
100017
100017
100017
100023
100023
100023
100024
100025
100025
100026
100028
100029
100029
100030
100029
100029
100028
100027
100026
100025
100023
100021
100020
100019
100018
100018
100017
100016
100015
100014
100013
100012
100012
100018
100018
100018
100018
100019
100020
100021
100022
100023
100023
100024
100024
100024
100023
100022
100021
100020
100019
100017
100015
100014
100014
100013
100013
100012
100011
100010
100009
100009
100009
100013
100013
100013
100014
100014
100015
100016
100017
100018
100018
100019
100019
100019
100018
100018
100017
100016
100015
100013
100012
100011
100010
100010
100009
100009
100008
100007
100007
100006
100006
100009
100009
100009
100010
100011
100011
100012
100013
100014
100014
100015
100015
100015
100015
100014
100014
100013
100012
100011
100010
100009
100009
100008
100007
100007
100006
100006
100005
100005
100005
100006
100006
100007
100007
100008
100008
100009
100010
100010
100011
100011
100012
100012
100012
100011
100011
100010
100010
100009
100008
100008
100007
100007
100006
100006
100005
100005
100004
100004
100004
100004
100005
100005
100006
100006
100007
100007
100008
100008
100009
100009
100009
100009
100009
100009
100009
100008
100008
100008
100007
100007
100006
100006
100005
100005
100005
100004
100004
100004
100004
100003
100004
100004
100005
100005
100005
100006
100006
100007
100007
100007
100008
100008
100008
100008
100007
100007
100007
100006
100006
100006
100005
100005
100005
100004
100004
100004
100004
100004
100004
100003
100003
100003
100004
100004
100005
100005
100005
100006
100006
100006
100006
100006
100006
100006
100006
100006
100006
100005
100005
100005
100005
100004
100004
100004
100004
100004
100004
100003
100003
100002
100002
100003
100003
100003
100004
100004
100004
100005
100005
100005
100005
100005
100005
100005
100005
100005
100005
100005
100005
100004
100004
100004
100004
100003
100003
100003
100003
100003
100003
100002
100002
100002
100002
100003
100003
100003
100004
100004
100004
100004
100004
100004
100004
100004
100004
100004
100004
100004
100004
100004
100004
100003
100003
100003
100003
100003
100003
100003
100003
100002
100002
100002
100002
100002
100002
100003
100003
100003
100003
100003
100003
100004
100004
100004
100004
100004
100004
100003
100003
100003
100003
100003
100003
100003
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100003
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100002
100002
100002
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
)
;
boundaryField
{
inlet
{
type calculated;
value nonuniform List<scalar>
30
(
106354
106353
106352
106350
106349
106349
106349
106349
106349
106351
106351
106351
106351
106351
106352
106354
106355
106354
106354
106354
106353
106353
106352
106353
106354
106356
106358
106359
106359
106360
)
;
}
outlet
{
type calculated;
value uniform 100000;
}
walls
{
type calculated;
value nonuniform List<scalar>
400
(
106354
106285
106235
106182
106127
106073
106019
105966
105914
105863
105813
105766
105720
105677
105634
105592
105551
105510
105469
105427
105384
105340
105296
105252
105209
105166
105124
105082
105039
104997
104955
104912
104870
104827
104783
104740
104696
104653
104611
104570
104528
104486
104444
104401
104359
104319
104278
104238
104197
104155
104112
104067
104018
103967
103918
103869
103824
103781
103739
103696
103652
103608
103562
103515
103468
103420
103372
103324
103276
103228
103180
103129
103077
103022
102966
102910
102854
102799
102746
102694
102642
102591
102539
102487
102435
102383
102331
102278
102225
102171
102116
102062
102007
101953
101900
101847
101793
101740
101688
101639
101593
101549
101506
101462
101418
101373
101327
101281
101235
101189
101142
101094
101044
100993
100944
100897
100856
100816
100775
100734
100692
100651
100610
100571
100533
100496
100459
100423
100387
100352
100319
100288
100261
100235
100209
100185
100164
100145
100128
100113
100100
100089
100079
100069
100060
100051
100043
100036
100029
100023
100018
100013
100009
100006
100004
100003
100003
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
106360
106290
106238
106183
106129
106075
106023
105973
105927
105884
105843
105802
105761
105717
105668
105616
105565
105516
105467
105420
105374
105329
105284
105238
105190
105140
105091
105044
104998
104953
104908
104863
104819
104775
104732
104690
104647
104604
104562
104520
104478
104437
104396
104355
104314
104274
104233
104192
104150
104106
104062
104017
103970
103924
103877
103830
103783
103737
103690
103645
103600
103556
103513
103470
103425
103379
103331
103283
103233
103184
103136
103089
103044
102999
102956
102912
102867
102819
102770
102720
102668
102618
102567
102517
102465
102414
102363
102313
102263
102212
102162
102113
102065
102016
101967
101915
101861
101805
101746
101687
101630
101577
101525
101475
101426
101378
101331
101286
101241
101197
101151
101104
101054
101004
100957
100912
100866
100820
100772
100723
100675
100628
100584
100542
100503
100466
100431
100397
100364
100332
100300
100270
100241
100214
100190
100168
100147
100128
100111
100097
100085
100075
100065
100056
100047
100038
100031
100024
100017
100012
100009
100006
100005
100004
100004
100004
100003
100003
100003
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100002
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100001
100000
100000
100000
100000
100000
100000
100000
100000
100000
100000
)
;
}
frontAndBackPlanes
{
type empty;
}
}
// ************************************************************************* //
| [
"mizuha.watanabe@gmail.com"
] | mizuha.watanabe@gmail.com | |
169b0fbfeb036b7821c54f5daabd6644205b701e | 097007b435b1bf420a19ce33aabee32f0789f145 | /leetcode/nth_tribonacci_number.cpp | 977ba0903352dbf37d4328df1c1097d76adcf755 | [] | no_license | Anshit01/Competitive-Programming | 71f84a85dde49278f8c3318d00db70616d8ea470 | 13911ec7f622abc061fea1ccc1f35d34118641f7 | refs/heads/master | 2023-06-11T12:06:11.722865 | 2021-06-30T11:51:01 | 2021-06-30T11:51:01 | 266,321,296 | 5 | 2 | null | 2020-10-19T09:47:06 | 2020-05-23T11:21:40 | C++ | UTF-8 | C++ | false | false | 725 | cpp | #include <bits/stdc++.h>
#define ll long long
#define f(i, x, n) for(int i = x; i < n; i++)
#define dbg(x) cout << x << endl
#define dbg2(x, y) cout << x << " " << y << endl
#define dbg3(x, y, z) cout << x << " " << y << " " << z << endl
#define mod 1000000007
using namespace std;
int tribonacci(int n) {
if(n == 0) return 0;
if(n == 1) return 1;
int n0 = 0, n1 = 1, n2 = 1;
int tmp;
for(int i = 3; i <= n; i++){
int tmp1 = n2, tmp0 = n1;
n2 += n1 + n0;
n1 = tmp1;
n0 = tmp0;
}
return n2;
}
int main(){
ios::sync_with_stdio(0);
cin.tie(NULL);
int t, n;
cin >> t;
while(t--){
cin >> n;
cout << tribonacci(n) << endl;
}
} | [
"bhardwaj.anshit1379@gmail.com"
] | bhardwaj.anshit1379@gmail.com |
ff8e476da5ef901e90c9e8cd1edafd1d0e76be04 | 96445444ff06432651f98d8c0c11e614ab2653a6 | /debug/moc_client.cpp | cfb79592438c511188edff562a75c436203f35b4 | [] | no_license | mladja777/mrkrmqtemailsystem | 3eb26d707c0f2cdb2472e7157472cc63b7e07db8 | c328384d0ffb9a5c9b1b218c445094851becbbdc | refs/heads/master | 2020-04-12T04:02:40.869621 | 2018-12-27T13:44:55 | 2018-12-27T13:44:55 | 162,283,322 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,461 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'client.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.6.2)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../client.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'client.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.6.2. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_Client_t {
QByteArrayData data[16];
char stringdata0[187];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_Client_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_Client_t qt_meta_stringdata_Client = {
{
QT_MOC_LITERAL(0, 0, 6), // "Client"
QT_MOC_LITERAL(1, 7, 10), // "newMessage"
QT_MOC_LITERAL(2, 18, 0), // ""
QT_MOC_LITERAL(3, 19, 4), // "from"
QT_MOC_LITERAL(4, 24, 7), // "message"
QT_MOC_LITERAL(5, 32, 14), // "newParticipant"
QT_MOC_LITERAL(6, 47, 4), // "nick"
QT_MOC_LITERAL(7, 52, 15), // "participantLeft"
QT_MOC_LITERAL(8, 68, 13), // "newConnection"
QT_MOC_LITERAL(9, 82, 11), // "Connection*"
QT_MOC_LITERAL(10, 94, 10), // "connection"
QT_MOC_LITERAL(11, 105, 15), // "connectionError"
QT_MOC_LITERAL(12, 121, 28), // "QAbstractSocket::SocketError"
QT_MOC_LITERAL(13, 150, 11), // "socketError"
QT_MOC_LITERAL(14, 162, 12), // "disconnected"
QT_MOC_LITERAL(15, 175, 11) // "readyForUse"
},
"Client\0newMessage\0\0from\0message\0"
"newParticipant\0nick\0participantLeft\0"
"newConnection\0Connection*\0connection\0"
"connectionError\0QAbstractSocket::SocketError\0"
"socketError\0disconnected\0readyForUse"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_Client[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
7, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
3, // signalCount
// signals: name, argc, parameters, tag, flags
1, 2, 49, 2, 0x06 /* Public */,
5, 1, 54, 2, 0x06 /* Public */,
7, 1, 57, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
8, 1, 60, 2, 0x08 /* Private */,
11, 1, 63, 2, 0x08 /* Private */,
14, 0, 66, 2, 0x08 /* Private */,
15, 0, 67, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void, QMetaType::QString, QMetaType::QString, 3, 4,
QMetaType::Void, QMetaType::QString, 6,
QMetaType::Void, QMetaType::QString, 6,
// slots: parameters
QMetaType::Void, 0x80000000 | 9, 10,
QMetaType::Void, 0x80000000 | 12, 13,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void Client::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
Client *_t = static_cast<Client *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->newMessage((*reinterpret_cast< const QString(*)>(_a[1])),(*reinterpret_cast< const QString(*)>(_a[2]))); break;
case 1: _t->newParticipant((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 2: _t->participantLeft((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 3: _t->newConnection((*reinterpret_cast< Connection*(*)>(_a[1]))); break;
case 4: _t->connectionError((*reinterpret_cast< QAbstractSocket::SocketError(*)>(_a[1]))); break;
case 5: _t->disconnected(); break;
case 6: _t->readyForUse(); break;
default: ;
}
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
switch (_id) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 4:
switch (*reinterpret_cast<int*>(_a[1])) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< QAbstractSocket::SocketError >(); break;
}
break;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (Client::*_t)(const QString & , const QString & );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&Client::newMessage)) {
*result = 0;
return;
}
}
{
typedef void (Client::*_t)(const QString & );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&Client::newParticipant)) {
*result = 1;
return;
}
}
{
typedef void (Client::*_t)(const QString & );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&Client::participantLeft)) {
*result = 2;
return;
}
}
}
}
const QMetaObject Client::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_Client.data,
qt_meta_data_Client, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *Client::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *Client::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_Client.stringdata0))
return static_cast<void*>(const_cast< Client*>(this));
return QObject::qt_metacast(_clname);
}
int Client::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 7)
qt_static_metacall(this, _c, _id, _a);
_id -= 7;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 7)
qt_static_metacall(this, _c, _id, _a);
_id -= 7;
}
return _id;
}
// SIGNAL 0
void Client::newMessage(const QString & _t1, const QString & _t2)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)), const_cast<void*>(reinterpret_cast<const void*>(&_t2)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
// SIGNAL 1
void Client::newParticipant(const QString & _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 1, _a);
}
// SIGNAL 2
void Client::participantLeft(const QString & _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 2, _a);
}
QT_END_MOC_NAMESPACE
| [
"student@domain.local"
] | student@domain.local |
99f15f97e95341efcc6cffa68f127b009ef89db4 | a5054df3fa38dbf5c7c03d8721f9bcfe04db570f | /Examples/Tilemap/GameHeader.cpp | 40fb2a816bbf9a98387991f7e6b00b2de9a83f14 | [
"CC-BY-3.0",
"MIT"
] | permissive | Bjohh/SuperPlay | 850a5baa3f114ea65b8ed4629bdff9c0e4c040e9 | e2d33cb52635251cd3f180b73f5fb08944940d18 | refs/heads/master | 2023-03-16T20:27:49.749763 | 2020-12-09T19:58:16 | 2020-12-09T19:58:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,019 | cpp | // This code is part of the Super Play Library (http://www.superplay.info),
// and may only be used under the terms contained in the LICENSE file,
// included with the Super Play Library.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
#include <GameHeader.h>
#include "GameDefines.h"
using namespace SPlay;
void getGameHeader(GameHeader& _gameHeader)
{
// App name
_gameHeader.strAppName = "Tilemap demo";
// Screen size
_gameHeader.iScreenWidth = gsc_iScreenWidth;
_gameHeader.iScreenHeight = gsc_iScreenHeight;
// Window size
_gameHeader.iWindowedWidth = gsc_iScreenWidth;
_gameHeader.iWindowedHeight = gsc_iScreenHeight;
// SRAM size
_gameHeader.iSRAMSize = 0;
// Full screen
_gameHeader.bFullScreen = false;
// Use Shadow OAM
_gameHeader.bUseShadowOAM = false;
}
| [
"cdoty@rastersoft.net"
] | cdoty@rastersoft.net |
ec0bbc054fdac810edbedeba770843b2fe15cd13 | 3565e8721e93c11175906a43b02999798e1be744 | /Source/RendererRuntime/Public/Resource/CompositorNode/Pass/Copy/CompositorInstancePassCopy.h | b41d363d5279aa763de15063e8583a3d50ff2ec5 | [
"MIT"
] | permissive | raptoravis/unrimp | c5a900811c95e3ad9b19a4d6eb93e904523574be | 5072120151c62d7901682d516f029fc524fdcfb3 | refs/heads/master | 2020-07-21T13:48:13.505367 | 2019-08-31T18:51:38 | 2019-08-31T18:57:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,889 | h | /*********************************************************\
* Copyright (c) 2012-2019 The Unrimp Team
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Header guard ]
//[-------------------------------------------------------]
#pragma once
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include "RendererRuntime/Public/Resource/CompositorNode/Pass/ICompositorInstancePass.h"
//[-------------------------------------------------------]
//[ Forward declarations ]
//[-------------------------------------------------------]
namespace RendererRuntime
{
class CompositorResourcePassCopy;
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace RendererRuntime
{
//[-------------------------------------------------------]
//[ Classes ]
//[-------------------------------------------------------]
class CompositorInstancePassCopy final : public ICompositorInstancePass
{
//[-------------------------------------------------------]
//[ Friends ]
//[-------------------------------------------------------]
friend class CompositorPassFactory; // The only one allowed to create instances of this class
//[-------------------------------------------------------]
//[ Protected virtual RendererRuntime::ICompositorInstancePass methods ]
//[-------------------------------------------------------]
protected:
virtual void onFillCommandBuffer(const Renderer::IRenderTarget* renderTarget, const CompositorContextData& compositorContextData, Renderer::CommandBuffer& commandBuffer) override;
//[-------------------------------------------------------]
//[ Private methods ]
//[-------------------------------------------------------]
private:
CompositorInstancePassCopy(const CompositorResourcePassCopy& compositorResourcePassCopy, const CompositorNodeInstance& compositorNodeInstance);
inline virtual ~CompositorInstancePassCopy() override
{
// Nothing here
}
explicit CompositorInstancePassCopy(const CompositorInstancePassCopy&) = delete;
CompositorInstancePassCopy& operator=(const CompositorInstancePassCopy&) = delete;
};
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // RendererRuntime
| [
"cofenberg@gmail.com"
] | cofenberg@gmail.com |
a7a83d74dd7ec3dd88322a5961001ee4fbbe8596 | 8cc370ea11cb670ff21e3def2b2293a4ab570ba2 | /VSstudio/project euler/problem48.cpp | 33f8a7e694d2433160faec4aac5c097d553a32af | [] | no_license | Wishu969/Project-Euler | 4fc3a81f8e76b05e4f526012d6f9abcbc2d22b03 | e367b1e141257666d578fdb326e8524bbc2fa0d5 | refs/heads/master | 2020-04-16T11:43:43.455864 | 2019-01-14T09:13:57 | 2019-01-14T09:13:57 | 165,549,020 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 859 | cpp | #include "problem48.h"
problem48::problem48()
{
}
problem48::~problem48()
{
}
int problem48::run()
{
std::cout << power(12, 12) << std::endl;
/*
unsigned long long int y = 0;
unsigned long long int temp = 0;
for (unsigned int i = 1; i <= 1000; i++)
{
temp = power(i, i);
y += temp;
std::cout << i << " squared = " << temp << " total current = " << y << std::endl;
}
std::cout << y;
*/
return 0;
}
unsigned long long int problem48::power(unsigned int a, unsigned int b)
{
unsigned long long int temp = 1;
for (unsigned long long int i = 1; i <= b; i++)
{
temp *= a;
std::string tempstr = std::to_string(temp);
if (tempstr.length() >= 10)
{
tempstr.erase(0, (tempstr.length() - 10));
}
temp = FunctionLibrary::stringToInt(tempstr);
std::cout << temp << " || " <<tempstr.length() << std::endl;
}
return temp;
}
| [
"Wishu969@gmail.com"
] | Wishu969@gmail.com |
6317d19603c52312aa454bb108c0ebc65afd3c40 | 9c9c6b8deca524c9401dd24d19510d3843bebe4b | /disposing/perception_pcl/pcl_ros/src/pcl_ros/filters/passthrough.cpp | e0de5af3a70b40da757f13f370f2d5c7b0be7665 | [
"MIT"
] | permissive | tku-iarc/wrs2020 | 3f6473c2f3077400527b5e3008ae8a6e88eb00d6 | a19d1106206e65f9565fa68ad91887e722d30eff | refs/heads/master | 2022-12-12T20:33:10.958300 | 2021-02-01T10:21:09 | 2021-02-01T10:21:09 | 238,463,359 | 3 | 8 | MIT | 2022-12-09T02:09:35 | 2020-02-05T14:00:16 | C++ | UTF-8 | C++ | false | false | 5,277 | cpp | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2010, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id: passthrough.cpp 36194 2011-02-23 07:49:21Z rusu $
*
*/
#include <pluginlib/class_list_macros.h>
#include "pcl_ros/filters/passthrough.h"
//////////////////////////////////////////////////////////////////////////////////////////////
bool
pcl_ros::PassThrough::child_init (ros::NodeHandle &nh, bool &has_service)
{
// Enable the dynamic reconfigure service
has_service = true;
srv_ = boost::make_shared <dynamic_reconfigure::Server<pcl_ros::FilterConfig> > (nh);
dynamic_reconfigure::Server<pcl_ros::FilterConfig>::CallbackType f = boost::bind (&PassThrough::config_callback, this, _1, _2);
srv_->setCallback (f);
return (true);
}
//////////////////////////////////////////////////////////////////////////////////////////////
void
pcl_ros::PassThrough::config_callback (pcl_ros::FilterConfig &config, uint32_t level)
{
boost::mutex::scoped_lock lock (mutex_);
double filter_min, filter_max;
impl_.getFilterLimits (filter_min, filter_max);
// Check the current values for filter min-max
if (filter_min != config.filter_limit_min)
{
filter_min = config.filter_limit_min;
NODELET_DEBUG ("[%s::config_callback] Setting the minimum filtering value a point will be considered from to: %f.", getName ().c_str (), filter_min);
// Set the filter min-max if different
impl_.setFilterLimits (filter_min, filter_max);
}
// Check the current values for filter min-max
if (filter_max != config.filter_limit_max)
{
filter_max = config.filter_limit_max;
NODELET_DEBUG ("[%s::config_callback] Setting the maximum filtering value a point will be considered from to: %f.", getName ().c_str (), filter_max);
// Set the filter min-max if different
impl_.setFilterLimits (filter_min, filter_max);
}
// Check the current value for the filter field
//std::string filter_field = impl_.getFilterFieldName ();
if (impl_.getFilterFieldName () != config.filter_field_name)
{
// Set the filter field if different
impl_.setFilterFieldName (config.filter_field_name);
NODELET_DEBUG ("[%s::config_callback] Setting the filter field name to: %s.", getName ().c_str (), config.filter_field_name.c_str ());
}
// Check the current value for keep_organized
if (impl_.getKeepOrganized () != config.keep_organized)
{
NODELET_DEBUG ("[%s::config_callback] Setting the filter keep_organized value to: %s.", getName ().c_str (), config.keep_organized ? "true" : "false");
// Call the virtual method in the child
impl_.setKeepOrganized (config.keep_organized);
}
// Check the current value for the negative flag
if (impl_.getFilterLimitsNegative () != config.filter_limit_negative)
{
NODELET_DEBUG ("[%s::config_callback] Setting the filter negative flag to: %s.", getName ().c_str (), config.filter_limit_negative ? "true" : "false");
// Call the virtual method in the child
impl_.setFilterLimitsNegative (config.filter_limit_negative);
}
// The following parameters are updated automatically for all PCL_ROS Nodelet Filters as they are inexistent in PCL
if (tf_input_frame_ != config.input_frame)
{
tf_input_frame_ = config.input_frame;
NODELET_DEBUG ("[%s::config_callback] Setting the input TF frame to: %s.", getName ().c_str (), tf_input_frame_.c_str ());
}
if (tf_output_frame_ != config.output_frame)
{
tf_output_frame_ = config.output_frame;
NODELET_DEBUG ("[%s::config_callback] Setting the output TF frame to: %s.", getName ().c_str (), tf_output_frame_.c_str ());
}
}
typedef pcl_ros::PassThrough PassThrough;
PLUGINLIB_EXPORT_CLASS(PassThrough,nodelet::Nodelet);
| [
"dual-arm@dualarm.com"
] | dual-arm@dualarm.com |
f0773cde301b3354bee258443200d1db52106e2e | 6ee200c9dba87a5d622c2bd525b50680e92b8dab | /Walkyrie Dx9/DoomeRX/Objects/CameraPremierePersonneLaby.h | 02d0dc70db7fd1af164a7f809cf2df11bc2e9617 | [] | no_license | Ishoa/bizon | 4dbcbbe94d1b380f213115251e1caac5e3139f4d | d7820563ab6831d19e973a9ded259d9649e20e27 | refs/heads/master | 2016-09-05T11:44:00.831438 | 2010-03-10T23:14:22 | 2010-03-10T23:14:22 | 32,632,823 | 0 | 0 | null | null | null | null | ISO-8859-2 | C++ | false | false | 537 | h | // Classe pour la gestion d'une caméra
#pragma once
#include "..\..\Valkyrie\Moteur\CameraPremierePersonne.h"
#include "..\..\Valkyrie\Moteur\EnvCollision.h"
class CScene;
class CCameraPremierePersonneLaby : public CCameraPremierePersonne
{
CEnvCollision* m_pEnvCollision;
public:
CCameraPremierePersonneLaby();
CCameraPremierePersonneLaby(CScene* pScene,CEnvCollision* pEnvCollision, float fHauteur = 1.0f);
~CCameraPremierePersonneLaby();
virtual D3DXVECTOR3 CheckPosition(D3DXVECTOR3, D3DXVECTOR3);
};
| [
"Colas.Vincent@ab19582e-f48f-11de-8f43-4547254af6c6"
] | Colas.Vincent@ab19582e-f48f-11de-8f43-4547254af6c6 |
f90cd6bed0a6983930d7a7fdbf225a968f43b912 | a766fccaca6866bd0344cf0754589918a6bef85d | /airdcpp-webapi/api/ShareApi.cpp | 96db57c71d1899f0e51a61b3fee05fd224cdbd2a | [] | no_license | sbraz/airdcpp-webclient | f3537473f85effac411001445185a9d65d795830 | d4801cc913dd6f34d1846daaf20c77a30de99b59 | refs/heads/master | 2020-05-29T12:18:19.538572 | 2016-01-11T20:12:35 | 2016-01-11T20:12:35 | 49,369,470 | 0 | 1 | null | 2016-01-10T14:10:39 | 2016-01-10T14:10:39 | null | UTF-8 | C++ | false | false | 4,287 | cpp | /*
* Copyright (C) 2011-2015 AirDC++ Project
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <api/ShareApi.h>
#include <api/common/Serializer.h>
#include <api/common/Deserializer.h>
#include <api/ShareUtils.h>
#include <web-server/JsonUtil.h>
#include <airdcpp/ShareManager.h>
#include <airdcpp/HubEntry.h>
namespace webserver {
ShareApi::ShareApi(Session* aSession) : ApiModule(aSession) {
METHOD_HANDLER("grouped_root_paths", Access::ANY, ApiRequest::METHOD_GET, (), false, ShareApi::handleGetGroupedRootPaths);
METHOD_HANDLER("stats", Access::ANY, ApiRequest::METHOD_GET, (), false, ShareApi::handleGetStats);
METHOD_HANDLER("find_dupe_paths", Access::ANY, ApiRequest::METHOD_POST, (), true, ShareApi::handleFindDupePaths);
METHOD_HANDLER("refresh", Access::SETTINGS_EDIT, ApiRequest::METHOD_POST, (), false, ShareApi::handleRefreshShare);
METHOD_HANDLER("refresh", Access::SETTINGS_EDIT, ApiRequest::METHOD_POST, (EXACT_PARAM("paths")), true, ShareApi::handleRefreshPaths);
}
ShareApi::~ShareApi() {
}
api_return ShareApi::handleRefreshShare(ApiRequest& aRequest) {
auto incoming = JsonUtil::getOptionalFieldDefault<bool>("incoming", aRequest.getRequestBody(), false);
auto ret = ShareManager::getInstance()->refresh(incoming);
//aRequest.setResponseBody(j);
return websocketpp::http::status_code::ok;
}
api_return ShareApi::handleRefreshPaths(ApiRequest& aRequest) {
auto paths = JsonUtil::getField<StringList>("paths", aRequest.getRequestBody(), false);
auto ret = ShareManager::getInstance()->refreshPaths(paths);
//aRequest.setResponseBody(j);
return websocketpp::http::status_code::ok;
}
api_return ShareApi::handleGetStats(ApiRequest& aRequest) {
json j;
auto optionalStats = ShareManager::getInstance()->getShareStats();
if (!optionalStats) {
return websocketpp::http::status_code::no_content;
}
auto stats = *optionalStats;
j["total_file_count"] = stats.totalFileCount;
j["total_directory_count"] = stats.totalDirectoryCount;
j["files_per_directory"] = stats.filesPerDirectory;
j["total_size"] = stats.totalSize;
j["unique_file_percentage"] = stats.uniqueFilePercentage;
j["unique_files"] = stats.uniqueFileCount;
j["average_file_age"] = stats.averageFileAge;
j["profile_count"] = stats.profileCount;
j["profile_root_count"] = stats.profileDirectoryCount;
aRequest.setResponseBody(j);
return websocketpp::http::status_code::ok;
}
api_return ShareApi::handleGetGroupedRootPaths(ApiRequest& aRequest) {
json ret;
auto roots = ShareManager::getInstance()->getGroupedDirectories();
if (!roots.empty()) {
for (const auto& vPath : roots) {
json parentJson;
parentJson["name"] = vPath.first;
for (const auto& realPath : vPath.second) {
parentJson["paths"].push_back(realPath);
}
ret.push_back(parentJson);
}
} else {
ret = json::array();
}
aRequest.setResponseBody(ret);
return websocketpp::http::status_code::ok;
}
api_return ShareApi::handleFindDupePaths(ApiRequest& aRequest) {
const auto& reqJson = aRequest.getRequestBody();
json ret;
StringList paths;
auto path = JsonUtil::getOptionalField<string>("path", reqJson, false, false);
if (path) {
paths = ShareManager::getInstance()->getDirPaths(Util::toNmdcFile(*path));
} else {
auto tth = Deserializer::deserializeTTH(reqJson);
paths = ShareManager::getInstance()->getRealPaths(tth);
}
if (!paths.empty()) {
for (const auto& p : paths) {
ret.push_back(p);
}
} else {
ret = json::array();
}
aRequest.setResponseBody(ret);
return websocketpp::http::status_code::ok;
}
} | [
"maksis@adrenaline-network.com"
] | maksis@adrenaline-network.com |
39e9967967665a19e9b8005d78dac85bbc350f62 | 23c524e47a96829d3b8e0aa6792fd40a20f3dd41 | /.history/List_20210518150358.hpp | cf830dca6487cf333a9d666bc3078539e4a452f0 | [] | no_license | nqqw/ft_containers | 4c16d32fb209aea2ce39e7ec25d7f6648aed92e8 | f043cf52059c7accd0cef7bffcaef0f6cb2c126b | refs/heads/master | 2023-06-25T16:08:19.762870 | 2021-07-23T17:28:09 | 2021-07-23T17:28:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,015 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* List.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: dbliss <dbliss@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/04/26 14:06:11 by dbliss #+# #+# */
/* Updated: 2021/05/18 15:03:58 by dbliss ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef LIST_HPP
#define LIST_HPP
#include <iostream>
#include <memory>
#include "ListIterator.hpp"
#include "Algorithm.hpp"
#include "Identifiers.hpp"
namespace ft
{
template <class T, class Alloc = std::allocator<T> >
class list
{
private:
struct Node
{
T val;
Node *next;
Node *prev;
};
public:
typedef T value_type;
typedef Alloc allocator_type;
typedef typename Alloc::reference reference;
typedef typename Alloc::const_reference const_reference;
typedef typename Alloc::pointer pointer;
typedef typename Alloc::const_pointer const_pointer;
typedef typename ft::ListIterator<pointer, Node> iterator;
typedef typename ft::ListIterator<const_pointer, Node> const_iterator;
typedef typename ft::myReverseIterator<iterator> reverse_iterator;
typedef typename ft::myReverseIterator<const_iterator> const_reverse_iterator;
typedef ptrdiff_t difference_type;
typedef size_t size_type;
typedef typename Alloc::template rebind<Node>::other node_allocator_type; // мб это не нужно, так как указала в приватных по=другому
/*================================ 4 CONSTRUCTORS: ================================*/
// #1 : DEFAULT:
explicit list(const allocator_type &alloc = allocator_type()) : _size(0), _allocator_type(alloc)
{
this->_node = allocate_node();
}
// #2: FILL:
explicit list(size_type n, const value_type &val = value_type(),
const allocator_type &alloc = allocator_type()) : _size(0), _allocator_type(alloc)
{
this->_node = allocate_node();
for (int i = 0; i < n; ++i)
{
insert_end(val);
}
}
//#3: RANGE:
template <class InputIterator>
list(InputIterator first, InputIterator last, typename ft::enable_if<!is_integral<InputIterator>::value> * = NULL,
const allocator_type &alloc = allocator_type()) : _size(0), _allocator_type(alloc)
{
this->_node = allocate_node();
assign(first, last);
}
// #4 COPY:
list(const list &x)
{
this->_node = allocate_node();
assign(x.begin(), x.end());
}
/*================================ DESTRUCTOR: ================================*/
virtual ~list()
{
erase(begin(), end());
// The next steps we need to do for allocated node in the constructor.
this->_node->prev->next = this->_node->next;
this->_node->next->prev = this->_node->prev;
this->_alloc_node.deallocate(this->_node, 1);
}
/*================================ OPERATOR=: ================================*/
list &operator=(const list &x)
{
if (this != &x)
{
assign(x.begin(), x.end());
}
return (*this);
}
/*================================ ITERATORS: ================================*/
iterator begin()
{
return iterator(this->_node->next);
}
const_iterator begin() const
{
return const_iterator(this->_node->next);
}
iterator end()
{
return iterator(this->_node);
}
const_iterator end() const
{
return const_iterator(this->_node);
}
reverse_iterator rbegin()
{
return reverse_iterator(end());
}
const_reverse_iterator rbegin() const
{
return const_reverse_iterator(end());
}
reverse_iterator rend()
{
return reverse_iterator(begin());
}
const_reverse_iterator rend() const
{
return const_reverse_iterator(begin());
}
/*================================ CAPACITY: ================================*/
bool empty() const
{
return this->_node->next == this->_node;
}
size_type size() const
{
return this->_size;
}
size_type max_size() const
{
return this->_alloc_node.max_size();
}
/*================================ ELEMENT ACCESS: ================================*/
reference front()
{
return this->_node->next->val;
}
const_reference front() const
{
return this->_node->next->val;
}
reference back()
{
return this->_node->prev->val;
}
const_reference back() const
{
return this->_node->prev->val;
}
/*================================ MODIFIERS: ================================*/
/* ASSIGN */
/* Assigns new contents to the list container, replacing its current contents, and modifying its size accordingly. */
/* In the range version (1), the new contents are elements constructed
from each of the elements in the range between first and last, in the same order.*/
template <class InputIterator>
void assign(InputIterator first, InputIterator last, typename ft::enable_if<!is_integral<InputIterator>::value, InputIterator>::type isIterator = InputIterator())
{
(void)isIterator;
clear();
insert(begin(), first, last);
}
/* In the fill version (2), the new contents are n elements,
each initialized to a copy of val.*/
void assign(size_type n, const value_type &val)
{
clear();
insert(begin(), n, val);
}
/* Insert element at the beginning */
void push_front(const value_type &val)
{
//insert(begin(), val);
insert_begin(val);
}
/* Removes the first element in the list container, effectively reducing its size by one. */
void pop_front()
{
erase(begin());
}
void push_back(const value_type &val)
{
insert_end(val);
}
/* Removes the last element in the list container, effectively reducing the container size by one.
This destroys the removed element. */
void pop_back()
{
erase(--end());
// --end because the result of end an iterator to the element past the end of the sequence.
}
/* INSERT */
/* The container is extended by inserting new elements before
the element at the specified position. */
iterator insert(iterator position, const value_type &val)
{
Node *new_node = construct_node(val);
// setting up previous and next of new node
new_node->next = position.get_node();
new_node->prev = position.get_node()->prev;
// // Update next and previous pointers of the prev node
position.get_node()->prev->next = new_node;
position.get_node()->prev = new_node;
++this->_size;
return iterator(new_node);
}
void insert(iterator position, size_type n, const value_type &val)
{
for (int i = 0; i < n; ++i)
{
insert(position, val);
}
}
template <class InputIterator>
void insert(iterator position, InputIterator first, InputIterator last, typename ft::enable_if<!is_integral<InputIterator>::value, InputIterator>::type isIterator = InputIterator())
{
(void)isIterator;
while (first != last)
{
position = insert(position, *first);
++position;
++first;
}
}
/* Removes from the list container a single element (position).
This effectively reduces the container size by the number of elements removed, which are destroyed.*/
iterator erase(iterator position)
{
Node *next;
next = position.get_node()->next;
delete_node(position.get_node());
return iterator(next);
}
/* Removes from the list container a range of elements ([first,last)).
This effectively reduces the container size by the number of elements removed, which are destroyed.*/
iterator erase(iterator first, iterator last)
{
Node *begin;
Node *end;
begin = first.get_node()->prev;
end = last.get_node();
begin->next = end;
end->prev = begin;
while (first != last)
{
this->_alloc_node.destroy(first.get_node());
this->_alloc_node.deallocate(first.get_node(), 1);
this->_size--;
first++;
}
return (last);
}
void swap(list &x)
{
if (this == &x)
return;
ft::swap(this->_node, x._node);
ft::swap(this->_size, x._size);
ft::swap(this->_allocator_type, x._allocator_type);
ft::swap(this->_alloc_node, x._alloc_node);
}
void resize(size_type n, value_type val = value_type())
{
iterator pos = begin();
size_type n_copy = n;
while (n_copy--)
pos++;
if (n < this->_size)
erase(pos, end());
else if (this->_size < n)
{
size_type offset;
offset = n - this->_size;
insert(end(), offset, val);
}
}
/* Removes all elements from the list container (which are destroyed),
and leaving the container with a size of 0. */
void clear()
{
erase(begin(), end());
}
/*================================ OPERATIONS: ================================*/
/* SPLICE
Transfers elements from x into the container, inserting them at position.
This effectively inserts those elements into the container and removes them from x,
altering the sizes of both containers. The operation does not involve
the construction or destruction of any element. They are transferred,
no matter whether x is an lvalue or an rvalue, or whether the value_type supports
move-construction or not.*/
/*The first version (1) transfers all the elements of x into the container.*/
void splice(iterator position, list &x)
{
iterator it = x.begin();
size_type i = 0;
while (i < x.size())
{
insert(position, it.get_node()->val);
i++;
it++;
}
x.clear();
}
/*The second version (2) transfers only the element pointed by i from x into the container.*/
void splice(iterator position, list &x, iterator i)
{
iterator tmp = x.begin();
while (tmp != i)
tmp++; // get the iterator to the element in x in order to delete it lately
insert(position, i.get_node()->val);
x.erase(tmp);
}
/*The third version (3) transfers the range [first,last] from x into the container.*/
void splice(iterator position, list &x, iterator first, iterator last)
{
iterator x_first = first; // save the iterator position for x
while (first != last)
{
insert(position, first.get_node()->val);
first++;
x.erase(x_first);
x_first++;
}
}
/* REMOVE */
/*Removes from the container all the elements that compare equal to val.
This calls the destructor of these objects and reduces the container size
by the number of elements removed.
Unlike member function list::erase, which erases elements by their position
(using an iterator), this function (list::remove) removes elements by their value. */
void remove(const value_type &val)
{
Node *save;
save = this->_node->next; // 1st element
size_type i = 0;
size_type save_size = this->_size;
while (i < save_size)
{
save = save->next;
if (save->prev->val == val)
{
delete_node(save->prev); // delete_node func reduces the container size itself!
}
--save_size;
}
}
/* REMOVE IF */
template <class Predicate>
void remove_if(Predicate pred)
{
Node *save;
save = this->_node->next; // 1st element
size_type i = 0;
size_type save_size = this->_size;
while (i < save_size)
{
save = save->next;
if (pred(save->prev->val))
{
delete_node(save->prev); // delete_node func reduces the container size itself!
}
--save_size;
}
}
/* UNIQUE */
/*removes all but the first element from every consecutive
group of equal elements in the container.*/
void unique()
{
Node *save;
save = this->_node->next->next; // 2nd element
size_type i = 0;
size_type save_size = this->_size;
while (i < save_size)
{
if (save->prev->val == save->val)
{
save = save->next;
delete_node(save->prev); // delete_node func reduces the container size itself!
}
else
save = save->next;
--save_size;
}
}
template <class BinaryPredicate>
void unique(BinaryPredicate binary_pred)
{
Node *save;
save = this->_node->next->next; // 2nd element
size_type i = 0;
size_type save_size = this->_size;
while (i < save_size)
{
if (binary_pred(save->prev->val, save->val))
{
save = save->next;
delete_node(save->prev); // delete_node func reduces the container size itself!
}
else
save = save->next;
--save_size;
}
}
/* MERGE */
/* Merges x into the list by transferring all of its elements at their respective ordered positions
into the container (both containers shall already be ordered).*/
void merge(list &x)
{
merge(x, ft::less<value_type>());
}
template <class Compare>
void merge(list &x, Compare comp)
{
if (&x == this)
return;
size_type i = 0;
Node *first = this->_node->next;
Node *second = x._node->next;
iterator position = this->begin();
while (first != this->_node && second != x._node)
{
// std::cout << "first->val: " << first->val << std::endl;
// std::cout << "second->val: " << second->val << std::endl << std::endl;
if (comp(second->val, first->val))
{
insert(position, second->val);
second = second->next;
}
else
{
first = first->next;
}
position++;
}
while (second != x._node)
{
this->push_back(second->val);
second = second->next;
}
x.clear();
}
/* SORT */
void sort()
{
this->_node->next = mergeSort(this->_node->next, ft::less<value_type>());
// These code we need to get the last of our node;
Node *head = this->_node->next;
Node *last;
while (head != this->_node)
{
last = head;
head = head->next;
}
this->_node->prev = last;
}
template <class Compare>
void sort(Compare comp)
{
this->_node->next = mergeSort(this->_node->next, comp);
Node *head = this->_node->next;
// get pointer to the node which will be the
// last node of the final list
Node *last;
while (head != this->_node)
{
last = head;
head = head->next;
}
this->_node->prev = last;
}
/* REVERSE */
void reverse()
{
Node *tmp_first = this->_node->next;
Node *tmp_last = this->_node->prev;
while (tmp_first != tmp_last)
{
ft::swap(tmp_first->val, tmp_last->val);
tmp_first = tmp_first->next;
tmp_last = tmp_last->prev;
}
}
/*================================ PRIVATE HELPER FUNCS: ================================*/
private:
Node *allocate_node()
{
Node *node;
node = this->_alloc_node.allocate(1);
node->next = node;
node->prev = node;
std::memset(&node->val, 0, sizeof(node->val));
return node;
}
Node *construct_node(const_reference val)
{
Node *node;
node = allocate_node();
this->_allocator_type.construct(&node->val, val);
return (node);
}
void insert_end(const_reference val)
{
// find last node
Node *last = this->_node->prev;
// create new node
Node *new_node;
new_node = construct_node(val);
// start is going to be next of new_node
new_node->next = this->_node;
// make new_node previous of start
this->_node->prev = new_node;
// make last previous of new node
new_node->prev = last;
// make new node next of old start
last->next = new_node;
this->_size += 1;
}
void insert_begin(const_reference val)
{
std::cout << "position.get_node()->val" << position.get_node()->val << std::endl;
std::cout << "position.get_node()->val" << position.get_node()->prev << std::endl;
std::cout << "last->val" << last->val << std::endl;
//Pointer points to last Node
Node *last = this->_node->prev;
Node *new_node = construct_node(val); // Inserting data
// setting up previous and next of new node
new_node->next = this->_node->next;
new_node->prev = last;
// Update next and previous pointers of start
// and last.
last->next = this->_node->prev = new_node;
// Update start pointer
this->_node = new_node;
// Increment size + 1;
++this->_size;
}
// Node *new_node = construct_node(val);
// // setting up previous and next of new node
// new_node->next = position.get_node();
// new_node->prev = position.get_node()->prev;
// // // Update next and previous pointers of the prev node
// position.get_node()->prev->next = new_node;
// position.get_node()->prev = new_node;
// ++this->_size;
// return iterator(new_node);
void delete_node(Node *node)
{
this->_alloc_node.destroy(node);
node->prev->next = node->next;
node->next->prev = node->prev;
this->_alloc_node.deallocate(node, 1);
this->_size -= 1;
}
Node *splitList(Node *src)
{
Node *fast = src->next;
Node *slow = src;
while (fast != this->_node)
{
fast = fast->next;
if (fast != this->_node)
{
fast = fast->next;
slow = slow->next;
}
}
Node *splitted = slow->next;
slow->next = this->_node;
return (splitted);
}
template <class Compare>
Node *mergeSortedLists(Node *first, Node *second, Compare comp)
{
if (first == this->_node) // if the first list is empty
return (second);
if (second == this->_node) // if the second list is empty
return (first);
// Pick the smaller value and adjust the links
if (comp(first->val, second->val)) // if first < second
{
first->next = mergeSortedLists(first->next, second, comp);
first->next->prev = first;
first->prev = this->_node;
return (first);
}
else
{
second->next = mergeSortedLists(first, second->next, comp);
second->next->prev = second;
second->prev = this->_node;
return (second);
}
}
template <class Compare>
Node *mergeSort(Node *first, Compare comp)
{
if (first == this->_node || first->next == this->_node)
return (first); // if there is only one element in our list
Node *second = splitList(first); // returns the pointer to the 2nd splitted part
first = mergeSort(first, comp);
second = mergeSort(second, comp);
return (mergeSortedLists(first, second, comp));
}
private:
allocator_type _allocator_type;
node_allocator_type _alloc_node;
size_type _size;
Node *_node;
};
/*================================ NON-MEMBER FUNCITON OVERLOADS: ================================*/
/* RELATIONAL OPERATORS */
/* The equality comparison (operator==) is performed by first comparing sizes, and if they match,
** the elements are compared sequentially using operator==,
** stopping at the first mismatch (as if using algorithm equal).
*/
template <class T, class Alloc>
bool operator==(const list<T, Alloc> &lhs, const list<T, Alloc> &rhs)
{
return (lhs.size() == rhs.size() && ft::equal(lhs.begin(), lhs.end(), rhs.begin()));
}
template <class T, class Alloc>
bool operator!=(const list<T, Alloc> &lhs, const list<T, Alloc> &rhs)
{
return !(lhs == rhs);
}
template <class T, class Alloc>
bool operator<(const list<T, Alloc> &lhs, const list<T, Alloc> &rhs)
{
return ft::lexicographical_compare(lhs.begin(), lhs.end(), rhs.begin(), rhs.end());
}
// a<=b equivalent !(b<a)
template <class T, class Alloc>
bool operator<=(const list<T, Alloc> &lhs, const list<T, Alloc> &rhs)
{
return !(rhs < lhs);
}
// a>b equivalent to b<a
template <class T, class Alloc>
bool operator>(const list<T, Alloc> &lhs, const list<T, Alloc> &rhs)
{
return (rhs < lhs);
}
// a>=b equivalent !(a<b)
template <class T, class Alloc>
bool operator>=(const list<T, Alloc> &lhs, const list<T, Alloc> &rhs)
{
return !(lhs < rhs);
}
/* SWAP */
template <class T, class Alloc>
void swap(list<T, Alloc> &x, list<T, Alloc> &y)
{
x.swap(y);
}
}
#endif | [
"asleonova.1@gmail.com"
] | asleonova.1@gmail.com |
5d79508b01874e966fa9affcb3f434c5f641dc5a | 80d14f6274e7812882589ca351c5bb61ea090626 | /src/mesh.h | e5b397117f18385eeb69dbcc962d133c323d19b2 | [] | no_license | fengkan/Geo | 57df86ea768ecc9f52c49c172b2e391477d45ae8 | 1cdbd90b35909889a20565a5aec1216cb5d93db6 | refs/heads/master | 2021-01-14T13:21:18.065445 | 2014-02-22T03:34:53 | 2014-02-22T03:34:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,071 | h | #ifndef MESH_H
#define MESH_H
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <string>
#include "base.h"
#include "point.h"
class Face {
public:
int vertex_index[3] {0, 0, 0};
int texture_index[3] {0, 0, 0};
Face() {
vertex_index[0] = 0;
vertex_index[1] = 0;
vertex_index[2] = 0;
texture_index[0] = 0;
texture_index[1] = 0;
texture_index[2] = 0;
}
Face(int u, int v, int w) {
vertex_index[0] = u;
vertex_index[1] = v;
vertex_index[2] = w;
texture_index[0] = 0;
texture_index[1] = 0;
texture_index[2] = 0;
}
Face(int u, int v, int w, int r, int s, int f) {
vertex_index[0] = u;
vertex_index[1] = v;
vertex_index[2] = w;
texture_index[0] = r;
texture_index[1] = s;
texture_index[2] = f;
}
bool has_vertex(int i) const {
return vertex_index[0] == i || vertex_index[1] == i || vertex_index[2] == i;
}
bool has_texture(int i) const {
return texture_index[0] == i || texture_index[1] == i || texture_index[2] == i;
}
};
class Mesh {
public:
std::vector<Point3f> vertex;
std::vector<Point2f> texture;
std::vector<Face> face;
std::vector<std::string> text;
public:
std::vector<Point3f> face_normal;
std::vector<Point3f> vertex_normal;
std::vector<std::vector<int> > adj_vertex;
std::vector<std::vector<int> > faces_of_vertex;
std::vector<std::vector<int> > adj_face;
protected:
void remove_unused_vertex();
void remove_unused_texture();
void calculate_adj_vertex();
void calculate_adj_face();
void calculate_faces_of_vertex();
void calculate_face_normal();
void calculate_vertex_normal();
void connect_vertex(int u, int v);
void connect_face(int u, int v);
public:
void update();
void clean();
void load(std::istream& in);
void save(std::ostream& out);
};
#endif
| [
"zhangchao6865@gmail.com"
] | zhangchao6865@gmail.com |
62502ec71778bebc0304fe1c9a11afdc4a53f0ae | 3a3cf942f2cbf74727c49cd756e0474c24b0dedb | /Homework2/Cube.h | 3ae1061e86a7d998fbd26cea64d6f9ba94005a9c | [] | no_license | MosheStauber/OpenGL_Maze | 52b659109e12a9ec56255a2578ea6b8a3a8a02a7 | a6a4b8758e4710ce7129d73201fd3bb812f3f235 | refs/heads/master | 2021-05-28T17:58:21.723531 | 2015-04-17T23:31:22 | 2015-04-17T23:31:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 475 | h | #ifndef CUBE_H
#define CUBE_H
#include "Wall.h"
class Cube
{
public:
Cube();
void addWall(Wall wall, int side);
void removeWall(int side);
Wall* getWalls();
int getNumWalls();
bool isWall();
void setAsPath();
int* getBorderIndices();
private:
Wall walls[4]; //One for each side of the cube besides for top and bottom
vector<Wall> wallsToUse;
bool isAWall;
};
#endif // CUBE_H
| [
"Moshe.stauber89@gmail.om"
] | Moshe.stauber89@gmail.om |
3df5e24e6e1a867bc87f30df8455a4f2b7dc9f3b | dd5356457879b9edf8c982a412e0068f94da697d | /SDK/RoCo_E_ButtonFontStyle_enums.hpp | 1dc5cccc4049e89075f5e625623cff5f3f0d395b | [] | no_license | ALEHACKsp/RoCo-SDK | 5ee6567294674b6933dcd0acda720f64712ccdbf | 3a9e37be3a48bc0a10aa9e4111865c996f3b5680 | refs/heads/master | 2023-05-14T16:54:49.296847 | 2021-06-08T20:09:37 | 2021-06-08T20:09:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 564 | hpp | #pragma once
// Rogue Company (0.60) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Enums
//---------------------------------------------------------------------------
// Enum E_ButtonFontStyle.E_ButtonFontStyle
enum class E_ButtonFontStyle : uint8_t
{
E_ButtonFontStyle__NewEnumerator0 = 0,
E_ButtonFontStyle__NewEnumerator1 = 1,
E_ButtonFontStyle__NewEnumerator2 = 2,
E_ButtonFontStyle__E_MAX = 3
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"30532128+pubgsdk@users.noreply.github.com"
] | 30532128+pubgsdk@users.noreply.github.com |
04aa49cc576f251a5532c36a62a6be5e67aa5743 | 2988320aaae18651f9d579acddd0dc52dbd12360 | /src/com/cyosp/mpa/api/rest/v1/User.hpp | 2d203fff24ad26a6a854c3d013b6f7c779a2ff59 | [
"BSD-3-Clause"
] | permissive | cyosp/MPA | 06d0911ac1e62780299656e338b183047db1b638 | f640435c483dcbf7bfe7ff7887a25e6c76612528 | refs/heads/master | 2021-03-19T17:12:59.843964 | 2020-10-21T05:32:26 | 2020-10-21T05:32:26 | 45,033,594 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,370 | hpp | /*
* User.hpp
*
* Created on: 21 March 2015
* Author: cyosp
*/
#ifndef INCLUDES_MPA_API_REST_V1_USER_HPP_
#define INCLUDES_MPA_API_REST_V1_USER_HPP_
#include "com/cyosp/helpers/BoostHelper.hpp"
#include "com/cyosp/mpa/api/rest/v1/Account.hpp"
#include "com/cyosp/mpa/core/MPA.hpp"
#include "com/cyosp/mpa/core/User.hpp"
#include "com/cyosp/mpa/api/rest/v1/MPAO.hpp"
#include "com/cyosp/mpa/api/rest/v1/Token.hpp"
#include "com/cyosp/mpa/api/rest/v1/MPAOFactory.hpp"
namespace mpa_api_rest_v1
{
class User : public MPAO
{
public:
static string URL_STRING_PATH_IDENTIFIER;
protected:
bool isValidAccess();
bool areGetParametersOk();
bool arePostAddParametersOk();
bool arePostDeleteParametersOk();
bool arePostUpdateParametersOk();
string executeGetRequest(ptree & root);
string executePostAddRequest(ptree & root);
string executePostDeleteRequest(ptree & root);
string executePostUpdateRequest(ptree & root);
bool isObjectAlreadyExisting(string objectName);
public:
User(HttpRequestType httpRequestType, ActionType actionType, const map<string, string>& argvals,
vector<std::pair<string, int> > urlPairs);
virtual ~User();
};
}
#endif
| [
"cyosp@users.noreply.github.com"
] | cyosp@users.noreply.github.com |
2fccf7c784c07f13e0e97041e06a3d0b15f73cee | 9955e81a916bc3093a7e34942da0973b3d612b8f | /arduino_code.ino | 40b1cf6d756ba3c9793eb70268a158dacb23e4be | [
"MIT"
] | permissive | Adirockzz95/TARS | 7acbc69ddf3909a54f89a5ab8ef6ee91ddfb5de9 | 6e8f42e5654ec1ad2444f3b1a8d11a1fb8b8d03f | refs/heads/master | 2020-12-25T14:38:27.234828 | 2016-07-20T11:09:02 | 2016-07-20T11:09:02 | 62,555,352 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,869 | ino | /* Connections:
* USB---> Pi
*
* SCL --> SCL (OLED)
* SDL --> SDL (OLED)
*
*/
#include<SPI.h>
#include<Wire.h>
#include <avr/wdt.h>
#include<Adafruit_SSD1306.h>
#define RESET_OLED 12
#define LOGO16_GLCD_HEIGHT 16
#define LOGO16_GLCD_WIDTH 16
/* Error values are for tuning the TARS' legs position.
* Do not change speed
* Error values depends on SPEED.
*/
#define COAST_ERROR 10
#define PUSH_ERROR 140
#define SPEED 80
// delay without delay()
unsigned long motorStartMillis;
/* Structure for holding attributes for
* each DC motor.
* Motor driver is LM298n
*/
typedef struct {
int pwm; // pwm values
int INA; // Motor driver pin INA
int INB; // Motor driver pin INB
char id; // Motor identifier
char current_dir; // Current direction of motor
int current_pos; // Current position of motor
}Motor;
// This motor controls left leg
Motor Motor1 = {.pwm=10,
.INA=9,
.INB=8,
.id='1',
.current_dir='F',
.current_pos=0
};
// This motor controls right leg
Motor Motor2 = {.pwm=11,
.INA=7,
.INB=6,
.id='2',
.current_dir='F', // Default direction
.current_pos=0 // Default position
};
// setup motors
void SetupMotors(){
pinMode(Motor1.pwm,OUTPUT);
pinMode(Motor1.INA,OUTPUT);
pinMode(Motor1.INB,OUTPUT);
pinMode(Motor2.pwm,OUTPUT);
pinMode(Motor2.INA,OUTPUT);
pinMode(Motor2.INB,OUTPUT);
}
void RunOLED(word time){
Adafruit_SSD1306 display(RESET_OLED);
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
// 'ON' every pixel for given time
for(int i=0;i<128;i++){
for(int j=0;j<32;j++){
display.drawPixel(i, j, WHITE);
}
}
display.display();
delay(time);
display.clearDisplay();
display.ssd1306_command(SSD1306_DISPLAYOFF); // put the OLED display in sleep mode
display.ssd1306_command(0x8D); // disable charge pump
}
// run motor in forward direction
void motor_FORWARD(char id,byte speed){
if(id=='1'){
digitalWrite(Motor1.INA,HIGH);
digitalWrite(Motor1.INB,LOW);
analogWrite(Motor1.pwm,speed);
}
else if(id=='2'){
digitalWrite(Motor2.INA,HIGH);
digitalWrite(Motor2.INB,LOW);
analogWrite(Motor2.pwm,speed);
}
}
// run motor in reverse direction
void motor_REVERSE(char id,byte speed){
if(id=='1'){
digitalWrite(Motor1.INA,LOW);
digitalWrite(Motor1.INB,HIGH);
analogWrite(Motor1.pwm,speed);
}
else if(id=='2'){
digitalWrite(Motor2.INA,LOW);
digitalWrite(Motor2.INB,HIGH);
analogWrite(Motor2.pwm,speed);
}
}
/* Command format for controlling individual motors:
*
* |ControlByte|Identifier|Motor Id|Direction|Speed|Time
*
* controlbyte: 'A' or 'C'
* Decides whether this is a Command or Action
*
* Identifier: 'D' or 'S'
* D for DC motors and S for servos (not implemented)
*
* Motor Id: 1 to 8
* 1 and 2 for DC motors and 3 to 8 are for servos
*
* Direction: 'F' or 'B'
* sets direction for DC motors.
*
* Speed : 0 to FF
* sets pwm speed value for DC motors. This will serve as an angle for servos (not implemented)
*
* Time : 0 to FFFF
* run command for given time
* ----------------------------------------------------------------
* Command format for executing predefined Actions:
* |ControlByte|Action Byte|Time
*
* Action:
* 'R' reset
* 'W' walk
* 'D' Default
* 'J' joke
* 'B' standby
* 'S' shutdown
*
* Time: 0 to FFFF
* run action for given time
*/
void ParseSerial(String data) {
char hold[4];
String temp;
char controlbyte;
word time;
char direction;
byte speed;
char id;
char identifier;
byte action;
controlbyte = data.charAt(1);
if(controlbyte=='C'){
identifier = data.charAt(3);
id = data.charAt(5);
direction = data.charAt(7);
temp = data.substring(9, 11);
temp.toCharArray(hold, 3);
String bemp = temp;
speed = strtol(hold, NULL, 16);
temp = data.substring(12, data.length());
temp.toCharArray(hold, temp.length() + 1);
time = strtol(hold, NULL, 16);
if(id=='1'){
if(direction=='F'){
motor_FORWARD('1',speed);
delay(time);
motor_BRAKE('1');
}
else if(direction=='R'){
motor_REVERSE('1',speed);
delay(time);
motor_BRAKE('1');
}
}
else if(id=='2'){
if(direction=='F'){
motor_FORWARD('2',speed);
delay(time);
motor_BRAKE('2');
}
else if(direction=='R'){
motor_REVERSE('2',speed);
delay(time);
motor_BRAKE('2');
}
}
}
if(controlbyte=='A'){
action = data.charAt(3);
temp = data.substring(5,data.length());
temp.toCharArray(hold,temp.length()+1);
time = strtol(hold,NULL,16);
HandleAction(action,time);
}
}
void HandleAction(char action,word time){
/*
* Actions:
* 'R' reset
* 'W' walk
* 'D' Default
* 'J' joke
* 'B' standby
* 'S' shutdown
*/
switch(action){
case 'S':
Shutdown();
break;
case 'B':
CentrePos();
break;
case 'D':
DefaultPos();
break;
case 'W':
Walk(time,SPEED);
break;
case 'J':
RunOLED(time);
break;
case 'R':
Reset(WDTO_30MS);
break;
}
}
// Reset arduino
void Reset(uint8_t prescaller){
wdt_enable(prescaller);
while(1){}
}
// BRAKE motors
void motor_BRAKE(char id){
if(id=='1'){
analogWrite(Motor1.pwm,0);
}
else if(id=='2'){
analogWrite(Motor2.pwm,0);
}
}
// Walk action
void Walk(word time,short speed){
//set position
Motor1.current_pos+=time;
Motor2.current_pos+=time;
// set motor directions
Motor1.current_dir='F';
Motor2.current_dir='R';
//start motors
motor_FORWARD('1',speed);
motor_REVERSE('2',speed);
motorStartMillis = millis();
while(millis()-motorStartMillis < time+0){
;
}
//urgent BRAKE
UrgentBrake('1');
UrgentBrake('2');
delay(500);
Motor1.current_dir='R';
Motor2.current_dir='F';
motor_FORWARD('2',speed);
motor_REVERSE('1',speed);
motorStartMillis = millis();
while(millis()-motorStartMillis < time+PUSH_ERROR){
;
}
UrgentBrake('1');
UrgentBrake('2');
}
// Standing position of TARS
void DefaultPos(){
Motor1.current_dir='R';
Motor2.current_dir='R';
Motor1.current_pos+=400;
Motor2.current_pos+=400;
motor_REVERSE('1',90);
motor_REVERSE('2',90);
delay(400);
UrgentBrake('1');
UrgentBrake('2');
}
/* This DC motors dosen't have PID control,
* so to track the current position I'm using Time as
* a heuristic.
*
* The assumption is, on start up all motors are at their
* Center position. i.e current_pos = 0
*
* TODO: use map()
*/
void CentrePos(){
if(Motor1.current_dir='F'){
motor_FORWARD('1',SPEED);
motorStartMillis = millis();
while(millis()-motorStartMillis < Motor1.current_pos-COAST_ERROR){
;
}
UrgentBrake('1');
Motor1.current_pos=0;
}
else if(Motor1.current_dir='R'){
motor_FORWARD('1',SPEED);
motorStartMillis = millis();
while(millis()-motorStartMillis < Motor1.current_pos-COAST_ERROR){
;
}
UrgentBrake('1');
Motor1.current_pos=0;
}
if(Motor2.current_dir='F'){
motorStartMillis = millis();
motor_FORWARD('2',SPEED);
while(millis()-motorStartMillis < Motor2.current_pos-120){
;
}
UrgentBrake('2');
Motor2.current_pos=0;
}
else if(Motor2.current_dir='R'){
motorStartMillis = millis();
motor_FORWARD('2',SPEED);
while(millis()-motorStartMillis < Motor2.current_pos-120){
;
}
UrgentBrake('2');
Motor2.current_pos=0;
}
}
void Shutdown(){
// TODO: Store current values in eeprom
CentrePos();
Reset(WDTO_30MS);
}
// Urgent brakes
void UrgentBrake(char id){
if(id=='1'){
analogWrite(Motor1.pwm,255);
digitalWrite(Motor1.INA,LOW);
digitalWrite(Motor1.INB,LOW);
}
if(id=='2'){
analogWrite(Motor2.pwm,255);
digitalWrite(Motor2.INA,LOW);
digitalWrite(Motor2.INB,LOW);
}
}
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
String Commands;
if(Serial.available()>0){
Commands = Serial.readStringUntil(' ');
SetupMotors();
ParseSerial(Commands);
}
}
| [
"noreply@github.com"
] | Adirockzz95.noreply@github.com |
db5cf43b45b6d5c619321025893b097dcb0f0424 | 223b55bda5f2c1211abd1be6793ecacbd5a86ed5 | /pawn_nodes_version.inc | a41c15567a775fd5bc515b76998e0c1d57129cc2 | [] | no_license | killermvc/pawn-nodes | a388024e6fac25233332a427dda5abfc875ee78d | 1c2bfa5d056c82d3225187765ad39c78886f5696 | refs/heads/master | 2023-05-02T07:36:09.105921 | 2021-05-20T20:04:07 | 2021-05-20T20:04:07 | 368,379,340 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 284 | inc | // This file was generated by "sampctl package release"
// DO NOT EDIT THIS FILE MANUALLY!
// To update the version number for a new release, run "sampctl package release"
#define PAWN_NODES_VERSION_MAJOR (1)
#define PAWN_NODES_VERSION_MINOR (0)
#define PAWN_NODES_VERSION_PATCH (2)
| [
"manuel.7000@hotmail.com"
] | manuel.7000@hotmail.com |
747e1a4e3480ba5ee4afc57898065c89c5fd3969 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5706278382862336_1/C++/dhruvj/1.cpp | a0df7951b285b137c63603d0786f63e12a10596e | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,222 | cpp | #include <iostream>
#include <stdio.h>
#include <math.h>
#include <list>
#include <queue>
#include <vector>
#include <functional>
#include <stack>
#include <utility>
#include <stdlib.h>
#include <map>
#include <string.h>
#include <algorithm>
typedef long long int ll;
#define SWAP(a, b) (((a) ^= (b)), ((b) ^= (a)), ((a) ^= (b)))
#define CLR(a) memset(a, 0, sizeof(a))
using namespace std;
ll gcdr ( ll a, ll b )
{
if ( a==0 ) return b;
return gcdr ( b%a, a );
}
bool IsPowerOfTwo(ll x)
{
return (x & (x - 1)) == 0;
}
int main() {
freopen ("output.txt","w",stdout);
freopen ("input.in","r",stdin);
ll t, i, j,a, b, ans;
double x;
char str[10000];
cin>>t;
for(ll lol = 1; lol <= t; ++lol) {
cin>>str;
ans = 1;
a=b=0;
for(i=0; str[i] != '/'; ++i) {
a=a*10;
a+=((int)(str[i]-'0'));
}
for(++i; str[i] != '\0'; ++i) {
b=b*10;
b+=((int)(str[i]-'0'));
}
x = a/(double)b;
while(!((x <= 1.00) && (x >= 0.5000))) {
x = x*2.0;
++ans;
}
b = b/gcdr(a,b);
if(!IsPowerOfTwo(b)) ans = -1;
if(ans!=-1)
cout<<"Case #"<<lol<<": "<<ans<<endl;
else
cout<<"Case #"<<lol<<": impossible"<<endl;
}
return 0;
} | [
"eewestman@gmail.com"
] | eewestman@gmail.com |
950f87c01be79ba45684168580682a4526dd591b | b4a4bd096cfe7de130582f21c4fe1e36497abeca | /tetv-graphics/tetv-graphics/ui/controls/TPushButton.cpp | 9b95171e303c34de556934b768b660d7866c9be5 | [] | no_license | dag10/tetv-graphics | 7ab277fbfd245c39d8986001b89f38b854ccce2a | c260ecf2eeee92668edd16816fd02c5504ff30f3 | refs/heads/master | 2021-01-01T19:42:13.341602 | 2013-08-04T03:34:01 | 2013-08-04T03:34:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,735 | cpp | /* Copyright (c) 2013, Drew Gottlieb
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
* - Neither the name of the TETV Graphics nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "ui/controls/TPushButton.h"
TPushButton::TPushButton(const QString & text, QWidget * parent)
: QPushButton(text, parent)
{
// Nothing at the moment
} | [
"gottlieb.drew@gmail.com"
] | gottlieb.drew@gmail.com |
4b1b4c9322880bb6774c200ec55868f5970d82c4 | 349fe789ab1e4e46aae6812cf60ada9423c0b632 | /FIB_DataModule/REM_GurAllDoc/UREM_DMGurAllDocCF.cpp | 421b484808b8d385dc48bfb9446ecb56691c1a9e | [] | no_license | presscad/ERP | a6acdaeb97b3a53f776677c3a585ca860d4de980 | 18ecc6c8664ed7fc3f01397d587cce91fc3ac78b | refs/heads/master | 2020-08-22T05:24:15.449666 | 2019-07-12T12:59:13 | 2019-07-12T12:59:13 | 216,326,440 | 1 | 0 | null | 2019-10-20T07:52:26 | 2019-10-20T07:52:26 | null | UTF-8 | C++ | false | false | 1,752 | cpp | #include "vcl.h"
#pragma hdrstop
#include "UREM_DMGurAllDocCF.h"
#include "UREM_DMGurAllDocImpl.h"
#include "IREM_DMGurAllDoc.h"
#pragma package(smart_init)
extern int NumObject;
//---------------------------------------------------------------
TREM_DMGurAllDocCF::TREM_DMGurAllDocCF()
{
NumRefs=0;
++NumObject;
}
//---------------------------------------------------------------
TREM_DMGurAllDocCF::~TREM_DMGurAllDocCF()
{
--NumObject;
}
//---------------------------------------------------------------
int TREM_DMGurAllDocCF::kanQueryInterface(REFIID id_interface, void**ppv)
{
int result=0;
if (id_interface==IID_IkanUnknown)
{
*ppv=static_cast<IkanUnknown*> (this);
result=-1;
}
else if (id_interface==IID_IkanClassFactory)
{
*ppv=static_cast<IkanClassFactory*> (this);
result=-1;
}
else
{
*ppv=NULL;
result=0;
return result;
}
kanAddRef();
return result;
}
//---------------------------------------------------------------
int TREM_DMGurAllDocCF::kanAddRef(void)
{
return (++NumRefs);
}
//---------------------------------------------------------------
int TREM_DMGurAllDocCF::kanRelease(void)
{
if (--NumRefs==0)
{
delete this;
}
return NumRefs;
}
//---------------------------------------------------------------
int TREM_DMGurAllDocCF::kanCreateInstance(REFIID id_interface, void ** ppv)
{
int result=0;
TREM_DMGurAllDocImpl * ob=new TREM_DMGurAllDocImpl();
if (ob->kanQueryInterface(id_interface, ppv)==-1)
{
result=-1;
}
else
{
delete ob;
result=0;
}
return result;
}
//---------------------------------------------------------------
| [
"sasha@kaserv.ru"
] | sasha@kaserv.ru |
1ce6426dffb40a6e19d202133b82f58d0d7e4d21 | a9a69d75423576d42cdb995a8a320c1a423e0130 | /2013-CaroloCup/sources/hesperia-light/libcore/include/core/wrapper/TCPAcceptorListener.h | 319507bef258ec2fd604d0fcc59c97497f79b718 | [] | no_license | Pedram87/CaroloCup | df23bd4dd57ff5eab8f8232f0f7e4aa7500c3215 | d97dd565acd4f11412032a9cf5c174d82b2ae285 | refs/heads/master | 2021-03-15T04:19:23.393383 | 2016-03-10T22:49:16 | 2016-03-10T22:49:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 644 | h | /*
* Copyright (c) Christian Berger and Bernhard Rumpe, Rheinisch-Westfaelische Technische Hochschule Aachen, Germany.
*
* The Hesperia Framework.
*/
#ifndef HESPERIA_CORE_WRAPPER_TCPACCEPTORLISTENER_H_
#define HESPERIA_CORE_WRAPPER_TCPACCEPTORLISTENER_H_
#include "core/native.h"
#include "core/wrapper/TCPConnection.h"
namespace core {
namespace wrapper {
class HESPERIA_API TCPAcceptorListener {
public:
virtual ~TCPAcceptorListener() {};
virtual void onNewConnection(TCPConnection* connection) = 0;
};
}
}
#endif /* HESPERIA_CORE_WRAPPER_TCPACCEPTORLISTENER_H_ */
| [
"bergerc@remote11.chalmers.se"
] | bergerc@remote11.chalmers.se |
fd636d514dae5f04fd2b92567e246f64f2da7d01 | e24b6a271eefc144c2b66d38779caf027c192c77 | /Demo1/mainwindow.cpp | 317217ac3217c7ed9fcbc00ba975bc6a1ebad973 | [] | no_license | sccai/EquipDemo | ac7f569a0569857e15d41d13eb595e0703a6b06b | f43c63d417aed1ea19c78e34f1259d6f436ca927 | refs/heads/master | 2022-12-15T05:36:49.699246 | 2020-09-23T06:26:54 | 2020-09-23T06:26:54 | 297,873,502 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,584 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include "QLabel"
#include "QApplication"
#include "QtNetwork"
#include "QMessageBox"
#include "iostream"
#include "string"
#include "QDebug"
#include "QTime"
#include "roundprogressbartest.h"
#include "parawindow.h"
#include "uidemo08.h"
#include "QMovie"
#include "flatui.h"
#include "formchild.h"
#include "tool/commhelper.h"
#include "PrintMod/printmod.h"
#include "tool/appinit.h"
#include "tool/fontawesomeicons.h"
#include "deviceinfo.h"
#include "SendMod/sendmod.h"
#include "control/lightbutton.h"
enum Excep
{
EXCEP_ONE,
EXCEP_TWO
};
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
translator(new QTranslator(qApp))
{
ui->setupUi(this);
QStringList qss;
//全局无焦点虚边框
qss.append(QString("*{outline:0px;}"));
this->setStyleSheet(qss.join(""));
this->InitEquip();
this->InitForm();
this->InitSlot();
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::InitEquip()
{
dicPrintModChecked["1"]=false;
dicPrintModChecked["2"]=false;
dicPrintModChecked["3"]=false;
//读取配置文件获取设备配置信息
//AppInit::Instance()->domparser->printAllMembers();//打印设备列表
int maxEquip= AppInit::Instance()->domparser->m_deviceinfolist.size();//总数量,设置圆环的百分比
ui->roundProgressBar_DeviceCheck->setRange(0, maxEquip);
ui->roundProgressBar_DeviceCheck->setValue(21);
ui->RoundBar_Slot1->setValue(100);
//从配置文件获取设备参数
for (const DeviceInfoModel::DeviceInfo& device : AppInit::Instance()->domparser->m_deviceinfolist)
{
if(device.DeviceType=="SendCardModule")
{
sendMod=new SendMod(QString::fromStdString(device.DeviceIP),device.DevicePort,this);
QObject::connect(sendMod,&SendMod::OnReceiveMsg,this,&MainWindow::OnRefresh);
QObject::connect(sendMod,&SendMod::OnSendMsg,this,&MainWindow::OnRefreshSend);
}
else if(device.DeviceType=="PrinterModule" && device.DeviceID=="1")
{
printMod1=new PrintMod(QString::fromStdString(device.DeviceIP),device.DevicePort,device.DeviceID,this);
QObject::connect(printMod1,&PrintMod::OnReceiveMsg,this,&MainWindow::OnRefresh);
QObject::connect(printMod1,&PrintMod::OnSendMsg,this,&MainWindow::OnRefreshSend);
}
else if(device.DeviceType=="PrinterModule" && device.DeviceID=="2")
{
printMod2=new PrintMod(QString::fromStdString(device.DeviceIP),device.DevicePort,device.DeviceID,this);
QObject::connect(printMod2,&PrintMod::OnReceiveMsg,this,&MainWindow::OnRefresh);
QObject::connect(printMod2,&PrintMod::OnSendMsg,this,&MainWindow::OnRefreshSend);
}
else if(device.DeviceType=="PrinterModule" && device.DeviceID=="3")
{
printMod3=new PrintMod(QString::fromStdString(device.DeviceIP),device.DevicePort,device.DeviceID,this);
QObject::connect(printMod3,&PrintMod::OnReceiveMsg,this,&MainWindow::OnRefresh);
QObject::connect(printMod3,&PrintMod::OnSendMsg,this,&MainWindow::OnRefreshSend);
}
else if(device.DeviceType=="ErasableLaminatinModule")
{
lamMod=new LamMod(QString::fromStdString(device.DeviceIP),device.DevicePort,this);
QObject::connect(lamMod,&LamMod::OnReceiveMsg,this,&MainWindow::OnRefresh);
QObject::connect(lamMod,&LamMod::OnSendMsg,this,&MainWindow::OnRefreshSend);
}
else if(device.DeviceType=="SortingModule")
{
sortMod=new SortMod(QString::fromStdString(device.DeviceIP),device.DevicePort,this);
QObject::connect(sortMod,&SortMod::OnReceiveMsg,this,&MainWindow::OnRefresh);
QObject::connect(sortMod,&SortMod::OnSendMsg,this,&MainWindow::OnRefreshSend);
}
else
{
//TODO 未完
}
}
}
void MainWindow::InitForm()
{
//======状态栏======
statusLayout = new QHBoxLayout;
statusLayout->setSpacing(0);
statusLayout->setMargin(0);
QLabel *per1 = new QLabel("系统时间:", this);
QLabel *per2 = new QLabel("2020/05/08 11:14", this);
//左对齐
//statusLayout->addWidget();
//右对齐
QHBoxLayout *time_layout = new QHBoxLayout;
time_layout->setSpacing(0);
time_layout->setContentsMargins(5,0,10,0);
time_layout->addWidget(per1);
time_layout->addWidget(per2);
QWidget *time_widget = new QWidget;
time_widget->setObjectName(QStringLiteral("time_widget"));
time_widget->setMinimumHeight(35);
time_widget->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);
time_widget->setLayout(time_layout);
statusLayout->addWidget(time_widget,0,Qt::AlignRight);//右对齐
//ui->statusBar->addPermanentWidget(per1); //窗体默认的状态栏,现实永久信息
//ui->statusBar->addPermanentWidget(per2);
//ui->statusBar->setStyleSheet(QString("QStatusBar::item{border: 0px}")); // 设置不显示label的边框
//ui->statusBar->setSizeGripEnabled(false); //设置是否显示右边的大小控制点
//ui->statusBar->showMessage("Status is here...", 3000); // 显示临时信息,时间3秒钟.
ui->statusBar->setLayout(statusLayout);
//======状态栏======
//设置无边框
setWindowFlags(Qt::FramelessWindowHint|Qt::WindowSystemMenuHint);
//设置右下角有个三角图标可以改变窗口大小
//this->setSizeGripEnabled(true);
isMousePressed = false;//判断鼠标是否按下的变量
//加载字体图标
iconFont = FontAweSomeIcons::Instance().getFont();
//窗口主布局
mainLayout = new QVBoxLayout;
mainLayout->setSpacing(0);
mainLayout->setMargin(0);
ui->widget->setLayout(mainLayout);
//生成标题栏
createTitle();
//生成标题栏的最大最小化等按钮
createTitleMenu();
//连接信号槽
connect(title_closeBtn,&QPushButton::clicked,this,&MainWindow::title_closeBtn_clicked);
connect(title_maxBtn,&QPushButton::clicked,this,&MainWindow::title_maxBtn_clicked);
connect(title_minBtn,&QPushButton::clicked,this,&MainWindow::title_minBtn_clicked);
FlatUI::Instance()->setPushButtonQss(ui->pushButton_AllInit, 5, 8, "#3498DB", "#FFFFFF", "#5DACE4", "#E5FEFF", "#2483C7", "#A0DAFB");
FlatUI::Instance()->setPushButtonQss(ui->pushButton_Start);
FlatUI::Instance()->setPushButtonQss(ui->pushButton_Pause, 5, 8, "#3498DB", "#FFFFFF", "#5DACE4", "#E5FEFF", "#2483C7", "#A0DAFB");
FlatUI::Instance()->setPushButtonQss(ui->pushButton_Stop, 5, 8, "#E74C3C", "#FFFFFF", "#EC7064", "#FFF5E7", "#DC2D1A", "#F5A996");
//QPixmap icon1(":/image/main_config.png");
//ui->pushButton_Para->setIcon(icon1);
ui->widget_img->setStyleSheet("border-image: url(:/image/img.png);");
}
//初始化卡槽样式
void MainWindow::InitSlot()
{
//圆环,设备自检百分比
ui->roundProgressBar_DeviceCheck->setDecimals(0);
ui->roundProgressBar_DeviceCheck->setBarStyle(QRoundProgressBar::StyleLine);
ui->roundProgressBar_DeviceCheck->setOutlinePenWidth(28);//外环的宽度
ui->roundProgressBar_DeviceCheck->setDataPenWidth(25);//内环的宽度
//卡槽1样式
ui->RoundBar_Slot1->setFormat("%v");//setFormat默认显示百分号例如:10%
ui->RoundBar_Slot1->setDecimals(0);
ui->RoundBar_Slot1->setBarStyle(QRoundProgressBar::StyleLine);
ui->RoundBar_Slot1->setOutlinePenWidth(20);//外环的宽度
ui->RoundBar_Slot1->setDataPenWidth(15);//内环的宽度
//卡槽2样式
QPalette p1;//字体颜色
p1.setBrush(QPalette::AlternateBase, Qt::gray);
p1.setColor(QPalette::Text, Qt::blue);
ui->RoundBar_Slot2->setFormat("%v");
//ui->RoundBar_Slot2->setPalette(p1);
ui->RoundBar_Slot2->setDecimals(0);
//卡槽3样式,根据百分比的数据变颜色gradientPoints
QGradientStops gradientPoints;
gradientPoints << QGradientStop(0, Qt::green) << QGradientStop(0.5, Qt::yellow) << QGradientStop(1, Qt::red);
QPalette p2(p1);
//p2.setBrush(QPalette::Base, Qt::lightGray);
//p2.setColor(QPalette::Text, Qt::magenta);
//p2.setColor(QPalette::Shadow, Qt::green);
//ui->RoundBar_Slot3->setPalette(p2);
ui->RoundBar_Slot3->setFormat("%v");
ui->RoundBar_Slot3->setDecimals(0);
//ui->RoundBar_Slot3->setNullPosition(QRoundProgressBar::PositionLeft);
//ui->RoundBar_Slot3->setDataColors(gradientPoints);
ui->RoundBar_Slot4->setFormat("%v");
ui->RoundBar_Slot4->setDecimals(0);
//打印耗材用量默认值
ui->widget_Battery_New->setDefault(0);
}
void MainWindow::createTitle()
{
//设置标题栏图标
title_icon = new QLabel;
title_icon->setObjectName(QStringLiteral("title_icon"));//设置对象名
title_icon->setMinimumSize(QSize(30,0));//设置最小大小
title_icon->setMaximumHeight(27);
title_icon->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Preferred);//设置尺寸策略
title_icon->setAlignment(Qt::AlignCenter);//居中显示
iconFont.setPointSize(10);//设置字体图标大小
title_icon->setFont(iconFont);//设置字体族
//设置FontAweSome图标
//title_icon->setText(FontAweSomeIcons::Instance().getIconChar(FontAweSomeIcons::IconIdentity::icon_apple));
//设置label显示图片,资源图片
title_icon->setPixmap(QPixmap(":/image/CETeam/logo.png"));
//设置标题栏名字
title_name = new QLabel;
title_name->setObjectName(QStringLiteral("title_name"));
title_name->setText(tr("通行证制证程序"));
title_name->setSizePolicy(QSizePolicy::Expanding,QSizePolicy::Preferred);
title_name->setAlignment(Qt::AlignVCenter|Qt::AlignCenter);
QFont font;
font.setFamily(QString("微软雅黑"));
font.setPointSize(14);
title_name->setFont(font);
title_name->setContentsMargins(5,2,0,0);
title_name->installEventFilter(this);//安装事件过滤器
//设置菜单按钮
title_menuBtn = new QPushButton;
title_menuBtn->setObjectName(QStringLiteral("title_menuBtn"));
title_menuBtn->setFixedWidth(35);
title_menuBtn->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Expanding);
title_menuBtn->setFlat(true);//设置按钮为扁平化样式
iconFont.setPointSize(10);
title_menuBtn->setFont(iconFont);
title_menuBtn->setText(FontAweSomeIcons::Instance().getIconChar(FontAweSomeIcons::IconIdentity::icon_list_ul));
title_menuBtn->setFocusPolicy(Qt::NoFocus);
//设置最小化按钮
title_minBtn = new QPushButton;
title_minBtn->setObjectName(QStringLiteral("title_minBtn"));
title_minBtn->setFixedWidth(35);
title_minBtn->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Expanding);
title_minBtn->setFlat(true);
iconFont.setPointSize(12);
title_minBtn->setFont(iconFont);
title_minBtn->setText(FontAweSomeIcons::Instance().getIconChar(FontAweSomeIcons::IconIdentity::icon_minus));
title_minBtn->setFocusPolicy(Qt::NoFocus);
//设置最大化按钮
title_maxBtn = new QPushButton;
title_maxBtn->setObjectName(QStringLiteral("title_maxBtn"));
title_maxBtn->setFixedWidth(35);
title_maxBtn->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Expanding);
title_maxBtn->setFlat(true);
title_maxBtn->setFont(iconFont);
title_maxBtn->setText(FontAweSomeIcons::Instance().getIconChar(FontAweSomeIcons::IconIdentity::icon_square_o));
title_maxBtn->setFocusPolicy(Qt::NoFocus);
//设置关闭按钮
title_closeBtn = new QPushButton;
title_closeBtn->setObjectName(QStringLiteral("title_closeBtn"));
title_closeBtn->setFixedWidth(40);
title_closeBtn->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Expanding);
title_closeBtn->setFlat(true);
iconFont.setPointSize(14);
title_closeBtn->setFont(iconFont);
title_closeBtn->setText(FontAweSomeIcons::Instance().getIconChar(FontAweSomeIcons::IconIdentity::icon_close));
title_closeBtn->setFocusPolicy(Qt::NoFocus);
//创建按钮布局
titleBtn_layout = new QHBoxLayout;
titleBtn_layout->setSpacing(0);
titleBtn_layout->setContentsMargins(0,0,0,0);
titleBtn_layout->addWidget(title_menuBtn);
titleBtn_layout->addWidget(title_minBtn);
titleBtn_layout->addWidget(title_maxBtn);
titleBtn_layout->addWidget(title_closeBtn);
//创建一个widget放置标题栏按钮
titleBtn_widget = new QWidget;
titleBtn_widget->setSizePolicy(QSizePolicy::Minimum,QSizePolicy::Preferred);
titleBtn_widget->setLayout(titleBtn_layout);
//创建标题栏主布局
title_layout = new QHBoxLayout;
title_layout->setSpacing(0);
title_layout->setContentsMargins(5,0,0,0);
title_layout->addWidget(title_icon);
title_layout->addWidget(title_name);
title_layout->addWidget(titleBtn_widget);
//创建标题栏widget放置标题栏元素
title_widget = new QWidget;
title_widget->setObjectName(QStringLiteral("title_widget"));
title_widget->setMinimumHeight(35);
title_widget->setSizePolicy(QSizePolicy::Preferred,QSizePolicy::Fixed);
title_widget->setLayout(title_layout);
//加入主布局
mainLayout->addWidget(title_widget);
}
void MainWindow::createTitleMenu()//创建标题栏菜单内容
{
//创建语言切换菜单
langue_menu = new QMenu(tr("Langue"));
setChinese = new QAction(tr("Chinese"),this);
setChinese->setIcon(QIcon(":/image/CETeam/china_32.png"));
setChinese->setCheckable(true);
setChinese->setChecked(true);
setEnglish = new QAction(tr("English"),this);
setEnglish->setIcon(QIcon(":/image/CETeam/english_32.png"));
setEnglish->setCheckable(true);
langue_menu->addAction(setChinese);
langue_menu->addAction(setEnglish);
langueGroup = new QActionGroup(this);
langueGroup->addAction(setEnglish);
langueGroup->addAction(setChinese);
//创建主题切换菜单
theme_menu = new QMenu(tr("Theme"));
setBlue = new QAction(tr("blue"),this);
setBlue->setCheckable(true);
setBlue->setChecked(true);
setBlack = new QAction(tr("black"),this);
setBlack->setCheckable(true);
theme_menu->addAction(setBlue);
theme_menu->addAction(setBlack);
themeGroup = new QActionGroup(this);
themeGroup->addAction(setBlue);
themeGroup->addAction(setBlack);
//参数设置
setPara = new QAction(tr("SetPara"),this);
//测试耗材用量
setConsumables = new QAction(tr("测试耗材用量"),this);
//测试导航栏
setNav = new QAction(tr("导航栏"),this);
//创建主菜单,将主题和语言菜单当二级菜单加入主菜单
title_menu = new QMenu;
title_menu->addAction(setPara);
title_menu->addSeparator();
title_menu->addMenu(langue_menu);
title_menu->addMenu(theme_menu);
title_menuBtn->setMenu(title_menu);//将主菜单设置到菜单按钮
title_menu->addSeparator();
title_menu->addAction(setConsumables);
title_menu->addAction(setNav);
//关联换肤和切换语言功能
connect(langueGroup,&QActionGroup::triggered,this,&MainWindow::changeLangue);
connect(themeGroup,&QActionGroup::triggered,this,&MainWindow::changeTheme);
connect(setPara,&QAction::triggered,this,&MainWindow::funcParamter);
connect(setNav,&QAction::triggered,this,&MainWindow::funcNav);
connect(setConsumables,&QAction::triggered,this,&MainWindow::funcConsumables);
}
void MainWindow::OnRefresh(QString ModType,QString HexString,int c)
{
CommHelper::Instance()->ShowLog(ModType+" 机构返回数据 ="+HexString);
ui ->textEdit ->append(ModType+" 机构返回数据 ="+HexString);//追加到编辑区中
if(ModType=="SendMod")
{
if(HexString.mid(4,2)=="AA" && HexString.mid(8,2)=="00")
{
sendCardModChecked=true;
ui ->textEdit ->append("进卡机构初始化成功");
ui->groupBox_SendMod->setStyleSheet("QGroupBox{background:green}"); //设定背景颜色为绿色
//圆环百分比
int current=ui->roundProgressBar_DeviceCheck->value();
qDebug()<<"已完成检测设备数 =" <<current+1;
ui->roundProgressBar_DeviceCheck->setValue(current+1);
}
//传感器参数
else if(HexString.mid(4,2)=="70")
{
//解析传感器参数
//QStringList returnValue= CommHelper::Instance()->HexStringToBytes("AA55700456010802D6");
QStringList returnValue= CommHelper::Instance()->HexStringToBytes(HexString);
//从第5位,开始是数据
//qDebug()<<"returnValue.length() = "<<returnValue.length();
//qDebug()<<returnValue;
//CommHelper::Instance()->ShowLog("解析结果 = "+returnValue.join(","));
QStringList statusList=CommHelper::Instance()->GetStatusBackData(returnValue);
sendMod->SetCurrentStatus(statusList);
}
}
else if(ModType=="PrintMod")
{
QString number= QString::number(c);
if(HexString.mid(4,2)=="AA" && HexString.mid(8,2)=="00")
{
dicPrintModChecked[number]=true;
ui ->textEdit ->append("打印机构初始化成功");
if(number=="1")
{
ui->groupBox_PrintMod1->setStyleSheet("QGroupBox{background:rgb(125,255,125)}");
}
else if(number=="2")
{
// ui->groupBox_PrintMod2->setStyleSheet("QGroupBox{background:rgb(125,255,125)}");
}
else if(number=="3")
{
// ui->groupBox_PrintMod3->setStyleSheet("QGroupBox{background:rgb(125,255,125)}");
}
//圆环百分比
int current=ui->roundProgressBar_DeviceCheck->value();
qDebug()<<"已完成检测设备数 =" <<current+1;
ui->roundProgressBar_DeviceCheck->setValue(current+1);
}
//传感器参数
else if(HexString.mid(4,2)=="70")
{
//解析传感器参数
QStringList returnValue= CommHelper::Instance()->HexStringToBytes(HexString);
//CommHelper::Instance()->ShowLog("解析结果 = "+returnValue.join(","));
QStringList statusList=CommHelper::Instance()->GetStatusBackData(returnValue);
if(number=="1")
{
printMod1->SetCurrentStatus(statusList);
}
else if(number=="2")
{
printMod2->SetCurrentStatus(statusList);
}
else if(number=="3")
{
printMod3->SetCurrentStatus(statusList);
}
}
}
else if(ModType=="LamMod")
{
if(HexString.mid(4,2)=="AA" && HexString.mid(8,2)=="00")
{
lamModChecked=true;
ui ->textEdit ->append("覆膜机构初始化成功");
ui->groupBox_Lam->setStyleSheet("QGroupBox{background:rgb(125,255,125)}");
//圆环百分比
int current=ui->roundProgressBar_DeviceCheck->value();
qDebug()<<"已完成检测设备数 =" <<current+1;
ui->roundProgressBar_DeviceCheck->setValue(current+1);
}
//传感器参数
else if(HexString.mid(4,2)=="70")
{
//解析传感器参数
QStringList returnValue= CommHelper::Instance()->HexStringToBytes(HexString);
//CommHelper::Instance()->ShowLog("解析结果 = "+returnValue.join(","));
QStringList statusList=CommHelper::Instance()->GetStatusBackData(returnValue);
lamMod->SetCurrentStatus(statusList);
}
}
else if(ModType=="SortMod")
{
if(HexString.mid(4,2)=="AA" && HexString.mid(8,2)=="00")
{
sortModChecked=true;
ui ->textEdit ->append("分拣机构初始化成功");
ui->groupBox_Sort->setStyleSheet("QGroupBox{background:rgb(125,255,125)}");
//圆环百分比
int current=ui->roundProgressBar_DeviceCheck->value();
qDebug()<<"已完成检测设备数 =" <<current+1;
ui->roundProgressBar_DeviceCheck->setValue(current+1);
}
//传感器参数
else if(HexString.mid(4,2)=="70")
{
//解析传感器参数
QStringList returnValue= CommHelper::Instance()->HexStringToBytes(HexString);
//CommHelper::Instance()->ShowLog("解析结果 = "+returnValue.join(","));
QStringList statusList=CommHelper::Instance()->GetStatusBackData(returnValue);
sortMod->SetCurrentStatus(statusList);
}
}
//TODO 判断传感器状态执行操作
ModChange(ModType);
}
void MainWindow::OnRefreshSend(QString ModType,QString HexString,int c)
{
CommHelper::Instance()->ShowLog(ModType+" 机构发送数据 ="+HexString);
ui ->textEdit_Send ->append(ModType+" 机构发送数据 ="+HexString);
}
void throwFun()
{
throw EXCEP_TWO;
}
void MainWindow::title_closeBtn_clicked()
{
this->close();//退出程序
}
void MainWindow::title_minBtn_clicked()
{
this->showMinimized();//最小化
}
void MainWindow::title_maxBtn_clicked()
{
if(isMaximized()){//判断窗口是否已经最大化,是则还原,不是则最大化
this->showNormal();
title_maxBtn->setText(FontAweSomeIcons::Instance().getIconChar(FontAweSomeIcons::IconIdentity::icon_square_o));
}else{
windowWidth = this->width();//记录窗口普通状态下的宽度,在窗口最大化而拖动了窗口是计算窗口位置用
this->showMaximized();
//改变最大化按钮的图标
title_maxBtn->setText(FontAweSomeIcons::Instance().getIconChar(FontAweSomeIcons::IconIdentity::icon_retweet));
}
}
void MainWindow::retranslateUI()//切换语言后刷新界面
{
langue_menu->setTitle(tr("Langue"));
setChinese->setText(tr("Chinese"));
setEnglish->setText(tr("English"));
title_name->setText(tr("通行证制证程序"));
theme_menu->setTitle(tr("Theme"));
setBlue->setText(tr("blue"));
setBlack->setText(tr("black"));
}
void MainWindow::changeLangue()//切换语言
{
if(setChinese->isChecked()){//判断选中了哪个语言
translator->load(":/langue/zh_cn.qm");//加载翻译文件
qApp->installTranslator(translator);//安装翻译文件
//刷新界面,因为没有Ui文件,所以要手动实现刷新(类似:setBlue->setText(tr("blue"));如果有使用Ui文件只需要调用ui->retranslateUi(this)即可
ui->retranslateUi(this);
retranslateUI();
}else if(setEnglish->isChecked()){
translator->load(":/langue/lang_en.qm");//加载翻译文件
qApp->installTranslator(translator);//安装翻译文件
//刷新界面,因为没有Ui文件,所以要手动实现刷新(类似:setBlue->setText(tr("blue"));重新执行一次赋值),如果有使用Ui文件只需要调用ui->retranslateUi(this)即可
ui->retranslateUi(this);
retranslateUI();
}
}
void MainWindow::changeTheme()//切换主题
{
if(setBlue->isChecked()){//判断选中了哪个主题,然后应用相应主题
QFile styleFile(QStringLiteral(":/css/blue.css"));//读取主题文件
if(styleFile.open(QFile::ReadOnly)){
QString qss = styleFile.readAll();
qApp->setStyleSheet(qss);//设置主题
qApp->setPalette(QPalette(QColor("#f0f0f0")));//设置窗体调色板
styleFile.close();
}else{
qDebug()<<"styleFile Loading error";
}
}else if(setBlack->isChecked()){
QFile styleFile(QStringLiteral(":/css/black.css"));
if(styleFile.open(QFile::ReadOnly)){
QString qss = styleFile.readAll();
qApp->setStyleSheet(qss);
qApp->setPalette(QPalette(QColor("#f0f0f0")));
styleFile.close();
}else{
qDebug()<<"styleFile Loading error";
}
}
}
void MainWindow::funcParamter()//设置参数
{
dialog=new ParaWindow(this);
//dialog->setModal(false);//非模态
//dialog->setModal(true);//模态,只能移动弹出的窗口,后面的窗口不能点击
dialog->show();
}
void MainWindow::funcNav()//测试导航
{
UIDemo08 *frm=new UIDemo08(this);
//frm->setModel(false);
frm->show();
}
void MainWindow::funcConsumables()//测试耗材
{
ui->widget_Battery_New->setValue(0);
}
bool MainWindow::eventFilter(QObject *obj, QEvent *e)//事件过滤器
{
if(obj == title_name){//判断发送信号的是否是标题栏
if(e->type() == QEvent::MouseButtonDblClick){//是否是双击
QMouseEvent *event = static_cast<QMouseEvent*>(e);
if(event->button() == Qt::LeftButton){//是否是鼠标左键
title_maxBtn_clicked();//双击则最大化或还原窗口
return true;
}
}
else if(e->type() == QEvent::MouseButtonPress){//是否是单击
QMouseEvent *event = static_cast<QMouseEvent*>(e);
if(event->button() == Qt::LeftButton){
isMousePressed = true;//单击则记录已经单击
mousePressPos = event->globalPos() - this->pos();//记录点击位置到窗口起始位置偏移
return true;
}
}else{
return false;
}
}
return QObject::eventFilter(obj,e);
}
void MainWindow::mouseMoveEvent(QMouseEvent *e)//处理鼠标移动事件
{
if(isMousePressed){//判断鼠标左键是否点击
if(isMaximized()){//窗口是否处于最大化状态,是则还原窗口,并计算偏移位置
this->showNormal();
if(mousePressPos.x() - windowWidth/2 <= 0){
mousePressPos = e->globalPos();
}else if(mousePressPos.x() + windowWidth/2 >= qApp->desktop()->availableGeometry().width()){
int desktopWidth = qApp->desktop()->availableGeometry().width();
int temp = desktopWidth - e->globalPos().x();
temp = windowWidth - temp;
mousePressPos = QPoint(temp,e->globalPos().y());
}else{
mousePressPos = QPoint(windowWidth/2,e->globalPos().y());
}
}
this->move(e->globalPos() - mousePressPos);//移动窗口
e->accept();
}
}
void MainWindow::mouseReleaseEvent(QMouseEvent *e)
{
Q_UNUSED(e)
isMousePressed = false;//鼠标点击置false
}
//发卡器
void MainWindow::on_pushButton_SendCardInit_clicked()
{
qDebug()<<"发卡器初始化";
}
//发卡器发卡
void MainWindow::on_pushButton_SendCard_clicked()
{
}
//初始化进卡机构
void MainWindow::on_pushButton_SmInit_clicked()
{
try {
if (sendMod==NULL)
{
qDebug()<<"对象为空";
return;
}
sendMod->InitDevice();
}
catch(Excep ex)
{
std::cout << "输入不是整数\n";
}
}
void MainWindow::on_pushButton_SmFlipin_clicked()
{
try
{
sendMod->FlipCardInFun();
}
catch(Excep ex)
{
std::cout << "输入不是整数\n";
}
}
void MainWindow::on_pushButton_SmFlipout_clicked()
{
sendMod->FlipCardOutFun();
}
void MainWindow::on_pushButton_SmCleanIn_clicked()
{
sendMod->CleanCardInFun();
}
void MainWindow::on_pushButton_SmCleanOut_clicked()
{
sendMod->CleanCardOutFun();
}
void MainWindow::on_pushButton_SmCleanCache_clicked()
{
sendMod->CardCacheOutFun();
}
//打印机构1
void MainWindow::on_pushButton_PrintMod1_clicked()
{
if (printMod1==NULL)
{
qDebug()<<"对象为空";
return;
}
printMod1->InitDevice();
}
//覆膜机构
void MainWindow::on_pushButton_LamModInit_clicked()
{
if (lamMod==NULL)
{
qDebug()<<"对象为空";
return;
}
lamMod->InitDevice();
}
//分拣机构
void MainWindow::on_pushButton_SortModInit_clicked()
{
if (sortMod==NULL)
{
qDebug()<<"对象为空";
return;
}
sortMod->InitDevice();
}
//机构传感器变化触发操作
void MainWindow::ModChange(QString modeType)
{
// QMetaEnum metaEnum = QMetaEnum::fromType<SendMod::ModStatus>();
// QMetaEnum metaEnumC1 = QMetaEnum::fromType<SendMod::CardStatus>();
// qDebug()<< metaEnum.valueToKey(sendMod->currentSendCardModStatus);
// qDebug()<< metaEnumC1.valueToKey(sendMod->currentRotationFlipCardStatus);
if(modeType=="SendMod") {
if(currentStatus==ApplicationStatus::Startup)
{
while(sendMod->currentRotationFlipStatus==SendMod::Idle &&sendMod->currentRotationFlipCardStatus==SendMod::HaveCard)
{
CommHelper::Instance()->sleepme(1000);
sendMod->FlipCardOutFun();
}
}
}
}
//all init
void MainWindow::on_pushButton_AllInit_clicked()
{
sendMod->InitDevice();
while(!sendCardModChecked)
{
CommHelper::Instance()->sleepme(1000);
}
printMod1->InitDevice();
while(!dicPrintModChecked["1"])
{
CommHelper::Instance()->sleepme(1000);
}
printMod2->InitDevice();
while(!dicPrintModChecked["2"])
{
CommHelper::Instance()->sleepme(1000);
}
printMod3->InitDevice();
while(!dicPrintModChecked["3"])
{
CommHelper::Instance()->sleepme(1000);
}
lamMod->InitDevice();
while(!lamModChecked)
{
CommHelper::Instance()->sleepme(1000);
}
sortMod->InitDevice();
CommHelper::Instance()->sleepme(5000);
sortMod->LightControl(4,0);
currentStatus=ApplicationStatus::InitFinish;
}
//start
void MainWindow::on_pushButton_Start_clicked()
{
ui->lightButton1->setBgColor(QColor(24, 189, 155));
if(currentStatus==ApplicationStatus::InitFinish)
{
currentStatus=ApplicationStatus::Startup;
}
else
{
QMessageBox::information(this,tr("Tip"),tr("Not InitDevice!"));
}
}
//pause
void MainWindow::on_pushButton_Pause_clicked()
{
ui->lightButton1->setBgColor(QColor(255, 107, 107));
}
void MainWindow::on_pushButton_Stop_clicked()
{
if (!(QMessageBox::information(this,tr("exit tip"),tr("Do you really want exit ?"),tr("Yes"),tr("No"))))
{
QApplication* app;
//app->quit();
app->exit(0);
}
}
void MainWindow::on_pushButton_SendCardInit_2_clicked()
{
}
void MainWindow::on_pushButton_ConnectDB_clicked()
{
}
| [
"349056681@qq.com"
] | 349056681@qq.com |
53181dda457a0faf00a88e59418e385c4edf115a | 35ae9cc47056b42a51391db3a8ce14fea9a29beb | /include/BasicDataStructures/VirtualMachine/VirtualMachineContext.h | f7853c64babad976fca0b4a58536784e5df7298f | [
"Apache-2.0"
] | permissive | dreamsxin/101_browser | 54c974d881e31671af07e6d023ce3f31284f401d | cadb28c5bfaab40c4be97c1c39e4c97fca0ccfb9 | refs/heads/master | 2021-01-01T15:55:13.934901 | 2012-04-20T20:22:34 | 2012-04-20T20:22:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,220 | h | /*
* Copyright 2008-2011 Wolfgang Keller
*
* 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 _VirtualMachineRunningContext
#define _VirtualMachineRunningContext
#include <vector>
#include "BasicDataStructures/VirtualMachine/InstructionContext.h"
struct VirtualMachineContext
{
size_t programCounter;
std::vector<Instruction> instructions;
std::vector<ReversibleContext> reversibleContexts;
protected:
bool _inReversibleMode;
public:
inline VirtualMachineContext() : programCounter(0) { }
void invoke();
// simply returns if not in reversible mode - so
// you have to check this by yourself
void revoke();
inline bool isInReversibleMode()
{
return _inReversibleMode;
}
};
#endif
| [
"wolfgangkeller@gmail.com"
] | wolfgangkeller@gmail.com |
76d8fd306e636268e5137fb41d7a5a2912d282e8 | 193a66bee070ed11b6c795a9d40502d4c502667b | /spoj/SUPPER.CPP | e30fa04068ce01af93ee79652c06d4fb9edd3552 | [] | no_license | 1tygoime/a | d3603b0f9dc043f3249b2574af060ed487193ac2 | a5ca1c8193959e8619adebf3430d35b652f5d399 | refs/heads/main | 2023-08-11T09:53:13.925780 | 2021-10-11T16:28:49 | 2021-10-11T16:28:49 | 416,415,399 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 990 | cpp | #include <bits/stdc++.h>
using namespace std;
int a[100005], L[100005], R[100005], n, m = 1, b[100005], lis;
multiset <int> s;
bool cmp(const int &a, const int &b){
return a > b;
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
for(int t = 10; t--; ){
cin >> n;
s.clear();
for(int i = 1; i <= n; i++) cin >> a[i];
memset(L, 0, sizeof(L));
memset(b, 0, sizeof(b));
memset(R, 0, sizeof(R));
L[1] = m = 1, b[1] = a[1];
for(int i = 2; i <= n; i++){
L[i] = lower_bound(b + 1, b + 1 + m, a[i]) - b,
m = max(m, L[i]),
b[L[i]] = a[i];
}
lis = m;
R[n] = m = 1, b[1] = a[n];
for(int i = n - 1; i >= 1; i--){
R[i]= lower_bound(b + 1, b + 1 + m, a[i], cmp) - b;
m = max(m, R[i]);
b[R[i]] = a[i];
}
for(int i = 1; i <= n; i++){
if(L[i] + R[i] - 1 == lis) s.insert(a[i]);
}
cout << s.size() << "\n";
for(const int &i: s) cout << i << ' ';
cout << "\n";
}
}
| [
"jssjsonsn@gmail.com"
] | jssjsonsn@gmail.com |
209752d16fcc2606f6fc6ca20d35831d4af929fa | 7bd101aa6d4eaf873fb9813b78d0c7956669c6f0 | /PPTShell_Multi/PPTShell/DUI/LoginWindowUI.cpp | 0050463f6d02f75a6097de7781a70929cb5794d7 | [] | no_license | useafter/PPTShell-1 | 3cf2dad609ac0adcdba0921aec587e7168ee91a0 | 16d9592e8fa2d219a513e9f8cfbaf7f7f3d3c296 | refs/heads/master | 2021-06-24T13:33:54.039140 | 2017-09-10T06:31:11 | 2017-09-10T06:35:10 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 17,531 | cpp | #include "stdafx.h"
#include "LoginWindowUI.h"
#include "NDCloud/NDCloudUser.h"
#include <regex>
#include "Util/Util.h"
#include "DUI/GroupExplorer.h"
#include "DUI/ThirdPartyLogin.h"
CLoginWindowUI::CLoginWindowUI()
{
m_bSetChapter = false;
m_bLogining = false;
m_pUserNameEdit = NULL;
m_pPasswordEdit = NULL;
}
CLoginWindowUI::~CLoginWindowUI()
{
NDCloudUser::GetInstance()->CancelLogin();
}
void CLoginWindowUI::Init(HWND hMainWnd)
{
m_hMainWnd = hMainWnd;
m_pUserNameEdit = dynamic_cast<CEditClearUI*>(FindSubControl(_T("username")));
m_pPasswordEdit = dynamic_cast<CEditClearUI*>(FindSubControl(_T("password")));
m_pUserNameEdit->SetHandleSpecialKeydown(true);
m_pPasswordEdit->SetHandleSpecialKeydown(true);
m_pLoginTipLayout = dynamic_cast<CVerticalLayoutUI*>(FindSubControl(_T("LoginTipLayout")));
m_pLoginTip = dynamic_cast<CLabelUI*>(m_pLoginTipLayout->FindSubControl(_T("LoginTip")));
m_pSavePasswordUI = dynamic_cast<CCheckBoxUI*>(FindSubControl(_T("SavePassword")));
m_pAutomaticLoginUI = dynamic_cast<CCheckBoxUI*>(FindSubControl(_T("AutomaticLogin")));
m_pErrorTipUserNameLabel = dynamic_cast<CLabelUI*>(FindSubControl(_T("error_tip_username")));
m_pErrorTipPasswordLabel = dynamic_cast<CLabelUI*>(FindSubControl(_T("error_tip_password")));
m_pErrorTipNetLabel = dynamic_cast<CLabelUI*>(FindSubControl(_T("error_tip_net")));
m_pLoginBtn = dynamic_cast<CButtonUI*>(FindSubControl(_T("LoginBtn")));
TCHAR szUserName[MAX_PATH + 1];
TCHAR szPassword[MAX_PATH + 1];
if(GetPassword(szUserName, szPassword))
{
m_pUserNameEdit->SetText(szUserName);
m_pUserNameEdit->SetClearBtn();
m_pPasswordEdit->SetText(szPassword);
m_pPasswordEdit->SetClearBtn();
m_pSavePasswordUI->SetCheck(true);
}
tstring strPath = GetLocalPath();
strPath += _T("\\setting\\Config.ini");
TCHAR szBuff[MAX_PATH + 1];
GetPrivateProfileString(_T("config"), _T("AutoLogin"), _T("false"), szBuff, MAX_PATH, strPath.c_str());
if(_tcsicmp(szBuff, _T("true")) == 0)
{
m_pAutomaticLoginUI->SetCheck(true);
}
m_pQQLoginBtn = dynamic_cast<CButtonUI*>(FindSubControl(_T("qqLoginBtn")));
m_pWeiboLoginBtn = dynamic_cast<CButtonUI*>(FindSubControl(_T("weiboLoginBtn")));
m_pNdLoginBtn = dynamic_cast<CButtonUI*>(FindSubControl(_T("ndLoginBtn")));
m_pQQLoginBtn->OnEvent += MakeDelegate(this, &CLoginWindowUI::OnLoginEvent);
m_pWeiboLoginBtn->OnEvent += MakeDelegate(this, &CLoginWindowUI::OnLoginEvent);
m_pNdLoginBtn->OnEvent += MakeDelegate(this, &CLoginWindowUI::OnLoginEvent);
}
void CLoginWindowUI::MobileLogin(CStream *loginStream)
{
HideLoginTip();
SetLoginBtnEnable(false);
m_bSetChapter = false;
NDCloudUser::GetInstance()->MobileLogin(loginStream, MakeHttpDelegate(this, &CLoginWindowUI::OnUserLogin));
return ;
}
void CLoginWindowUI::Login()
{
//#ifdef _DEBUG
// ShowLoginComplete();
// return;
//#endif
HideLoginTip();
tstring strUserName = m_pUserNameEdit->GetText();
tstring strPassword = m_pPasswordEdit->GetText();
if(strUserName.empty() || strUserName == m_pUserNameEdit->GetTipText())
{
ShowLoginTip(0, _T("用户名不能为空"));
return;
}
else if(strPassword.empty() || strPassword == m_pPasswordEdit->GetTipText())
{
ShowLoginTip(1, _T("密码不能为空"));
return;
}
/*
//正则
//
std::tr1::regex szUserNameRule("^\\d+$");
std::tr1::smatch sResult;
if(std::tr1::regex_search(strUserName, sResult, szUserNameRule))
{
//手机
std::tr1::regex szUserNameRuleEx("^1[34578]\\d{9}$");
if(!std::tr1::regex_search(strUserName, sResult, szUserNameRuleEx))
{
ShowLoginTip(0, _T("您输入的手机号码格式不正确 ,请输入11位有效的手机号码"));
//ShowLoginTip(0, _T("用户名格式不正确"));
return;
}
}
else
{
//邮箱
std::tr1::regex szUserNameRuleEx("^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$");
if(!std::tr1::regex_search(strUserName, sResult, szUserNameRuleEx))
{
ShowLoginTip(0, _T("您输入的邮箱格式有误 ,请输入正确的邮箱"));
//ShowLoginTip(0, _T("用户名格式不正确"));
return;
}
}*/
SetLoginBtnEnable(false);
m_bSetChapter = false;
m_bLogining = true;
NDCloudUser::GetInstance()->Login(strUserName.c_str(), strPassword.c_str(), _T("org_esp_app_prod"), MakeHttpDelegate(this, &CLoginWindowUI::OnUserLogin));
}
void CLoginWindowUI::ShowLoginTip( int nType,tstring strTip )
{
if(nType == 0)
{
m_pErrorTipUserNameLabel->SetText(strTip.c_str());
m_pErrorTipUserNameLabel->SetVisible(true);
}
else if(nType == 1)
{
m_pErrorTipPasswordLabel->SetText(strTip.c_str());
m_pErrorTipPasswordLabel->SetVisible(true);
}
else if(nType == 2)
{
m_pErrorTipNetLabel->SetText(strTip.c_str());
m_pErrorTipNetLabel->SetVisible(true);
}
m_bLogining = false;
SetLoginBtnEnable(true);
}
void CLoginWindowUI::HideLoginTip()
{
if(m_pErrorTipUserNameLabel->IsVisible())
{
m_pErrorTipUserNameLabel->SetVisible(false);
}
if(m_pErrorTipPasswordLabel->IsVisible())
{
m_pErrorTipPasswordLabel->SetVisible(false);
}
if(m_pErrorTipNetLabel->IsVisible())
{
m_pErrorTipNetLabel->SetVisible(false);
}
}
void CLoginWindowUI::CalcText( HDC hdc, RECT& rc, LPCTSTR lpszText, int nFontId, UINT format, UITYPE_FONT nFontType, int c)
{
if (nFontType == UIFONT_GDI)
{
HFONT hFont = GetManager()->GetFont(nFontId);
HFONT hOldFont = (HFONT)::SelectObject(hdc, hFont);
if ((DT_SINGLELINE & format))
{
SIZE size = {0};
::GetTextExtentExPoint(hdc, lpszText, c == -1 ? _tcslen(lpszText) : c, 0, NULL, NULL, &size);
rc.right = rc.left + size.cx;
rc.bottom = rc.top + size.cy;
}
else
{
format &= ~DT_END_ELLIPSIS;
format &= ~DT_PATH_ELLIPSIS;
if (!(DT_SINGLELINE & format)) format |= DT_WORDBREAK | DT_EDITCONTROL;
::DrawText(hdc, lpszText, c, &rc, format | DT_CALCRECT);
}
::SelectObject(hdc, hOldFont);
}
}
void CLoginWindowUI::ShowLoginComplete()
{
tstring strUserName = NDCloudUser::GetInstance()->GetUserName();
tstring strPassword = NDCloudUser::GetInstance()->GetPassword();
if(m_pSavePasswordUI->GetCheck())//选择保存密码
{
SavePassword(strUserName, strPassword);
}
else
{
RemoveSaveAccount();
m_pUserNameEdit->SetText(m_pUserNameEdit->GetTipText().c_str());
m_pUserNameEdit->SetClearBtn();
m_pPasswordEdit->SetText(m_pPasswordEdit->GetTipText().c_str());
m_pPasswordEdit->SetClearBtn();
}
tstring strPath = GetLocalPath();
strPath += _T("\\setting\\Config.ini");
if(m_pAutomaticLoginUI->GetCheck())
WritePrivateProfileString(_T("config"), _T("AutoLogin"), _T("true"), strPath.c_str());
else
WritePrivateProfileString(_T("config"), _T("AutoLogin"), _T("false"), strPath.c_str());
tstring strRealUserName = NDCloudUser::GetInstance()->GetRealName();
TCHAR szBuff[MAX_PATH];
_stprintf(szBuff, _T("{f 23}{c #11B0A7}%s{/c} {c #6F6F6F}老师{/c} {c #FFFFFF}登录成功{/c}{/f}"), strRealUserName.c_str());
TCHAR szBuff1[MAX_PATH];
_stprintf(szBuff1, _T("%s 老师 登录成功"), strRealUserName.c_str());
m_pLoginTip->SetText(szBuff);
m_bLogining = false;
RECT rcCalc = {0};
rcCalc.right = 600;
rcCalc.top = 60;
CalcText(GetManager()->GetPaintDC(), rcCalc, szBuff1, m_pLoginTip->GetFont(), DT_CALCRECT | DT_WORDBREAK | DT_EDITCONTROL | DT_LEFT|DT_NOPREFIX, UIFONT_GDI);
m_pLoginTip->SetFixedWidth(rcCalc.right - rcCalc.left);
SetLoginBtnEnable(true);
m_pLoginTipLayout->SetVisible(true);
SetTimer(m_hMainWnd, WM_LOGIN_COMPLETE, 1000, (TIMERPROC)CGroupExplorerUI::TimerProcComplete);
}
bool CLoginWindowUI::OnUserLogin( void * pParam )
{
THttpNotify* pNotify = static_cast<THttpNotify*>(pParam);
if(pNotify->dwErrorCode != 0)
{
ShowLoginTip(2, _T("当前网络不太好,无法登录,请检查网络连接"));
return false;
}
CNDCloudUser* pUser = NDCloudUser::GetInstance();
int nStep = pUser->GetCurStep();
switch( nStep )
{
case UCSTEP_LOGIN:
{
if( pUser->IsSuccess() )
{
CHttpDownloadManager* pHttpDownloadManager = HttpDownloadManager::GetInstance();
TCHAR szPost[1024];
_stprintf(szPost, _T("/101ppt/getChapter.php?account=%d"),NDCloudUser::GetInstance()->GetUserId());
if(pHttpDownloadManager)
{
pHttpDownloadManager->AddTask(_T("p.101.com"),szPost, _T(""), _T("Get"),_T(""), 80,MakeHttpDelegate(this, &CLoginWindowUI::OnUCLoginSaveStatus) ,MakeHttpDelegate(NULL), MakeHttpDelegate(NULL) );
}
}
else
{
tstring strErrorCode = pUser->GetErrorCode();
tstring strErrorMessage = pUser->GetErrorMessage();
ShowLoginTip(1, strErrorMessage);
}
}
break;
}
return true;
}
void CLoginWindowUI::SetLoginBtnEnable( bool bEnable )
{
if(bEnable)
{
m_pLoginBtn->SetEnabled(true);
m_pLoginBtn->SetText(_T("登录"));
}
else
{
m_pLoginBtn->SetEnabled(false);
m_pLoginBtn->SetText(_T("登录中..."));
}
}
void CLoginWindowUI::OnEditTabChangeLogin(CControlUI * pControl)
{
if(m_pUserNameEdit && pControl == m_pUserNameEdit)
{
m_pPasswordEdit->SetFocus();
m_pPasswordEdit->SetSelAll();
}
else if(m_pPasswordEdit && pControl == m_pPasswordEdit)
{
m_pUserNameEdit->SetFocus();
m_pUserNameEdit->SetSelAll();
}
}
void CLoginWindowUI::NotifyTabToEdit()
{
CControlUI* pControl = GetManager()->FindControl(_T("loginLayout"));
if (pControl)
{
if(m_pUserNameEdit->IsFocused())
{
GetManager()->SendNotify(m_pUserNameEdit, DUI_MSGTYPE_TABSWITCH);
}
else if(m_pPasswordEdit->IsFocused())
{
GetManager()->SendNotify(m_pPasswordEdit, DUI_MSGTYPE_TABSWITCH);
}
}
}
bool CLoginWindowUI::OnUCLoginSaveStatus( void * pParam )
{
THttpNotify* pNotify = static_cast<THttpNotify*>(pParam);
if(pNotify->dwErrorCode == 0)
{
pNotify->pData[pNotify->nDataSize] = '\0';
tstring str = pNotify->pData;
Json::Reader reader;
Json::Value root;
tstring strChapter;
bool res = reader.parse(str, root);
if( res )
{
if( !root["Chapter"].isNull() )
{
strChapter = root["Chapter"].asCString();
TCHAR szSectionCode[MAX_PATH] = _T("");
TCHAR szGradeCode[MAX_PATH] = _T("");
TCHAR szCourseCode[MAX_PATH] = _T("");
TCHAR szEditionCode[MAX_PATH] = _T("");
TCHAR szSubEditionCode[MAX_PATH] = _T("");
TCHAR szChapterGuid[MAX_PATH] = _T("");
TCHAR szGrade[MAX_PATH] = _T("");
if(sscanf_s(strChapter.c_str(),_T("%[^/]/%[^/]/%[^/]/%[^/]/%[^/]/%[^/]/%[^/]"),
szSectionCode, sizeof(szSectionCode) - 1,
szGradeCode, sizeof(szGradeCode) - 1,
szCourseCode, sizeof(szCourseCode) - 1,
szEditionCode, sizeof(szEditionCode) - 1,
szSubEditionCode,sizeof(szSubEditionCode) - 1,
szChapterGuid, sizeof(szChapterGuid) - 1,
szGrade, sizeof(szGrade) - 1) == 7)
{
m_strSectionCode = szSectionCode;
m_strGradeCode = szGradeCode;
m_strCourseCode = szCourseCode;
m_strEditionCode = szEditionCode;
m_strSubEditionCode = szSubEditionCode;
m_strChapterGuid = szChapterGuid;
m_strGrade = szGrade;
m_strGrade = Utf8ToAnsi(m_strGrade);
CCategoryTree * pCategoryTree = NULL;
NDCloudGetCategoryTree(pCategoryTree);
if(pCategoryTree)
{
CategoryNode * pGradeNode = pCategoryTree->FindNode(m_strSectionCode,m_strGradeCode, _T(""), _T(""));
if(pGradeNode && pGradeNode->pFirstChild)
{
pGradeNode = pCategoryTree->FindNode(m_strSectionCode,m_strGradeCode,m_strCourseCode, _T(""));
if(pGradeNode && pGradeNode->pFirstChild)
{
tstring strUrl = NDCloudComposeUrlBookInfo(
m_strSectionCode.c_str(),
m_strGradeCode.c_str(),
m_strCourseCode.c_str(),
m_strEditionCode.c_str(),
m_strSubEditionCode.c_str(),
0,
20
);
NDCloudDownload(strUrl, MakeHttpDelegate(this, &CLoginWindowUI::OnGetBookGUID));
}
else
{
tstring strUrl = NDCloudComposeUrlCategory(m_strGradeCode,m_strCourseCode);
NDCloudDownload(strUrl, MakeHttpDelegate(this, &CLoginWindowUI::OnGetEdition));
return true;
}
}
else
{
tstring strUrl = NDCloudComposeUrlCategory(m_strGradeCode);
NDCloudDownload(strUrl, MakeHttpDelegate(this, &CLoginWindowUI::OnGetCourse));
}
}
return true;
}
}
}
}
ShowLoginComplete();
return true;
}
bool CLoginWindowUI::OnGetCourse( void * pParam )
{
THttpNotify* pNotify = static_cast<THttpNotify*>(pParam);
if(pNotify->dwErrorCode == 0)
{
BOOL bRet = NDCloudDecodeCategory(pNotify->pData, pNotify->nDataSize, m_strSectionCode, m_strGradeCode, _T(""), _T(""));
if(bRet)
{
CCategoryTree * pCategoryTree = NULL;
NDCloudGetCategoryTree(pCategoryTree);
CategoryNode * pGradeNode = pCategoryTree->FindNode(m_strSectionCode,m_strGradeCode,m_strCourseCode, _T(""));
if(pGradeNode && pGradeNode->pFirstChild)
{
tstring strUrl = NDCloudComposeUrlBookInfo(
m_strSectionCode.c_str(),
m_strGradeCode.c_str(),
m_strCourseCode.c_str(),
m_strEditionCode.c_str(),
m_strSubEditionCode.c_str(),
0,
20
);
NDCloudDownload(strUrl, MakeHttpDelegate(this, &CLoginWindowUI::OnGetBookGUID));
}
else
{
tstring strUrl = NDCloudComposeUrlCategory(m_strGradeCode,m_strCourseCode);
NDCloudDownload(strUrl, MakeHttpDelegate(this, &CLoginWindowUI::OnGetEdition));
}
return true;
}
}
ShowLoginComplete();
return true;
}
bool CLoginWindowUI::OnGetEdition( void * pParam )
{
THttpNotify* pNotify = static_cast<THttpNotify*>(pParam);
if(pNotify->dwErrorCode == 0)
{
BOOL bRet = NDCloudDecodeCategory(pNotify->pData, pNotify->nDataSize,m_strSectionCode,m_strGradeCode,m_strCourseCode, _T(""));
if(bRet)
{
tstring strUrl = NDCloudComposeUrlBookInfo(
m_strSectionCode.c_str(),
m_strGradeCode.c_str(),
m_strCourseCode.c_str(),
m_strEditionCode.c_str(),
m_strSubEditionCode.c_str(),
0,
20
);
NDCloudDownload(strUrl, MakeHttpDelegate(this, &CLoginWindowUI::OnGetBookGUID));
return true;
}
}
ShowLoginComplete();
return true;
}
bool CLoginWindowUI::OnGetBookGUID( void * pParam )
{
THttpNotify* pNotify = static_cast<THttpNotify*>(pParam);
if(pNotify->dwErrorCode == 0)
{
tstring strBookGUID;
BOOL bRet = NDCloudDecodeBookGUID(pNotify->pData, pNotify->nDataSize , strBookGUID);
if(bRet && strBookGUID.length())
{
tstring strUrl = NDCloudComposeUrlChapterInfo(strBookGUID);
NDCloudDownload(strUrl, MakeHttpDelegate(this, &CLoginWindowUI::OnGetChapter));
return true;
}
}
ShowLoginComplete();
return true;
}
bool CLoginWindowUI::OnGetChapter( void * pParam )
{
THttpNotify* pNotify = static_cast<THttpNotify*>(pParam);
if(pNotify->dwErrorCode == 0)
{
m_pChapterTree = new CChapterTree;
BOOL bRet = NDCloudDecodeChapterInfo(pNotify->pData, pNotify->nDataSize, m_pChapterTree);
if(bRet && m_strChapterGuid != NDCloudGetChapterGUID() && m_pChapterTree)
{
m_bSetChapter = true;
}
else
delete m_pChapterTree;
}
//
ShowLoginComplete();
return true;
}
void CLoginWindowUI::SetCheckBoxAutoLogin()
{
if(m_pAutomaticLoginUI->IsSelected())
{
if(!m_pSavePasswordUI->IsSelected())
{
m_pSavePasswordUI->Selected(true);
}
}
}
void CLoginWindowUI::SetCheckBoxSavePassword()
{
if(!m_pSavePasswordUI->IsSelected())
{
if(m_pAutomaticLoginUI->IsSelected())
{
m_pAutomaticLoginUI->Selected(false);
}
}
}
bool CLoginWindowUI::OnLoginEvent( void * pParam )
{
TEventUI* pNotify = (TEventUI*)pParam;
if (pNotify->Type == UIEVENT_BUTTONDOWN )
{
CThirdPartyLoginUI * pThirdPartyLogin = ThirdPartyLoginUI::GetInstance();
HWND hwnd = AfxGetApp()->m_pMainWnd->GetSafeHwnd();
// CRect rect;
// GetWindowRect(hwnd, &rect);
if(pThirdPartyLogin->GetHWND() == NULL)
{
pThirdPartyLogin->Create(hwnd, _T(""), WS_POPUP, NULL,0,0,0,0);
}
// ::MoveWindow(pThirdPartyLogin->GetHWND(), rect.left, rect.top, rect.Width(), rect.Height(), TRUE);
pThirdPartyLogin->CenterWindow();
CButtonUI* pButton = dynamic_cast<CButtonUI*>(pNotify->pSender);
if(pButton->GetName() == _T("weiboLoginBtn"))
{
pThirdPartyLogin->Init(1);
}
else if(pButton->GetName() == _T("qqLoginBtn"))
{
pThirdPartyLogin->Init(2);
}
else if(pButton->GetName() == _T("ndLoginBtn"))
{
pThirdPartyLogin->Init(3);
}
// MoveWindow(pThirdPartyLogin->GetHWND(), rect.left, rect.top, rect.Width(), rect.Height(), TRUE);
pThirdPartyLogin->ShowWindow(true);
}
return true;
}
bool CLoginWindowUI::GetLoginStatus()
{
return m_bLogining;
}
void CLoginWindowUI::ClearEditStatus()
{
TCHAR szUserName[MAX_PATH + 1];
TCHAR szPassword[MAX_PATH + 1];
if(GetPassword(szUserName, szPassword))
{
m_pUserNameEdit->SetText(szUserName);
m_pUserNameEdit->SetClearBtn();
m_pPasswordEdit->SetText(szPassword);
m_pPasswordEdit->SetClearBtn();
m_pSavePasswordUI->SetCheck(true);
}
else
{
m_pUserNameEdit->SetText(m_pUserNameEdit->GetTipText().c_str());
m_pUserNameEdit->SetClearBtn();
m_pPasswordEdit->SetText(m_pPasswordEdit->GetTipText().c_str());
m_pPasswordEdit->SetClearBtn();
m_pSavePasswordUI->SetCheck(false);
}
tstring strPath = GetLocalPath();
strPath += _T("\\setting\\Config.ini");
TCHAR szBuff[MAX_PATH + 1];
GetPrivateProfileString(_T("config"), _T("AutoLogin"), _T("false"), szBuff, MAX_PATH, strPath.c_str());
if(_tcsicmp(szBuff, _T("true")) == 0)
m_pAutomaticLoginUI->SetCheck(true);
else
m_pAutomaticLoginUI->SetCheck(false);
m_pErrorTipUserNameLabel->SetVisible(false);
m_pErrorTipPasswordLabel->SetVisible(false);
m_pErrorTipNetLabel->SetVisible(false);
}
| [
"794549193@qq.com"
] | 794549193@qq.com |
2e85d12d64f648e93e03fd58703f100ba34a75b6 | f0e73ba5633e6f9d944f490cb95b6cc0c2e26c4e | /DrillTweetESP32/DrillTweetESP32.ino | ea3b4e29bcab07ec4a30cb14119a2582a579152b | [] | no_license | sdaitzman/drillTweet | 2aba7c4cd45cc01715e19f2073ba2ddb3a2aff47 | 8e6f7f73af5884786e975d92ae5613ad5b2a8d18 | refs/heads/master | 2020-04-10T06:43:52.210419 | 2019-02-03T07:47:37 | 2019-02-03T07:47:37 | 160,862,918 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 987 | ino | #include "config.h"
#include <WiFi.h>
#include <WebSocketClient.h>
#define samples 120
WebSocketClient webSocketClient;
WiFiClient client;
void setup() {
Serial.begin(115200);
delay(10);
// Set up ADC
pinMode(33, INPUT_PULLUP);
pinMode(13, OUTPUT);
analogSetCycles(2);
analogSetSamples(1);
analogSetWidth(10);
wifiConnect();
delay(50);
serverConnect();
}
void loop() {
String data;
if (client.connected()) {
webSocketClient.getData(data);
if (data.length() > 0) {
Serial.print("Received data: ");
Serial.println(data);
if (data == "getReading") {
Serial.println("Sending a reading!");
float current = getCurrent();
webSocketClient.sendData(String(current));
Serial.println(current);
Serial.println(WiFi.macAddress());
}
}
} else {
Serial.println("Disconnected from WebSocket server. Will attempt reconnect in 5 seconds...");
delay(5000);
serverConnect();
}
}
| [
"sdaitzman@olin.edu"
] | sdaitzman@olin.edu |
ff367cf045117ddaf445166fd5c0b30606c05daa | 8a7af7ea37a74c6a9e7888bf82c04f2c9ad81ac2 | /hdf5pp/handle.hpp | 0bab044e1af8fb4faa4bbf9523f5b2e5e655ce11 | [] | no_license | andreabedini/visaw-triangular-only-two-flatperm | 958cee732bef868b959ede0fb078b367ef740174 | c57be1940b6225727c7537e9aee26844d8cb34a8 | refs/heads/master | 2021-01-10T13:48:46.457346 | 2015-02-05T23:42:58 | 2015-02-05T23:42:58 | 51,583,136 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 948 | hpp | #ifndef HANDLE_HPP
#define HANDLE_HPP
#include <hdf5.h>
namespace hdf5 {
class handle {
hid_t _id;
public:
handle() : _id(0) { }
explicit handle(hid_t&& id) : _id(id) { }
handle(handle const& o) : _id(o._id) {
if (_id) H5Iinc_ref(_id);
}
handle(handle&& o) : _id(std::move(o._id)) { }
virtual ~handle() {
if (_id) H5Idec_ref(_id);
}
handle& operator=(handle const& o)
{
if (_id) H5Idec_ref(_id);
_id = o._id;
if (_id) H5Iinc_ref(_id);
return *this;
}
handle& operator=(handle&& o)
{
using namespace std;
swap(_id, o._id);
return *this;
}
bool is_valid() const { return H5Iis_valid(_id) == true; }
hid_t getId() const { return _id; }
void flush()
{
herr_t err = H5Fflush(getId(), H5F_SCOPE_GLOBAL);
if (err < 0) throw std::runtime_error("H5Fflush failed");
}
};
}
#endif
| [
"andrea@andreabedini.com"
] | andrea@andreabedini.com |
48e36568bafd103c26a00a0022449b6872b3fa83 | 81a733de6ed46f8a73916a4fbe512a2fd2555b0e | /src/ofxFace.h | 3970cd71f2544395a14bb9b19a79a03701f9fd6a | [
"MIT"
] | permissive | rezaali/ofxMesh | 8e8603825a594d665f6d565a75cd760f7fefb072 | 33cb94feaa85ae075a1733f3b3440ecba01a3810 | refs/heads/master | 2021-01-17T09:40:59.372252 | 2014-08-26T10:08:36 | 2014-08-26T10:08:36 | 19,436,419 | 11 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 954 | h | #ifndef OFX_FACE
#define OFX_FACE
#include "ofRectangle.h"
#include <vector>
using namespace std;
class ofxVertex;
class ofxEdge;
class ofxFace
{
public:
ofxFace(int _id);
~ofxFace();
int id;
int getID();
void sortPoints();
void clearVerts();
void clearEdges();
void clear();
void deleteVerts();
void deleteEdges();
ofxFace *clone();
int getNumVerts();
int getNumEdges();
ofRectangle getBoundingRect();
void addEdge(ofxEdge *edge);
void addVertex(ofxVertex *vertex);
ofxVertex *getVertex(int index);
ofxEdge *getEdge(int index);
vector<ofxEdge *> edges; //All edges that make up this edge
vector<ofxVertex *> verts; //All verts that make the face
ofVec3f centroid;
ofVec3f &calculateCentroid();
ofVec3f &getCentroid();
ofVec3f normal;
ofVec3f &calculateNormal();
ofVec3f &getNormal();
};
#endif
| [
"syed.reza.ali@gmail.com"
] | syed.reza.ali@gmail.com |
62cb78043d4f86d92b6f39713e590811b7c21394 | d6617d5eca1d99f60f66249f7679f7ca11d6a16a | /密码检查.cpp | 3edf65b393398b2ba3fe3ccf1d7abbb5b6e72ed4 | [] | no_license | qiyutao/NewCoder | 7ccee34700a5a7aa640d7e5d88d9ed4883b3364b | 84979f24dc1b82b30b94669a0fc91e074e41bf51 | refs/heads/master | 2020-04-18T22:41:44.720547 | 2019-03-11T13:41:15 | 2019-03-11T13:41:15 | 167,801,726 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,023 | cpp | #include <iostream>
#include <string>
#include <list>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
cin >> n;
string lines[n];
string results[n];
for(int i=0;i<n;i++) {
cin >> lines[i];
}
for(int i=0;i<n;i++) {
if(lines[i].size() < 8 || (lines[i][0]>='0'&&lines[i][0]<='9')) {
results[i] = "NO";
continue;
}
int table[3] = {0,0,0};
for(int j = 0;j<lines[i].size();j++) {
if(lines[i].at(j)>='A'&&lines[i].at(j)<='Z') {
table[0] = 1;
} else if(lines[i].at(j)>='a'&&lines[i].at(j)<='z') {
table[1] = 1;
} else {
table[2] = 1;
}
}
int count = table[0] + table[1] + table[2];
if(count <= 1) {
results[i] = "NO";
continue;
}
results[i] = "YES";
}
for(int i=0;i<n;i++) {
cout<< results[i] << endl;
}
return 0;
}
| [
"noreply@github.com"
] | qiyutao.noreply@github.com |
fac6f69bbf2e9019469549ed4466ab4364e43f59 | 6710593a8befd769fb592c835749bc3d48665b57 | /11.1/vector.h/randwork.cpp | 9eabbab9546790e56de57a0e8e2d5de65fbf0301 | [] | no_license | heathjay/C-_study | 30f0df6be5fcf59db542a29479972cfdd6ae401c | 68213d3fb1e6903db8f30a057e48f9c05cedda62 | refs/heads/master | 2022-11-07T05:58:58.824555 | 2020-06-20T22:31:13 | 2020-06-20T22:31:13 | 268,048,698 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,085 | cpp | #include<iostream>
#include<cstdlib>
#include<ctime>
#include"vector.h"
int main(){
using namespace std;
using VECTOR::Vector;
srand(time(0));//seed rang-number generator
double direction;
Vector step;
Vector result(0.0,0.0);
unsigned long steps = 0;
double target;
double dstep;
cout << "Enter target distance (q to quit): ";
while(cin >> target){
cout << "Enter step length: ";
if(!(cin >> dstep)) break;
while(result.magval() < target){
direction = rand() % 360;
step.set(dstep,direction,'p');
result = result + step;
steps++;
}
cout << "after " << steps << " steps , the subject has the following location :\n";
cout <<result <<endl;
result.polar_mode();
cout << " or\n" <<result <<endl;
cout <<"Average outward distance per step = " << result.magval()/ steps << endl;
steps = 0;
result.set(0.0,0.0);
cout << "Enter target distance (q to quit): ";
}
cout << "Bye!n";
return 0;
} | [
"jpmzy@163.com"
] | jpmzy@163.com |
e5ceee0cb22e2e31ca2f9d35042460be2c39ca44 | 39bfb3ebbfacb209685ced948195c346eb2bc368 | /Src/Generator/Noise/OctavePerlin.h | f000cd8b9e32daee021c71a7683e03938ea2861b | [
"MIT"
] | permissive | ira20022/clonecraft | 41a053764cf05d6f90349b2bb4a99899041611f2 | d3723ae2419a57ca8cb07f39f6905eaeafce74f5 | refs/heads/master | 2023-08-17T11:10:55.087579 | 2021-09-23T15:48:29 | 2021-09-23T15:48:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 451 | h | #pragma once
#include "Maths/GlmCommon.h"
#include <vector>
class OctavePerlin {
public:
OctavePerlin(int octaves = 4, double persistence = 0.5, double frequency = 1.0);
double getNoise(dvec2 pos) const;
private:
int m_octaves; // The more octaves, the more accurate is the noise
double m_persistence; // The less persistence, the less next octaves will have impact
double m_frequency; // The more frequency, the more dense is the noise
};
| [
"v.dheur@hotmail.be"
] | v.dheur@hotmail.be |
bd064721fc9e979fec71be36860aa83885b080bb | 006ff11fd8cfd5406c6f4318f1bafa1542095f2a | /AnalysisDataFormats/TrackInfo/src/RecoTracktoTP.cc | 080d764dd64a5eaf4f85b1b46b6b29dd8fdb3289 | [] | permissive | amkalsi/cmssw | 8ac5f481c7d7263741b5015381473811c59ac3b1 | ad0f69098dfbe449ca0570fbcf6fcebd6acc1154 | refs/heads/CMSSW_7_4_X | 2021-01-19T16:18:22.857382 | 2016-08-09T16:40:50 | 2016-08-09T16:40:50 | 262,608,661 | 0 | 0 | Apache-2.0 | 2020-05-09T16:10:07 | 2020-05-09T16:10:07 | null | UTF-8 | C++ | false | false | 1,909 | cc | #include "AnalysisDataFormats/TrackInfo/interface/RecoTracktoTP.h"
// Constructors
RecoTracktoTP::RecoTracktoTP()
{
SetBeamSpot(math::XYZPoint(-9999.0, -9999.0, -9999.0));
SetTrackingParticlePCA(GlobalPoint(-9999.0, -9999.0, -9999.0));
SetTrackingParticleMomentumPCA(GlobalVector(-9999.0, -9999.0, -9999.0));
}
RecoTracktoTP::~RecoTracktoTP()
{
}
TrackingParticle RecoTracktoTP::TPMother(unsigned short i) const
{
std::vector<TrackingParticle> result;
if( TP().parentVertex().isNonnull())
{
if(TP().parentVertex()->nSourceTracks() > 0)
{
for(TrackingParticleRefVector::iterator si = TP().parentVertex()->sourceTracks_begin();
si != TP().parentVertex()->sourceTracks_end(); si++)
{
for(TrackingParticleRefVector::iterator di = TP().parentVertex()->daughterTracks_begin();
di != TP().parentVertex()->daughterTracks_end(); di++)
{
if(si != di)
{
result.push_back(**si);
break;
}
}
if(result.size()) break;
}
}
else
{
return TrackingParticle();
}
}
else
{
return TrackingParticle();
}
return i < result.size() ? result[i] : TrackingParticle();
}
int RecoTracktoTP::numTPMothers() const
{
int count = 0;
for(TrackingParticleRefVector::iterator si = TP().parentVertex()->sourceTracks_begin();
si != TP().parentVertex()->sourceTracks_end(); si++)
{
for(TrackingParticleRefVector::iterator di = TP().parentVertex()->daughterTracks_begin();
di != TP().parentVertex()->daughterTracks_end(); di++)
{
if(si != di) count++;
break;
}
if(count>0) break;
}
return count;
}
| [
"giulio.eulisse@gmail.com"
] | giulio.eulisse@gmail.com |
3aed725c3fc4c9498e4c585cf85b6dfdf9b3c677 | 8a90d85e4a0536ae64d7599649aeece6d2cac6b7 | /paddle/fluid/inference/anakin/convert/test_elementwise_op.cc | 3a437f5fdb565609667b7a862c9b2bb13cdbeded | [
"Apache-2.0"
] | permissive | VictorZhang2014/Paddle | decbfbf6cfa154e3581b67b9928843e98cd96fbe | 01d1c22b1b316585d96b9a4b3c537d61ae08d14b | refs/heads/develop | 2020-05-19T04:43:08.213074 | 2019-05-04T00:49:34 | 2019-05-04T00:49:34 | 184,832,005 | 0 | 0 | Apache-2.0 | 2019-05-04T00:49:35 | 2019-05-03T23:32:53 | C++ | UTF-8 | C++ | false | false | 1,832 | cc | /* Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
#include <gtest/gtest.h>
#include "paddle/fluid/inference/anakin/convert/elementwise.h"
#include "paddle/fluid/inference/anakin/convert/op_converter.h"
#include "paddle/fluid/inference/anakin/convert/ut_helper.h"
namespace paddle {
namespace inference {
namespace anakin {
static void test_elementwise_op(const std::string &op_type) {
std::unordered_set<std::string> parameters;
framework::Scope scope;
AnakinConvertValidation validator(parameters, &scope);
validator.DeclInputVar("x", {1, 1, 2, 2});
validator.DeclInputVar("y", {1, 1, 2, 2});
validator.DeclOutputVar("out", {1, 1, 2, 2});
// Prepare Op description
framework::OpDesc desc;
desc.SetType(op_type);
desc.SetInput("X", {"x"});
desc.SetInput("Y", {"y"});
desc.SetOutput("Out", {"out"});
int axis = -1;
desc.SetAttr("axis", axis);
validator.SetOp(*desc.Proto());
validator.Execute(1);
}
TEST(elementwise_op, native_add) { test_elementwise_op("elementwise_add"); }
TEST(elementwise_op, native_mul) { test_elementwise_op("elementwise_mul"); }
} // namespace anakin
} // namespace inference
} // namespace paddle
USE_OP(elementwise_add);
USE_ANAKIN_CONVERTER(elementwise_add);
USE_OP(elementwise_mul);
USE_ANAKIN_CONVERTER(elementwise_mul);
| [
"zlx_hg@163.com"
] | zlx_hg@163.com |
bd3086322141dd992acd3743f0445a3103b7d8e9 | b006f0996d346266ca6547a2733ad9d2dd015312 | /avl_tree.tpp | fd3fbc06bcd8c98b4f240adef2d194d9277c0cec | [] | no_license | LuisNY/avl_tree | 7751032404e368256b346a8f1aa391ffcc88a08c | 11746ea602962b8b6630c3780cc9563aea9120bd | refs/heads/master | 2020-07-22T18:23:07.884711 | 2019-09-09T10:56:00 | 2019-09-09T10:56:00 | 207,288,050 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,806 | tpp | // avl_tree.tpp
namespace avl_tree {
template <class T>
void TREE<T>::inOrderTraverse(NODE<T> *root){
if(root == nullptr) { return; }
inOrderTraverse(root->left);
std::cout << root->val << std::endl;
inOrderTraverse(root->right);
}
template <class T>
void TREE<T>::PostOrderTraverse(NODE<T> *root){
if(root == nullptr) { return; }
PostOrderTraverse(root->left);
PostOrderTraverse(root->right);
std::cout << root->val << std::endl;
}
template <class T>
void TREE<T>::PreOrderTraverse(NODE<T>* root){
if(root == nullptr){ return; }
std::stack<NODE<T>*> stk;
stk.push(root);
while(!stk.empty()){
NODE<T>* curr = stk.top();
stk.pop();
std::cout << curr->val << std::endl;
if (curr->right != nullptr) {
stk.push(curr->right);
}
if (curr->left != nullptr) {
stk.push(curr->left);
}
}
}
template <class T>
int TREE<T>::getHeight(NODE<T>* root) {
if(root == nullptr){
return 0;
}
return 1 + std::max(getHeight(root->left), getHeight(root->right));
}
template <class T>
int TREE<T>::difference(NODE<T>* root) {
if(root==nullptr){
return 0;
}
return getHeight(root->left) - getHeight(root->right);
}
template <class T>
NODE<T>* TREE<T>::rotateLeft(NODE<T>* root){
NODE<T>* new_root = root->right;
root->right = new_root->left;
new_root->left = root;
return new_root;
}
template <class T>
NODE<T>* TREE<T>::rotateRight(NODE<T>* root){
NODE<T>* new_root = root->left;
root->left = new_root->right;
new_root->right = root;
return new_root;
}
template <class T>
NODE<T>* TREE<T>::balance(NODE<T>* root) {
int diff = difference(root);
if (diff < -1) {
if (difference(root->right) < 0) {
root = rotateLeft(root);
} else {
root->right = rotateRight(root->right);
root = rotateLeft(root);
}
} else if (diff > 1) {
if (difference(root->left) > 0) {
root = rotateRight(root);
} else {
root->left = rotateLeft(root->left);
root = rotateRight(root);
}
}
return root;
}
template <class T>
NODE<T>* TREE<T>::insert(NODE<T>* root, T val) {
if(root==nullptr){
root = new NODE<T>(val);
return root;
} else if(root->val > val){
root->left = insert(root->left, val);
root = balance(root);
} else { // root->val <= val
root->right = insert(root->right, val);
root = balance(root);
}
return root;
}
template <class T>
NODE<T>* TREE<T>::find(NODE<T>* root, T val){
if(root==nullptr){
return nullptr;
}
if(root->val == val){
return root;
}
if(root->val > val){
return find(root->left, val);
} else {
return find(root->right, val);
}
}
template <class T>
NODE<T>* TREE<T>::deleteNode(NODE<T>* root, T val){
if(root == nullptr){
return root;
}
if(root->val == val) {
if (root->left == nullptr) {
NODE<T>* succ = root->right;
delete root;
return succ;
} else if (root->right == nullptr) {
NODE<T>* succ = root->left;
delete root;
return succ;
}
NODE<T>* succ = root->left;
while(succ->right!=nullptr){
succ = succ->right;
}
root->val = succ->val;
root->left = deleteNode(root->left, root->val);
root = balance(root);
return root;
}
if(root->val > val){
root->left = deleteNode(root->left, val);
root = balance(root);
} else {
root->right = deleteNode(root->right, val);
root = balance(root);
}
return root;
}
} | [
"luigipepe90@gmail.com"
] | luigipepe90@gmail.com |
322f5a05e114473c1c744dc900d5fbe46c43edf5 | 4344a545005cac2442293157e33e6720e84d01ae | /solution1/syn/systemc/myproject.h | 6ec0772547c24f690b6597165089d73d6ddf9629 | [] | no_license | skkwan/hls_taus | 382b7e4553ab94c4095bcb4eef80cfea0462361b | 4ab0603393d23dc789d609e3ecdb0d4efc761835 | refs/heads/master | 2020-09-23T09:02:50.712105 | 2020-02-28T22:25:20 | 2020-02-28T22:25:20 | 225,460,174 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,639 | h | // ==============================================================
// RTL generated by Vivado(TM) HLS - High-Level Synthesis from C, C++ and SystemC
// Version: 2018.2
// Copyright (C) 1986-2018 Xilinx, Inc. All Rights Reserved.
//
// ===========================================================
#ifndef _myproject_HH_
#define _myproject_HH_
#include "systemc.h"
#include "AESL_pkg.h"
#include "decision_function_1.h"
namespace ap_rtl {
struct myproject : public sc_module {
// Port declarations 19
sc_in_clk ap_clk;
sc_in< sc_logic > ap_rst;
sc_in< sc_logic > ap_start;
sc_out< sc_logic > ap_done;
sc_out< sc_logic > ap_idle;
sc_out< sc_logic > ap_ready;
sc_in< sc_lv<18> > x_0_V;
sc_in< sc_lv<18> > x_1_V;
sc_in< sc_lv<18> > x_2_V;
sc_in< sc_lv<18> > x_3_V;
sc_in< sc_lv<18> > x_4_V;
sc_in< sc_lv<18> > x_5_V;
sc_in< sc_lv<18> > x_6_V;
sc_in< sc_lv<18> > x_7_V;
sc_in< sc_lv<18> > x_8_V;
sc_out< sc_lv<18> > score_0_V;
sc_out< sc_logic > score_0_V_ap_vld;
sc_in< sc_lv<18> > score_1_V;
sc_out< sc_lv<18> > ap_return;
// Module declarations
myproject(sc_module_name name);
SC_HAS_PROCESS(myproject);
~myproject();
sc_trace_file* mVcdFile;
ofstream mHdltvinHandle;
ofstream mHdltvoutHandle;
decision_function_1* grp_decision_function_1_fu_105;
sc_signal< sc_lv<1> > ap_CS_fsm;
sc_signal< sc_logic > ap_CS_fsm_pp0_stage0;
sc_signal< sc_logic > ap_enable_reg_pp0_iter0;
sc_signal< sc_logic > ap_enable_reg_pp0_iter1;
sc_signal< sc_logic > ap_enable_reg_pp0_iter2;
sc_signal< sc_logic > ap_enable_reg_pp0_iter3;
sc_signal< sc_logic > ap_enable_reg_pp0_iter4;
sc_signal< sc_logic > ap_enable_reg_pp0_iter5;
sc_signal< sc_logic > ap_enable_reg_pp0_iter6;
sc_signal< sc_logic > ap_enable_reg_pp0_iter7;
sc_signal< sc_logic > ap_enable_reg_pp0_iter8;
sc_signal< sc_logic > ap_enable_reg_pp0_iter9;
sc_signal< sc_logic > ap_enable_reg_pp0_iter10;
sc_signal< sc_logic > ap_enable_reg_pp0_iter11;
sc_signal< sc_logic > ap_enable_reg_pp0_iter12;
sc_signal< sc_logic > ap_enable_reg_pp0_iter13;
sc_signal< sc_logic > ap_enable_reg_pp0_iter14;
sc_signal< sc_logic > ap_enable_reg_pp0_iter15;
sc_signal< sc_logic > ap_enable_reg_pp0_iter16;
sc_signal< sc_logic > ap_enable_reg_pp0_iter17;
sc_signal< sc_logic > ap_enable_reg_pp0_iter18;
sc_signal< sc_logic > ap_enable_reg_pp0_iter19;
sc_signal< sc_logic > ap_enable_reg_pp0_iter20;
sc_signal< sc_logic > ap_enable_reg_pp0_iter21;
sc_signal< sc_logic > ap_idle_pp0;
sc_signal< bool > ap_block_state1_pp0_stage0_iter0;
sc_signal< bool > ap_block_state2_pp0_stage0_iter1;
sc_signal< bool > ap_block_state3_pp0_stage0_iter2;
sc_signal< bool > ap_block_state4_pp0_stage0_iter3;
sc_signal< bool > ap_block_state5_pp0_stage0_iter4;
sc_signal< bool > ap_block_state6_pp0_stage0_iter5;
sc_signal< bool > ap_block_state7_pp0_stage0_iter6;
sc_signal< bool > ap_block_state8_pp0_stage0_iter7;
sc_signal< bool > ap_block_state9_pp0_stage0_iter8;
sc_signal< bool > ap_block_state10_pp0_stage0_iter9;
sc_signal< bool > ap_block_state11_pp0_stage0_iter10;
sc_signal< bool > ap_block_state12_pp0_stage0_iter11;
sc_signal< bool > ap_block_state13_pp0_stage0_iter12;
sc_signal< bool > ap_block_state14_pp0_stage0_iter13;
sc_signal< bool > ap_block_state15_pp0_stage0_iter14;
sc_signal< bool > ap_block_state16_pp0_stage0_iter15;
sc_signal< bool > ap_block_state17_pp0_stage0_iter16;
sc_signal< bool > ap_block_state18_pp0_stage0_iter17;
sc_signal< bool > ap_block_state19_pp0_stage0_iter18;
sc_signal< bool > ap_block_state20_pp0_stage0_iter19;
sc_signal< bool > ap_block_state21_pp0_stage0_iter20;
sc_signal< bool > ap_block_state22_pp0_stage0_iter21;
sc_signal< bool > ap_block_pp0_stage0_11001;
sc_signal< bool > ap_block_pp0_stage0_subdone;
sc_signal< sc_lv<18> > grp_decision_function_1_fu_105_ap_return;
sc_signal< sc_logic > grp_decision_function_1_fu_105_ap_ce;
sc_signal< bool > ap_block_pp0_stage0;
sc_signal< bool > ap_block_pp0_stage0_01001;
sc_signal< sc_lv<1> > ap_NS_fsm;
sc_signal< sc_logic > ap_idle_pp0_0to20;
sc_signal< sc_logic > ap_reset_idle_pp0;
sc_signal< sc_logic > ap_enable_pp0;
static const sc_logic ap_const_logic_1;
static const sc_logic ap_const_logic_0;
static const sc_lv<1> ap_ST_fsm_pp0_stage0;
static const sc_lv<32> ap_const_lv32_0;
static const bool ap_const_boolean_1;
static const bool ap_const_boolean_0;
static const sc_lv<18> ap_const_lv18_0;
// Thread declarations
void thread_ap_clk_no_reset_();
void thread_ap_CS_fsm_pp0_stage0();
void thread_ap_block_pp0_stage0();
void thread_ap_block_pp0_stage0_01001();
void thread_ap_block_pp0_stage0_11001();
void thread_ap_block_pp0_stage0_subdone();
void thread_ap_block_state10_pp0_stage0_iter9();
void thread_ap_block_state11_pp0_stage0_iter10();
void thread_ap_block_state12_pp0_stage0_iter11();
void thread_ap_block_state13_pp0_stage0_iter12();
void thread_ap_block_state14_pp0_stage0_iter13();
void thread_ap_block_state15_pp0_stage0_iter14();
void thread_ap_block_state16_pp0_stage0_iter15();
void thread_ap_block_state17_pp0_stage0_iter16();
void thread_ap_block_state18_pp0_stage0_iter17();
void thread_ap_block_state19_pp0_stage0_iter18();
void thread_ap_block_state1_pp0_stage0_iter0();
void thread_ap_block_state20_pp0_stage0_iter19();
void thread_ap_block_state21_pp0_stage0_iter20();
void thread_ap_block_state22_pp0_stage0_iter21();
void thread_ap_block_state2_pp0_stage0_iter1();
void thread_ap_block_state3_pp0_stage0_iter2();
void thread_ap_block_state4_pp0_stage0_iter3();
void thread_ap_block_state5_pp0_stage0_iter4();
void thread_ap_block_state6_pp0_stage0_iter5();
void thread_ap_block_state7_pp0_stage0_iter6();
void thread_ap_block_state8_pp0_stage0_iter7();
void thread_ap_block_state9_pp0_stage0_iter8();
void thread_ap_done();
void thread_ap_enable_pp0();
void thread_ap_enable_reg_pp0_iter0();
void thread_ap_idle();
void thread_ap_idle_pp0();
void thread_ap_idle_pp0_0to20();
void thread_ap_ready();
void thread_ap_reset_idle_pp0();
void thread_ap_return();
void thread_grp_decision_function_1_fu_105_ap_ce();
void thread_score_0_V();
void thread_score_0_V_ap_vld();
void thread_ap_NS_fsm();
void thread_hdltv_gen();
};
}
using namespace ap_rtl;
#endif
| [
"kystephkwan2@gmail.com"
] | kystephkwan2@gmail.com |
6bd5fc645e3eac1620b230085308ca74559cbcd7 | cc7b04f0e991071fa747c892b25d3bafe32b8460 | /Chap02/WaitThread.cpp | 1e724834cdc874c760cb1833e1a870160e207d29 | [] | no_license | BlockJJam/Windows_System_Programming_KernelObjectSync | b0598f7b07942a05f995d41c4a004f97f49930a5 | 18e9d09ec6a5f7bb9b078d52633ed0d5d0d34f48 | refs/heads/master | 2020-09-14T11:58:30.328284 | 2019-11-21T07:49:25 | 2019-11-21T07:49:25 | 223,122,453 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 740 | cpp | #include "stdafx.h"
#include "Windows.h"
#include "iostream"
using namespace std;
DWORD WINAPI ThreadProc(PVOID pParam)
{
DWORD dwDelay = (DWORD)pParam;
cout << ">>>> Thread " << GetCurrentThreadId() << " enter." << endl;
Sleep(5000);
cout << "<<<< Thread " << GetCurrentThreadId() << " leave." << endl;
return dwDelay;
}
void _tmain()
{
cout << "Main thread creating sub thread..." << endl;
DWORD dwThreadID = 0;
HANDLE hThread = CreateThread(NULL, 0, ThreadProc, (PVOID)5000, 0, &dwThreadID);
WaitForSingleObject(hThread, INFINITE);
DWORD dwExitCode;
GetExitCodeThread(hThread, &dwExitCode);
cout << "Sub thread " << dwThreadID << " terminated. ";
cout << "Exit Code = " << dwExitCode << endl;
CloseHandle(hThread);
} | [
"blockjjam99@gmail.com"
] | blockjjam99@gmail.com |
8808182e5fa5da58f296c7cbc0e7a2462adc8876 | 8dff321eb861eccc42c6b602f2f4a4f96e90dc86 | /arduino_menu.ino | 236707799a62c6f45d33e2ba0bc59359d989385a | [] | no_license | nsisong/arduino-menu-option | db2ba15b56608bf60e8eb8e2dd5901c67c8a28a7 | 97bb25abd65e08523cc66ec0be9539cb5cd26072 | refs/heads/master | 2022-12-28T15:50:54.040278 | 2020-10-12T13:40:49 | 2020-10-12T13:40:49 | 303,099,289 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,688 | ino | /* ARDUINO menu code - four buttons actions
*
* DEVELOPED BY NSISONG PETER ©2020 @KODEHAUZ
* this code demonstrate the use of button for menu sellections in arduino
* the library used in this code is the liquid crystal distplay which can be downloaded from arduino .cc
* for this project demonstration, i will be using a 16 by 2 lcd display
*
* this code print power perameters and their values below
*
* the Pin configurations are as follows
* sda = A4
* scl = A5
*
*/
#include "Wire.h" // For I2C
#include "LCD.h" // For LCD
#include "LiquidCrystal_I2C.h" // Added library*
//Set the pins on the I2C chip used for LCD connections
//ADDR,EN,R/W,RS,D4,D5,D6,D7
//#include <LiquidCrystal.h>
//LiquidCrystal lcd(6, 7, 5, 4, 3, 2);
LiquidCrystal_I2C lcd(0x27,2,1,0,4,5,6,7); // 0x27 is the default I2C bus address of the backpack-see article
//Input & Button Logic
const int numOfInputs = 4;
const int inputPins[numOfInputs] = {8,9,10,11};
int inputState[numOfInputs];
int lastInputState[numOfInputs] = {LOW,LOW,LOW,LOW};
bool inputFlags[numOfInputs] = {LOW,LOW,LOW,LOW};
long lastDebounceTime[numOfInputs] = {0,0,0,0};
long debounceDelay = 5;
//LCD Menu Logic
const int numOfScreens = 4;// number of menues
int currentScreen = 0;
String screens[numOfScreens][2] = {{"Tidal volume","TV"}, {"In time/Out time", "I:E"},
{"Positive .. pressure","PEEP"},{"Respiratory Rate.","breaths/min"}};
int parameters[numOfScreens];
void setup() {
Serial.begin(9600);
lcd.begin(20, 4);
lcd.setBacklightPin(3,POSITIVE); // BL, BL_POL
lcd.setBacklight(HIGH);
lcd.setCursor(5,1);
lcd.print("KODEHAUZ");
lcd.setCursor(4,2);
lcd.print("COVID VENT");
delay (5000);
lcd.clear();
lcd.setCursor(4,0);
lcd.print("PLEASE READ");
lcd.setCursor(4,1);
lcd.print("USER MANUAL");
lcd.setCursor(4,2);
lcd.print("BEFORE USE !!!");
delay(5000);
for(int i = 0; i < numOfInputs; i++) {
pinMode(inputPins[i], INPUT);
digitalWrite(inputPins[i], HIGH); // pull-up 20k
}
}
void loop() {
setInputFlags();
resolveInputFlags();
}
void setInputFlags() {
for(int i = 0; i < numOfInputs; i++) {
int reading = digitalRead(inputPins[i]);
if (reading != lastInputState[i]) {
lastDebounceTime[i] = millis();
}
if ((millis() - lastDebounceTime[i]) > debounceDelay) {
if (reading != inputState[i]) {
inputState[i] = reading;
if (inputState[i] == HIGH) {
inputFlags[i] = HIGH;
}
}
}
lastInputState[i] = reading;
}
}
void resolveInputFlags() {
for(int i = 0; i < numOfInputs; i++) {
if(inputFlags[i] == HIGH) {
inputAction(i);
inputFlags[i] = LOW;
printScreen();
}
}
}
void inputAction(int input) {
if(input == 0) {
if (currentScreen == 0) {
currentScreen = numOfScreens-1;
}else{
currentScreen--;
}
}else if(input == 1) {
if (currentScreen == numOfScreens-1) {
currentScreen = 0;
}else{
currentScreen++;
}
}else if(input == 2) {
parameterChange(0);
}else if(input == 3) {
parameterChange(1);
}
}
void parameterChange(int key) {
if(key == 0) {
parameters[currentScreen]++;
}else if(key == 1) {
parameters[currentScreen]--;
}
}
void printScreen() {
lcd.clear();
lcd.print("RunTime : ");
lcd.setCursor(0,1);
lcd.print(screens[currentScreen][0]);
lcd.setCursor(0,2);
lcd.print(parameters[currentScreen]);
lcd.print(" ");
lcd.print(screens[currentScreen][1]);
Serial.println(screens[currentScreen][0]);
// Serial.setCursor(0,1);
Serial.println(parameters[currentScreen]);
// Serial.print(" ");
Serial.println(screens[currentScreen][1]);
}
| [
"edetnsisongpeter@gmail.com"
] | edetnsisongpeter@gmail.com |
6969e6f59ac47bae64bab97fd37a30f9c759d838 | c7df3b262e94b4cb2853284ce83a7eb0903761dd | /Plugin/MainTextLineBreak.cpp | b9a630fd6721c460bbe40858d0399c070cb07bee | [
"MIT"
] | permissive | amanwithcommonsense/CK2dll | c5777dbf633b5f655122336517cf46741dce25f4 | 6e3c48ec1cdae69513af73d304bd7ec79aa9e295 | refs/heads/master | 2020-04-07T07:04:51.849949 | 2018-11-17T12:03:36 | 2018-11-17T12:03:36 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 12,728 | cpp | #include "stdinc.h"
#include "byte_pattern.h"
namespace MainTextLineBreak {
/*-----------------------------------------------*/
uintptr_t func1_v28;
uintptr_t func1_v30;
/*-----------------------------------------------*/
errno_t func_hook(CK2Version version) {
std::string desc = "func hook";
switch (version) {
case v2_8_X:
// push esi
byte_pattern::temp_instance().find_pattern("56 8B F1 8B 46 14 83 F8 10 72 0E");
if (byte_pattern::temp_instance().has_size(2, desc)) {
func1_v28 = byte_pattern::temp_instance().get_first().address();
}
else return CK2ERROR1;
return NOERROR;
case v3_0_X:
// push esi
byte_pattern::temp_instance().find_pattern("56 8B F1 8B 46 14 83 F8 10 72 0E");
if (byte_pattern::temp_instance().has_size(3, desc)) {
func1_v30 = byte_pattern::temp_instance().get_first().address();
}
else return CK2ERROR1;
return NOERROR;
}
return CK2ERROR1;
}
/*-----------------------------------------------*/
uintptr_t dd_5;
uintptr_t dd_4;
__declspec(naked) void dd_1_v28()
{
__asm {
cmp cl, ESCAPE_SEQ_1;
jz dd_3;
cmp cl, ESCAPE_SEQ_2;
jz dd_3;
cmp cl, ESCAPE_SEQ_3;
jz dd_3;
cmp cl, ESCAPE_SEQ_4;
jz dd_3;
cmp cl, 0x20;
jz dd_3;
jmp dd_2;
dd_3:
mov eax, esi;
dd_2:
mov [ebp - 0x1C], eax;
xor eax, eax;
cmp cl, ESCAPE_SEQ_1;
jz dd_6;
cmp cl, ESCAPE_SEQ_2;
jz dd_6;
cmp cl, ESCAPE_SEQ_3;
jz dd_6;
cmp cl, ESCAPE_SEQ_4;
jz dd_6;
cmp cl, 0x20;
jz dd_6;
push dd_5;
ret;
dd_6:
push dd_4;
ret;
}
}
__declspec(naked) void dd_1_v30()
{
__asm {
cmp cl, ESCAPE_SEQ_1;
jz dd_3;
cmp cl, ESCAPE_SEQ_2;
jz dd_3;
cmp cl, ESCAPE_SEQ_3;
jz dd_3;
cmp cl, ESCAPE_SEQ_4;
jz dd_3;
cmp cl, 0x20;
jz dd_3;
jmp dd_2;
dd_3:
mov eax, esi;
dd_2:
mov dword ptr [ebp - 0x18], eax; // ここの値だけ違う
xor eax, eax;
cmp cl, ESCAPE_SEQ_1;
jz dd_6;
cmp cl, ESCAPE_SEQ_2;
jz dd_6;
cmp cl, ESCAPE_SEQ_3;
jz dd_6;
cmp cl, ESCAPE_SEQ_4;
jz dd_6;
cmp cl, 0x20;
jz dd_6;
push dd_5;
ret;
dd_6:
push dd_4;
ret;
}
}
/*-----------------------------------------------*/
errno_t fixA_hook(CK2Version version) {
std::string desc = "fixA";
switch (version) {
case v2_8_X:
// cmp cl,20h
byte_pattern::temp_instance().find_pattern("80 F9 20 0F 44 C6 89 45");
if (byte_pattern::temp_instance().has_size(1, desc)) {
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(), dd_1_v28);
// cmovnz eax,[ebp+var_10]
dd_5 = byte_pattern::temp_instance().get_first().address(14);
// mov [ebp+var_10],eax
dd_4 = byte_pattern::temp_instance().get_first().address(0x12);
}
else return CK2ERROR1;
return NOERROR;
case v3_0_X:
// cmp cl,20h
byte_pattern::temp_instance().find_pattern("80 F9 20 0F 44 C6 89 45");
if (byte_pattern::temp_instance().has_size(1, desc)) {
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(), dd_1_v30);
// cmovnz eax,[ebp+var_10]
dd_5 = byte_pattern::temp_instance().get_first().address(14);
// mov [ebp+var_10],eax
dd_4 = byte_pattern::temp_instance().get_first().address(0x12);
}
else return CK2ERROR1;
return NOERROR;
}
return CK2ERROR1;
}
/*-----------------------------------------------*/
uintptr_t k_2;
__declspec(naked) void k_1()
{
__asm {
cmp byte ptr[eax + esi], ESCAPE_SEQ_1;
jz k_10;
cmp byte ptr[eax + esi], ESCAPE_SEQ_2;
jz k_11;
cmp byte ptr[eax + esi], ESCAPE_SEQ_3;
jz k_12;
cmp byte ptr[eax + esi], ESCAPE_SEQ_4;
jz k_13;
mov al, [eax + esi];
movzx eax, al;
jmp k_6;
k_10:
movzx eax, word ptr[eax + esi + 1];
jmp k_1x;
k_11:
movzx eax, word ptr[eax + esi + 1];
sub eax, SHIFT_2;
jmp k_1x;
k_12:
movzx eax, word ptr[eax + esi + 1];
add eax, SHIFT_3;
jmp k_1x;
k_13:
movzx eax, word ptr[eax + esi + 1];
add eax, SHIFT_4;
k_1x:
add esi, 2;
movzx eax, ax;
cmp eax, NO_FONT;
ja k_6;
mov eax, NOT_DEF;
k_6:
mov ecx, [ebp - 0x20];
cmp ax, 0x20;
jz k_2_2;
cmp ax, 0x100;
ja k_2_2;
cmp word ptr[ebp - 0x8C + 2], 0x100;
jb k_2_5;
k_2_6:
mov word ptr[ebp - 0x8C + 2], 9;
jmp k_2_3;
k_2_5:
cmp word ptr[ebp - 0x8C + 2], 9;
jz k_2_6;
k_2_2:
mov word ptr[ebp - 0x8C + 2], ax;
k_2_3:
push k_2;
ret;
}
}
uintptr_t w_2;
__declspec(naked) void w_1()
{
__asm {
cmp word ptr[ebp - 0x8C + 2], 0x100;
jb w_3;
sub esi, 2;
w_3:
mov eax, [ebp + 0x18];//arg_10
add eax, [ebp - 0x24];
push w_2;
ret;
}
}
uintptr_t loc_194690F;
/*-----------------------------------------------*/
errno_t fix0_hook(CK2Version version) {
std::string desc = "fix0";
switch (version) {
case v2_8_X:
case v3_0_X:
//スタック修正 OK
// sub esp,7Ch
byte_pattern::temp_instance().find_pattern("83 EC 7C 53 8B 5D 0C 56 57 8B F1");
if (byte_pattern::temp_instance().has_size(1, desc)) {
injector::WriteMemory<uint8_t>(byte_pattern::temp_instance().get_first().address(2), 0x7E, true);
}
else return CK2ERROR1;
// mov al,[eax+esi] OK
byte_pattern::temp_instance().find_pattern("8A 04 30 8B 4D");
if (byte_pattern::temp_instance().has_size(1, desc)) {
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(), k_1);
// mov ecx, [ecx+eax*4+OFFSET]
k_2 = byte_pattern::temp_instance().get_first().address(9);
}
else return CK2ERROR1;
// mov eax,[ebp+arg_10] OK
byte_pattern::temp_instance().find_pattern("8B 45 18 03 45 DC 89 55");
if (byte_pattern::temp_instance().has_size(1, desc)) {
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(), w_1);
// mov [ebp+var_14],edx
w_2 = byte_pattern::temp_instance().get_first().address(6);
}
else return CK2ERROR1;
// 結合するブロックの飛び先 OK
// cmp eax,[ebp+arc_C]
byte_pattern::temp_instance().find_pattern("3B 45 14 0F 8F ? 01 00 00 C7");
if (byte_pattern::temp_instance().has_size(1, desc)) {
loc_194690F = byte_pattern::temp_instance().get_first().address();
}
else return CK2ERROR1;
return NOERROR;
}
return CK2ERROR1;
}
/*-----------------------------------------------*/
uintptr_t ee_2_v28;
uintptr_t ee_3_v28;
__declspec(naked) void ee_1_1_v28()
{
__asm {
cmp word ptr[ebp - 0x8C + 2], 9;
jz ee_2_jmp;
cmp word ptr[ebp - 0x8C + 2], 0x100;
ja ee_2_jmp;
cmp ebx, [ebp - 0x18];
jg ee_3_jmp;
jmp ee_2_jmp;
ee_2_jmp:
push ee_2_v28;
ret;
ee_3_jmp:
push ee_3_v28;
ret;
}
}
// ブロックの表示がv28と逆になっているので注意
uintptr_t ee_2_v30;
uintptr_t ee_3_v30;
__declspec(naked) void ee_1_1_v30()
{
__asm {
cmp word ptr[ebp - 0x8C + 2], 9;
jz ee_3_jmp;
cmp word ptr[ebp - 0x8C + 2], 0x100;
ja ee_3_jmp;
mov ecx, dword ptr [ebp - 0x1C];
cmp dword ptr [ebp - 0x18], ecx;
jle ee_3_jmp;
cmp eax, dword ptr [ebp + 0x14]; // arg_C
jle ee_2_jmp;
cmp dword ptr [ebp + 0x24], 0; // arg_1C
jnz ee_3_jmp;
ee_2_jmp: // 左
push ee_2_v30;
ret;
ee_3_jmp: // 右
push ee_3_v30;
ret;
}
}
/*-----------------------------------------------*/
errno_t fix1_hook(CK2Version version) {
std::string desc = "fix1";
switch (version) {
case v2_8_X:
// cmp ebx,[ebp+var_18]
byte_pattern::temp_instance().find_pattern("3B 5D E8 0F 8F");
if (byte_pattern::temp_instance().has_size(1, desc)) {
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(), ee_1_1_v28);
// 左側ブロックの開始位置
// push esi
ee_2_v28 = byte_pattern::temp_instance().get_first().address(9);
}
else return CK2ERROR1;
//右側のブロックの開始位置
// push ebx
byte_pattern::temp_instance().find_pattern("53 FF 75 E8 8D 45 90 C7");
if (byte_pattern::temp_instance().has_size(1, desc)) {
ee_3_v28 = byte_pattern::temp_instance().get_first().address();
}
else return CK2ERROR1;
return NOERROR;
case v3_0_X:
// cmp ebx,[ebp+var_18]
byte_pattern::temp_instance().find_pattern("8B 4D E4 39 4D E8 0F 8E A4 00 00 00");
if (byte_pattern::temp_instance().has_size(1, desc)) {
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(), ee_1_1_v30);
}
else return CK2ERROR1;
//左側のブロックの開始位置
// push offset asc_XXXXXX
byte_pattern::temp_instance().find_pattern("68 ? ? ? ? 8D 4D C0 E8 EE 23 07 00");
if (byte_pattern::temp_instance().has_size(1, desc)) {
ee_2_v30 = byte_pattern::temp_instance().get_first().address();
}
else return CK2ERROR1;
//右側のブロックの開始位置
// push offset asc_XXXXXX
byte_pattern::temp_instance().find_pattern("68 ? ? ? ? 8D 4D C0 E8 59 23 07 00");
if (byte_pattern::temp_instance().has_size(1, desc)) {
ee_3_v30 = byte_pattern::temp_instance().get_first().address();
}
else return CK2ERROR1;
return NOERROR;
}
return CK2ERROR1;
}
/*-----------------------------------------------*/
uintptr_t x_2_v28;
__declspec(naked) void x_1_v28()
{
__asm {
cmp word ptr[ebp - 0x8C + 2], 0x100;
jb x_4;
mov ecx, [eax + 0x10];
sub ecx, 1;
mov[eax + 0x10], ecx;
x_4:
lea ecx, [ebp - 0x70];
call func1_v28;
push x_2_v28;
ret;
}
}
uintptr_t x_2_v30;
__declspec(naked) void x_1_v30()
{
__asm {
cmp word ptr[ebp - 0x8C + 2], 0x100;
jb x_4;
mov ecx, [eax + 0x10];
sub ecx, 1;
mov[eax + 0x10], ecx;
x_4:
lea ecx, [ebp - 0x88];
call func1_v30;
push x_2_v30;
ret;
}
}
/*-----------------------------------------------*/
errno_t fix2_hook(CK2Version version) {
std::string desc = "fix2";
switch (version) {
case v2_8_X:
// mov ebx,[ebp+arg_4]
byte_pattern::temp_instance().find_pattern("8B 5D 0C 8B CB 6A FF 6A 00 50 C6 45 FC 02 E8");
if (byte_pattern::temp_instance().has_size(1, desc)) {
// lea ecx,[ebp+var_70]
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(0x13), x_1_v28);
// lea ecx,[ebp+var_88]
x_2_v28 = byte_pattern::temp_instance().get_first().address(0x1B);
}
else return CK2ERROR1;
return NOERROR;
case v3_0_X:
// lea ecx,[ebp+var_70]
byte_pattern::temp_instance().find_pattern("8D 8D 78 FF FF FF E8 92 62"); // このパターン検出は微妙 call sub_XXXを含んでいる
if (byte_pattern::temp_instance().has_size(1, desc)) {
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(), x_1_v30);
x_2_v30 = byte_pattern::temp_instance().get_first().address(0xB);
}
else return CK2ERROR1;
return NOERROR;
}
return CK2ERROR1;
}
/*-----------------------------------------------*/
__declspec(naked) void x_5_v28()
{
__asm {
cmp word ptr[ebp - 0x8C + 2], 0x100;
jb x_6;
sub esi, 1;
x_6:
mov[ebp - 0x14], 0;
push loc_194690F;
ret;
}
}
__declspec(naked) void x_5_v30()
{
__asm {
cmp word ptr[ebp - 0x8C + 2], 0x100;
jb x_6;
sub esi, 1;
x_6:
mov[ebp - 0x10], 0;
push loc_194690F;
ret;
}
}
/*-----------------------------------------------*/
errno_t fix3_hook(CK2Version version) {
std::string desc = "fix3";
switch (version) {
case v2_8_X:
// mov dl,[ebp+arg_18]
byte_pattern::temp_instance().find_pattern("8A 55 20 89 4D E4 89 75 E8");
if (byte_pattern::temp_instance().has_size(1, desc)) {
// mov [ebp+var_14],0
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(0x9), x_5_v28);
}
else return CK2ERROR1;
return NOERROR;
case v3_0_X:
// ブロックの終端先を変更する
// mov eax,[ebp+arg_14],0
byte_pattern::temp_instance().find_pattern("C7 45 EC 00 00 00 00 EB 03");
if (byte_pattern::temp_instance().has_size(1, desc)) {
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(), x_5_v30);
}
else return CK2ERROR1;
return NOERROR;
}
return CK2ERROR1;
}
/*-----------------------------------------------*/
errno_t init(CK2Version version) {
errno_t result = NOERROR;
byte_pattern::debug_output2("main text line break routine");
result |= func_hook(version); // OK
result |= fix0_hook(version); // OK
result |= fixA_hook(version); // OK
// ブロックの分岐判定処理
result |= fix1_hook(version); // NG
// 左側の分岐ブロックの処理の途中1
result |= fix2_hook(version); // OK
// 左側の分岐ブロックの処理の途中2
result |= fix3_hook(version); // OK
return result;
}
} | [
"matanki.saito@gmail.com"
] | matanki.saito@gmail.com |
a60d82bc99638794839bcbacfda6ca7b9d8d1c50 | a2111a80faf35749d74a533e123d9da9da108214 | /raw/workshop11/workshop2011-data-20110925/sources/fec6t5zk4j2ik4e7/11/sandbox/my_sandbox/apps/my_app/my_app.cpp | d39da403d62389ff0317bf8bf279128df77b08eb | [
"MIT"
] | permissive | bkahlert/seqan-research | f2c550d539f511825842a60f6b994c1f0a3934c2 | 21945be863855077eec7cbdb51c3450afcf560a3 | refs/heads/master | 2022-12-24T13:05:48.828734 | 2015-07-01T01:56:22 | 2015-07-01T01:56:22 | 21,610,669 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,510 | cpp | // ==========================================================================
// my_app
// ==========================================================================
// Copyright (c) 2006-2011, Knut Reinert, FU Berlin
// 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 Knut Reinert or the FU Berlin 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 KNUT REINERT OR THE FU BERLIN 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: Your Name <your.email@example.net>
// ==========================================================================
#include <seqan/basic.h>
#include <seqan/sequence.h>
#include <seqan/misc/misc_cmdparser.h>
#include "my_app.h"
using namespace seqan;
// Program entry point
int main(int argc, char const ** argv) {
String<AminoAcid> aaString = "MQDRVKRPMNAFIVWSRDQRRKMALEN";
Iterator<String<AminoAcid> >::Type it = begin(aaString);
Iterator<String<AminoAcid> >::Type last = end(aaString);
while (it != last) {
if (it == 'A') {
it = 'R';
}
it++;
}
std::cout << aaString << std::endl;
} | [
"mail@bkahlert.com"
] | mail@bkahlert.com |
e9f55ff1b60023c2ad61d1da0787b078db7ee079 | 2eb514283781c43d3741d7ce8805741e0d909ee0 | /3_3.cpp | 1b5efb46e4b5f46a20b0c5aa0259a5bec5508b68 | [] | no_license | beddingearly/DataStr | 93b595df4f8f6f7aa686e82b5a0ea498f11dc7fa | 7db5da1a2fc502217b3bb295f2214bf608d9e5a5 | refs/heads/master | 2021-06-16T21:48:48.223306 | 2016-10-10T15:44:30 | 2016-10-10T15:44:30 | 56,070,944 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 645 | cpp |
/*
线性表的操作:
初始化(建立空表)InitList(*L)
判断是否为空 ListEmpty(L)
插入 ListInsert(*L, i, e)
删除 ListDelete(*L, i, *e)
清空 ClearList(*L)
查找特定元素,返回位置 LocateElem(L,e)
得到特定数值 GetElem(L, i, *e)
得到元素个数 ListLength(L)
*/
//A = AUB,
void union(List *La, List Lb){
int La_len, Lb_len, i;
ElemType e;
La_len = ListLength(La);
Lb_len = Listlength(Lb);
for(i = 1; i <= Lb_len; i++){
GetElem(Lb, i, e);
if(!LocateElem(La, e, equal))
ListInsert(La, ++La_len, e);
}
}
| [
"wangzitonggg@163.com"
] | wangzitonggg@163.com |
f3a80dea27f07e20678b213803447a005a206a20 | 00db27c07ad2e08aeb0b01285488d46fd3cb8b61 | /Clases/2013-04-26/Summits/summits.cpp | ce5a418ad2f527650fd6347e1c00949a16eac5a6 | [] | no_license | RGAM496/ProgrammingLab | ceee5fe6e8805312bfff35ffdde87beb5283bc20 | 0ca4a6e0d80fcb25330f66c9e9aa04e2ae53d261 | refs/heads/master | 2021-01-16T18:42:24.965507 | 2013-10-11T21:44:39 | 2013-10-11T21:44:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,811 | cpp | #include <cstdio>
#include <algorithm>
using std::sort;
#define MIN_X 1
#define MAX_X 500
#define MIN_Y 1
#define MAX_Y 500
#define MIN_D 1
#define MAX_D 1000000000
#define MIN_H 0
#define MAX_H 1000000000
#define MAX_XY (MAX_X * MAX_Y)
#define NOT_EVALUATED -1
#define for_int(i,n) for (int i = 0; i < n; ++i)
/**********************************************************/
struct Point
{
int h, flood_zone;
inline void set (int h, int flood_zone) {
this->h = h;
this->flood_zone = flood_zone;
}
};
struct Coord
{
int x, y;
inline void set (int x, int y) {
this->x = x;
this->y = y;
}
inline Coord & operator += (const Coord &c) {
this->x += c.x;
this->y += c.y;
return *this;
}
};
bool operator < (const Coord &c1, const Coord &c2);
/**********************************************************/
template <class v_type, size_t SIZE>
struct Queue
{
v_type buffer[SIZE];
size_t first, last;
enum Operation {POP, PUSH} last_operation;
inline void next (size_t &index) {index = (index + 1) % SIZE;}
inline void previous (size_t &index) {index = (SIZE - 1 + index) % SIZE;}
inline void clear () {last = first = 0; last_operation = POP;}
inline bool empty () {return first == last && last_operation == POP;}
inline size_t size () {return first < last ? last - first : SIZE + last - first;}
inline v_type & front () {return buffer[first];}
inline v_type & back () {return buffer[last-1];}
inline void push (const v_type &v) {buffer[last] = v; next(last); last_operation = PUSH;}
inline void pop () {next(first); last_operation = POP;}
};
/**********************************************************/
struct Map
{
Point point[MAX_X][MAX_Y];
Coord coord[MAX_X*MAX_Y];
Queue <Coord, MAX_XY> not_evaluated;
int X, Y, D;
inline void read ();
inline Point & get_point (const Coord &c) {return point[c.x][c.y];}
inline Point & operator [] (const Coord &c) {return get_point (c);}
inline bool is_invalid (const Coord &c) {
return c.x < 0 || c.y < 0 || c.x >= X || c.y >= Y;
}
int summits ();
};
/**********************************************************/
void Map::read ()
{
int h, i;
scanf ("%d %d %d", &X, &Y, &D);
i = 0;
for_int (x, X)
{
for_int (y, Y)
{
scanf ("%d", &h);
point[x][y].set (h, NOT_EVALUATED);
coord[i].set (x, y);
++i;
}
}
}
int Map::summits ()
{
static Coord neighbor[4] = {{-1,0}, {0,-1}, {0,1}, {1,0}};
const int AREA = X * Y;
int result, candidates, pd;
bool found_summits;
sort (coord, coord + AREA);
not_evaluated.clear();
result = 0;
for_int (i, AREA)
{
Coord &c = coord[i];
Point &p = get_point (c);
if (p.flood_zone == NOT_EVALUATED)
{
pd = p.h - D;
candidates = 0;
found_summits = true;
p.flood_zone = p.h;
not_evaluated.push (c);
while (not_evaluated.empty() == false)
{
Coord ec = not_evaluated.front(); not_evaluated.pop();
Point &ep = get_point (ec);
candidates += ep.h == p.h;
for_int (n, 4)
{
Coord nc = ec;
nc += neighbor[n];
if (is_invalid (nc))
continue;
Point &np = get_point (nc);
if (np.flood_zone == NOT_EVALUATED)
{
np.flood_zone = p.h;
if (np.h > pd)
not_evaluated.push (nc);
}
else if (np.flood_zone > ep.h)
{
if (np.h > pd && np.flood_zone > p.h)
found_summits = false;
}
}
}
if (found_summits)
result += candidates;
}
}
return result;
}
/**********************************************************/
Map map;
bool operator < (const Coord &c1, const Coord &c2)
{
return map[c1].h > map[c2].h;
}
/**********************************************************/
int main ()
{
int T;
scanf ("%d", &T);
for_int (test_case, T)
{
map.read();
printf ("%d\n", map.summits());
}
return 0;
} | [
"rgam1989@gmail.com"
] | rgam1989@gmail.com |
f36b3c9e6bc4a9b8d2266ede9ff2f4cbd44b4630 | b055706d1aabeb7ff4fa5a490c221e37cd26b3ca | /my_set.h | a1306fe16bb4c87e77114562ccf2b77904605f80 | [] | no_license | demon1999/my_set | 3a13a2030e21dd83a290ff899453e6b58e107ff1 | d261a5eec6031bf9283bac4bbe951f316a073588 | refs/heads/master | 2020-03-20T19:37:33.966010 | 2018-06-20T17:44:40 | 2018-06-20T17:44:40 | 137,645,777 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,740 | h | //
// Created by demon1999 on 17.06.18.
//
#ifndef MY_SET_MY_SET_H
#define MY_SET_MY_SET_H
#include <cstdio>
#include <stdexcept>
#include <queue>
template <typename T>
struct my_set {
private:
struct node {
node* l;
node* r;
node* par;
const T* data;
bool is_end, is_beg;
node() {
is_beg = is_end = false;
data = NULL;
l = r = par = NULL;
}
node(const T& a) {
data = new T(a);
l = r = par = NULL;
is_beg = is_end = false;
}
~node() {
if (data != NULL)
delete data;
}
const node* prev_node() const {
const node* we = this;
if (we->l != NULL) {
we = we->l;
while (we->r != NULL)
we = we->r;
} else {
const node* prev = we;
we = we->par;
while (we != NULL && (we->l) == prev) {
prev = we;
if ((we->par) == NULL) return we;
we = we->par;
}
}
return we;
};
node* prev_node() {
return const_cast<node*>((const_cast<const node*>(this))->prev_node());
};
const node* next_node() const {
const node* we = this;
if (we->r != NULL) {
we = we->r;
while (we->l != NULL)
we = we->l;
} else {
const node* prev = we;
we = we->par;
while (we != NULL && (we->r) == prev) {
prev = we;
if ((we->par) == NULL) return we;
we = we->par;
}
}
return we;
}
node* next_node() {
return const_cast<node*>((const_cast<const node*>(this))->next_node());
};
};
public:
struct my_const_iterator;
typedef my_const_iterator const_iterator;
struct iterator : public std::iterator<
std::bidirectional_iterator_tag, // iterator_category
T, // value_type
long, // difference_type
T*, // pointer
T& // reference
> {
private:
node* we;
iterator(node *a) {
we = a;
}
public:
iterator() = default;
bool operator==(const iterator & other) const {
return we == other.we;
}
bool operator==(const const_iterator & other) const {
return const_iterator(we) == other.we;
}
bool operator!=(const const_iterator & other) const {
return const_iterator(we) != other.we;
}
bool operator!=(const iterator & other) const {
return we != other.we;
}
const T& operator*() const {
return *(we->data);
}
const T* operator->() const {
return we->data;
}
iterator &operator++() {
we = we->next_node();
return *this;
}
iterator operator++(int) {
iterator a = we;
++(*this);
return a;
}
iterator &operator--() {
we = we->prev_node();
return *this;
}
iterator operator--(int) {
iterator a = we;
--(*this);
return a;
}
friend struct my_set<T>;
friend struct my_const_iterator;
};
struct my_const_iterator : public std::iterator<
std::bidirectional_iterator_tag, // iterator_category
T, // value_type
long, // difference_type
const T*, // pointer
const T& // reference
>{
private:
const node* we;
my_const_iterator(const node *a) {
we = a;
}
public:
my_const_iterator() = default;
my_const_iterator(const iterator & other) {
we = other.we;
}
bool operator==(const my_const_iterator & other) const {
return we == other.we;
}
bool operator!=(const my_const_iterator & other) const{
return we != other.we;
}
const T& operator*() const {
return *(we->data);
}
const T* operator->() const {
return we->data;
}
my_const_iterator &operator--() {
we = we->prev_node();
return *this;
}
my_const_iterator operator--(int) {
my_const_iterator a = we;
--(*this);
return a;
}
my_const_iterator &operator++() {
we = we->next_node();
return *this;
}
my_const_iterator operator++(int) {
my_const_iterator a = we;
++(*this);
return a;
}
friend struct my_set<T>;
};
iterator begin() {
return ++iterator(&start);
}
iterator end() {
return &finish;
}
const_iterator begin() const {
return ++const_iterator(&start);
}
const_iterator end() const {
return &finish;
}
const_iterator cbegin() const {
return ++const_iterator(&start);
}
const_iterator cend() const {
return &finish;
}
struct const_reverse_iterator;
struct reverse_iterator : public std::iterator<
std::bidirectional_iterator_tag, // iterator_category
T, // value_type
long, // difference_type
T*, // pointer
T& // reference
> {
private:
node* we;
reverse_iterator(node *a) {
we = a;
}
public:
bool operator==(const reverse_iterator & other) const {
return we == other.we;
}
bool operator==(const const_reverse_iterator & other) const {
return const_reverse_iterator(we) == other.we;
}
bool operator!=(const const_reverse_iterator & other) const {
return const_reverse_iterator(we) != other.we;
}
bool operator!=(const reverse_iterator & other) const {
return we != other.we;
}
const T& operator*() const {
return *(we->data);
}
const T* operator->() const {
return we->data;
}
reverse_iterator &operator++() {
we = we->prev_node();
return *this;
}
reverse_iterator operator++(int) {
reverse_iterator a = we;
++(*this);
return a;
}
reverse_iterator &operator--() {
we = we->next_node();
return *this;
}
reverse_iterator operator--(int) {
reverse_iterator a = we;
--(*this);
return a;
}
friend struct my_set<T>;
friend struct const_reverse_iterator;
};
struct const_reverse_iterator : public std::iterator<
std::bidirectional_iterator_tag, // iterator_category
T, // value_type
long, // difference_type
const T*, // pointer
const T& // reference
>{
private:
const node* we;
const_reverse_iterator(const node *a) {
we = a;
}
public:
const_reverse_iterator(const reverse_iterator & other) {
we = other.we;
}
bool operator==(const const_reverse_iterator & other) const {
return we == other.we;
}
bool operator!=(const const_reverse_iterator & other) const{
return we != other.we;
}
const T& operator*() const {
return *(we->data);
}
const T* operator->() const {
return we->data;
}
const_reverse_iterator &operator--() {
we = we->next_node();
return *this;
}
const_reverse_iterator operator--(int) {
const_reverse_iterator a = we;
--(*this);
return a;
}
const_reverse_iterator &operator++() {
we = we->prev_node();
return *this;
}
const_reverse_iterator operator++(int) {
const_reverse_iterator a = we;
++(*this);
return a;
}
friend struct my_set<T>;
};
reverse_iterator rbegin() {
return ++reverse_iterator(&finish);
}
reverse_iterator rend() {
return &start;
}
const_reverse_iterator rbegin() const {
return ++const_reverse_iterator(&finish);
}
const_reverse_iterator rend() const {
return &start;
}
const_reverse_iterator crbegin() const {
return ++const_reverse_iterator(&finish);
}
const_reverse_iterator crend() const {
return const_reverse_iterator(&start);
}
const_iterator find(T const& a) const;
iterator find(T const& a);
const_iterator lower_bound(T const& a) const;
iterator lower_bound(T const& a);
const_iterator upper_bound(T const& a) const;
iterator upper_bound(T const& a);
void swap(my_set & a) {
if (this == &a) return;
node* rr = start.r;
start.r = a.start.r;
a.start.r = rr;
if (start.r != NULL)
start.r->par = (&start);
if (a.start.r != NULL)
a.start.r->par = (&a.start);
}
void clear();
void my_deleter(node *q);
iterator erase(const_iterator we);
private:
iterator extract(iterator we);
public:
std::pair<iterator, bool> insert(T const& a);
bool empty() const;
my_set();
my_set(my_set const &other);
~my_set();
my_set& operator=(my_set const &other);
private:
node start, finish;
};
template<typename T>
my_set<T>::my_set() {
finish.l = &start;
finish.is_end = true;
start.is_beg = true;
start.par = &finish;
}
template<typename T>
my_set<T>::my_set(my_set const &other) {
auto a = my_set<T>();
a.finish.l = &a.start;
a.finish.is_end = true;
a.start.is_beg = true;
a.start.par = &a.finish;
std::queue<std::pair<node*, const node*> > data;
data.push({a.rend().we, &other.start});
while (!data.empty()) {
auto v = data.front();
data.pop();
if (((v.second)->l) != NULL) {
node* lch = (v.second)->l;
node* nw = new node(*(lch->data));
v.first->l = nw;
nw->par = v.first;
data.push({nw, lch});
}
if (((v.second)->r) != NULL) {
node* rch = (v.second)->r;
node* nw = new node(*(rch->data));
v.first->r = nw;
nw->par = v.first;
data.push({nw, rch});
}
}
a.swap(*this);
start.par = &finish;
finish.l = &start;
}
template<typename T>
my_set<T>::~my_set() {
clear();
}
template<typename T>
my_set<T> &my_set<T>::operator=(my_set const &other) {
if (this != &other) {
my_set<T>(other).swap(*this);
start.par = &finish;
finish.l = &start;
}
return *this;
}
template<typename T>
void my_set<T>::clear() {
my_deleter(start.r);
start.r = NULL;
}
template<typename T>
bool my_set<T>::empty() const {
return start.r == NULL;
}
template<typename T>
typename my_set<T>::const_iterator my_set<T>::find(const T &a) const {
node* go = start.r;
while (go != NULL) {
if ((go->data) != NULL && (*(go->data)) == a) {
return const_iterator(go);
}
if ((go->data) != NULL && (*(go->data)) > a)
go = go->l;
else
go = go->r;
}
return const_iterator(&finish);
}
template<typename T>
typename my_set<T>::const_iterator my_set<T>::upper_bound(const T &a) const {
if (start.r == NULL)
return const_iterator(&finish);
node* go = start.r;
while (go != NULL) {
if ((go->data) != NULL && (*(go->data)) > a) {
if ((go->l) == NULL) {
break;
}
go = go->l;
}
else {
if ((go->r) == NULL) {
break;
}
go = go->r;
}
}
const_iterator we = go;
if ((go->data) != NULL && (*(go->data)) <= a)
we++;
return we;
}
template<typename T>
typename my_set<T>::const_iterator my_set<T>::lower_bound(const T &a) const {
if ((find(a)) != &finish) {
return find(a);
} else
return upper_bound(a);
}
template<typename T>
std::pair<typename my_set<T>::iterator, bool> my_set<T>::insert(const T &a) {
iterator we = lower_bound(a);
if (we != iterator(&finish)) {
if ((*we) == a) {
return {we, false};
} else {
auto nw = new node(a);
nw->par = (we.we);
nw->l = (we.we->l);
if ((nw->l) != NULL) {
(nw->l)->par = nw;
}
we.we->l = nw;
return {nw, true};
}
} else {
auto nw = new node(a);
we--;
we.we->r = nw;
nw->par = we.we;
return {nw, true};
}
}
template<typename T>
typename my_set<T>::iterator my_set<T>::erase(my_set::const_iterator we) {
if (we == end())
return const_cast<node*>(we.we);
auto ans = upper_bound((*(we.we->data)));
auto me = extract(const_cast<node*>(we.we));
delete me.we;
return const_cast<node*>(ans.we);
}
template<typename T>
typename my_set<T>::iterator my_set<T>::extract(my_set::iterator we) {
if (we == end()) {
return we;
}
auto ans = we;
ans++;
if (we.we->r == NULL) {
auto nw = we.we->par;
if ((nw->l) == we.we)
nw->l = we.we->l;
else
nw->r = we.we->l;
if (we.we->l != NULL) {
((we.we->l)->par) = nw;
}
} else if (we.we->l == NULL) {
auto nw = we.we->par;
if ((nw->l) == we.we)
nw->l = we.we->r;
else
nw->r = we.we->r;
((we.we->r)->par) = nw;
} else {
auto nk = extract(ans);
nk.we->par = we.we->par;
if (((we.we->par)->l) == we.we){
((we.we->par)->l) = nk.we;
} else
((we.we->par)->r) = nk.we;
nk.we->l = (we.we->l);
if ((we.we->l) != NULL) {
((we.we->l)->par) = nk.we;
}
nk.we->r = (we.we->r);
if ((we.we->r) != NULL) {
((we.we->r)->par) = nk.we;
}
}
return we;
}
template<typename T>
typename my_set<T>::iterator my_set<T>::lower_bound(const T &a) {
return const_cast<node*>(((const_cast<const my_set*>(this))->lower_bound(a)).we);
}
template<typename T>
typename my_set<T>::iterator my_set<T>::upper_bound(const T &a) {
return const_cast<node*>(((const_cast<const my_set*>(this))->upper_bound(a)).we);
}
template<typename T>
typename my_set<T>::iterator my_set<T>::find(const T &a) {
return const_cast<node*>(((const_cast<const my_set*>(this))->find(a)).we);
}
template<typename T>
void my_set<T>::my_deleter(my_set::node * q) {
if (q == NULL) return;
my_deleter(q->l);
my_deleter(q->r);
delete q;
}
template<typename T>
void swap(my_set<T>& a, my_set<T>& b) {
a.swap(b);
}
#endif //MY_SET_MY_SET_H
| [
"aleksandra.drozdova@codefights.com"
] | aleksandra.drozdova@codefights.com |
83e92707e553d7efe4a8f4bd8501d33ccab1db4c | 03312dcbed3099f58cf225abc861340985ff021e | /src/Texture.cpp | 593421cfe19f91e2fdc88c20f7be1e8781379c9a | [] | no_license | andrewrk/labyrinth | 1d49709a406d3424ac2b34855333e0a6606703a5 | 6b25b5e9ef68e46e974ff3e509bc56b6ebf69ecf | refs/heads/master | 2023-03-13T06:58:22.964746 | 2009-11-23T23:30:25 | 2009-11-23T23:30:25 | 2,722,794 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,692 | cpp | #include "Texture.h"
#include <cmath>
using namespace std;
#include "Bitmap.h"
#include "GL/freeglut.h"
Texture::Mode Texture::s_mode = ModeReplace;
Texture::Texture(Bitmap * bmp)
: m_bmp(bmp)
{
glGenTextures(1, &m_id);
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, m_id);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
setFilterMode(FilterModeSimple);
// create mipmaps
gluBuild2DMipmaps(
GL_TEXTURE_2D,
GL_RGBA,
bmp->width(),
bmp->height(),
GL_RGB,
GL_UNSIGNED_BYTE,
bmp->buffer()
);
}
Texture::~Texture() {
glDeleteTextures(1, &m_id);
}
void Texture::bind() {
if( s_mode != ModeOff ) {
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, m_id);
}
switch(s_mode){
case ModeReplace:
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
break;
case ModeBlend:
glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_BLEND);
break;
case ModeOff:
glDisable(GL_TEXTURE_2D);
break;
}
}
void Texture::setMode(Mode mode) {
s_mode = mode;
}
void Texture::setFilterMode(FilterMode mode){
switch(mode){
case FilterModeSimple:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
break;
case FilterModeSmooth:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,
GL_LINEAR_MIPMAP_LINEAR);
break;
}
}
| [
"superjoe30@gmail.com"
] | superjoe30@gmail.com |
f59aab77cedca580d2339fcde30b7e1c0844df1f | 5a3d20275a00e088441dae833f017f3b84cf399f | /servo_test/servo_test.ino | ef0c9e3b4a668aeda1890c30eaebbd8e55dec7a6 | [] | no_license | philbarbier/arduino-projects | b1575e4e1c7dead4d945c5140420021a025dabc4 | e8f7cdb8ce5647cbead82af9993b5af62f844a85 | refs/heads/master | 2020-04-10T22:48:42.472791 | 2016-09-25T08:33:02 | 2016-09-25T08:33:02 | 68,182,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 663 | ino | #include <Servo.h>
Servo switch1;
int controlPin = 2;
int servoPin = 27;
int b = 0;
int die = 0;
int switchMax = 25;
void setup() {
switch1.attach(servoPin);
Serial.begin(9600);
}
void loop() {
int switchState = digitalRead(controlPin);
Serial.println("state: ");
Serial.println(switchState);
if (switchState == 0) {
makeTurn();
} else {
makeStraight();
}
//exit(0);
if (die > 25) {
exit(0);
}
die++;
}
void makeTurn() {
for (b = 0; b <= switchMax; b+=1) {
switch1.write(b);
delay(15);
}
}
void makeStraight() {
for (b = switchMax; b >= 0; b-=1) {
switch1.write(b);
delay(15);
}
}
| [
"flimflam@gmail.com"
] | flimflam@gmail.com |
78b6c13317155dba0b18859a8a0797686bbe045d | cafe801758da2ab7df15f2b3b37d311bc6db02f7 | /apps/emuHAIPE/LList.cpp | ca5b99c5f7414a2ffb1c1b5a18fd9b29a56e6a56 | [] | no_license | raytheonbbn/IRON | a79da13afe8c2752407cdd82773ef3988c2959b1 | 7c4fcb15622d8029efc48e9323efbf385cbf2e63 | refs/heads/master | 2023-04-03T23:45:24.356042 | 2021-03-31T14:50:35 | 2021-03-31T14:50:35 | 275,175,579 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,576 | cpp | /* IRON: iron_headers */
/*
* Distribution A
*
* Approved for Public Release, Distribution Unlimited
*
* EdgeCT (IRON) Software Contract No.: HR0011-15-C-0097
* DCOMP (GNAT) Software Contract No.: HR0011-17-C-0050
* Copyright (c) 2015-20 Raytheon BBN Technologies Corp.
*
* This material is based upon work supported by the Defense Advanced
* Research Projects Agency under Contracts No. HR0011-15-C-0097 and
* HR0011-17-C-0050. Any opinions, findings and conclusions or
* recommendations expressed in this material are those of the author(s)
* and do not necessarily reflect the views of the Defense Advanced
* Research Project Agency.
*
* 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.
*/
/* IRON: end */
#include <stdio.h>
#include "LList.h"
#include "ZLog.h"
//
// Class name to use in logging output.
//
static const char cn[] = "LList";
//============================================================================
LList::LList()
{
//
// Initialize the mutex that will protect the linked list. The call never
// fails.
//
pthread_mutex_init((pthread_mutex_t*)&mutex, NULL);
//
// Initially, the head and tail of the linked list are NULL.
//
head = NULL;
tail = NULL;
}
//============================================================================
LList::~LList()
{
LListElem* delElem;
//
// We will unlink and delete all objects stored in the linked list. We will
// simply iteratively unlink and delete the head of the linked list until it
// is NULL. We must remember the head element because unlink will modify
// it.
//
delElem = head;
while (delElem != NULL)
{
//
// Unlink the element and destroy it. Then get the next element to unlink
// and delete. Note that this will lock the class mutex, but that should
// be OK.
//
unlink(delElem);
delete delElem;
delElem = head;
}
//
// Finally, we destroy the linked list mutex.
//
pthread_mutex_destroy((pthread_mutex_t*)&mutex);
}
//============================================================================
int LList::size() const
{
int e = 0;
const LListElem* elem = getHead();
while (elem != NULL)
{
e++;
elem = elem->getNext();
}
return e;
}
//============================================================================
void
LList::addToHead(LListElem* elem)
{
static const char mn[] = "addToHead";
if (elem == NULL)
{
return;
}
//
// Lock the mutex because we will be changing the state of the linked list.
//
pthread_mutex_lock((pthread_mutex_t*)&mutex);
if (elem->llist != NULL)
{
//
// Remove element from linked list that it is currently a part of because
// linked list does not allow LListElems to be in more than one linked
// list at a time. If desired, build a wrapper around object to be placed
// in multiple linked lists.
//
zlogW(cn, mn, ("Warning: Element part of different linked list. Element "
"is being removed from previous list.\n"));
if (elem->llist == this)
{
//
// We do this because we are unlinking from our linked list and we
// already have the mutex locked.
//
elem->llist->lockedUnlink(elem);
}
else
{
//
// To protect against a possible deadlock situation here, we unlock the
// mutex prior to unlinking the element from another linked list. We
// will lock it again following the unlink.
//
pthread_mutex_unlock((pthread_mutex_t*)&mutex);
elem->llist->unlink(elem);
pthread_mutex_lock((pthread_mutex_t*)&mutex);
}
}
if (head == NULL)
{
//
// This is the first element added to the linked list. We must adjust tail
// also.
//
head = elem;
tail = head;
}
else
{
//
// The linked list is not empty, so we simply add the element to the head
// of it.
//
elem->next = head;
head->prev = elem;
head = elem;
}
//
// Set the linked list that the element is a part of.
//
elem->llist = this;
//
// Finally, we unlock the mutex.
//
pthread_mutex_unlock((pthread_mutex_t*)&mutex);
}
//============================================================================
void
LList::addToTail(LListElem* elem)
{
static const char mn[] = "addToTail";
if (elem == NULL)
{
return;
}
//
// Lock the mutex because we will be changing the state of the linked list.
//
pthread_mutex_lock((pthread_mutex_t*)&mutex);
if (elem->llist != NULL)
{
//
// Remove element from linked list that it is currently a part of because
// linked list does not allow LListElems to be in more than one linked
// list at a time. If desired, build a wrapper around object to be placed
// in multiple linked lists.
//
zlogW(cn, mn, ("Warning: Element part of different linked list. Element "
"is being removed from previous list.\n"));
if (elem->llist == this)
{
//
// We do this because we are unlinking from our linked list and we
// already have the mutex locked.
//
elem->llist->lockedUnlink(elem);
}
else
{
//
// To protect against a possible deadlock situation here, we unlock the
// mutex prior to unlinking the element from another linked list. We
// will lock it again following the unlink.
pthread_mutex_unlock((pthread_mutex_t*)&mutex);
elem->llist->unlink(elem);
pthread_mutex_lock((pthread_mutex_t*)&mutex);
}
}
if (tail == NULL)
{
//
// This is the first element added to the linked list. We must adjust head
// also.
//
tail = elem;
head = tail;
}
else
{
//
// The linked list is not empty, so we simply add the element to the end
// of it.
//
tail->next = elem;
elem->prev = tail;
tail = elem;
}
//
// Set the linked list that the element is a part of.
//
elem->llist = this;
//
// Finally, we unlock the mutex.
//
pthread_mutex_unlock((pthread_mutex_t*)&mutex);
}
//============================================================================
LListElem*
LList::getHead()
{
LListElem* retElem;
//
// Lock the mutex in case the linked list is being modified.
//
pthread_mutex_lock((pthread_mutex_t*)&mutex);
retElem = head;
//
// We must unlock the mutex before return the head of the linked list.
//
pthread_mutex_unlock((pthread_mutex_t*)&mutex);
return retElem;
}
//============================================================================
const LListElem*
LList::getHead() const
{
const LListElem* retElem;
//
// Lock the mutex in case the linked list is being modified.
//
pthread_mutex_lock((pthread_mutex_t*)&mutex);
retElem = head;
//
// We must unlock the mutex before return the head of the linked list.
//
pthread_mutex_unlock((pthread_mutex_t*)&mutex);
return retElem;
}
//============================================================================
LListElem*
LList::getTail()
{
LListElem* retElem;
//
// Lock the mutex in case the linked list is being modified.
//
pthread_mutex_lock((pthread_mutex_t*)&mutex);
retElem = tail;
//
// We must unlock the mutex before return the head of the linked list.
//
pthread_mutex_unlock((pthread_mutex_t*)&mutex);
return retElem;
}
//============================================================================
const LListElem*
LList::getTail() const
{
const LListElem* retElem;
//
// Lock the mutex in case the linked list is being modified.
//
pthread_mutex_lock((pthread_mutex_t*)&mutex);
retElem = tail;
//
// We must unlock the mutex before return the head of the linked list.
//
pthread_mutex_unlock((pthread_mutex_t*)&mutex);
return retElem;
}
//============================================================================
void
LList::insertBefore(LListElem* beforeElem, LListElem* newElem)
{
static const char mn[] = "insertBefore";
if ((beforeElem == NULL) || (newElem == NULL))
{
return;
}
//
// Lock the mutex because we will be changing the state of the linked list.
//
pthread_mutex_lock((pthread_mutex_t*)&mutex);
if (newElem->llist != NULL)
{
//
// Remove the new element from linked list that it is currently a part of
// because linked list does not allow LListElems to be in more than one
// linked list at a time. If desired, build a wrapper around object to be
// placed in multiple linked lists.
//
zlogW(cn, mn, ("Warning: New element part of different linked "
"list. New element is being removed from previous "
"list.\n"));
if (newElem->llist == this)
{
//
// We do this because we are unlinking from our linked list and we
// already have the mutex locked.
//
newElem->llist->lockedUnlink(newElem);
}
else
{
//
// To protect against a possible deadlock situation here, we unlock the
// mutex prior to unlinking the element from another linked list. We
// will lock it again following the unlink.
//
pthread_mutex_unlock((pthread_mutex_t*)&mutex);
newElem->llist->unlink(newElem);
pthread_mutex_lock((pthread_mutex_t*)&mutex);
}
}
if (beforeElem == head)
{
//
// The element we are inserting before is the head element, so there will
// be a new head.
//
newElem->next = beforeElem;
beforeElem->prev = newElem;
head = newElem;
}
else
{
//
// The element we are inserting is somewhere between the head and tail of
// the linked list.
//
newElem->prev = beforeElem->prev;
newElem->next = beforeElem;
beforeElem->prev->next = newElem;
beforeElem->prev = newElem;
}
//
// Set the linked list that the element is a part of.
//
newElem->llist = this;
//
// Finally, we unlock the mutex.
//
pthread_mutex_unlock((pthread_mutex_t*)&mutex);
}
//============================================================================
void
LList::lockedUnlink(LListElem* elem)
{
static const char mn[] = "lockedUnlink";
//
// NOTE: This method will simply break the linkages of the element to be
// unlinked. Ownership of the memory is passed to the calling object, which
// MUST either delete the memory of pass ownership to another object to
// prevent a memory leak.
//
// We don't check the elem for NULL here because this method is called from
// another method in this class that has already checked its value.
//
if (elem->llist == NULL)
{
zlogW(cn, mn,
("Unlink called for element that is not part of linked list.\n"));
return;
}
if (elem->llist != this)
{
zlogE(cn, mn,
("Unlink called for element that is not part of this linked "
"list.\n"));
return;
}
//
// Unlink the element. It may be the only element in the linked list, the
// element at the head of the linked list, the element at the tail of the
// linked list, or an element somewhere between the head and tail of the
// linked list.
//
if (elem->prev == NULL)
{
if (elem->next == NULL)
{
//
// The element that is being unlinked from the linked list is the only
// element in the linked list. We must be sure to modify head and tail
// also.
head = NULL;
tail = NULL;
}
else
{
//
// The element is at the head of the linked list. We must be sure to
// modify the head also.
//
elem->next->prev = NULL;
head = elem->next;
elem->next = NULL;
}
}
else
{
if (elem->next == NULL)
{
//
// The element is at the tail of the linked list. We must be sure to
// modify the tail also.
//
elem->prev->next = NULL;
tail = elem->prev;
elem->prev = NULL;
}
else
{
//
// The element is somewhere in between the head and tail of the linked
// list. We will not modify head or tail.
//
elem->prev->next = elem->next;
elem->next->prev = elem->prev;
elem->next = NULL;
elem->prev = NULL;
}
}
//
// Now, we set the linked list that the element is part of to NULL as it is
// no longer a part of the linked list.
//
elem->llist = NULL;
}
//============================================================================
LListElem*
LList::removeFromHead()
{
LListElem* rv;
//
// We are going to be modifying the internal state of the linked list so we
// must lock the mutex.
//
pthread_mutex_lock((pthread_mutex_t*)&mutex);
rv = head;
if (rv != NULL)
{
//
// We must unlink the element from the linked list.
//
lockedUnlink(rv);
}
//
// Don't forget to unlock the mutex to prevent a deadlock situation.
//
pthread_mutex_unlock((pthread_mutex_t*)&mutex);
return rv;
}
//============================================================================
LListElem*
LList::removeFromTail()
{
LListElem* rv;
//
// We are going to be modifying the internal state of the linked list so we
// must lock the mutex.
//
pthread_mutex_lock((pthread_mutex_t*)&mutex);
rv = tail;
if (rv != NULL)
{
//
// We must unlink the element from the linked list.
//
lockedUnlink(rv);
}
//
// Don't forget to unlock the mutex to prevent a deadlock situation.
//
pthread_mutex_unlock((pthread_mutex_t*)&mutex);
return rv;
}
//============================================================================
void
LList::unlink(LListElem* elem)
{
if (elem == NULL)
{
return;
}
//
// NOTE: This method will simply break the linkages of the element to be
// unlinked. Ownership of the memory is passed to the calling object, which
// MUST either delete the memory of pass ownership to another object to
// prevent a memory leak.
//
//
// Lock the mutex because we will be changing the state of the linked list.
//
pthread_mutex_lock((pthread_mutex_t*)&mutex);
lockedUnlink(elem);
//
// We are finished modifying the linked list, so we must unlock the mutex.
//
pthread_mutex_unlock((pthread_mutex_t*)&mutex);
}
| [
"greg.lauer@raytheon.com"
] | greg.lauer@raytheon.com |
bd1465d3f17915a9eb62a24301710c25ec7bc63e | 4218cc8ea49bd0244c78db7282b792d54488d0f2 | /Pelatda/simple_hashing.cpp | 80439114e9d29ff360f91cb158f836fca9c9e3b1 | [] | no_license | irff/cp-codes | 436678ce0d1939e6103c983eb1907078df391808 | 5c0c3a7710fff48751b4307f3ad0f135d25ea180 | refs/heads/master | 2020-03-29T14:36:34.904213 | 2014-10-19T18:27:02 | 2014-10-19T18:27:02 | 25,435,733 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 332 | cpp | #include <cstdio>
#include <algorithm>
using namespace std;
#define R(i,_a,_b) for(int i=int(_a);i<int(_b);i++)
int k, n;
int rek(int ke, int n) {
return 0;
}
int main() {
scanf("%d%d", &k, &n);
while(k!=0 and n!=0) {
rek(0, n);
scanf("%d%d", &k, &n);
}
return 0;
}
| [
"triahmad1996@gmail.com"
] | triahmad1996@gmail.com |
5c4054d22b18e0193e1d9de4bb08b5782dcfbecf | befaf0dfc5880d18f42e1fa7e39e27f8d2f8dde9 | /SDK/SCUM_Zombie_MilitaryPants_04_functions.cpp | 5a00e14ca16934027f8866905f90098f28abc1b7 | [] | no_license | cpkt9762/SCUM-SDK | 0b59c99748a9e131eb37e5e3d3b95ebc893d7024 | c0dbd67e10a288086120cde4f44d60eb12e12273 | refs/heads/master | 2020-03-28T00:04:48.016948 | 2018-09-04T13:32:38 | 2018-09-04T13:32:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 359 | cpp | // SCUM (0.1.17.8320) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SCUM_Zombie_MilitaryPants_04_classes.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"igromanru@yahoo.de"
] | igromanru@yahoo.de |
1ca48ec8a13c2dbad06e52d4372057f2768b2c7c | 8dca25d64e554e6eb0050d8b87de313d37ba0ab9 | /1000/118A - String Task.cpp | 4c83c669f4ec4989f2aa0c3032eb72ff9739f6cc | [] | no_license | Ii-xD-iI/CodeForces | d57e26a8ffa846bce2f853149ebd5dc745562b17 | 4226aed69f849bba6c49059b328c164ed955befb | refs/heads/master | 2023-03-16T06:59:31.679988 | 2021-02-28T18:35:22 | 2021-02-28T18:35:22 | 290,790,921 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 848 | cpp | #include "bits/stdc++.h"
//PRAY :DOLPHINGARLIC: orz orz orz orz orz
//PRAY :DORI: orz orz orz orz orz orz orz
//PRAY :SAHIL KUCHLOUS: orz orz orz orz orz
//pray :stefan: orz orz orz orz orz orz orz
//pray :foshy: orz orz orz orz orz orz orz
#define GS ios_base::sync_with_stdio(false);cin.tie(nullptr);cout.tie(0)
#define all(x) x.begin(), x.end()
#define el '\n'
#define Int long long
#define elif else if
#define test Int t; cin>>t; while(t--)
// #define
using namespace std;
int main(){
GS;
string s;cin>>s;
vector<char> v;
for(int i {};i<(int)s.size();i++){
s[i] = tolower(s[i]);
if(s[i]!='a'&&s[i]!='o'&&s[i]!='y'&&s[i]!='e'&&s[i]!='u'&&s[i]!='i'){
v.push_back('.');
v.push_back(s[i]);
}
}
for(auto i:v){
cout << i;
}
cout << endl;
return 0;
}
/*
12:43 AM
9/18/2020
*/
| [
"noreply@github.com"
] | Ii-xD-iI.noreply@github.com |
5309d8c501c6489c3172b0bf48215e76f2f3d0c8 | 00dbe4fd5f00fab51f959fdf32ddb185daa8de30 | /P10901.cpp | 0f71cc4a6bda19fb7e831b4b8800cb95169d04c6 | [] | no_license | LasseD/uva | c02b21c37700bd6f43ec91e788b2787152bfb09b | 14b62742d3dfd8fb55948b2682458aae676e7c14 | refs/heads/master | 2023-01-29T14:51:42.426459 | 2023-01-15T09:29:47 | 2023-01-15T09:29:47 | 17,707,082 | 3 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,029 | cpp | #include <iostream>
#include <vector>
#include <queue>
using namespace std;
#define MAX 10000
typedef pair<int,int> PP;
int main() {
int cases, n, t, m, tmp;
string s;
std::cin >> cases;
for(int cas = 0; cas < cases; ++cas) {
if(cas != 0)
cout << endl;
cin >> n >> t >> m; // capacity n, travel time t, m cars to arrive.
int *departures = new int[m];
// Read arrivals:
int time = 99999999;
vector<PP> arrivalsLeft, arrivalsRight;
for(int i = 0; i < m; ++i) {
cin >> tmp >> s;
if(tmp < time)
time = tmp;
if(s[0] == 'l')
arrivalsLeft.push_back(PP(tmp, i));
else
arrivalsRight.push_back(PP(tmp, i));
}
vector<PP>::const_iterator itLeft = arrivalsLeft.begin();
vector<PP>::const_iterator itRight = arrivalsRight.begin();
// perform simulation:
bool left = true; // side of ferry.
while(itLeft != arrivalsLeft.end() || itRight != arrivalsRight.end()) {
int onFerry = 0;
bool anyWaitingOnOtherSide;
if(left) {
while(onFerry < n && itLeft != arrivalsLeft.end() && itLeft->first <= time) {
departures[itLeft->second] = time + t;
++onFerry;
++itLeft;
}
anyWaitingOnOtherSide = itRight != arrivalsRight.end() && itRight->first <=time;
}
else {
while(onFerry < n && itRight != arrivalsRight.end() && itRight->first <= time) {
departures[itRight->second] = time + t;
++onFerry;
++itRight;
}
anyWaitingOnOtherSide = itLeft != arrivalsLeft.end() && itLeft->first <=time;
}
if(onFerry == 0 && !anyWaitingOnOtherSide) { // Wait until there are cars:
int nextArrival = 9999999;
if(itLeft != arrivalsLeft.end())
nextArrival = itLeft->first;
if(itRight != arrivalsRight.end() && itRight->first < nextArrival)
nextArrival = itRight->first;
time = nextArrival;
}
else {
time += t;
left = !left;
}
}
// Output:
for(int i = 0; i < m; ++i) {
cout << departures[i] << endl;
}
delete[] departures;
} // for cas
return 0;
}
| [
"lassedeleuran@gmail.com"
] | lassedeleuran@gmail.com |
c4d61426decb7510bbb8692feeeda5c0fdd8e478 | 86a29d61557608afae02550491ee2613d272a755 | /test/testkeytrans.cpp | 224f36026f9d647cc2c0e7f5b5d152163507268a | [] | no_license | fcitx/fcitx5-qt | b00300f1d04a6829eb0ec6b33fbec172fd857c45 | 413747e761b13bacc5ebd01e20810c64c2f3b6dc | refs/heads/master | 2023-09-01T07:38:59.672676 | 2023-08-14T18:09:49 | 2023-08-14T18:09:49 | 83,364,113 | 62 | 27 | null | 2023-07-31T22:07:49 | 2017-02-27T22:34:56 | C++ | UTF-8 | C++ | false | false | 1,391 | cpp | /*
* SPDX-FileCopyrightText: 2020~2020 CSSlayer <wengxt@gmail.com>
*
* SPDX-License-Identifier: LGPL-2.1-or-later
*
*/
#include "qtkeytrans.h"
#include <QApplication>
#include <fcitx-utils/keysym.h>
#include <fcitx-utils/log.h>
int main(int argc, char *argv[]) {
QCoreApplication app(argc, argv);
int sym;
unsigned int states;
fcitx::keyQtToSym(Qt::Key_Space, {}, " ", sym, states);
FCITX_ASSERT(sym == FcitxKey_space) << sym;
FCITX_ASSERT(static_cast<fcitx::KeyState>(states) ==
fcitx::KeyState::NoState);
fcitx::keyQtToSym(Qt::Key_Space, {}, "", sym, states);
FCITX_ASSERT(sym == FcitxKey_space) << sym;
FCITX_ASSERT(static_cast<fcitx::KeyState>(states) ==
fcitx::KeyState::NoState);
fcitx::keyQtToSym(Qt::Key_Space, Qt::ControlModifier, "", sym, states);
FCITX_ASSERT(sym == FcitxKey_space) << sym;
FCITX_ASSERT(static_cast<fcitx::KeyState>(states) == fcitx::KeyState::Ctrl);
fcitx::keyQtToSym(Qt::Key_F, Qt::ControlModifier, "", sym, states);
FCITX_ASSERT(sym == FcitxKey_F) << sym;
FCITX_ASSERT(static_cast<fcitx::KeyState>(states) == fcitx::KeyState::Ctrl);
fcitx::keyQtToSym(Qt::Key_F, Qt::ControlModifier, "\x06", sym, states);
FCITX_ASSERT(sym == FcitxKey_F) << sym;
FCITX_ASSERT(static_cast<fcitx::KeyState>(states) == fcitx::KeyState::Ctrl);
return 0;
}
| [
"wengxt@gmail.com"
] | wengxt@gmail.com |
6d05c001d53cc7111a988fc925ce24f2ddc40d08 | 350d6ea7d82208b5027e8c23a2a17bc42fef4daa | /dependencies-include/nxogre/include/NxOgreClothRaycaster.h | 987ef7e8094bd306d70e7bf6f19e3aac022226c0 | [] | no_license | bach74/Lisa | 2436d4da3765b9fe307d5e3dc31bfe532cf37dce | d80af7b880c0f99b914028dcf330d00ef0540cd3 | refs/heads/master | 2021-01-23T11:49:37.826497 | 2010-12-09T16:31:22 | 2010-12-09T16:31:22 | 1,153,210 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,901 | h | /** \file NxOgreClothRaycaster.h
* \brief Header for the ClothRayCaster class.
* \version 1.0-20
*
* \licence NxOgre a wrapper for the PhysX physics library.
* Copyright (C) 2005-8 Robin Southern of NxOgre.org http://www.nxogre.org
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef __NXOGRE_CLOTH_RAYCASTER_H__
#define __NXOGRE_CLOTH_RAYCASTER_H__
#include "NxOgrePrerequisites.h"
#include "NxOgreContainer.h" // For: mActors
#if (NX_USE_CLOTH_API == 1)
namespace NxOgre {
#if 0
class NxPublicClass ClothRayCaster {
friend class Scene;
public:
ClothRayCaster(Scene*);
~ClothRayCaster();
bool castCloth(Cloth*, const Ogre::Vector3& worldPosition, const Ogre::Vector3& normal);
bool castAllCloths(const Ogre::Vector3& worldPosition, const Ogre::Vector3& normal);
Cloth* getClosestCloth();
NxU32 getVertex();
ClothVertex getClothVertex();
Ogre::Vector3 getHitPosition();
protected:
Scene *mScene;
Cloth* mCloth;
NxU32 mLastVertexId;
NxVec3 mLastHitPosition;
private:
};
#endif
};
#endif
#endif
| [
"tomislav.reichenbach@fer.hr"
] | tomislav.reichenbach@fer.hr |
2c0a29b39ec393db4cb8a554dc8691d80e3bbcdd | 1ff71fc75dda697b9841bf73fb510f25dc4e88d6 | /project1.cpp | ad7c8d977079e7aaa5e826e47d6a4f2bfc3c0eb9 | [] | no_license | anchello2810/project1 | 7840b3a11ee291980e1cba8774e19850120f6a0a | 7cb13742f1f7383533d7de08eeab9b5daad52d5c | refs/heads/master | 2023-04-24T15:54:42.439223 | 2021-05-18T09:46:24 | 2021-05-18T09:46:24 | 368,477,905 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 529 | cpp | #include <iostream>
// This function prints
void print()
{
// Вызываем оператор << на объекте типа std::cout
std::cout << "Hello Skillbox!\n";
}
/*
* Приписываем значение переменным и печатаем Hello World
*/
int main()
{
int x = 100;
3 + 7;
int y = x + 100;
int b = 0;
b = b + 2;
int test;
test = 100500;
int test2 = 1005001;
int mult = x * y;
int rundom = 1002;
std::cout << "Hello World!\n";
} | [
"anchello@yandex.ru"
] | anchello@yandex.ru |
1bf2824b03ebd2e8835faa4a6c5f75c8fff6bc5d | 899e293884d1ed1896414d46e3b46a1a9bfdc490 | /ACM/regional2015online/shenyang/10022.cpp | b64b3f7923082d02cc200640dd30d722ef9b8e4b | [] | no_license | py100/University | d936dd071cca6c7db83551f15a952ffce2f4764c | 45906ae95c22597b834aaf153730196541b45e06 | refs/heads/master | 2021-06-09T05:49:23.656824 | 2016-10-27T08:22:52 | 2016-10-27T08:22:52 | 53,556,979 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 367 | cpp | #include <cstring>
#include <string>
#include <iostream>
#include <cstdio>
#include <vector>
#include <cstdlib>
#include <cmath>
using namespace std;
int P;
int main()
{
int T;
scanf("%d", &T);
int x;
for(int ka = 1; ka <= T; ka++)
{
scanf("%d%d", &x, &P);
printf("Case #%d: %d\n", ka, cal(x));
}
return 0;
} | [
"py100@live.cn"
] | py100@live.cn |
32ae862a910d6b0bb05f4c1b360776d58162779f | 5df66b7c0cf0241831ea7d8345aa4102f77eba03 | /Carberp Botnet/source - absource/pro/all source/FakeDllAutorun/src/exe/main.cpp | 6d97b50ec903440fff5cd8e695c8b0cf647f9d2a | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | bengalm/fireroothacker | e8f20ae69f4246fc4fe8c48bbb107318f7a79265 | ceb71ba972caca198524fe91a45d1e53b80401f6 | refs/heads/main | 2023-04-02T03:00:41.437494 | 2021-04-06T00:26:28 | 2021-04-06T00:26:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,928 | cpp | #include <tchar.h>
#include <windows.h>
#include <stdio.h>
#include <conio.h>
typedef void (WINAPI *StartRecPidFunction)( char* uid, char* nameVideo, DWORD pid, const char* ip1, int port1, const char* ip2, int port2 );
typedef void (WINAPI *StartCommandsConnectionFunction)(char* uid, const char* ip1, int port1, const char* ip2, int port2);
typedef void (WINAPI *StartSendFunction)( char* uid, char* path, const char* ip1, int port1, const char* ip2, int port2 );
int _tmain(int argc, _TCHAR* argv[])
{
char a[] = "\xE8\xFF\x15";
const WCHAR* dll_path = argv[1];
HMODULE dll_handle = LoadLibrary(dll_path);
//HMODULE dll_handle = LoadLibraryExW(dll_path, NULL, 0);
printf("LoadLibrary: dll_handle=0x%X\r\n", dll_handle);
if (dll_handle == NULL) return 0;
HMODULE h1 = GetModuleHandle(dll_path);
HMODULE h2 = GetModuleHandle(L"fake.dll");
HMODULE h3 = LoadLibraryExW(dll_path, NULL, 0);
HMODULE h4 = LoadLibrary(dll_path);
StartRecPidFunction start_rec_by_pid = (StartRecPidFunction)GetProcAddress(dll_handle,
"StartRecPid");
printf("GetProcAddress: start_rec_by_pid=0x%X\r\n", start_rec_by_pid);
if (start_rec_by_pid == NULL) return 0;
StartCommandsConnectionFunction start_commands =
(StartCommandsConnectionFunction)GetProcAddress(dll_handle, "StartTasksConnection");
printf("GetProcAddress: start_commands=0x%X\r\n", start_commands);
if (start_commands == NULL) return 0;
StartSendFunction start_send =
(StartSendFunction)GetProcAddress(dll_handle, "StartSend");
printf("GetProcAddress: start_send=0x%X\r\n", start_send);
if (start_send == NULL) return 0;
printf("WndRec loaded successfuly.\r\n");
//start_rec_by_pid("test01876128768", "notepad", 2544, "127.0.0.1", 700, NULL, 700);
start_commands("test01876128768", "127.0.0.1", 700, NULL, 0);
//start_send("test01876128768", "E:\\tftp", "127.0.0.1", 700, NULL, 0);
printf("press any key...\r\n");
_getch();
return 0;
}
| [
"ludi@ps.ac.cn"
] | ludi@ps.ac.cn |
45226a55db71a2c6ccf0973e8ca169eb173d39f1 | 616f19c9ecab3330a70d7378f5f73bbbc84ee071 | /cpp/DX93dProgramming/renumbered/Chapter 09/Radiosity/RadiosityCalc.cpp | eb05b791548a9ad47acae4082c186098fe23288b | [] | no_license | rjking58/development | 07dd809da012f736d82fde79c051cc2df328e6b7 | 9566648c6ecfc8b8cb6d166912dd674346da246b | refs/heads/master | 2021-10-11T12:25:31.025767 | 2021-10-01T16:41:06 | 2021-10-01T16:41:06 | 14,648,819 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 8,346 | cpp | /********************************************************************
* Advanced 3D Game Programming using DirectX 9.0 *
********************************************************************
* copyright (c) 2003 by Peter A Walsh and Adrian Perez *
* See license.txt for modification and distribution information *
********************************************************************/
#include "stdafx.h"
#include "RadiosityCalc.h"
#include <algorithm>
using namespace std;
cRadiosityCalc::sPolygon::sPolygon() :
m_pSPList( NULL ),
m_pPtList( NULL )
{
}
cRadiosityCalc::sPolygon::~sPolygon()
{
}
void cRadiosityCalc::sPolygon::CalcArea()
{
m_area = ((m_v[1]-m_v[0])^(m_v[2]-m_v[0])).Mag();
}
void cRadiosityCalc::sPolygon::CalcCenter()
{
m_center = m_v[0] + m_v[1] + m_v[2] + m_v[3];
m_center /= 4.f;
}
void cRadiosityCalc::sPolygon::GenPlane()
{
m_plane = plane3( m_v[0], m_v[1], m_v[2] );
}
void cRadiosityCalc::sPolygon::Subdivide( float targetArea, list< sPatch* >& inList )
{
point3 uDir = m_v[1] - m_v[0];
point3 vDir = m_v[3] - m_v[0];
float uMag = uDir.Mag();
float vMag = vDir.Mag();
float targetDim = (float)sqrt( targetArea ); // the length of a side of our target square
int uDim = (int) ceil( uDir.Mag() / targetDim );
int vDim = (int) ceil( vDir.Mag() / targetDim );
m_nVerts = (uDim+1)*(vDim+1);
//m_nTris = 2 * (uDim)*(vDim);
m_nSubPatches = (uDim)*(vDim);
// This memory should be released after the radiosity
// simulator has run its course
m_pPtList = new point3[ m_nVerts ];
m_pSPList = new sPatch[ m_nSubPatches ];
// build the list of points
int u, v;
float du, dv;
point3* pCurrPt = m_pPtList;
for( v=0; v< vDim+1; v++ )
{
if( v == vDim )
{
dv = 1.f;
}
else
{
dv = (float)v * targetDim / vMag;
}
for( u=0; u< uDim+1; u++ )
{
if( u == uDim )
{
du = 1.f;
}
else
{
du = (float)u * targetDim / uMag;
}
*pCurrPt = m_v[0] + (du * uDir) + (dv * vDir);
pCurrPt++;
}
}
// build the patch list.
sPatch* pCurrSP = m_pSPList;
for( v=0; v< vDim; v++ )
{
for( u=0; u< uDim; u++ )
{
// tesselating square [u,v]
pCurrSP->m_v[0] = &m_pPtList[(uDim+1)*(v+0) + (u+0)];
pCurrSP->m_v[1] = &m_pPtList[(uDim+1)*(v+0) + (u+1)];
pCurrSP->m_v[2] = &m_pPtList[(uDim+1)*(v+1) + (u+1)];
pCurrSP->m_v[3] = &m_pPtList[(uDim+1)*(v+1) + (u+0)];
pCurrSP->m_area =
((*pCurrSP->m_v[1] - *pCurrSP->m_v[0]) ^
(*pCurrSP->m_v[3] - *pCurrSP->m_v[0])).Mag();
pCurrSP->m_center = (*pCurrSP->m_v[0] + *pCurrSP->m_v[1] + *pCurrSP->m_v[2] + *pCurrSP->m_v[3]) / 4.f;
pCurrSP->m_deltaRad = m_deltaRad;
pCurrSP->m_intensity =
pCurrSP->m_area *
(pCurrSP->m_deltaRad.r + pCurrSP->m_deltaRad.g + pCurrSP->m_deltaRad.b);
pCurrSP->m_plane = m_plane;
pCurrSP->m_radiosity = m_radiosity;
pCurrSP->m_reflect = m_reflect;
pCurrSP->m_pParent = this;
inList.push_back( pCurrSP );
pCurrSP++;
}
}
}
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
cRadiosityCalc::cRadiosityCalc()
{
m_stdArea = 1.f;
}
cRadiosityCalc::~cRadiosityCalc()
{
}
void cRadiosityCalc::Load( cFile &file )
{
int nPatches;
char currLine[255];
// get the first line without comments on it.
do
{
file.ReadLine( currLine );
} while( currLine[0] == '\n' || currLine[0] == '#' );
sscanf( currLine, "%i", &nPatches );
sPolygon* pPatch;
for( int pIndex=0; pIndex<nPatches; pIndex++ )
{
pPatch = new sPolygon();
// get a good line of text
do
{
file.ReadLine( currLine );
} while( currLine[0] == '\n' || currLine[0] == '#' );
sscanf( currLine, "%f %f %f %f",
&pPatch->m_radiosity.r,
&pPatch->m_radiosity.g,
&pPatch->m_radiosity.b,
&pPatch->m_reflect );
pPatch->m_deltaRad = pPatch->m_radiosity;
// we implicitly assume quads.
for( int vIndex=0; vIndex<4; vIndex++ )
{
// get a good line of text
do
{
file.ReadLine( currLine );
} while( currLine[0] == '\n' || currLine[0] == '#' );
sscanf(
currLine,
"%f %f %f",
&pPatch->m_v[vIndex].x,
&pPatch->m_v[vIndex].y,
&pPatch->m_v[vIndex].z );
}
pPatch->GenPlane();
pPatch->CalcCenter();
pPatch->CalcArea();
pPatch->Subdivide( m_stdArea, m_patchList );
m_polyList.push_back( pPatch );
// add the patch to the tree
polygon<point3> poly(4);
poly.nElem = 4;
poly.pList[0] = pPatch->m_v[0];
poly.pList[1] = pPatch->m_v[1];
poly.pList[2] = pPatch->m_v[2];
poly.pList[3] = pPatch->m_v[3];
m_tree.AddPolygon( poly );
}
m_startTime = timeGetTime();
}
void cRadiosityCalc::Draw()
{
LPDIRECT3DDEVICE9 pDevice = Graphics()->GetDevice();
list<sPolygon*>::iterator iter;
sPolygon* pCurr;
sLitVertex v[4];
// init
for( iter = m_polyList.begin(); iter != m_polyList.end(); iter++ )
{
pCurr = *iter;
color3 col;
sPatch* pCurrSP;
for( int i=0; i<pCurr->m_nSubPatches; i++ )
{
pCurrSP = &pCurr->m_pSPList[i];
v[0] = sLitVertex( *pCurrSP->m_v[0], pCurrSP->m_radiosity.MakeDWordSafe() );
v[1] = sLitVertex( *pCurrSP->m_v[1], pCurrSP->m_radiosity.MakeDWordSafe() );
v[2] = sLitVertex( *pCurrSP->m_v[2], pCurrSP->m_radiosity.MakeDWordSafe() );
v[3] = sLitVertex( *pCurrSP->m_v[3], pCurrSP->m_radiosity.MakeDWordSafe() );
pDevice->DrawPrimitiveUP(
D3DPT_TRIANGLEFAN,
2,
v,
sizeof( sLitVertex ) );
}
}
}
bool cRadiosityCalc::LineOfSight( sPatch* a, sPatch* b )
{
// Early-out 1: they're sitting on the same spot
if( a->m_plane == b->m_plane )
return false;
// Early-out 2: b is behind a
if( a->m_plane.TestPoint( b->m_center ) == ptBack )
return false;
// Early-out 3: a is behind b
if( b->m_plane.TestPoint( a->m_center ) == ptBack )
return false;
// Compute the slow
return m_tree.LineOfSight( a->m_center, b->m_center );
}
float cRadiosityCalc::FormFactor( sPatch *pSrc, sPatch *pDest )
{
float angle1, angle2, dist, factor;
point3 vec;
// find vij first. If it's 0, we can early-out.
if( !LineOfSight( pSrc, pDest ) )
return 0.f;
point3 srcLoc = pSrc->m_center;
point3 destLoc = pDest->m_center;
vec = destLoc - srcLoc;
dist = vec.Mag();
vec /= dist;
angle1 = vec * pSrc->m_plane.n;
angle2 = -( vec * pDest->m_plane.n );
factor = angle1 * angle2 * pDest->m_area;
factor /= PI * dist * dist;
return factor;
}
cRadiosityCalc::sPatch* cRadiosityCalc::FindBrightest()
{
sPatch* pBrightest = NULL;
float brightest = 0.05f;
float currIntensity;
list<sPatch*>::iterator iter;
// Blech. Linear search
sPatch* pCurr;
for( iter = m_patchList.begin(); iter != m_patchList.end(); iter++ )
{
pCurr = *iter;
currIntensity = pCurr->m_intensity;
if( currIntensity > brightest )
{
brightest = currIntensity;
pBrightest = pCurr;
}
}
// This will be NULL if nothing was bright enough
return pBrightest;
}
bool cRadiosityCalc::CalcNextIteration()
{
// Find the next patch that we need to
sPatch* pSrc = FindBrightest();
// If there was no patch, we're done.
if( !pSrc )
{
DWORD diff = timeGetTime() - m_startTime;
float time = (float)diff/1000;
char buff[255];
sprintf(buff,"Radiosity : Done - took %f seconds to render", time );
SetWindowText( MainWindow()->GetHWnd(), buff );
return false; // no more to calculate
}
sPatch* pDest;
list<sPatch*>::iterator iter;
float formFactor; // form factor Fi-j
color3 deltaRad; // Incremental radiosity shot from src to dest
for( iter = m_patchList.begin(); iter != m_patchList.end(); iter++ )
{
pDest = *iter;
// Skip sending energy to ourself
if( pDest == pSrc )
continue;
// Compute the form factor
formFactor = FormFactor( pDest, pSrc );
// Early out if the form factor was 0.
if( formFactor == 0.f )
continue;
// Compute the energy being sent from src to dest
deltaRad = pDest->m_reflect * pSrc->m_deltaRad * formFactor;
// Send said energy
pDest->m_radiosity += deltaRad;
pDest->m_deltaRad += deltaRad;
// Cache the new intensity.
pDest->m_intensity =
pDest->m_area *
(pDest->m_deltaRad.r +
pDest->m_deltaRad.g +
pDest->m_deltaRad.b );
}
// this patch has shot out all of its engergy.
pSrc->m_deltaRad = color3::Black;
pSrc->m_intensity = 0.f;
return true;
}
| [
"richardjking2000@yahoo.com"
] | richardjking2000@yahoo.com |
d314c0f876c85cd687345e7676c9ed69b149e3d2 | 199db94b48351203af964bada27a40cb72c58e16 | /lang/uk/gen/Bible43.h | 0f06402c77060e8558bdcf430c65a38d71c44865 | [] | no_license | mkoldaev/bible50cpp | 04bf114c1444662bb90c7e51bd19b32e260b4763 | 5fb1fb8bd2e2988cf27cfdc4905d2702b7c356c6 | refs/heads/master | 2023-04-05T01:46:32.728257 | 2021-04-01T22:36:06 | 2021-04-01T22:36:06 | 353,830,130 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 162,180 | h | #include <map>
#include <string>
class Bible43
{
struct uk1 { int val; const char *msg; };
struct uk2 { int val; const char *msg; };
struct uk3 { int val; const char *msg; };
struct uk4 { int val; const char *msg; };
struct uk5 { int val; const char *msg; };
struct uk6 { int val; const char *msg; };
struct uk7 { int val; const char *msg; };
struct uk8 { int val; const char *msg; };
struct uk9 { int val; const char *msg; };
struct uk10 { int val; const char *msg; };
struct uk11 { int val; const char *msg; };
struct uk12 { int val; const char *msg; };
struct uk13 { int val; const char *msg; };
struct uk14 { int val; const char *msg; };
struct uk15 { int val; const char *msg; };
struct uk16 { int val; const char *msg; };
struct uk17 { int val; const char *msg; };
struct uk18 { int val; const char *msg; };
struct uk19 { int val; const char *msg; };
struct uk20 { int val; const char *msg; };
struct uk21 { int val; const char *msg; };
public:
static void view1() {
struct uk1 poems[] = {
{1, "1 Споконвіку було Слово, а Слово в Бога було, і Бог було Слово."},
{2, "2 Воно в Бога було споконвіку."},
{3, "3 Усе через Нього повстало, і ніщо, що повстало, не повстало без Нього."},
{4, "4 І життя було в Нім, а життя було Світлом людей."},
{5, "5 А Світло у темряві світить, і темрява не обгорнула його."},
{6, "6 Був один чоловік, що від Бога був посланий, йому ймення Іван."},
{7, "7 Він прийшов на свідоцтво, щоб засвідчити про Світло, щоб повірили всі через нього."},
{8, "8 Він тим Світлом не був, але свідчити мав він про Світло."},
{9, "9 Світлом правдивим був Той, Хто просвічує кожну людину, що приходить на світ."},
{10, "10 Воно в світі було, і світ через Нього повстав, але світ не пізнав Його."},
{11, "11 До свого Воно прибуло, та свої відцурались Його."},
{12, "12 А всім, що Його прийняли, їм владу дало дітьми Божими стати, тим, що вірять у Ймення Його,"},
{13, "13 що не з крови, ані з пожадливости тіла, ані з пожадливости мужа, але народились від Бога."},
{14, "14 І Слово сталося тілом, і перебувало між нами, повне благодаті та правди, і ми бачили славу Його, славу як Однородженого від Отця."},
{15, "15 Іван свідчить про Нього, і кликав, говорячи: Це був Той, що про Нього казав я: Той, Хто прийде за мною, існував передо мною, бо був перше, ніж я."},
{16, "16 А з Його повноти ми одержали всі, а то благодать на благодать."},
{17, "17 Закон бо через Мойсея був даний, а благодать та правда з'явилися через Ісуса Христа."},
{18, "18 Ніхто Бога ніколи не бачив, Однороджений Син, що в лоні Отця, Той Сам виявив був."},
{19, "19 А це ось свідоцтво Іванове, як юдеї послали були з Єрусалиму священиків та Левитів, щоб спитали його: Хто ти такий?"},
{20, "20 І він визнав, і не зрікся, а визнав: Я не Христос."},
{21, "21 І запитали його: А хто ж? Чи Ілля? І відказує: Ні! Чи пророк? І дав відповідь: Ні!"},
{22, "22 Сказали ж йому: Хто ж ти такий? щоб дати відповідь тим, хто послав нас. Що ти кажеш про себе самого?"},
{23, "23 Відказав: Я голос того, хто кличе: В пустині рівняйте дорогу Господню, як Ісая пророк заповів."},
{24, "24 Посланці ж із фарисеїв були."},
{25, "25 І вони запитали його та сказали йому: Для чого ж ти христиш, коли ти не Христос, ні Ілля, ні пророк?"},
{26, "26 Відповів їм Іван, промовляючи: Я водою хрищу, а між вами стоїть, що Його ви не знаєте."},
{27, "27 Він Той, Хто за мною йде, Хто до мене був, Кому розв'язати ремінця від узуття Його я негідний."},
{28, "28 Це в Віфанії діялося, на тім боці Йордану, де христив був Іван."},
{29, "29 Наступного дня Іван бачить Ісуса, що до нього йде, та й каже: Оце Агнець Божий, що на Себе гріх світу бере!"},
{30, "30 Це Той, що про Нього казав я: За мною йде Муж, що передо мною Він був, бо був перше, ніж я."},
{31, "31 І не знав я Його; та для того прийшов я, христивши водою, щоб Ізраїлеві Він з'явився."},
{32, "32 І свідчив Іван, промовляючи: Бачив я Духа, що сходив, як голуб, із неба, та зоставався на Ньому."},
{33, "33 І не знав я Його, але Той, Хто христити водою послав мене, мені оповів: Над Ким Духа побачиш, що сходить і зостається на Ньому, це Той, Хто христитиме Духом Святим."},
{34, "34 І я бачив, і засвідчив, що Він Божий Син!"},
{35, "35 Наступного дня стояв знову Іван та двоє з учнів його."},
{36, "36 І, поглянувши на Ісуса, що проходив, Він сказав: Ото Агнець Божий!"},
{37, "37 І почули два учні, як він говорив, та й пішли за Ісусом."},
{38, "38 А Ісус обернувся й побачив, що вони йшли за Ним, та й каже до них: Чого ви шукаєте? А вони відказали Йому: Равві перекладене це визначає: Учителю, де Ти живеш?"},
{39, "39 Він говорить до них: Ходіть і побачте! Ті пішли та й побачили, де Він жив, і в Нього той день перебули. Було ж коло години десятої."},
{40, "40 А один із тих двох, що чули від Івана та йшли вслід за Ним, був Андрій, брат Симона Петра."},
{41, "41 Він знайшов перше Симона, брата свого, та й говорить до нього: Знайшли ми Месію, що визначає: Христос."},
{42, "42 І привів він його до Ісуса. На нього ж споглянувши, промовив Ісус: Ти Симон, син Йонин; будеш званий ти Кифа, що визначає: скеля."},
{43, "43 Наступного дня захотів Він піти в Галілею. І знайшов Він Пилипа та й каже йому: Іди за Мною!"},
{44, "44 А Пилип із Віфсаїди походив, із міста Андрія й Петра."},
{45, "45 Пилип Нафанаїла знаходить та й каже йому: Ми знайшли Того, що про Нього писав був Мойсей у Законі й Пророки, Ісуса, сина Йосипового, із Назарету."},
{46, "46 І сказав йому Нафанаїл: Та хіба ж може бути з Назарету що добре? Пилип йому каже: Прийди та побач."},
{47, "47 Ісус, угледівши Нафанаїла, що до Нього йде, говорить про нього: Ото справді ізраїльтянин, що немає в нім підступу!"},
{48, "48 Говорить Йому Нафанаїл: Звідки знаєш мене? Ісус відповів і до нього сказав: Я бачив тебе ще давніш, ніж Пилип тебе кликав, як під фіґовим деревом був ти."},
{49, "49 Відповів Йому Нафанаїл: Учителю, Ти Син Божий, Ти Цар Ізраїлів!"},
{50, "50 Ісус відповів і до нього сказав: Через те віриш ти, що сказав Я тобі, що під фіґовим деревом бачив тебе? Більш від цього побачиш!"},
{51, "51 І Він каже йому: Поправді, поправді кажу вам: Відтепер ви побачите небо відкрите та Анголів Божих, що на Людського Сина підіймаються та спускаються."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view2() {
struct uk2 poems[] = {
{1, "1 А третього дня весілля справляли в Кані Галілейській, і була там Ісусова мати."},
{2, "2 На весілля запрошений був теж Ісус та учні Його."},
{3, "3 Як забракло ж вина, то мати Ісусова каже до Нього: Не мають вина!"},
{4, "4 Ісус же відказує їй: Що тобі, жоно, до Мене? Не прийшла ще година Моя!"},
{5, "5 А мати Його до слуг каже: Зробіть усе те, що Він вам скаже!"},
{6, "6 Було тут шість камінних посудин на воду, що стояли для очищення юдейського, що відер по дві чи по три вміщали."},
{7, "7 Ісус каже до слуг: Наповніть водою посудини. І їх поналивали вщерть."},
{8, "8 І Він каже до них: Тепер зачерпніть, і занесіть до весільного старости. І занесли."},
{9, "9 Як весільний же староста скуштував воду, що сталась вином, а він не знав, звідки воно, знали ж слуги, що води наливали, то староста кличе тоді молодого"},
{10, "10 та й каже йому: Кожна людина подає перше добре вино, а як понапиваються, тоді гірше; а ти добре вино аж на досі зберіг..."},
{11, "11 Такий початок чудам зробив Ісус у Кані Галілейській, і виявив славу Свою. І ввірували в Нього учні Його."},
{12, "12 Після цього відправивсь Він Сам, і мати Його, і брати Його, і Його учні до Капернауму, і там перебули небагато днів."},
{13, "13 А зближалася Пасха юдейська, і до Єрусалиму подався Ісус."},
{14, "14 І знайшов Він, що продавали у храмі волів, і овець, і голубів, та сиділи міняльники."},
{15, "15 І, зробивши бича з мотузків, Він вигнав із храму всіх, вівці й воли, а міняльникам гроші розсипав, і поперевертав їм столи."},
{16, "16 І сказав продавцям голубів: Заберіть оце звідси, і не робіть із дому Отця Мого дому торгового!"},
{17, "17 Тоді учні Його згадали, що написано: Ревність до дому Твого з'їдає Мене!"},
{18, "18 І обізвались юдеї й сказали Йому: Яке нам знамено покажеш, що Ти можеш робити таке?"},
{19, "19 Ісус відповів і промовив до них: Зруйнуйте цей храм, і за три дні Я поставлю його!"},
{20, "20 Відказали ж юдеї: Сорок шість літ будувався цей храм, а Ти за три дні поставиш його?"},
{21, "21 А Він говорив про храм тіла Свого."},
{22, "22 Коли ж Він із мертвих воскрес, то учні Його згадали, що Він говорив це, і ввірували в Писання та в слово, що сказав був Ісус."},
{23, "23 А як в Єрусалимі Він був у свято Пасхи, то багато-хто ввірували в Його Ймення, побачивши чуда Його, що чинив."},
{24, "24 Але Сам Ісус їм не звірявся, бо Сам знав усіх,"},
{25, "25 і потреби не мав, щоб хто свідчив Йому про людину, бо знав Сам, що в людині було."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view3() {
struct uk3 poems[] = {
{1, "1 Був один чоловік із фарисеїв Никодим на ім'я, начальник юдейський."},
{2, "2 Він до Нього прийшов уночі, та й промовив Йому: Учителю, знаємо ми, що прийшов Ти від Бога, як Учитель, бо не може ніхто таких чуд учинити, які чиниш Ти, коли Бог із ним не буде."},
{3, "3 Ісус відповів і до нього сказав: Поправді, поправді кажу Я тобі: Коли хто не народиться згори, то не може побачити Божого Царства."},
{4, "4 Никодим Йому каже: Як може людина родитися, бувши старою? Хіба може вона ввійти до утроби своїй матері знову й родитись?"},
{5, "5 Ісус відповів: Поправді, поправді кажу Я тобі: Коли хто не родиться з води й Духа, той не може ввійти в Царство Боже."},
{6, "6 Що вродилося з тіла є тіло, що ж уродилося з Духа є дух."},
{7, "7 Не дивуйся тому, що сказав Я тобі: Вам необхідно родитись згори."},
{8, "8 Дух дихає, де хоче, і його голос ти чуєш, та не відаєш, звідкіля він приходить, і куди він іде. Так буває і з кожним, хто від Духа народжений."},
{9, "9 Відповів Никодим і до Нього сказав: Як це статися може?"},
{10, "10 Ісус відповів і до нього сказав: Ти учитель ізраїльський, то чи ж цього не знаєш?"},
{11, "11 Поправді, поправді кажу Я тобі: Ми говоримо те, що ми знаємо, а свідчимо про те, що ми бачили, але свідчення нашого ви не приймаєте."},
{12, "12 Коли Я говорив вам про земне, та не вірите ви, то як же повірите ви, коли Я говоритиму вам про небесне?"},
{13, "13 І не сходив на небо ніхто, тільки Той, Хто з неба зійшов, Людський Син, що на небі."},
{14, "14 І, як Мойсей підніс змія в пустині, так мусить піднесений бути й Син Людський,"},
{15, "15 щоб кожен, хто вірує в Нього, мав вічне життя."},
{16, "16 Так бо Бог полюбив світ, що дав Сина Свого Однородженого, щоб кожен, хто вірує в Нього, не згинув, але мав життя вічне."},
{17, "17 Бо Бог не послав Свого Сина на світ, щоб Він світ засудив, але щоб через Нього світ спасся."},
{18, "18 Хто вірує в Нього, не буде засуджений; хто ж не вірує, той вже засуджений, що не повірив в Ім'я Однородженого Сина Божого."},
{19, "19 Суд же такий, що світло на світ прибуло, люди ж темряву більш полюбили, як світло, лихі бо були їхні вчинки!"},
{20, "20 Бо кожен, хто робить лихе, ненавидить світло, і не приходить до світла, щоб не зганено вчинків його."},
{21, "21 А хто робить за правдою, той до світла йде, щоб діла його виявились, бо зроблені в Бозі вони."},
{22, "22 По цьому прийшов Ісус та учні Його до країни Юдейської, і з ними Він там проживав та христив."},
{23, "23 А Іван теж христив в Еноні поблизу Салиму, бо було там багато води; і приходили люди й христились,"},
{24, "24 бо Іван до в'язниці не був ще посаджений."},
{25, "25 І зчинилось змагання Іванових учнів з юдеями про очищення."},
{26, "26 І прийшли до Івана вони та й сказали йому: Учителю, Той, Хто був із тобою по той бік Йордану, про Якого ти свідчив, ото христить і Він, і до Нього всі йдуть."},
{27, "27 Іван відповів і сказав: Людина нічого приймати не може, як їй з неба не дасться."},
{28, "28 Ви самі мені свідчите, що я говорив: я не Христос, але посланий я перед Ним."},
{29, "29 Хто має заручену, той молодий. А дружко молодого, що стоїть і його слухає, дуже тішиться з голосу молодого. Така радість моя оце здійснилась!"},
{30, "30 Він має рости, я ж маліти."},
{31, "31 Хто зверху приходить, Той над усіма. Хто походить із землі, то той земний, і говорить поземному. Хто приходить із неба, Той над усіма,"},
{32, "32 і що бачив і чув, те Він свідчить, та свідоцтва Його не приймає ніхто."},
{33, "33 Хто ж прийняв свідоцтво Його, той ствердив тим, що Бог правдивий."},
{34, "34 Бо Кого Бог послав, Той Божі слова промовляє, бо Духа дає Бог без міри."},
{35, "35 Отець любить Сина, і дав усе в Його руку."},
{36, "36 Хто вірує в Сина, той має вічне життя; а хто в Сина не вірує, той життя не побачить а гнів Божий на нім перебуває."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view4() {
struct uk4 poems[] = {
{1, "1 Як Господь же довідався, що почули фарисеї, що Ісус учнів більше збирає та христить, як Іван,"},
{2, "2 хоч Ісус не христив Сам, а учні Його,"},
{3, "3 Він покинув Юдею та знову пішов у Галілею."},
{4, "4 І потрібно було Самарію Йому переходити."},
{5, "5 Отож, прибуває Він до самарійського міста, що зветься Сіхар, недалеко від поля, яке Яків був дав своєму синові Йосипові."},
{6, "6 Там же була Яковова криниця. І Ісус, дорогою зморений, сів отак край криниці. Було коло години десь шостої."},
{7, "7 Надходить ось жінка одна з Самарії набрати води. Ісус каже до неї: Дай напитись Мені!"},
{8, "8 Бо учні Його відійшли були в місто, щоб купити поживи."},
{9, "9 Тоді каже Йому самарянка: Як же Ти, юдеянин бувши, та просиш напитись від мене, самарянки? Бо юдеї не сходяться із самарянами."},
{10, "10 Ісус відповів і промовив до неї: Коли б знала ти Божий дар, і Хто Той, Хто говорить тобі: Дай напитись Мені, ти б у Нього просила, і Він тобі дав би живої води."},
{11, "11 Каже жінка до Нього: І черпака в Тебе, Пане, нема, а криниця глибока, звідки ж маєш Ти воду живу?"},
{12, "12 Чи Ти більший за нашого отця Якова, що нам дав цю криницю, і він сам із неї пив, і сини його, і худоба його?"},
{13, "13 Ісус відповів і сказав їй: Кожен, хто воду цю п'є, буде прагнути знову."},
{14, "14 А хто питиме воду, що Я йому дам, прагнути не буде повік, бо вода, що Я йому дам, стане в нім джерелом тієї води, що тече в життя вічне."},
{15, "15 Каже жінка до Нього: Дай мені, Пане, цієї води, щоб я пити не хотіла, і сюди не приходила брати."},
{16, "16 Говорить до неї Ісус: Іди, поклич чоловіка свого та й вертайся сюди."},
{17, "17 Жінка відповіла та й сказала: Чоловіка не маю... Відказав їй Ісус: Ти добре сказала: Чоловіка не маю."},
{18, "18 Бо п'ятьох чоловіків ти мала, а той, кого маєш тепер, не муж він тобі. Це ти правду сказала."},
{19, "19 Каже жінка до Нього: Бачу, Пане, що Пророк Ти."},
{20, "20 Отці наші вклонялися Богу на цій ось горі, а ви твердите, що в Єрусалимі те місце, де потрібно вклонятись."},
{21, "21 Ісус промовляє до неї: Повір, жінко, Мені, що надходить година, коли ні на горі цій, ані в Єрусалимі вклонятись Отцеві не будете ви."},
{22, "22 Ви вклоняєтесь тому, чого ви не знаєте, ми вклоняємось тому, що знаємо, бо спасіння від юдеїв."},
{23, "23 Але наступає година, і тепер вона є, коли богомільці правдиві вклонятися будуть Отцеві в дусі та в правді, бо Отець Собі прагне таких богомільців."},
{24, "24 Бог є Дух, і ті, що Йому вклоняються, повинні в дусі та в правді вклонятись."},
{25, "25 Відказує жінка Йому: Я знаю, що прийде Месія, що зветься Христос, як Він прийде, то все розповість нам."},
{26, "26 Промовляє до неї Ісус: Це Я, що розмовляю з тобою..."},
{27, "27 І тоді надійшли Його учні, і дивувались, що з жінкою Він розмовляв. Проте жаден із них не спитав: Чого хочеш? або: Про що з нею говориш?"},
{28, "28 Покинула жінка тоді водоноса свого, і побігла до міста, та й людям говорить:"},
{29, "29 Ходіть но, побачте Того Чоловіка, що сказав мені все, що я вчинила. Чи Він не Христос?"},
{30, "30 І вони повиходили з міста, і до Нього прийшли."},
{31, "31 Тим часом же учні просили Його та й казали: Учителю, їж!"},
{32, "32 А Він їм відказав: Я маю поживу на їдження, якої не знаєте ви."},
{33, "33 Питали тоді один одного учні: Хіба хто приніс Йому їсти?"},
{34, "34 Ісус каже до них: Пожива Моя чинити волю Того, Хто послав Мене, і справу Його довершити."},
{35, "35 Чи не кажете ви: Ще чотири от місяці, і настануть жнива? А Я вам кажу: Підійміть свої очі, та гляньте на ниви, як для жнив уже пополовіли вони!"},
{36, "36 А хто жне, той заплату бере, та збирає врожай в життя вічне, щоб хто сіє й хто жне разом раділи."},
{37, "37 Бо про це поговірка правдива: Хто інший сіє, а хто інший жне."},
{38, "38 Я вас жати послав, де ви не працювали: працювали інші, ви ж до їхньої праці ввійшли."},
{39, "39 З того ж міста багато-хто із самарян в Нього ввірували через слово жінки, що свідчила: Він сказав мені все, що я вчинила була!"},
{40, "40 А коли самаряни до Нього прийшли, то благали Його, щоб у них позостався. І Він перебув там два дні."},
{41, "41 Значно ж більш вони ввірували через слово Його."},
{42, "42 А до жінки казали вони: Не за слово твоє ми вже віруємо, самі бо ми чули й пізнали, що справді Спаситель Він світу!"},
{43, "43 Як минуло ж два дні, Він ізвідти пішов в Галілею."},
{44, "44 Сам бо свідчив Ісус, що не має пошани пророк у вітчизні своїй."},
{45, "45 А коли Він прийшов в Галілею, Його прийняли галілеяни, побачивши все, що вчинив Він в Єрусалимі на святі, бо ходили на свято й вони."},
{46, "46 Тоді знову прийшов Ісус у Кану Галілейську, де перемінив був Він воду на вино. І був там один царедворець, що син його хворів у Капернаумі."},
{47, "47 Він, почувши, що Ісус із Юдеї прибув в Галілею, до Нього прийшов і благав Його, щоб пішов і сина йому вздоровив, бо мав той умерти."},
{48, "48 Ісус же промовив до нього: Як знамен тих та чуд не побачите, не ввіруєте!"},
{49, "49 Царедворець говорить до Нього: Піди, Господи, поки не вмерла дитина моя!"},
{50, "50 Промовляє до нього Ісус: Іди, син твій живе! І повірив той слову, що до нього промовив Ісус, і пішов."},
{51, "51 А коли ще в дорозі він був, то раби його перестріли його й сповістили, говорячи: Син твій живе."},
{52, "52 А він їх запитав про годину, о котрій стало легше йому. Вони ж відказали до нього: Учора о сьомій годині гарячка покинула його."},
{53, "53 Зрозумів тоді батько, що була то година, о котрій до нього промовив Ісус: Син твій живе. І ввірував сам і ввесь його дім."},
{54, "54 Це знов друге знамено Ісус учинив, як вернувся до Галілеї з Юдеї."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view5() {
struct uk5 poems[] = {
{1, "1 Після того юдейське Свято було, і до Єрусалиму Ісус відійшов."},
{2, "2 А в Єрусалимі, біля брами Овечої, є купальня, Віфесда по-єврейському зветься, що мала п'ять ґанків."},
{3, "3 У них лежало багато слабих, сліпих, кривих, сухих, що чекали, щоб воду порушено."},
{4, "4 Бо Ангол Господній часами спускавсь до купальні, і порушував воду, і хто перший улазив, як воду порушено, той здоровим ставав, хоч би яку мав хворобу."},
{5, "5 А був там один чоловік, що тридцять і вісім років був недужим."},
{6, "6 Як Ісус його вгледів, що лежить, та, відаючи, що багато він часу слабує, говорить до нього: Хочеш бути здоровим?"},
{7, "7 Відповів Йому хворий: Пане, я не маю людини, щоб вона, як порушено воду, до купальні всадила мене. А коли я приходжу, то передо мною вже інший улазить."},
{8, "8 Говорить до нього Ісус: Уставай, візьми ложе своє та й ходи!"},
{9, "9 І зараз одужав оцей чоловік, і взяв ложе своє та й ходив. Того ж дня субота була,"},
{10, "10 тому то сказали юдеї вздоровленому: Є субота, і не годиться тобі брати ложа свого."},
{11, "11 А він відповів їм: Хто мене вздоровив, Той до мене сказав: Візьми ложе своє та й ходи."},
{12, "12 А вони запитали його: Хто Той Чоловік, що до тебе сказав: Візьми ложе своє та й ходи?"},
{13, "13 Та не знав уздоровлений, Хто то Він, бо Ісус ухиливсь від народу, що був на тім місці."},
{14, "14 Після того Ісус стрів у храмі його, та й промовив до нього: Ось видужав ти. Не гріши ж уже більше, щоб не сталось тобі чого гіршого!"},
{15, "15 Чоловік же пішов і юдеям звістив, що Той, Хто вздоровив його, то Ісус."},
{16, "16 І тому зачали юдеї переслідувати Ісуса, що таке Він чинив у суботу."},
{17, "17 А Ісус відповів їм: Отець Мій працює аж досі, працюю і Я."},
{18, "18 І тому то юдеї ще більш намагалися вбити Його, що не тільки суботу порушував Він, але й Бога Отцем Своїм звав, тим роблячись Богові рівним."},
{19, "19 Відповів же Ісус і сказав їм: Поправді, поправді кажу вам: Син нічого робити не може Сам від Себе, тільки те, що Він бачить, що робить Отець; бо що робить Він, те так само й Син робить."},
{20, "20 Бо Отець любить Сина, і показує все, що Сам робить, Йому. І покаже Йому діла більші від цих, щоб ви дивувались."},
{21, "21 Бо як мертвих Отець воскрешає й оживлює, так і Син, кого хоче, оживлює."},
{22, "22 Бо Отець і не судить нікого, а ввесь суд віддав Синові,"},
{23, "23 щоб усі шанували і Сина, як шанують Отця. Хто не шанує Сина, не шанує Отця, що послав Його."},
{24, "24 Поправді, поправді кажу вам: Хто слухає слова Мого, і вірує в Того, Хто послав Мене, життя вічне той має, і на суд не приходить, але перейшов він від смерти в життя."},
{25, "25 Поправді, поправді кажу вам: Наступає година, і тепер уже є, коли голос Божого Сина почують померлі, а ті, що почують, оживуть."},
{26, "26 Бо як має Отець життя Сам у Собі, так і Синові дав життя мати в Самому Собі."},
{27, "27 І Він дав Йому силу чинити і суд, бо Він Людський Син."},
{28, "28 Не дивуйтесь цьому, бо надходить година, коли всі, хто в гробах, Його голос почують,"},
{29, "29 і повиходять ті, що чинили добро, на воскресення життя, а котрі зло чинили, на воскресення Суду."},
{30, "30 Я нічого не можу робити Сам від Себе. Як Я чую, суджу, і Мій суд справедливий, не шукаю бо волі Своєї, але волі Отця, що послав Мене."},
{31, "31 Коли свідчу про Себе Я Сам, то свідоцтво Моє неправдиве."},
{32, "32 Є Інший, Хто свідчить про Мене, і Я знаю, що правдиве свідоцтво, яким свідчить про Мене."},
{33, "33 Ви послали були до Івана, і він свідчив про правду."},
{34, "34 Та Я не від людини свідоцтва приймаю, але це говорю, щоб були ви спасені."},
{35, "35 Він світильником був, що горів і світив, та ви тільки хвилю хотіли потішитись світлом його."},
{36, "36 Але Я маю свідчення більше за Іванове, бо ті справи, що Отець Мені дав, щоб Я виконав їх, ті справи, що Я їх чиню, самі свідчать про Мене, що Отець Мене послав!"},
{37, "37 Та й Отець, що послав Мене, Сам засвідчив про Мене; але ви ані голосу Його не чули ніколи, ані виду Його не бачили."},
{38, "38 Навіть слова Його ви не маєте, щоб у вас перебувало, бо не вірите в Того, Кого Він послав."},
{39, "39 Дослідіть но Писання, бо ви думаєте, що в них маєте вічне життя, вони ж свідчать про Мене!"},
{40, "40 Та до Мене прийти ви не хочете, щоб мати життя."},
{41, "41 Від людей не приймаю Я слави,"},
{42, "42 але вас Я пізнав, що любови до Бога в собі ви не маєте."},
{43, "43 Я прийшов у Ймення Свого Отця, та Мене не приймаєте ви. Коли ж прийде інший у ймення своє, того приймете ви."},
{44, "44 Як ви можете вірувати, коли славу один від одного приймаєте, а слави тієї, що від Бога Єдиного, не прагнете ви?"},
{45, "45 Не думайте, що Я перед Отцем буду вас винуватити, є, хто вас винуватити буде, Мойсей, що на нього надієтесь ви!"},
{46, "46 Коли б ви Мойсеєві вірили, то й Мені б ви повірили, бо про Мене писав він."},
{47, "47 Якщо писанням його ви не вірите, то як віри поймете словам Моїм?"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view6() {
struct uk6 poems[] = {
{1, "1 Після того Ісус перейшов на той бік Галілейського чи Тіверіядського моря."},
{2, "2 А за Ним ішла безліч народу, бо бачили чуда Його, що чинив над недужими."},
{3, "3 Ісус же на гору зійшов, і сидів там зо Своїми учнями."},
{4, "4 Наближалася ж Пасха, свято юдейське."},
{5, "5 А Ісус, звівши очі Свої та побачивши, яка безліч народу до Нього йде, говорить Пилипові: Де ми купимо хліба, щоб вони поживились?"},
{6, "6 Він же це говорив, його випробовуючи, бо знав Сам, що Він має робити."},
{7, "7 Пилип Йому відповідь дав: І за двісті динаріїв їм хліба не стане, щоб кожен із них бодай трохи дістав."},
{8, "8 Говорить до Нього Андрій, один з учнів Його, брат Симона Петра:"},
{9, "9 Є тут хлопчина один, що має п'ять ячних хлібів та дві рибі, але що то на безліч таку!"},
{10, "10 А Ісус відказав: Скажіть людям сідати! А була на тім місці велика трава. І засіло чоловіка числом із п'ять тисяч."},
{11, "11 А Ісус узяв хліби, і, подяку вчинивши, роздав тим, хто сидів. Так само і з риб, скільки хотіли вони."},
{12, "12 І, як наїлись вони, Він говорить до учнів Своїх: Позбирайте куски позосталі, щоб ніщо не загинуло."},
{13, "13 І зібрали вони. І дванадцять повних кошів наклали кусків, що лишились їдцям із п'яти ячних хлібів."},
{14, "14 А люди, що бачили чудо, яке Ісус учинив, гомоніли: Це Той справді Пророк, що повинен прибути на світ!"},
{15, "15 Спостерігши ж Ісус, що вони мають замір прийти та забрати Його, щоб настановити царем, знов на гору пішов Сам один."},
{16, "16 А як вечір настав, то зійшли Його учні над море."},
{17, "17 І, ввійшовши до човна, на другий бік моря вони попливли, до Капернауму. І темрява вже наступила була, а Ісус ще до них не приходив."},
{18, "18 Від великого ж вітру, що віяв, хвилювалося море."},
{19, "19 Як вони ж пропливли стадій із двадцять п'ять або з тридцять, то Ісуса побачили, що йде Він по морю, і до човна зближається, і їх страх обгорнув..."},
{20, "20 Він же каже до них: Це Я, не лякайтесь!"},
{21, "21 І хотіли вони взяти до човна Його; та човен зараз пристав до землі, до якої пливли."},
{22, "22 А наступного дня той народ, що на тім боці моря стояв, побачив, що там іншого човна, крім одного того, що до нього ввійшли були учні Його, не було, і що до човна не входив Ісус із Своїми учнями, але відпливли самі учні."},
{23, "23 А тим часом із Тіверіяди припливли човни інші близько до місця того, де вони їли хліб, як Господь учинив був подяку."},
{24, "24 Отож, як побачили люди, що Ісуса та учнів Його там нема, то в човни посідали самі й прибули до Капернауму, і шукали Ісуса."},
{25, "25 І, на тім боці моря знайшовши Його, сказали Йому: Коли Ти прибув сюди, Учителю?"},
{26, "26 Відповів їм Ісус і сказав: Поправді, поправді кажу вам: Мене не тому ви шукаєте, що бачили чуда, а що їли з хлібів і наситились."},
{27, "27 Пильнуйте не про поживу, що гине, але про поживу, що зостається на вічне життя, яку дасть нам Син Людський, бо відзначив Його Бог Отець."},
{28, "28 Сказали ж до Нього вони: Що ми маємо почати, щоб робити діла Божі?"},
{29, "29 Ісус відповів і сказав їм: Оце діло Боже, щоб у Того ви вірували, Кого Він послав."},
{30, "30 А вони відказали Йому: Яке ж знамено Ти чиниш, щоб побачили ми й поняли Тобі віри? Що Ти робиш?"},
{31, "31 Наші отці їли манну в пустині, як написано: Хліб із неба їм дав на поживу."},
{32, "32 А Ісус їм сказав: Поправді, поправді кажу вам: Не Мойсей хліб із неба вам дав, Мій Отець дає вам хліб правдивий із неба."},
{33, "33 Бо хліб Божий є Той, Хто сходить із неба й дає життя світові."},
{34, "34 А вони відказали до Нього: Давай, Господи, хліба такого нам завжди!"},
{35, "35 Ісус же сказав їм: Я хліб життя. Хто до Мене приходить, не голодуватиме він, а хто вірує в Мене, ніколи не прагнутиме."},
{36, "36 Але Я вам сказав, що Мене хоч ви й бачили, та не віруєте."},
{37, "37 Усе прийде до Мене, що Отець дає Мені, а того, хто до Мене приходить, Я не вижену геть."},
{38, "38 Бо Я з неба зійшов не на те, щоб волю чинити Свою, але волю Того, Хто послав Мене."},
{39, "39 Оце ж воля Того, Хто послав Мене, щоб з усього, що дав Мені Він, Я нічого не стратив, але воскресив те останнього дня."},
{40, "40 Оце ж воля Мого Отця, щоб усякий, хто Сина бачить та вірує в Нього, мав вічне життя, і того воскрешу Я останнього дня."},
{41, "41 Тоді стали юдеї ремствувати на Нього, що сказав: Я той хліб, що з неба зійшов."},
{42, "42 І казали вони: хіба Він не Ісус, син Йосипів, що ми знаємо батька та матір Його? Як же Він каже: Я з неба зійшов?"},
{43, "43 А Ісус відповів і промовив до них: Не ремствуйте ви між собою!"},
{44, "44 Ніхто бо не може до Мене прийти, як Отець, що послав Мене, не притягне його, і того воскрешу Я останнього дня."},
{45, "45 У Пророків написано: І всі будуть від Бога навчені. Кожен, хто від Бога почув і навчився, приходить до Мене."},
{46, "46 Це не значить, щоб хтось Отця бачив, тільки Той Отця бачив, Хто походить від Бога."},
{47, "47 Поправді, поправді кажу Вам: Хто вірує в Мене, життя вічне той має."},
{48, "48 Я хліб життя!"},
{49, "49 Отці ваші в пустині їли манну, і померли."},
{50, "50 То є хліб, Який сходить із неба, щоб не вмер, хто Його споживає."},
{51, "51 Я хліб живий, що з неба зійшов: коли хто споживатиме хліб цей, той повік буде жити. А хліб, що дам Я, то є тіло Моє, яке Я за життя світові дам."},
{52, "52 Тоді між собою змагатися стали юдеї, говорячи: Як же Він може дати нам тіла спожити?"},
{53, "53 І сказав їм Ісус: Поправді, поправді кажу вам: Якщо ви споживати не будете тіла Сина Людського й пити не будете крови Його, то в собі ви не будете мати життя."},
{54, "54 Хто тіло Моє споживає та кров Мою п'є, той має вічне життя, і того воскрешу Я останнього дня."},
{55, "55 Бо тіло Моє то правдиво пожива, Моя ж кров то правдиво пиття."},
{56, "56 Хто тіло Моє споживає та кров Мою п'є, той в Мені перебуває, а Я в ньому."},
{57, "57 Як Живий Отець послав Мене, і живу Я Отцем, так і той, хто Мене споживає, і він житиме Мною."},
{58, "58 То є хліб, що з неба зійшов. Не як ваші отці їли манну й померли, хто цей хліб споживає, той жити буде повік!"},
{59, "59 Оце Він говорив, коли в Капернаумі навчав у синагозі."},
{60, "60 А багато-хто з учнів Його, як почули оце, гомоніли: Жорстока це мова! Хто слухати може її?"},
{61, "61 А Ісус, Сам у Собі знавши це, що учні Його на те ремствують, промовив до них: Чи оце вас спокушує?"},
{62, "62 А що ж, як побачите Людського Сина, що сходить туди, де перше Він був?"},
{63, "63 То дух, що оживлює, тіло ж не помагає нічого. Слова, що їх Я говорив вам, то дух і життя."},
{64, "64 Але є дехто з вас, хто не вірує. Бо Ісус знав спочатку, хто ті, хто не вірує, і хто видасть Його."},
{65, "65 І сказав Він: Я тому й говорив вам, що до Мене прибути не може ніхто, як не буде йому від Отця дане те."},
{66, "66 Із того часу відпали багато-хто з учнів Його, і не ходили вже з Ним."},
{67, "67 І сказав Ісус Дванадцятьом: Чи не хочете й ви відійти?"},
{68, "68 Відповів Йому Симон Петро: До кого ми підемо, Господи? Ти маєш слова життя вічного."},
{69, "69 Ми ж увірували та пізнали, що Ти Христос, Син Бога Живого!"},
{70, "70 Відповів їм Ісус: Чи не Дванадцятьох Я вас вибрав? Та один із вас диявол..."},
{71, "71 Це сказав Він про Юду, сина Симонового, Іскаріота. Бо цей мав Його видати, хоч він був один із Дванадцятьох."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view7() {
struct uk7 poems[] = {
{1, "1 Після цього Ісус ходив по Галілеї, не хотів бо ходити по Юдеї, бо юдеї шукали нагоди, щоб убити Його."},
{2, "2 А надходило свято юдейське Кучки."},
{3, "3 І сказали до Нього брати Його: Піди звідси, і йди до Юдеї, щоб і учні Твої побачили вчинки Твої, що Ти робиш."},
{4, "4 Тайкома бо не робить нічого ніхто, але сам прагне бути відомий. Коли Ти таке чиниш, то з'яви Себе світові."},
{5, "5 Бо не вірували в Нього навіть брати Його!"},
{6, "6 А Ісус промовляє до них: Не настав ще Мій час, але завжди готовий час ваш."},
{7, "7 Вас ненавидіти світ не може, а Мене він ненавидить, бо Я свідчу про нього, що діла його злі."},
{8, "8 Ідіть на це свято, Я ж іще не піду на це свято, бо не виповнився ще Мій час."},
{9, "9 Це сказавши до них, Він зоставсь у Галілеї."},
{10, "10 Коли ж вийшли на свято брати Його, тоді й Сам Він пішов, не відкрито, але ніби потай."},
{11, "11 А юдеї за свята шукали Його та питали: Де Він?"},
{12, "12 І поголоска велика про Нього в народі була. Одні говорили: Він добрий, а інші казали: Ні, Він зводить з дороги народ..."},
{13, "13 Та відкрито про Нього ніхто не казав, бо боялись юдеїв."},
{14, "14 У половині вже свята Ісус у храм увійшов і навчав."},
{15, "15 І дивувались юдеї й казали: Як Він знає Писання, не вчившись?"},
{16, "16 Відповів їм Ісус і сказав: Наука Моя не Моя, а Того, Хто послав Мене."},
{17, "17 Коли хоче хто волю чинити Його, той довідається про науку, чи від Бога вона, чи від Себе Самого кажу Я."},
{18, "18 Хто говорить від себе самого, той власної слави шукає, а Хто слави шукає Того, Хто послав Його, Той правдивий, і в Ньому неправди нема."},
{19, "19 Чи ж Закона вам дав не Мойсей? Та ніхто з вас Закона того не виконує. Нащо хочете вбити Мене?"},
{20, "20 Народ відповів: Чи Ти демона маєш? Хто Тебе хоче вбити?"},
{21, "21 Ісус відповів і сказав їм: Одне діло зробив Я, і всі ви дивуєтесь."},
{22, "22 Через це Мойсей дав обрізання вам, не тому, що воно від Мойсея, але від отців, та ви й у суботу обрізуєте чоловіка."},
{23, "23 Коли ж чоловік у суботу приймає обрізання, щоб Закону Мойсеєвого не порушити, чого ж ремствуєте ви на Мене, що Я всю людину в суботу вздоровив?"},
{24, "24 Не судіть за обличчям, але суд справедливий чиніть!"},
{25, "25 Дехто ж з єрусалимлян казали: Хіба це не Той, що Його шукають убити?"},
{26, "26 Бо говорить відкрито ось Він, і нічого не кажуть Йому. Чи то справді дізналися старші, що Він дійсно Христос?"},
{27, "27 Та ми знаєм Цього, звідки Він. Про Христа ж, коли прийде, ніхто знати не буде, звідки Він."},
{28, "28 І скликнув у храмі Ісус, навчаючи й кажучи: І Мене знаєте ви, і знаєте, звідки Я. А Я не прийшов Сам від Себе; правдивий же Той, Хто послав Мене, що Його ви не знаєте."},
{29, "29 Я знаю Його, Я бо від Нього, і послав Мене Він!"},
{30, "30 Тож шукали вони, щоб схопити Його, та ніхто не наклав рук на Нього, бо то ще не настала година Його."},
{31, "31 А багато з народу в Нього ввірували та казали: Коли прийде Христос, чи ж Він чуда чинитиме більші, як чинить Оцей?"},
{32, "32 Фарисеї прочули такі поголоски про Нього в народі. Тоді первосвященики та фарисеї послали свою службу, щоб схопити Його."},
{33, "33 Ісус же сказав: Ще недовго побуду Я з вами, та й до Того піду, Хто послав Мене."},
{34, "34 Ви будете шукати Мене, і не знайдете; а туди, де Я є, ви прибути не можете..."},
{35, "35 Тоді говорили юдеї між собою: Куди це Він хоче йти, що не знайдемо Його? Чи не хоче йти до виселенців між греки, та й греків навчати?"},
{36, "36 Що за слово, яке Він сказав: Ви будете шукати Мене, і не знайдете; а туди, де Я є, ви прибути не можете?"},
{37, "37 А останнього великого дня свята Ісус стояв і кликав, говорячи: Коли прагне хто з вас нехай прийде до Мене та й п'є!"},
{38, "38 Хто вірує в Мене, як каже Писання, то ріки живої води потечуть із утроби його."},
{39, "39 Це ж сказав Він про Духа, що мали прийняти Його, хто ввірував у Нього. Не було бо ще Духа на них, не був бо Ісус ще прославлений."},
{40, "40 А багато з народу, почувши слова ті, казали: Він справді пророк!"},
{41, "41 Інші казали: Він Христос. А ще інші казали: Хіба прийде Христос із Галілеї?"},
{42, "42 Чи ж не каже Писання, що Христос прийде з роду Давидового, і з села Віфлеєму, звідкіля був Давид?"},
{43, "43 Так повстала незгода в народі з-за Нього."},
{44, "44 А декотрі з них мали замір схопити Його, та ніхто не поклав рук на Нього."},
{45, "45 І вернулася служба до первосвящеників та фарисеїв, а ті їх запитали: Чому не привели ви Його?"},
{46, "46 Відказала та служба: Чоловік ще ніколи так не промовляв, як Оцей Чоловік..."},
{47, "47 А їм відповіли фарисеї: Чи й вас із дороги не зведено?"},
{48, "48 Хіба хто з старших або з фарисеїв увірував у Нього?"},
{49, "49 Та проклятий народ, що не знає Закону!"},
{50, "50 Говорить до них Никодим, що приходив до Нього вночі, і що був один із них:"},
{51, "51 Хіба судить Закон наш людину, як перше її не вислухає, і не дізнається, що вона робить?"},
{52, "52 Йому відповіли та сказали вони: Чи й ти не з Галілеї? Досліди та побач, що не прийде Пророк із Галілеї."},
{53, "53 І до дому свого пішов кожен."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view8() {
struct uk8 poems[] = {
{1, "1 Ісус же на гору Оливну пішов."},
{2, "2 А над ранком прийшов знов у храм, і всі люди збігались до Нього. А Він сів і навчав їх."},
{3, "3 І ось книжники та фарисеї приводять до Нього в перелюбі схоплену жінку, і посередині ставлять її,"},
{4, "4 та й говорять Йому: Оцю жінку, Учителю, зловлено на гарячому вчинку перелюбу..."},
{5, "5 Мойсей же в Законі звелів нам таких побивати камінням. А Ти що говориш?"},
{6, "6 Це ж казали вони, Його спокушуючи, та щоб мати на Нього оскарження. А Ісус, нахилившись додолу, по землі писав пальцем..."},
{7, "7 А коли ті не переставали питати Його, Він підвівся й промовив до них: Хто з вас без гріха, нехай перший на неї той каменем кине!..."},
{8, "8 І Він знов нахилився додолу, і писав по землі..."},
{9, "9 А вони, це почувши й сумлінням докорені, стали один по одному виходити, почавши з найстарших та аж до останніх. І зоставсь Сам Ісус і та жінка, що стояла всередині..."},
{10, "10 І підвівся Ісус, і нікого, крім жінки, не бачивши, промовив до неї: Де ж ті, жінко, що тебе оскаржали? Чи ніхто тебе не засудив?"},
{11, "11 А вона відказала: Ніхто, Господи... І сказав їй Ісус: Не засуджую й Я тебе. Іди собі, але більш не гріши!"},
{12, "12 І знову Ісус промовляв до них, кажучи: Я Світло для світу. Хто йде вслід за Мною, не буде ходити у темряві той, але матиме світло життя."},
{13, "13 Фарисеї ж Йому відказали: Ти Сам свідчиш про Себе, тим свідоцтво Твоє неправдиве."},
{14, "14 Відповів і сказав їм Ісус: Хоч і свідчу про Себе Я Сам, та правдиве свідоцтво Моє, бо Я знаю, звідкіля Я прийшов і куди Я йду. Ви ж не відаєте, відкіля Я приходжу, і куди Я йду."},
{15, "15 Ви за тілом судите, Я не суджу нікого."},
{16, "16 А коли Я суджу, то правдивий Мій суд, бо не Сам Я, а Я та Отець, що послав Він Мене!"},
{17, "17 Та й у вашім Законі написано, що свідчення двох чоловіків правдиве."},
{18, "18 Я Сам свідчу про Себе Самого, і свідчить про Мене Отець, що послав Він Мене."},
{19, "19 І сказали до Нього вони: Де Отець Твій? Ісус відповів: Не знаєте ви ні Мене, ні Мого Отця. Якби знали Мене, то й Отця Мого знали б."},
{20, "20 Ці слова Він казав при скарбниці, у храмі навчаючи. І ніхто не схопив Його, бо то ще не настала година Його..."},
{21, "21 І сказав Він їм знову: Я відходжу, ви ж шукати Мене будете, і помрете в гріху своїм. Куди Я йду, туди ви прибути не можете..."},
{22, "22 А юдеї казали: Чи не вб'є Він Сам Себе, коли каже: Куди Я йду, туди ви прибути не можете?"},
{23, "23 І сказав Він до них: Ви від долу, Я звисока, і ви зо світу цього, Я не з цього світу."},
{24, "24 Тому Я сказав вам, що помрете в своїх гріхах. Бо коли не ввіруєте, що то Я, то помрете в своїх гріхах."},
{25, "25 А вони запитали Його: Хто Ти такий? І Ісус відказав їм: Той, Хто спочатку, як і говорю Я до вас."},
{26, "26 Я маю багато про вас говорити й судити; правдивий же Той, Хто послав Мене, і Я світові те говорю, що від Нього почув."},
{27, "27 Але не зрозуміли вони, що то Він про Отця говорив їм."},
{28, "28 Тож Ісус їм сказав: Коли ви підіймете Людського Сина, тоді зрозумієте, що то Я, і що Сам Я від Себе нічого не дію, але те говорю, як Отець Мій Мене був навчив."},
{29, "29 А Той, Хто послав Мене, перебуває зо Мною; Отець не зоставив Самого Мене, бо Я завжди чиню, що Йому до вподоби."},
{30, "30 Коли Він говорив це, то багато-хто в Нього увірували."},
{31, "31 Тож промовив Ісус до юдеїв, що в Нього ввірували: Як у слові Моїм позостанетеся, тоді справді Моїми учнями будете,"},
{32, "32 і пізнаєте правду, а правда вас вільними зробить!"},
{33, "33 Вони відказали Йому: Авраамів ми рід, і нічиїми невільниками не були ми ніколи. То як же Ти кажеш: Ви станете вільні?"},
{34, "34 Відповів їм Ісус: Поправді, поправді кажу вам, що кожен, хто чинить гріх, той раб гріха."},
{35, "35 І не зостається раб у домі повік, але Син зостається повік."},
{36, "36 Коли Син отже зробить вас вільними, то справді ви будете вільні."},
{37, "37 Знаю Я, що ви рід Авраамів, але хочете смерть заподіяти Мені, бо наука Моя не вміщається в вас."},
{38, "38 Я те говорю, що Я бачив в Отця, та й ви робите те, що ви бачили в батька свого."},
{39, "39 Сказали вони Йому в відповідь: Наш отець Авраам. Відказав їм Ісус: Коли б ви Авраамові діти були, то чинили б діла Авраамові."},
{40, "40 А тепер ось ви хочете вбити Мене, Чоловіка, що вам казав правду, яку чув Я від Бога. Цього Авраам не робив."},
{41, "41 Ви робите діла батька свого. Вони ж відказали Йому: Не родилися ми від перелюбу, одного ми маєм Отця то Бога."},
{42, "42 А Ісус їм сказав: Якби Бог був Отець ваш, ви б любили Мене, бо від Бога Я вийшов і прийшов, не від Себе ж Самого прийшов Я, а Мене Він послав."},
{43, "43 Чому мови Моєї ви не розумієте? Бо не можете чути ви слова Мого."},
{44, "44 Ваш батько диявол, і пожадливості батька свого ви виконувати хочете. Він був душогуб споконвіку, і в правді не встояв, бо правди нема в нім. Як говорить неправду, то говорить зо свого, бо він неправдомовець і батько неправді."},
{45, "45 А Мені ви не вірите, бо Я правду кажу."},
{46, "46 Хто з вас може Мені докорити за гріх? Коли ж правду кажу, чом Мені ви не вірите?"},
{47, "47 Хто від Бога, той слухає Божі слова; через те ви не слухаєте, що ви не від Бога."},
{48, "48 Відізвались юдеї й сказали Йому: Чи ж не добре ми кажемо, що Ти самарянин і демона маєш?"},
{49, "49 Ісус відповів: Не маю Я демона, та шаную Свого Отця, ви ж Мене зневажаєте."},
{50, "50 Не шукаю ж Я власної слави, є Такий, Хто шукає та судить."},
{51, "51 Поправді, поправді кажу вам: Хто слово Моє берегтиме, не побачить той смерти повік!"},
{52, "52 І сказали до Нього юдеї: Тепер ми дізнались, що демона маєш: умер Авраам і пророки, а Ти кажеш: Хто науку Мою берегтиме, не скуштує той смерти повік."},
{53, "53 Чи ж Ти більший, аніж отець наш Авраам, що помер? Та повмирали й пророки. Ким Ти робиш Самого Себе?"},
{54, "54 Ісус відповів: Як Я славлю Самого Себе, то ніщо Моя слава. Мене прославляє Отець Мій, про Якого ви кажете, що Він Бог ваш."},
{55, "55 І ви не пізнали Його, а Я знаю Його. А коли Я скажу, що не знаю Його, буду неправдомовець, подібний до вас. Та Я знаю Його, і слово Його зберігаю."},
{56, "56 Отець ваш Авраам прагнув із радістю, щоб побачити день Мій, і він бачив, і тішився."},
{57, "57 А юдеї ж до Нього сказали: Ти й п'ятидесяти років не маєш іще, і Авраама Ти бачив?"},
{58, "58 Ісус їм відказав: Поправді, поправді кажу вам: Перш, ніж був Авраам, Я є."},
{59, "59 І схопили каміння вони, щоб кинути на Нього. Та сховався Ісус, і з храму пішов."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view9() {
struct uk9 poems[] = {
{1, "1 А коли Він проходив, побачив чоловіка, що сліпим був з народження."},
{2, "2 І спитали Його учні Його, говорячи: Учителю, хто згрішив: чи він сам, чи батьки його, що сліпим він родився?"},
{3, "3 Ісус відповів: Не згрішив ані він, ні батьки його, а щоб діла Божі з'явились на ньому."},
{4, "4 Ми мусимо виконувати діла Того, Хто послав Мене, аж поки є день. Надходить он ніч, коли жаден нічого не зможе виконувати."},
{5, "5 Доки Я в світі, Я Світло для світу."},
{6, "6 Промовивши це, Він сплюнув на землю, і з слини грязиво зробив, і очі сліпому помазав грязивом,"},
{7, "7 і до нього промовив: Піди, умийся в ставку Сілоам визначає це Посланий. Тож пішов той і вмився, і вернувся видющим..."},
{8, "8 А сусіди та ті, що бачили перше його, як був він сліпий, говорили: Чи ж не той це, що сидів та просив?"},
{9, "9 Говорили одні, що це він, а інші казали: Ні, подібний до нього. А він відказав: Це я!"},
{10, "10 І питали його: Як же очі відкрились тобі?"},
{11, "11 А той оповідав: Чоловік, що Його звуть Ісусом, грязиво зробив, і очі помазав мені, і до мене сказав: Піди в Сілоам та й умийся. Я ж пішов та й умився, і став бачити."},
{12, "12 І сказали до нього: Де Він? Відказує той: Я не знаю."},
{13, "13 Ведуть тоді до фарисеїв того, що був перше незрячий."},
{14, "14 А була то субота, як грязиво Ісус учинив і відкрив йому очі."},
{15, "15 І знов запитали його й фарисеї, як видющим він став. А він розповів їм: Грязиво поклав Він на очі мені, а я вмився, та й бачу."},
{16, "16 Тоді деякі з фарисеїв казали: Не від Бога Оцей Чоловік, бо суботи не держить. А інші казали: Як же чуда такі може грішна людина чинити? І незгода між ними була."},
{17, "17 Тому знову говорять сліпому: Що ти кажеш про Нього, коли очі відкрив Він тобі? А той відказав: Він Пророк!"},
{18, "18 Юдеї проте йому не повірили, що незрячим він був і прозрів, аж поки не покликано батьків того прозрілого."},
{19, "19 І запитали їх, кажучи: Чи ваш оце син, про якого ви кажете, ніби родився сліпим? Як же він тепер бачить?"},
{20, "20 А батьки його відповіли та сказали: Ми знаєм, що цей то наш син, і що він народився сліпим."},
{21, "21 Але як тепер бачить, не знаємо, або хто йому очі відкрив, ми не відаємо. Поспитайте його, він дорослий, хай сам скаже про себе..."},
{22, "22 Таке говорили батьки його, бо боялись юдеїв: юдеї бо вже були змовились, як хто за Христа Його визнає, щоб той був відлучений від синагоги."},
{23, "23 Ось тому говорили батьки його: Він дорослий, його поспитайте."},
{24, "24 І покликали вдруге того чоловіка, що був сліпим, і сказали йому: Віддай хвалу Богові. Ми знаємо, що грішний Отой Чоловік."},
{25, "25 Але він відповів: Чи Він грішний не знаю. Одне тільки знаю, що я був сліпим, а тепер бачу!..."},
{26, "26 І спитали його: Що тобі Він зробив? Як відкрив тобі очі?"},
{27, "27 Відповів він до них: Я вже вам говорив, та не слухали ви. Що бажаєте знову почути? Може й ви Його учнями хочете стати?"},
{28, "28 А вони його вилаяли та й сказали: То ти Його учень, а ми учні Мойсеєві."},
{29, "29 Ми знаємо, що Бог говорив до Мойсея, звідки ж узявся Оцей, ми не відаємо."},
{30, "30 Відповів чоловік і сказав їм: То ж воно й дивно, що не знаєте ви, звідки Він, а Він мені очі відкрив!"},
{31, "31 Та ми знаємо, що грішників Бог не послухає; хто ж богобійний, і виконує волю Його, того слухає Він."},
{32, "32 Відвіку не чувано, щоб хто очі відкрив був сліпому з народження."},
{33, "33 Коли б не від Бога був Цей, Він нічого не міг би чинити."},
{34, "34 Вони відповіли та й сказали йому: Ти ввесь у гріхах народився, і чи тобі нас учити? І геть його вигнали."},
{35, "35 Дізнався Ісус, що вони того вигнали геть, і, знайшовши його, запитав: Чи віруєш ти в Сина Божого?"},
{36, "36 Відповів той, говорячи: Хто ж то, Пане, Такий, щоб я вірував у Нього?"},
{37, "37 Промовив до нього Ісус: І ти бачив Його, і Той, Хто говорить з тобою то Він!..."},
{38, "38 А він відказав: Я вірую, Господи! І вклонився Йому."},
{39, "39 І промовив Ісус: На суд Я прийшов у цей світ, щоб бачили темні, а видющі щоб стали незрячі."},
{40, "40 І почули це деякі з тих фарисеїв, що були з Ним, та й сказали Йому: Чи ж і ми невидющі?"},
{41, "41 Відказав їм Ісус: Якби ви невидющі були, то не мали б гріха; а тепер ви говорите: Бачимо, то й ваш гріх зостається при вас!"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view10() {
struct uk10 poems[] = {
{1, "1 Поправді, поправді кажу вам: Хто не входить дверима в кошару, але перелазить деінде, той злодій і розбійник."},
{2, "2 А хто входить дверима, той вівцям пастух."},
{3, "3 Воротар відчиняє йому, і його голосу слухають вівці; і свої вівці він кличе по йменню, і випроваджує їх."},
{4, "4 А як вижене всі свої вівці, він іде перед ними, і вівці слідом за ним ідуть, бо знають голос його."},
{5, "5 За чужим же не підуть вони, а будуть утікати від нього, бо не знають вони чужого голосу."},
{6, "6 Оцю притчу повів їм Ісус, але не зрозуміли вони, про що їм говорив."},
{7, "7 І знову промовив Ісус: Поправді, поправді кажу вам, що Я двері вівцям."},
{8, "8 Усі, скільки їх перше Мене приходило, то злодії й розбійники, але вівці не слухали їх."},
{9, "9 Я двері: коли через Мене хто ввійде, спасеться, і той ввійде та вийде, і пасовисько знайде."},
{10, "10 Злодій тільки на те закрадається, щоб красти й убивати та нищити. Я прийшов, щоб ви мали життя, і подостатком щоб мали."},
{11, "11 Я Пастир Добрий! Пастир добрий кладе життя власне за вівці."},
{12, "12 А наймит, і той, хто не вівчар, кому вівці не свої, коли бачить, що вовк наближається, то кидає вівці й тікає, а вовк їх хапає й полошить."},
{13, "13 А наймит утікає тому, що він наймит, і не дбає про вівці."},
{14, "14 Я Пастир Добрий, і знаю Своїх, і Свої Мене знають."},
{15, "15 Як Отець Мене знає, так і Я Отця знаю, і власне життя Я за вівці кладу."},
{16, "16 Також маю Я інших овець, які не з цієї кошари, Я повинен і їх припровадити. І Мій голос почують вони, і буде отара одна й Один Пастир!"},
{17, "17 Через те Отець любить Мене, що Я власне життя віддаю, щоб ізнову прийняти його."},
{18, "18 Ніхто в Мене його не бере, але Я Сам від Себе кладу його. Маю владу віддати його, і маю владу прийняти його знову, Я цю заповідь взяв від Свого Отця."},
{19, "19 З-за цих слів між юдеями знову незгода знялася."},
{20, "20 І багато-хто з них говорили: Він демона має, і несамовитий. Чого слухаєте ви Його?"},
{21, "21 Інші казали: Ці слова не того, хто демона має. Хіба демон може очі сліпим відкривати?..."},
{22, "22 Було тоді свято Відновлення в Єрусалимі. Стояла зима."},
{23, "23 А Ісус у храмі ходив, у Соломоновім ґанку."},
{24, "24 Юдеї тоді обступили Його та й казали Йому: Доки будеш тримати в непевності нас? Якщо Ти Христос, то відкрито скажи нам!"},
{25, "25 Відповів їм Ісус: Я вам був сказав, та не вірите ви. Ті діла,що чиню їх у Ймення Свого Отця, вони свідчать про Мене."},
{26, "26 Та не вірите ви, не з Моїх бо овець ви."},
{27, "27 Мого голосу слухають вівці Мої, і знаю Я їх, і за Мною слідком вони йдуть."},
{28, "28 І Я життя вічне даю їм, і вони не загинуть повік, і ніхто їх не вихопить із Моєї руки."},
{29, "29 Мій Отець, що дав їх Мені, Він більший за всіх, і вихопити ніхто їх не може Отцеві з руки."},
{30, "30 Я й Отець Ми одне!"},
{31, "31 Знов каміння схопили юдеї, щоб укаменувати Його."},
{32, "32 Відповів їм Ісус: Від Отця показав Я вам добрих учинків багато, за котрий же з тих учинків хочете Мене каменувати?"},
{33, "33 Юдеї Йому відказали: Не за добрий учинок хочемо Тебе вкаменувати, а за богозневагу, бо Ти, бувши людиною, за Бога Себе видаєш..."},
{34, "34 Відповів їм Ісус: Хіба не написано в вашім Законі: Я сказав: ви боги?"},
{35, "35 Коли тих Він богами назвав, що до них слово Боже було, а Писання не може порушене бути,"},
{36, "36 то Тому, що Отець освятив і послав Його в світ, закидаєте ви: Зневажаєш Ти Бога, через те, що сказав Я: Я Син Божий?"},
{37, "37 Коли Я не чиню діл Свого Отця, то не вірте Мені."},
{38, "38 А коли Я чиню, то хоч ви Мені віри й не ймете, повірте ділам, щоб пізнали й повірили ви, що Отець у Мені, а Я ув Отці!"},
{39, "39 Тоді знову шукали вони, щоб схопити Його, але вийшов із рук їхніх Він."},
{40, "40 І Він знову на той бік Йордану пішов, на те місце, де Іван найперше христив, та й там перебував."},
{41, "41 І багато до Нього приходили та говорили, що хоч жадного чуда Іван не вчинив, але все, що про Нього Іван говорив, правдиве було."},
{42, "42 І багато-хто ввірували в Нього там."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view11() {
struct uk11 poems[] = {
{1, "1 Був же хворий один, Лазар у Віфанії, із села Марії й сестри її Марти."},
{2, "2 А Марія, що брат її Лазар був хворий, була та, що помазала Господа миром, і волоссям своїм Йому ноги обтерла."},
{3, "3 Тоді сестри послали до Нього, говорячи: Ось нездужає, Господи, той, що кохаєш його!..."},
{4, "4 Як почув же Ісус, то промовив: Не на смерть ця недуга, а на Божу славу, щоб Син Божий прославився нею."},
{5, "5 А Ісус любив Марту, і сестру її, і Лазаря."},
{6, "6 А коли Він почув, що нездужає той, то зостався два дні на тім місці, де був."},
{7, "7 Після ж того говорить до учнів: Ходімо знову в Юдею."},
{8, "8 Йому учні сказали: Учителю, таж допіру юдеї хотіли камінням побити Тебе, а Ти знов туди підеш?"},
{9, "9 Ісус відповів: Хіба дня не дванадцять годин? Як хто ходить за дня, не спіткнеться, цьогосвітнє бо світло він бачить."},
{10, "10 А хто ходить нічної пори, той спіткнеться, бо немає в нім світла."},
{11, "11 Оце Він сказав, а по тому говорить до них: Друг наш Лазар заснув, та піду розбудити Його."},
{12, "12 А учні сказали Йому: Як заснув, то він, Господи, видужає."},
{13, "13 Та про смерть його мовив Ісус, вони ж думали, що про сонний спочинок Він каже."},
{14, "14 Тоді просто сказав їм Ісус: Умер Лазар."},
{15, "15 І Я тішусь за вас, що там Я не був, щоб повірили ви. Та ходімо до нього."},
{16, "16 Сказав же Хома, називаний Близнюк, до співучнів: Ходімо й ми, щоб із Ним повмирати."},
{17, "17 Як прибув же Ісус, то знайшов, що чотири вже дні той у гробі."},
{18, "18 А Віфанія поблизу Єрусалиму була, яких стадій з п'ятнадцять."},
{19, "19 І багато з юдеїв до Марти й Марії прийшли, щоб за брата розважити їх."},
{20, "20 Тоді Марта, почувши, що надходить Ісус, побігла зустріти Його, Марія ж удома сиділа."},
{21, "21 І Марта сказала Ісусові: Коли б, Господи, був Ти отут, то не вмер би мій брат..."},
{22, "22 Та й тепер, знаю я, що чого тільки в Бога попросиш, то дасть Тобі Бог!"},
{23, "23 Промовляє до неї Ісус: Воскресне твій брат!"},
{24, "24 Відказує Марта Йому: Знаю, що в воскресення останнього дня він воскресне."},
{25, "25 Промовив до неї Ісус: Я воскресення й життя. Хто вірує в Мене, хоч і вмре, буде жити."},
{26, "26 І кожен, хто живе та хто вірує в Мене, повіки не вмре. Чи ти віруєш в це?"},
{27, "27 Вона каже Йому: Так, Господи! Я вірую, що Ти Христос, Син Божий, що має прийти на цей світ."},
{28, "28 І промовивши це, відійшла, та й покликала нишком Марію, сестру свою, кажучи: Учитель тут, і Він кличе тебе!"},
{29, "29 А та, як зачула, квапливо встала й до Нього пішла."},
{30, "30 А Ісус не ввійшов був іще до села, а знаходивсь на місці, де Марта зустріла Його."},
{31, "31 Юдеї тоді, що були з нею в домі й її розважали, як побачили, що Марія квапливо встала й побігла, подалися за нею, гадаючи, що до гробу пішла вона, плакати там."},
{32, "32 Як Марія ж прийшла туди, де був Ісус, і Його вгледіла, то припала до ніг Йому та й говорила до Нього: Коли б, Господи, був Ти отут, то не вмер би мій брат!"},
{33, "33 А Ісус, як побачив, що плаче вона, і плачуть юдеї, що з нею прийшли, то в дусі розжалобився та й зворушився Сам,"},
{34, "34 і сказав: Де його ви поклали? Говорять Йому: Іди, Господи, та подивися!"},
{35, "35 І закапали сльози Ісусові..."},
{36, "36 А юдеї казали: Дивись, як кохав Він його!"},
{37, "37 А з них дехто сказали: Чи не міг же зробити Отой, Хто очі сліпому відкрив, щоб і цей не помер?"},
{38, "38 Ісус же розжалобивсь знову в Собі, і до гробу прийшов. Була ж то печера, і камінь на ній налягав."},
{39, "39 Промовляє Ісус: Відваліть цього каменя! Сестра вмерлого Марта говорить до Нього: Уже, Господи, чути, бо чотири вже дні він у гробі..."},
{40, "40 Ісус каже до неї: Чи тобі не казав Я, що як будеш ти вірувати, славу Божу побачиш?"},
{41, "41 І зняли тоді каменя. А Ісус ізвів очі до неба й промовив: Отче, дяку приношу Тобі, що Мене Ти почув."},
{42, "42 Та Я знаю, що Ти завжди почуєш Мене, але ради народу, що довкола стоїть, Я сказав, щоб увірували, що послав Ти Мене."},
{43, "43 І, промовивши це, Він скричав гучним голосом: Лазарю, вийди сюди!"},
{44, "44 І вийшов померлий, по руках і ногах обв'язаний пасами, а обличчя у нього було перев'язане хусткою... Ісус каже до них: Розв'яжіть його та й пустіть, щоб ходив..."},
{45, "45 І багато з юдеїв, що посходилися до Марії, та бачили те, що Він учинив, у Нього ввірували."},
{46, "46 А деякі з них пішли до фарисеїв, і їм розповіли, що Ісус учинив."},
{47, "47 Тоді первосвященики та фарисеї скликали раду й казали: Що маємо робити, бо Цей Чоловік пребагато чуд чинить?"},
{48, "48 Якщо так позоставимо Його, то всі в Нього ввірують, і прийдуть римляни, та й візьмуть нам і Край, і народ!"},
{49, "49 А один із них, Кайяфа, що був первосвящеником року того, промовив до них: Ви нічого не знаєте,"},
{50, "50 і не поміркуєте, що краще для вас, щоб один чоловік прийняв смерть за людей, аніж щоб увесь народ мав загинути!"},
{51, "51 А того не сказав сам від себе, але, первосвящеником бувши в тім році, пророкував, що Ісус за народ мав умерти,"},
{52, "52 і не лише за народ, але й щоб сполучити в одне розпорошених Божих дітей."},
{53, "53 Отож, від того дня вони змовилися, щоб убити Його."},
{54, "54 І тому не ходив більш Ісус між юдеями явно, але звідти вдавсь до околиць поближче пустині, до міста, що зветься Єфрем, і тут залишався з Своїми учнями."},
{55, "55 Наближалася ж Пасха юдейська, і багато-хто з Краю вдались перед Пасхою в Єрусалим, щоб очистити себе."},
{56, "56 І шукали Ісуса вони, а в храмі стоявши, гомоніли один до одного: А як вам здається? Хіба Він не прийде на свято?"},
{57, "57 А первосвященики та фарисеї наказа дали: як дізнається хто, де Він перебуватиме, нехай донесе, щоб схопити Його."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view12() {
struct uk12 poems[] = {
{1, "1 Ісус же за шість день до Пасхи прибув до Віфанії, де жив Лазар, що його воскресив Ісус із мертвих."},
{2, "2 І для Нього вечерю там справили, а Марта прислуговувала. Був же й Лазар одним із тих, що до столу з Ним сіли."},
{3, "3 А Марія взяла літру мира, з найдорожчого нарду пахучого, і намастила Ісусові ноги, і волоссям своїм Йому ноги обтерла... І пахощі мира наповнили дім!"},
{4, "4 І говорить один з Його учнів, Юда Іскаріотський, що мав Його видати:"},
{5, "5 Чому мира оцього за триста динарів не продано, та й не роздано вбогим?"},
{6, "6 А це він сказав не тому, що про вбогих журився, а тому, що був злодій: він мав скриньку на гроші, і крав те, що вкидали."},
{7, "7 І промовив Ісус: Позостав її ти, це вона на день похорону заховала Мені..."},
{8, "8 Бо вбогих ви маєте завжди з собою, а Мене не постійно ви маєте!"},
{9, "9 А натовп великий юдеїв довідався, що Він там, та й поприходили не з-за Ісуса Самого, але щоб побачити й Лазаря, що його воскресив Він із мертвих."},
{10, "10 А первосвященики змовилися, щоб і Лазареві смерть заподіяти,"},
{11, "11 бо багато з юдеїв з-за нього відходили, та в Ісуса ввірували."},
{12, "12 А другого дня, коли безліч народу, що зібрався на свято, прочула, що до Єрусалиму надходить Ісус,"},
{13, "13 то взяли вони пальмове віття, і вийшли назустріч Йому та й кричали: Осанна! Благословенний, хто йде у Господнє Ім'я! Цар Ізраїлів!"},
{14, "14 Ісус же, знайшовши осля, сів на нього, як написано:"},
{15, "15 Не бійся, дочко Сіонська! Ото Цар твій іде, сидячи на ослі молодому!"},
{16, "16 А учні Його спочатку того не зрозуміли були, але, як прославивсь Ісус, то згадали тоді, що про Нього було так написано, і що цеє вчинили Йому."},
{17, "17 Тоді свідчив народ, який був із Ним, що Він викликав Лазаря з гробу, і воскресив його з мертвих."},
{18, "18 Через це й зустрів натовп Його, бо почув, що Він учинив таке чудо."},
{19, "19 Фарисеї тоді між собою казали: Ви бачите, що нічого не вдієте: ось пішов увесь світ услід за Ним!"},
{20, "20 А між тими, що в свято прийшли поклонитись, були й деякі геллени."},
{21, "21 І вони підійшли до Пилипа, що з Віфсаїди Галілейської, і просили його та казали: Ми хочемо, пане, побачити Ісуса."},
{22, "22 Іде Пилип та Андрієві каже; іде Андрій і Пилип та Ісусові розповідають."},
{23, "23 Ісус же їм відповідає, говорячи: Надійшла година, щоб Син Людський прославивсь."},
{24, "24 Поправді, поправді кажу вам: коли зерно пшеничне, як у землю впаде, не помре, то одне зостається; як умре ж, плід рясний принесе."},
{25, "25 Хто кохає душу свою, той погубить її; хто ж ненавидить душу свою на цім світі, збереже її в вічне життя."},
{26, "26 Як хто служить Мені, хай іде той за Мною, і де Я, там буде й слуга Мій. Як хто служить Мені, того пошанує Отець."},
{27, "27 Затривожена зараз душа Моя. І що Я повім? Заступи Мене, Отче, від цієї години! Та на те Я й прийшов на годину оцю..."},
{28, "28 Прослав, Отче, Ім'я Своє! Залунав тоді голос із неба: І прославив, і знову прославлю!"},
{29, "29 А народ, що стояв і почув, говорив: Загреміло! Інші казали: Це Ангол Йому говорив!"},
{30, "30 Ісус відповів і сказав: Не для Мене цей голос лунав, а для вас."},
{31, "31 Тепер суд цьому світові. Князь світу цього буде вигнаний звідси тепер."},
{32, "32 І, як буду піднесений з землі, то до Себе Я всіх притягну."},
{33, "33 А Він це говорив, щоб зазначити, якою то смертю Він має померти."},
{34, "34 А народ відповів Йому: Ми чули з Закону, що Христос перебуває повік, то чого ж Ти говориш, що Людському Сину потрібно піднесеному бути? Хто такий Цей Син Людський?"},
{35, "35 І сказав їм Ісус: Короткий ще час світло з вами. Ходіть, поки маєте світло, щоб вас темрява не обгорнула. А хто в темряві ходить, не знає, куди він іде..."},
{36, "36 Аж доки ви маєте світло, то віруйте в світло, щоб синами світла ви стали. Промовивши це, Ісус відійшов, і сховався від них."},
{37, "37 І хоч Він стільки чуд перед ними вчинив був, та в Нього вони не ввірували,"},
{38, "38 щоб справдилось слово пророка Ісаї, який провіщав: Хто повірив тому, що ми, Господи, чули, а Господнє рамено кому об'явилось?"},
{39, "39 Тому не могли вони вірити, що знову Ісая прорік:"},
{40, "40 Засліпив їхні очі, і скам'янив їхнє серце, щоб очима не бачили, ані серцем щоб не зрозуміли, і не навернулись, щоб Я їх уздоровив!"},
{41, "41 Це Ісая сказав, коли бачив славу Його, і про Нього звіщав."},
{42, "42 Проте багато-хто навіть із старших у Нього ввірували, та не признавались через фарисеїв, щоб не вигнано їх із синагоги."},
{43, "43 Бо любили вони славу людську більше, аніж славу Божу."},
{44, "44 А Ісус підняв голос, та й промовляв: Хто вірує в Мене, не в Мене він вірує, але в Того, Хто послав Мене."},
{45, "45 А хто бачить Мене, той бачить Того, хто послав Мене."},
{46, "46 Я, Світло, на світ прийшов, щоб кожен, хто вірує в Мене, у темряві не зоставався."},
{47, "47 Коли б же хто слів Моїх слухав та не вірував, Я того не суджу, бо Я не прийшов світ судити, але щоб спасти світ."},
{48, "48 Хто цурається Мене, і Моїх слів не приймає, той має для себе суддю: те слово, що Я говорив, останнього дня воно буде судити його!"},
{49, "49 Бо від Себе Я не говорив, а Отець, що послав Мене, то Він Мені заповідь дав, що Я маю казати та що говорити."},
{50, "50 І відаю Я, що Його ота заповідь то вічне життя. Тож що Я говорю, то так говорю, як Отець Мені розповідав."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view13() {
struct uk13 poems[] = {
{1, "1 Перед святом же Пасхи Ісус, знавши, що настала година Йому перейти до Отця з цього світу, полюбивши Своїх, що на світі були, до кінця полюбив їх."},
{2, "2 Під час же вечері, як диявол уже був укинув у серце синові Симона Юді Іскаріотському, щоб він видав Його,"},
{3, "3 то Ісус, знавши те, що Отець віддав все Йому в руки, і що від Бога прийшов Він, і до Бога відходить,"},
{4, "4 устає від вечері, і здіймає одежу, бере рушника й підперізується."},
{5, "5 Потому налив Він води до вмивальниці, та й зачав обмивати ноги учням, і витирати рушником, що ним був підперезаний."},
{6, "6 І підходить до Симона Петра, а той каже Йому: Ти, Господи, митимеш ноги мені?"},
{7, "7 Ісус відказав і промовив йому: Що Я роблю, ти не знаєш тепер, але опісля зрозумієш."},
{8, "8 Говорить до Нього Петро: Ти повік мені ніг не обмиєш! Ісус відповів йому: Коли Я не вмию тебе, ти не матимеш частки зо Мною."},
{9, "9 До Нього проказує Симон Петро: Господи, не самі мої ноги, а й руки та голову!"},
{10, "10 Ісус каже йому: Хто обмитий, тільки ноги обмити потребує, бо він чистий увесь. І ви чисті, та не всі."},
{11, "11 Бо Він знав Свого зрадника, тому то сказав: Ви чисті не всі."},
{12, "12 Коли ж пообмивав їхні ноги, і одежу Свою Він надів, засів знову за стіл і промовив до них: Чи знаєте ви, що Я зробив вам?"},
{13, "13 Ви Мене називаєте: Учитель і Господь, і добре ви кажете, бо Я є."},
{14, "14 А коли обмив ноги вам Я, Господь і Вчитель, то повинні й ви один одному ноги вмивати."},
{15, "15 Бо то Я вам приклада дав, щоб і ви те чинили, як Я вам учинив."},
{16, "16 Поправді, поправді кажу вам: Раб не більший за пана свого, посланець же не більший від того, хто вислав його."},
{17, "17 Коли знаєте це, то блаженні ви, якщо таке чините!"},
{18, "18 Не про всіх вас кажу. Знаю Я, кого вибрав, але щоб збулося Писання: Хто хліб споживає зо Мною, підняв той на Мене п'яту свою!"},
{19, "19 Уже тепер вам кажу, перше ніж те настане, щоб як станеться, ви ввірували, що то Я."},
{20, "20 Поправді, поправді кажу вам: Хто приймає Мого посланця, той приймає Мене; хто ж приймає Мене, той приймає Того, Хто послав Мене!"},
{21, "21 Промовивши це, затривожився духом Ісус, і освідчив, говорячи: Поправді, поправді кажу вам, що один із вас видасть Мене!..."},
{22, "22 І озиралися учні один на одного, непевними бувши, про кого Він каже."},
{23, "23 При столі, при Ісусовім лоні, був один з Його учнів, якого любив Ісус."},
{24, "24 От цьому кивнув Симон Петро та й шепнув: Запитай, хто б то був, що про нього Він каже?"},
{25, "25 І, пригорнувшись до лоня Ісусового, той говорить до Нього: Хто це, Господи?"},
{26, "26 Ісус же відказує: Це той, кому, умочивши, подам Я куска. І, вмочивши куска, подав синові Симона, Юді Іскаріотському!..."},
{27, "27 За тим же куском тоді в нього ввійшов сатана. А Ісус йому каже: Що ти робиш роби швидше..."},
{28, "28 Але жаден із тих, хто був при столі, того не зрозумів, до чого сказав Він йому."},
{29, "29 А тому, що тримав Юда скриньку на гроші, то деякі думали, ніби каже до нього Ісус: Купи, що потрібно на свято для нас, або щоб убогим подав що."},
{30, "30 А той, узявши кусок хліба, зараз вийшов. Була ж ніч."},
{31, "31 Тоді, як він вийшов, промовляє Ісус: Тепер ось прославивсь Син Людський, і в Ньому прославився Бог."},
{32, "32 Коли в Ньому прославився Бог, то і Його Бог прославить у Собі, і зараз прославить Його!"},
{33, "33 Мої дітоньки, не довго вже бути Мені з вами! Ви шукати Мене будете, але як сказав Я юдеям: Куди Я йду, туди ви прибути не можете, те й вам говорю Я тепер."},
{34, "34 Нову заповідь Я вам даю: Любіть один одного! Як Я вас полюбив, так любіть один одного й ви!"},
{35, "35 По тому пізнають усі, що ви учні Мої, як будете мати любов між собою."},
{36, "36 А Симон Петро Йому каже: Куди, Господи, ідеш Ти? Ісус відповів: Куди Я йду, туди ти тепер іти за Мною не можеш, але потім ти підеш за Мною."},
{37, "37 Говорить до Нього Петро: Чому, Господи, іти за Тобою тепер я не можу? За Тебе я душу свою покладу!"},
{38, "38 Ісус відповідає: За Мене покладеш ти душу свою? Поправді, поправді кажу Я тобі: Півень не заспіває, як ти тричі зречешся Мене..."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view14() {
struct uk14 poems[] = {
{1, "1 Нехай серце вам не тривожиться! Віруйте в Бога, і в Мене віруйте!"},
{2, "2 Багато осель у домі Мого Отця; а коли б то не так, то сказав би Я вам, що йду приготувати місце для вас?"},
{3, "3 А коли відійду й приготую вам місце, Я знову прийду й заберу вас до Себе, щоб де Я були й ви."},
{4, "4 А куди Я йду дорогу ви знаєте."},
{5, "5 Говорить до Нього Хома: Ми не знаємо, Господи, куди йдеш; як же можемо знати дорогу?"},
{6, "6 Промовляє до нього Ісус: Я дорога, і правда, і життя. До Отця не приходить ніхто, якщо не через Мене."},
{7, "7 Коли б то були ви пізнали Мене, ви пізнали були б і Мого Отця. Відтепер Його знаєте ви, і Його бачили."},
{8, "8 Говорить до Нього Пилип: Господи, покажи нам Отця, і вистачить нам!"},
{9, "9 Промовляє до нього Ісус: Стільки часу Я з вами, ти ж не знаєш, Пилипе, Мене? Хто бачив Мене, той бачив Отця, то як же ти кажеш: Покажи нам Отця?"},
{10, "10 Чи не віруєш ти, що Я в Отці, а Отець у Мені? Слова, що Я вам говорю, говорю не від Себе, а Отець, що в Мені перебуває, Той чинить діла ті."},
{11, "11 Повірте Мені, що Я в Отці, а Отець у Мені! Коли ж ні, то повірте за вчинки самі."},
{12, "12 Поправді, поправді кажу вам: Хто вірує в Мене, той учинить діла, які чиню Я, і ще більші від них він учинить, бо Я йду до Отця."},
{13, "13 І коли що просити ви будете в Імення Моє, те вчиню, щоб у Сині прославивсь Отець."},
{14, "14 Коли будете в Мене просити чого в Моє Ймення, то вчиню."},
{15, "15 Якщо Ви Мене любите, Мої заповіді зберігайте!"},
{16, "16 І вблагаю Отця Я, і Втішителя іншого дасть вам, щоб із вами повік перебував,"},
{17, "17 Духа правди, що Його світ прийняти не може, бо не бачить Його та не знає Його. Його знаєте ви, бо при вас перебуває, і в вас буде Він."},
{18, "18 Я не кину вас сиротами, Я прибуду до вас!"},
{19, "19 Ще недовго, і вже світ Мене не побачить, але ви Мене бачити будете, бо живу Я і ви жити будете!"},
{20, "20 Того дня пізнаєте ви, що в Своїм Я Отці, а ви в Мені, і Я в вас."},
{21, "21 Хто заповіді Мої має та їх зберігає, той любить Мене. А хто любить Мене, то полюбить його Мій Отець, і Я полюблю Його, і об'явлюсь йому Сам."},
{22, "22 Запитує Юда, не Іскаріотський, Його: Що то, Господи, що Ти нам об'явитися маєш, а не світові?"},
{23, "23 Ісус відповів і до нього сказав: Як хто любить Мене, той слово Моє берегтиме, і Отець Мій полюбить його, і Ми прийдемо до нього, і оселю закладемо в нього."},
{24, "24 Хто не любить Мене, той не береже Моїх слів. А слово, що чуєте ви, не Моє, а Отця, що послав Мене."},
{25, "25 Говорив це Я вам, бувши з вами."},
{26, "26 Утішитель же, Дух Святий, що Його Отець пошле в Ім'я Моє, Той навчить вас усього, і пригадає вам усе, що Я вам говорив."},
{27, "27 Зоставляю вам мир, мир Свій вам даю! Я даю вам не так, як дає світ. Серце ваше нехай не тривожиться, ані не лякається!"},
{28, "28 Чули ви, що Я вам говорив: Я відходжу, і вернуся до вас. Якби ви любили Мене, то ви б тішилися, що Я йду до Отця, бо більший за Мене Отець."},
{29, "29 І тепер Я сказав вам, передніше, ніж сталося, щоб ви вірували, коли станеться."},
{30, "30 Небагато вже Я говоритиму з вами, бо надходить князь світу цього, а в Мені він нічого не має,"},
{31, "31 та щоб світ зрозумів, що люблю Я Отця, і як Отець наказав Мені, так роблю. Уставайте, ходім звідсіля!"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view15() {
struct uk15 poems[] = {
{1, "1 Я правдива Виноградина, а Отець Мій Виноградар."},
{2, "2 Усяку галузку в Мене, що плоду не приносить, Він відтинає, але всяку, що плід родить, обчищає її, щоб рясніше родила."},
{3, "3 Через Слово, що Я вам говорив, ви вже чисті."},
{4, "4 Перебувайте в Мені, а Я в вас! Як та вітка не може вродити плоду сама з себе, коли не позостанеться на виноградині, так і ви, як в Мені перебувати не будете."},
{5, "5 Я Виноградина, ви галуззя! Хто в Мені перебуває, а Я в ньому, той рясно зароджує, бо без Мене нічого чинити не можете ви."},
{6, "6 Коли хто перебувати не буде в Мені, той буде відкинений геть, як галузка, і всохне. І громадять їх, і кладуть на огонь, і згорять."},
{7, "7 Коли ж у Мені перебувати ви будете, а слова Мої позостануться в вас, то просіть, чого хочете, і станеться вам!"},
{8, "8 Отець Мій прославиться в тому, якщо рясно зародите й будете учні Мої."},
{9, "9 Як Отець полюбив Мене, так і Я полюбив вас. Перебувайте в любові Моїй!"},
{10, "10 Якщо будете ви зберігати Мої заповіді, то в любові Моїй перебуватимете, як і Я зберіг Заповіді Свого Отця, і перебуваю в любові Його."},
{11, "11 Це Я вам говорив, щоб радість Моя була в вас, і щоб повна була ваша радість!"},
{12, "12 Оце Моя заповідь, щоб любили один одного ви, як Я вас полюбив!"},
{13, "13 Ніхто більшої любови не має над ту, як хто свою душу поклав би за друзів своїх."},
{14, "14 Ви друзі Мої, якщо чините все, що Я вам заповідую."},
{15, "15 Я вже більше не буду рабами вас звати, бо не відає раб, що пан його чинить. А вас назвав друзями Я, бо Я вам об'явив усе те, що почув від Мого Отця."},
{16, "16 Не ви Мене вибрали, але Я вибрав вас, і вас настановив, щоб ішли ви й приносили плід, і щоб плід ваш зостався, щоб дав вам Отець, чого тільки попросите в Імення Моє."},
{17, "17 Це Я вам заповідую, щоб любили один одного ви!"},
{18, "18 Коли вас світ ненавидить, знайте, що Мене він зненавидів перше, як вас."},
{19, "19 Коли б ви зо світу були, то своє світ любив би. А що ви не зо світу, але Я вас зо світу обрав, тому світ вас ненавидить."},
{20, "20 Пригадайте те слово, яке Я вам сказав: Раб не більший за пана свого. Як Мене переслідували, то й вас переслідувати будуть; як слово Моє зберігали, берегтимуть і ваше."},
{21, "21 Але все це робитимуть вам за Ім'я Моє, бо не знають Того, хто послав Мене."},
{22, "22 Коли б Я не прийшов і до них не казав, то не мали б гріха, а тепер вимовки не мають вони за свій гріх."},
{23, "23 Хто Мене ненавидить, і Мого Отця той ненавидить."},
{24, "24 Коли б Я серед них не вчинив був тих діл, яких не чинив ніхто інший, то не мали б гріха. Та тепер вони бачили, і зненавиділи і Мене, і Мого Отця."},
{25, "25 Та щоб справдилось слово, що в їхнім Законі написане: Мене безпідставно зненавиділи!"},
{26, "26 А коли Втішитель прибуде, що Його від Отця Я пошлю вам, Той Дух правди, що походить від Отця, Він засвідчить про Мене."},
{27, "27 Та засвідчте і ви, бо ви від початку зо Мною."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view16() {
struct uk16 poems[] = {
{1, "1 Оце Я сказав вам, щоб ви не спокусились."},
{2, "2 Вас виженуть із синагог. Прийде навіть година, коли кожен, хто вам смерть заподіє, то думатиме, ніби службу приносить він Богові!"},
{3, "3 А це вам учинять, бо вони не пізнали Отця, ні Мене."},
{4, "4 Але Я це сказав вам, щоб згадали про те, про що говорив був Я вам, як настане година. Цього вам не казав Я спочатку, бо з вами Я був."},
{5, "5 Тепер же до Того Я йду, Хто послав Мене, і ніхто з вас Мене не питає: Куди йдеш?"},
{6, "6 Та від того, що це Я сказав вам, серце ваше наповнилось смутком."},
{7, "7 Та Я правду кажу вам: Краще для вас, щоб пішов Я, бо як Я не піду, Утішитель не прийде до вас. А коли Я піду, то пошлю вам Його."},
{8, "8 А як прийде, Він світові виявить про гріх, і про правду, і про суд:"},
{9, "9 тож про гріх, що не вірують у Мене;"},
{10, "10 а про правду, що Я до Отця Свого йду, і Мене не побачите вже;"},
{11, "11 а про суд, що засуджений князь цього світу."},
{12, "12 Я ще маю багато сказати вам, та тепер ви не можете знести."},
{13, "13 А коли прийде Він, Той Дух правди, Він вас попровадить до цілої правди, бо не буде казати Сам від Себе, а що тільки почує, казатиме, і що має настати, звістить вам."},
{14, "14 Він прославить Мене, бо Він візьме з Мого та й вам сповістить."},
{15, "15 Усе, що має Отець, то Моє; через те Я й сказав, що Він візьме з Мого та й вам сповістить."},
{16, "16 Незабаром, і Мене вже не будете бачити, і знов незабаром і Мене ви побачите, бо Я йду до Отця."},
{17, "17 А деякі з учнів Його говорили один до одного: Що таке, що сказав Він до нас: Незабаром, і Мене вже не будете бачити, і знов незабаром і Мене ви побачите, та: Я йду до Отця?..."},
{18, "18 Гомоніли також: Що таке, що говорить: Незабаром? Про що каже, не знаємо..."},
{19, "19 Ісус же пізнав, що хочуть поспитати Його, і сказав їм: Чи про це між собою міркуєте ви, що сказав Я: Незабаром, і вже Мене бачити не будете ви, і знов незабаром і Мене ви побачите?"},
{20, "20 Поправді, поправді кажу вам, що ви будете плакати та голосити, а світ буде радіти. Сумувати ви будете, але сум ваш обернеться в радість!"},
{21, "21 Журиться жінка, що родить, бо настала година її. Як дитинку ж породить вона, то вже не пам'ятає терпіння з-за радощів, що людина зродилась на світ..."},
{22, "22 Так сумуєте й ви ось тепер, та побачу вас знову, і серце ваше радітиме, і ніхто радости вашої вам не відійме!"},
{23, "23 Ні про що ж того дня ви Мене не спитаєте. Поправді, поправді кажу вам: Чого тільки попросите ви від Отця в Моє Ймення, Він дасть вам."},
{24, "24 Не просили ви досі нічого в Ім'я Моє. Просіть і отримаєте, щоб повна була ваша радість."},
{25, "25 Оце все Я в притчах до вас говорив. Настає година, коли притчами Я вже не буду до вас промовляти, але явно звіщу про Отця вам."},
{26, "26 Того дня ви проситимете в Моє Ймення, і Я вам не кажу, що вблагаю Отця Я за вас,"},
{27, "27 бо Отець любить Сам вас за те, що ви полюбили Мене та й увірували, що Я вийшов від Бога."},
{28, "28 Від Отця вийшов Я, і на світ Я прийшов. І знов покидаю Я світ та й іду до Отця."},
{29, "29 Його учні відказують: Ось тепер Ти говориш відкрито, і жадної притчі не кажеш."},
{30, "30 Тепер відаємо ми, що Ти знаєш усе, і потреби не маєш, щоб Тебе хто питав. Тому віруємо, що Ти вийшов від Бога!"},
{31, "31 Ісус їм відповів: Тепер віруєте?"},
{32, "32 Ото настає година, і вже настала, що ви розпорошитесь кожен у власне своє, а Мене ви Самого покинете... Та не Сам Я, бо зо Мною Отець!"},
{33, "33 Це Я вам розповів, щоб мали ви мир у Мені. Страждання зазнаєте в світі, але будьте відважні: Я світ переміг!"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view17() {
struct uk17 poems[] = {
{1, "1 По мові оцій Ісус очі Свої звів до неба й промовив: Прийшла, Отче, година, прослав Сина Свого, щоб і Син Твій прославив Тебе,"},
{2, "2 бо Ти дав Йому владу над тілом усяким, щоб Він дав життя вічне всім їм, яких дав Ти Йому."},
{3, "3 Життя ж вічне це те, щоб пізнали Тебе, єдиного Бога правдивого, та Ісуса Христа, що послав Ти Його."},
{4, "4 Я прославив Тебе на землі, довершив Я те діло, що Ти дав Мені виконати."},
{5, "5 І тепер прослав, Отче, Мене Сам у Себе тією славою, яку в Тебе Я мав, поки світ не постав."},
{6, "6 Я Ім'я Твоє виявив людям, що Мені Ти із світу їх дав. Твоїми були вони, і Ти дав їх Мені, і вони зберегли Твоє слово."},
{7, "7 Тепер пізнали вони, що все те, що Ти Мені дав, від Тебе походить,"},
{8, "8 бо слова, що дав Ти Мені, Я їм передав, і вони прийняли й зрозуміли правдиво, що Я вийшов від Тебе, і ввірували, що послав Ти Мене."},
{9, "9 Я благаю за них. Не за світ Я благаю, а за тих, кого дав Ти Мені, Твої бо вони!"},
{10, "10 Усе бо Моє то Твоє, а Твоє то Моє, і прославивсь Я в них."},
{11, "11 І не на світі вже Я, а вони ще на світі, а Я йду до Тебе. Святий Отче, заховай в Ім'я Своє їх, яких дав Ти Мені, щоб як Ми, єдине були!"},
{12, "12 Коли з ними на світі Я був, Я беріг їх у Ймення Твоє, тих, що дав Ти Мені, і зберіг, і ніхто з них не згинув, крім призначеного на загибіль, щоб збулося Писання."},
{13, "13 Тепер же до Тебе Я йду, але це говорю Я на світі, щоб мали вони в собі радість Мою досконалу."},
{14, "14 Я їм дав Твоє слово, але світ їх зненавидів, бо вони не від світу, як і Я не від світу."},
{15, "15 Не благаю, щоб Ти їх зо світу забрав, але щоб зберіг їх від злого."},
{16, "16 Не від світу вони, як і Я не від світу."},
{17, "17 Освяти Ти їх правдою! Твоє слово то правда."},
{18, "18 Як на світ Ти послав Мене, так і Я на світ послав їх."},
{19, "19 А за них Я посвячую в жертву Самого Себе, щоб освячені правдою стали й вони."},
{20, "20 Та не тільки за них Я благаю, а й за тих, що ради їхнього слова ввірують у Мене,"},
{21, "21 щоб були всі одно: як Ти, Отче, в Мені, а Я у Тобі, щоб одно були в Нас і вони, щоб увірував світ, що Мене Ти послав."},
{22, "22 А ту славу, що дав Ти Мені, Я їм передав, щоб єдине були, як єдине і Ми."},
{23, "23 Я у них, а Ти у Мені, щоб були досконалі в одно, і щоб пізнав світ, що послав Мене Ти, і що їх полюбив Ти, як Мене полюбив."},
{24, "24 Бажаю Я, Отче, щоб і ті, кого дав Ти Мені, там зо Мною були, де знаходжуся Я, щоб бачили славу Мою, яку дав Ти Мені, бо Ти полюбив Мене перше закладин світу."},
{25, "25 Отче Праведний! Хоча не пізнав Тебе світ, та пізнав Тебе Я. І пізнали вони, що послав Мене Ти."},
{26, "26 Я ж Ім'я Твоє їм об'явив й об'являтиму, щоб любов, що Ти нею Мене полюбив, була в них, а Я в них!..."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view18() {
struct uk18 poems[] = {
{1, "1 Промовивши це, Ісус вийшов із учнями Своїми на той бік потоку Кедрону, де був сад, до якого ввійшов Він та учні Його."},
{2, "2 Але й Юда, що видав Його, знав те місце, бо там часто збирались Ісус й Його учні."},
{3, "3 Отож Юда, узявши відділ війська та службу від первосвящеників і фарисеїв, приходить туди із смолоскипами, та з ліхтарями, та з зброєю."},
{4, "4 А Ісус, усе відавши, що з Ним статися має, виходить та й каже до них: Кого ви шукаєте?"},
{5, "5 Йому відповіли: Ісуса Назарянина. Він говорить до них: Це Я... А стояв із ними й Юда, що видав Його."},
{6, "6 І як тільки сказав їм: Це Я, вони подалися назад, та й на землю попадали..."},
{7, "7 І Він знов запитав їх: Кого ви шукаєте? Вони ж відказали: Ісуса Назарянина."},
{8, "8 Ісус відповів: Я сказав вам, що це Я... Отож, як Мене ви шукаєте, то дайте оцим відійти,"},
{9, "9 щоб збулося те слово, що Він був сказав: Я не втратив нікого із тих, кого дав Ти Мені."},
{10, "10 Тоді Симон Петро, меча мавши, його вихопив, і рубонув раба первосвященика, і відтяв праве вухо йому. А рабу на ім'я було Малх."},
{11, "11 Та промовив Ісус до Петра: Всунь у піхви меча! Чи ж не мав би Я пити ту чашу, що Отець дав Мені?"},
{12, "12 Відділ же війська та тисяцький і служба юдейська схопили Ісуса, і зв'язали Його,"},
{13, "13 і повели Його перше до Анни, бо тестем доводивсь Кайяфі, що первосвящеником був того року."},
{14, "14 Це ж був той Кайяфа, що порадив юдеям, що ліпше померти людині одній за народ."},
{15, "15 А Симон Петро й інший учень ішли за Ісусом слідом. Той же учень відомий був первосвященикові, і ввійшов у двір первосвящеників із Ісусом."},
{16, "16 А Петро за ворітьми стояв. Тоді вийшов той учень, що відомий був первосвященикові, і сказав воротарці, і впровадив Петра."},
{17, "17 І питає Петра воротарка служниця: Ти хіба не з учнів Цього Чоловіка? Той відказує: Ні!"},
{18, "18 А раби й служба, розклавши огонь, стояли та й грілися, бо був холод. І Петро стояв із ними та грівся."},
{19, "19 А первосвященик спитався Ісуса про учнів Його, і про науку Його."},
{20, "20 Ісус Йому відповідь дав: Я світові явно казав. Я постійно навчав у синагозі й у храмі, куди всі юдеї збираються, а таємно нічого Я не говорив."},
{21, "21 Чого ти питаєш Мене? Поспитайся тих, що чули, що Я їм говорив. Отже, знають вони, про що Я говорив."},
{22, "22 А як Він це сказав, то один із присутньої там служби вдарив Ісуса в щоку, говорячи: То так відповідаєш первосвященикові?"},
{23, "23 Ісус йому відповідь дав: Якщо зле Я сказав, покажи, що то зле; коли ж добре, за що Мене б'єш?"},
{24, "24 І відіслав Його Анна зв'язаним первосвященикові Кайяфі."},
{25, "25 А Симон Петро стояв, гріючись. І сказали до нього: Чи й ти не з учнів Його? Він відрікся й сказав: Ні!"},
{26, "26 Говорить один із рабів первосвященика, родич тому, що йому Петро вухо відтяв: Чи тебе я не бачив у саду з Ним?"},
{27, "27 І знову відрікся Петро, і заспівав півень хвилі тієї..."},
{28, "28 А Ісуса ведуть від Кайяфи в преторій. Був же ранок. Та вони не ввійшли до преторія, щоб не опоганитись, а щоб їсти пасху."},
{29, "29 Тоді вийшов Пилат назовні до них і сказав: Яку скаргу приносите ви на Цього Чоловіка?"},
{30, "30 Вони відповіли та й сказали йому: Коли б Цей злочинцем не був, ми б Його тобі не видавали."},
{31, "31 А Пилат їм сказав: Візьміть Його, та й за вашим Законом судіть Його. Юдеї сказали йому: Нам не вільно нікого вбивати,"},
{32, "32 щоб збулося Ісусове слово, що його Він прорік, зазначаючи, якою то смертю Він має померти."},
{33, "33 Тоді знову Пилат увійшов у преторій, і покликав Ісуса, і до Нього сказав: Чи Ти Цар Юдейський?"},
{34, "34 Ісус відповів: Чи від себе самого питаєш ти це, чи то інші тобі говорили про Мене?"},
{35, "35 Пилат відповів: Чи ж юдеянин я? Твій народ та первосвященики мені Тебе видали. Що таке Ти вчинив?"},
{36, "36 Ісус відповів: Моє Царство не із світу цього. Якби із цього світу було Моє Царство, то служба Моя воювала б, щоб не виданий був Я юдеям. Та тепер Моє Царство не звідси..."},
{37, "37 Сказав же до Нього Пилат: Так Ти Цар? Ісус відповів: Сам ти кажеш, що Цар Я. Я на те народився, і на те прийшов у світ, щоб засвідчити правду. І кожен, хто з правди, той чує Мій голос."},
{38, "38 Говорить до Нього Пилат: Що є правда? І сказавши оце, до юдеїв знов вийшов, та й каже до них: Не знаходжу Я в Ньому провини ніякої."},
{39, "39 Та ви маєте звичай, щоб я випустив вам одного на Пасху. Чи хочете отже, відпущу вам Царя Юдейського?"},
{40, "40 Та знову вони зняли крик, вимагаючи: Не Його, а Варавву! А Варавва був злочинець."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view19() {
struct uk19 poems[] = {
{1, "1 От тоді взяв Ісуса Пилат, та й звелів збичувати Його."},
{2, "2 Вояки ж, сплівши з терну вінка, Йому поклали на голову, та багряницю наділи на Нього,"},
{3, "3 і приступали до Нього й казали: Радій, Царю Юдейський! І били по щоках Його..."},
{4, "4 Тоді вийшов назовні ізнову Пилат та й говорить до них: Ось Його я виводжу назовні до вас, щоб ви переконались, що провини ніякої в Нім не знаходжу."},
{5, "5 І вийшов назовні Ісус, у терновім вінку та в багрянім плащі. А Пилат до них каже: Оце Чоловік!"},
{6, "6 Як зобачили ж Його первосвященики й служба, то закричали, говорячи: Розіпни, розіпни! Пилат каже до них: То візьміть Його ви й розіпніть, бо провини я в Нім не знаходжу!"},
{7, "7 Відказали юдеї йому: Ми маємо Закона, а за Законом Він мусить умерти, бо за Божого Сина Себе видавав!"},
{8, "8 Як зачув же Пилат оце слово, налякався ще більш,"},
{9, "9 і вернувся в преторій ізнову, і питає Ісуса: Звідки Ти? Та Ісус йому відповіді не подав."},
{10, "10 І каже до Нього Пилат: Не говориш до мене? Хіба ж Ти не знаєш, що маю я владу розп'ясти Тебе, і маю владу Тебе відпустити?"},
{11, "11 Ісус відповів: Надо Мною ти жадної влади не мав би, коли б тобі зверху не дано було; тому більший гріх має той, хто Мене тобі видав..."},
{12, "12 Після цього Пилат намагався пустити Його, та юдеї кричали, говорячи: Якщо Його пустиш, то не кесарів приятель ти! Усякий, хто себе за царя видає, противиться кесареві."},
{13, "13 Як зачув же Пилат оце слово, то вивів назовні Ісуса, і засів на суддеве сидіння, на місці, що зветься літостротон, по-гебрейському ж гаввата."},
{14, "14 Був то ж день Приготовлення Пасхи, година була близько шостої. І він каже юдеям: Ось ваш Цар!"},
{15, "15 Та вони закричали: Геть, геть із Ним! Розіпни Його! Пилат каже до них: Царя вашого маю розп'ясти? Первосвященики відповіли: Ми не маєм царя, окрім кесаря!"},
{16, "16 Ось тоді він їм видав Його, щоб розп'ясти... І взяли Ісуса й повели..."},
{17, "17 І, нісши Свого хреста, Він вийшов на місце, Череповищем зване, по-гебрейському Голгофа."},
{18, "18 Там Його розп'яли, а з Ним разом двох інших, з одного та з другого боку, а Ісуса всередині."},
{19, "19 А Пилат написав і написа, та й умістив на хресті. Було ж там написано: Ісус Назарянин, Цар Юдейський."},
{20, "20 І багато з юдеїв читали цього написа, бо те місце, де Ісус був розп'ятий, було близько від міста. А було по-гебрейському, по-грецькому й по-римському написано."},
{21, "21 Тож сказали Пилатові юдейські первосвященики: Не пиши: Цар Юдейський, але що Він Сам говорив: Я Цар Юдейський."},
{22, "22 Пилат відповів: Що я написав написав!"},
{23, "23 Розп'явши ж Ісуса, вояки взяли одіж Його, та й поділили на чотири частині, по частині для кожного вояка, теж і хітона. А хітон був не шитий, а витканий цілий відверху."},
{24, "24 Тож сказали один до одного: Не будемо дерти його, але жереба киньмо на нього, кому припаде. Щоб збулося Писання: Поділили одежу Мою між собою, і метнули про шату Мою жеребка. Вояки ж це й зробили..."},
{25, "25 Під хрестом же Ісуса стояли Його мати, і сестра Його матері, Марія Клеопова, і Марія Магдалина."},
{26, "26 Як побачив Ісус матір та учня, що стояв тут, якого любив, то каже до матері: Оце, жоно, твій син!"},
{27, "27 Потім каже до учня: Оце мати твоя! І з тієї години той учень узяв її до себе."},
{28, "28 Потім, знавши Ісус, що вже все довершилось, щоб збулося Писання, проказує: Прагну!"},
{29, "29 Тут стояла посудина, повна оцту. Вояки ж, губку оцтом наповнивши, і на тростину її настромивши, піднесли до уст Його."},
{30, "30 А коли Ісус оцту прийняв, то промовив: Звершилось!... І, голову схиливши, віддав Свого духа..."},
{31, "31 Був же день Приготовлення, тож юдеї, щоб тіла на хресті не зосталися в суботу, був бо Великдень тієї суботи просили Пилата зламати голінки розп'ятим, і зняти."},
{32, "32 Тож прийшли вояки й поламали голінки першому й другому, що розп'ятий з Ним був."},
{33, "33 Коли ж підійшли до Ісуса й побачили, що Він уже вмер, то голінок Йому не зламали,"},
{34, "34 та один з вояків списом бока Йому проколов, і зараз витекла звідти кров та вода."},
{35, "35 І самовидець засвідчив, і правдиве свідоцтво його; і він знає, що правду говорить, щоб повірили й ви."},
{36, "36 о це сталось тому, щоб збулося Писання: Йому кості ламати не будуть!"},
{37, "37 І знов друге Писання говорить: Дивитися будуть на Того, Кого прокололи."},
{38, "38 Потім Йосип із Аріматеї, що був учень Ісуса, але потайний, бо боявся юдеїв, став просити Пилата, щоб тіло Ісусове взяти. І дозволив Пилат. Тож прийшов він, і взяв тіло Ісусове."},
{39, "39 Прибув також і Никодим, що давніше приходив вночі до Ісуса, і смирну приніс, із алоєм помішану, щось літрів із сто."},
{40, "40 Отож, узяли вони тіло Ісусове, та й обгорнули його плащаницею із пахощами, як є звичай ховати в юдеїв."},
{41, "41 На тім місці, де Він був розп'ятий, знаходився сад, а в саду новий гріб, що в ньому ніколи ніхто не лежав."},
{42, "42 Тож отут, з-за юдейського дня Приготовлення вони поклали Ісуса, бо поблизу був гріб."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view20() {
struct uk20 poems[] = {
{1, "1 А дня першого в тижні, рано вранці, як ще темно було, прийшла Марія Магдалина до гробу, та й бачить, що камінь від гробу відвалений."},
{2, "2 Тож біжить вона та й прибуває до Симона Петра, та до другого учня, що Ісус його любив, та й каже до них: Взяли Господа з гробу, і ми не знаємо, де поклали Його!"},
{3, "3 Тоді вийшов Петро й другий учень, і до гробу пішли."},
{4, "4 Вони ж бігли обидва укупі, але другий той учень попереду біг, хутчіш від Петра, і перший до гробу прибув."},
{5, "5 І, нахилившися, бачить лежить плащаниця... Але він не ввійшов."},
{6, "6 Прибуває і Симон Петро, що слідком за ним біг, і входить до гробу, і плащаницю оглядає, що лежала,"},
{7, "7 і хустка, що була на Його голові, лежить не з плащаницею, але осторонь, згорнена, в іншому місці..."},
{8, "8 Тоді ж увійшов й інший учень, що перший до гробу прибув, і побачив, і ввірував."},
{9, "9 Бо ще не розуміли з Писання вони, що Він має воскреснути з мертвих."},
{10, "10 І учні вернулися знову до себе."},
{11, "11 А Марія стояла при гробі назовні та й плакала. Плачучи, нахилилась до гробу."},
{12, "12 І бачить два Анголи, що в білім сиділи, один у головах, а другий у ніг, де лежало Ісусове тіло..."},
{13, "13 І говорять до неї вони: Чого плачеш ти, жінко? Та відказує їм: Узяли мого Господа, і я не знаю, де Його поклали..."},
{14, "14 І, сказавши оце, обернулась назад, і бачить Ісуса, що стояв, та вона не пізнала, що то Ісус..."},
{15, "15 Промовляє до неї Ісус: Чого плачеш ти, жінко? Кого ти шукаєш? Вона ж, думаючи, що то садівник, говорить до Нього: Якщо, пане, узяв ти Його, то скажи мені, де поклав ти Його, і Його я візьму!"},
{16, "16 Ісус мовить до неї: Маріє! А вона обернулася та по-єврейському каже Йому: Раббуні! цебто: Учителю мій!"},
{17, "17 Говорить до неї Ісус: Не торкайся до Мене, бо Я ще не зійшов до Отця. Але йди до братів Моїх та їм розповіж: Я йду до Свого Отця й Отця вашого, і до Бога Мого й Бога вашого!"},
{18, "18 Іде Марія Магдалина, та й учням звіщає, що бачила Господа, і Він це їй сказав..."},
{19, "19 Того ж дня дня першого в тижні, коли вечір настав, а двері, де учні зібрались були, були замкнені, бо боялись юдеїв, з'явився Ісус, і став посередині, та й промовляє до них: Мир вам!"},
{20, "20 І, сказавши оце, показав Він їм руки та бока. А учні зраділи, побачивши Господа."},
{21, "21 Тоді знову сказав їм Ісус: Мир вам! Як Отець послав Мене, і Я вас посилаю!"},
{22, "22 Сказавши оце, Він дихнув, і говорить до них: Прийміть Духа Святого!"},
{23, "23 Кому гріхи простите, простяться їм, а кому затримаєте, то затримаються!"},
{24, "24 А Хома, один з Дванадцятьох, званий Близнюк, із ними не був, як приходив Ісус."},
{25, "25 Інші ж учні сказали йому: Ми бачили Господа!... А він відказав їм: Коли на руках Його знаку відцвяшного я не побачу, і пальця свого не вкладу до відцвяшної рани, і своєї руки не вкладу до боку Його, не ввірую!"},
{26, "26 За вісім же день знов удома були Його учні, а з ними й Хома. І, як замкнені двері були, прийшов Ісус, і став посередині та й проказав: Мир вам!"},
{27, "27 Потім каже Хомі: Простягни свого пальця сюди, та на руки Мої подивись. Простягни й свою руку, і вклади до боку Мого. І не будь ти невіруючий, але віруючий!"},
{28, "28 А Хома відповів і сказав Йому: Господь мій і Бог мій!"},
{29, "29 Промовляє до нього Ісус: Тому ввірував ти, що побачив Мене? Блаженні, що не бачили й увірували!"},
{30, "30 Багато ж і інших ознак учинив був Ісус у присутності учнів Своїх, що в книзі оцій не записані."},
{31, "31 Це ж написано, щоб ви ввірували, що Ісус є Христос, Божий Син, і щоб, віруючи, життя мали в Ім'я Його!"},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
static void view21() {
struct uk21 poems[] = {
{1, "1 Після цього з'явивсь Ісус знов Своїм учням над морем Тіверіядським. А з'явився отак."},
{2, "2 Укупі були Симон Петро, і Хома, званий Близнюк, і Нафанаїл, із Кани Галілейської, і обидва сини Зеведеєві, і двоє інших із учнів Його."},
{3, "3 Говорить їм Симон Петро: Піду риби вловити. Вони кажуть до нього: І ми підемо з тобою. І пішли вони, і всіли до човна. Та ночі тієї нічого вони не вловили."},
{4, "4 А як ранок настав, то Ісус став над берегом, але учні не знали, що то був Ісус."},
{5, "5 Ісус тоді каже до них: Чи не маєте, діти, якоїсь поживи? Ні, вони відказали."},
{6, "6 А Він їм сказав: Закиньте невода праворуч від човна, то й знайдете! Вони кинули, і вже не могли його витягнути із-за безлічі риби..."},
{7, "7 Тоді учень, якого любив був Ісус, говорить Петрові: Це ж Господь!... А Симон Петро, як зачув, що Господь то, накинув на себе одежину, бо він був нагий, та й кинувся в море..."},
{8, "8 Інші ж учні, що були недалеко від берега якихсь ліктів із двісті припливли човником, тягнучи невода з рибою."},
{9, "9 А коли вони вийшли на землю, то бачать розложений жар, а на нім рибу й хліб."},
{10, "10 Ісус каже до них: Принесіть тієї риби, що оце ви вловили!"},
{11, "11 Пішов Симон Петро та й на землю витягнув невода, повного риби великої, сто п'ятдесят три. І хоч стільки було її, не продерся проте невід."},
{12, "12 Ісус каже до учнів: Ідіть, снідайте! А з учнів ніхто не наважився спитати Його: Хто Ти такий? Бо знали вони, що Господь то..."},
{13, "13 Тож підходить Ісус, бере хліб і дає їм, так само ж і рибу."},
{14, "14 Це вже втретє з'явився Ісус Своїм учням, як із мертвих воскрес."},
{15, "15 Як вони вже поснідали, то Ісус промовляє до Симона Петра: Симоне, сину Йонин, чи ти любиш мене більше цих? Той каже Йому: Так, Господи, відаєш Ти, що кохаю Тебе! Промовляє йому: Паси ягнята Мої!"},
{16, "16 І говорить йому Він удруге: Симоне, сину Йонин, чи ти любиш Мене? Той каже Йому: Так, Господи, відаєш Ти, що кохаю Тебе! Промовляє йому: Паси вівці Мої!"},
{17, "17 Утретє Він каже йому: Симоне, сину Йонин, чи кохаєш Мене? Засмутився Петро, що спитав його втретє: Чи кохаєш Мене? І він каже Йому: Ти все відаєш, Господи, відаєш Ти, що кохаю Тебе! Промовляє до нього Ісус: Паси вівці Мої!"},
{18, "18 Поправді, поправді кажу Я тобі: Коли був ти молодший, то ти сам підперізувався, і ходив, куди ти бажав. А коли постарієш, свої руки простягнеш, і інший тебе підпереже, і поведе, куди не захочеш..."},
{19, "19 А оце Він сказав, щоб зазначити, якою то смертю той Бога прославить. Сказавши таке, Він говорить йому: Іди за Мною!"},
{20, "20 Обернувся Петро, та й ось бачить, що за ним слідкома йде той учень, якого любив Ісус, який на вечері до лоня Йому був схилився й спитав: Хто, Господи, видасть Тебе?"},
{21, "21 Петро, як побачив того, говорить Ісусові: Господи, цей же що?"},
{22, "22 Промовляє до нього Ісус: Якщо Я схотів, щоб він позостався, аж поки прийду, що до того тобі? Ти йди за Мною!"},
{23, "23 І це слово рознеслось було між братами, що той учень не вмре. Проте Ісус не сказав йому, що не вмре, а: Якщо Я схотів, щоб він позостався, аж поки прийду, що до того тобі?"},
{24, "24 Це той учень, що свідчить про це, що й оце написав. І знаємо ми, що правдиве свідоцтво його!"},
{25, "25 Багато є й іншого, що Ісус учинив. Але думаю, що коли б написати про все те зокрема про кожне, то й сам світ не вмістив би написаних книг! Амінь."},
};
size_t npoems = sizeof poems / sizeof poems[0];size_t i;for (i=0; i < npoems; ++i) {printf("%s\n", poems[i].msg);}
}
}; | [
"max@mkoldaev.ru"
] | max@mkoldaev.ru |
58cac9baad37044a1c7dd62c7f780b2cb50332f5 | 5e70e0a90dccacfb2788ea430a698ccf464b35de | /src/function/function.cpp | c3480cb99d15048cebe3b9ff5147cddd13a6ebbc | [] | no_license | RieLL/ILS-model | 369e6334e5ada4c06c25920ccf343742e121f9e8 | 666b9d120f635d911e2177f51026feae6adf1d1c | refs/heads/master | 2020-03-21T05:28:16.166402 | 2018-07-01T11:37:16 | 2018-07-01T11:37:16 | 138,162,587 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,420 | cpp | #include "function.h"
Function::Function(qreal min, qreal step, qreal max)
: min { min }
, step { step }
, max { max }
{
//
}
Function::~Function()
{
//
}
QVector<QPointF> Function::functionCos_1(
qreal m,
qreal f,
qreal biasY,
qreal amplitude)
{
QVector<QPointF> points;
for(qreal x = { min }; x < max; x += step)
{
qreal y = { amplitude * (biasY + m * qCos(f * x)) };
points.append( QPointF(x, y) );
}
return points;
}
QVector<QPointF> Function::functionCos_2(
qreal m90,
qreal f90,
qreal m150,
qreal f150,
qreal biasY,
qreal amplitude)
{
QVector<QPointF> points;
for(qreal x = { min }; x < max; x += step)
{
qreal y = { amplitude * (biasY + m90 * qCos(f90 * x) + m150 * qCos(f150 * x)) };
points.append( QPointF(x, y) );
}
return points;
}
QVector<QPointF> Function::functionCos_3(
qreal m90,
qreal f90,
qreal m150,
qreal f150,
qreal f,
qreal amplitude)
{
QVector<QPointF> points;
for(qreal x = min; x < max; x += step)
{
qreal y = { amplitude * (qCos(f * x) + (m90 * qCos(f90 * x) + m150 * qCos(f150 * x)) * qCos(f * x)) };
points.append( QPointF(x, y) );
}
return points;
}
| [
"nak.bes@mail.ru"
] | nak.bes@mail.ru |
a802412612126cbd8bb090c55cfc976bd914cc2a | 204bc4fe1d6cb71f29e7c6b579f30160107121e7 | /Lib/src/EC/SILConvertersOffice/COMAddInShim/ConnectProxy.cpp | 0bba945015788539afd7546928d4c986dfa69f0f | [] | no_license | sillsdev/WorldPad | 5ab38c0162e03b7652b7c238a4571774e4d0efc9 | 79762436d0b9420d1e668943ed35cdefad716227 | refs/heads/master | 2020-06-03T04:42:19.274488 | 2012-10-22T12:02:38 | 2012-10-22T12:03:49 | 6,078,880 | 7 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 700 | cpp | // ConnectProxy.cpp : Implementation of CConnectProxy
#include "stdafx.h"
#include "ConnectProxy.h"
#include "CLRLoader.h"
#include "ShimConfig.h"
using namespace ShimConfig;
using namespace AddInDesignerObjects;
// CConnectProxy
HRESULT CConnectProxy::FinalConstruct()
{
HRESULT hr = S_OK;
// Create an instance of a managed addin
// and fetch the interface pointer
CCLRLoader *pCLRLoader = CCLRLoader::TheInstance();
IfNullGo(pCLRLoader);
IfFailGo(pCLRLoader->CreateInstance(AssemblyName(), ConnectClassName(),
__uuidof(IDTExtensibility2),
(void **)&m_pConnect));
Error:
return hr;
}
void CConnectProxy::FinalRelease()
{
if (m_pConnect)
m_pConnect->Release();
} | [
"eb1@sil.org"
] | eb1@sil.org |
84ab8fa5ef204d4479fa19c5ee2966eb8ed22783 | 04251e142abab46720229970dab4f7060456d361 | /lib/rosetta/source/src/core/scoring/disulfides/FullatomDisulfideEnergyContainer.hh | 3d4832dfce611085bd0b957decf652d4f8ce302d | [] | no_license | sailfish009/binding_affinity_calculator | 216257449a627d196709f9743ca58d8764043f12 | 7af9ce221519e373aa823dadc2005de7a377670d | refs/heads/master | 2022-12-29T11:15:45.164881 | 2020-10-22T09:35:32 | 2020-10-22T09:35:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,148 | hh | // -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington CoMotion, email: license@uw.edu.
/// @file core/scoring/disulfides/FullatomDisulfideEnergyContainer.hh
/// @brief Disulfide Energy Container class declaration
/// @author Andrew Leaver-Fay
#ifndef INCLUDED_core_scoring_disulfides_FullatomDisulfideEnergyContainer_hh
#define INCLUDED_core_scoring_disulfides_FullatomDisulfideEnergyContainer_hh
// Unit headers
#include <core/scoring/disulfides/FullatomDisulfideEnergyContainer.fwd.hh>
// Package headers
#include <core/scoring/LREnergyContainer.hh>
// Project headers
#include <core/chemical/ResidueType.fwd.hh>
#include <core/scoring/EnergyMap.fwd.hh>
#include <core/pose/Pose.fwd.hh>
#include <core/scoring/disulfides/DisulfideAtomIndices.fwd.hh>
#include <utility/vector1.hh>
#ifdef SERIALIZATION
// Cereal headers
#include <cereal/access.fwd.hpp>
#include <cereal/types/polymorphic.fwd.hpp>
#endif // SERIALIZATION
namespace core {
namespace scoring {
namespace disulfides {
class DisulfResNeighbIterator : public ResidueNeighborIterator {
DisulfResNeighbIterator & operator = (DisulfResNeighbIterator const & );
public:
DisulfResNeighbIterator(
FullatomDisulfideEnergyContainer * owner,
Size focused_node,
Size disulfide_index
);
DisulfResNeighbIterator(
FullatomDisulfideEnergyContainer * owner
);
~DisulfResNeighbIterator() override;
ResidueNeighborIterator & operator = ( ResidueNeighborIterator const & ) override;
ResidueNeighborIterator const & operator ++ () override;
bool operator == ( ResidueNeighborIterator const & ) const override;
bool operator != ( ResidueNeighborIterator const & ) const override;
Size upper_neighbor_id() const override;
Size lower_neighbor_id() const override;
Size residue_iterated_on() const override;
Size neighbor_id() const override;
void save_energy( EnergyMap const & ) override;
void retrieve_energy( EnergyMap & ) const override;
void accumulate_energy( EnergyMap & ) const override;
void mark_energy_computed() override;
void mark_energy_uncomputed() override;
bool energy_computed() const override;
private:
FullatomDisulfideEnergyContainer * owner_;
Size focused_residue_;
Size disulfide_index_;
};
class DisulfResNeighbConstIterator : public ResidueNeighborConstIterator {
DisulfResNeighbConstIterator & operator = (DisulfResNeighbConstIterator const & );
public:
DisulfResNeighbConstIterator(
FullatomDisulfideEnergyContainer const * owner,
Size focused_node,
Size disulfide_index
);
DisulfResNeighbConstIterator( FullatomDisulfideEnergyContainer const * owner );
~DisulfResNeighbConstIterator() override;
ResidueNeighborConstIterator & operator = ( ResidueNeighborConstIterator const & ) override;
ResidueNeighborConstIterator const & operator ++ () override;
bool operator == ( ResidueNeighborConstIterator const & ) const override;
bool operator != ( ResidueNeighborConstIterator const & ) const override;
Size upper_neighbor_id() const override;
Size lower_neighbor_id() const override;
Size residue_iterated_on() const override;
Size neighbor_id() const override;
void retrieve_energy( EnergyMap & ) const override;
void accumulate_energy( EnergyMap & ) const override;
bool energy_computed() const override;
private:
FullatomDisulfideEnergyContainer const * owner_;
Size focused_residue_;
Size disulfide_index_;
};
class FullatomDisulfideEnergyComponents
{
public:
FullatomDisulfideEnergyComponents() :
dslf_ss_dst_( 0.0 ),
dslf_cs_ang_( 0.0 ),
dslf_ss_dih_( 0.0 ),
dslf_ca_dih_( 0.0 ),
dslf_cbs_ds_( 0.0 ),
dslf_fa13_( 0.0 )
{}
Energy dslf_ss_dst() const { return dslf_ss_dst_;}
Energy dslf_cs_ang() const { return dslf_cs_ang_;}
Energy dslf_ss_dih() const { return dslf_ss_dih_;}
Energy dslf_ca_dih() const { return dslf_ca_dih_;}
Energy dslf_cbs_ds() const { return dslf_cbs_ds_;}
Energy dslf_fa13() const { return dslf_fa13_;}
Energy & dslf_ss_dst() { return dslf_ss_dst_;}
Energy & dslf_cs_ang() { return dslf_cs_ang_;}
Energy & dslf_ss_dih() { return dslf_ss_dih_;}
Energy & dslf_ca_dih() { return dslf_ca_dih_;}
Energy & dslf_cbs_ds() { return dslf_cbs_ds_;}
Energy & dslf_fa13() { return dslf_fa13_;}
private:
Energy dslf_ss_dst_;
Energy dslf_cs_ang_;
Energy dslf_ss_dih_;
Energy dslf_ca_dih_;
Energy dslf_cbs_ds_;
Energy dslf_fa13_;
#ifdef SERIALIZATION
public:
template< class Archive > void save( Archive & arc ) const;
template< class Archive > void load( Archive & arc );
#endif // SERIALIZATION
};
class FullatomDisulfideEnergyContainer : public LREnergyContainer {
public:
static Size const NO_DISULFIDE;
public:
FullatomDisulfideEnergyContainer();
FullatomDisulfideEnergyContainer( pose::Pose const & );
void
update( pose::Pose const & );
~FullatomDisulfideEnergyContainer() override;
bool empty() const override;
LREnergyContainerOP clone() const override;
void
set_num_nodes( Size ) override;
bool
any_neighbors_for_residue( int resid ) const override;
bool
any_upper_neighbors_for_residue( int resid ) const override;
ResidueNeighborConstIteratorOP
const_neighbor_iterator_begin( int resid ) const override;
ResidueNeighborConstIteratorOP
const_neighbor_iterator_end( int resid ) const override;
ResidueNeighborConstIteratorOP
const_upper_neighbor_iterator_begin( int resid ) const override;
ResidueNeighborConstIteratorOP
const_upper_neighbor_iterator_end( int resid ) const override;
ResidueNeighborIteratorOP
neighbor_iterator_begin( int resid ) override;
ResidueNeighborIteratorOP
neighbor_iterator_end( int resid ) override;
ResidueNeighborIteratorOP
upper_neighbor_iterator_begin( int resid ) override;
ResidueNeighborIteratorOP
upper_neighbor_iterator_end( int resid ) override;
bool
disulfide_bonded( Size res1id, Size res2id ) const;
bool residue_forms_disulfide( Size resid ) const;
// What residue is resid forming a disulfide with?
Size other_neighbor_id( Size resid ) const;
DisulfideAtomIndices const &
disulfide_atom_indices( Size resid ) const;
DisulfideAtomIndices const &
other_neighbor_atom_indices( Size resid ) const;
// Read and write access granted to Disulf Iterators. Other classes should not use these methods.
public:
// Mutators
void save_energy( Size disulfide_index, EnergyMap const & emap );
void mark_energy_computed( Size disulfide_index );
void mark_energy_uncomputed( Size disulfide_index );
// Accessors
Size lower_neighbor_id( Size disulfide_index ) const;
Size upper_neighbor_id( Size disulfide_index ) const;
Size other_neighbor_id( Size disulfide_index, Size resid ) const;
void accumulate_energy( Size disulfide_index, EnergyMap & emap ) const;
void retrieve_energy( Size disulfide_index, EnergyMap & emap ) const;
bool energy_computed( Size disulfide_index ) const;
Size num_residues() const;
private:
void find_disulfides( pose::Pose const & pose );
bool disulfides_changed( pose::Pose const & pose );
Size num_disulfides() const;
private:
utility::vector1< Size > resid_2_disulfide_index_;
utility::vector1< chemical::ResidueTypeCOP > disulfide_residue_types_;
utility::vector1< std::pair< Size, Size > > disulfide_partners_;
utility::vector1< std::pair< DisulfideAtomIndices, DisulfideAtomIndices > > disulfide_atom_indices_;
utility::vector1< std::pair< FullatomDisulfideEnergyComponents, bool > > disulfide_info_;
#ifdef SERIALIZATION
public:
template< class Archive > void save( Archive & arc ) const;
template< class Archive > void load( Archive & arc );
#endif // SERIALIZATION
};
}
}
}
#ifdef SERIALIZATION
CEREAL_FORCE_DYNAMIC_INIT( core_scoring_disulfides_FullatomDisulfideEnergyContainer )
#endif // SERIALIZATION
#endif
| [
"lzhangbk@connect.ust.hk"
] | lzhangbk@connect.ust.hk |
de947a0c64d4a64437ca40d0a384fa4797d63d76 | 4a2d8cbabd712cf614608775385c9ce9e4b9ebbd | /Lesther_Reynoso_GHP_6.cpp | 3da3cf6df5eb212e46b17e44020fd14e5bec72b1 | [] | no_license | lestherreynoso/SUNYIT-CS-240 | 7f85ab73624ef6df90cce4b3da441a7568a5362d | ae597ea87d0e31ff25fb2d4a1860fcd0d7ff8d14 | refs/heads/master | 2020-05-17T17:23:01.706937 | 2014-05-21T07:28:43 | 2014-05-21T07:28:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 847 | cpp | /* Program to take a non negative integer and place commas in the
correct locations
Written by Lesther Reynoso
April 2011
Language C++ <g++ target>
*/
#include <iostream>
#include <string>
using namespace std;
string comma(string num);
int length, times, n;
int main(void)
{ string number;
string newnum;
cout<<"Enter a non negative integer greater than 999 to place commas in: ";
cin>>number;
length=number.length();
if ((length%3)!=0)
times=(length/3);
else
times=(length/3)-1;
n=0;
newnum=comma(number);
cout<<newnum<<endl;
return 0;
}
string comma(string num)
/* Recursive function to insert commas
Written by Lesther Reynoso
April 2011
Language C++ <g++ target>
*/
{ n=n+3;
while (times!=0)
{ num.insert(num.end()-n,',');
n=n+1;
times=times-1;
return(comma(num));
}
return(num);
}
| [
"reynosl@sunyit.edu"
] | reynosl@sunyit.edu |
828eb89cf7f2e283ee70201b4b4ee097c6a8167c | 950cf3aaa0f3af597972ee1f0dc223aa8ac4b8a5 | /200428_MemRepair/200428_MemRepair/main.cpp | 2f5fb1994365fecf15e6ed57bd34cd5d6734d97b | [] | no_license | Zhangddy/Win32_Project | 315f366d9fc1db5fe3d918411118552608cdfb1f | f9d529b4bde8d79890ada00bedee1bbe4a732b47 | refs/heads/master | 2022-04-26T04:46:33.356018 | 2020-04-29T10:38:26 | 2020-04-29T10:38:26 | 258,665,200 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,063 | cpp | #include "MemRepair.h"
HANDLE g_hProcess;
unordered_set<DWORD> g_HashMap;
int main()
{
// wchar_t szFileName[] = L"D:\\Code\\Cpp_program\\200428_test\\Debug\\200428_test.exe";
ShowProcess();
DWORD ProcessID;
cout << "Input ProcessID: ";
cin >> ProcessID;
g_hProcess = FindProcess(ProcessID);
cout << endl << "-----------------------------" << endl;
int val;
cout << "Input val = ";
cin >> val;
FindFirst(val);
ShowHash();
cout << endl << "----------------" << endl;
size_t countAddr = 0;
while (g_HashMap.size() > 1 && countAddr != g_HashMap.size())
{
countAddr = g_HashMap.size();
cout << "Input val = ";
cin >> val;
FindNext(val);
if (FindNext == false)
{
cout << "找不到此数据! " << endl;
return -1;
}
ShowHash();
cout << "----------------" << endl;
}
cout << "Input new val = ";
cin >> val;
auto it = g_HashMap.begin();
while (it != g_HashMap.end())
{
if (WriteMemory(*it, val))
{
cout << "Write data success!" << endl;
}
else
{
cout << "Write data fail!" << endl;
}
it++;
}
return 0;
}
//int main()
//{
// // wchar_t szFileName[] = L"D:\\Code\\Cpp_program\\200428_test\\Debug\\200428_test.exe";
// wchar_t szFileName[] = L"D:\\game\\GHra2-china\\ra2.exe";
//
// STARTUPINFO si = { sizeof(si) };
// PROCESS_INFORMATION pi;
// BOOL bRet = CreateProcess(NULL, szFileName, NULL, NULL, FALSE
// , 0, NULL, NULL, &si, &pi);
// cout << "bRet: " << bRet << endl;
// system("pause");
// CloseHandle(pi.hThread);
// g_hProcess = pi.hProcess;
//
// int val;
// cout << "Input val = ";
// cin >> val;
// FindFirst(val);
// ShowHash();
// cout << "----------------" << endl;
// while (g_HashMap.size() > 1)
// {
// cout << "Input val = ";
// cin >> val;
//
// FindNext(val);
//
// ShowHash();
// cout << "----------------" << endl;
// }
//
// cout << "Input new val = ";
// cin >> val;
// auto it = g_HashMap.begin();
//
// if (WriteMemory(*it, val))
// {
// cout << "Write data success!" << endl;
// }
// else
// {
// cout << "Write data fail!" << endl;
// }
//
// return 0;
//} | [
"530281461@qq.com"
] | 530281461@qq.com |
0636b0410185168f6bfd95e7ffdba833eb7cbe19 | 5c3dc8991d5bb766fafa33045f8eebe7cc2759f0 | /DataStructures/Vector.tpp | 202fb86733c8eb802c8e9580af7316b02a71fb62 | [] | no_license | chrisb2244/cfd-solver | 473b863f9ef852011de1794de4dcb13f7dbcf77a | 924b3ce340457a877748168094fc5fdd20287bdd | refs/heads/master | 2021-01-10T13:38:42.247228 | 2015-10-16T02:58:01 | 2015-10-16T02:59:04 | 43,545,054 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,599 | tpp | /* ---------------------------------------------------------------------------
* Vector class to be used for examining particular values or extracting
* vectors at a point in a field, or alternatively holding positions in space
*
* Don't intend to use this for the data type of a Field, as would require the
* construction of a huge number of Vector objects, which I expect would be
* slow
* --------------------------------------------------------------------------*/
#ifndef VECTOR_H
#define VECTOR_H
#include "TemplateFunctions.H"
#include <array>
template<typename T, size_t D>
class Vector
{
public:
// Default constructor (needed?)
Vector():
value_(std::array<T,D>())
{}
// Construct from literal values
template<typename... Vals, EnableIf<areT<T, Vals...>::value>..., EnableIf<sizeof...(Vals)==D>...>
Vector(Vals... vals):
value_(std::array<T,D>{vals...})
{}
template<size_t vecD = D, EnableIf<vecD>=1>...>
T &x() { return value_[0]; }
template<size_t vecD = D, EnableIf<vecD>=2>...>
T &y() { return value_[1]; }
template<size_t vecD = D, EnableIf<vecD>=3>...>
T &z() { return value_[2]; }
private:
std::array<T, D> value_;
};
template<typename T>
class Vector<T, 1>
{
public:
Vector():
value_()
{}
Vector(T val):
value_(val)
{}
void operator=(const T &val) { value_ = val; }
Vector<T, 1>& operator+=(const T &rhs) { value_ += rhs; return *this; }
T &x() { return value_; } // To satisfy vectorField when mD == 1
private:
T value_;
};
#endif // VECTOR_H
| [
"chrisb2244@gmail.com"
] | chrisb2244@gmail.com |
33d28bf38f1e90efb451c814899d125f8de49791 | 841205b28a8c9553eb41943954690cb4fc1ddd0e | /curators_behavior/src/DataRepresentation.h | 9499b718228d70430b05141bade38d369a76d856 | [
"MIT"
] | permissive | Snedashkovsky/golos-analytics | 2b160b7ccf9b40cb76145a33e07f3969fc8be232 | 0da3784701db0db1df12f6a3b68ec36ba124ad9d | refs/heads/master | 2021-09-23T20:13:14.794436 | 2018-09-27T08:38:40 | 2018-09-27T08:38:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,265 | h | #ifndef DATAREPRESENTATION_H_
#define DATAREPRESENTATION_H_
#include <string>
#include <map>
#include <vector>
#include "gnuplot-iostream.h"
//-lboost_iostreams -lboost_system -lboost_filesystem
class ProjectedDataRepresentation
{
public:
using ProjectionStruct = std::pair<std::string, std::vector<std::string> >;
using PointStruct = std::vector<ProjectionStruct>;
protected:
struct Projection
{
std::string _name;
std::vector<std::string> _coords;
std::vector<std::vector<double> > _data;
Projection(size_t pointsNum, const std::string& name, const std::vector<std::string>& coords);
};
std::map<std::string, size_t> _nameToProj;
std::vector<Projection> _projs;
size_t _pointsNum;
bool _colored;
PointStruct _pointStruct;
size_t _maxRegisteredPoint;
size_t _curPoint;
void resize();
public:
ProjectedDataRepresentation():
_pointsNum(0), _colored(false), _maxRegisteredPoint(0), _curPoint(0) {};
void init(const PointStruct& pointStruct, bool colored){_pointStruct = pointStruct; _colored = colored;};
void startSending(){_curPoint = 0;};
void next(){++_curPoint;};
void set(const std::string& projName,
const std::vector<double>&& data);//last value in data is reserved for group id
virtual void show() = 0;
virtual ~ProjectedDataRepresentation(){};
size_t getPointsNum()const {return _pointsNum;};
};
class MeanToConsole : public ProjectedDataRepresentation
{
public:
void show() override;
};
class GnuplotDisplay final: public ProjectedDataRepresentation
{
static constexpr std::array<const char*, 2> DIM_NAMES = {"x", "y"};
Gnuplot _gnuplot;
std::vector<std::vector<std::pair<double, double> > > _ranges;
double _zoomInBorder;
double _zoomOutFactor;
size_t _pointType;
const bool _multiplotMode;
std::string _name;
size_t _rowSize;
void updateRanges();
void showMultiplot();
void showSingleplot();
std::string getPointsStr() const;
public:
GnuplotDisplay(const std::string& name, double zoomInBorder, double zoomOutFactor, size_t pointType, bool multiplotMode = true, size_t rowSize = 0):
_zoomInBorder(zoomInBorder), _zoomOutFactor(zoomOutFactor), _pointType(pointType), _multiplotMode(multiplotMode),
_name(name), _rowSize(rowSize){};
void show() override;
};
#endif /* DATAREPRESENTATION_H_ */
| [
"vadimkaynarov@gmail.com"
] | vadimkaynarov@gmail.com |
e1bad64c2aa06eed3776e90f66632682b3a05962 | 1d9df1156e49f768ed2633641075f4c307d24ad2 | /third_party/WebKit/Source/core/page/FocusController.h | d81f225071216e7775e2b1b4dfd7e6e09b287701 | [
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"MIT",
"Apache-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft"
] | permissive | GSIL-Monitor/platform.framework.web.chromium-efl | 8056d94301c67a8524f6106482087fd683c889ce | e156100b0c5cfc84c19de612dbdb0987cddf8867 | refs/heads/master | 2022-10-26T00:23:44.061873 | 2018-10-30T03:41:51 | 2018-10-30T03:41:51 | 161,171,104 | 0 | 1 | BSD-3-Clause | 2022-10-20T23:50:20 | 2018-12-10T12:24:06 | C++ | UTF-8 | C++ | false | false | 5,184 | h | /*
* Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. 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.
*/
#ifndef FocusController_h
#define FocusController_h
#include "core/CoreExport.h"
#include "platform/geometry/LayoutRect.h"
#include "platform/heap/Handle.h"
#include "platform/wtf/Forward.h"
#include "platform/wtf/Noncopyable.h"
#include "platform/wtf/RefPtr.h"
#include "public/platform/WebFocusType.h"
namespace blink {
struct FocusCandidate;
struct FocusParams;
class ContainerNode;
class Document;
class Element;
class FocusChangedObserver;
class Frame;
class HTMLFrameOwnerElement;
class InputDeviceCapabilities;
class LocalFrame;
class Node;
class Page;
class RemoteFrame;
class CORE_EXPORT FocusController final
: public GarbageCollected<FocusController> {
WTF_MAKE_NONCOPYABLE(FocusController);
public:
using OwnerMap = HeapHashMap<Member<ContainerNode>, Member<Element>>;
static FocusController* Create(Page*);
void SetFocusedFrame(Frame*, bool notify_embedder = true);
void FocusDocumentView(Frame*, bool notify_embedder = true);
LocalFrame* FocusedFrame() const;
Frame* FocusedOrMainFrame() const;
// Finds the focused HTMLFrameOwnerElement, if any, in the provided frame.
// An HTMLFrameOwnerElement is considered focused if the frame it owns, or
// one of its descendant frames, is currently focused.
HTMLFrameOwnerElement* FocusedFrameOwnerElement(
LocalFrame& current_frame) const;
// Determines whether the provided Document has focus according to
// http://www.w3.org/TR/html5/editing.html#dom-document-hasfocus
bool IsDocumentFocused(const Document&) const;
bool SetInitialFocus(WebFocusType);
bool AdvanceFocus(WebFocusType type,
InputDeviceCapabilities* source_capabilities = nullptr) {
return AdvanceFocus(type, false, source_capabilities);
}
bool AdvanceFocusAcrossFrames(
WebFocusType,
RemoteFrame* from,
LocalFrame* to,
InputDeviceCapabilities* source_capabilities = nullptr);
Element* FindFocusableElementInShadowHost(const Element& shadow_host);
Element* NextFocusableElementInForm(Element*, WebFocusType);
bool SetFocusedElement(Element*, Frame*, const FocusParams&);
// |setFocusedElement| variant with SelectionBehaviorOnFocus::None,
// |WebFocusTypeNone, and null InputDeviceCapabilities.
bool SetFocusedElement(Element*, Frame*);
void SetActive(bool);
bool IsActive() const { return is_active_; }
void SetFocused(bool);
bool IsFocused() const { return is_focused_; }
void RegisterFocusChangedObserver(FocusChangedObserver*);
#if defined(OS_TIZEN_TV_PRODUCT)
bool AdvanceCSSNavigationFocus(WebFocusType);
#endif
DECLARE_TRACE();
private:
explicit FocusController(Page*);
Element* FindFocusableElement(WebFocusType, Element&, OwnerMap&);
bool AdvanceFocus(WebFocusType,
bool initial_focus,
InputDeviceCapabilities* source_capabilities = nullptr);
bool AdvanceFocusDirectionally(WebFocusType);
bool AdvanceFocusInDocumentOrder(
LocalFrame*,
Element* start,
WebFocusType,
bool initial_focus,
InputDeviceCapabilities* source_capabilities);
bool AdvanceFocusDirectionallyInContainer(Node* container,
const LayoutRect& starting_rect,
WebFocusType);
void FindFocusCandidateInContainer(Node& container,
const LayoutRect& starting_rect,
WebFocusType,
FocusCandidate& closest);
void NotifyFocusChangedObservers() const;
Member<Page> page_;
Member<Frame> focused_frame_;
bool is_active_;
bool is_focused_;
bool is_changing_focused_frame_;
HeapHashSet<WeakMember<FocusChangedObserver>> focus_changed_observers_;
};
} // namespace blink
#endif // FocusController_h
| [
"RetZero@desktop"
] | RetZero@desktop |
a774c5980f842dba6461876c41e90eec63836b81 | 266a11a367068953ec83d56405dfcfa7455625cf | /ChernoCpp/TemplateDemo.hpp | 716c19c29e6327f07d2845b696393f43c348dc23 | [] | no_license | goeltanu1986/ChernoCpp | 14528f6b3559ccad523c43b039291b9f897f8915 | 6400a7fd2e714024d28714357bd9f10e060e90e0 | refs/heads/main | 2023-01-14T10:21:18.271275 | 2020-11-22T19:13:25 | 2020-11-22T19:13:25 | 315,112,327 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 358 | hpp | //
// TemplateDemo.hpp
// ChernoCpp
//
// Created by Tanu Goel on 7/21/20.
// Copyright © 2020 None. All rights reserved.
//
#ifndef TemplateDemo_hpp
#define TemplateDemo_hpp
#include <stdio.h>
template <typename t>
class Array
{
t *start;
int size;
public:
Array(t arr[], int s);
void print();
};
#endif /* TemplateDemo_hpp */
| [
"30600387+goeltanu1986@users.noreply.github.com"
] | 30600387+goeltanu1986@users.noreply.github.com |
55a206dcf1c9b51502e74c61c8731e26451dfabf | 021cd4714a0afc680292191c8a4a8e34fc2c6bd4 | /src/core/NEON/kernels/NETransposeKernel.cpp | 492de8a6eea7d7ee258e08fb889ebe85565eb1a7 | [
"MIT"
] | permissive | liangdong-xjtu/ComputeLibrary | af6476dd926740ec12f394ccddf2d7faccbda609 | 8fbb5a59206e5a83b7ed3fa88deca9a8c1666786 | refs/heads/master | 2021-01-18T15:30:42.933987 | 2017-08-15T13:25:19 | 2017-08-15T13:25:19 | 100,378,810 | 1 | 0 | null | 2017-08-15T13:13:27 | 2017-08-15T13:13:27 | null | UTF-8 | C++ | false | false | 12,886 | cpp | /*
* Copyright (c) 2017 ARM Limited.
*
* SPDX-License-Identifier: MIT
*
* 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 "arm_compute/core/NEON/kernels/NETransposeKernel.h"
#include "arm_compute/core/AccessWindowTranspose.h"
#include "arm_compute/core/Error.h"
#include "arm_compute/core/Helpers.h"
#include "arm_compute/core/ITensor.h"
#include "arm_compute/core/Validate.h"
#include <arm_neon.h>
using namespace arm_compute;
namespace arm_compute
{
class Coordinates;
} // namespace arm_compute
namespace
{
void transpose_8bit_elements(const ITensor *in, ITensor *out, const Window &window)
{
Window window_out(window);
window_out.set(Window::DimX, Window::Dimension(0, 0, 0));
window_out.set(Window::DimY, Window::Dimension(0, 0, 0));
Iterator input(in, window);
Iterator output(out, window_out);
const size_t input_stride_in_bytes = in->info()->strides_in_bytes()[1];
const size_t output_stride_in_bytes = out->info()->strides_in_bytes()[1];
execute_window_loop(window, [&](const Coordinates & id)
{
const uint8x8_t row0 = vld1_u8(reinterpret_cast<const uint8_t *>(input.ptr() + 0 * input_stride_in_bytes));
const uint8x8_t row1 = vld1_u8(reinterpret_cast<const uint8_t *>(input.ptr() + 1 * input_stride_in_bytes));
const uint8x8_t row2 = vld1_u8(reinterpret_cast<const uint8_t *>(input.ptr() + 2 * input_stride_in_bytes));
const uint8x8_t row3 = vld1_u8(reinterpret_cast<const uint8_t *>(input.ptr() + 3 * input_stride_in_bytes));
const uint8x8_t row4 = vld1_u8(reinterpret_cast<const uint8_t *>(input.ptr() + 4 * input_stride_in_bytes));
const uint8x8_t row5 = vld1_u8(reinterpret_cast<const uint8_t *>(input.ptr() + 5 * input_stride_in_bytes));
const uint8x8_t row6 = vld1_u8(reinterpret_cast<const uint8_t *>(input.ptr() + 6 * input_stride_in_bytes));
const uint8x8_t row7 = vld1_u8(reinterpret_cast<const uint8_t *>(input.ptr() + 7 * input_stride_in_bytes));
// Transpose 2x2
const uint8x8x2_t k0_u8 = vtrn_u8(row0, row1);
const uint8x8x2_t k1_u8 = vtrn_u8(row2, row3);
const uint8x8x2_t k2_u8 = vtrn_u8(row4, row5);
const uint8x8x2_t k3_u8 = vtrn_u8(row6, row7);
// Transpose 4x4
const uint16x4x2_t k0_u16 = vtrn_u16(vreinterpret_u16_u8(k0_u8.val[0]), vreinterpret_u16_u8(k1_u8.val[0]));
const uint16x4x2_t k1_u16 = vtrn_u16(vreinterpret_u16_u8(k0_u8.val[1]), vreinterpret_u16_u8(k1_u8.val[1]));
const uint16x4x2_t k2_u16 = vtrn_u16(vreinterpret_u16_u8(k2_u8.val[0]), vreinterpret_u16_u8(k3_u8.val[0]));
const uint16x4x2_t k3_u16 = vtrn_u16(vreinterpret_u16_u8(k2_u8.val[1]), vreinterpret_u16_u8(k3_u8.val[1]));
// Transpose 8x8
const uint32x2x2_t k0_u32 = vtrn_u32(vreinterpret_u32_u16(k0_u16.val[0]), vreinterpret_u32_u16(k2_u16.val[0]));
const uint32x2x2_t k1_u32 = vtrn_u32(vreinterpret_u32_u16(k0_u16.val[1]), vreinterpret_u32_u16(k2_u16.val[1]));
const uint32x2x2_t k2_u32 = vtrn_u32(vreinterpret_u32_u16(k1_u16.val[0]), vreinterpret_u32_u16(k3_u16.val[0]));
const uint32x2x2_t k3_u32 = vtrn_u32(vreinterpret_u32_u16(k1_u16.val[1]), vreinterpret_u32_u16(k3_u16.val[1]));
// Compute destination address
const size_t dst_offset_in_bytes = id.y() * sizeof(uint8_t) + id.x() * output_stride_in_bytes;
vst1_u8(reinterpret_cast<uint8_t *>(output.ptr() + dst_offset_in_bytes + 0 * output_stride_in_bytes), vreinterpret_u8_u16(vreinterpret_u16_u32(k0_u32.val[0])));
vst1_u8(reinterpret_cast<uint8_t *>(output.ptr() + dst_offset_in_bytes + 1 * output_stride_in_bytes), vreinterpret_u8_u16(vreinterpret_u16_u32(k2_u32.val[0])));
vst1_u8(reinterpret_cast<uint8_t *>(output.ptr() + dst_offset_in_bytes + 2 * output_stride_in_bytes), vreinterpret_u8_u16(vreinterpret_u16_u32(k1_u32.val[0])));
vst1_u8(reinterpret_cast<uint8_t *>(output.ptr() + dst_offset_in_bytes + 3 * output_stride_in_bytes), vreinterpret_u8_u16(vreinterpret_u16_u32(k3_u32.val[0])));
vst1_u8(reinterpret_cast<uint8_t *>(output.ptr() + dst_offset_in_bytes + 4 * output_stride_in_bytes), vreinterpret_u8_u16(vreinterpret_u16_u32(k0_u32.val[1])));
vst1_u8(reinterpret_cast<uint8_t *>(output.ptr() + dst_offset_in_bytes + 5 * output_stride_in_bytes), vreinterpret_u8_u16(vreinterpret_u16_u32(k2_u32.val[1])));
vst1_u8(reinterpret_cast<uint8_t *>(output.ptr() + dst_offset_in_bytes + 6 * output_stride_in_bytes), vreinterpret_u8_u16(vreinterpret_u16_u32(k1_u32.val[1])));
vst1_u8(reinterpret_cast<uint8_t *>(output.ptr() + dst_offset_in_bytes + 7 * output_stride_in_bytes), vreinterpret_u8_u16(vreinterpret_u16_u32(k3_u32.val[1])));
},
input, output);
}
void transpose_16bit_elements(const ITensor *in, ITensor *out, const Window &window)
{
Window window_out(window);
window_out.set(Window::DimX, Window::Dimension(0, 0, 0));
window_out.set(Window::DimY, Window::Dimension(0, 0, 0));
Iterator input(in, window);
Iterator output(out, window_out);
const size_t input_stride_in_bytes = in->info()->strides_in_bytes()[1];
const size_t output_stride_in_bytes = out->info()->strides_in_bytes()[1];
execute_window_loop(window, [&](const Coordinates & id)
{
const uint16x4_t row0 = vld1_u16(reinterpret_cast<const uint16_t *>(input.ptr() + 0 * input_stride_in_bytes));
const uint16x4_t row1 = vld1_u16(reinterpret_cast<const uint16_t *>(input.ptr() + 1 * input_stride_in_bytes));
const uint16x4_t row2 = vld1_u16(reinterpret_cast<const uint16_t *>(input.ptr() + 2 * input_stride_in_bytes));
const uint16x4_t row3 = vld1_u16(reinterpret_cast<const uint16_t *>(input.ptr() + 3 * input_stride_in_bytes));
// Transpose 2x2
const uint16x4x2_t k0_u16 = vtrn_u16(row0, row1);
const uint16x4x2_t k1_u16 = vtrn_u16(row2, row3);
// Transpose 4x4
const uint32x2x2_t k0_u32 = vtrn_u32(vreinterpret_u32_u16(k0_u16.val[0]), vreinterpret_u32_u16(k1_u16.val[0]));
const uint32x2x2_t k1_u32 = vtrn_u32(vreinterpret_u32_u16(k0_u16.val[1]), vreinterpret_u32_u16(k1_u16.val[1]));
// Compute destination address
const size_t dst_offset_in_bytes = id.y() * sizeof(uint16_t) + id.x() * output_stride_in_bytes;
vst1_u16(reinterpret_cast<uint16_t *>(output.ptr() + dst_offset_in_bytes + 0 * output_stride_in_bytes), vreinterpret_u16_u32(k0_u32.val[0]));
vst1_u16(reinterpret_cast<uint16_t *>(output.ptr() + dst_offset_in_bytes + 1 * output_stride_in_bytes), vreinterpret_u16_u32(k1_u32.val[0]));
vst1_u16(reinterpret_cast<uint16_t *>(output.ptr() + dst_offset_in_bytes + 2 * output_stride_in_bytes), vreinterpret_u16_u32(k0_u32.val[1]));
vst1_u16(reinterpret_cast<uint16_t *>(output.ptr() + dst_offset_in_bytes + 3 * output_stride_in_bytes), vreinterpret_u16_u32(k1_u32.val[1]));
},
input, output);
}
void transpose_32bit_elements(const ITensor *in, ITensor *out, const Window &window)
{
Window window_out(window);
window_out.set(Window::DimX, Window::Dimension(0, 0, 0));
window_out.set(Window::DimY, Window::Dimension(0, 0, 0));
Iterator input(in, window);
Iterator output(out, window_out);
const size_t input_stride_in_bytes = in->info()->strides_in_bytes()[1];
const size_t output_stride_in_bytes = out->info()->strides_in_bytes()[1];
execute_window_loop(window, [&](const Coordinates & id)
{
const uint32x4_t row0 = vld1q_u32(reinterpret_cast<const uint32_t *>(input.ptr() + 0 * input_stride_in_bytes));
const uint32x4_t row1 = vld1q_u32(reinterpret_cast<const uint32_t *>(input.ptr() + 1 * input_stride_in_bytes));
const uint32x4_t row2 = vld1q_u32(reinterpret_cast<const uint32_t *>(input.ptr() + 2 * input_stride_in_bytes));
const uint32x4_t row3 = vld1q_u32(reinterpret_cast<const uint32_t *>(input.ptr() + 3 * input_stride_in_bytes));
// Transpose 2x2
const uint32x2x2_t k0_u32 = vtrn_u32(vget_low_u32(row0), vget_low_u32(row1));
const uint32x2x2_t k1_u32 = vtrn_u32(vget_high_u32(row2), vget_high_u32(row3));
const uint32x2x2_t k2_u32 = vtrn_u32(vget_high_u32(row0), vget_high_u32(row1));
const uint32x2x2_t k3_u32 = vtrn_u32(vget_low_u32(row2), vget_low_u32(row3));
// Compute destination address
const size_t dst_offset_in_bytes = id.y() * sizeof(uint32_t) + id.x() * output_stride_in_bytes;
// Swap block 01 with block 10 and store
vst1q_u32(reinterpret_cast<uint32_t *>(output.ptr() + dst_offset_in_bytes + 0 * output_stride_in_bytes), vcombine_u32(k0_u32.val[0], k3_u32.val[0]));
vst1q_u32(reinterpret_cast<uint32_t *>(output.ptr() + dst_offset_in_bytes + 1 * output_stride_in_bytes), vcombine_u32(k0_u32.val[1], k3_u32.val[1]));
vst1q_u32(reinterpret_cast<uint32_t *>(output.ptr() + dst_offset_in_bytes + 2 * output_stride_in_bytes), vcombine_u32(k2_u32.val[0], k1_u32.val[0]));
vst1q_u32(reinterpret_cast<uint32_t *>(output.ptr() + dst_offset_in_bytes + 3 * output_stride_in_bytes), vcombine_u32(k2_u32.val[1], k1_u32.val[1]));
},
input, output);
}
} // namespace
NETransposeKernel::NETransposeKernel()
: _func(nullptr), _input(nullptr), _output(nullptr)
{
}
void NETransposeKernel::configure(const ITensor *input, ITensor *output)
{
ARM_COMPUTE_ERROR_ON_DATA_TYPE_CHANNEL_NOT_IN(input, 1, DataType::U8, DataType::S8, DataType::QS8, DataType::U16, DataType::S16, DataType::U32, DataType::S32, DataType::F16, DataType::F32);
ARM_COMPUTE_ERROR_ON(output == nullptr);
TensorShape output_shape{ input->info()->tensor_shape() };
const size_t w_out = input->info()->dimension(1);
const size_t h_out = input->info()->dimension(0);
output_shape.set(0, w_out);
output_shape.set(1, h_out);
// Output tensor auto inizialitation if not yet initialized
auto_init_if_empty(*output->info(), output_shape, 1, input->info()->data_type(), input->info()->fixed_point_position());
ARM_COMPUTE_ERROR_ON_MISMATCHING_DATA_TYPES(input, output);
ARM_COMPUTE_ERROR_ON_MISMATCHING_DIMENSIONS(output->info()->tensor_shape(), output_shape);
_input = input;
_output = output;
unsigned int num_elems_processed_per_iteration = 0;
switch(input->info()->element_size())
{
case 1:
_func = &transpose_8bit_elements;
num_elems_processed_per_iteration = 8;
break;
case 2:
_func = &transpose_16bit_elements;
num_elems_processed_per_iteration = 4;
break;
case 4:
_func = &transpose_32bit_elements;
num_elems_processed_per_iteration = 4;
break;
default:
ARM_COMPUTE_ERROR("Element size not supported");
break;
}
// Configure kernel window
Window win = calculate_max_window(*input->info(), Steps(num_elems_processed_per_iteration, num_elems_processed_per_iteration));
AccessWindowTranspose output_access(output->info(), 0, 0, num_elems_processed_per_iteration, num_elems_processed_per_iteration);
update_window_and_padding(win,
AccessWindowRectangle(input->info(), 0, 0, num_elems_processed_per_iteration, num_elems_processed_per_iteration),
output_access);
output_access.set_valid_region(win, input->info()->valid_region());
INEKernel::configure(win);
}
void NETransposeKernel::run(const Window &window)
{
ARM_COMPUTE_ERROR_ON_UNCONFIGURED_KERNEL(this);
ARM_COMPUTE_ERROR_ON_INVALID_SUBWINDOW(INEKernel::window(), window);
ARM_COMPUTE_ERROR_ON(_func == nullptr);
(*_func)(_input, _output, window);
}
| [
"anthony.barbier@arm.com"
] | anthony.barbier@arm.com |
e815871b29d6be2b4b886a136aa722d9e59f87f8 | fc8c9b04739cb649380acd15779cbff9d7fa6917 | /src/lib/gtkmm-3.0/gtkmm/treedragsource.h | fbab8c996ff632fb94e1ba4ae61218be89499b2c | [] | no_license | vasychan/MTSClient | 4bc6ac54ff8ca2de316ded546e7af6981f66f38c | 1355a566d66f33b4bbdfb850ff5927807745b49d | refs/heads/master | 2021-01-22T13:42:11.719567 | 2012-07-17T06:48:18 | 2012-07-17T06:48:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,911 | h | // -*- c++ -*-
// Generated by gtkmmproc -- DO NOT MODIFY!
#ifndef _GTKMM_TREEDRAGSOURCE_H
#define _GTKMM_TREEDRAGSOURCE_H
#include <glibmm/ustring.h>
#include <sigc++/sigc++.h>
/* $Id: treedragsource.hg,v 1.8 2006/05/10 20:59:28 murrayc Exp $ */
/* Copyright (C) 1998-2002 The gtkmm Development Team
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <glibmm/interface.h>
#include <gtkmm/treemodel.h>
#include <gtkmm/selectiondata.h>
#ifndef DOXYGEN_SHOULD_SKIP_THIS
extern "C"
{
typedef struct _GtkTreeDragSourceIface GtkTreeDragSourceIface;
typedef struct _GtkSelectionData GtkSelectionData;
}
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
#ifndef DOXYGEN_SHOULD_SKIP_THIS
typedef struct _GtkTreeDragSource GtkTreeDragSource;
typedef struct _GtkTreeDragSourceClass GtkTreeDragSourceClass;
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
namespace Gtk
{ class TreeDragSource_Class; } // namespace Gtk
namespace Gtk
{
/**
* @ingroup TreeView
*/
class TreeDragSource : public Glib::Interface
{
#ifndef DOXYGEN_SHOULD_SKIP_THIS
public:
typedef TreeDragSource CppObjectType;
typedef TreeDragSource_Class CppClassType;
typedef GtkTreeDragSource BaseObjectType;
typedef GtkTreeDragSourceIface BaseClassType;
private:
friend class TreeDragSource_Class;
static CppClassType treedragsource_class_;
// noncopyable
TreeDragSource(const TreeDragSource&);
TreeDragSource& operator=(const TreeDragSource&);
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
protected:
/**
* You should derive from this class to use it.
*/
TreeDragSource();
#ifndef DOXYGEN_SHOULD_SKIP_THIS
/** Called by constructors of derived classes. Provide the result of
* the Class init() function to ensure that it is properly
* initialized.
*
* @param interface_class The Class object for the derived type.
*/
explicit TreeDragSource(const Glib::Interface_Class& interface_class);
public:
// This is public so that C++ wrapper instances can be
// created for C instances of unwrapped types.
// For instance, if an unexpected C type implements the C interface.
explicit TreeDragSource(GtkTreeDragSource* castitem);
protected:
#endif /* DOXYGEN_SHOULD_SKIP_THIS */
public:
virtual ~TreeDragSource();
static void add_interface(GType gtype_implementer);
#ifndef DOXYGEN_SHOULD_SKIP_THIS
static GType get_type() G_GNUC_CONST;
static GType get_base_type() G_GNUC_CONST;
#endif
///Provides access to the underlying C GObject.
GtkTreeDragSource* gobj() { return reinterpret_cast<GtkTreeDragSource*>(gobject_); }
///Provides access to the underlying C GObject.
const GtkTreeDragSource* gobj() const { return reinterpret_cast<GtkTreeDragSource*>(gobject_); }
private:
public:
/** Asks the Gtk::TreeDragSource whether a particular row can be used as
* the source of a DND operation. If the source doesn't implement
* this interface, the row is assumed draggable.
* @param path Row on which user is initiating a drag.
* @return <tt>true</tt> if the row can be dragged.
*/
bool row_draggable(const TreeModel::Path& path) const;
/** Asks the Gtk::TreeDragSource to fill in @a selection_data with a
* representation of the row at @a path. @a selection_data->target gives
* the required type of the data. Should robustly handle a @a path no
* longer found in the model!
* @param path Row that was dragged.
* @param selection_data A Gtk::SelectionData to fill with data
* from the dragged row.
* @return <tt>true</tt> if data of the required type was provided.
*/
bool drag_data_get(const TreeModel::Path& path, SelectionData& selection_data);
/** Asks the Gtk::TreeDragSource to delete the row at @a path, because
* it was moved somewhere else via drag-and-drop. Returns <tt>false</tt>
* if the deletion fails because @a path no longer exists, or for
* some model-specific reason. Should robustly handle a @a path no
* longer found in the model!
* @param path Row that was being dragged.
* @return <tt>true</tt> if the row was successfully deleted.
*/
bool drag_data_delete(const TreeModel::Path& path);
protected:
virtual bool row_draggable_vfunc(const TreeModel::Path& path) const;
//We hand-code this so that we can use a temporary instance for the SelectionData& output parameter:
virtual bool drag_data_get_vfunc(const TreeModel::Path& path, SelectionData& selection_data) const;
virtual bool drag_data_delete_vfunc(const TreeModel::Path& path);
public:
public:
//C++ methods used to invoke GTK+ virtual functions:
protected:
//GTK+ Virtual Functions (override these to change behaviour):
//Default Signal Handlers::
};
} // namespace Gtk
namespace Glib
{
/** A Glib::wrap() method for this object.
*
* @param object The C instance.
* @param take_copy False if the result should take ownership of the C instance. True if it should take a new copy or ref.
* @result A C++ instance that wraps this C instance.
*
* @relates Gtk::TreeDragSource
*/
Glib::RefPtr<Gtk::TreeDragSource> wrap(GtkTreeDragSource* object, bool take_copy = false);
} // namespace Glib
#endif /* _GTKMM_TREEDRAGSOURCE_H */
| [
"vasy.chan@gmail.com"
] | vasy.chan@gmail.com |
d157e480a26bbdb5525e09ee537f08d72c12f94d | 36126c38751d6d35d89172d829e0d8be8e860e77 | /ProjectJormag/GUISlider.h | 78936968742844b469cea824b207789125862ac3 | [] | no_license | enginmanap/Shadow-Realm | 7453f1d58098cd950d2113e9ed63b56e8aa7919e | e3df4c1c34b5382a94936bd57d3209f241d218b7 | refs/heads/master | 2020-04-03T18:09:39.100758 | 2018-10-31T00:24:27 | 2018-10-31T00:24:27 | 155,473,250 | 0 | 0 | null | 2018-10-31T00:11:34 | 2018-10-31T00:11:34 | null | UTF-8 | C++ | false | false | 574 | h | #pragma once
#ifndef GUISLIDER_H
#define GUISLIDER_H
#include "GUIObject.h"
namespace Jormag {
class GUISlider : public GUIObject {
private:
float mMin, mMax;
float mCurrent;
public:
GUISlider(float min, float max, float initValue);
GUISlider(float min, float max, float initValue, std::string backTexturePath, std::string focusTexturePath);
~GUISlider();
void Tick(unsigned int deltaTime);
void Render(SDL_Renderer* renderer);
float GetMinValue();
float GetMaxValue();
float GetCurrentValue();
void ModifyValue(float change);
};
}
#endif | [
"josh-calvert@users.noreply.github.com"
] | josh-calvert@users.noreply.github.com |
231e329574f9f75f8a74648b5082057900b59f98 | 8f36dbec492228eefe336417ab70b2b251d9ea76 | /Development/external/luabind/no_dependency.hpp | b5181dda475e41ee3552e53b12c89f897fbc243b | [] | no_license | galek/vegaEngine | a3c02d44c0502d0ded9c9db455e399eedca6bd49 | 074f7be78b9cc945241dc7469aeea8592bb50b56 | refs/heads/master | 2021-11-04T23:52:31.025799 | 2015-06-19T00:07:15 | 2015-06-19T00:07:15 | 37,155,697 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 677 | hpp | // Copyright Daniel Wallin 2010. Use, modification and distribution is
// 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 LUABIND_NO_DEPENDENCY_100324_HPP
# define LUABIND_NO_DEPENDENCY_100324_HPP
# include "detail/policy.hpp"
namespace luabind {
namespace detail
{
struct no_dependency_policy
{
static void postcall(lua_State*, int results, meta::index_list_tag)
{}
};
} // namespace detail
using no_dependency = policy_list<call_policy_injector<detail::no_dependency_policy>>;
} // namespace luabind
#endif // LUABIND_NO_DEPENDENCY_100324_HPP
| [
"nikolay.galko@gmail.com"
] | nikolay.galko@gmail.com |
e4c364fed88e025c6b32e45155703ed25a8d55cc | 1e093d2b7504956d5dede1f49938275dbc128ff1 | /inc/game_factory.h | 5c8ec1dae0522f3212d3f42e72aee83d8e51fc66 | [] | no_license | ubermouser/pokemonAI | e2a73d75d56ea568c81c7a7f717fbce7f64f5a1a | fc7589e8db5d9116d25ec83f525757551ff3aaeb | refs/heads/master | 2021-05-16T01:47:39.494081 | 2020-10-09T20:17:37 | 2020-10-09T20:17:37 | 23,047,614 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,662 | h | /*
* File: game_factory.h
* Author: drendleman
*
* Created on September 21, 2020, 8:59 PM
*/
#ifndef GAME_FACTORY_H
#define GAME_FACTORY_H
#include "true_skill.h"
#include "ranked_battlegroup.h"
class GameFactory {
public:
struct Config {
/* speed of rank propagation */
double dynamicsFactor = TrueSkill::initialMean() / 300.;
/* probability of a draw given two equal teams */
double drawProbability = 0.1;
Config(){};
};
GameFactory(const Config& cfg = Config{});
TrueSkill create(size_t numTeammates) const;
TrueSkill feather(const TrueSkill& source) const;
/* determine the quality of a match between two teams */
double matchQuality(const Battlegroup& team_a, const Battlegroup& team_b) const;
size_t update(Battlegroup& team_a, Battlegroup& team_b, const HeatResult& gResult) const;
protected:
static double calculateDrawMargin(double drawProbability, double beta);
/* determine if performance is greater than draw margin */
static double VExceedsMargin(double dPerformance, double drawMargin);
static double WExceedsMargin(double dPerformance, double drawMargin);
/* determine if performance is within margin */
static double VWithinMargin(double dPerformance, double drawMargin);
static double WWithinMargin(double dPerformance, double drawMargin);
void update_ranked(
TrueSkill& cSkill,
double v,
double w,
double c,
double cSquared,
double rankMultiplier,
double partialPlay) const;
Config cfg_;
/* equivalent to performanceStdDev squared */
double betaSquared_;
double drawMargin_;
double tauSquared_;
};
#endif /* GAME_FACTORY_H */
| [
"david.rendleman@gmail.com"
] | david.rendleman@gmail.com |
00f3183c72fbaac4825ca70df29c93873fbe6014 | 1fe4bd74391239ccd6c121cc2d733f90e0bc5753 | /release/moc_memorywindow.cpp | 501b5c13a175dad6287eb907f2a457e1f76350ec | [] | no_license | jooohny/qt-mcs-51-app | 165dbee84d035556fc4dca1900abd2b941584128 | 77bae31ee09c83c28eeba43a4f9cbb9c6d9b629e | refs/heads/master | 2022-12-09T14:40:26.574669 | 2020-07-06T12:00:27 | 2020-09-24T11:51:43 | 298,252,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,846 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'memorywindow.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.6.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../memorywindow.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'memorywindow.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.6.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_MemoryWindow_t {
QByteArrayData data[3];
char stringdata0[20];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_MemoryWindow_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_MemoryWindow_t qt_meta_stringdata_MemoryWindow = {
{
QT_MOC_LITERAL(0, 0, 12), // "MemoryWindow"
QT_MOC_LITERAL(1, 13, 5), // "erase"
QT_MOC_LITERAL(2, 19, 0) // ""
},
"MemoryWindow\0erase\0"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_MemoryWindow[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
1, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
1, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 19, 2, 0x06 /* Public */,
// signals: parameters
QMetaType::Void,
0 // eod
};
void MemoryWindow::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
MemoryWindow *_t = static_cast<MemoryWindow *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->erase(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (MemoryWindow::*_t)();
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&MemoryWindow::erase)) {
*result = 0;
return;
}
}
}
Q_UNUSED(_a);
}
const QMetaObject MemoryWindow::staticMetaObject = {
{ &QMainWindow::staticMetaObject, qt_meta_stringdata_MemoryWindow.data,
qt_meta_data_MemoryWindow, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *MemoryWindow::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *MemoryWindow::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_MemoryWindow.stringdata0))
return static_cast<void*>(const_cast< MemoryWindow*>(this));
return QMainWindow::qt_metacast(_clname);
}
int MemoryWindow::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QMainWindow::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 1)
qt_static_metacall(this, _c, _id, _a);
_id -= 1;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 1)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 1;
}
return _id;
}
// SIGNAL 0
void MemoryWindow::erase()
{
QMetaObject::activate(this, &staticMetaObject, 0, Q_NULLPTR);
}
QT_END_MOC_NAMESPACE
| [
"jooohny@bk.ru"
] | jooohny@bk.ru |
6d87b0e95c579e52905465f12c443d7ddb578def | 341fbbaa6d7e9b8cf5beba68bde5c8c1090cf3ef | /按 OJ 分类/出处遗忘/f-work2/f-work2/main.cpp | 56ff60d8ddd860850e84fcea4a2cc52fdd3562ef | [] | no_license | webturing/ACM-1 | 0ceb79e5439a95315234ae1e8bee93b353305459 | 7fcf14d1ff2ae42b001139d04bde01378fb4f5c4 | refs/heads/master | 2020-03-19T17:33:37.098619 | 2018-06-09T17:07:14 | 2018-06-09T17:07:14 | 136,766,339 | 3 | 0 | null | 2018-06-09T23:59:30 | 2018-06-09T23:59:30 | null | UTF-8 | C++ | false | false | 511 | cpp | //
// main.cpp
// f-work2
//
// Created by ZYJ on 2017/3/14.
// Copyright © 2017年 ZYJ. All rights reserved.
//
#include <iostream>
#include <string>
#include "file.hpp"
int main(int argc, const char * argv[])
{
int n;
std::cin >> n;
int *num = new int[n];
std::string text = "text.txt";
std::string in = "in.txt";
File f = File(text, n, num);
f.randDate();
f.sortDate();
File f_ = File(in, n, num);
f_.coutDate();
return 0;
}
| [
"1179754741@qq.com"
] | 1179754741@qq.com |
f2d5b291cda3909407735ee90fb24759af3efb03 | cecfda84e25466259d3ef091953c3ac7b44dc1fc | /UVa Online Judge/volume104/10406 Cutting Tabletops/program1.cpp | d71ee96908413d6b0514f1fc908e9af35c8f69bd | [] | no_license | metaphysis/Code | 8e3c3610484a8b5ca0bb116bc499a064dda55966 | d144f4026872aae45b38562457464497728ae0d6 | refs/heads/master | 2023-07-26T12:44:21.932839 | 2023-07-12T13:39:41 | 2023-07-12T13:39:41 | 53,327,611 | 231 | 57 | null | null | null | null | UTF-8 | C++ | false | false | 1,969 | cpp | // Cutting Tabletops
// UVa ID: 10406
// Verdict: Accepted
// Submission Date: 2017-12-19
// UVa Run Time: 0.000s
//
// 版权所有(C)2017,邱秋。metaphysis # yeah dot net
#include <bits/stdc++.h>
using namespace std;
struct point {
double x, y;
point (double x = 0, double y = 0): x(x), y(y) {}
point operator + (point p) { return point(x + p.x, y + p.y); };
point operator - (point p) { return point(x - p.x, y - p.y); };
point operator * (double k) { return point(x * k, y * k); };
point operator / (double k) { return point(x / k, y / k); };
};
typedef vector<point> polygon;
double norm(point a)
{
return a.x * a.x + a.y * a.y;
}
double abs(point a)
{
return sqrt(norm(a));
}
double dot(point a, point b)
{
return a.x * b.x + a.y * b.y;
}
point rotate(point p, double t)
{
return point(p.x * cos(t) - p.y * sin(t), p.x * sin(t) + p.y * cos(t));
}
point shift(point a, point b, point c, double d)
{
point u = a - b, v = c - b;
double t = acos(dot(u, v) / (abs(u) * abs(v)));
point uu = u * (d / (sin(t / 2) * abs(u)));
return b + rotate(uu, t / 2);
}
double area(polygon &pg)
{
if (pg.size() < 3) return 0.0;
double A = 0.0;
int n = pg.size();
for (int i = 0, j = (i + 1) % n; i < n; i++, j = (i + 1) % n)
A += (pg[i].x * pg[j].y - pg[j].x * pg[i].y);
return fabs(A / 2.0);
}
int main(int argc, char *argv[])
{
cin.tie(0), cout.tie(0), ios::sync_with_stdio(false);
int n;
double d;
point vertices[1010];
while (cin >> d >> n)
{
if (n == 0) break;
for (int i = 0; i < n; i++)
cin >> vertices[i].x >> vertices[i].y;
polygon pg;
for (int i = 0; i < n; i++)
{
int j = (i + 1) % n, k = (i + 2) % n;
pg.push_back(shift(vertices[i], vertices[j], vertices[k], d));
}
cout << fixed << setprecision(3) << area(pg) << '\n';
}
return 0;
}
| [
"metaphysis@yeah.net"
] | metaphysis@yeah.net |
faee0c547f0e4db052ea32c5f914ae45ed635df2 | 39e3644a3723d7cf9359e233c68e2bc11b176e01 | /692_Top K Frequent Words/Solution.h | 348d482a2fc5cf06c2c42f6a10c9e642459652c5 | [] | no_license | eashion/LeetCode | bb40b5523747d5046d2d6fa4e3bd578051689a94 | 0f09c189436b9e53274318c1264c5a7cf3c240b0 | refs/heads/master | 2021-01-12T09:10:41.426853 | 2018-07-29T06:24:39 | 2018-07-29T06:24:39 | 76,785,196 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,442 | h | struct node{
string word;
int cnt;
node(){}
node(string word, int cnt){
this->word = word;
this->cnt = cnt;
}
};
class Solution {
public:
vector<string> topKFrequent(vector<string>& words, int k) {
vector<node> lis;
vector<string> res;
unordered_map<string, int> mm;
lis.push_back(node("",INT_MAX));
for(int i = 0; i < words.size(); i++){
int pos = mm[words[i]];
if (pos!=0) {
lis[pos].cnt+=1;
doswap(lis,pos,mm);
} else {
mm[words[i]] = lis.size();
lis.push_back(node(words[i],1));
doswap(lis,lis.size()-1,mm);
}
}
for(int i = 1; i <= k; i++){
res.push_back(lis[i].word);
}
return res;
}
void doswap(vector<node>& lis, int pos, unordered_map<string, int>& mm){
if (pos==1) {
return ;
}
while(pos>1){
if (lis[pos].cnt<lis[pos-1].cnt) {
return ;
} else if (lis[pos].cnt==lis[pos-1].cnt) {
if (lis[pos].word.compare(lis[pos-1].word)>0) {
return ;
}
mm[lis[pos].word] = pos-1;
mm[lis[pos-1].word] = pos;
swap(lis[pos], lis[pos-1]);
} else {
mm[lis[pos].word] = pos-1;
mm[lis[pos-1].word] = pos;
swap(lis[pos], lis[pos-1]);
}
pos--;
}
return ;
}
};
class Solution {
public List<String> topKFrequent(String[] words, int k) {
List<String> result = new LinkedList<>();
Map<String, Integer> map = new HashMap<>();
for(int i=0; i<words.length; i++)
{
if(map.containsKey(words[i]))
map.put(words[i], map.get(words[i])+1);
else
map.put(words[i], 1);
}
PriorityQueue<Map.Entry<String, Integer>> pq = new PriorityQueue<>(
(a,b) -> a.getValue()==b.getValue() ? b.getKey().compareTo(a.getKey()) : a.getValue()-b.getValue()
);
for(Map.Entry<String, Integer> entry: map.entrySet())
{
pq.offer(entry);
if(pq.size()>k)
pq.poll();
}
while(!pq.isEmpty())
result.add(0, pq.poll().getKey());
return result;
}
}
| [
"noreply@github.com"
] | eashion.noreply@github.com |
6ef992a8aacafb3701e01d980fd9faf43e879e89 | 07170185c836f4fc05f396e270a7a8b4fa9acb5e | /data-structures/queue/queue.cpp | 39776202763dd7c7cd27ddf4085995d88049bcc3 | [] | no_license | ashokv915/data-structures-and-algorithms | 8d66f1c0a66d2a1264278556f4ed279738f19b3b | c25114d88690c87e0eca5c30b4c71b2766b2ff1b | refs/heads/master | 2023-04-13T00:21:14.016835 | 2021-04-12T19:33:23 | 2021-04-12T19:33:23 | 361,383,671 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,008 | cpp | #include <iostream>
#define MAX_SIZE 5
using namespace std;
class Queue {
private:
int q[MAX_SIZE], rear, frnt;
public:
Queue(){
rear = 0;
frnt = 0;
}
bool isFull() {
if (rear == MAX_SIZE) {
return true;
}
return false;
}
bool isEmpty() {
if (frnt == rear) {
return true;
}
return false;
}
void enQueue(int elem) {
if(isFull()) {
cout << "Queue is Full!" << endl;
} else {
cout << "Rear = " << rear << endl;
q[rear] = elem;
cout << "Inserted " << elem << endl;
rear++;
}
}
void shiftElements() {
int ptr = frnt;
for (int i=frnt+1; i<=rear; i++) {
q[ptr] = q[i];
ptr++;
}
rear--;
}
void deQueue(){
int value;
if (isEmpty()) {
cout << "Queue is Underflow!" << endl;
}
else {
value = q[frnt];
cout << "Deleted Element = " << value << endl;
shiftElements();
}
}
void displayQueue() {
int i;
if (isEmpty()) {
cout << "Queue is Empty!" <<endl;
}
else {
for (i=frnt; i<rear;i++) {
cout << q[i] << "\t";
}
}
}
void displayRearandFront() {
cout << "Rear = " << rear << "Front = " << frnt << endl;
}
};
int main() {
Queue myq;
myq.deQueue();
cout << "Queue Created! " << endl;
myq.enQueue(10);
myq.enQueue(20);
myq.enQueue(30);
myq.enQueue(40);
myq.enQueue(50);
myq.enQueue(60);
myq.deQueue();
cout << endl;
myq.displayQueue();
cout << endl;
myq.enQueue(90);
cout << endl;
myq.enQueue(45);
myq.displayQueue();
myq.deQueue();
myq.deQueue();
myq.deQueue();
myq.deQueue();
myq.deQueue();
myq.deQueue();
myq.displayQueue();
}
| [
"vashok915@gmail.com"
] | vashok915@gmail.com |
73b1cde8b842bca6bae0608bc302a7a8f22da955 | d03d052c0ca220d06ec17d170e2b272f4e935a0c | /gen/mojo/services/gpu/interfaces/command_buffer.mojom.cc | eefd3ff5eec218ab5dc047712e22f44bc0d91ba0 | [
"Apache-2.0"
] | permissive | amplab/ray-artifacts | f7ae0298fee371d9b33a40c00dae05c4442dc211 | 6954850f8ef581927df94be90313c1e783cd2e81 | refs/heads/master | 2023-07-07T20:45:43.526694 | 2016-08-06T19:53:55 | 2016-08-06T19:53:55 | 65,099,400 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 34,150 | cc | // NOTE: This file was generated by the Mojo bindings generator.
#include "mojo/services/gpu/interfaces/command_buffer.mojom.h"
#include <math.h>
#include <ostream>
#include "mojo/public/cpp/bindings/lib/array_serialization.h"
#include "mojo/public/cpp/bindings/lib/bindings_serialization.h"
#include "mojo/public/cpp/bindings/lib/bounds_checker.h"
#include "mojo/public/cpp/bindings/lib/map_data_internal.h"
#include "mojo/public/cpp/bindings/lib/map_serialization.h"
#include "mojo/public/cpp/bindings/lib/message_builder.h"
#include "mojo/public/cpp/bindings/lib/message_validation.h"
#include "mojo/public/cpp/bindings/lib/string_serialization.h"
#include "mojo/public/cpp/bindings/lib/validate_params.h"
#include "mojo/public/cpp/bindings/lib/validation_errors.h"
#include "mojo/public/cpp/bindings/lib/validation_util.h"
#include "mojo/public/cpp/environment/logging.h"
namespace mojo {
// --- Interface definitions ---
CommandBufferSyncClientProxy::CommandBufferSyncClientProxy(mojo::MessageReceiverWithResponder* receiver)
: ControlMessageProxy(receiver) {
}
void CommandBufferSyncClientProxy::DidInitialize(
bool in_success, mojo::GpuCapabilitiesPtr in_capabilities) {
size_t size = sizeof(internal::CommandBufferSyncClient_DidInitialize_Params_Data);
size += in_capabilities.is_null()
? 0
: GetSerializedSize_(*in_capabilities);
mojo::MessageBuilder builder(
static_cast<uint32_t>(internal::CommandBufferSyncClient_Base::MessageOrdinals::DidInitialize), size);
internal::CommandBufferSyncClient_DidInitialize_Params_Data* params =
internal::CommandBufferSyncClient_DidInitialize_Params_Data::New(builder.buffer());
params->success = in_success;
{Serialize_(in_capabilities.get(),
builder.buffer(),
¶ms->capabilities.ptr);
}
if (!params->capabilities.ptr) {
MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING(mojo::internal::ValidationError::UNEXPECTED_NULL_POINTER, "null capabilities in CommandBufferSyncClient.DidInitialize request");
}
params->EncodePointersAndHandles(builder.message()->mutable_handles());
bool ok = receiver_->Accept(builder.message());
// This return value may be ignored as !ok implies the Connector has
// encountered an error, which will be visible through other means.
MOJO_ALLOW_UNUSED_LOCAL(ok);
}
void CommandBufferSyncClientProxy::DidMakeProgress(
CommandBufferStatePtr in_state) {
size_t size = sizeof(internal::CommandBufferSyncClient_DidMakeProgress_Params_Data);
size += in_state.is_null()
? 0
: GetSerializedSize_(*in_state);
mojo::MessageBuilder builder(
static_cast<uint32_t>(internal::CommandBufferSyncClient_Base::MessageOrdinals::DidMakeProgress), size);
internal::CommandBufferSyncClient_DidMakeProgress_Params_Data* params =
internal::CommandBufferSyncClient_DidMakeProgress_Params_Data::New(builder.buffer());
{Serialize_(in_state.get(),
builder.buffer(),
¶ms->state.ptr);
}
if (!params->state.ptr) {
MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING(mojo::internal::ValidationError::UNEXPECTED_NULL_POINTER, "null state in CommandBufferSyncClient.DidMakeProgress request");
}
params->EncodePointersAndHandles(builder.message()->mutable_handles());
bool ok = receiver_->Accept(builder.message());
// This return value may be ignored as !ok implies the Connector has
// encountered an error, which will be visible through other means.
MOJO_ALLOW_UNUSED_LOCAL(ok);
}
CommandBufferSyncClientStub::CommandBufferSyncClientStub()
: sink_(nullptr),
control_message_handler_(CommandBufferSyncClient::Version_) {
}
CommandBufferSyncClientStub::~CommandBufferSyncClientStub() {}
bool CommandBufferSyncClientStub::Accept(mojo::Message* message) {
if (mojo::internal::ControlMessageHandler::IsControlMessage(message))
return control_message_handler_.Accept(message);
internal::CommandBufferSyncClient_Base::MessageOrdinals method_ordinal =
static_cast<internal::CommandBufferSyncClient_Base::MessageOrdinals>(message->header()->name);
switch (method_ordinal) {
case internal::CommandBufferSyncClient_Base::MessageOrdinals::DidInitialize: {
internal::CommandBufferSyncClient_DidInitialize_Params_Data* params =
reinterpret_cast<internal::CommandBufferSyncClient_DidInitialize_Params_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
bool p_success {};
mojo::GpuCapabilitiesPtr p_capabilities {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
p_success = params->success;
if (params->capabilities.ptr) {
p_capabilities = mojo::GpuCapabilities::New();
Deserialize_(params->capabilities.ptr, p_capabilities.get());
}
} while (false);
// A null |sink_| means no implementation was bound.
assert(sink_);
sink_->DidInitialize(p_success, p_capabilities.Pass());
return true;
}
case internal::CommandBufferSyncClient_Base::MessageOrdinals::DidMakeProgress: {
internal::CommandBufferSyncClient_DidMakeProgress_Params_Data* params =
reinterpret_cast<internal::CommandBufferSyncClient_DidMakeProgress_Params_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
CommandBufferStatePtr p_state {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
if (params->state.ptr) {
p_state = CommandBufferState::New();
Deserialize_(params->state.ptr, p_state.get());
}
} while (false);
// A null |sink_| means no implementation was bound.
assert(sink_);
sink_->DidMakeProgress(p_state.Pass());
return true;
}
}
return false;
}
bool CommandBufferSyncClientStub::AcceptWithResponder(
mojo::Message* message, mojo::MessageReceiverWithStatus* responder) {
if (mojo::internal::ControlMessageHandler::IsControlMessage(message))
return control_message_handler_.AcceptWithResponder(message, responder);
internal::CommandBufferSyncClient_Base::MessageOrdinals method_ordinal =
static_cast<internal::CommandBufferSyncClient_Base::MessageOrdinals>(message->header()->name);
switch (method_ordinal) {
case internal::CommandBufferSyncClient_Base::MessageOrdinals::DidInitialize: {
break;
}
case internal::CommandBufferSyncClient_Base::MessageOrdinals::DidMakeProgress: {
break;
}
}
return false;
}
CommandBufferSyncPointClientProxy::CommandBufferSyncPointClientProxy(mojo::MessageReceiverWithResponder* receiver)
: ControlMessageProxy(receiver) {
}
void CommandBufferSyncPointClientProxy::DidInsertSyncPoint(
uint32_t in_sync_point) {
size_t size = sizeof(internal::CommandBufferSyncPointClient_DidInsertSyncPoint_Params_Data);
mojo::MessageBuilder builder(
static_cast<uint32_t>(internal::CommandBufferSyncPointClient_Base::MessageOrdinals::DidInsertSyncPoint), size);
internal::CommandBufferSyncPointClient_DidInsertSyncPoint_Params_Data* params =
internal::CommandBufferSyncPointClient_DidInsertSyncPoint_Params_Data::New(builder.buffer());
params->sync_point = in_sync_point;
params->EncodePointersAndHandles(builder.message()->mutable_handles());
bool ok = receiver_->Accept(builder.message());
// This return value may be ignored as !ok implies the Connector has
// encountered an error, which will be visible through other means.
MOJO_ALLOW_UNUSED_LOCAL(ok);
}
CommandBufferSyncPointClientStub::CommandBufferSyncPointClientStub()
: sink_(nullptr),
control_message_handler_(CommandBufferSyncPointClient::Version_) {
}
CommandBufferSyncPointClientStub::~CommandBufferSyncPointClientStub() {}
bool CommandBufferSyncPointClientStub::Accept(mojo::Message* message) {
if (mojo::internal::ControlMessageHandler::IsControlMessage(message))
return control_message_handler_.Accept(message);
internal::CommandBufferSyncPointClient_Base::MessageOrdinals method_ordinal =
static_cast<internal::CommandBufferSyncPointClient_Base::MessageOrdinals>(message->header()->name);
switch (method_ordinal) {
case internal::CommandBufferSyncPointClient_Base::MessageOrdinals::DidInsertSyncPoint: {
internal::CommandBufferSyncPointClient_DidInsertSyncPoint_Params_Data* params =
reinterpret_cast<internal::CommandBufferSyncPointClient_DidInsertSyncPoint_Params_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
uint32_t p_sync_point {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
p_sync_point = params->sync_point;
} while (false);
// A null |sink_| means no implementation was bound.
assert(sink_);
sink_->DidInsertSyncPoint(p_sync_point);
return true;
}
}
return false;
}
bool CommandBufferSyncPointClientStub::AcceptWithResponder(
mojo::Message* message, mojo::MessageReceiverWithStatus* responder) {
if (mojo::internal::ControlMessageHandler::IsControlMessage(message))
return control_message_handler_.AcceptWithResponder(message, responder);
internal::CommandBufferSyncPointClient_Base::MessageOrdinals method_ordinal =
static_cast<internal::CommandBufferSyncPointClient_Base::MessageOrdinals>(message->header()->name);
switch (method_ordinal) {
case internal::CommandBufferSyncPointClient_Base::MessageOrdinals::DidInsertSyncPoint: {
break;
}
}
return false;
}
CommandBufferLostContextObserverProxy::CommandBufferLostContextObserverProxy(mojo::MessageReceiverWithResponder* receiver)
: ControlMessageProxy(receiver) {
}
void CommandBufferLostContextObserverProxy::DidLoseContext(
int32_t in_context_lost_reason) {
size_t size = sizeof(internal::CommandBufferLostContextObserver_DidLoseContext_Params_Data);
mojo::MessageBuilder builder(
static_cast<uint32_t>(internal::CommandBufferLostContextObserver_Base::MessageOrdinals::DidLoseContext), size);
internal::CommandBufferLostContextObserver_DidLoseContext_Params_Data* params =
internal::CommandBufferLostContextObserver_DidLoseContext_Params_Data::New(builder.buffer());
params->context_lost_reason = in_context_lost_reason;
params->EncodePointersAndHandles(builder.message()->mutable_handles());
bool ok = receiver_->Accept(builder.message());
// This return value may be ignored as !ok implies the Connector has
// encountered an error, which will be visible through other means.
MOJO_ALLOW_UNUSED_LOCAL(ok);
}
CommandBufferLostContextObserverStub::CommandBufferLostContextObserverStub()
: sink_(nullptr),
control_message_handler_(CommandBufferLostContextObserver::Version_) {
}
CommandBufferLostContextObserverStub::~CommandBufferLostContextObserverStub() {}
bool CommandBufferLostContextObserverStub::Accept(mojo::Message* message) {
if (mojo::internal::ControlMessageHandler::IsControlMessage(message))
return control_message_handler_.Accept(message);
internal::CommandBufferLostContextObserver_Base::MessageOrdinals method_ordinal =
static_cast<internal::CommandBufferLostContextObserver_Base::MessageOrdinals>(message->header()->name);
switch (method_ordinal) {
case internal::CommandBufferLostContextObserver_Base::MessageOrdinals::DidLoseContext: {
internal::CommandBufferLostContextObserver_DidLoseContext_Params_Data* params =
reinterpret_cast<internal::CommandBufferLostContextObserver_DidLoseContext_Params_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
int32_t p_context_lost_reason {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
p_context_lost_reason = params->context_lost_reason;
} while (false);
// A null |sink_| means no implementation was bound.
assert(sink_);
sink_->DidLoseContext(p_context_lost_reason);
return true;
}
}
return false;
}
bool CommandBufferLostContextObserverStub::AcceptWithResponder(
mojo::Message* message, mojo::MessageReceiverWithStatus* responder) {
if (mojo::internal::ControlMessageHandler::IsControlMessage(message))
return control_message_handler_.AcceptWithResponder(message, responder);
internal::CommandBufferLostContextObserver_Base::MessageOrdinals method_ordinal =
static_cast<internal::CommandBufferLostContextObserver_Base::MessageOrdinals>(message->header()->name);
switch (method_ordinal) {
case internal::CommandBufferLostContextObserver_Base::MessageOrdinals::DidLoseContext: {
break;
}
}
return false;
}
class CommandBuffer_Echo_ForwardToCallback
: public mojo::MessageReceiver {
public:
CommandBuffer_Echo_ForwardToCallback(
const CommandBuffer::EchoCallback& callback)
: callback_(callback) {
}
bool Accept(mojo::Message* message) override;
private:
CommandBuffer::EchoCallback callback_;
MOJO_DISALLOW_COPY_AND_ASSIGN(CommandBuffer_Echo_ForwardToCallback);
};
bool CommandBuffer_Echo_ForwardToCallback::Accept(
mojo::Message* message) {
internal::CommandBuffer_Echo_ResponseParams_Data* params =
reinterpret_cast<internal::CommandBuffer_Echo_ResponseParams_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
} while (false);
callback_.Run();
return true;
}
CommandBufferProxy::CommandBufferProxy(mojo::MessageReceiverWithResponder* receiver)
: ControlMessageProxy(receiver) {
}
void CommandBufferProxy::Initialize(
mojo::InterfaceHandle<CommandBufferSyncClient> in_sync_client, mojo::InterfaceHandle<CommandBufferSyncPointClient> in_sync_point_client, mojo::InterfaceHandle<CommandBufferLostContextObserver> in_lost_observer, mojo::ScopedSharedBufferHandle in_shared_state) {
size_t size = sizeof(internal::CommandBuffer_Initialize_Params_Data);
mojo::MessageBuilder builder(
static_cast<uint32_t>(internal::CommandBuffer_Base::MessageOrdinals::Initialize), size);
internal::CommandBuffer_Initialize_Params_Data* params =
internal::CommandBuffer_Initialize_Params_Data::New(builder.buffer());
mojo::internal::InterfaceHandleToData(in_sync_client.Pass(),
¶ms->sync_client);
if (!params->sync_client.handle.is_valid()) {
MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING(mojo::internal::ValidationError::UNEXPECTED_INVALID_HANDLE, "invalid sync_client in CommandBuffer.Initialize request");
}
mojo::internal::InterfaceHandleToData(in_sync_point_client.Pass(),
¶ms->sync_point_client);
if (!params->sync_point_client.handle.is_valid()) {
MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING(mojo::internal::ValidationError::UNEXPECTED_INVALID_HANDLE, "invalid sync_point_client in CommandBuffer.Initialize request");
}
mojo::internal::InterfaceHandleToData(in_lost_observer.Pass(),
¶ms->lost_observer);
if (!params->lost_observer.handle.is_valid()) {
MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING(mojo::internal::ValidationError::UNEXPECTED_INVALID_HANDLE, "invalid lost_observer in CommandBuffer.Initialize request");
}
params->shared_state = in_shared_state.release();
if (!params->shared_state.is_valid()) {
MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING(mojo::internal::ValidationError::UNEXPECTED_INVALID_HANDLE, "invalid shared_state in CommandBuffer.Initialize request");
}
params->EncodePointersAndHandles(builder.message()->mutable_handles());
bool ok = receiver_->Accept(builder.message());
// This return value may be ignored as !ok implies the Connector has
// encountered an error, which will be visible through other means.
MOJO_ALLOW_UNUSED_LOCAL(ok);
}
void CommandBufferProxy::SetGetBuffer(
int32_t in_buffer) {
size_t size = sizeof(internal::CommandBuffer_SetGetBuffer_Params_Data);
mojo::MessageBuilder builder(
static_cast<uint32_t>(internal::CommandBuffer_Base::MessageOrdinals::SetGetBuffer), size);
internal::CommandBuffer_SetGetBuffer_Params_Data* params =
internal::CommandBuffer_SetGetBuffer_Params_Data::New(builder.buffer());
params->buffer = in_buffer;
params->EncodePointersAndHandles(builder.message()->mutable_handles());
bool ok = receiver_->Accept(builder.message());
// This return value may be ignored as !ok implies the Connector has
// encountered an error, which will be visible through other means.
MOJO_ALLOW_UNUSED_LOCAL(ok);
}
void CommandBufferProxy::Flush(
int32_t in_put_offset) {
size_t size = sizeof(internal::CommandBuffer_Flush_Params_Data);
mojo::MessageBuilder builder(
static_cast<uint32_t>(internal::CommandBuffer_Base::MessageOrdinals::Flush), size);
internal::CommandBuffer_Flush_Params_Data* params =
internal::CommandBuffer_Flush_Params_Data::New(builder.buffer());
params->put_offset = in_put_offset;
params->EncodePointersAndHandles(builder.message()->mutable_handles());
bool ok = receiver_->Accept(builder.message());
// This return value may be ignored as !ok implies the Connector has
// encountered an error, which will be visible through other means.
MOJO_ALLOW_UNUSED_LOCAL(ok);
}
void CommandBufferProxy::MakeProgress(
int32_t in_last_get_offset) {
size_t size = sizeof(internal::CommandBuffer_MakeProgress_Params_Data);
mojo::MessageBuilder builder(
static_cast<uint32_t>(internal::CommandBuffer_Base::MessageOrdinals::MakeProgress), size);
internal::CommandBuffer_MakeProgress_Params_Data* params =
internal::CommandBuffer_MakeProgress_Params_Data::New(builder.buffer());
params->last_get_offset = in_last_get_offset;
params->EncodePointersAndHandles(builder.message()->mutable_handles());
bool ok = receiver_->Accept(builder.message());
// This return value may be ignored as !ok implies the Connector has
// encountered an error, which will be visible through other means.
MOJO_ALLOW_UNUSED_LOCAL(ok);
}
void CommandBufferProxy::RegisterTransferBuffer(
int32_t in_id, mojo::ScopedSharedBufferHandle in_transfer_buffer, uint32_t in_size) {
size_t size = sizeof(internal::CommandBuffer_RegisterTransferBuffer_Params_Data);
mojo::MessageBuilder builder(
static_cast<uint32_t>(internal::CommandBuffer_Base::MessageOrdinals::RegisterTransferBuffer), size);
internal::CommandBuffer_RegisterTransferBuffer_Params_Data* params =
internal::CommandBuffer_RegisterTransferBuffer_Params_Data::New(builder.buffer());
params->id = in_id;
params->transfer_buffer = in_transfer_buffer.release();
if (!params->transfer_buffer.is_valid()) {
MOJO_INTERNAL_DLOG_SERIALIZATION_WARNING(mojo::internal::ValidationError::UNEXPECTED_INVALID_HANDLE, "invalid transfer_buffer in CommandBuffer.RegisterTransferBuffer request");
}
params->size = in_size;
params->EncodePointersAndHandles(builder.message()->mutable_handles());
bool ok = receiver_->Accept(builder.message());
// This return value may be ignored as !ok implies the Connector has
// encountered an error, which will be visible through other means.
MOJO_ALLOW_UNUSED_LOCAL(ok);
}
void CommandBufferProxy::DestroyTransferBuffer(
int32_t in_id) {
size_t size = sizeof(internal::CommandBuffer_DestroyTransferBuffer_Params_Data);
mojo::MessageBuilder builder(
static_cast<uint32_t>(internal::CommandBuffer_Base::MessageOrdinals::DestroyTransferBuffer), size);
internal::CommandBuffer_DestroyTransferBuffer_Params_Data* params =
internal::CommandBuffer_DestroyTransferBuffer_Params_Data::New(builder.buffer());
params->id = in_id;
params->EncodePointersAndHandles(builder.message()->mutable_handles());
bool ok = receiver_->Accept(builder.message());
// This return value may be ignored as !ok implies the Connector has
// encountered an error, which will be visible through other means.
MOJO_ALLOW_UNUSED_LOCAL(ok);
}
void CommandBufferProxy::InsertSyncPoint(
bool in_retire) {
size_t size = sizeof(internal::CommandBuffer_InsertSyncPoint_Params_Data);
mojo::MessageBuilder builder(
static_cast<uint32_t>(internal::CommandBuffer_Base::MessageOrdinals::InsertSyncPoint), size);
internal::CommandBuffer_InsertSyncPoint_Params_Data* params =
internal::CommandBuffer_InsertSyncPoint_Params_Data::New(builder.buffer());
params->retire = in_retire;
params->EncodePointersAndHandles(builder.message()->mutable_handles());
bool ok = receiver_->Accept(builder.message());
// This return value may be ignored as !ok implies the Connector has
// encountered an error, which will be visible through other means.
MOJO_ALLOW_UNUSED_LOCAL(ok);
}
void CommandBufferProxy::RetireSyncPoint(
uint32_t in_sync_point) {
size_t size = sizeof(internal::CommandBuffer_RetireSyncPoint_Params_Data);
mojo::MessageBuilder builder(
static_cast<uint32_t>(internal::CommandBuffer_Base::MessageOrdinals::RetireSyncPoint), size);
internal::CommandBuffer_RetireSyncPoint_Params_Data* params =
internal::CommandBuffer_RetireSyncPoint_Params_Data::New(builder.buffer());
params->sync_point = in_sync_point;
params->EncodePointersAndHandles(builder.message()->mutable_handles());
bool ok = receiver_->Accept(builder.message());
// This return value may be ignored as !ok implies the Connector has
// encountered an error, which will be visible through other means.
MOJO_ALLOW_UNUSED_LOCAL(ok);
}
void CommandBufferProxy::Echo(
const EchoCallback& callback) {
size_t size = sizeof(internal::CommandBuffer_Echo_Params_Data);
mojo::RequestMessageBuilder builder(
static_cast<uint32_t>(internal::CommandBuffer_Base::MessageOrdinals::Echo), size);
internal::CommandBuffer_Echo_Params_Data* params =
internal::CommandBuffer_Echo_Params_Data::New(builder.buffer());
params->EncodePointersAndHandles(builder.message()->mutable_handles());
mojo::MessageReceiver* responder =
new CommandBuffer_Echo_ForwardToCallback(callback);
if (!receiver_->AcceptWithResponder(builder.message(), responder))
delete responder;
}
// This class implements a method's response callback: it serializes the
// response args into a mojo message and passes it to the MessageReceiver it
// was created with.
class CommandBuffer_Echo_ProxyToResponder
: public CommandBuffer::EchoCallback::Runnable {
public:
~CommandBuffer_Echo_ProxyToResponder() override {
// Is the Mojo application destroying the callback without running it
// and without first closing the pipe?
bool callback_was_dropped = responder_ && responder_->IsValid();
// If the Callback was dropped then deleting the responder will close
// the pipe so the calling application knows to stop waiting for a reply.
delete responder_;
MOJO_DCHECK(!callback_was_dropped) << "The callback passed to "
"CommandBuffer::Echo(callback) "
"was never run.";
}
CommandBuffer_Echo_ProxyToResponder(
uint64_t request_id,
mojo::MessageReceiverWithStatus* responder)
: request_id_(request_id),
responder_(responder) {
}
void Run() const override;
private:
uint64_t request_id_;
mutable mojo::MessageReceiverWithStatus* responder_;
MOJO_DISALLOW_COPY_AND_ASSIGN(CommandBuffer_Echo_ProxyToResponder);
};
void CommandBuffer_Echo_ProxyToResponder::Run(
) const {
size_t size = sizeof(internal::CommandBuffer_Echo_ResponseParams_Data);
mojo::ResponseMessageBuilder builder(
static_cast<uint32_t>(internal::CommandBuffer_Base::MessageOrdinals::Echo), size, request_id_);
internal::CommandBuffer_Echo_ResponseParams_Data* params =
internal::CommandBuffer_Echo_ResponseParams_Data::New(builder.buffer());
params->EncodePointersAndHandles(builder.message()->mutable_handles());
bool ok = responder_->Accept(builder.message());
MOJO_ALLOW_UNUSED_LOCAL(ok);
// TODO(darin): !ok returned here indicates a malformed message, and that may
// be good reason to close the connection. However, we don't have a way to do
// that from here. We should add a way.
delete responder_;
responder_ = nullptr;
}
CommandBufferStub::CommandBufferStub()
: sink_(nullptr),
control_message_handler_(CommandBuffer::Version_) {
}
CommandBufferStub::~CommandBufferStub() {}
bool CommandBufferStub::Accept(mojo::Message* message) {
if (mojo::internal::ControlMessageHandler::IsControlMessage(message))
return control_message_handler_.Accept(message);
internal::CommandBuffer_Base::MessageOrdinals method_ordinal =
static_cast<internal::CommandBuffer_Base::MessageOrdinals>(message->header()->name);
switch (method_ordinal) {
case internal::CommandBuffer_Base::MessageOrdinals::Initialize: {
internal::CommandBuffer_Initialize_Params_Data* params =
reinterpret_cast<internal::CommandBuffer_Initialize_Params_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
mojo::InterfaceHandle<CommandBufferSyncClient> p_sync_client {};
mojo::InterfaceHandle<CommandBufferSyncPointClient> p_sync_point_client {};
mojo::InterfaceHandle<CommandBufferLostContextObserver> p_lost_observer {};
mojo::ScopedSharedBufferHandle p_shared_state {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
mojo::internal::InterfaceDataToHandle(¶ms->sync_client, &p_sync_client);
mojo::internal::InterfaceDataToHandle(¶ms->sync_point_client, &p_sync_point_client);
mojo::internal::InterfaceDataToHandle(¶ms->lost_observer, &p_lost_observer);
p_shared_state.reset(mojo::internal::FetchAndReset(¶ms->shared_state));
} while (false);
// A null |sink_| means no implementation was bound.
assert(sink_);
sink_->Initialize(p_sync_client.Pass(), p_sync_point_client.Pass(), p_lost_observer.Pass(), p_shared_state.Pass());
return true;
}
case internal::CommandBuffer_Base::MessageOrdinals::SetGetBuffer: {
internal::CommandBuffer_SetGetBuffer_Params_Data* params =
reinterpret_cast<internal::CommandBuffer_SetGetBuffer_Params_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
int32_t p_buffer {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
p_buffer = params->buffer;
} while (false);
// A null |sink_| means no implementation was bound.
assert(sink_);
sink_->SetGetBuffer(p_buffer);
return true;
}
case internal::CommandBuffer_Base::MessageOrdinals::Flush: {
internal::CommandBuffer_Flush_Params_Data* params =
reinterpret_cast<internal::CommandBuffer_Flush_Params_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
int32_t p_put_offset {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
p_put_offset = params->put_offset;
} while (false);
// A null |sink_| means no implementation was bound.
assert(sink_);
sink_->Flush(p_put_offset);
return true;
}
case internal::CommandBuffer_Base::MessageOrdinals::MakeProgress: {
internal::CommandBuffer_MakeProgress_Params_Data* params =
reinterpret_cast<internal::CommandBuffer_MakeProgress_Params_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
int32_t p_last_get_offset {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
p_last_get_offset = params->last_get_offset;
} while (false);
// A null |sink_| means no implementation was bound.
assert(sink_);
sink_->MakeProgress(p_last_get_offset);
return true;
}
case internal::CommandBuffer_Base::MessageOrdinals::RegisterTransferBuffer: {
internal::CommandBuffer_RegisterTransferBuffer_Params_Data* params =
reinterpret_cast<internal::CommandBuffer_RegisterTransferBuffer_Params_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
int32_t p_id {};
mojo::ScopedSharedBufferHandle p_transfer_buffer {};
uint32_t p_size {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
p_id = params->id;
p_transfer_buffer.reset(mojo::internal::FetchAndReset(¶ms->transfer_buffer));
p_size = params->size;
} while (false);
// A null |sink_| means no implementation was bound.
assert(sink_);
sink_->RegisterTransferBuffer(p_id, p_transfer_buffer.Pass(), p_size);
return true;
}
case internal::CommandBuffer_Base::MessageOrdinals::DestroyTransferBuffer: {
internal::CommandBuffer_DestroyTransferBuffer_Params_Data* params =
reinterpret_cast<internal::CommandBuffer_DestroyTransferBuffer_Params_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
int32_t p_id {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
p_id = params->id;
} while (false);
// A null |sink_| means no implementation was bound.
assert(sink_);
sink_->DestroyTransferBuffer(p_id);
return true;
}
case internal::CommandBuffer_Base::MessageOrdinals::InsertSyncPoint: {
internal::CommandBuffer_InsertSyncPoint_Params_Data* params =
reinterpret_cast<internal::CommandBuffer_InsertSyncPoint_Params_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
bool p_retire {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
p_retire = params->retire;
} while (false);
// A null |sink_| means no implementation was bound.
assert(sink_);
sink_->InsertSyncPoint(p_retire);
return true;
}
case internal::CommandBuffer_Base::MessageOrdinals::RetireSyncPoint: {
internal::CommandBuffer_RetireSyncPoint_Params_Data* params =
reinterpret_cast<internal::CommandBuffer_RetireSyncPoint_Params_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
uint32_t p_sync_point {};
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
p_sync_point = params->sync_point;
} while (false);
// A null |sink_| means no implementation was bound.
assert(sink_);
sink_->RetireSyncPoint(p_sync_point);
return true;
}
case internal::CommandBuffer_Base::MessageOrdinals::Echo: {
break;
}
}
return false;
}
bool CommandBufferStub::AcceptWithResponder(
mojo::Message* message, mojo::MessageReceiverWithStatus* responder) {
if (mojo::internal::ControlMessageHandler::IsControlMessage(message))
return control_message_handler_.AcceptWithResponder(message, responder);
internal::CommandBuffer_Base::MessageOrdinals method_ordinal =
static_cast<internal::CommandBuffer_Base::MessageOrdinals>(message->header()->name);
switch (method_ordinal) {
case internal::CommandBuffer_Base::MessageOrdinals::Initialize: {
break;
}
case internal::CommandBuffer_Base::MessageOrdinals::SetGetBuffer: {
break;
}
case internal::CommandBuffer_Base::MessageOrdinals::Flush: {
break;
}
case internal::CommandBuffer_Base::MessageOrdinals::MakeProgress: {
break;
}
case internal::CommandBuffer_Base::MessageOrdinals::RegisterTransferBuffer: {
break;
}
case internal::CommandBuffer_Base::MessageOrdinals::DestroyTransferBuffer: {
break;
}
case internal::CommandBuffer_Base::MessageOrdinals::InsertSyncPoint: {
break;
}
case internal::CommandBuffer_Base::MessageOrdinals::RetireSyncPoint: {
break;
}
case internal::CommandBuffer_Base::MessageOrdinals::Echo: {
internal::CommandBuffer_Echo_Params_Data* params =
reinterpret_cast<internal::CommandBuffer_Echo_Params_Data*>(
message->mutable_payload());
params->DecodePointersAndHandles(message->mutable_handles());
CommandBuffer::EchoCallback::Runnable* runnable =
new CommandBuffer_Echo_ProxyToResponder(
message->request_id(), responder);
CommandBuffer::EchoCallback callback(runnable);
do {
// NOTE: The memory backing |params| may has be smaller than
// |sizeof(*params)| if the message comes from an older version.
} while (false);
// A null |sink_| means no implementation was bound.
assert(sink_);
sink_->Echo(callback);
return true;
}
}
return false;
}
} // namespace mojo
| [
"pcmoritz@gmail.com"
] | pcmoritz@gmail.com |
e43086dae324ae3718fda7caf8fa877a0beb7ec8 | c03615f53093643e3c1e323b83cbe77970966575 | /PRT/3rdParty/cgal/cgal/include/CGAL/Nef_S2/OGL_base_object.h | edcef50542375f5fe006c8eda93759d25ae871a0 | [] | no_license | fangguanya/PRT | 0925b28671e756a6e9431fd57149cf2eebc94818 | 77c1b8e5f3a7a149825ad0cc3ef6002816222622 | refs/heads/master | 2021-06-08T20:54:22.954395 | 2016-11-24T07:38:11 | 2016-11-24T07:38:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,544 | h | // Copyright (c) 1997-2002 Max-Planck-Institute Saarbruecken (Germany).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org); you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation; either version 3 of the License,
// or (at your option) any later version.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id$
//
//
// Author(s) : Peter Hachenberger <hachenberger@mpi-sb.mpg.de>
#ifndef CGAL_OGL_BASE_OBJECT_H
#define CGAL_OGL_BASE_OBJECT_H
#include <CGAL/Simple_cartesian.h>
namespace CGAL {
namespace OGL {
class OGL_base_object {
public:
typedef CGAL::Simple_cartesian<double> Double_kernel;
typedef Double_kernel::Point_3 Double_point;
typedef Double_kernel::Vector_3 Double_vector;
typedef Double_kernel::Segment_3 Double_segment;
typedef Double_kernel::Aff_transformation_3 Affine_3;
virtual void draw() const = 0;
virtual void init() = 0;
virtual void toggle(int) = 0;
virtual void set_style(int) = 0;
virtual ~OGL_base_object() {}
};
}
} //namespace CGAL
#endif // CGAL_OGL_BASE_OBJECT_H
| [
"succeed.2009@163.com"
] | succeed.2009@163.com |
2ed6dcc1729b099b8caaabda2eda042623409545 | 058aead2a638f554bc57fe95a2abd3f63f2e14eb | /Tools/stl2obj/libStl2Obj/libSmoothSample/mesh.cpp | e7e21d3ca884f0bf28d29e00f7322c588d64af75 | [] | no_license | seenen/VR | 4da6bf946de13e6f0d3a5c56ac148e20e9b74046 | 59a3287630c235920d2005396ad4bd5784cc3f1a | refs/heads/master | 2021-01-10T04:57:36.179545 | 2017-05-30T16:36:59 | 2017-05-30T16:36:59 | 53,755,894 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,435 | cpp | #include "mesh.h"
bool indexed_mesh::load_from_ascii_stereo_lithography_file(const char *const file_name, const bool generate_normals, const size_t buffer_width)
{
clear();
cout << "Reading file: " << file_name << endl;
return true;
}
bool indexed_mesh::load_from_binary_stereo_lithography_file(const char *const file_name, const bool generate_normals, const size_t buffer_width)
{
clear();
cout << "Reading file: " << file_name << endl;
ifstream in(file_name, ios_base::binary);
if(in.fail())
return false;
const size_t header_size = 80;
vector<char> buffer(header_size, 0);
unsigned int num_triangles = 0; // Must be 4-byte unsigned int.
// Read header.
in.read(reinterpret_cast<char *>(&(buffer[0])), header_size);
if(header_size != in.gcount())
return false;
if( 's' == tolower(buffer[0]) &&
'o' == tolower(buffer[1]) &&
'l' == tolower(buffer[2]) &&
'i' == tolower(buffer[3]) &&
'd' == tolower(buffer[4]) )
{
cout << "Encountered ASCII STL file header -- aborting." << endl;
return false;
}
// Read number of triangles.
in.read(reinterpret_cast<char *>(&num_triangles), sizeof(unsigned int));
if(sizeof(unsigned int) != in.gcount())
return false;
triangles.resize(num_triangles);
cout << "Triangles: " << triangles.size() << endl;
// Enough bytes for twelve 4-byte floats plus one 2-byte integer, per triangle.
const size_t per_triangle_data_size = (12*sizeof(float) + sizeof(short unsigned int));
const size_t buffer_size = per_triangle_data_size * buffer_width;
buffer.resize(buffer_size, 0);
size_t num_triangles_remaining = triangles.size();
size_t tri_index = 0;
set<indexed_vertex_3> vertex_set;
while(num_triangles_remaining > 0)
{
size_t num_triangles_to_read = buffer_width;
if(num_triangles_remaining < buffer_width)
num_triangles_to_read = num_triangles_remaining;
size_t data_size = per_triangle_data_size*num_triangles_to_read;
in.read(reinterpret_cast<char *>(&buffer[0]), data_size);
if(data_size != in.gcount() || in.fail())
return false;
num_triangles_remaining -= num_triangles_to_read;
// Use a pointer to assist with the copying.
// Should probably use std::copy() instead, but memcpy() does the trick, so whatever...
char *cp = &buffer[0];
for(size_t i = 0; i < num_triangles_to_read; i++)
{
// Skip face normal. We will calculate them manually later.
cp += 3*sizeof(float);
// For each of the three vertices in the triangle.
for(short unsigned int j = 0; j < 3; j++)
{
indexed_vertex_3 v;
// Get vertex components.
memcpy(&v.x, cp, sizeof(float)); cp += sizeof(float);
memcpy(&v.y, cp, sizeof(float)); cp += sizeof(float);
memcpy(&v.z, cp, sizeof(float)); cp += sizeof(float);
// Look for vertex in set.
set<indexed_vertex_3>::const_iterator find_iter = vertex_set.find(v);
// If vertex not found in set...
if(vertex_set.end() == find_iter)
{
// Assign new vertices index
v.index = vertices.size();
// Add vertex to set
vertex_set.insert(v);
// Add vertex to vector
vertex_3 indexless_vertex;
indexless_vertex.x = v.x;
indexless_vertex.y = v.y;
indexless_vertex.z = v.z;
vertices.push_back(indexless_vertex);
// Assign vertex index to triangle
triangles[tri_index].vertex_indices[j] = v.index;
// Add triangle index to vertex
vector<size_t> tri_indices;
tri_indices.push_back(tri_index);
vertex_to_triangle_indices.push_back(tri_indices);
}
else
{
// Assign existing vertex index to triangle
triangles[tri_index].vertex_indices[j] = find_iter->index;
// Add triangle index to vertex
vertex_to_triangle_indices[find_iter->index].push_back(tri_index);
}
}
// Skip attribute.
cp += sizeof(short unsigned int);
tri_index++;
}
}
vertex_to_vertex_indices.resize(vertices.size());
for(size_t i = 0; i < vertex_to_triangle_indices.size(); i++)
{
// Use a temporary set to avoid duplicates.
set<size_t> vertex_to_vertex_indices_set;
for(size_t j = 0; j < vertex_to_triangle_indices[i].size(); j++)
{
size_t tri_index = vertex_to_triangle_indices[i][j];
for(size_t k = 0; k < 3; k++)
if(i != triangles[tri_index].vertex_indices[k]) // Don't add current vertex index to its own adjacency list.
vertex_to_vertex_indices_set.insert(triangles[tri_index].vertex_indices[k]);
}
// Copy to final vector.
for(set<size_t>::const_iterator ci = vertex_to_vertex_indices_set.begin(); ci != vertex_to_vertex_indices_set.end(); ci++)
vertex_to_vertex_indices[i].push_back(*ci);
}
cout << "Vertices: " << triangles.size()*3 << " (of which " << vertices.size() << " are unique)" << endl;
in.close();
if(true == generate_normals)
{
cout << "Generating normals" << endl;
generate_vertex_and_triangle_normals();
}
return true;
}
bool indexed_mesh::save_to_binary_stereo_lithography_file(const char *const file_name, const size_t buffer_width)
{
cout << "Writing file: " << file_name << endl;
cout << "Triangles: " << triangles.size() << endl;
cout << "Vertices: " << triangles.size()*3 << endl;
if(0 == triangles.size())
return false;
// Write to file.
ofstream out(file_name, ios_base::binary);
if(out.fail())
return false;
const size_t header_size = 80;
vector<char> buffer(header_size, 0);
const unsigned int num_triangles = triangles.size(); // Must be 4-byte unsigned int.
vertex_3 normal;
// Write blank header.
out.write(reinterpret_cast<const char *>(&(buffer[0])), header_size);
// Write number of triangles.
out.write(reinterpret_cast<const char *>(&num_triangles), sizeof(unsigned int));
// Enough bytes for twelve 4-byte floats plus one 2-byte integer, per triangle.
const size_t per_triangle_data_size = (12*sizeof(float) + sizeof(short unsigned int));
const size_t buffer_size = per_triangle_data_size * buffer_width;
buffer.resize(buffer_size, 0);
// Use a pointer to assist with the copying.
// Should probably use std::copy() instead, but memcpy() does the trick, so whatever...
char *cp = &buffer[0];
size_t buffer_count = 0;
cout << "Writing " << per_triangle_data_size*triangles.size() / 1048576 << " MB of data to disk" << endl;
for(size_t i = 0; i < triangles.size(); i++)
{
// Copy face normal if it's been calculated, otherwise manually calculate it.
if(triangle_normals.size() == triangles.size())
{
normal = triangle_normals[i];
}
else
{
vertex_3 v0 = vertices[triangles[i].vertex_indices[1]] - vertices[triangles[i].vertex_indices[0]];
vertex_3 v1 = vertices[triangles[i].vertex_indices[2]] - vertices[triangles[i].vertex_indices[0]];
normal = v0.cross(v1);
normal.normalize();
}
memcpy(cp, &normal.x, sizeof(float)); cp += sizeof(float);
memcpy(cp, &normal.y, sizeof(float)); cp += sizeof(float);
memcpy(cp, &normal.z, sizeof(float)); cp += sizeof(float);
memcpy(cp, &vertices[triangles[i].vertex_indices[0]].x, sizeof(float)); cp += sizeof(float);
memcpy(cp, &vertices[triangles[i].vertex_indices[0]].y, sizeof(float)); cp += sizeof(float);
memcpy(cp, &vertices[triangles[i].vertex_indices[0]].z, sizeof(float)); cp += sizeof(float);
memcpy(cp, &vertices[triangles[i].vertex_indices[1]].x, sizeof(float)); cp += sizeof(float);
memcpy(cp, &vertices[triangles[i].vertex_indices[1]].y, sizeof(float)); cp += sizeof(float);
memcpy(cp, &vertices[triangles[i].vertex_indices[1]].z, sizeof(float)); cp += sizeof(float);
memcpy(cp, &vertices[triangles[i].vertex_indices[2]].x, sizeof(float)); cp += sizeof(float);
memcpy(cp, &vertices[triangles[i].vertex_indices[2]].y, sizeof(float)); cp += sizeof(float);
memcpy(cp, &vertices[triangles[i].vertex_indices[2]].z, sizeof(float)); cp += sizeof(float);
cp += sizeof(short unsigned int);
buffer_count++;
// If buffer is full, write triangles in buffer to disk.
if(buffer_count == buffer_width)
{
out.write(reinterpret_cast<const char *>(&buffer[0]), buffer_size);
if(out.fail())
return false;
buffer_count = 0;
cp = &buffer[0];
}
}
// Write any remaining triangles in buffer to disk.
// This will occur whenever triangles.size() % buffer_width != 0
// (ie. when triangle count is not a multiple of buffer_width, which should happen almost all of the time).
if(buffer_count > 0)
{
out.write(reinterpret_cast<const char *>(&buffer[0]), per_triangle_data_size*buffer_count);
if(out.fail())
return false;
}
out.close();
return true;
}
// This produces results that are practically identical to Meshlab
void indexed_mesh::laplace_smooth(const float scale)
{
vector<vertex_3> displacements(vertices.size(), vertex_3(0, 0, 0));
// Get per-vertex displacement.
for(size_t i = 0; i < vertices.size(); i++)
{
// Skip rogue vertices (which were probably made rogue during a previous
// attempt to fix mesh cracks).
if(0 == vertex_to_vertex_indices[i].size())
continue;
const float weight = 1.0f / static_cast<float>(vertex_to_vertex_indices[i].size());
for(size_t j = 0; j < vertex_to_vertex_indices[i].size(); j++)
{
size_t neighbour_j = vertex_to_vertex_indices[i][j];
displacements[i] += (vertices[neighbour_j] - vertices[i])*weight;
}
}
// Apply per-vertex displacement.
for(size_t i = 0; i < vertices.size(); i++)
vertices[i] += displacements[i]*scale;
}
void indexed_mesh::taubin_smooth(const float lambda, const float mu, const size_t steps)
{
cout << "Smoothing mesh using Taubin lambda|mu algorithm ";
cout << "(inverse neighbour count weighting)" << endl;
for(size_t s = 0; s < steps; s++)
{
cout << "Step " << s + 1 << " of " << steps << endl;
laplace_smooth(lambda);
laplace_smooth(mu);
}
// Recalculate normals, if necessary.
regenerate_vertex_and_triangle_normals_if_exists();
}
void indexed_mesh::set_max_extent(float max_extent)
{
float curr_x_min = numeric_limits<float>::max();
float curr_y_min = numeric_limits<float>::max();
float curr_z_min = numeric_limits<float>::max();
float curr_x_max = numeric_limits<float>::min();
float curr_y_max = numeric_limits<float>::min();
float curr_z_max = numeric_limits<float>::min();
for(size_t i = 0; i < vertices.size(); i++)
{
if(vertices[i].x < curr_x_min)
curr_x_min = vertices[i].x;
if(vertices[i].x > curr_x_max)
curr_x_max = vertices[i].x;
if(vertices[i].y < curr_y_min)
curr_y_min = vertices[i].y;
if(vertices[i].y > curr_y_max)
curr_y_max = vertices[i].y;
if(vertices[i].z < curr_z_min)
curr_z_min = vertices[i].z;
if(vertices[i].z > curr_z_max)
curr_z_max = vertices[i].z;
}
float curr_x_extent = fabsf(curr_x_min - curr_x_max);
float curr_y_extent = fabsf(curr_y_min - curr_y_max);
float curr_z_extent = fabsf(curr_z_min - curr_z_max);
float curr_max_extent = curr_x_extent;
if(curr_y_extent > curr_max_extent)
curr_max_extent = curr_y_extent;
if(curr_z_extent > curr_max_extent)
curr_max_extent = curr_z_extent;
float scale_value = max_extent / curr_max_extent;
cout << "Original max extent: " << curr_max_extent << endl;
cout << "Scaling all vertices by a factor of: " << scale_value << endl;
cout << "New max extent: " << max_extent << endl;
for(size_t i = 0; i < vertices.size(); i++)
vertices[i] *= scale_value;
}
bool indexed_mesh::save_to_povray_mesh2_file(const char *const file_name, const bool write_vertex_normals)
{
cout << "Triangle count: " << triangles.size() << endl;
if(0 == triangles.size())
return false;
if(true == write_vertex_normals && vertex_normals.size() != vertices.size())
generate_vertex_normals();
// Write to file.
ofstream out(file_name);
if(out.fail())
return false;
out << setiosflags(ios_base::fixed);
cout << "Writing data to " << file_name << endl;
// Bump up output precision to help keep very small triangles from becoming degenerate.
//out << setprecision(18);
// Note: Some of these vertices may be rogue vertices that aren't referenced by triangles;
// this occurs after cracks have been fixed. Whatever.
out << " vertex_vectors" << endl;
out << " {" << endl;
out << " " << vertices.size() << ',' << endl;
for(size_t i = 0; i < vertices.size() - 1; i++)
out << " <" << vertices[i].x << ',' << vertices[i].y << ',' << vertices[i].z << ">," << endl;
out << " <" << vertices[vertices.size() - 1].x << ',' << vertices[vertices.size() - 1].y << ',' << vertices[vertices.size() - 1].z << '>' << endl;
out << " }" << endl;
if(true == write_vertex_normals)
{
out << " normal_vectors" << endl;
out << " {" << endl;
out << " " << vertex_normals.size() << ',' << endl;
for(size_t i = 0; i < vertex_normals.size() - 1; i++)
out << " <" << vertex_normals[i].x << ',' << vertex_normals[i].y << ',' << vertex_normals[i].z << ">," << endl;
out << " <" << vertex_normals[vertex_normals.size() - 1].x << ',' << vertex_normals[vertex_normals.size() - 1].y << ',' << vertex_normals[vertex_normals.size() - 1].z << '>' << endl;
out << " }" << endl;
}
out << " face_indices" << endl;
out << " {" << endl;
out << " " << triangles.size() << ',' << endl;
for(size_t i = 0; i < triangles.size() - 1; i++)
out << " <" << triangles[i].vertex_indices[0] << ',' << triangles[i].vertex_indices[1] << ',' << triangles[i].vertex_indices[2] << ">," << endl;
out << " <" << triangles[triangles.size() - 1].vertex_indices[0] << ',' << triangles[triangles.size() - 1].vertex_indices[1] << ',' << triangles[triangles.size() - 1].vertex_indices[2]<< ">" << endl;
out << " }" << endl;
out.close();
return true;
}
void indexed_mesh::generate_vertex_normals(void)
{
if(triangles.size() == 0 || vertices.size() == 0)
return;
vertex_normals.clear();
vertex_normals.resize(vertices.size());
for(size_t i = 0; i < triangles.size(); i++)
{
vertex_3 v0 = vertices[triangles[i].vertex_indices[1]] - vertices[triangles[i].vertex_indices[0]];
vertex_3 v1 = vertices[triangles[i].vertex_indices[2]] - vertices[triangles[i].vertex_indices[0]];
vertex_3 v2 = v0.cross(v1);
vertex_normals[triangles[i].vertex_indices[0]] = vertex_normals[triangles[i].vertex_indices[0]] + v2;
vertex_normals[triangles[i].vertex_indices[1]] = vertex_normals[triangles[i].vertex_indices[1]] + v2;
vertex_normals[triangles[i].vertex_indices[2]] = vertex_normals[triangles[i].vertex_indices[2]] + v2;
}
for(size_t i = 0; i < vertex_normals.size(); i++)
vertex_normals[i].normalize();
}
void indexed_mesh::generate_triangle_normals(void)
{
if(triangles.size() == 0)
return;
triangle_normals.clear();
triangle_normals.resize(triangles.size());
for(size_t i = 0; i < triangles.size(); i++)
{
vertex_3 v0 = vertices[triangles[i].vertex_indices[1]] - vertices[triangles[i].vertex_indices[0]];
vertex_3 v1 = vertices[triangles[i].vertex_indices[2]] - vertices[triangles[i].vertex_indices[0]];
triangle_normals[i] = v0.cross(v1);
triangle_normals[i].normalize();
}
}
void indexed_mesh::generate_vertex_and_triangle_normals(void)
{
generate_vertex_normals();
generate_triangle_normals();
}
void indexed_mesh::regenerate_vertex_and_triangle_normals_if_exists(void)
{
if(triangle_normals.size() > 0)
generate_triangle_normals();
if(vertex_normals.size() > 0)
generate_vertex_normals();
}
void indexed_mesh::fix_cracks(void)
{
cout << "Finding cracks" << endl;
// Find edges that belong to only one triangle.
set<ordered_indexed_edge> problem_edges_set;
size_t problem_edge_id = 0;
// For each vertex.
for(size_t i = 0; i < vertices.size(); i++)
{
// For each edge.
for(size_t j = 0; j < vertex_to_vertex_indices[i].size(); j++)
{
size_t triangle_count = 0;
size_t neighbour_j = vertex_to_vertex_indices[i][j];
// Find out which two triangles are shared by this edge.
for(size_t k = 0; k < vertex_to_triangle_indices[i].size(); k++)
{
for(size_t l = 0; l < vertex_to_triangle_indices[neighbour_j].size(); l++)
{
size_t tri0_index = vertex_to_triangle_indices[i][k];
size_t tri1_index = vertex_to_triangle_indices[neighbour_j][l];
if(tri0_index == tri1_index)
{
triangle_count++;
break;
}
}
} // End of: Find out which two triangles are shared by this edge.
// Found a problem edge.
if(triangle_count != 2)
{
indexed_vertex_3 v0;
v0.index = i;
v0.x = vertices[i].x;
v0.y = vertices[i].y;
v0.z = vertices[i].z;
indexed_vertex_3 v1;
v1.index = neighbour_j;
v1.x = vertices[neighbour_j].x;
v1.y = vertices[neighbour_j].y;
v1.z = vertices[neighbour_j].z;
ordered_indexed_edge problem_edge(v0, v1);
if(problem_edges_set.end() == problem_edges_set.find(problem_edge))
{
problem_edge.id = problem_edge_id++;
problem_edges_set.insert(problem_edge);
}
} // End of: Found a problem edge.
} // End of: For each edge.
} // End of: For each vertex.
if(0 == problem_edges_set.size())
{
cout << "No cracks found -- the mesh seems to be in good condition" << endl;
return;
}
cout << "Found " << problem_edges_set.size() << " problem edges" << endl;
if(0 != problem_edges_set.size() % 2)
{
cout << "Error -- the number of problem edges must be an even number (perhaps the mesh has holes?). Aborting." << endl;
return;
}
// Make a copy of the set into a vector because the edge matching will
// run a bit faster while looping through a vector by index vs looping through
// a set by iterator.
vector<ordered_indexed_edge> problem_edges_vec(problem_edges_set.begin(), problem_edges_set.end());
vector<bool> processed_problem_edges(problem_edges_set.size(), false);
problem_edges_set.clear();
set<ordered_size_t_pair> merge_vertices;
cout << "Pairing problem edges" << endl;
// Each problem edge is practically a duplicate of some other, but not quite exactly.
// So, find the closest match for each problem edge.
for(size_t i = 0; i < problem_edges_vec.size(); i++)
{
// This edge has already been matched up previously, so skip it.
if(true == processed_problem_edges[problem_edges_vec[i].id])
continue;
float closest_dist_sq = numeric_limits<float>::max();
size_t closest_problem_edges_vec_index = 0;
for(size_t j = i + 1; j < problem_edges_vec.size(); j++)
{
// Note: Don't check to see if this edge has been processed yet.
// Doing so will actually only slow this down further.
// Perhaps vector<bool> is a bit of a sloth?
//if(true == processed_problem_edges[problem_edges_vec[j].id])
// continue;
float dist_sq = problem_edges_vec[i].centre_point.distance_sq(problem_edges_vec[j].centre_point);
if(dist_sq < closest_dist_sq)
{
closest_dist_sq = dist_sq;
closest_problem_edges_vec_index = j;
}
}
processed_problem_edges[problem_edges_vec[i].id] = true;
processed_problem_edges[problem_edges_vec[closest_problem_edges_vec_index].id] = true;
// If edge 0 vertex 0 is further in space from edge 1 vertex 0 than from edge 1 vertex 1,
// then swap the indices on the edge 1 -- this makes sure that the edges are not pointing
// in opposing directions.
if(vertices[problem_edges_vec[i].indices[0]].distance_sq(vertices[problem_edges_vec[closest_problem_edges_vec_index].indices[0]]) > vertices[problem_edges_vec[i].indices[0]].distance_sq(vertices[problem_edges_vec[closest_problem_edges_vec_index].indices[1]]))
{
size_t temp = problem_edges_vec[closest_problem_edges_vec_index].indices[0];
problem_edges_vec[closest_problem_edges_vec_index].indices[0] = problem_edges_vec[closest_problem_edges_vec_index].indices[1];
problem_edges_vec[closest_problem_edges_vec_index].indices[1] = temp;
}
// If the first indices aren't already the same, then merge them.
if(problem_edges_vec[i].indices[0] != problem_edges_vec[closest_problem_edges_vec_index].indices[0])
merge_vertices.insert(ordered_size_t_pair(problem_edges_vec[i].indices[0], problem_edges_vec[closest_problem_edges_vec_index].indices[0]));
// If the second indices aren't already the same, then merge them.
if(problem_edges_vec[i].indices[1] != problem_edges_vec[closest_problem_edges_vec_index].indices[1])
merge_vertices.insert(ordered_size_t_pair(problem_edges_vec[i].indices[1], problem_edges_vec[closest_problem_edges_vec_index].indices[1]));
}
cout << "Merging " << merge_vertices.size() << " vertex pairs" << endl;
for(set<ordered_size_t_pair>::const_iterator ci = merge_vertices.begin(); ci != merge_vertices.end(); ci++)
merge_vertex_pair(ci->indices[0], ci->indices[1]);
// Recalculate normals, if necessary.
regenerate_vertex_and_triangle_normals_if_exists();
}
template<typename T> void indexed_mesh::eliminate_vector_duplicates(vector<T> &v)
{
if(0 == v.size())
return;
set<T> s(v.begin(), v.end()); // Eliminate duplicates (and sort them)
vector<T> vtemp(s.begin(), s.end()); // Stuff things back into a temp vector
v.swap(vtemp); // Assign temp vector contents to destination vector
}
bool indexed_mesh::merge_vertex_pair(const size_t keeper, const size_t goner)
{
if(keeper >= vertices.size() || goner >= vertices.size())
return false;
if(keeper == goner)
return true;
// Merge vertex to triangle data.
// Add goner's vertex to triangle data to keeper's triangle to vertex data,
// and replace goner's index with keeper's index in all relevant triangles' index data.
for(size_t i = 0; i < vertex_to_triangle_indices[goner].size(); i++)
{
size_t tri_index = vertex_to_triangle_indices[goner][i];
vertex_to_triangle_indices[keeper].push_back(tri_index);
for(size_t j = 0; j < 3; j++)
if(goner == triangles[tri_index].vertex_indices[j])
triangles[tri_index].vertex_indices[j] = keeper;
}
// Finalize keeper's vertex to triangle data.
eliminate_vector_duplicates(vertex_to_triangle_indices[keeper]);
// Clear out goner's vertex to triangle data for good.
vertex_to_triangle_indices[goner].clear();
// Merge vertex to vertex data.
// Add goner's vertex to vertex data to keeper's vertex to vertex data,
// and replace goner's index with keeper's index in all relevant vertices' vertex to vertex data.
for(size_t i = 0; i < vertex_to_vertex_indices[goner].size(); i++)
{
size_t vert_index = vertex_to_vertex_indices[goner][i];
vertex_to_vertex_indices[keeper].push_back(vert_index);
for(size_t j = 0; j < vertex_to_vertex_indices[vert_index].size(); j++)
{
// Could probably break after this, but whatever...
if(goner == vertex_to_vertex_indices[vert_index][j])
vertex_to_vertex_indices[vert_index][j] = keeper;
}
eliminate_vector_duplicates(vertex_to_vertex_indices[vert_index]);
}
// Finalize keeper's vertex to vertex data.
eliminate_vector_duplicates(vertex_to_vertex_indices[keeper]);
// Clear out goner's vertex to vertex data for good.
vertex_to_vertex_indices[goner].clear();
// Note: At this point, vertices[goner] is now a rogue vertex.
// We will skip erasing it from the vertices vector because that would mean a whole lot more work
// (we'd have to reindex every vertex after it in the vector, etc.).
//
// If the mesh is saved to STL, then the rogue vertex will automatically be skipped, and life is good.
//
// If the mesh is saved to POV-Ray mesh2, then the rogue vertex will be included in the vertex
// list, but it will simply not be referenced in the triangle list -- this is a bit inoptimal
// in terms of the file size (it will add a few dozen unneeded bytes to the file size).
return true;
} | [
"44057536@qq.com"
] | 44057536@qq.com |
50c122ad186c974c2310252a6dcd8018a986d5fb | 56e50d4f2a3713d541e7f649d1a108d45a02b51d | /Version0_1_1.cpp | cf626a4bdc4829a6efcc95f2e0eee4856d291d81 | [] | no_license | WYHIII/I-LIKE-APPLE | cacefdbf990148a493e286ade6171a151edce6ad | e73edbf6dbc6acee361d7e3119956878716a5405 | refs/heads/master | 2020-06-24T01:34:37.104728 | 2019-07-27T20:10:06 | 2019-07-27T20:10:06 | 198,809,943 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,405 | cpp | /************************************************
GAME I-LIKE-APPLE by WuYuhang
VERSION 0.1.1
DATE(LAST VIEW) 2019.7.25
************************************************/
#include<iostream>
#include<cstdio>
#include<stdio.h>
#include<cstring>
#include<string>
#include<ctime>
#include<conio.h>
#include<windows.h>
using std::cin;
using std::cout;
using std::endl;
using std::string;
using std::getchar;
using std::putchar;
const int X = 100 + 1;
const int Y = 30 + 1;
const int XX = XX / 2;
const int YY = YY / 2;
const int _HP = 100;
const int _MP = 10;
bool m[X+3][Y+3]; //apple
struct Node {
int x, y;
int hp, mp, xp;
Node(int x = XX, int y = YY, int hp = _HP, int mp = _MP, int xp = 0) {
this->x = x; this->y = y; this->hp = hp; this->mp = mp; this->xp = xp;
}
void draw() {
system("cls");
for (int y = 1; y < Y; y++) {
for (int x = 1; x < X; x++) {
if (y == this->y && x == this->x) {putchar('('); putchar('^'); putchar('_'); putchar('^'); putchar(')');}
else if (m[x][y]) putchar('*');
else putchar(' ');
}
putchar('\n');
}
/*
for (int i = 1; i < this->y; i++) cout << endl;
for (int i = 1; i < this->x; i++) cout << ' ';
cout << "(!)"; */
}
void forward(const int &c) {
draw();
switch(c) {
case 'w': case 'W': if (this->y > 1) this->y = this->y - 1; break;
case 'd': case 'D': if (this->x < X) this->x = this->x + 1; break;
case 's': case 'S': if (this->y < Y) this->y = this->y + 1; break;
case 'a': case 'A': if (this->x > 1) this->x = this->x - 1; break;
}
}
};
inline void zeroClean() {memset(m, false, sizeof(m));}
inline void hideMouse();
void preGame();
int main() {
Node Player;
preGame();
int c;
while (c = getch()) {
Player.forward(c);
}
return 0;
}
inline void hideMouse() {
CONSOLE_CURSOR_INFO cursor_info = {1, 0};
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &cursor_info);
}
void preGame() {
srand((unsigned)time(NULL));
zeroClean();
hideMouse();
for (int k = 1; k <= X*Y/4; k++) {
int x1 = rand() / (RAND_MAX / X);
int y1 = rand() / (RAND_MAX / Y);
if (!m[x1][y1]) m[x1][y1] = true;
}
} | [
"53282395+WYHIII@users.noreply.github.com"
] | 53282395+WYHIII@users.noreply.github.com |
5a3ae9c7d49feaeab3f406f3a8351171ac9b77b6 | 52e7e8516086538699317a0c1a1b263c00690d5e | /maxhs/ifaces/SatSolver.cc | d9056b2c3ed5878196f9d911025c5a6825ce521b | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | fbacchus/MaxHS | 4a2170e25ffc63a57553e22510673abc56f1d23f | c8df41ac63e27c2cb32905302e6ede3118b7a07b | refs/heads/master | 2022-02-08T00:59:40.319946 | 2022-01-24T18:08:11 | 2022-01-24T18:08:11 | 25,798,779 | 23 | 8 | null | null | null | null | UTF-8 | C++ | false | false | 4,285 | cc | /***********[SatSolver.cc]
Copyright (c) 2012-2018 Jessica Davies, Fahiem Bacchus
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.
***********/
/* Generic interface for maxhs to use a satsolver.
Access to a particular sat solver is implemented by defining a
derived class.
The interface maintains a mapping between interally numbered
variables and externally numbered variables.
This is to ensure that the internal variables are consecutively ordered,
so that the external theory can be fed to the sat solver in parts with
generating huge gaps in the variable numbering.
This also means however, that not all external variables will be given a
value by a found sat model.
*/
#include "maxhs/ifaces/SatSolver.h"
#include "maxhs/utils/Params.h"
#include "maxhs/utils/io.h"
namespace MaxHS_Iface {
lbool SatSolver::solveBudget(const vector<Lit>& assumps, vector<Lit>& conflict,
int64_t confBudget, int64_t propagationBudget) {
/*******************************************************************
Solve with assumptions. Track statistics.
can set conflict and propagation budgets (-1 = no budget)
Return l_true/l_false/l_Undef formula is sat/unsat/budget-exceeded
If unsat put conflict clause into conflict (mapped to external numbering)
if sat, the "modelValue" function allow access to satisfying assignment
*******************************************************************/
stime = cpuTime();
prevTotalTime = totalTime;
if(params.verbosity > 3) {
cout << "SatSolver confBudget = " << confBudget << " propagationBudget " <<
propagationBudget << "\n";
}
lbool val = solve_(assumps, conflict, confBudget, propagationBudget);
totalTime += cpuTime() - stime;
stime = -1;
solves++;
return val;
}
lbool SatSolver::solveBudget(const vector<Lit>& assumps, vector<Lit>& conflict,
double timeLimit) {
// sat solver runtime is not very predictable. So if no complex solves have
// been done before odds are the time taken will far from the timeLimit. The
// accuracy of the timeLimit gets better as more solves are executed.
prevTotalTime = totalTime;
bool try_2nd_trial{props_per_second_uncertain()};
int64_t propagationBudget{props_per_time_period(timeLimit)};
if (params.verbosity > 2) {
cout << "SatSolver 1. timelimit = " << time_fmt(timeLimit) << " confBudget = -1 "
<< "propagationBudget = " << propagationBudget << '\n';
}
stime = cpuTime();
lbool val = solve_(assumps, conflict, -1, propagationBudget);
auto solvetime = cpuTime() - stime;
totalTime += solvetime;
stime = -1;
solves++;
if (try_2nd_trial && val == l_Undef && solvetime < timeLimit * .6) {
timeLimit -= solvetime;
int64_t morePropagations = props_per_time_period(timeLimit);
if (morePropagations > propagationBudget * 0.5) {
stime = cpuTime();
val = solve_(assumps, conflict, -1, morePropagations);
totalTime += cpuTime() - stime;
stime = -1;
solves++;
if (params.verbosity > 2) {
cout << "SatSolver 2. timelimit = " << time_fmt(timeLimit) << " confBudget = -1"
<< " propagationBudget " << morePropagations << "\n";
}
}
}
return val;
}
} // namespace MaxHS_Iface
| [
"fbacchus@cs.toronto.edu"
] | fbacchus@cs.toronto.edu |
b21439eb01836e445e14f7fad1541bea92412118 | 3438e8c139a5833836a91140af412311aebf9e86 | /extensions/renderer/argument_spec.cc | 623f13587a4bd2a353ee27eb0f8a964e940184c5 | [
"BSD-3-Clause"
] | permissive | Exstream-OpenSource/Chromium | 345b4336b2fbc1d5609ac5a67dbf361812b84f54 | 718ca933938a85c6d5548c5fad97ea7ca1128751 | refs/heads/master | 2022-12-21T20:07:40.786370 | 2016-10-18T04:53:43 | 2016-10-18T04:53:43 | 71,210,435 | 0 | 2 | BSD-3-Clause | 2022-12-18T12:14:22 | 2016-10-18T04:58:13 | null | UTF-8 | C++ | false | false | 9,274 | 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 "extensions/renderer/argument_spec.h"
#include "base/memory/ptr_util.h"
#include "base/values.h"
#include "content/public/child/v8_value_converter.h"
#include "gin/converter.h"
#include "gin/dictionary.h"
namespace extensions {
namespace {
template <class T>
std::unique_ptr<base::Value> GetFundamentalConvertedValueHelper(
v8::Local<v8::Value> arg,
v8::Local<v8::Context> context,
const base::Optional<int>& minimum) {
T val;
if (!gin::Converter<T>::FromV8(context->GetIsolate(), arg, &val))
return nullptr;
if (minimum && val < minimum.value())
return nullptr;
return base::MakeUnique<base::FundamentalValue>(val);
}
} // namespace
ArgumentSpec::ArgumentSpec(const base::Value& value)
: type_(ArgumentType::INTEGER), optional_(false) {
const base::DictionaryValue* dict = nullptr;
CHECK(value.GetAsDictionary(&dict));
dict->GetBoolean("optional", &optional_);
dict->GetString("name", &name_);
InitializeType(dict);
}
void ArgumentSpec::InitializeType(const base::DictionaryValue* dict) {
std::string ref_string;
if (dict->GetString("$ref", &ref_string)) {
ref_ = std::move(ref_string);
type_ = ArgumentType::REF;
return;
}
std::string type_string;
CHECK(dict->GetString("type", &type_string));
if (type_string == "integer")
type_ = ArgumentType::INTEGER;
else if (type_string == "number")
type_ = ArgumentType::DOUBLE;
else if (type_string == "object")
type_ = ArgumentType::OBJECT;
else if (type_string == "array")
type_ = ArgumentType::LIST;
else if (type_string == "boolean")
type_ = ArgumentType::BOOLEAN;
else if (type_string == "string")
type_ = ArgumentType::STRING;
else if (type_string == "any")
type_ = ArgumentType::ANY;
else if (type_string == "function")
type_ = ArgumentType::FUNCTION;
else
NOTREACHED();
int min = 0;
if (dict->GetInteger("minimum", &min))
minimum_ = min;
const base::DictionaryValue* properties_value = nullptr;
if (type_ == ArgumentType::OBJECT &&
dict->GetDictionary("properties", &properties_value)) {
for (base::DictionaryValue::Iterator iter(*properties_value);
!iter.IsAtEnd(); iter.Advance()) {
properties_[iter.key()] = base::MakeUnique<ArgumentSpec>(iter.value());
}
} else if (type_ == ArgumentType::LIST) {
const base::DictionaryValue* item_value = nullptr;
CHECK(dict->GetDictionary("items", &item_value));
list_element_type_ = base::MakeUnique<ArgumentSpec>(*item_value);
} else if (type_ == ArgumentType::STRING) {
// Technically, there's no reason enums couldn't be other objects (e.g.
// numbers), but right now they seem to be exclusively strings. We could
// always update this if need be.
const base::ListValue* enums = nullptr;
if (dict->GetList("enum", &enums)) {
size_t size = enums->GetSize();
CHECK_GT(size, 0u);
for (size_t i = 0; i < size; ++i) {
std::string enum_value;
CHECK(enums->GetString(i, &enum_value));
enum_values_.insert(std::move(enum_value));
}
}
}
}
ArgumentSpec::~ArgumentSpec() {}
std::unique_ptr<base::Value> ArgumentSpec::ConvertArgument(
v8::Local<v8::Context> context,
v8::Local<v8::Value> value,
const RefMap& refs,
std::string* error) const {
// TODO(devlin): Support functions?
DCHECK_NE(type_, ArgumentType::FUNCTION);
if (type_ == ArgumentType::REF) {
DCHECK(ref_);
auto iter = refs.find(ref_.value());
DCHECK(iter != refs.end()) << ref_.value();
return iter->second->ConvertArgument(context, value, refs, error);
}
if (IsFundamentalType())
return ConvertArgumentToFundamental(context, value, error);
if (type_ == ArgumentType::OBJECT) {
// TODO(devlin): Currently, this would accept an array (if that array had
// all the requisite properties). Is that the right thing to do?
if (!value->IsObject()) {
*error = "Wrong type";
return nullptr;
}
v8::Local<v8::Object> object = value.As<v8::Object>();
return ConvertArgumentToObject(context, object, refs, error);
}
if (type_ == ArgumentType::LIST) {
if (!value->IsArray()) {
*error = "Wrong type";
return nullptr;
}
v8::Local<v8::Array> array = value.As<v8::Array>();
return ConvertArgumentToArray(context, array, refs, error);
}
if (type_ == ArgumentType::ANY)
return ConvertArgumentToAny(context, value, error);
NOTREACHED();
return nullptr;
}
bool ArgumentSpec::IsFundamentalType() const {
return type_ == ArgumentType::INTEGER || type_ == ArgumentType::DOUBLE ||
type_ == ArgumentType::BOOLEAN || type_ == ArgumentType::STRING;
}
std::unique_ptr<base::Value> ArgumentSpec::ConvertArgumentToFundamental(
v8::Local<v8::Context> context,
v8::Local<v8::Value> value,
std::string* error) const {
DCHECK(IsFundamentalType());
switch (type_) {
case ArgumentType::INTEGER:
return GetFundamentalConvertedValueHelper<int32_t>(value, context,
minimum_);
case ArgumentType::DOUBLE:
return GetFundamentalConvertedValueHelper<double>(value, context,
minimum_);
case ArgumentType::STRING: {
std::string s;
// TODO(devlin): If base::StringValue ever takes a std::string&&, we could
// use std::move to construct.
if (!gin::Converter<std::string>::FromV8(context->GetIsolate(),
value, &s) ||
(!enum_values_.empty() && enum_values_.count(s) == 0)) {
return nullptr;
}
return base::MakeUnique<base::StringValue>(s);
}
case ArgumentType::BOOLEAN: {
bool b = false;
if (value->IsBoolean() &&
gin::Converter<bool>::FromV8(context->GetIsolate(), value, &b)) {
return base::MakeUnique<base::FundamentalValue>(b);
}
return nullptr;
}
default:
NOTREACHED();
}
return nullptr;
}
std::unique_ptr<base::Value> ArgumentSpec::ConvertArgumentToObject(
v8::Local<v8::Context> context,
v8::Local<v8::Object> object,
const RefMap& refs,
std::string* error) const {
DCHECK_EQ(ArgumentType::OBJECT, type_);
auto result = base::MakeUnique<base::DictionaryValue>();
gin::Dictionary dictionary(context->GetIsolate(), object);
for (const auto& kv : properties_) {
v8::Local<v8::Value> subvalue;
// See comment in ConvertArgumentToArray() about passing in custom crazy
// values here.
// TODO(devlin): gin::Dictionary::Get() uses Isolate::GetCurrentContext() -
// is that always right here, or should we use the v8::Object APIs and
// pass in |context|?
// TODO(devlin): Hyper-optimization - Dictionary::Get() also creates a new
// v8::String for each call. Hypothetically, we could cache these, or at
// least use an internalized string.
if (!dictionary.Get(kv.first, &subvalue))
return nullptr;
if (subvalue.IsEmpty() || subvalue->IsNull() || subvalue->IsUndefined()) {
if (!kv.second->optional_) {
*error = "Missing key: " + kv.first;
return nullptr;
}
continue;
}
std::unique_ptr<base::Value> property =
kv.second->ConvertArgument(context, subvalue, refs, error);
if (!property)
return nullptr;
result->Set(kv.first, std::move(property));
}
return std::move(result);
}
std::unique_ptr<base::Value> ArgumentSpec::ConvertArgumentToArray(
v8::Local<v8::Context> context,
v8::Local<v8::Array> value,
const RefMap& refs,
std::string* error) const {
DCHECK_EQ(ArgumentType::LIST, type_);
auto result = base::MakeUnique<base::ListValue>();
uint32_t length = value->Length();
for (uint32_t i = 0; i < length; ++i) {
v8::MaybeLocal<v8::Value> maybe_subvalue = value->Get(context, i);
v8::Local<v8::Value> subvalue;
// Note: This can fail in the case of a developer passing in the following:
// var a = [];
// Object.defineProperty(a, 0, { get: () => { throw new Error('foo'); } });
// Currently, this will cause the developer-specified error ('foo') to be
// thrown.
// TODO(devlin): This is probably fine, but it's worth contemplating
// catching the error and throwing our own.
if (!maybe_subvalue.ToLocal(&subvalue))
return nullptr;
std::unique_ptr<base::Value> item =
list_element_type_->ConvertArgument(context, subvalue, refs, error);
if (!item)
return nullptr;
result->Append(std::move(item));
}
return std::move(result);
}
std::unique_ptr<base::Value> ArgumentSpec::ConvertArgumentToAny(
v8::Local<v8::Context> context,
v8::Local<v8::Value> value,
std::string* error) const {
DCHECK_EQ(ArgumentType::ANY, type_);
std::unique_ptr<content::V8ValueConverter> converter(
content::V8ValueConverter::create());
std::unique_ptr<base::Value> converted(
converter->FromV8Value(value, context));
if (!converted)
*error = "Could not convert to 'any'.";
return converted;
}
} // namespace extensions
| [
"support@opentext.com"
] | support@opentext.com |
58e75abf3afb92a8a225b00d48b69557f214cd2c | 450e2dba7742f412c1385ef0ca0339877465ca68 | /src/Model_Hydro/Hydro_BoundaryCondition_Outflow.cpp | ce5d4e10a0673d9680643885a3e85737d6a3f0a3 | [
"BSD-3-Clause"
] | permissive | luminosa42/gamer | e25c01161116ee88c3dec84b0f5bfbb298232c98 | 418c6a9b50ba47459cb85ddabf5abf4cb2fb6273 | refs/heads/master | 2021-01-04T03:48:49.830028 | 2020-02-09T12:41:49 | 2020-02-09T12:41:49 | 240,367,991 | 1 | 0 | NOASSERTION | 2020-02-13T21:37:11 | 2020-02-13T21:37:10 | null | UTF-8 | C++ | false | false | 12,432 | cpp | #include "GAMER.h"
static void BC_Outflow_xm( real *Array, const int NVar, const int GhostSize, const int ArraySizeX, const int ArraySizeY,
const int ArraySizeZ, const int Idx_Start[], const int Idx_End[] );
static void BC_Outflow_xp( real *Array, const int NVar, const int GhostSize, const int ArraySizeX, const int ArraySizeY,
const int ArraySizeZ, const int Idx_Start[], const int Idx_End[] );
static void BC_Outflow_ym( real *Array, const int NVar, const int GhostSize, const int ArraySizeX, const int ArraySizeY,
const int ArraySizeZ, const int Idx_Start[], const int Idx_End[] );
static void BC_Outflow_yp( real *Array, const int NVar, const int GhostSize, const int ArraySizeX, const int ArraySizeY,
const int ArraySizeZ, const int Idx_Start[], const int Idx_End[] );
static void BC_Outflow_zm( real *Array, const int NVar, const int GhostSize, const int ArraySizeX, const int ArraySizeY,
const int ArraySizeZ, const int Idx_Start[], const int Idx_End[] );
static void BC_Outflow_zp( real *Array, const int NVar, const int GhostSize, const int ArraySizeX, const int ArraySizeY,
const int ArraySizeZ, const int Idx_Start[], const int Idx_End[] );
//-------------------------------------------------------------------------------------------------------
// Function : Hydro_BoundaryCondition_Outflow
// Description : Fill up the ghost-zone values by the outflow B.C.
//
// Note : 1. Work for Prepare_PatchData(), InterpolateGhostZone(), Refine(), and LB_Refine_GetNewRealPatchList()
// 2. Specifically, the so-called outflow B.C. is actually the **zero-gradient** B.C.
//
// Parameter : Array : Array to store the prepared data including ghost zones
// BC_Face : Boundary face (0~5) --> (-x,+x,-y,+y,-z,+z)
// NVar : Number of fluid and derived variables to be prepared
// GhostSize : Number of ghost zones
// ArraySizeX/Y/Z : Size of Array including the ghost zones on each side
// Idx_Start : Minimum array indices
// Idx_End : Maximum array indices
//
// Return : Array
//-------------------------------------------------------------------------------------------------------
void Hydro_BoundaryCondition_Outflow( real *Array, const int BC_Face, const int NVar, const int GhostSize,
const int ArraySizeX, const int ArraySizeY, const int ArraySizeZ,
const int Idx_Start[], const int Idx_End[] )
{
// check the index range
# ifdef GAMER_DEBUG
switch ( BC_Face )
{
case 0: if ( Idx_Start[0] != 0 || Idx_End[0] != GhostSize-1 )
Aux_Error( ERROR_INFO, "incorrect index range (Start %d, End %d, GhostSize %d, Face %d) !!\n",
Idx_Start[0], Idx_End[0], GhostSize, BC_Face ); break;
case 1: if ( Idx_Start[0] != ArraySizeX-GhostSize || Idx_End[0] != ArraySizeX-1 )
Aux_Error( ERROR_INFO, "incorrect index range (Start %d, End %d, GhostSize %d, Face %d) !!\n",
Idx_Start[0], Idx_End[0], GhostSize, BC_Face ); break;
case 2: if ( Idx_Start[1] != 0 || Idx_End[1] != GhostSize-1 )
Aux_Error( ERROR_INFO, "incorrect index range (Start %d, End %d, GhostSize %d, Face %d) !!\n",
Idx_Start[1], Idx_End[1], GhostSize, BC_Face ); break;
case 3: if ( Idx_Start[1] != ArraySizeY-GhostSize || Idx_End[1] != ArraySizeY-1 )
Aux_Error( ERROR_INFO, "incorrect index range (Start %d, End %d, GhostSize %d, Face %d) !!\n",
Idx_Start[1], Idx_End[1], GhostSize, BC_Face ); break;
case 4: if ( Idx_Start[2] != 0 || Idx_End[2] != GhostSize-1 )
Aux_Error( ERROR_INFO, "incorrect index range (Start %d, End %d, GhostSize %d, Face %d) !!\n",
Idx_Start[2], Idx_End[2], GhostSize, BC_Face ); break;
case 5: if ( Idx_Start[2] != ArraySizeZ-GhostSize || Idx_End[2] != ArraySizeZ-1 )
Aux_Error( ERROR_INFO, "incorrect index range (Start %d, End %d, GhostSize %d, Face %d) !!\n",
Idx_Start[2], Idx_End[2], GhostSize, BC_Face ); break;
default: Aux_Error( ERROR_INFO, "incorrect boundary face (%d) !!\n", BC_Face );
} // switch ( BC_Face )
# endif // #ifdef GAMER_DEBUG
// set the boundary values at different boundary faces
switch ( BC_Face )
{
case 0: BC_Outflow_xm( Array, NVar, GhostSize, ArraySizeX, ArraySizeY, ArraySizeZ, Idx_Start, Idx_End ); break;
case 1: BC_Outflow_xp( Array, NVar, GhostSize, ArraySizeX, ArraySizeY, ArraySizeZ, Idx_Start, Idx_End ); break;
case 2: BC_Outflow_ym( Array, NVar, GhostSize, ArraySizeX, ArraySizeY, ArraySizeZ, Idx_Start, Idx_End ); break;
case 3: BC_Outflow_yp( Array, NVar, GhostSize, ArraySizeX, ArraySizeY, ArraySizeZ, Idx_Start, Idx_End ); break;
case 4: BC_Outflow_zm( Array, NVar, GhostSize, ArraySizeX, ArraySizeY, ArraySizeZ, Idx_Start, Idx_End ); break;
case 5: BC_Outflow_zp( Array, NVar, GhostSize, ArraySizeX, ArraySizeY, ArraySizeZ, Idx_Start, Idx_End ); break;
default: Aux_Error( ERROR_INFO, "incorrect boundary face (%d) !!\n", BC_Face );
}
} // FUNCTION : Hydro_BoundaryCondition_Outflow
//-------------------------------------------------------------------------------------------------------
// Function : BC_Outflow_xm
// Description : Set the outflow B.C. at the -x boundary
//
// Note : Work for Hydro_BoundaryCondition_Outflow()
//
// Parameter : See Hydro_BoundaryCondition_Outflow()
//
// Return : Array
//-------------------------------------------------------------------------------------------------------
void BC_Outflow_xm( real *Array, const int NVar, const int GhostSize, const int ArraySizeX, const int ArraySizeY,
const int ArraySizeZ, const int Idx_Start[], const int Idx_End[] )
{
const int i_ref = GhostSize; // reference i index
// 1D array -> 3D array
real (*Array3D)[ArraySizeZ][ArraySizeY][ArraySizeX] = ( real (*)[ArraySizeZ][ArraySizeY][ArraySizeX] )Array;
// set the boundary values
for (int v=0; v<NVar; v++)
for (int k=Idx_Start[2]; k<=Idx_End[2]; k++)
for (int j=Idx_Start[1]; j<=Idx_End[1]; j++)
for (int i=Idx_Start[0]; i<=Idx_End[0]; i++)
Array3D[v][k][j][i] = Array3D[v][k][j][i_ref];
} // FUNCTION : BC_Outflow_xm
//-------------------------------------------------------------------------------------------------------
// Function : BC_Outflow_xp
// Description : Set the outflow B.C. at the +x boundary
//
// Note : Work for Hydro_BoundaryCondition_Outflow()
//
// Parameter : See Hydro_BoundaryCondition_Outflow()
//
// Return : Array
//-------------------------------------------------------------------------------------------------------
void BC_Outflow_xp( real *Array, const int NVar, const int GhostSize, const int ArraySizeX, const int ArraySizeY,
const int ArraySizeZ, const int Idx_Start[], const int Idx_End[] )
{
const int i_ref = ArraySizeX - GhostSize - 1; // reference i index
// 1D array -> 3D array
real (*Array3D)[ArraySizeZ][ArraySizeY][ArraySizeX] = ( real (*)[ArraySizeZ][ArraySizeY][ArraySizeX] )Array;
// set the boundary values
for (int v=0; v<NVar; v++)
for (int k=Idx_Start[2]; k<=Idx_End[2]; k++)
for (int j=Idx_Start[1]; j<=Idx_End[1]; j++)
for (int i=Idx_Start[0]; i<=Idx_End[0]; i++)
Array3D[v][k][j][i] = Array3D[v][k][j][i_ref];
} // FUNCTION : BC_Outflow_xp
//-------------------------------------------------------------------------------------------------------
// Function : BC_Outflow_ym
// Description : Set the outflow B.C. at the -y boundary
//
// Note : Work for Hydro_BoundaryCondition_Outflow()
//
// Parameter : See Hydro_BoundaryCondition_Outflow()
//
// Return : Array
//-------------------------------------------------------------------------------------------------------
void BC_Outflow_ym( real *Array, const int NVar, const int GhostSize, const int ArraySizeX, const int ArraySizeY,
const int ArraySizeZ, const int Idx_Start[], const int Idx_End[] )
{
const int j_ref = GhostSize; // reference j index
// 1D array -> 3D array
real (*Array3D)[ArraySizeZ][ArraySizeY][ArraySizeX] = ( real (*)[ArraySizeZ][ArraySizeY][ArraySizeX] )Array;
// set the boundary values
for (int v=0; v<NVar; v++)
for (int k=Idx_Start[2]; k<=Idx_End[2]; k++)
for (int j=Idx_Start[1]; j<=Idx_End[1]; j++)
for (int i=Idx_Start[0]; i<=Idx_End[0]; i++)
Array3D[v][k][j][i] = Array3D[v][k][j_ref][i];
} // FUNCTION : BC_Outflow_ym
//-------------------------------------------------------------------------------------------------------
// Function : BC_Outflow_yp
// Description : Set the outflow B.C. at the +y boundary
//
// Note : Work for Hydro_BoundaryCondition_Outflow()
//
// Parameter : See Hydro_BoundaryCondition_Outflow()
//
// Return : Array
//-------------------------------------------------------------------------------------------------------
void BC_Outflow_yp( real *Array, const int NVar, const int GhostSize, const int ArraySizeX, const int ArraySizeY,
const int ArraySizeZ, const int Idx_Start[], const int Idx_End[] )
{
const int j_ref = ArraySizeY - GhostSize - 1; // reference j index
// 1D array -> 3D array
real (*Array3D)[ArraySizeZ][ArraySizeY][ArraySizeX] = ( real (*)[ArraySizeZ][ArraySizeY][ArraySizeX] )Array;
// set the boundary values
for (int v=0; v<NVar; v++)
for (int k=Idx_Start[2]; k<=Idx_End[2]; k++)
for (int j=Idx_Start[1]; j<=Idx_End[1]; j++)
for (int i=Idx_Start[0]; i<=Idx_End[0]; i++)
Array3D[v][k][j][i] = Array3D[v][k][j_ref][i];
} // FUNCTION : BC_Outflow_yp
//-------------------------------------------------------------------------------------------------------
// Function : BC_Outflow_zm
// Description : Set the outflow B.C. at the -z boundary
//
// Note : Work for Hydro_BoundaryCondition_Outflow()
//
// Parameter : See Hydro_BoundaryCondition_Outflow()
//
// Return : Array
//-------------------------------------------------------------------------------------------------------
void BC_Outflow_zm( real *Array, const int NVar, const int GhostSize, const int ArraySizeX, const int ArraySizeY,
const int ArraySizeZ, const int Idx_Start[], const int Idx_End[] )
{
const int k_ref = GhostSize; // reference k index
// 1D array -> 3D array
real (*Array3D)[ArraySizeZ][ArraySizeY][ArraySizeX] = ( real (*)[ArraySizeZ][ArraySizeY][ArraySizeX] )Array;
// set the boundary values
for (int v=0; v<NVar; v++)
for (int k=Idx_Start[2]; k<=Idx_End[2]; k++)
for (int j=Idx_Start[1]; j<=Idx_End[1]; j++)
for (int i=Idx_Start[0]; i<=Idx_End[0]; i++)
Array3D[v][k][j][i] = Array3D[v][k_ref][j][i];
} // FUNCTION : BC_Outflow_zm
//-------------------------------------------------------------------------------------------------------
// Function : BC_Outflow_zp
// Description : Set the outflow B.C. at the +z boundary
//
// Note : Work for Hydro_BoundaryCondition_Outflow()
//
// Parameter : See Hydro_BoundaryCondition_Outflow()
//
// Return : Array
//-------------------------------------------------------------------------------------------------------
void BC_Outflow_zp( real *Array, const int NVar, const int GhostSize, const int ArraySizeX, const int ArraySizeY,
const int ArraySizeZ, const int Idx_Start[], const int Idx_End[] )
{
const int k_ref = ArraySizeZ - GhostSize - 1; // reference k index
// 1D array -> 3D array
real (*Array3D)[ArraySizeZ][ArraySizeY][ArraySizeX] = ( real (*)[ArraySizeZ][ArraySizeY][ArraySizeX] )Array;
// set the boundary values
for (int v=0; v<NVar; v++)
for (int k=Idx_Start[2]; k<=Idx_End[2]; k++)
for (int j=Idx_Start[1]; j<=Idx_End[1]; j++)
for (int i=Idx_Start[0]; i<=Idx_End[0]; i++)
Array3D[v][k][j][i] = Array3D[v][k_ref][j][i];
} // FUNCTION : BC_Outflow_zp
| [
"hyschive@gmail.com"
] | hyschive@gmail.com |
ff188ea3cfa4cc111b13d4ef7976c049d2bb996f | 63168b3cc1a8019583b331ebc8c4ec58c241753c | /inference-engine/tests/functional/inference_engine/ov_variable_state_test.cpp | f9233e5eebc9b0a74d25af76f359329fcb61da15 | [
"Apache-2.0"
] | permissive | generalova-kate/openvino | 2e14552ab9b1196fe35af63b5751a96d0138587a | 72fb7d207cb61fd5b9bb630ee8785881cc656b72 | refs/heads/master | 2023-08-09T20:39:03.377258 | 2021-09-07T09:43:33 | 2021-09-07T09:43:33 | 300,206,718 | 0 | 0 | Apache-2.0 | 2020-10-01T08:35:46 | 2020-10-01T08:35:45 | null | UTF-8 | C++ | false | false | 918 | cpp | // Copyright (C) 2018-2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <gtest/gtest.h>
#include <openvino/runtime/variable_state.hpp>
using namespace ::testing;
using namespace std;
TEST(VariableStateOVTests, throwsOnUninitializedReset) {
ov::runtime::VariableState state;
ASSERT_THROW(state.reset(), InferenceEngine::NotAllocated);
}
TEST(VariableStateOVTests, throwsOnUninitializedGetname) {
ov::runtime::VariableState state;
ASSERT_THROW(state.get_name(), InferenceEngine::NotAllocated);
}
TEST(VariableStateOVTests, throwsOnUninitializedGetState) {
ov::runtime::VariableState state;
ASSERT_THROW(state.get_state(), InferenceEngine::NotAllocated);
}
TEST(VariableStateOVTests, throwsOnUninitializedSetState) {
ov::runtime::VariableState state;
InferenceEngine::Blob::Ptr blob;
ASSERT_THROW(state.set_state(blob), InferenceEngine::NotAllocated);
}
| [
"noreply@github.com"
] | generalova-kate.noreply@github.com |
5257e68e5286429bcc31bd22727c1969a71a9ad6 | 18e6fbe21381ccfa0c61492a3542629ec9e9d3f5 | /trace-cocoa-sdk/TraceInternal/CrashReporting/swift/Basic/Punycode.h | b73888abcbb47109891a3391dd2f01dc0ba1246e | [
"Apache-2.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | zhanyongZhang/apm-ios-test-mortyUI | d827972ba3b0f93c971292e22f8cf7d3b83d09a0 | 13da0bdf7ed581b7d0f182d185580ebbc05cf593 | refs/heads/main | 2023-03-03T12:12:33.878439 | 2021-02-08T00:26:02 | 2021-02-08T00:26:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,134 | h | //===--- Punycode.h - UTF-8 to Punycode transcoding -------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// These functions implement a variant of the Punycode algorithm from RFC3492,
// originally designed for encoding international domain names, for the purpose
// of encoding Swift identifiers into mangled symbol names. This version differs
// from RFC3492 in the following respects:
// - '_' is used as the encoding delimiter instead of '-'.
// - Encoding digits are represented using [a-zA-J] instead of [a-z0-9], because
// symbol names are case-sensitive, and Swift mangled identifiers cannot begin
// with a digit.
//
//===----------------------------------------------------------------------===//
#ifndef CRASHREPORTING_SWIFT_BASIC_PUNYCODE_H
#define CRASHREPORTING_SWIFT_BASIC_PUNYCODE_H
//#include "swift/Basic/LLVM.h"
//#include "llvm/ADT/StringRef.h"
//#include "llvm/ADT/SmallVector.h"
#include "LLVM.h"
#include "StringRef.h"
#include <vector>
#include <cstdint>
namespace swift {
namespace Punycode {
/// Encodes a sequence of code points into Punycode.
///
/// Returns false if input contains surrogate code points.
bool encodePunycode(const std::vector<uint32_t> &InputCodePoints,
std::string &OutPunycode);
/// Decodes a Punycode string into a sequence of Unicode scalars.
///
/// Returns false if decoding failed.
bool decodePunycode(StringRef InputPunycode,
std::vector<uint32_t> &OutCodePoints);
bool encodePunycodeUTF8(StringRef InputUTF8, std::string &OutPunycode);
bool decodePunycodeUTF8(StringRef InputPunycode, std::string &OutUTF8);
} // end namespace Punycode
} // end namespace swift
#endif // CRASHREPORTING_SWIFT_BASIC_PUNYCODE_H
| [
"shamsahmed@me.com"
] | shamsahmed@me.com |
cec11362e4c17ba8da41eed7829ff8b912293ed1 | aaeafd2d5360abfdd837578b6f208d6a701d02cd | /prcore/src/prcore/osx/timer.cpp | 5e0559c5de0e4d50ae1a760770f48fb99e0375ee | [] | no_license | ARRENl/Test_Assigment_prophesy_engine_Arcanoid | be375a07a3cb7a658f805c54800026d974aef5a3 | dea5f00df0ecb54ebc76aa563d434d27535855d8 | refs/heads/master | 2020-05-19T18:41:30.897409 | 2015-02-23T07:57:47 | 2015-02-23T07:57:47 | 30,100,925 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,213 | cpp | /*
Twilight Prophecy SDK
A multi-platform development system for virtual reality and multimedia.
Copyright (C) 1997-2003 Twilight 3D Finland Oy Ltd.
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
source:
Timer Linux implementation
revision history:
December/25/2003 - Stefan Karlsson - created with base on Edmond Cote/Daniel Kolawskis code.
Todo: REWRITE (?)
*/
#include <prcore/prcore.hpp>
#include <sys/time.h>
#include <unistd.h>
namespace prcore
{
// NOTE: this is a very basic timer
static struct timeval start;
static struct timeval now;
Timer::Timer()
{
gettimeofday(&start,NULL);
}
Timer::~Timer()
{
}
void Timer::Reset()
{
}
float Timer::GetTime() const
{
gettimeofday(&now,NULL);
return (float)((now.tv_sec-start.tv_sec)*1000+(now.tv_usec-start.tv_usec)/1000.0f)/1000.f;
}
uint32 Timer::GetTick() const
{
gettimeofday(&now,NULL);
return ((now.tv_sec-start.tv_sec)*1000+(now.tv_usec-start.tv_usec)/1000);
}
TimeInfo GetTimeInfo()
{
TimeInfo time;
// TODO
time.year = 0;
time.month = 0;
time.day = 0;
time.hour = 0;
time.minute = 0;
time.second = 0;
time.milliseconds = 0;
return time;
}
}
| [
"alexanderartemchuk89@gmail.com"
] | alexanderartemchuk89@gmail.com |
d92588e7460b5daf247575790f86f3ebf1c1ec22 | 3f75df57ae155e3eaada2885b12b78a63bbc43a1 | /source/Geometry/tbeam/src/TBdchX02.cc | 152e444d0ba949f7a00fbeb724eb174a3183216f | [] | no_license | nkxuyin/mokka-cepc | 52bb13455b6fc5961de678ad7cb695f754e49a47 | 61ce9f792a4cb8883f0d1cd1391884444b372dc0 | refs/heads/master | 2021-01-20T10:42:00.982704 | 2015-02-11T12:59:43 | 2015-02-11T12:59:43 | 24,243,983 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,464 | cc | //#####################################
// #
// Driver used to simulate the drift #
// chambers in the 2006 Desy setup #
// #
//#####################################
#include "TBdchX02.hh"
// #include "TBSD_VCell02.hh"
//#include "TBCellReplication.hh"
#include "Control.hh"
#include "CGADefs.h"
#include "MySQLWrapper.hh"
#include "G4Material.hh"
#include "G4MaterialTable.hh"
#include "G4Element.hh"
#include "G4ElementTable.hh"
#include "G4Isotope.hh"
#include "CGAGeometryManager.hh"
#include "G4Box.hh"
#include "G4LogicalVolume.hh"
#include "G4PVPlacement.hh"
#include "G4VPhysicalVolume.hh"
#include "G4VisAttributes.hh"
#include <sstream>
INSTANTIATE(TBdchX02)
TBdchX02::~TBdchX02()
{}
G4bool TBdchX02::ContextualConstruct(const CGAGeometryEnvironment &aGeometryEnvironment,
G4LogicalVolume *theWorld)
{
ecal_front_face = aGeometryEnvironment.GetParameterAsDouble("ecal_begin_z");
// variable config_angle (a double) will be used by method "construct" to place the detector
config_angle = aGeometryEnvironment.GetParameterAsDouble("configuration_angle");
// variables translateX and translateY have default value (0,0) and are used
// to translate DCH and Sci wrt beam axis (user defined parameters)
translateX = aGeometryEnvironment.GetParameterAsDouble("TranslateX");
translateY = aGeometryEnvironment.GetParameterAsDouble("TranslateY");
G4cout << "\nBuilding TBdchX02..." << G4endl;
db = new Database(aGeometryEnvironment.GetDBName());
// fetch db parms
FetchAll();
G4bool doDch1 = DchConstruct (theWorld,x_place1,y_place1,z_place1,1);
G4bool doDch2 = DchConstruct (theWorld,x_place2,y_place2,z_place2,2);
G4bool doDch3 = DchConstruct (theWorld,x_place3,y_place3,z_place3,3);
G4bool doDch4 = DchConstruct (theWorld,x_place4,y_place4,z_place4,4);
delete db;
db = 0;
G4bool doDch = false;
if (doDch1 && doDch2 && doDch3 && doDch4) doDch = true;
G4cout << "\nDone building TBdchX02" << G4endl;
return doDch;
}
G4bool TBdchX02::DchConstruct(G4LogicalVolume *WorldLog,
G4double x_place, G4double y_place, G4double z_place,
G4int idch)
{
G4cout << " Building Drift Chamber " << idch << G4endl;
WorldLogVol = WorldLog;
// depth to layer
SetDepthToLayer(1);
G4cout << " Building DCH elements " << G4endl;
BuildElements();
// do build process
G4bool cokay = BuildDch(x_place, y_place, z_place);
// set Sensitive Detector
SetSD(idch);
return cokay;
}
void TBdchX02::FetchAll()
{
config_angle = config_angle*deg;
db->exec("select * from dch_virt;");
db->getTuple();
ncell_xy[0] = db->fetchDouble("dch_dim_x"); // 72 mm
ncell_xy[1] = db->fetchDouble("dch_dim_y"); // 72 mm
assert(ncell_xy[0]>0 && ncell_xy[1]>0);
z_place1 = db->fetchDouble("z_placeX1"); // 682mm from ECAL front face
z_place2 = db->fetchDouble("z_placeX2"); // 1782mm from ECAL front face
z_place3 = db->fetchDouble("z_placeX3"); // 2692mm from ECAL front face
z_place4 = db->fetchDouble("z_placeX4"); // 3792mm from ECAL front face
// take into account configuration angle and translation
x_place1 = translateX + (ecal_front_face + z_place1)*sin(config_angle);
y_place1 = translateY;
z_place1 = (ecal_front_face + z_place1)*cos(config_angle);
x_place2 = translateX + (ecal_front_face + z_place2)*sin(config_angle);
y_place2 = translateY;
z_place2 = (ecal_front_face + z_place2)*cos(config_angle);
x_place3 = translateX + (ecal_front_face + z_place3)*sin(config_angle);
y_place3 = translateY;
z_place3 = (ecal_front_face + z_place3)*cos(config_angle);
x_place4 = translateX + (ecal_front_face + z_place4)*sin(config_angle);
y_place4 = translateY;
z_place4 = (ecal_front_face + z_place4)*cos(config_angle);
db->exec("select * from layer_thickness;");
db->getTuple();
winfront_hthickness = db->fetchDouble("winfront_thickness"); // 20 micron
dch_hthickness = db->fetchDouble("dch_thickness"); // 44 mm
gas_hthickness = dch_hthickness - winfront_hthickness;
gas_temperature = STP_Temperature;
gas_pressure = db->fetchDouble("gas_pressure"); // 1.2 atm (+0.2Kg/cm^2)
gas_pressure = gas_pressure*atmosphere;
grid_size = 1;
Print();
}
void TBdchX02::BuildElements()
{
// materials
G4String name, symbol;
G4int nel, natoms;
G4double a, z, density, temperature, pressure;
G4double fractionmass;
// Hydrogen
a = 1.01*g/mole;
elH = new G4Element(name="Hydrogen",symbol="H" , z= 1., a);
// Carbon
a = 12.01*g/mole;
elC = new G4Element(name="Carbon" ,symbol="C" , z= 6., a);
// Oxigen
a = 16.00*g/mole;
elO = new G4Element(name="Oxigen", symbol="O", z=8., a);
// Nitrogen
a = 14.01*g/mole;
elN = new G4Element(name="Nitrogen", symbol="N", z=7., a);
// Argon
a = 39.95*g/mole;
density = 1.78e-3*g/cm3;
elAr= new G4Material(name="Argon", z=18., a, density);
// Air
density = 1.29e-3*g/cm3;
air = new G4Material(name="Air", density, nel=2);
air->AddElement(elN, fractionmass=0.7);
air->AddElement(elO, fractionmass=0.3);
// Ethane
density = 1.36e-3*g/cm3;
C2H6 = new G4Material(name="Ethane", density, nel=2, kStateGas);
C2H6->AddElement(elC, natoms=2);
C2H6->AddElement(elH, natoms=6);
// Gas mixture in DCH is 96% Ar and 4% Ethane (C2H6)
density = ((1.78e-3)*0.96 + (1.36e-3)*0.04)*g/cm3;
temperature = gas_temperature;
pressure = gas_pressure;
gas_mix = new G4Material(name="mixture", density, nel=2, kStateGas, temperature, pressure);
gas_mix->AddMaterial(elAr, 96*perCent);
gas_mix->AddMaterial(C2H6, 4*perCent);
// Mylar
density = 1.39*g/cm3;
mylar = new G4Material(name="Mylar", density, nel=3);
mylar->AddElement(elC, natoms=3);
mylar->AddElement(elH, natoms=4);
mylar->AddElement(elO, natoms=2);
// dch (half) dimensions
dch_hx = (ncell_xy[0])/2;
dch_hy = (ncell_xy[1])/2;
dch_hz = dch_hthickness/2;
mylarF_hz = winfront_hthickness/2;
gas_hz = gas_hthickness/2;
// mylarB_hz = winback_hthickness/2;
// detector
G4Box *DetectorSolid = new G4Box("DetectorSolid",
dch_hx,
dch_hy,
dch_hz);
DetectorLogical = new G4LogicalVolume(DetectorSolid,
air,
"DetectorLogical",
0,
0,
0);
G4cout << " Dimension of detector box " << G4endl;
G4cout << " dch_hx: " << dch_hx*2 << " mm " << G4endl;
G4cout << " dch_hy: " << dch_hy*2 << " mm " << G4endl;
G4cout << " dch_hz: " << dch_hz*2 << " mm " << G4endl;
// Mylar front window
G4Box *MylarFrontWindow = new G4Box("MylarFrontWindow",
dch_hx,
dch_hy,
mylarF_hz);
MylarFrontLogical = new G4LogicalVolume(MylarFrontWindow,
mylar,
"MylarFrontLogical",
0,
0,
0);
G4cout << " Dimension of front window " << G4endl;
G4cout << " dch_hx: " << dch_hx*2 << " mm " << G4endl;
G4cout << " dch_hy: " << dch_hy*2 << " mm " << G4endl;
G4cout << " dch_hz: " << mylarF_hz*2 << " mm " << G4endl;
// Ar-Ethane gas mixture
G4Box *GasSolid = new G4Box("GasSolid",
dch_hx,
dch_hy,
gas_hz);
GasLogical = new G4LogicalVolume(GasSolid,
gas_mix,
"GasLogical",
0,
0,
0);
G4cout << " Dimension of gas volume " << G4endl;
G4cout << " dch_hx: " << dch_hx*2 << " mm " << G4endl;
G4cout << " dch_hy: " << dch_hy*2 << " mm " << G4endl;
G4cout << " dch_hz: " << gas_hz*2 << " mm " << G4endl;
}
G4bool TBdchX02::BuildDch(G4double x_place, G4double y_place, G4double z_place)
{
G4cout << " Building Dch structure " << G4endl;
G4cout << " x_place of full Dch detector " << x_place << G4endl;
G4cout << " y_place of full Dch detector " << y_place << G4endl;
G4cout << " z_place of full Dch detector " << z_place << G4endl;
translateDch = G4ThreeVector(x_place, y_place, z_place);
G4RotationMatrix rotateDch;
rotateDch.rotateY(config_angle);
transformDch = new G4Transform3D(rotateDch, translateDch);
new G4PVPlacement(*transformDch,
DetectorLogical,
"DetectorPhys",
WorldLogVol,
0,
0);
// Place gas part of the detector in the middle of detector box
G4double gas_z = winfront_hthickness/2;
new G4PVPlacement(0,
G4ThreeVector(0.,0.,gas_z),
GasLogical,
"GasPhys",
DetectorLogical,
false,
0);
G4VisAttributes *gasColour = new G4VisAttributes(G4Colour(1.,0.,1.));
gasColour->SetVisibility(true);
GasLogical->SetVisAttributes(gasColour);
G4double wfront_z = winfront_hthickness/2 - dch_hthickness/2;
G4cout << " Front window Z position (centre, wrt detector box): " << wfront_z << " mm " << G4endl;
new G4PVPlacement(0,
G4ThreeVector(0.,0.,wfront_z),
MylarFrontLogical,
"WinFrontPhys",
DetectorLogical,
false,
0);
G4VisAttributes *winColour = new G4VisAttributes(G4Colour(0.,1.,0.));
winColour->SetVisibility(true);
MylarFrontLogical->SetVisAttributes(winColour);
return true;
}
void TBdchX02::SetSD(G4int idch)
{
G4String base = "dchSDx";
stringstream s;
s << base << idch;
G4cout <<" Sensitive detector " << s.str() << G4endl;
TBSD_Dch01 *dchSD;
dchSD = new TBSD_Dch01(s.str(), 0.001);
// set active layer
GasLogical->SetSensitiveDetector(dchSD);
// register
RegisterSensitiveDetector(dchSD);
}
void TBdchX02::SetDepthToLayer(G4int i) {
depthToLayer = i;
G4cout <<" DepthToLayer in Dch: " << depthToLayer << G4endl;
}
void TBdchX02::Print()
{
G4cout << "\nTBdchX02 information: " << G4endl
<< " ecal_front_face: " << ecal_front_face << " mm " << G4endl
<< " z_place1: " << z_place1 << " mm " << G4endl
<< " z_place2: " << z_place2 << " mm " << G4endl
<< " z_place3: " << z_place3 << " mm " << G4endl
<< " z_place4: " << z_place4 << " mm " << G4endl
<< " layer_hthickness: " << dch_hthickness << " mm " << G4endl
<< " winfront_hthickness: " << winfront_hthickness << " mm " << G4endl
// << " winback_hthickness: " << winback_hthickness << " mm " << G4endl
<< " gas_hthickness: " << gas_hthickness << " mm " << G4endl
<< " gas_pressure: " << gas_pressure << " mm " << G4endl
<< " gas_temperature: " << gas_temperature << " mm " << G4endl
<< G4endl;
}
| [
"xuyin@nankai.edu.cn"
] | xuyin@nankai.edu.cn |
a74471a5850773812e8ca091cfd58be1bda6f40f | 631dd6db65445f979bf33ffea8357ce2fe535729 | /CAD_PowerLand/DlgAddPoint.h | 267cabdabbb80c8e26650bacf9631d210ba9e434 | [] | no_license | Spritutu/CAD-2 | 5117449f600baf43db3ca11d3cef081d32808ba0 | adf366ae642e4d5b9c626896a29f2e0aad402d0a | refs/heads/master | 2022-09-15T03:19:18.897844 | 2020-05-27T23:19:42 | 2020-05-27T23:19:42 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,501 | h | #if !defined(AFX_DLGADDPOINT_H__07C669A5_62FA_4DDD_B5DE_7D6F67F30818__INCLUDED_)
#define AFX_DLGADDPOINT_H__07C669A5_62FA_4DDD_B5DE_7D6F67F30818__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// DlgAddPoint.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CDlgAddPoint dialog
class CDlgAddPoint : public CDialog
{
// Construction
public:
CDlgAddPoint(CWnd* pParent = NULL); // standard constructor
Position m_posBegin,m_posEnd;
// Dialog Data
//{{AFX_DATA(CDlgAddPoint)
enum { IDD = IDD_DLG_ADD_POINT };
double m_dEditLongHori;
double m_dEditLongVert;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CDlgAddPoint)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CDlgAddPoint)
afx_msg void OnAddPointOk();
afx_msg void OnAddPointCancel();
virtual BOOL OnInitDialog();
//}}AFX_MSG
private:
//点是否在给定的点集里
BOOL PosOnAryPoint(CArray<Position,Position&> &aryPoint,CArray<double,double&> &aryTudu,Position posClick);
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_DLGADDPOINT_H__07C669A5_62FA_4DDD_B5DE_7D6F67F30818__INCLUDED_)
| [
"11720846@qq.com"
] | 11720846@qq.com |
c0c0d7773631b6b0d34d2f8b162fec17743b2c0f | aa71205fd8b1ca031fc9d56e58a16bf9dcdbd1d0 | /src/component/MidiSourceComponent.h | a3846827358c99b7fab2178e64df9240007230a9 | [
"LicenseRef-scancode-public-domain",
"Unlicense"
] | permissive | xiangwencheng1994/L | df461b015758aee7bf18ddf1ac5834f72efabccb | dbdaf3dbd2a257c87ebdda529ab9e741d3cca9c7 | refs/heads/master | 2020-08-02T12:12:45.912896 | 2019-09-01T14:49:07 | 2019-09-24T20:29:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 781 | h | #pragma once
#include "../audio/MidiSequence.h"
#include "../engine/Resource.h"
#include "Component.h"
namespace L {
class MidiSourceComponent : public Component {
L_COMPONENT(MidiSourceComponent)
L_COMPONENT_HAS_UPDATE(MidiSourceComponent)
protected:
Resource<MidiSequence> _sequence;
uintptr_t _play_index;
Time _play_time;
bool _loop, _playing;
public:
virtual Map<Symbol, Var> pack() const override;
virtual void unpack(const Map<Symbol, Var>&) override;
static void script_registration();
void update();
void play();
void stop();
inline void sequence(const char* filepath) { _sequence = filepath; }
inline void looping(bool loop) { _loop = loop; }
inline bool playing() const { return _playing; }
};
}
| [
"lutopia@hotmail.fr"
] | lutopia@hotmail.fr |
f7d54b89673ed31cf8b78c8a35c5b886745d57b9 | b07baaa9ec8b9f7ec745b97875bebe4f268f6775 | /src/plugins/flite/synth_thread.h | a54fa8395101f3e1a7fc9d846b1b894f96383bf5 | [] | no_license | timn/fawkes | 9a56dc42aacbb87302ac813d5cc47af9337025db | bc3024b62963d2144dc085fb7edbff51b360cc51 | refs/heads/master | 2021-07-21T12:15:15.097567 | 2021-02-03T12:06:09 | 2021-02-03T12:06:09 | 1,030,913 | 0 | 0 | null | 2018-10-05T15:10:45 | 2010-10-28T05:30:51 | C++ | UTF-8 | C++ | false | false | 2,286 | h |
/***************************************************************************
* synth_thread.h - Flite synthesis thread
*
* Created: Tue Oct 28 14:31:58 2008
* Copyright 2006-2008 Tim Niemueller [www.niemueller.de]
*
****************************************************************************/
/* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* Read the full text in the LICENSE.GPL file in the doc directory.
*/
#ifndef _PLUGINS_FLITE_SYNTH_THREAD_H_
#define _PLUGINS_FLITE_SYNTH_THREAD_H_
#include <aspect/blackboard.h>
#include <aspect/blocked_timing.h>
#include <aspect/clock.h>
#include <aspect/configurable.h>
#include <aspect/logging.h>
#include <blackboard/interface_listener.h>
#include <core/threading/thread.h>
#include <flite/flite.h>
#include <string>
namespace fawkes {
class SpeechSynthInterface;
}
class FliteSynthThread : public fawkes::Thread,
public fawkes::LoggingAspect,
public fawkes::ConfigurableAspect,
public fawkes::ClockAspect,
public fawkes::BlackBoardAspect,
public fawkes::BlackBoardInterfaceListener
{
public:
FliteSynthThread();
virtual void init();
virtual void finalize();
virtual void loop();
void say(const char *text);
virtual bool bb_interface_message_received(fawkes::Interface *interface,
fawkes::Message * message) throw();
/** Stub to see name in backtrace for easier debugging. @see Thread::run() */
protected:
virtual void
run()
{
Thread::run();
}
private: /* methods */
void play_wave(cst_wave *wave);
float get_duration(cst_wave *wave);
private:
fawkes::SpeechSynthInterface *speechsynth_if_;
std::string cfg_soundcard_;
cst_voice *voice_;
};
#endif
| [
"niemueller@kbsg.rwth-aachen.de"
] | niemueller@kbsg.rwth-aachen.de |
0e1da56cd77dbdb9c2698fa3490971bbf02df493 | f1031bc6d5f8f295c89797a109cb38ab8cc035a0 | /glut/Ex-ClipCohSuth.cpp | 2b310d124b0188f75cf1079d0f7e3194b7d3a308 | [] | no_license | Alessa0/OpenGL_Notes | 54f91260b5b82e2780c4425a7fba2dc45cc19b75 | e17c49e34f0b6563c9a15314d9f2003d3fcf98ec | refs/heads/main | 2023-05-18T12:01:16.294869 | 2021-06-16T10:34:29 | 2021-06-16T10:34:29 | 370,897,911 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 4,665 | cpp | //
//
//#include <glut.h>
//
//#pragma comment( linker, "/subsystem:\"windows\" /entry:\"mainCRTStartup\"" )
//
//class CPt2D
//{
//public:
// float x, y;
//};
//#define numVerts 8
//CPt2D verts[20] =
//{
// {100.0, -30.0},
// {-100.0, 30.0},
// {0.0, 50.0},
// {400,0},
// {350,250},
// {-350,-250},
// {20, 350},
// {-60, -150}
//};
//
//const int winLeftBitCode = 0x1;
//const int winRightBitCode = 0x2;
//const int winBottomBitCode = 0x4;
//const int winTopBitCode = 0x8;
//
////全为0,表示在内部
//int pointInside(int code)
//{
// return int(!code);
//}
//
////相与为1,完全不在内部
//int lineOutside(int code1, int code2)
//{
// return int(code1 & code2);
//}
//
////完全在内部
//int lineInside(int code1, int code2)
//{
// return int(!(code1 | code2));
//}
//
//unsigned char encode(CPt2D pt, CPt2D winMin, CPt2D winMax)
//{
// unsigned char code = 0x00;
//
// //补充完整
// if (pt.x < winMin.x) code = code | winLeftBitCode;
// if (pt.x > winMax.x) code = code | winRightBitCode;
// if (pt.y < winMin.y) code = code | winBottomBitCode;
// if (pt.y > winMax.y) code = code | winTopBitCode;
//
// return code;
//}
//
//void swapPts(CPt2D *p1, CPt2D *p2)
//{
// CPt2D tmp;
// tmp = *p1;
// *p1 = *p2;
// *p2 = tmp;
//
//}
//
//void swapCodes(unsigned char *c1, unsigned char *c2)
//{
// unsigned char tmp;
// tmp = *c1;
// *c1 = *c2;
// *c2 = tmp;
//
//
//}
//
//void lineClipCohSuth(CPt2D winMin, CPt2D winMax, CPt2D p1, CPt2D p2)
//{
// unsigned char code1, code2;
// int done = false;
// int plotLine = false;
// float k = 0;
//
// while(!done)
// {
// code1 = encode(p1, winMin, winMax);
// code2 = encode(p2, winMin, winMax);
// if (!(code1 | code2)) //code1|code2等于0
// {
// done = true;
// plotLine = true;
// }
// else if (code1 & code2)
// {
// done = true;
// }
// else
// {
// if (pointInside(code1)) {
// swapPts(&p1, &p2);
// swapCodes(&code1, &code2);
// }
// //判断P1在窗口外哪一侧,然后求出两者的交点,并用交点的值替代P1的坐标值,以达到去掉P1线段的目的
// if (p2.x != p1.x) k = (p2.y - p1.y) / (p2.x - p1.x);
// if (code1 & winLeftBitCode) {
// p1.y += (winMin.x - p1.x) * k;
// p1.x = winMin.x;
// }
// else if (code1 & winRightBitCode) {
// p1.y += (winMax.x - p1.x) * k;
// p1.x = winMax.x;
// }
// else if (code1 & winBottomBitCode) {
// if (p2.x != p1.x)
// p1.x += (winMin.y - p1.y) / k;
// p1.y = winMin.y;
// }
// else if (code1 & winTopBitCode) {
// if (p2.x != p1.x)
// p1.x = (winMax.y - p1.y) / k;
// p1.y = winMax.y;
// }
// }
// }
//
// if(plotLine)
// {
// glColor3f(1.0, 0.0, 0.0);
// glBegin(GL_LINES);
// glVertex2f(p1.x, p1.y);
// glVertex2f(p2.x, p2.y);
// glEnd();
// }
//
//}
//
//void InitGL(void)
//{
// glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
//
// glMatrixMode(GL_PROJECTION);
// gluOrtho2D(-400, 400, -300, 300);
//
// glMatrixMode(GL_MODELVIEW);
//
//}
//
//void RenderRect(int width, int height)
//{
// glColor3f(0.0, 0.0, 1.0);
//
// glBegin(GL_LINE_LOOP);
// glVertex2f(-width/2, -height/2);
// glVertex2f(-width/2, height/2);
// glVertex2f(width/2, height/2);
// glVertex2f(width/2, -height/2);
// glEnd();
//}
//
//void RenderLine(CPt2D *verts)
//{
// int i=0;
//
// while(i<numVerts)
// {
// glColor3f(0.0, 0.0, 1.0);
// glBegin(GL_LINES);
// glVertex2f(verts[i].x, verts[i].y);
// glVertex2f(verts[i+1].x, verts[i+1].y);
// glEnd();
//
// i+=2;
// }
//}
//
//void RenderTriangle (CPt2D *verts)
//{
// GLint k;
// glBegin (GL_TRIANGLES);
// for (k = 0; k < 3; k++)
// {
// glVertex2f (verts [k].x, verts [k].y);
// }
// glEnd();
//}
//
//void RenderScene()
//{
// int width = 400;
// int height = 400;
// CPt2D winMin = {-width/2, -height/2};
// CPt2D winMax = {width/2, height/2};
//
// glClear (GL_COLOR_BUFFER_BIT);
//
// RenderRect(width,height);
//
// RenderLine(verts);
// RenderTriangle(verts);
// int i=0;
// while(i<numVerts)
// {
// lineClipCohSuth(winMin, winMax, verts[i], verts[i+1]);
// i+=2;
// }
//
//
// glFlush ( );
//}
//
//void main (int argc, char ** argv)
//{
// glutInit (&argc, argv);
//
// glutInitDisplayMode (GLUT_SINGLE | GLUT_RGB);
// glutInitWindowPosition (50, 50);
// glutInitWindowSize (800, 600);
// glutCreateWindow ("Clip Coh Suth Example");
//
// InitGL();
// glutDisplayFunc (RenderScene);
//
// glutMainLoop ( );
//}
//
//
//
| [
"noreply@github.com"
] | Alessa0.noreply@github.com |
8685aaac85b34831d9dbcaa67313d5e77c1fe49d | 0edbcda83b7a9542f15f706573a8e21da51f6020 | /private/shell/ext/url/persist.cpp | 0c0fd78dafe619188f5a09420c1890eeff36e28c | [] | no_license | yair-k/Win2000SRC | fe9f6f62e60e9bece135af15359bb80d3b65dc6a | fd809a81098565b33f52d0f65925159de8f4c337 | refs/heads/main | 2023-04-12T08:28:31.485426 | 2021-05-08T22:47:00 | 2021-05-08T22:47:00 | 365,623,923 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 41,438 | cpp | /*
* persist.cpp - IPersist, IPersistFile, and IPersistStream implementations for
* URL class.
*/
/* Headers
**********/
#include "project.hpp"
#pragma hdrstop
#include "resource.h"
#include <mluisupp.h>
/* Global Constants
*******************/
#pragma data_seg(DATA_SEG_READ_ONLY)
extern const UINT g_ucMaxURLLen = 1024;
extern const char g_cszURLPrefix[] = "url:";
extern const UINT g_ucbURLPrefixLen = sizeof(g_cszURLPrefix) - 1;
extern const char g_cszURLExt[] = ".url";
extern const char g_cszURLDefaultFileNamePrompt[] = "*.url";
extern const char g_cszCRLF[] = "\r\n";
#pragma data_seg()
/* Module Constants
*******************/
#pragma data_seg(DATA_SEG_READ_ONLY)
// case-insensitive
PRIVATE_DATA const char s_cszInternetShortcutSection[] = "InternetShortcut";
PRIVATE_DATA const char s_cszURLKey[] = "URL";
PRIVATE_DATA const char s_cszIconFileKey[] = "IconFile";
PRIVATE_DATA const char s_cszIconIndexKey[] = "IconIndex";
PRIVATE_DATA const char s_cszHotkeyKey[] = "Hotkey";
PRIVATE_DATA const char s_cszWorkingDirectoryKey[] = "WorkingDirectory";
PRIVATE_DATA const char s_cszShowCmdKey[] = "ShowCommand";
PRIVATE_DATA const UINT s_ucMaxIconIndexLen = 1 + 10 + 1; // -2147483647
PRIVATE_DATA const UINT s_ucMaxHotkeyLen = s_ucMaxIconIndexLen;
PRIVATE_DATA const UINT s_ucMaxShowCmdLen = s_ucMaxIconIndexLen;
#pragma data_seg()
/***************************** Private Functions *****************************/
PRIVATE_CODE BOOL DeletePrivateProfileString(PCSTR pcszSection, PCSTR pcszKey,
PCSTR pcszFile)
{
ASSERT(IS_VALID_STRING_PTR(pcszSection, CSTR));
ASSERT(IS_VALID_STRING_PTR(pcszKey, CSTR));
ASSERT(IS_VALID_STRING_PTR(pcszFile, CSTR));
return(WritePrivateProfileString(pcszSection, pcszKey, NULL, pcszFile));
}
#define SHDeleteIniString(pcszSection, pcszKey, pcszFile) \
SHSetIniString(pcszSection, pcszKey, NULL, pcszFile)
PRIVATE_CODE HRESULT MassageURL(PSTR pszURL)
{
HRESULT hr = E_FAIL;
ASSERT(IS_VALID_STRING_PTR(pszURL, STR));
TrimWhiteSpace(pszURL);
PSTR pszBase = pszURL;
PSTR psz;
// Skip over any "url:" prefix.
if (! lstrnicmp(pszBase, g_cszURLPrefix, g_ucbURLPrefixLen))
pszBase += g_ucbURLPrefixLen;
lstrcpy(pszURL, pszBase);
hr = S_OK;
TRACE_OUT(("MassageURL(): Massaged URL to %s.",
pszURL));
ASSERT(FAILED(hr) ||
IS_VALID_STRING_PTR(pszURL, STR));
return(hr);
}
PRIVATE_CODE HRESULT ReadURLFromFile(PCSTR pcszFile, PSTR *ppszURL)
{
HRESULT hr;
PSTR pszNewURL;
ASSERT(IS_VALID_STRING_PTR(pcszFile, CSTR));
ASSERT(IS_VALID_WRITE_PTR(ppszURL, PSTR));
*ppszURL = NULL;
pszNewURL = new(char[g_ucMaxURLLen]);
if (pszNewURL)
{
DWORD dwcValueLen;
dwcValueLen = SHGetIniString(s_cszInternetShortcutSection,
s_cszURLKey,
pszNewURL, g_ucMaxURLLen, pcszFile);
if (dwcValueLen > 0)
{
hr = MassageURL(pszNewURL);
if (hr == S_OK)
{
PSTR pszShorterURL;
// (+ 1) for null terminator.
if (ReallocateMemory(pszNewURL, lstrlen(pszNewURL) + 1,
(PVOID *)&pszShorterURL))
{
*ppszURL = pszShorterURL;
hr = S_OK;
}
else
hr = E_OUTOFMEMORY;
}
}
else
{
hr = S_FALSE;
WARNING_OUT(("ReadURLFromFile: No URL found in file %s.",
pcszFile));
}
}
else
hr = E_OUTOFMEMORY;
if (FAILED(hr) ||
hr == S_FALSE)
{
if (pszNewURL)
{
delete pszNewURL;
pszNewURL = NULL;
}
}
ASSERT((hr == S_OK &&
IS_VALID_STRING_PTR(*ppszURL, STR)) ||
(hr != S_OK &&
! *ppszURL));
return(hr);
}
PRIVATE_CODE HRESULT WriteURLToFile(PCSTR pcszFile, PCSTR pcszURL)
{
HRESULT hr;
ASSERT(IS_VALID_STRING_PTR(pcszFile, CSTR));
ASSERT(! pcszURL ||
IS_VALID_STRING_PTR(pcszURL, CSTR));
if (AnyMeat(pcszURL))
{
int ncbLen;
ASSERT(IS_VALID_STRING_PTR(pcszFile, CSTR));
ASSERT(IS_VALID_STRING_PTR(pcszURL, PSTR));
hr = (SHSetIniString(s_cszInternetShortcutSection, s_cszURLKey, pcszURL, pcszFile))
? S_OK
: E_FAIL;
}
else
hr = (SHDeleteIniString(s_cszInternetShortcutSection, s_cszURLKey, pcszFile))
? S_OK
: E_FAIL;
return(hr);
}
PRIVATE_CODE HRESULT ReadIconLocationFromFile(PCSTR pcszFile,
PSTR *ppszIconFile, PINT pniIcon)
{
HRESULT hr;
char rgchNewIconFile[MAX_PATH_LEN];
DWORD dwcValueLen;
ASSERT(IS_VALID_STRING_PTR(pcszFile, CSTR));
ASSERT(IS_VALID_WRITE_PTR(ppszIconFile, PSTR));
ASSERT(IS_VALID_WRITE_PTR(pniIcon, INT));
*ppszIconFile = NULL;
*pniIcon = 0;
dwcValueLen = SHGetIniString(s_cszInternetShortcutSection,
s_cszIconFileKey,
rgchNewIconFile,
sizeof(rgchNewIconFile), pcszFile);
if (dwcValueLen > 0)
{
char rgchNewIconIndex[s_ucMaxIconIndexLen];
dwcValueLen = GetPrivateProfileString(s_cszInternetShortcutSection,
s_cszIconIndexKey,
EMPTY_STRING, rgchNewIconIndex,
sizeof(rgchNewIconIndex),
pcszFile);
if (dwcValueLen > 0)
{
int niIcon;
if (StrToIntEx(rgchNewIconIndex, 0, &niIcon))
{
// (+ 1) for null terminator.
*ppszIconFile = new(char[lstrlen(rgchNewIconFile) + 1]);
if (*ppszIconFile)
{
lstrcpy(*ppszIconFile, rgchNewIconFile);
*pniIcon = niIcon;
hr = S_OK;
}
else
hr = E_OUTOFMEMORY;
}
else
{
hr = S_FALSE;
WARNING_OUT(("ReadIconLocationFromFile(): Bad icon index \"%s\" found in file %s.",
rgchNewIconIndex,
pcszFile));
}
}
else
{
hr = S_FALSE;
WARNING_OUT(("ReadIconLocationFromFile(): No icon index found in file %s.",
pcszFile));
}
}
else
{
hr = S_FALSE;
TRACE_OUT(("ReadIconLocationFromFile(): No icon file found in file %s.",
pcszFile));
}
ASSERT(IsValidIconIndex(hr, *ppszIconFile, MAX_PATH_LEN, *pniIcon));
return(hr);
}
PRIVATE_CODE HRESULT WriteIconLocationToFile(PCSTR pcszFile,
PCSTR pcszIconFile,
int niIcon)
{
HRESULT hr;
ASSERT(IS_VALID_STRING_PTR(pcszFile, CSTR));
ASSERT(! pcszIconFile ||
IS_VALID_STRING_PTR(pcszIconFile, CSTR));
ASSERT(IsValidIconIndex((pcszIconFile ? S_OK : S_FALSE), pcszIconFile, MAX_PATH_LEN, niIcon));
if (AnyMeat(pcszIconFile))
{
char rgchIconIndexRHS[s_ucMaxIconIndexLen];
int ncLen;
ncLen = wsprintf(rgchIconIndexRHS, "%d", niIcon);
ASSERT(ncLen > 0);
ASSERT(ncLen < sizeof(rgchIconIndexRHS));
ASSERT(ncLen == lstrlen(rgchIconIndexRHS));
hr = (SHSetIniString(s_cszInternetShortcutSection,
s_cszIconFileKey, pcszIconFile,
pcszFile) &&
WritePrivateProfileString(s_cszInternetShortcutSection,
s_cszIconIndexKey, rgchIconIndexRHS,
pcszFile))
? S_OK
: E_FAIL;
}
else
hr = (SHDeleteIniString(s_cszInternetShortcutSection,
s_cszIconFileKey, pcszFile) &&
DeletePrivateProfileString(s_cszInternetShortcutSection,
s_cszIconIndexKey, pcszFile))
? S_OK
: E_FAIL;
return(hr);
}
PRIVATE_CODE HRESULT ReadHotkeyFromFile(PCSTR pcszFile, PWORD pwHotkey)
{
HRESULT hr = S_FALSE;
char rgchHotkey[s_ucMaxHotkeyLen];
DWORD dwcValueLen;
ASSERT(IS_VALID_STRING_PTR(pcszFile, CSTR));
ASSERT(IS_VALID_WRITE_PTR(pwHotkey, WORD));
*pwHotkey = 0;
dwcValueLen = GetPrivateProfileString(s_cszInternetShortcutSection,
s_cszHotkeyKey, EMPTY_STRING,
rgchHotkey, sizeof(rgchHotkey),
pcszFile);
if (dwcValueLen > 0)
{
UINT uHotkey;
if (StrToIntEx(rgchHotkey, 0, (int *)&uHotkey))
{
*pwHotkey = (WORD)uHotkey;
hr = S_OK;
}
else
WARNING_OUT(("ReadHotkeyFromFile(): Bad hotkey \"%s\" found in file %s.",
rgchHotkey,
pcszFile));
}
else
WARNING_OUT(("ReadHotkeyFromFile(): No hotkey found in file %s.",
pcszFile));
ASSERT((hr == S_OK &&
IsValidHotkey(*pwHotkey)) ||
(hr == S_FALSE &&
! *pwHotkey));
return(hr);
}
PRIVATE_CODE HRESULT WriteHotkeyToFile(PCSTR pcszFile, WORD wHotkey)
{
HRESULT hr;
ASSERT(IS_VALID_STRING_PTR(pcszFile, CSTR));
ASSERT(! wHotkey ||
IsValidHotkey(wHotkey));
if (wHotkey)
{
char rgchHotkeyRHS[s_ucMaxHotkeyLen];
int ncLen;
ncLen = wsprintf(rgchHotkeyRHS, "%u", (UINT)wHotkey);
ASSERT(ncLen > 0);
ASSERT(ncLen < sizeof(rgchHotkeyRHS));
ASSERT(ncLen == lstrlen(rgchHotkeyRHS));
hr = WritePrivateProfileString(s_cszInternetShortcutSection,
s_cszHotkeyKey, rgchHotkeyRHS,
pcszFile)
? S_OK
: E_FAIL;
}
else
hr = DeletePrivateProfileString(s_cszInternetShortcutSection,
s_cszHotkeyKey, pcszFile)
? S_OK
: E_FAIL;
return(hr);
}
PRIVATE_CODE HRESULT ReadWorkingDirectoryFromFile(PCSTR pcszFile,
PSTR *ppszWorkingDirectory)
{
HRESULT hr;
char rgchDirValue[MAX_PATH_LEN];
DWORD dwcValueLen;
ASSERT(IS_VALID_STRING_PTR(pcszFile, CSTR));
ASSERT(IS_VALID_WRITE_PTR(ppszWorkingDirectory, PSTR));
*ppszWorkingDirectory = NULL;
dwcValueLen = SHGetIniString(s_cszInternetShortcutSection,
s_cszWorkingDirectoryKey,
rgchDirValue,
sizeof(rgchDirValue), pcszFile);
if (dwcValueLen > 0)
{
char rgchFullPath[MAX_PATH_LEN];
PSTR pszFileName;
if (GetFullPathName(rgchDirValue, sizeof(rgchFullPath), rgchFullPath,
&pszFileName) > 0)
{
// (+ 1) for null terminator.
*ppszWorkingDirectory = new(char[lstrlen(rgchFullPath) + 1]);
if (*ppszWorkingDirectory)
{
lstrcpy(*ppszWorkingDirectory, rgchFullPath);
hr = S_OK;
}
else
hr = E_OUTOFMEMORY;
}
else
hr = E_FAIL;
}
else
{
hr = S_FALSE;
TRACE_OUT(("ReadWorkingDirectoryFromFile: No working directory found in file %s.",
pcszFile));
}
ASSERT(IsValidPathResult(hr, *ppszWorkingDirectory, MAX_PATH_LEN));
return(hr);
}
PRIVATE_CODE HRESULT WriteWorkingDirectoryToFile(PCSTR pcszFile,
PCSTR pcszWorkingDirectory)
{
HRESULT hr;
ASSERT(IS_VALID_STRING_PTR(pcszFile, CSTR));
ASSERT(! pcszWorkingDirectory ||
IS_VALID_STRING_PTR(pcszWorkingDirectory, CSTR));
if (AnyMeat(pcszWorkingDirectory))
hr = (SHSetIniString(s_cszInternetShortcutSection,
s_cszWorkingDirectoryKey,
pcszWorkingDirectory, pcszFile))
? S_OK
: E_FAIL;
else
hr = (SHDeleteIniString(s_cszInternetShortcutSection,
s_cszWorkingDirectoryKey, pcszFile))
? S_OK
: E_FAIL;
return(hr);
}
PRIVATE_CODE HRESULT ReadShowCmdFromFile(PCSTR pcszFile, PINT pnShowCmd)
{
HRESULT hr;
char rgchNewShowCmd[s_ucMaxShowCmdLen];
DWORD dwcValueLen;
ASSERT(IS_VALID_STRING_PTR(pcszFile, CSTR));
ASSERT(IS_VALID_WRITE_PTR(pnShowCmd, INT));
*pnShowCmd = g_nDefaultShowCmd;
dwcValueLen = GetPrivateProfileString(s_cszInternetShortcutSection,
s_cszShowCmdKey, EMPTY_STRING,
rgchNewShowCmd,
sizeof(rgchNewShowCmd), pcszFile);
if (dwcValueLen > 0)
{
int nShowCmd;
if (StrToIntEx(rgchNewShowCmd, 0, &nShowCmd))
{
*pnShowCmd = nShowCmd;
hr = S_OK;
}
else
{
hr = S_FALSE;
WARNING_OUT(("ReadShowCmdFromFile: Invalid show command \"%s\" found in file %s.",
rgchNewShowCmd,
pcszFile));
}
}
else
{
hr = S_FALSE;
TRACE_OUT(("ReadShowCmdFromFile: No show command found in file %s.",
pcszFile));
}
ASSERT((hr == S_OK &&
EVAL(IsValidShowCmd(*pnShowCmd))) ||
(hr == S_FALSE &&
EVAL(*pnShowCmd == g_nDefaultShowCmd)));
return(hr);
}
PRIVATE_CODE HRESULT WriteShowCmdToFile(PCSTR pcszFile, int nShowCmd)
{
HRESULT hr;
ASSERT(IS_VALID_STRING_PTR(pcszFile, CSTR));
ASSERT(IsValidShowCmd(nShowCmd));
if (nShowCmd != g_nDefaultShowCmd)
{
char rgchShowCmdRHS[s_ucMaxShowCmdLen];
int ncLen;
ncLen = wsprintf(rgchShowCmdRHS, "%d", nShowCmd);
ASSERT(ncLen > 0);
ASSERT(ncLen < sizeof(rgchShowCmdRHS));
ASSERT(ncLen == lstrlen(rgchShowCmdRHS));
hr = (WritePrivateProfileString(s_cszInternetShortcutSection,
s_cszShowCmdKey, rgchShowCmdRHS,
pcszFile))
? S_OK
: E_FAIL;
}
else
hr = (DeletePrivateProfileString(s_cszInternetShortcutSection,
s_cszShowCmdKey, pcszFile))
? S_OK
: E_FAIL;
return(hr);
}
/****************************** Public Functions *****************************/
PUBLIC_CODE HRESULT UnicodeToANSI(LPCOLESTR pcwszUnicode, PSTR *ppszANSI)
{
HRESULT hr;
int ncbLen;
// BUGBUG: Need OLESTR validation function to validate pcwszUnicode here.
ASSERT(IS_VALID_WRITE_PTR(ppszANSI, PSTR));
*ppszANSI = NULL;
// Get length of translated string.
ncbLen = WideCharToMultiByte(CP_ACP, 0, pcwszUnicode, -1, NULL, 0, NULL,
NULL);
if (ncbLen > 0)
{
PSTR pszNewANSI;
// (+ 1) for null terminator.
pszNewANSI = new(char[ncbLen]);
if (pszNewANSI)
{
// Translate string.
if (WideCharToMultiByte(CP_ACP, 0, pcwszUnicode, -1, pszNewANSI,
ncbLen, NULL, NULL) > 0)
{
*ppszANSI = pszNewANSI;
hr = S_OK;
}
else
{
delete pszNewANSI;
pszNewANSI = NULL;
hr = E_UNEXPECTED;
WARNING_OUT(("UnicodeToANSI(): Failed to translate Unicode string to ANSI."));
}
}
else
hr = E_OUTOFMEMORY;
}
else
{
hr = E_UNEXPECTED;
WARNING_OUT(("UnicodeToANSI(): Failed to get length of translated ANSI string."));
}
ASSERT(FAILED(hr) ||
IS_VALID_STRING_PTR(*ppszANSI, STR));
return(hr);
}
PUBLIC_CODE HRESULT ANSIToUnicode(PCSTR pcszANSI, LPOLESTR *ppwszUnicode)
{
HRESULT hr;
int ncbWideLen;
ASSERT(IS_VALID_STRING_PTR(pcszANSI, CSTR));
ASSERT(IS_VALID_WRITE_PTR(ppwszUnicode, LPOLESTR));
*ppwszUnicode = NULL;
// Get length of translated string.
ncbWideLen = MultiByteToWideChar(CP_ACP, 0, pcszANSI, -1, NULL, 0);
if (ncbWideLen > 0)
{
PWSTR pwszNewUnicode;
// (+ 1) for null terminator.
pwszNewUnicode = new(WCHAR[ncbWideLen]);
if (pwszNewUnicode)
{
// Translate string.
if (MultiByteToWideChar(CP_ACP, 0, pcszANSI, -1, pwszNewUnicode,
ncbWideLen) > 0)
{
*ppwszUnicode = pwszNewUnicode;
hr = S_OK;
}
else
{
delete pwszNewUnicode;
pwszNewUnicode = NULL;
hr = E_UNEXPECTED;
WARNING_OUT(("ANSIToUnicode(): Failed to translate ANSI path string to Unicode."));
}
}
else
hr = E_OUTOFMEMORY;
}
else
{
hr = E_UNEXPECTED;
WARNING_OUT(("ANSIToUnicode(): Failed to get length of translated Unicode string."));
}
// BUGBUG: Need OLESTR validation function to validate *ppwszUnicode here.
return(hr);
}
/********************************** Methods **********************************/
HRESULT STDMETHODCALLTYPE InternetShortcut::SaveToFile(PCSTR pcszFile,
BOOL bRemember)
{
HRESULT hr;
PSTR pszURL;
DebugEntry(InternetShortcut::SaveToFile);
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
ASSERT(IS_VALID_STRING_PTR(pcszFile, CSTR));
hr = GetURL(&pszURL);
if (SUCCEEDED(hr))
{
hr = WriteURLToFile(pcszFile, pszURL);
if (pszURL)
{
SHFree(pszURL);
pszURL = NULL;
}
if (hr == S_OK)
{
char rgchBuf[MAX_PATH_LEN];
int niIcon;
hr = GetIconLocation(rgchBuf, sizeof(rgchBuf), &niIcon);
if (SUCCEEDED(hr))
{
hr = WriteIconLocationToFile(pcszFile, rgchBuf, niIcon);
if (hr == S_OK)
{
WORD wHotkey;
hr = GetHotkey(&wHotkey);
if (SUCCEEDED(hr))
{
hr = WriteHotkeyToFile(pcszFile, wHotkey);
if (hr == S_OK)
{
hr = GetWorkingDirectory(rgchBuf, sizeof(rgchBuf));
if (SUCCEEDED(hr))
{
hr = WriteWorkingDirectoryToFile(pcszFile, rgchBuf);
if (hr == S_OK)
{
int nShowCmd;
GetShowCmd(&nShowCmd);
hr = WriteShowCmdToFile(pcszFile, nShowCmd);
if (hr == S_OK)
{
/* Remember file if requested. */
if (bRemember)
{
PSTR pszFileCopy;
if (StringCopy(pcszFile, &pszFileCopy))
{
if (m_pszFile)
delete m_pszFile;
m_pszFile = pszFileCopy;
TRACE_OUT(("InternetShortcut::SaveToFile(): Remembering file %s, as requested.",
m_pszFile));
}
else
hr = E_OUTOFMEMORY;
}
if (hr == S_OK)
{
Dirty(FALSE);
SHChangeNotify(SHCNE_UPDATEITEM,
(SHCNF_PATH | SHCNF_FLUSH), pcszFile,
NULL);
#ifdef DEBUG
TRACE_OUT(("InternetShortcut::SaveToFile(): Internet Shortcut saved to file %s:",
pcszFile));
Dump();
#endif
}
}
}
}
}
}
}
}
}
}
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
DebugExitHRESULT(InternetShortcut::SaveToFile, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE InternetShortcut::LoadFromFile(PCSTR pcszFile,
BOOL bRemember)
{
HRESULT hr;
PSTR pszURL;
DebugEntry(InternetShortcut::LoadFromFile);
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
ASSERT(IS_VALID_STRING_PTR(pcszFile, CSTR));
hr = ReadURLFromFile(pcszFile, &pszURL);
if (SUCCEEDED(hr))
{
hr = SetURL(pszURL, (IURL_SETURL_FL_GUESS_PROTOCOL |
IURL_SETURL_FL_USE_DEFAULT_PROTOCOL));
if (pszURL)
{
delete pszURL;
pszURL = NULL;
}
if (hr == S_OK)
{
PSTR pszIconFile;
int niIcon;
hr = ReadIconLocationFromFile(pcszFile, &pszIconFile, &niIcon);
if (SUCCEEDED(hr))
{
hr = SetIconLocation(pszIconFile, niIcon);
if (pszIconFile)
{
delete pszIconFile;
pszIconFile = NULL;
}
if (hr == S_OK)
{
WORD wHotkey;
hr = ReadHotkeyFromFile(pcszFile, &wHotkey);
if (SUCCEEDED(hr))
{
hr = SetHotkey(wHotkey);
if (hr == S_OK)
{
PSTR pszWorkingDirectory;
hr = ReadWorkingDirectoryFromFile(pcszFile,
&pszWorkingDirectory);
if (SUCCEEDED(hr))
{
hr = SetWorkingDirectory(pszWorkingDirectory);
if (pszWorkingDirectory)
{
delete pszWorkingDirectory;
pszWorkingDirectory = NULL;
}
if (hr == S_OK)
{
int nShowCmd;
hr = ReadShowCmdFromFile(pcszFile, &nShowCmd);
if (SUCCEEDED(hr))
{
/* Remember file if requested. */
if (bRemember)
{
PSTR pszFileCopy;
if (StringCopy(pcszFile, &pszFileCopy))
{
if (m_pszFile)
delete m_pszFile;
m_pszFile = pszFileCopy;
TRACE_OUT(("InternetShortcut::LoadFromFile(): Remembering file %s, as requested.",
m_pszFile));
}
else
hr = E_OUTOFMEMORY;
}
if (SUCCEEDED(hr))
{
SetShowCmd(nShowCmd);
Dirty(FALSE);
hr = S_OK;
#ifdef DEBUG
TRACE_OUT(("InternetShortcut::LoadFromFile(): Internet Shortcut loaded from file %s:",
pcszFile));
Dump();
#endif
}
}
}
}
}
}
}
}
}
}
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
DebugExitHRESULT(InternetShortcut::LoadFromFile, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE InternetShortcut::GetCurFile(PSTR pszFile,
UINT ucbLen)
{
HRESULT hr;
DebugEntry(InternetShortcut::GetCurFile);
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
ASSERT(IS_VALID_WRITE_BUFFER_PTR(pszFile, STR, ucbLen));
if (m_pszFile)
{
lstrcpyn(pszFile, m_pszFile, ucbLen);
TRACE_OUT(("InternetShortcut::GetCurFile(): Current file name is %s.",
pszFile));
hr = S_OK;
}
else
hr = S_FALSE;
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
ASSERT(IS_VALID_STRING_PTR(pszFile, STR) &&
EVAL((UINT)lstrlen(pszFile) < ucbLen));
ASSERT(hr == S_OK ||
hr == S_FALSE);
DebugExitHRESULT(InternetShortcut::GetCurFile, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE InternetShortcut::Dirty(BOOL bDirty)
{
HRESULT hr;
DebugEntry(InternetShortcut::Dirty);
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
if (bDirty)
{
if (IS_FLAG_CLEAR(m_dwFlags, INTSHCUT_FL_DIRTY)) {
TRACE_OUT(("InternetShortcut::Dirty(): Now dirty."));
}
SET_FLAG(m_dwFlags, INTSHCUT_FL_DIRTY);
}
else
{
if (IS_FLAG_SET(m_dwFlags, INTSHCUT_FL_DIRTY)) {
TRACE_OUT(("InternetShortcut::Dirty(): Now clean."));
}
CLEAR_FLAG(m_dwFlags, INTSHCUT_FL_DIRTY);
}
hr = S_OK;
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
ASSERT(hr == S_OK);
DebugExitVOID(InternetShortcut::Dirty);
return(hr);
}
HRESULT STDMETHODCALLTYPE InternetShortcut::GetClassID(PCLSID pclsid)
{
HRESULT hr;
DebugEntry(InternetShortcut::GetClassID);
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
ASSERT(IS_VALID_STRUCT_PTR(pclsid, CCLSID));
*pclsid = CLSID_InternetShortcut;
hr = S_OK;
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
ASSERT(FAILED(hr) ||
IS_VALID_STRUCT_PTR(pclsid, CCLSID));
DebugExitHRESULT(InternetShortcut::GetClassID, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE InternetShortcut::IsDirty(void)
{
HRESULT hr;
DebugEntry(InternetShortcut::IsDirty);
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
if (IS_FLAG_SET(m_dwFlags, INTSHCUT_FL_DIRTY))
hr = S_OK;
else
hr = S_FALSE;
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
DebugExitHRESULT(InternetShortcut::IsDirty, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE InternetShortcut::Save(LPCOLESTR pcwszFile,
BOOL bRemember)
{
HRESULT hr;
PSTR pszFile;
DebugEntry(InternetShortcut::Save);
// bRemember may be any value.
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
// BUGBUG: Need OLESTR validation function to validate pcwszFile here.
if (pcwszFile)
{
hr = UnicodeToANSI(pcwszFile, &pszFile);
if (hr == S_OK)
{
hr = SaveToFile(pszFile, bRemember);
delete pszFile;
pszFile = NULL;
}
}
else if (m_pszFile)
// Ignore bRemember.
hr = SaveToFile(m_pszFile, FALSE);
else
hr = E_FAIL;
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
DebugExitHRESULT(InternetShortcut::Save, hr);
return(hr);
}
#pragma warning(disable:4100) /* "unreferenced formal parameter" warning */
HRESULT STDMETHODCALLTYPE InternetShortcut::SaveCompleted(LPCOLESTR pcwszFile)
{
HRESULT hr;
DebugEntry(InternetShortcut::SaveCompleted);
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
// BUGBUG: Need OLESTR validation function to validate pcwszFile here.
hr = S_OK;
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
DebugExitHRESULT(InternetShortcut::SaveCompleted, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE InternetShortcut::Load(LPCOLESTR pcwszFile,
DWORD dwMode)
{
HRESULT hr;
PSTR pszFile;
DebugEntry(InternetShortcut::Load);
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
// BUGBUG: Need OLESTR validation function to validate pcwszFile here.
// BUGBUG: Validate dwMode here.
// BUGBUG: Implement dwMode flag support.
hr = UnicodeToANSI(pcwszFile, &pszFile);
if (hr == S_OK)
{
hr = LoadFromFile(pszFile, TRUE);
delete pszFile;
pszFile = NULL;
}
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
DebugExitHRESULT(InternetShortcut::Load, hr);
return(hr);
}
#pragma warning(default:4100) /* "unreferenced formal parameter" warning */
HRESULT STDMETHODCALLTYPE InternetShortcut::GetCurFile(LPOLESTR *ppwszFile)
{
HRESULT hr;
LPOLESTR pwszTempFile;
DebugEntry(InternetShortcut::GetCurFile);
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
ASSERT(IS_VALID_WRITE_PTR(ppwszFile, LPOLESTR));
if (m_pszFile)
{
hr = ANSIToUnicode(m_pszFile, &pwszTempFile);
if (hr == S_OK) {
TRACE_OUT(("InternetShortcut::GetCurFile(): Current file name is %s.",
m_pszFile));
}
}
else
{
hr = ANSIToUnicode(g_cszURLDefaultFileNamePrompt, &pwszTempFile);
if (hr == S_OK)
{
hr = S_FALSE;
TRACE_OUT(("InternetShortcut::GetCurFile(): No current file name. Returning default file name prompt %s.",
g_cszURLDefaultFileNamePrompt));
}
}
if (SUCCEEDED(hr))
{
// We should really call OleGetMalloc() to get the process IMalloc here.
// Use SHAlloc() here instead to avoid loading ole32.dll.
// SHAlloc() / SHFree() turn in to IMalloc::Alloc() and IMalloc::Free()
// once ole32.dll is loaded.
// N.b., lstrlenW() returns the length of the given string in characters,
// not bytes.
// (+ 1) for null terminator.
*ppwszFile = (LPOLESTR)SHAlloc((lstrlenW(pwszTempFile) + 1) *
sizeof(*pwszTempFile));
if (*ppwszFile)
lstrcpyW(*ppwszFile, pwszTempFile);
else
hr = E_OUTOFMEMORY;
delete pwszTempFile;
pwszTempFile = NULL;
}
// BUGBUG: Need OLESTR validation function to validate *ppwszFile here.
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
DebugExitHRESULT(InternetShortcut::GetCurFile, hr);
return(hr);
}
#pragma warning(disable:4100) /* "unreferenced formal parameter" warning */
HRESULT STDMETHODCALLTYPE InternetShortcut::Load(PIStream pistr)
{
HRESULT hr;
DebugEntry(InternetShortcut::Load);
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
ASSERT(IS_VALID_INTERFACE_PTR(pistr, IStream));
hr = E_NOTIMPL;
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
DebugExitHRESULT(InternetShortcut::Load, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE InternetShortcut::Save(PIStream pistr,
BOOL bClearDirty)
{
HRESULT hr;
DebugEntry(InternetShortcut::Save);
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
ASSERT(IS_VALID_INTERFACE_PTR(pistr, IStream));
// BUGBUG: Yes, this is an awful hack, but that's what we get when
// no one implements a needed interface and we need to get a product
// shipped. (Actually, the hack isn't that bad, as it's what happens in
// TransferFileContents, except we're writing to a stream and not memory).
const static TCHAR s_cszNewLine[] = TEXT("\r\n");
const static TCHAR s_cszPrefix[] = TEXT("[InternetShortcut]\r\nURL=");
LPTSTR pszBuf;
DWORD cb;
pszBuf = (LPTSTR)LocalAlloc(LPTR, lstrlen(m_pszURL) + lstrlen(s_cszPrefix) + lstrlen(s_cszNewLine) + 1);
wsprintf(pszBuf, TEXT("%s%s%s"), s_cszPrefix, m_pszURL ? m_pszURL : TEXT("") , s_cszNewLine);
hr = pistr->Write(pszBuf, lstrlen(pszBuf), &cb);
LocalFree(pszBuf);
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
DebugExitHRESULT(InternetShortcut::Save, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE InternetShortcut::GetSizeMax(PULARGE_INTEGER pcbSize)
{
HRESULT hr;
DebugEntry(InternetShortcut::GetSizeMax);
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
ASSERT(IS_VALID_WRITE_PTR(pcbSize, ULARGE_INTEGER));
hr = E_NOTIMPL;
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
DebugExitHRESULT(InternetShortcut::GetSizeMax, hr);
return(hr);
}
#pragma warning(default:4100) /* "unreferenced formal parameter" warning */
DWORD STDMETHODCALLTYPE InternetShortcut::GetFileContentsSize(void)
{
DWORD dwcbLen;
DebugEntry(InternetShortcut::GetFileContentsSize);
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
// Section length.
// (- 1) for each null terminator.
HRESULT hr = CreateURLFileContents(m_pszURL, NULL);
// BUGBUG: (DavidDi 3/29/95) We need to save more than just the URL string
// here, i.e., icon file and index, working directory, and show command.
dwcbLen = SUCCEEDED(hr) ? hr : 0;
dwcbLen++; // + 1 for final null terminator
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
DebugExitDWORD(InternetShortcut::GetFileContentsSize, dwcbLen);
return(dwcbLen);
}
HRESULT STDMETHODCALLTYPE InternetShortcut::TransferUniformResourceLocator(
PFORMATETC pfmtetc,
PSTGMEDIUM pstgmed)
{
HRESULT hr;
DebugEntry(InternetShortcut::TransferUniformResourceLocator);
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
ASSERT(IS_VALID_STRUCT_PTR(pfmtetc, CFORMATETC));
ASSERT(IS_VALID_WRITE_PTR(pstgmed, STGMEDIUM));
ASSERT(pfmtetc->dwAspect == DVASPECT_CONTENT);
ASSERT(pfmtetc->lindex == -1);
ZeroMemory(pstgmed, sizeof(*pstgmed));
if (IS_FLAG_SET(pfmtetc->tymed, TYMED_HGLOBAL))
{
if (m_pszURL)
{
HGLOBAL hgURL;
hr = E_OUTOFMEMORY;
// (+ 1) for null terminator.
hgURL = GlobalAlloc(0, lstrlen(m_pszURL) + 1);
if (hgURL)
{
PSTR pszURL;
pszURL = (PSTR)GlobalLock(hgURL);
if (EVAL(pszURL))
{
lstrcpy(pszURL, m_pszURL);
pstgmed->tymed = TYMED_HGLOBAL;
pstgmed->hGlobal = hgURL;
ASSERT(! pstgmed->pUnkForRelease);
hr = S_OK;
GlobalUnlock(hgURL);
pszURL = NULL;
}
if (hr != S_OK)
{
GlobalFree(hgURL);
hgURL = NULL;
}
}
}
else
hr = DV_E_FORMATETC;
}
else
hr = DV_E_TYMED;
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
ASSERT((hr == S_OK &&
IS_VALID_STRUCT_PTR(pstgmed, CSTGMEDIUM)) ||
(FAILED(hr) &&
(EVAL(pstgmed->tymed == TYMED_NULL) &&
EVAL(! pstgmed->hGlobal) &&
EVAL(! pstgmed->pUnkForRelease))));
DebugExitHRESULT(InternetShortcut::TransferUniformResourceLocator, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE InternetShortcut::TransferText(PFORMATETC pfmtetc,
PSTGMEDIUM pstgmed)
{
HRESULT hr;
DebugEntry(InternetShortcut::TransferText);
// Assume InternetShortcut::TransferUniformResourceLocator() will perform
// input and output validation.
hr = TransferUniformResourceLocator(pfmtetc, pstgmed);
DebugExitHRESULT(InternetShortcut::TransferText, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE InternetShortcut::TransferFileGroupDescriptor(
PFORMATETC pfmtetc,
PSTGMEDIUM pstgmed)
{
HRESULT hr;
DebugEntry(InternetShortcut::TransferFileGroupDescriptor);
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
ASSERT(IS_VALID_STRUCT_PTR(pfmtetc, CFORMATETC));
ASSERT(IS_VALID_WRITE_PTR(pstgmed, STGMEDIUM));
ASSERT(pfmtetc->dwAspect == DVASPECT_CONTENT);
ASSERT(pfmtetc->lindex == -1);
pstgmed->tymed = TYMED_NULL;
pstgmed->hGlobal = NULL;
pstgmed->pUnkForRelease = NULL;
if (IS_FLAG_SET(pfmtetc->tymed, TYMED_HGLOBAL))
{
HGLOBAL hgFileGroupDesc;
hr = E_OUTOFMEMORY;
hgFileGroupDesc = GlobalAlloc(GMEM_ZEROINIT,
sizeof(FILEGROUPDESCRIPTOR));
if (hgFileGroupDesc)
{
PFILEGROUPDESCRIPTOR pfgd;
pfgd = (PFILEGROUPDESCRIPTOR)GlobalLock(hgFileGroupDesc);
if (EVAL(pfgd))
{
PFILEDESCRIPTOR pfd = &(pfgd->fgd[0]);
// Do we already have a file name to use?
if (m_pszFile)
{
lstrcpyn(pfd->cFileName, ExtractFileName(m_pszFile),
SIZECHARS(pfd->cFileName));
hr = S_OK;
}
else
{
if (EVAL(MLLoadStringA(
IDS_NEW_INTERNET_SHORTCUT, pfd->cFileName,
sizeof(pfd->cFileName))))
hr = S_OK;
}
if (hr == S_OK)
{
pfd->dwFlags = (FD_FILESIZE |
FD_LINKUI);
pfd->nFileSizeHigh = 0;
pfd->nFileSizeLow = GetFileContentsSize();
pfgd->cItems = 1;
pstgmed->tymed = TYMED_HGLOBAL;
pstgmed->hGlobal = hgFileGroupDesc;
ASSERT(! pstgmed->pUnkForRelease);
}
GlobalUnlock(hgFileGroupDesc);
pfgd = NULL;
}
if (hr != S_OK)
{
GlobalFree(hgFileGroupDesc);
hgFileGroupDesc = NULL;
}
}
}
else
hr = DV_E_TYMED;
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
ASSERT((hr == S_OK &&
IS_VALID_STRUCT_PTR(pstgmed, CSTGMEDIUM)) ||
(FAILED(hr) &&
(EVAL(pstgmed->tymed == TYMED_NULL) &&
EVAL(! pstgmed->hGlobal) &&
EVAL(! pstgmed->pUnkForRelease))));
DebugExitHRESULT(InternetShortcut::TransferFileGroupDescriptor, hr);
return(hr);
}
HRESULT STDMETHODCALLTYPE InternetShortcut::TransferFileContents(
PFORMATETC pfmtetc,
PSTGMEDIUM pstgmed)
{
HRESULT hr;
DebugEntry(InternetShortcut::TransferFileContents);
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
ASSERT(IS_VALID_STRUCT_PTR(pfmtetc, CFORMATETC));
ASSERT(IS_VALID_WRITE_PTR(pstgmed, STGMEDIUM));
ASSERT(pfmtetc->dwAspect == DVASPECT_CONTENT);
ASSERT(! pfmtetc->lindex);
pstgmed->tymed = TYMED_NULL;
pstgmed->hGlobal = NULL;
pstgmed->pUnkForRelease = NULL;
if (IS_FLAG_SET(pfmtetc->tymed, TYMED_HGLOBAL))
{
HGLOBAL hgFileContents;
hr = CreateURLFileContents(m_pszURL, (LPSTR *)&hgFileContents);
if (SUCCEEDED(hr))
{
// Note some apps don't pay attention to the nFileSizeLow
// field; fortunately, CreateURLFileContents adds a final
// null terminator to prevent trailing garbage.
pstgmed->tymed = TYMED_HGLOBAL;
pstgmed->hGlobal = hgFileContents;
ASSERT(! pstgmed->pUnkForRelease);
hr = S_OK;
}
else
hr = E_OUTOFMEMORY;
}
else
hr = DV_E_TYMED;
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
ASSERT((hr == S_OK &&
IS_VALID_STRUCT_PTR(pstgmed, CSTGMEDIUM)) ||
(FAILED(hr) &&
(EVAL(pstgmed->tymed == TYMED_NULL) &&
EVAL(! pstgmed->hGlobal) &&
EVAL(! pstgmed->pUnkForRelease))));
DebugExitHRESULT(InternetShortcut::TransferFileContents, hr);
return(hr);
}
#ifdef DEBUG
void STDMETHODCALLTYPE InternetShortcut::Dump(void)
{
ASSERT(IS_VALID_STRUCT_PTR(this, CInternetShortcut));
PLAIN_TRACE_OUT(("%sm_dwFlags = %#08lx",
INDENT_STRING,
m_dwFlags));
PLAIN_TRACE_OUT(("%sm_pszFile = \"%s\"",
INDENT_STRING,
CHECK_STRING(m_pszFile)));
PLAIN_TRACE_OUT(("%sm_pszURL = \"%s\"",
INDENT_STRING,
CHECK_STRING(m_pszURL)));
PLAIN_TRACE_OUT(("%sm_pszIconFile = \"%s\"",
INDENT_STRING,
CHECK_STRING(m_pszIconFile)));
PLAIN_TRACE_OUT(("%sm_niIcon = %d",
INDENT_STRING,
m_niIcon));
PLAIN_TRACE_OUT(("%sm_wHotkey = %#04x",
INDENT_STRING,
(UINT)m_wHotkey));
PLAIN_TRACE_OUT(("%sm_pszWorkingDirectory = \"%s\"",
INDENT_STRING,
CHECK_STRING(m_pszWorkingDirectory)));
PLAIN_TRACE_OUT(("%sm_nShowCmd = %d",
INDENT_STRING,
m_nShowCmd));
return;
}
#endif
| [
"ykorokhov@pace.ca"
] | ykorokhov@pace.ca |
65c7232e659cf7160cadfb802b13648dbf7d05a3 | 681c9cef5f4058c47fead3737ef6a0c5e3fbbd81 | /ExpressionAddOperators.cc | 1870e2266cddd7bd03a770b559f84774594aff3a | [] | no_license | sdecoder/algorithm | 63e75db725caecbfce1c3296176c0ab7b2a9c7ad | 2aca8fb0210107c257d5aeffded6282c4f0ef73c | refs/heads/master | 2021-01-10T04:05:56.210790 | 2016-04-13T05:42:35 | 2016-04-13T05:42:35 | 48,119,582 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,888 | cc |
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <limits.h>
#include <math.h>
#include <memory.h>
#include <sstream>
#include <iostream>
#include <vector>
#include <queue>
#include <list>
#include <stack>
using namespace std;
/*
Expression Add Operators My Submissions Question
Total Accepted: 5838 Total Submissions: 27038 Difficulty: Hard
Given a string that contains only digits 0-9 and a target value, return all
possibilities to add binary operators (not unary) +, -, or * between the digits
so they evaluate to the target value.
Examples:
"123", 6 -> ["1+2+3", "1*2*3"]
"232", 8 -> ["2*3+2", "2+3*2"]
"105", 5 -> ["1*0+5","10-5"]
"00", 0 -> ["0+0", "0-0", "0*0"]
"3456237490", 9191 -> []*/
class Solution {
public:
vector<string> addOperators(string num, int target) {
vector<string> res;
addOperatorsDFS(num, target, 0, 0, "", res);
return res;
}
void addOperatorsDFS(string num, int target, long long diff, long long curNum,
string out, vector<string> &res) {
if (num.size() == 0 && curNum == target) {
res.push_back(out);
}
for (int i = 1; i <= num.size(); ++i) {
string cur = num.substr(0, i);
if (cur.size() > 1 && cur[0] == '0') return;
string next = num.substr(i);
if (out.size() > 0) {
addOperatorsDFS(next, target, stoll(cur), curNum + stoll(cur),
out + "+" + cur, res);
addOperatorsDFS(next, target, -stoll(cur), curNum - stoll(cur),
out + "-" + cur, res);
addOperatorsDFS(next, target, diff * stoll(cur),
(curNum - diff) + diff * stoll(cur), out + "*" + cur,
res);
} else {
addOperatorsDFS(next, target, stoll(cur), stoll(cur), cur, res);
}
}
}
};
int main(int argc, char const *argv[]) {
/* code */
return 0;
} | [
"root@freebsd.localdomain"
] | root@freebsd.localdomain |
0a9e89b60921e61e1ec18f210e6ba4d92aa5897d | 282bd2db15bf7e7ad06f611f90cd81ee85453204 | /sources/Game/Graphics/LevelRenderer.h | 83f0faed32d99357bb74d3459cd666907aeddd58 | [
"MIT"
] | permissive | radiatus/swengine | ebce50ff29ab81b4879781230b4c009cb1c336af | 9e26efb50f79b4a74902026c285cef0cd4f3c7c1 | refs/heads/master | 2020-03-26T21:25:24.542597 | 2018-08-19T11:42:32 | 2018-08-19T11:42:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,231 | h | #pragma once
#include <Engine\Components\Graphics\GraphicsResourceFactory.h>
#include <Engine\Components\Graphics\RenderSystem\Camera.h>
#include "Light.h"
#include <Game\Graphics\Materials\BaseMaterial.h>
#include <Game\Graphics\Renderable.h>
#include <Game\Graphics\Primitives\NDCQuadPrimitive.h>
#include <Game\Graphics\Primitives\SpherePrimitive.h>
class LevelRenderer {
public:
LevelRenderer(GraphicsContext* graphicsContext,
GraphicsResourceFactory* graphicsResourceFactory,
GpuProgram* deferredLightingProgram);
~LevelRenderer();
void registerLightSource(Light* lightSource);
void updateLightSource(const Light* lightSource);
void removeLightSource(const Light* lightSource);
void setActiveCamera(const Camera* camera);
void render();
void registerBaseMaterial(BaseMaterial* baseMaterial);
void addRenderableObject(Renderable* object);
void removeRenderableObject(Renderable* object);
void enableGammaCorrection();
void disableGammaCorrection();
bool isGammaCorrectionEnabled();
void setGamma(float gamma);
float getGamma() const;
protected:
void prepareBaseMaterials();
void showGBuffer();
float calculateLightSourceSphereRadius(const Light* light) const;
void passLightSourceDataToGpuProgram(size_t index, const Light* light, GpuProgram* gpuProgram) const;
void initializeRenderTarget();
Texture* createGBufferColorTexture();
Texture* createGBufferDepthStencilTexture();
protected:
float m_gamma;
bool m_isGammaCorrectionEnabled;
protected:
const Camera* m_activeCamera;
GraphicsContext * m_graphicsContext;
GraphicsResourceFactory* m_graphicsResourceFactory;
std::vector<const Light*> m_lightsSources;
std::vector<BaseMaterial*> m_baseMaterials;
std::vector<Renderable*> m_renderableObjects;
protected:
GpuProgram* m_deferredLightingProgram;
NDCQuadPrimitive * m_ndcQuad;
SpherePrimitive* m_sphere;
RenderTarget * m_gBufferTarget;
Texture* m_gBufferAlbedo;
Texture* m_gBufferNormals;
Texture* m_gBufferPosition;
Texture* m_gBufferUV;
Texture* m_gBufferDepthStencil;
static const size_t ALBEDO_BUFFER_INDEX = 0;
static const size_t NORMALS_BUFFER_INDEX = 1;
static const size_t POSITION_BUFFER_INDEX = 2;
static const size_t UV_BUFFER_INDEX = 3;
}; | [
"nic.paukov@yandex.ru"
] | nic.paukov@yandex.ru |
88ab50dafff6d523b588aed94b8a68b2ada31678 | 9760f85154410ddc89454d35afb4a3fa9a83c8da | /Arduino/lwh6633/ledsp_final3/ledsp_final3.ino | 2671394b43257d47bda17b83f0a8ed3f6b0b02f4 | [] | no_license | girinssh/CDIC2021_LiDAR | 401a9c15bba900c0c3367662ae749cc4e22a9c8e | 9a8b55b13852e3f0fe4e210157491d1c0c3cbb63 | refs/heads/master | 2023-08-25T02:58:21.426261 | 2021-10-08T12:29:21 | 2021-10-08T12:29:21 | 406,448,228 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 136 | ino | #include <Adafruit_NeoPixel.h>
#include "setup.h"
#include "loop.h"
void setup()
{
ledsp_setup();
}
void loop()
{
ledsp_loop();
}
| [
"uhyunee0319@gmail.com"
] | uhyunee0319@gmail.com |
b3b46fbef6b440b9f679ba08a2f6faac033d7ec6 | 876a5840149b4ba1350ff5f6816144a9c51ed110 | /base/linux/libdbusglibsymboltable.h | 03a47717766de64424e0825b94e27eaac1f1e2d5 | [] | no_license | zhangyongfei/testjingle | 6165e7e57369397ae675db23cba2ca9d80433e3b | 15420097c65c2f1bac5df380603f6f71572fa4f2 | refs/heads/master | 2016-09-10T02:02:19.700814 | 2014-06-19T08:51:18 | 2014-06-19T08:51:18 | 20,157,419 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,839 | h | /*
* libjingle
* Copyright 2004--2011, Google Inc.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
#ifndef TALK_BASE_LIBDBUSGLIBSYMBOLTABLE_H_
#define TALK_BASE_LIBDBUSGLIBSYMBOLTABLE_H_
#ifdef HAVE_DBUS_GLIB
#include <dbus/dbus-glib.h>
#include <dbus/dbus-glib-lowlevel.h>
#include "os/linux/latebindingsymboltable.h"
namespace talk_base {
#define LIBDBUS_GLIB_CLASS_NAME LibDBusGlibSymbolTable
// The libdbus-glib symbols we need, as an X-Macro list.
// This list must contain precisely every libdbus-glib function that is used in
// dbus.cc.
#define LIBDBUS_GLIB_SYMBOLS_LIST \
X(dbus_bus_add_match) \
X(dbus_connection_add_filter) \
X(dbus_connection_close) \
X(dbus_connection_remove_filter) \
X(dbus_connection_set_exit_on_disconnect) \
X(dbus_g_bus_get) \
X(dbus_g_bus_get_private) \
X(dbus_g_connection_get_connection) \
X(dbus_g_connection_unref) \
X(dbus_g_thread_init) \
X(dbus_message_get_interface) \
X(dbus_message_get_member) \
X(dbus_message_get_path) \
X(dbus_message_get_type) \
X(dbus_message_iter_get_arg_type) \
X(dbus_message_iter_get_basic) \
X(dbus_message_iter_init) \
X(dbus_message_ref) \
X(dbus_message_unref)
#define LATE_BINDING_SYMBOL_TABLE_CLASS_NAME LIBDBUS_GLIB_CLASS_NAME
#define LATE_BINDING_SYMBOL_TABLE_SYMBOLS_LIST LIBDBUS_GLIB_SYMBOLS_LIST
#include "base/latebindingsymboltable.h.def"
} // namespace talk_base
#endif // HAVE_DBUS_GLIB
#endif // TALK_BASE_LIBDBUSGLIBSYMBOLTABLE_H_
| [
"zhang13730865557@163.com"
] | zhang13730865557@163.com |
33b12b38880b72e272291c3b965b2a8bca3d678b | b71b8bd385c207dffda39d96c7bee5f2ccce946c | /testcases/CWE762_Mismatched_Memory_Management_Routines/s02/CWE762_Mismatched_Memory_Management_Routines__delete_array_struct_realloc_09.cpp | 97ac914fb942c72e31dea2b5ced28c346e49f431 | [] | no_license | Sporknugget/Juliet_prep | e9bda84a30bdc7938bafe338b4ab2e361449eda5 | 97d8922244d3d79b62496ede4636199837e8b971 | refs/heads/master | 2023-05-05T14:41:30.243718 | 2021-05-25T16:18:13 | 2021-05-25T16:18:13 | 369,334,230 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,317 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_struct_realloc_09.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml
Template File: sources-sinks-09.tmpl.cpp
*/
/*
* @description
* CWE: 762 Mismatched Memory Management Routines
* BadSource: realloc Allocate data using realloc()
* GoodSource: Allocate data using new []
* Sinks:
* GoodSink: Deallocate data using free()
* BadSink : Deallocate data using delete []
* Flow Variant: 09 Control flow: if(GLOBAL_CONST_TRUE) and if(GLOBAL_CONST_FALSE)
*
* */
#include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_struct_realloc_09
{
#ifndef OMITBAD
void bad()
{
twoIntsStruct * data;
/* Initialize data*/
data = NULL;
{
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (twoIntsStruct *)realloc(data, 100*sizeof(twoIntsStruct));
if (data == NULL) {exit(-1);}
}
{
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodB2G1() - use badsource and goodsink by changing the second GLOBAL_CONST_TRUE to GLOBAL_CONST_FALSE */
static void goodB2G1()
{
twoIntsStruct * data;
/* Initialize data*/
data = NULL;
{
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (twoIntsStruct *)realloc(data, 100*sizeof(twoIntsStruct));
if (data == NULL) {exit(-1);}
}
{
/* FIX: Free memory using free() */
free(data);
}
}
/* goodB2G2() - use badsource and goodsink by reversing the blocks in the second if */
static void goodB2G2()
{
twoIntsStruct * data;
/* Initialize data*/
data = NULL;
{
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (twoIntsStruct *)realloc(data, 100*sizeof(twoIntsStruct));
if (data == NULL) {exit(-1);}
}
{
/* FIX: Free memory using free() */
free(data);
}
}
/* goodG2B1() - use goodsource and badsink by changing the first GLOBAL_CONST_TRUE to GLOBAL_CONST_FALSE */
static void goodG2B1()
{
twoIntsStruct * data;
/* Initialize data*/
data = NULL;
{
/* FIX: Allocate memory using new [] */
data = new twoIntsStruct[100];
}
{
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
}
/* goodG2B2() - use goodsource and badsink by reversing the blocks in the first if */
static void goodG2B2()
{
twoIntsStruct * data;
/* Initialize data*/
data = NULL;
{
/* FIX: Allocate memory using new [] */
data = new twoIntsStruct[100];
}
{
/* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may
* require a call to free() to deallocate the memory */
delete [] data;
}
}
void good()
{
goodB2G1();
goodB2G2();
goodG2B1();
goodG2B2();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_struct_realloc_09; /* so that we can use good and bad easily */
int main(int argc, char * argv[])
{
/* seed randomness */
srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
printLine("Calling good()...");
good();
printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
printLine("Calling bad()...");
bad();
printLine("Finished bad()");
#endif /* OMITBAD */
return 0;
}
#endif
| [
"jaredzap@rams.colostate.edu"
] | jaredzap@rams.colostate.edu |
cfc06ce4513cfb71f89f36f25b4acaa8e9266c7b | dfa8ebaecddd987d5b55b5fee918f517b527cbd5 | /JuneCodingChallenge/BinaryTreeAddition.cpp | 66d54450ca2f3f591d1eb91b0918f6893060f3aa | [] | no_license | c9thompson/InterviewQuestions | ea26449c94e5e137fa02d401eb0e94b8709a6cef | 06dc4d00c52ffc16f7c82502abc40813655f61a0 | refs/heads/master | 2022-12-02T10:12:59.081752 | 2020-08-10T06:48:28 | 2020-08-10T06:48:28 | 263,452,371 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 696 | cpp | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class solution{
public:
int dfs(TreeNode* node, string val){
if(!node) return stoi(val);
val += to_string(node->val);
return node->left ? dfs(node->left, val) : 0 +
node->right ? dfs(node->right, val) : 0;
}
int countBinaryTree(TreeNode* root){ return root ? dfs(root, "") : 0; }
}; | [
"c9thomps@gmail.com"
] | c9thomps@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.