blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 955
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 143
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 121
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
598d9e3bf146811077d89fba3cc3b537d1c189f8 | 7ab9732bfea95712d13ad0a0f9193c03e41ab3f4 | /C++ Primer/C++ Primer&17/Example&17.30.cpp | 6faaaea22d16c8075b9d81734d450f20ff2c619a | [] | no_license | LuckPsyduck/CPP-Example | 611a09a3b80deb00ceff348acee7dd7c3db25a4f | 8b4b75e1c90313811130c9c24484dce8ee951067 | refs/heads/master | 2021-05-23T00:18:57.770829 | 2020-04-05T13:05:58 | 2020-04-05T13:05:58 | 253,151,908 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 745 | cpp | #include<iostream>
#include<random>
using namespace std;
unsigned int rand_int(long seed = -1,long min=1,long max=0)
{
static uniform_int_distribution<unsigned> u(0, 9999);
static default_random_engine e;
if (seed >= 0)
e.seed(seed);
if (min <= max)
u = uniform_int_distribution<unsigned>(min, max);
return u(e);
}
int main()
{
for (int i = 0; i < 10; i++)
cout << rand_int() << " ";
cout << endl;
cout << rand_int(0) << " ";
for (int i = 0; i < 9; i++)
cout << rand_int() << " ";
cout << endl;
cout << rand_int(19743) << " ";
for (int i = 0; i < 9; i++)
cout << rand_int() << " ";
cout << endl;
cout << rand_int(19743,0,9) << " ";
for (int i = 0; i < 9; i++)
cout << rand_int() << " ";
cout << endl;
return 0;
} | [
"[email protected]"
] | |
dd706c7bc5bf22b8107f6ba45224d7858f36de80 | 9330e0bd51071ebcb5b863038c568b9e122e2356 | /my_lib.h | e3a644255c9067034734f1145f31f58aa9f68ecb | [] | no_license | rjimenez123/correo_mg_lab3 | bfbef5dbffaaa109962b3b1f6400084a9d160f44 | 6cdba18d7cd712158633b28f9cad69ab10daf34e | refs/heads/master | 2020-05-16T14:21:25.023338 | 2019-04-25T17:42:53 | 2019-04-25T17:42:53 | 183,100,997 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 491 | h | #ifndef MY_LIB_H
#define MY_LIB_H
template <typename TIPO>
void mergeSort(TIPO*, int, int);
template <typename TIPO>
void merge(TIPO*, int, int, int);
template <typename TIPO>
double mean(TIPO*, int);
template <typename TIPO>
double weighted_mean(TIPO*, TIPO*, int);
template <typename TIPO>
TIPO median(TIPO*, int);
template <typename TIPO>
double standard_deviation(TIPO*, int);
template <typename TIPO>
void distribution(TIPO*, int, TIPO*, int, int*, int&);
#endif /* MY_LIB_H */
| [
"[email protected]"
] | |
a39fb648311aad564eff2611ebab95d7d74c083c | 01b8c8094dc5beb8518dbed3be7775b79071a9c8 | /sky/engine/tonic/dart_string_cache.cc | d82deb1eb035a7f21260478bd888fa04d9f53f5d | [
"BSD-3-Clause"
] | permissive | bprosnitz/mojo | 2e01c9fed8326ad86d6364baf0790ff99e2d8f3c | 0c7f1938808f0df20704c336ccbe47b429c92f70 | refs/heads/master | 2021-01-09T07:00:22.139224 | 2015-06-23T17:20:56 | 2015-06-23T17:20:56 | 37,934,424 | 0 | 0 | null | 2015-06-23T17:39:27 | 2015-06-23T17:39:27 | null | UTF-8 | C++ | false | false | 2,008 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "sky/engine/config.h"
#include "sky/engine/tonic/dart_string_cache.h"
#include "sky/engine/tonic/dart_state.h"
#include "sky/engine/tonic/dart_string.h"
namespace blink {
DartStringCache::DartStringCache() : last_dart_string_(nullptr) {
}
DartStringCache::~DartStringCache() {
}
Dart_WeakPersistentHandle DartStringCache::GetSlow(StringImpl* string_impl,
bool auto_scope) {
if (Dart_WeakPersistentHandle string = cache_.get(string_impl)) {
last_dart_string_ = string;
last_string_impl_ = string_impl;
return string;
}
if (!auto_scope)
Dart_EnterScope();
Dart_Handle string = CreateDartString(string_impl);
DCHECK(!Dart_IsError(string));
intptr_t size_in_bytes = string_impl->sizeInBytes();
Dart_WeakPersistentHandle wrapper = Dart_NewWeakPersistentHandle(
string, string_impl, size_in_bytes, FinalizeCacheEntry);
string_impl->ref(); // Balanced in FinalizeCacheEntry.
cache_.set(string_impl, wrapper);
last_dart_string_ = wrapper;
last_string_impl_ = string_impl;
if (!auto_scope)
Dart_ExitScope();
return wrapper;
}
void DartStringCache::FinalizeCacheEntry(void* isolate_callback_data,
Dart_WeakPersistentHandle handle,
void* peer) {
DartState* state = reinterpret_cast<DartState*>(isolate_callback_data);
StringImpl* string_impl = reinterpret_cast<StringImpl*>(peer);
DartStringCache& cache = state->string_cache();
Dart_WeakPersistentHandle cached_handle = cache.cache_.take(string_impl);
ASSERT_UNUSED(cached_handle, handle == cached_handle);
if (cache.last_dart_string_ == handle) {
cache.last_dart_string_ = nullptr;
cache.last_string_impl_ = nullptr;
}
string_impl->deref();
}
} // namespace blink
| [
"[email protected]"
] | |
efc466d1307692ddda6f1281c9f54871ec047c55 | c3ffa07567d3d29a7439e33a6885a5544e896644 | /UVa/821.cpp | 49f7342156f1a2a6b253f0cf0b45bd45291f39fc | [] | no_license | a00012025/Online_Judge_Code | 398c90c046f402218bd14867a06ae301c0c67687 | 7084865a7050fc09ffb0e734f77996172a93d3ce | refs/heads/master | 2018-01-08T11:33:26.352408 | 2015-10-10T23:20:35 | 2015-10-10T23:20:35 | 44,031,127 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 784 | cpp | #include<stdio.h>
#include<algorithm>
#define INF 1000000
using namespace std;
int d[101][101] ;
main()
{
int a,b,tc=0 ;
while(scanf("%d%d",&a,&b)==2 && a+b)
{
for(int i=0;i<=100;i++) for(int j=0;j<=100;j++)
d[i][j]= (i==j ? 0 : INF) ;
d[a][b]=1 ;
while(scanf("%d%d",&a,&b)==2 && a+b) d[a][b]=1 ;
for(int k=1;k<=100;k++)
for(int i=1;i<=100;i++)
for(int j=1;j<=100;j++)
d[i][j]=min(d[i][j],d[i][k]+d[k][j]) ;
double ans=0.0,cnt=0.0 ;
for(int i=1;i<=100;i++) for(int j=1;j<=100;j++)
if(d[i][j]!=INF) {ans+=d[i][j] ; if(i!=j) cnt++ ;}
printf("Case %d: average length between pages = %.3lf clicks\n",++tc,ans/cnt) ;
}
}
| [
"[email protected]"
] | |
35c853756c54168af754088380c85e8dc062156d | ed9017f0222c52af0d2a6da73b9d046acae1ed76 | /workspace/Activity_timak/src/Graphics/Activity/ForkAlgorithm.cpp | 7ee95c135f9e0d56db648d24bcebb62c61627a2f | [] | no_license | next-dimension-team/Timak_15-16 | 7989d3a90d3cb20ec2a0d78fe604bf60740bf31d | 0902a296ff835a1a7f091b1d25351330ea5e74e8 | refs/heads/master | 2021-01-11T02:11:11.558451 | 2016-10-06T10:08:31 | 2016-10-06T10:08:31 | 70,096,900 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,691 | cpp | #include "ForkAlgorithm.h"
#include <math.h>
#include <OgreBlendMode.h>
#include <OgreCommon.h>
#include <OgreHardwarePixelBuffer.h>
#include <OgreLogManager.h>
#include <OgreManualObject.h>
#include <OgreMaterial.h>
#include <OgreMaterialManager.h>
#include <OgrePass.h>
#include <OgrePixelFormat.h>
#include <OgreRenderOperation.h>
#include <OgreSceneNode.h>
#include <OgreSharedPtr.h>
#include <OgreTechnique.h>
#include <OgreTexture.h>
#include <OgreTextureManager.h>
#include <sstream>
#include <string>
#include "../../Core/Activity/Fork.h"
#include "ForkGraphics.h"
#include "../../Core/Metamodel/include/Element.h"
#include "../../ApplicationManagement/ElementCollection.h"
#include "../../Core/Metamodel/include/ForkNode.h"
const double ForkAlgorithm::SIZE = 3;
ForkAlgorithm::ForkAlgorithm() : DrawingAlgorithm()
{
setSize((int)ForkAlgorithm::SIZE);
}
ForkAlgorithm::~ForkAlgorithm()
{}
void ForkAlgorithm::draw(const std::string& A_name)
{
std::pair<Element*, team4::MetamodelElement*> elem = ElementCollection::getInstance()->findElement(A_name);
Fork* elemCasted;
ForkGraphics* elemGraphicsCasted;
if (elem.second->getType() != team4::ForkNode::ELEMENT_TYPE)
{
std::ostringstream os;
os << "Invalid element type: ";
os << "Expecting '";
os << team4::ForkNode::ELEMENT_TYPE;
os << "' instead of '";
os << elem.second->getType();
os << "'.";
Ogre::LogManager::getSingleton().logMessage(os.str());
return;
}
else
{
elemCasted = static_cast<Fork*>(elem.first);
elemGraphicsCasted = static_cast<ForkGraphics*>(elem.first->getGraphics());
}
this->elem = elemCasted;
this->elemGraphics = elemGraphicsCasted;
double size = ForkAlgorithm::SIZE;
double z = 0;
Ogre::ManualObject* manualObject = elemGraphicsCasted->getManualObject();
int width = size;
int height = size *20;
manualObject->begin(elem.second->getName() + "_material", Ogre::RenderOperation::OT_TRIANGLE_STRIP);
manualObject->position(-height, width, z);
manualObject->position(height, width, z);
manualObject->position(-height, -width, z);
manualObject->position(height, -width, z);
manualObject->end();
manualObject->begin("BaseLineMaterial", Ogre::RenderOperation::OT_LINE_LIST);
manualObject->position(-height, width, z);
manualObject->position(height, width, z);
manualObject->position(-height, -width, z);
manualObject->position(height, -width, z);
manualObject->position(-height, width, z);
manualObject->position(-height, -width, z);
manualObject->position(height, width, z);
manualObject->position(height, -width, z);
manualObject->end();
Ogre::SceneNode* node = elemGraphicsCasted->getSceneNode();
node->attachObject(manualObject);
Ogre::MaterialPtr material = Ogre::MaterialManager::getSingleton().create(elem.second->getName() + "_material", "General");
elem.first->material=material;
material->getTechnique(0)->getPass(0)->createTextureUnitState(elem.second->getName() + "_texture");
material->getTechnique(0)->getPass(0)->setDepthCheckEnabled(false);
material->getTechnique(0)->getPass(0)->setSceneBlending(Ogre::SBT_MODULATE);
material->getTechnique(0)->getPass(0)->setDepthWriteEnabled(false);
material->getTechnique(0)->getPass(0)->setLightingEnabled(false);
material->getTechnique(0)->getPass(0)->setCullingMode(Ogre::CULL_NONE);
double textureSizeScale = 5;
Ogre::TexturePtr texture = Ogre::TextureManager::getSingleton().createManual(
elem.second->getName() + "_texture",
"General",
Ogre::TEX_TYPE_2D,
textureSizeScale * sqrt(2*pow(size,2)),
textureSizeScale * sqrt(2*pow(size,2)),
Ogre::MIP_UNLIMITED,
Ogre::PF_X8R8G8B8,
Ogre::TU_STATIC|Ogre::TU_AUTOMIPMAP);
Ogre::Texture* background = Ogre::TextureManager::getSingleton().load("3D_material_3.png", "General").getPointer();
texture->getBuffer()->blit(background->getBuffer());
}
void ForkAlgorithm::select(Element* elem)
{
Ogre::MaterialPtr material = elem->material;
material->getTechnique(0)->getPass(0)->setLightingEnabled(true);
}
void ForkAlgorithm::unselected(Element* elem)
{
Ogre::MaterialPtr material = elem->material;
material->getTechnique(0)->getPass(0)->setLightingEnabled(false);
}
double ForkAlgorithm::getFullSize()
{
return ForkAlgorithm::SIZE;
}
| [
"[email protected]"
] | |
1c53c4543c650b23552336f981d01a23c4551306 | f98a342cf3e30ef1ae810f1df6550ee7ed154ec7 | /SpriteNode.cpp | 4448a15d45ac45bcb23621c1829b5c0b7a13c520 | [] | no_license | nivuckovic/pokemon-clone | d683152028d8e1f8c4f5ea9913308fd8e0701d3e | 677a105d2c325f85d8ea3004e4c7859709a6b912 | refs/heads/master | 2022-01-24T19:06:20.943809 | 2022-01-10T10:18:47 | 2022-01-10T10:18:47 | 198,922,373 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 362 | cpp | #include "SpriteNode.h"
SpriteNode::SpriteNode(const sf::Texture & texture) : m_sprite(texture)
{
}
SpriteNode::SpriteNode(const sf::Texture & texture, const sf::IntRect & textureRect) : m_sprite(texture, textureRect)
{
}
void SpriteNode::drawCurrent(sf::RenderTarget & target, sf::RenderStates states) const
{
target.draw(m_sprite, states);
}
| [
"[email protected]"
] | |
f48d8806f14c1e8493263b2a03fc7d2500825e94 | 91a882547e393d4c4946a6c2c99186b5f72122dd | /Source/XPSP1/NT/admin/pchealth/sr/tools/logdump/logdump.cpp | dc979a0d647c24295743214653da6e7d09d7e11c | [] | no_license | IAmAnubhavSaini/cryptoAlgorithm-nt5src | 94f9b46f101b983954ac6e453d0cf8d02aa76fc7 | d9e1cdeec650b9d6d3ce63f9f0abe50dabfaf9e2 | refs/heads/master | 2023-09-02T10:14:14.795579 | 2021-11-20T13:47:06 | 2021-11-20T13:47:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,595 | cpp |
/*++
Copyright (c) 1998-1999 Microsoft Corporation
Module Name:
logdump.c
Abstract:
this file implements functrionality to read and dump the sr logs
Author:
Kanwaljit Marok (kmarok) 01-May-2000
Revision History:
--*/
#include <nt.h>
#include <ntrtl.h>
#include <nturtl.h>
#include <windows.h>
#include <stdio.h>
#include "logfmt.h"
#include "srapi.h"
struct _EVENT_STR_MAP
{
DWORD EventId;
PCHAR pEventStr;
} EventMap[ 13 ] =
{
{SrEventInvalid , "INVALID " },
{SrEventStreamChange, "FILE-MODIFY" },
{SrEventAclChange, "ACL-CHANGE " },
{SrEventAttribChange, "ATTR-CHANGE" },
{SrEventStreamOverwrite,"FILE-MODIFY" },
{SrEventFileDelete, "FILE-DELETE" },
{SrEventFileCreate, "FILE-CREATE" },
{SrEventFileRename, "FILE-RENAME" },
{SrEventDirectoryCreate,"DIR-CREATE " },
{SrEventDirectoryRename,"DIR-RENAME " },
{SrEventDirectoryDelete,"DIR-DELETE " },
{SrEventMountCreate, "MNT-CREATE " },
{SrEventMountDelete, "MNT-DELETE " }
};
BYTE Buffer[4096];
PCHAR
GetEventString(
DWORD EventId
)
{
PCHAR pStr = NULL;
static CHAR EventStringBuffer[8];
for( int i=0; i<sizeof(EventMap)/sizeof(_EVENT_STR_MAP);i++)
{
if ( EventMap[i].EventId == EventId )
{
pStr = EventMap[i].pEventStr;
}
}
if (pStr == NULL)
{
pStr = &EventStringBuffer[0];
wsprintf(pStr, "0x%X", EventId);
}
return pStr;
}
BOOLEAN
ProcessLogEntry(
BOOLEAN bPrintDebug,
LPCSTR pszSerNo,
LPCSTR pszSize,
LPCSTR pszEndSize,
LPCSTR pszSeqNo,
LPCSTR pszFlags,
LPCSTR pszProcess,
LPCSTR pszOperation,
LPCSTR pszAttr,
LPCSTR pszTmpFile,
LPCSTR pszPath1,
LPCSTR pszPath2,
LPCSTR pszAcl,
LPCSTR pszShortName,
LPCSTR pszProcessHandle,
LPCSTR pszThreadHandle)
{
BOOLEAN Status = TRUE;
if( bPrintDebug == FALSE )
{
printf( "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t",
pszSerNo,
pszSize,
pszSeqNo,
pszOperation,
pszAttr,
pszAcl,
pszPath1,
pszShortName);
}
else
{
printf( "%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t",
pszSerNo,
pszSize,
pszSeqNo,
pszOperation,
pszAttr,
pszProcess,
pszProcessHandle,
pszThreadHandle,
pszAcl,
pszPath1,
pszShortName);
}
if(pszTmpFile)
{
printf( "%s\t", pszTmpFile);
}
if(pszPath2)
{
printf( "%s\t", pszPath2);
}
printf("\n");
return Status;
}
#define SR_MAX_PATH ((1000) + sizeof (CHAR)) // Name will always be at most 1000 characters plus a NULL.
BOOLEAN
ReadLogData(
BOOLEAN bPrintDebugInfo,
LPTSTR pszFileName
)
{
BOOLEAN Status = FALSE;
BOOLEAN bHaveDebugInfo = FALSE;
HANDLE hFile;
DWORD nRead;
DWORD cbSize = 0, dwEntries = 0, dwEntriesAdded = 0;
DWORD dwSizeLow , dwSizeHigh;
CHAR szSerNo [10];
CHAR szSize [10];
CHAR szEndSize[10];
CHAR szSeqNo [20];
CHAR szOperation[50];
CHAR szAttr[50];
CHAR szFlags[10];
PCHAR szPath1 = NULL;
PCHAR szPath2 = NULL;
CHAR szTmpFile[MAX_PATH];
CHAR szAcl[MAX_PATH];
CHAR szShortName[MAX_PATH];
CHAR szProcess[32];
CHAR szProcessHandle[16];
CHAR szThreadHandle[16];
BYTE LogHeader[2048];
PSR_LOG_HEADER pLogHeader = (PSR_LOG_HEADER)LogHeader;
static INT s_dwEntries = -1;
szPath1 = (PCHAR) LocalAlloc( LMEM_FIXED, SR_MAX_PATH );
if (szPath1 == NULL )
{
fprintf( stderr, "Insufficient memory\n" );
}
szPath2 = (PCHAR) LocalAlloc( LMEM_FIXED, SR_MAX_PATH );
if (szPath2 == NULL )
{
fprintf( stderr, "Insufficient memory\n" );
}
hFile = CreateFile(
pszFileName,
GENERIC_READ,
FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL );
if ( hFile != INVALID_HANDLE_VALUE )
{
PBYTE pLoc = NULL;
dwSizeLow = GetFileSize( hFile, &dwSizeHigh );
//
// Read the header size
//
ReadFile(
hFile,
&cbSize,
sizeof(DWORD),
&nRead,
NULL );
SetFilePointer( hFile, - (INT)sizeof(DWORD), NULL, FILE_CURRENT );
//
// Read the whole header entry
//
ReadFile(
hFile,
pLogHeader,
cbSize,
&nRead,
NULL );
pLoc = (PBYTE)(&pLogHeader->SubRecords);
fprintf( stderr,
"Header Size: %ld, Version: %ld, Tool Version: %ld\n%S\n",
pLogHeader->Header.RecordSize,
pLogHeader->LogVersion,
SR_LOG_VERSION,
(LPWSTR)(pLoc + sizeof(RECORD_HEADER)) );
if( pLogHeader->LogVersion != SR_LOG_VERSION ||
pLogHeader->MagicNum != SR_LOG_MAGIC_NUMBER )
{
fprintf( stderr, "Invalid version or Corrupt log\n" );
CloseHandle(hFile);
goto End;
}
dwSizeLow -= pLogHeader->Header.RecordSize;
SetFilePointer (hFile,
pLogHeader->Header.RecordSize,
NULL,
FILE_BEGIN);
//
// Start reading the log entries
//
while( dwSizeLow )
{
PSR_LOG_ENTRY pLogEntry = (PSR_LOG_ENTRY)Buffer;
ZeroMemory(pLogEntry, sizeof(Buffer));
//
// Read the size of the entry
//
if ( !ReadFile(
hFile,
&pLogEntry->Header.RecordSize,
sizeof(DWORD),
&nRead,
NULL ) )
{
break;
}
cbSize = pLogEntry->Header.RecordSize;
if (cbSize == 0 )
{
//
// Zero size indicates end of the log
//
break;
}
SetFilePointer( hFile, - (INT)sizeof(DWORD), NULL, FILE_CURRENT );
//
// Read the rest of the entry
//
if ( !ReadFile( hFile,
((PBYTE)pLogEntry),
cbSize,
&nRead,
NULL ) )
{
break;
}
//
// Check the magic number
//
if( pLogEntry->MagicNum != SR_LOG_MAGIC_NUMBER )
{
fprintf(stderr, "Invalid Entry ( Magic num )\n");
break;
}
//
// Read the entries in to the buffer
//
sprintf( szSerNo , "%05d" , dwEntries + 1);
sprintf( szSize , "%04d" , pLogEntry->Header.RecordSize );
sprintf( szOperation, "%s" , GetEventString(
pLogEntry->EntryType ));
sprintf( szFlags , "%08x" , pLogEntry->EntryFlags );
sprintf( szSeqNo , "%010d" , pLogEntry->SequenceNum);
sprintf( szAttr , "%08x" , pLogEntry->Attributes );
sprintf( szProcess , "%12.12s" , pLogEntry->ProcName );
//
// get the first path
//
PBYTE pLoc = (PBYTE)&pLogEntry->SubRecords;
sprintf( szPath1 , "%S" , pLoc + sizeof(RECORD_HEADER) );
if (pLogEntry->EntryFlags & ENTRYFLAGS_TEMPPATH)
{
pLoc += RECORD_SIZE(pLoc);
sprintf( szTmpFile , "%S" , pLoc + sizeof(RECORD_HEADER) );
}
else
{
sprintf( szTmpFile , "" );
}
if (pLogEntry->EntryFlags & ENTRYFLAGS_SECONDPATH)
{
pLoc += RECORD_SIZE(pLoc);
sprintf( szPath2 , "%S" , pLoc + sizeof(RECORD_HEADER) );
}
else
{
sprintf( szPath2 , "" );
}
if (pLogEntry->EntryFlags & ENTRYFLAGS_ACLINFO)
{
ULONG AclInfoSize;
pLoc += RECORD_SIZE(pLoc);
AclInfoSize = RECORD_SIZE(pLoc);
sprintf( szAcl , "ACL(%04d)%" , AclInfoSize );
}
else
{
sprintf( szAcl , "" );
}
if (pLogEntry->EntryFlags & ENTRYFLAGS_DEBUGINFO)
{
bHaveDebugInfo = TRUE;
pLoc += RECORD_SIZE(pLoc);
sprintf( szProcess , "%12.12s",
((PSR_LOG_DEBUG_INFO)pLoc)->ProcessName );
sprintf( szProcessHandle,"0x%08X",
((PSR_LOG_DEBUG_INFO)pLoc)->ProcessId );
sprintf( szThreadHandle,"0x%08X",
((PSR_LOG_DEBUG_INFO)pLoc)->ThreadId );
}
else
{
bHaveDebugInfo = FALSE;
sprintf( szProcess , "" );
sprintf( szThreadHandle , "" );
sprintf( szProcessHandle , "" );
}
if (pLogEntry->EntryFlags & ENTRYFLAGS_SHORTNAME)
{
pLoc += RECORD_SIZE(pLoc);
sprintf( szShortName , "%S" , pLoc + sizeof(RECORD_HEADER) );
}
else
{
sprintf( szShortName , "" );
}
//
// read the trailing record size
//
sprintf( szEndSize , "%04d", GET_END_SIZE(pLogEntry));
ProcessLogEntry(
bPrintDebugInfo && bHaveDebugInfo,
szSerNo,
szSize,
szEndSize,
szSeqNo,
szFlags,
szProcess,
szOperation,
szAttr,
szTmpFile,
szPath1,
szPath2,
szAcl,
szShortName,
szProcessHandle,
szThreadHandle);
dwEntries++;
dwSizeLow -= cbSize;
cbSize = 0;
}
CloseHandle( hFile );
Status = TRUE;
}
else
{
fprintf( stderr, "Error opening LogFile %s\n", pszFileName );
}
End:
fprintf( stderr, "Number of entries read :%d\n", dwEntries );
if (szPath1 != NULL)
LocalFree( szPath1 );
if (szPath2 != NULL)
LocalFree( szPath2 );
return Status;
}
INT
__cdecl
main(
int argc,
char *argv[] )
{
if( argc < 2 || argc > 3 )
{
fprintf( stderr,
"USAGE: %s [-d] <LogFile> \n\t -d : debug info\n",
argv[0] );
}
else
{
int i = 1;
if ( argc == 3 && !strcmp( argv[i], "-d" ) )
{
i++;
ReadLogData(TRUE, argv[i] );
}
else
{
ReadLogData(FALSE, argv[i] );
}
}
return 0;
}
| [
"[email protected]"
] | |
72ccffca7796cf079a37937970b9163d083f3029 | 898ecea918175f07a36f7719ed3e0241a504f96b | /SNU Longest Hairpin Sequence/smallest.cpp | 95df57c9cb04abda5ced7da94205fe78d8670946 | [] | no_license | AdamBJ/Longest-Hairpin | b8abd0b508b1c317ccc0014a3955e5db5e35350a | 18167d394712d009b64e0093dd7688a51a26b6d6 | refs/heads/master | 2021-01-13T00:44:44.578462 | 2015-05-31T10:12:18 | 2015-05-31T10:12:18 | 36,597,709 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 153 | cpp | #include <algorithm> // std::min
//returns the minium of three input values
int smallest(int x, int y, int z){
return std::min(std::min(x, y), z);
} | [
"[email protected]"
] | |
289045c766490c88a0049d072660dab1e8fdc65a | 7e2b2217a5e2021b1495bde326e51dcf97ec3683 | /devel/include/turtlebot3_example/Turtlebot3Action.h | bfefa624472d580eeacea64794f1ff6c6581b856 | [] | no_license | JacobViertel/SOA_VZ1 | cffd0999856f1c26fbc17ff839a2a9a720c8a633 | 0bb2313b3de87cc282d047a4e66212d343fa96e2 | refs/heads/master | 2020-08-08T20:31:49.342284 | 2019-10-16T08:39:35 | 2019-10-16T08:39:35 | 213,911,528 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,050 | h | // Generated by gencpp from file turtlebot3_example/Turtlebot3Action.msg
// DO NOT EDIT!
#ifndef TURTLEBOT3_EXAMPLE_MESSAGE_TURTLEBOT3ACTION_H
#define TURTLEBOT3_EXAMPLE_MESSAGE_TURTLEBOT3ACTION_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
#include <turtlebot3_example/Turtlebot3ActionGoal.h>
#include <turtlebot3_example/Turtlebot3ActionResult.h>
#include <turtlebot3_example/Turtlebot3ActionFeedback.h>
namespace turtlebot3_example
{
template <class ContainerAllocator>
struct Turtlebot3Action_
{
typedef Turtlebot3Action_<ContainerAllocator> Type;
Turtlebot3Action_()
: action_goal()
, action_result()
, action_feedback() {
}
Turtlebot3Action_(const ContainerAllocator& _alloc)
: action_goal(_alloc)
, action_result(_alloc)
, action_feedback(_alloc) {
(void)_alloc;
}
typedef ::turtlebot3_example::Turtlebot3ActionGoal_<ContainerAllocator> _action_goal_type;
_action_goal_type action_goal;
typedef ::turtlebot3_example::Turtlebot3ActionResult_<ContainerAllocator> _action_result_type;
_action_result_type action_result;
typedef ::turtlebot3_example::Turtlebot3ActionFeedback_<ContainerAllocator> _action_feedback_type;
_action_feedback_type action_feedback;
typedef boost::shared_ptr< ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator> const> ConstPtr;
}; // struct Turtlebot3Action_
typedef ::turtlebot3_example::Turtlebot3Action_<std::allocator<void> > Turtlebot3Action;
typedef boost::shared_ptr< ::turtlebot3_example::Turtlebot3Action > Turtlebot3ActionPtr;
typedef boost::shared_ptr< ::turtlebot3_example::Turtlebot3Action const> Turtlebot3ActionConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace turtlebot3_example
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'turtlebot3_example': ['/home18/mr18m008/CATKINWS/devel/share/turtlebot3_example/msg'], 'actionlib_msgs': ['/opt/ros/melodic/share/actionlib_msgs/cmake/../msg'], 'std_msgs': ['/opt/ros/melodic/share/std_msgs/cmake/../msg'], 'geometry_msgs': ['/opt/ros/melodic/share/geometry_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator> >
{
static const char* value()
{
return "86a69578ab4eb5bb3e55984730f14503";
}
static const char* value(const ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x86a69578ab4eb5bbULL;
static const uint64_t static_value2 = 0x3e55984730f14503ULL;
};
template<class ContainerAllocator>
struct DataType< ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator> >
{
static const char* value()
{
return "turtlebot3_example/Turtlebot3Action";
}
static const char* value(const ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator> >
{
static const char* value()
{
return "# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n"
"\n"
"Turtlebot3ActionGoal action_goal\n"
"Turtlebot3ActionResult action_result\n"
"Turtlebot3ActionFeedback action_feedback\n"
"\n"
"================================================================================\n"
"MSG: turtlebot3_example/Turtlebot3ActionGoal\n"
"# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n"
"\n"
"Header header\n"
"actionlib_msgs/GoalID goal_id\n"
"Turtlebot3Goal goal\n"
"\n"
"================================================================================\n"
"MSG: std_msgs/Header\n"
"# Standard metadata for higher-level stamped data types.\n"
"# This is generally used to communicate timestamped data \n"
"# in a particular coordinate frame.\n"
"# \n"
"# sequence ID: consecutively increasing ID \n"
"uint32 seq\n"
"#Two-integer timestamp that is expressed as:\n"
"# * stamp.sec: seconds (stamp_secs) since epoch (in Python the variable is called 'secs')\n"
"# * stamp.nsec: nanoseconds since stamp_secs (in Python the variable is called 'nsecs')\n"
"# time-handling sugar is provided by the client library\n"
"time stamp\n"
"#Frame this data is associated with\n"
"string frame_id\n"
"\n"
"================================================================================\n"
"MSG: actionlib_msgs/GoalID\n"
"# The stamp should store the time at which this goal was requested.\n"
"# It is used by an action server when it tries to preempt all\n"
"# goals that were requested before a certain time\n"
"time stamp\n"
"\n"
"# The id provides a way to associate feedback and\n"
"# result message with specific goal requests. The id\n"
"# specified must be unique.\n"
"string id\n"
"\n"
"\n"
"================================================================================\n"
"MSG: turtlebot3_example/Turtlebot3Goal\n"
"# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n"
"# Define the goal\n"
"geometry_msgs/Vector3 goal\n"
"\n"
"================================================================================\n"
"MSG: geometry_msgs/Vector3\n"
"# This represents a vector in free space. \n"
"# It is only meant to represent a direction. Therefore, it does not\n"
"# make sense to apply a translation to it (e.g., when applying a \n"
"# generic rigid transformation to a Vector3, tf2 will only apply the\n"
"# rotation). If you want your data to be translatable too, use the\n"
"# geometry_msgs/Point message instead.\n"
"\n"
"float64 x\n"
"float64 y\n"
"float64 z\n"
"================================================================================\n"
"MSG: turtlebot3_example/Turtlebot3ActionResult\n"
"# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n"
"\n"
"Header header\n"
"actionlib_msgs/GoalStatus status\n"
"Turtlebot3Result result\n"
"\n"
"================================================================================\n"
"MSG: actionlib_msgs/GoalStatus\n"
"GoalID goal_id\n"
"uint8 status\n"
"uint8 PENDING = 0 # The goal has yet to be processed by the action server\n"
"uint8 ACTIVE = 1 # The goal is currently being processed by the action server\n"
"uint8 PREEMPTED = 2 # The goal received a cancel request after it started executing\n"
" # and has since completed its execution (Terminal State)\n"
"uint8 SUCCEEDED = 3 # The goal was achieved successfully by the action server (Terminal State)\n"
"uint8 ABORTED = 4 # The goal was aborted during execution by the action server due\n"
" # to some failure (Terminal State)\n"
"uint8 REJECTED = 5 # The goal was rejected by the action server without being processed,\n"
" # because the goal was unattainable or invalid (Terminal State)\n"
"uint8 PREEMPTING = 6 # The goal received a cancel request after it started executing\n"
" # and has not yet completed execution\n"
"uint8 RECALLING = 7 # The goal received a cancel request before it started executing,\n"
" # but the action server has not yet confirmed that the goal is canceled\n"
"uint8 RECALLED = 8 # The goal received a cancel request before it started executing\n"
" # and was successfully cancelled (Terminal State)\n"
"uint8 LOST = 9 # An action client can determine that a goal is LOST. This should not be\n"
" # sent over the wire by an action server\n"
"\n"
"#Allow for the user to associate a string with GoalStatus for debugging\n"
"string text\n"
"\n"
"\n"
"================================================================================\n"
"MSG: turtlebot3_example/Turtlebot3Result\n"
"# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n"
"# Define the result\n"
"string result\n"
"\n"
"================================================================================\n"
"MSG: turtlebot3_example/Turtlebot3ActionFeedback\n"
"# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n"
"\n"
"Header header\n"
"actionlib_msgs/GoalStatus status\n"
"Turtlebot3Feedback feedback\n"
"\n"
"================================================================================\n"
"MSG: turtlebot3_example/Turtlebot3Feedback\n"
"# ====== DO NOT MODIFY! AUTOGENERATED FROM AN ACTION DEFINITION ======\n"
"# Define a feedback message\n"
"string state\n"
"\n"
;
}
static const char* value(const ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.action_goal);
stream.next(m.action_result);
stream.next(m.action_feedback);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct Turtlebot3Action_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::turtlebot3_example::Turtlebot3Action_<ContainerAllocator>& v)
{
s << indent << "action_goal: ";
s << std::endl;
Printer< ::turtlebot3_example::Turtlebot3ActionGoal_<ContainerAllocator> >::stream(s, indent + " ", v.action_goal);
s << indent << "action_result: ";
s << std::endl;
Printer< ::turtlebot3_example::Turtlebot3ActionResult_<ContainerAllocator> >::stream(s, indent + " ", v.action_result);
s << indent << "action_feedback: ";
s << std::endl;
Printer< ::turtlebot3_example::Turtlebot3ActionFeedback_<ContainerAllocator> >::stream(s, indent + " ", v.action_feedback);
}
};
} // namespace message_operations
} // namespace ros
#endif // TURTLEBOT3_EXAMPLE_MESSAGE_TURTLEBOT3ACTION_H
| [
"[email protected]"
] | |
f1a434ed81af1ff8e428723b47e3894115e37e03 | d62af3d2dd56df30c190a59bf7699bc38865d610 | /cc/array/longest_consecutive_sequence.cc | 5c806132737a13ee731d283736f9efdb208c8b0e | [] | no_license | colinblack/leetcode | abadc3045c90b15694a17eb8d3916ac16f813332 | 9368bbc41993958fb4b538ef873f0dfc23488ba0 | refs/heads/master | 2020-07-24T20:30:48.841711 | 2020-01-13T23:51:51 | 2020-01-13T23:51:51 | 208,040,195 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 730 | cc | #include <iostream>
#include <unordered_map>
#include <vector>
#include <algorithm>
using std::vector;
using std::unordered_map;
class Solution {
public:
int longestConsecutive(vector<int> &num) {
unordered_map<int, bool> hash_table;
for (auto i : num)
{
hash_table[i] = false;
}
int length = 0;
for (auto i : num)
{
if (hash_table[i]) continue;
int len = 1;
hash_table[i] = true;
for (int j = i + 1; hash_table.find(j) != hash_table.end(); ++j)
{
hash_table[j] = true;
++len;
}
for (int j = i - 1; hash_table.find(j) != hash_table.end(); --j)
{
hash_table[j] = true;
++len;
}
length = std::max(length, len);
}
return length;
}
};
int main()
{
return 0;
} | [
"[email protected]"
] | |
7d45221b20beec0864ee7e7a4d34246a438f9211 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/squid/gumtree/squid_old_hunk_398.cpp | 414dc9fe7b74c670bdbec1a0d64cee3b75c3710d | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 512 | cpp | DelayTaggedBucket::~DelayTaggedBucket()
{
debugs(77, 3, "DelayTaggedBucket::~DelayTaggedBucket");
}
void
DelayTaggedBucket::stats (StoreEntry *entry) const
{
storeAppendPrintf(entry, " :" SQUIDSTRINGPH , SQUIDSTRINGPRINT(tag));
theBucket.stats (entry);
}
DelayTagged::Id::Id(DelayTagged::Pointer aDelayTagged, String &aTag) : theTagged(aDelayTagged)
{
theBucket = new DelayTaggedBucket(aTag);
DelayTaggedBucket::Pointer const *existing = theTagged->buckets.find(theBucket, DelayTaggedCmp);
| [
"[email protected]"
] | |
eb46a25d11bc8b682cefbc5384facc319d294d74 | dec817636542866fcb33b8ca41d1be119a51f5b1 | /myview/main.cpp | b68c617fc3319aa9bca8d2081c997a55a8a8b57e | [] | no_license | jinsook/cpluspluscodes | dfc6882a3e2489747cfb8a49800b115123483cca | 7d2be7b57b363e104d0aa774dfc420309972e691 | refs/heads/master | 2021-01-02T09:14:01.537354 | 2015-02-04T07:54:20 | 2015-02-04T07:54:20 | 23,863,934 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 342 | cpp | #include "ui_mainwindow.h"
#include <QtGui>
#include <QApplication>
#include "qtgui/ecanvas.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
QMainWindow *widget = new QMainWindow;
Ui::MainWindow ui;
ui.setupUi(widget);
widget->setCentralWidget(new ECanvas());
widget->show();
return a.exec();
}
| [
"[email protected]"
] | |
3529df8f8363115fb24802f3fd0705f170c09594 | ced1bc5e9b6035da5ff91b3ef4344faa45a477ea | /RE-flex-master/examples/ugrep.cpp | d5ab98850014c1071fb769a26eb8eb9ef38e3252 | [
"BSD-3-Clause"
] | permissive | WarlockD/BYOND_Compiler | 2892365967797b8abe4e05adf2ae0e755929a448 | 1fd2da9ed1465bbad42ad2fcc0592a308a735490 | refs/heads/master | 2020-06-13T05:36:45.687386 | 2019-12-22T14:16:51 | 2019-12-22T14:16:51 | 194,555,014 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,108 | cpp | /******************************************************************************\
* Copyright (c) 2019, Robert van Engelen, Genivia Inc. All rights reserved. *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are met: *
* *
* (1) Redistributions of source code must retain the above copyright notice, *
* this list of conditions and the following disclaimer. *
* *
* (2) Redistributions in binary form must reproduce the above copyright *
* notice, this list of conditions and the following disclaimer in the *
* documentation and/or other materials provided with the distribution. *
* *
* (3) 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. *
\******************************************************************************/
/**
@file ugrep.cpp
@brief Universal grep - high-performance Unicode file search utility
@author Robert van Engelen - [email protected]
@copyright (c) 2019-2019, Robert van Engelen, Genivia Inc. All rights reserved.
@copyright (c) BSD-3 License - see LICENSE.txt
Universal grep - high-performance universal search utility finds Unicode
patterns in UTF-8/16/32, ASCII, ISO-8859-1, EBCDIC, code pages 437, 850, 1250
to 1258, and other file formats.
For download and installation of the latest version, see:
https://github.com/Genivia/ugrep
Features:
- Patterns are ERE POSIX syntax compliant, extended with RE/flex pattern syntax.
- Unicode support for \p{} character categories, bracket list classes, etc.
- File encoding support for UTF-8/16/32, EBCDIC, and many other code pages.
- ugrep command-line options are the same as grep, simulates grep behavior.
Differences with grep:
- When option -b is used with option -o or with option -g, ugrep displays the
exact byte offset of the pattern match instead of the byte offset of the
start of the matched line.
- Adds option -g, --no-group to not group matches per line. This option
displays a matched input line again for each additional pattern match.
This option also changes option -c to report the total number of pattern
matches per file instead of the number of lines matched.
- Adds option -k, --column-number to display the column number, taking tab
spacing into account by expanding tabs.
Examples:
# display the lines in places.txt that contain capitalized Unicode words
ugrep '\p{Upper}\p{Lower}*' places.txt
# display the lines in places.txt with capitalized Unicode words color-highlighted
ugrep --color=auto '\p{Upper}\p{Lower}*' places.txt
# list all capitalized Unicode words in places.txt
ugrep -o '\p{Upper}\p{Lower}*' places.txt
# list all laughing face emojis (Unicode code points U+1F600 to U+1F60F) in birthday.txt
ugrep -o '[😀-😏]' birthday.txt
# list all laughing face emojis (Unicode code points U+1F600 to U+1F60F) in birthday.txt
ugrep -o '[\x{1F600}-\x{1F60F}]' birthday.txt
# display lines containing the names Gödel (or Goedel), Escher, or Bach in GEB.txt and wiki.txt
ugrep 'G(ö|oe)del|Escher|Bach' GEB.txt wiki.txt
# display lines that do not contain the names Gödel (or Goedel), Escher, or Bach in GEB.txt and wiki.txt
ugrep -v 'G(ö|oe)del|Escher|Bach' GEB.txt wiki.txt
# count the number of lines containing the names Gödel (or Goedel), Escher, or Bach in GEB.txt and wiki.txt
ugrep -c 'G(ö|oe)del|Escher|Bach' GEB.txt wiki.txt
# count the number of occurrences of the names Gödel (or Goedel), Escher, or Bach in GEB.txt and wiki.txt
ugrep -c -g 'G(ö|oe)del|Escher|Bach' GEB.txt wiki.txt
# check if some.txt file contains any non-ASCII (i.e. Unicode) characters
ugrep -q '[^[:ascii:]]' some.txt && echo "some.txt contains Unicode"
# display word-anchored 'lorem' in UTF-16 formatted file utf16lorem.txt that contains a UTF-16 BOM
ugrep -w -i 'lorem' utf16lorem.txt
# display word-anchored 'lorem' in UTF-16 formatted file utf16lorem.txt that does not contain a UTF-16 BOM
ugrep --file-format=UTF-16 -w -i 'lorem' utf16lorem.txt
# list the lines to fix in a C/C++ source file by looking for the word FIXME while skipping any FIXME in quoted strings by using a negative pattern `(?^X)' to ignore quoted strings:
ugrep -n -o -e 'FIXME' -e '(?^"(\\.|\\\r?\n|[^\\\n"])*")' file.cpp
# check if 'main' is defined in a C/C++ source file, skipping the word 'main' in comments and strings:
ugrep -q -e '\<main\>' -e '(?^"(\\.|\\\r?\n|[^\\\n"])*"|//.*|/[*](.|\n)*?[*]/)' file.cpp
Compile:
c++ -std=c++11 -o ugrep ugrep.cpp -lreflex
*/
#include <reflex/matcher.h>
// check if we are on a windows OS
#if defined(__WIN32__) || defined(_WIN32) || defined(WIN32) || defined(__CYGWIN__) || defined(__MINGW32__) || defined(__MINGW64__) || defined(__BORLANDC__)
# define OS_WIN
#endif
// windows has no isatty()
#ifdef OS_WIN
#define isatty(fildes) ((fildes) == 1)
#else
#include <unistd.h>
#endif
// ugrep version
#define VERSION "1.0.0"
// ugrep platform -- see configure.ac
#if !defined(PLATFORM)
# if defined(OS_WIN)
# define PLATFORM "WIN"
# else
# define PLATFORM ""
# endif
#endif
// ugrep exit codes
#define EXIT_OK 0 // One or more lines were selected
#define EXIT_FAIL 1 // No lines were selected
#define EXIT_ERROR 2 // An error occurred
// GREP_COLOR environment variable
const char *grep_color = NULL;
// ugrep command-line options
bool flag_filename = false;
bool flag_no_filename = false;
bool flag_no_group = false;
bool flag_no_messages = false;
bool flag_byte_offset = false;
bool flag_count = false;
bool flag_fixed_strings = false;
bool flag_free_space = false;
bool flag_ignore_case = false;
bool flag_invert_match = false;
bool flag_column_number = false;
bool flag_line_number = false;
bool flag_line_buffered = false;
bool flag_only_matching = false;
bool flag_quiet = false;
bool flag_word_regexp = false;
bool flag_line_regexp = false;
const char *flag_color = NULL;
const char *flag_file_format = NULL;
int flag_tabs = 8;
// function protos
bool ugrep(reflex::Pattern& pattern, FILE *file, reflex::Input::file_encoding_type encoding, const char *infile);
void help(const char *message = NULL, const char *arg = NULL);
void version();
// table of file formats for ugrep option --file-format
const struct { const char *format; reflex::Input::file_encoding_type encoding; } format_table[] = {
{ "binary", reflex::Input::file_encoding::plain },
{ "ISO-8859-1", reflex::Input::file_encoding::latin },
{ "ASCII", reflex::Input::file_encoding::utf8 },
{ "EBCDIC", reflex::Input::file_encoding::ebcdic },
{ "UTF-8", reflex::Input::file_encoding::utf8 },
{ "UTF-16", reflex::Input::file_encoding::utf16be },
{ "UTF-16BE", reflex::Input::file_encoding::utf16be },
{ "UTF-16LE", reflex::Input::file_encoding::utf16le },
{ "UTF-32", reflex::Input::file_encoding::utf32be },
{ "UTF-32BE", reflex::Input::file_encoding::utf32be },
{ "UTF-32LE", reflex::Input::file_encoding::utf32le },
{ "CP437", reflex::Input::file_encoding::cp437 },
{ "CP850", reflex::Input::file_encoding::cp850 },
{ "CP1250", reflex::Input::file_encoding::cp1250 },
{ "CP1251", reflex::Input::file_encoding::cp1251 },
{ "CP1252", reflex::Input::file_encoding::cp1252 },
{ "CP1253", reflex::Input::file_encoding::cp1253 },
{ "CP1254", reflex::Input::file_encoding::cp1254 },
{ "CP1255", reflex::Input::file_encoding::cp1255 },
{ "CP1256", reflex::Input::file_encoding::cp1256 },
{ "CP1257", reflex::Input::file_encoding::cp1257 },
{ "CP1258", reflex::Input::file_encoding::cp1258 },
{ NULL, 0 }
};
// ugrep main()
int main(int argc, char **argv)
{
std::string regex;
std::vector<const char*> infiles;
bool color_term = false;
#ifndef OS_WIN
// check whether we have a color terminal
const char *term = getenv("TERM");
color_term = term && (strstr(term, "ansi") || strstr(term, "xterm") || strstr(term, "color"));
grep_color = getenv("GREP_COLOR");
#endif
// parse ugrep command-line options and arguments
for (int i = 1; i < argc; ++i)
{
const char *arg = argv[i];
if (*arg == '-'
#ifdef OS_WIN
|| *arg == '/'
#endif
)
{
bool is_grouped = true;
// parse a ugrep command-line option
while (is_grouped && *++arg)
{
switch (*arg)
{
case '-':
++arg;
if (strcmp(arg, "byte-offset") == 0)
flag_byte_offset = true;
else if (strcmp(arg, "color") == 0 || strcmp(arg, "colour") == 0)
flag_color = "auto";
else if (strncmp(arg, "color=", 6) == 0)
flag_color = arg + 6;
else if (strncmp(arg, "colour=", 7) == 0)
flag_color = arg + 7;
else if (strcmp(arg, "column-number") == 0)
flag_column_number = true;
else if (strcmp(arg, "count") == 0)
flag_count = true;
else if (strcmp(arg, "extended-regexp") == 0)
;
else if (strncmp(arg, "file-format=", 12) == 0)
flag_file_format = arg + 12;
else if (strcmp(arg, "fixed-strings") == 0)
flag_fixed_strings = true;
else if (strcmp(arg, "free-space") == 0)
flag_free_space = true;
else if (strcmp(arg, "help") == 0)
help();
else if (strcmp(arg, "ignore-case") == 0)
flag_ignore_case = true;
else if (strcmp(arg, "invert-match") == 0)
flag_invert_match = true;
else if (strcmp(arg, "line-number") == 0)
flag_line_number = true;
else if (strcmp(arg, "line-regexp") == 0)
flag_line_regexp = true;
else if (strcmp(arg, "no-filename") == 0)
flag_no_filename = true;
else if (strcmp(arg, "no-group") == 0)
flag_no_group = true;
else if (strcmp(arg, "no-messages") == 0)
flag_no_messages = true;
else if (strcmp(arg, "only-matching") == 0)
flag_only_matching = true;
else if (strcmp(arg, "quiet") == 0 || strcmp(arg, "silent") == 0)
flag_quiet = true;
else if (strncmp(arg, "regexp=", 7) == 0)
regex.append(arg + 7).push_back('|');
else if (strncmp(arg, "tabs=", 5) == 0)
flag_tabs = atoi(arg + 5);
else if (strcmp(arg, "version") == 0)
version();
else if (strcmp(arg, "word-regexp") == 0)
flag_word_regexp = true;
else
help("unknown option --", arg);
is_grouped = false;
break;
case 'b':
flag_byte_offset = true;
break;
case 'c':
flag_count = true;
break;
case 'E':
break;
case 'e':
++arg;
if (*arg)
regex.append(&arg[*arg == '=']).push_back('|');
else if (++i < argc)
regex.append(argv[i]).push_back('|');
else
help("missing pattern for option -e");
is_grouped = false;
break;
case 'F':
flag_fixed_strings = true;
break;
case 'g':
flag_no_group = true;
break;
case 'H':
flag_filename = true;
flag_no_filename = false;
break;
case 'h':
flag_filename = false;
flag_no_filename = true;
break;
case 'i':
flag_ignore_case = true;
break;
case 'k':
flag_column_number = true;
break;
case 'n':
flag_line_number = true;
break;
case 'o':
flag_only_matching = true;
break;
case 'q':
flag_quiet = true;
break;
case 's':
flag_no_messages = true;
break;
case 'V':
version();
break;
case 'v':
flag_invert_match = true;
break;
case 'w':
flag_word_regexp = true;
break;
case 'x':
flag_line_regexp = true;
break;
case '?':
help();
default:
help("unknown option -", arg);
}
}
}
else
{
// parse a ugrep command-line argument
if (regex.empty())
// no regex pattern specified yet, so assign it to the regex string
regex.assign(arg).push_back('|');
else
// otherwise add the file argument to the list of files
infiles.push_back(arg);
}
}
// if no regex pattern was specified then exit
if (regex.empty())
help();
// remove the ending '|' from the |-concatenated regexes in the regex string
regex.pop_back();
if (regex.empty())
{
// if the specified regex is empty then it matches every line
regex.assign(".*");
}
else
{
// if -F --fixed-strings: make regex literal with \Q and \E
if (flag_fixed_strings)
regex.insert(0, "\\Q").append("\\E");
// if -w or -x: make the regex word- or line-anchored, respectively
if (flag_word_regexp)
regex.insert(0, "\\<(").append(")\\>");
else if (flag_line_regexp)
regex.insert(0, "^(").append(")$");
}
// if -v invert-match: options -g --no-group and -o --only-matching options cannot be used
if (flag_invert_match)
{
flag_no_group = false;
flag_only_matching = false;
}
// input is line-buffered if options -c --count -o --only-matching -q --quiet are not specified
if (!flag_count && !flag_only_matching && !flag_quiet)
flag_line_buffered = true;
// display file name if more than one input file is specified and option -h --no-filename is not specified
if (infiles.size() > 1 && !flag_no_filename)
flag_filename = true;
// (re)set grep_color depending on color_term, isatty(), and the ugrep --color option
if (!flag_color || strcmp(flag_color, "never") == 0)
{
grep_color = NULL;
}
else if (strcmp(flag_color, "always") == 0)
{
if (!grep_color)
grep_color = "1";
}
else if (strcmp(flag_color, "auto") == 0)
{
if (!color_term || !isatty(1))
grep_color = NULL;
else if (!grep_color)
grep_color = "1";
}
else
{
help("unknown --color=when value");
}
// if any match was found in any of the input files then we set found==true
bool found = false;
try
{
reflex::Input::file_encoding_type encoding = reflex::Input::file_encoding::plain;
// parse ugrep option --file-format=format
if (flag_file_format)
{
int i;
// scan the format_table[] for a matching format
for (i = 0; format_table[i].format != NULL; ++i)
if (strcmp(flag_file_format, format_table[i].format) == 0)
break;
if (format_table[i].format == NULL)
help("unknown --file-format=format encoding");
// encoding is the file format used by all input files, if no BOM is present
encoding = format_table[i].encoding;
}
std::string modifiers = "(?m";
if (flag_ignore_case)
modifiers.append("i");
if (flag_free_space)
modifiers.append("x");
modifiers.append(")");
std::string pattern_options;
if (flag_tabs)
{
if (flag_tabs == 1 || flag_tabs == 2 || flag_tabs == 4 || flag_tabs == 8)
pattern_options.assign("T=").push_back(flag_tabs + '0');
else
help("invalid value for option --tabs");
}
reflex::Pattern pattern(modifiers + reflex::Matcher::convert(regex, reflex::convert_flag::unicode), pattern_options);
if (infiles.empty())
{
// read standard input to find pattern matches
found |= ugrep(pattern, stdin, encoding, "(standard input)");
}
else
{
// read each file to find pattern matches
for (auto infile : infiles)
{
FILE *file = fopen(infile, "r");
if (file == NULL)
{
if (flag_no_messages)
continue;
perror("Cannot open file for reading");
exit(EXIT_ERROR);
}
found |= ugrep(pattern, file, encoding, infile);
fclose(file);
}
}
}
catch (reflex::regex_error& error)
{
std::cerr << error.what();
exit(EXIT_ERROR);
}
exit(found ? EXIT_OK : EXIT_FAIL);
}
// Search file, display pattern matches, return true when pattern matched anywhere
bool ugrep(reflex::Pattern& pattern, FILE *file, reflex::Input::file_encoding_type encoding, const char *infile)
{
bool found = false;
std::string label, mark, unmark;
if (flag_filename && infile)
label.assign(infile).append(":");
if (grep_color)
{
mark.assign("\033[").append(grep_color).append("m");
unmark.assign("\033[0m");
}
// create an input object to read the file (or stdin) using the given file format encoding
reflex::Input input(file, encoding);
if (flag_quiet)
{
// -q quite mode: report if a single pattern match was found in the input
found = reflex::Matcher(pattern, input).find();
if (flag_invert_match)
found = !found;
}
else if (flag_count)
{
// -c count mode: count the number of lines/patterns matched
if (flag_invert_match)
{
size_t lines = 0;
std::string line;
// -c count mode w/ -v: count the number of non-matching lines
while (input)
{
int ch;
// read the next line
line.clear();
while ((ch = input.get()) != EOF && ch != '\n')
line.push_back(ch);
if (ch == EOF && line.empty())
break;
// count this line if not matched
if (!reflex::Matcher(pattern, line).find())
{
found = true;
++lines;
}
}
std::cout << label << lines << std::endl;
}
else if (flag_no_group)
{
// -c count mode w/ -g: count the number of patterns matched in the file
reflex::Matcher matcher(pattern, input);
size_t matches = std::distance(matcher.find.begin(), matcher.find.end());
std::cout << label << matches << std::endl;
found = matches > 0;
}
else
{
// -c count mode w/o -g: count the number of matching lines
size_t lineno = 0;
size_t lines = 0;
reflex::Matcher matcher(pattern, input);
for (auto& match : matcher.find)
{
if (lineno != match.lineno())
{
lineno = match.lineno();
++lines;
}
}
std::cout << label << lines << std::endl;
found = lines > 0;
}
}
else if (flag_line_buffered)
{
// line-buffered input: read input line-by-line and display lines that matched the pattern
size_t byte_offset = 0;
size_t lineno = 1;
std::string line;
while (input)
{
int ch;
// read the next line
line.clear();
while ((ch = input.get()) != EOF && ch != '\n')
line.push_back(ch);
if (ch == EOF && line.empty())
break;
if (flag_invert_match)
{
// -v invert match: display non-matching line
if (!reflex::Matcher(pattern, line).find())
{
std::cout << label;
if (flag_line_number)
std::cout << lineno << ":";
if (flag_byte_offset)
std::cout << byte_offset << ":";
std::cout << line << std::endl;
found = true;
}
}
else if (flag_no_group)
{
// search the line for pattern matches and display the line again (with exact offset) for each pattern match
reflex::Matcher matcher(pattern, line);
for (auto& match : matcher.find)
{
std::cout << label;
if (flag_line_number)
std::cout << lineno << ":";
if (flag_column_number)
std::cout << match.columno() + 1 << ":";
if (flag_byte_offset)
std::cout << byte_offset << ":";
std::cout << line.substr(0, match.first()) << mark << match.text() << unmark << line.substr(match.last()) << std::endl;
found = true;
}
}
else
{
// search the line for pattern matches and display the line just once with all matches
size_t last = 0;
reflex::Matcher matcher(pattern, line);
for (auto& match : matcher.find)
{
if (last == 0)
{
std::cout << label;
if (flag_line_number)
std::cout << lineno << ":";
if (flag_column_number)
std::cout << match.columno() + 1 << ":";
if (flag_byte_offset)
std::cout << byte_offset + match.first() << ":";
std::cout << line.substr(0, match.first()) << mark << match.text() << unmark;
last = match.last();
found = true;
}
else
{
std::cout << line.substr(last, match.first() - last) << mark << match.text() << unmark;
last = match.last();
}
}
if (last > 0)
std::cout << line.substr(last) << std::endl;
}
// update byte offset and line number
byte_offset += line.size() + 1;
++lineno;
}
}
else
{
// block-buffered input: echo all pattern matches
size_t lineno = 0;
reflex::Matcher matcher(pattern, input);
for (auto& match : matcher.find)
{
if (flag_no_group || lineno != match.lineno())
{
lineno = match.lineno();
std::cout << label;
if (flag_line_number)
std::cout << lineno << ":";
if (flag_column_number)
std::cout << match.columno() + 1 << ":";
if (flag_byte_offset)
std::cout << match.first() << ":";
}
std::cout << mark << match.text() << unmark << std::endl;
found = true;
}
}
return found;
}
// Display help information with an optional diagnostic message and exit
void help(const char *message, const char *arg)
{
if (message)
std::cout << "ugrep: " << message << (arg != NULL ? arg : "") << std::endl;
std::cout << "Usage: ugrep [-bcEFgHhiknoqsVvwx] [--colour[=when]|--color[=when]] [-e pattern] [pattern] [file ...]\n\
\n\
-b, --byte-offset\n\
The offset in bytes of a matched pattern is displayed in front of\n\
the respective matched line.\n\
-c, --count\n\
Only a count of selected lines is written to standard output.\n\
When used with option -g, counts the number of patterns matched.\n\
--colour[=when], --color[=when]\n\
Mark up the matching text with the expression stored in the\n\
GREP_COLOR environment variable. The possible values of when can\n\
be `never', `always' or `auto'.\n\
-E, --extended-regexp\n\
Ignored, intended for grep compatibility.\n\
-e pattern, --regexp=pattern\n\
Specify a pattern used during the search of the input: an input\n\
line is selected if it matches any of the specified patterns.\n\
This option is most useful when multiple -e options are used to\n\
specify multiple patterns, or when a pattern begins with a dash\n\
(`-').\n\
--file-format=format\n\
The input file format. The possible values of format can be:";
for (int i = 0; format_table[i].format != NULL; ++i)
std::cout << (i % 8 ? " " : "\n ") << format_table[i].format;
std::cout << "\n\
-F, --fixed-strings\n\
Interpret pattern as a set of fixed strings (i.e. force ugrep to\n\
behave as fgrep).\n\
--free-space\n\
Spacing (blanks and tabs) in regular expressions are ignored.\n\
-g, --no-group\n\
Do not group pattern matches on the same line. Display the\n\
matched line again for each additional pattern match.\n\
-H\n\
Always print filename headers with output lines.\n\
-h, --no-filename\n\
Never print filename headers (i.e. filenames) with output lines.\n\
-?, --help\n\
Print a help message.\n\
-i, --ignore-case\n\
Perform case insensitive matching. This option applies\n\
case-insensitive matching of ASCII characters in the input.\n\
By default, ugrep is case sensitive.\n\
-k, --column-number\n\
The column number of a matched pattern is displayed in front of\n\
the respective matched line, starting at column 1. Tabs are\n\
expanded before columns are counted.\n\
-n, --line-number\n\
Each output line is preceded by its relative line number in the\n\
file, starting at line 1. The line number counter is reset for\n\
each file processed.\n\
-o, --only-matching\n\
Prints only the matching part of the lines. Allows a pattern\n\
match to span multiple lines.\n\
-q, --quiet, --silent\n\
Quiet mode: suppress normal output. ugrep will only search a file\n\
until a match has been found, making searches potentially less\n\
expensive. Allows a pattern match to span multiple lines.\n\
-s, --no-messages\n\
Silent mode. Nonexistent and unreadable files are ignored (i.e.\n\
their error messages are suppressed).\n\
--tabs=size\n\
Set the tab size to 1, 2, 4, or 8 to expand tabs for option -k.\n\
-V, --version\n\
Display version information and exit.\n\
-v, --invert-match\n\
Selected lines are those not matching any of the specified\n\
patterns.\n\
-w, --word-regexp\n\
The pattern is searched for as a word (as if surrounded by\n\
`\\<' and `\\>').\n\
-x, --line-regexp\n\
Only input lines selected against an entire pattern are considered\n\
to be matching lines (as if surrounded by ^ and $).\n\
\n\
The ugrep utility exits with one of the following values:\n\
\n\
0 One or more lines were selected.\n\
1 No lines were selected.\n\
>1 An error occurred.\n\
" << std::endl;
exit(EXIT_ERROR);
}
// Display version info
void version()
{
std::cout << "ugrep " VERSION " " PLATFORM << std::endl;
exit(EXIT_OK);
}
| [
"[email protected]"
] | |
54267294af1ff08e226a18605b3dd0b45f6a6914 | 5544235b9aa443ff5dc0731ee8cf7d557e9bc346 | /src/ch11.cpp | fbe85d9938bf4a77b7669fa34b9c1b3ebd965179 | [] | no_license | eric-simon/TMPBook | 67617cb2378aecdd19d378c0a50ffe5826f939b1 | 949c0d50fb396eb9cf3071ef059b30614985a7c4 | refs/heads/master | 2020-06-19T10:20:44.343955 | 2019-06-23T01:22:37 | 2019-06-23T01:22:37 | 74,908,953 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 438 | cpp | #include "stdafx.h"
#include "ch11.h"
#include "player.h"
#include <vector>
#include <ctime>
int ch11(int argc, _TCHAR* argv[])
{
player p;
p.process_event(open_close());
p.process_event(open_close());
//p.process_event(cd_detected("Louie, Louie", std::vector<std::clock_t>()));
p.process_event(cd_detected());
p.process_event(play());
p.process_event(pause());
p.process_event(play());
p.process_event(stop());
return 0;
} | [
"[email protected]"
] | |
6d580017737fb63134410a05b3a52c8ef8855827 | 8260762b35ea04ab54eac2043007bb1dd1a4be12 | /Streams/OStream.h | 3ecd2a60d3411df7aa551df517752a19662be888 | [] | no_license | analyst1001/SSHHandshakeFuzzer | 6253c447496daf8442ce4da6756c368e44e1e068 | 16d14605369a2589cc67bea6d55507ff9e055395 | refs/heads/master | 2020-03-13T18:40:23.962497 | 2018-05-03T23:18:02 | 2018-05-03T23:18:02 | 131,239,961 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 205 | h | #include "Stream.h"
#include "../MessageBuffers/MessageBuffer.h"
#ifndef OSTREAM_H
#define OSTREAM_H
class OStream : public Stream {
public:
virtual void write(MessageBuffer *) = 0;
};
#endif
| [
"[email protected]"
] | |
b2c0c0ec2f2bc32fc4320b2af0c469018cca2cfd | 15f6b119c19db8471210fc99650a1974c27fbc4c | /A/1176A.cpp | 7fc31d65e8b719dc605998e8b084c91ecb34c5b6 | [] | no_license | AsifWatson/codeforces | 8d1afd7f56fe84836e770d2de68f9caad596480b | ee38a5e8c19a54588fecf4f26986975e258e3b6b | refs/heads/master | 2021-07-12T23:33:54.021007 | 2021-02-28T14:06:09 | 2021-02-28T14:06:09 | 234,949,673 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 928 | cpp | #include "bits/stdc++.h"
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define all(v) v.begin(),v.end()
#define allre(v) v.rbegin(),v.rend()
#define sp(x,y) fixed<<setprecision(y)<<x
#define max3(a,b,c) max(a,max(b,c))
#define min3(a,b,c) min(a,min(b,c))
#define GCD(a,b) __gcd(a,b)
#define LCM(a,b) ((a*b)/__gcd(a,b))
using namespace std;
const double pi = acos(-1.0);
const double EPS = 1e-6;
const int MOD = (int)1e9+7;
bool Reverse(long long a,long long b){return a>b;}
int main()
{
IOS
long long q,n,ans;
cin>>q;
while(q--)
{
cin>>n;
ans=0;
while(true)
{
if(n==1)break;
if(n%2==0){n/=2;ans++;}
else
{
if(n%3==0){n/=3;n*=2;ans++;}
else if(n%5==0){n/=5;n*=4;ans++;}
else {ans=-1;break;}
}
}
cout<<ans<<endl;
}
return 0;
}
| [
"[email protected]"
] | |
a368f9ccd5c955e722941c78dcef007b6840b843 | ac1c9fbc1f1019efb19d0a8f3a088e8889f1e83c | /out/release/gen/third_party/blink/renderer/bindings/core/v8/v8_hash_change_event.cc | 38877198dd920e0296c490553215f0d577e2fdf9 | [
"BSD-3-Clause"
] | permissive | xueqiya/chromium_src | 5d20b4d3a2a0251c063a7fb9952195cda6d29e34 | d4aa7a8f0e07cfaa448fcad8c12b29242a615103 | refs/heads/main | 2022-07-30T03:15:14.818330 | 2021-01-16T16:47:22 | 2021-01-16T16:47:22 | 330,115,551 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,745 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated from the Jinja2 template
// third_party/blink/renderer/bindings/templates/interface.cc.tmpl
// by the script code_generator_v8.py.
// DO NOT MODIFY!
// clang-format off
#include "third_party/blink/renderer/bindings/core/v8/v8_hash_change_event.h"
#include <algorithm>
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/bindings/core/v8/idl_types.h"
#include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_dom_configuration.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_hash_change_event_init.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/frame/local_dom_window.h"
#include "third_party/blink/renderer/platform/bindings/exception_messages.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/bindings/runtime_call_stats.h"
#include "third_party/blink/renderer/platform/bindings/v8_object_constructor.h"
#include "third_party/blink/renderer/platform/scheduler/public/cooperative_scheduling_manager.h"
#include "third_party/blink/renderer/platform/wtf/get_ptr.h"
namespace blink {
// Suppress warning: global constructors, because struct WrapperTypeInfo is trivial
// and does not depend on another global objects.
#if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wglobal-constructors"
#endif
const WrapperTypeInfo v8_hash_change_event_wrapper_type_info = {
gin::kEmbedderBlink,
V8HashChangeEvent::DomTemplate,
nullptr,
"HashChangeEvent",
V8Event::GetWrapperTypeInfo(),
WrapperTypeInfo::kWrapperTypeObjectPrototype,
WrapperTypeInfo::kObjectClassId,
WrapperTypeInfo::kNotInheritFromActiveScriptWrappable,
};
#if defined(COMPONENT_BUILD) && defined(WIN32) && defined(__clang__)
#pragma clang diagnostic pop
#endif
// This static member must be declared by DEFINE_WRAPPERTYPEINFO in HashChangeEvent.h.
// For details, see the comment of DEFINE_WRAPPERTYPEINFO in
// platform/bindings/ScriptWrappable.h.
const WrapperTypeInfo& HashChangeEvent::wrapper_type_info_ = v8_hash_change_event_wrapper_type_info;
// not [ActiveScriptWrappable]
static_assert(
!std::is_base_of<ActiveScriptWrappableBase, HashChangeEvent>::value,
"HashChangeEvent inherits from ActiveScriptWrappable<>, but is not specifying "
"[ActiveScriptWrappable] extended attribute in the IDL file. "
"Be consistent.");
static_assert(
std::is_same<decltype(&HashChangeEvent::HasPendingActivity),
decltype(&ScriptWrappable::HasPendingActivity)>::value,
"HashChangeEvent is overriding hasPendingActivity(), but is not specifying "
"[ActiveScriptWrappable] extended attribute in the IDL file. "
"Be consistent.");
namespace hash_change_event_v8_internal {
static void OldURLAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Local<v8::Object> holder = info.Holder();
HashChangeEvent* impl = V8HashChangeEvent::ToImpl(holder);
V8SetReturnValueString(info, impl->oldURL(), info.GetIsolate());
}
static void NewURLAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Local<v8::Object> holder = info.Holder();
HashChangeEvent* impl = V8HashChangeEvent::ToImpl(holder);
V8SetReturnValueString(info, impl->newURL(), info.GetIsolate());
}
static void IsTrustedAttributeGetter(const v8::FunctionCallbackInfo<v8::Value>& info) {
v8::Local<v8::Object> holder = info.Holder();
HashChangeEvent* impl = V8HashChangeEvent::ToImpl(holder);
V8SetReturnValueBool(info, impl->isTrusted());
}
static void Constructor(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HashChangeEvent_ConstructorCallback");
ExceptionState exception_state(info.GetIsolate(), ExceptionState::kConstructionContext, "HashChangeEvent");
if (UNLIKELY(info.Length() < 1)) {
exception_state.ThrowTypeError(ExceptionMessages::NotEnoughArguments(1, info.Length()));
return;
}
V8StringResource<> type;
HashChangeEventInit* event_init_dict;
type = info[0];
if (!type.Prepare())
return;
if (!info[1]->IsNullOrUndefined() && !info[1]->IsObject()) {
exception_state.ThrowTypeError("parameter 2 ('eventInitDict') is not an object.");
return;
}
event_init_dict = NativeValueTraits<HashChangeEventInit>::NativeValue(info.GetIsolate(), info[1], exception_state);
if (exception_state.HadException())
return;
HashChangeEvent* impl = HashChangeEvent::Create(type, event_init_dict);
v8::Local<v8::Object> wrapper = info.Holder();
wrapper = impl->AssociateWithWrapper(info.GetIsolate(), V8HashChangeEvent::GetWrapperTypeInfo(), wrapper);
V8SetReturnValue(info, wrapper);
}
CORE_EXPORT void ConstructorCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HashChangeEvent_Constructor");
if (!info.IsConstructCall()) {
V8ThrowException::ThrowTypeError(
info.GetIsolate(),
ExceptionMessages::ConstructorNotCallableAsFunction("HashChangeEvent"));
return;
}
if (ConstructorMode::Current(info.GetIsolate()) == ConstructorMode::kWrapExistingObject) {
V8SetReturnValue(info, info.Holder());
return;
}
hash_change_event_v8_internal::Constructor(info);
}
} // namespace hash_change_event_v8_internal
void V8HashChangeEvent::OldURLAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HashChangeEvent_oldURL_Getter");
hash_change_event_v8_internal::OldURLAttributeGetter(info);
}
void V8HashChangeEvent::NewURLAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HashChangeEvent_newURL_Getter");
hash_change_event_v8_internal::NewURLAttributeGetter(info);
}
void V8HashChangeEvent::IsTrustedAttributeGetterCallback(const v8::FunctionCallbackInfo<v8::Value>& info) {
RUNTIME_CALL_TIMER_SCOPE_DISABLED_BY_DEFAULT(info.GetIsolate(), "Blink_HashChangeEvent_isTrusted_Getter");
hash_change_event_v8_internal::IsTrustedAttributeGetter(info);
}
static void InstallV8HashChangeEventTemplate(
v8::Isolate* isolate,
const DOMWrapperWorld& world,
v8::Local<v8::FunctionTemplate> interface_template) {
// Initialize the interface object's template.
V8DOMConfiguration::InitializeDOMInterfaceTemplate(isolate, interface_template, V8HashChangeEvent::GetWrapperTypeInfo()->interface_name, V8Event::DomTemplate(isolate, world), V8HashChangeEvent::kInternalFieldCount);
interface_template->SetCallHandler(hash_change_event_v8_internal::ConstructorCallback);
interface_template->SetLength(1);
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template);
ALLOW_UNUSED_LOCAL(signature);
v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instance_template);
v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototype_template);
// Register IDL constants, attributes and operations.
static constexpr V8DOMConfiguration::AccessorConfiguration
kAccessorConfigurations[] = {
{ "oldURL", V8HashChangeEvent::OldURLAttributeGetterCallback, nullptr, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds },
{ "newURL", V8HashChangeEvent::NewURLAttributeGetterCallback, nullptr, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::ReadOnly), V8DOMConfiguration::kOnPrototype, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds },
{ "isTrusted", V8HashChangeEvent::IsTrustedAttributeGetterCallback, nullptr, V8PrivateProperty::kNoCachedAccessor, static_cast<v8::PropertyAttribute>(v8::DontDelete | v8::ReadOnly), V8DOMConfiguration::kOnInstance, V8DOMConfiguration::kCheckHolder, V8DOMConfiguration::kHasSideEffect, V8DOMConfiguration::kAlwaysCallGetter, V8DOMConfiguration::kAllWorlds },
};
V8DOMConfiguration::InstallAccessors(
isolate, world, instance_template, prototype_template, interface_template,
signature, kAccessorConfigurations,
base::size(kAccessorConfigurations));
// Custom signature
V8HashChangeEvent::InstallRuntimeEnabledFeaturesOnTemplate(
isolate, world, interface_template);
}
void V8HashChangeEvent::InstallRuntimeEnabledFeaturesOnTemplate(
v8::Isolate* isolate,
const DOMWrapperWorld& world,
v8::Local<v8::FunctionTemplate> interface_template) {
v8::Local<v8::Signature> signature = v8::Signature::New(isolate, interface_template);
ALLOW_UNUSED_LOCAL(signature);
v8::Local<v8::ObjectTemplate> instance_template = interface_template->InstanceTemplate();
ALLOW_UNUSED_LOCAL(instance_template);
v8::Local<v8::ObjectTemplate> prototype_template = interface_template->PrototypeTemplate();
ALLOW_UNUSED_LOCAL(prototype_template);
// Register IDL constants, attributes and operations.
// Custom signature
}
v8::Local<v8::FunctionTemplate> V8HashChangeEvent::DomTemplate(
v8::Isolate* isolate, const DOMWrapperWorld& world) {
return V8DOMConfiguration::DomClassTemplate(
isolate, world, const_cast<WrapperTypeInfo*>(V8HashChangeEvent::GetWrapperTypeInfo()),
InstallV8HashChangeEventTemplate);
}
bool V8HashChangeEvent::HasInstance(v8::Local<v8::Value> v8_value, v8::Isolate* isolate) {
return V8PerIsolateData::From(isolate)->HasInstance(V8HashChangeEvent::GetWrapperTypeInfo(), v8_value);
}
v8::Local<v8::Object> V8HashChangeEvent::FindInstanceInPrototypeChain(
v8::Local<v8::Value> v8_value, v8::Isolate* isolate) {
return V8PerIsolateData::From(isolate)->FindInstanceInPrototypeChain(
V8HashChangeEvent::GetWrapperTypeInfo(), v8_value);
}
HashChangeEvent* V8HashChangeEvent::ToImplWithTypeCheck(
v8::Isolate* isolate, v8::Local<v8::Value> value) {
return HasInstance(value, isolate) ? ToImpl(v8::Local<v8::Object>::Cast(value)) : nullptr;
}
} // namespace blink
| [
"[email protected]"
] | |
4a2d898fa8920fb10e6c2a12f7b6295f7820cb63 | 48d5dbf4475448f5df6955f418d7c42468d2a165 | /SDK/SoT_BP_female_makeup_asian_02_Desc_parameters.hpp | a2fed182f7062c287f0e18e68d8fe04e8753f9b8 | [] | no_license | Outshynd/SoT-SDK-1 | 80140ba84fe9f2cdfd9a402b868099df4e8b8619 | 8c827fd86a5a51f3d4b8ee34d1608aef5ac4bcc4 | refs/heads/master | 2022-11-21T04:35:29.362290 | 2020-07-10T14:50:55 | 2020-07-10T14:50:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 385 | hpp | #pragma once
// Sea of Thieves (1.4.16) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "SoT_BP_female_makeup_asian_02_Desc_classes.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
ceea2d0ca8ebb5f1043e95d940890890c3d89782 | 7a3ba9759b81b486d3f701a635f73a697a6f44b8 | /sourceCompiler/cores/arduino/Briko/Temperature.h | 5f6c30982cec9977c6fe7681ac20be51c3220940 | [] | no_license | adrianloma/briko | 7cfd49273badf3268a16e87391d6f254393f3bd2 | 7b9df74d8505ad9c107e1ba2d8aae99ad29444ec | refs/heads/master | 2021-01-16T20:30:28.246371 | 2015-08-09T17:55:43 | 2015-08-09T17:55:43 | 40,435,688 | 0 | 0 | null | 2015-08-09T12:32:09 | 2015-08-09T12:32:08 | null | UTF-8 | C++ | false | false | 932 | h | /*
*
* Temperature.h
*
* Copyright 2014 IPSUM <[email protected]>
*
* This library is free software; you can redistribute it and/or
* 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.
*
* 14/08/14 Mexico.
*
*/
#ifndef Temperature //if not defined
#define Temperature //defines header name
#define TEMP_SAMPLES 5 //number of samples to average
#define C 0
#define F 1
#include "Arduino.h" //includes Arduino.h library
class temperaturebk
{
public:
temperaturebk(uint8_t pin); //initialize constructor
int read(); //read analog input function
int read(byte unit);
private:
uint8_t _pin; //declares a variable
};
#endif //end define
| [
"[email protected]"
] | |
801870eeeafc67f98e962ad242e64d2643f97612 | 2a88b58673d0314ed00e37ab7329ab0bbddd3bdc | /blazetest/src/mathtest/dmatdmatsub/UDaMDb.cpp | 6a5f9c835f238dbfb4b190d30f126c9425142a50 | [
"BSD-3-Clause"
] | permissive | shiver/blaze-lib | 3083de9600a66a586e73166e105585a954e324ea | 824925ed21faf82bb6edc48da89d3c84b8246cbf | refs/heads/master | 2020-09-05T23:00:34.583144 | 2016-08-24T03:55:17 | 2016-08-24T03:55:17 | 66,765,250 | 2 | 1 | NOASSERTION | 2020-04-06T05:02:41 | 2016-08-28T11:43:51 | C++ | UTF-8 | C++ | false | false | 4,007 | cpp | //=================================================================================================
/*!
// \file src/mathtest/dmatdmatsub/UDaMDb.cpp
// \brief Source file for the UDaMDb dense matrix/dense matrix subtraction math test
//
// Copyright (C) 2013 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice, this list
// of conditions and the following disclaimer in the documentation and/or other materials
// provided with the distribution.
// 3. Neither the names of the Blaze development group 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.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/UpperMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/dmatdmatsub/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'UDaMDb'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
typedef blaze::UpperMatrix< blaze::DynamicMatrix<TypeA> > UDa;
typedef blaze::DynamicMatrix<TypeB> MDb;
// Creator type definitions
typedef blazetest::Creator<UDa> CUDa;
typedef blazetest::Creator<MDb> CMDb;
// Running tests with small matrices
for( size_t i=0UL; i<=9UL; ++i ) {
RUN_DMATDMATSUB_OPERATION_TEST( CUDa( i ), CMDb( i, i ) );
}
// Running tests with large matrices
RUN_DMATDMATSUB_OPERATION_TEST( CUDa( 67UL ), CMDb( 67UL, 67UL ) );
RUN_DMATDMATSUB_OPERATION_TEST( CUDa( 128UL ), CMDb( 128UL, 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during dense matrix/dense matrix subtraction:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"[email protected]"
] | |
9804e71beeb76ad473191987527ba716cdf4df4c | ebd3360a127b9f0f38363dc0dad35a5d452140ac | /27.cpp | aa0c747a5a174888b0716293f94f9b6398f71f42 | [] | no_license | peachhhhh/CodingInterviews | e4c0f41ad956f0519e59d28de0064e381b9f5693 | 54e0bea986a30188b716c5a794222054b015b98f | refs/heads/master | 2020-09-12T06:54:39.782020 | 2020-01-16T08:33:50 | 2020-01-16T08:33:50 | 222,347,045 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 750 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void dfs(vector<string> &res, string s, int pos)
{
if (pos == s.size() - 1)
{
if (find(res.begin(), res.end(), s) == res.end())
{
res.push_back(s); //如果res中已有重复结果,则不push
}
return;
}
for (int i = pos; i < s.size(); i++)
{
swap(s[i], s[pos]);
dfs(res, s, pos + 1);
swap(s[i], s[pos]);
}
}
//字符串的排列(全排列,leetcode-46)
vector<string> Permutation(string str)
{
vector<string> res;
dfs(res, str, 0);
sort(res.begin(), res.end()); //转换成字典序
return res;
}
void test()
{
}
int main()
{
test();
return 0;
}
| [
"[email protected]"
] | |
09f26ee93a849945be0d9e043580fcfea3eccec0 | fe91ffa11707887e4cdddde8f386a8c8e724aa58 | /chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.cc | e8b0ad925e7c107dd5b05b7c311473f3a207be7e | [
"BSD-3-Clause"
] | permissive | akshaymarch7/chromium | 78baac2b45526031846ccbaeca96c639d1d60ace | d273c844a313b1e527dec0d59ce70c95fd2bd458 | refs/heads/master | 2023-02-26T23:48:03.686055 | 2020-04-15T01:20:07 | 2020-04-15T01:20:07 | 255,778,651 | 2 | 1 | BSD-3-Clause | 2020-04-15T02:04:56 | 2020-04-15T02:04:55 | null | UTF-8 | C++ | false | false | 6,703 | cc | // Copyright 2018 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 "chrome/browser/ui/webui/feed_internals/feed_internals_page_handler.h"
#include <string>
#include <utility>
#include "base/feature_list.h"
#include "base/metrics/statistics_recorder.h"
#include "base/time/time.h"
#include "chrome/browser/android/feed/feed_debugging_bridge.h"
#include "chrome/browser/android/feed/feed_lifecycle_bridge.h"
#include "chrome/browser/ui/webui/feed_internals/feed_internals.mojom.h"
#include "components/feed/content/feed_host_service.h"
#include "components/feed/content/feed_offline_host.h"
#include "components/feed/core/common/pref_names.h"
#include "components/feed/core/common/user_classifier.h"
#include "components/feed/core/feed_scheduler_host.h"
#include "components/feed/core/shared_prefs/pref_names.h"
#include "components/feed/feed_feature_list.h"
#include "components/offline_pages/core/prefetch/prefetch_prefs.h"
#include "components/offline_pages/core/prefetch/suggestions_provider.h"
#include "components/prefs/pref_service.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/receiver.h"
namespace {
const char kFeedHistogramPrefix[] = "ContentSuggestions.Feed.";
feed_internals::mojom::TimePtr ToMojoTime(base::Time time) {
return time.is_null() ? nullptr
: feed_internals::mojom::Time::New(time.ToJsTime());
}
std::string TriggerTypeToString(feed::TriggerType* trigger) {
if (trigger == nullptr)
return "Not set";
switch (*trigger) {
case feed::TriggerType::kNtpShown:
return "NTP Shown";
case feed::TriggerType::kForegrounded:
return "Foregrounded";
case feed::TriggerType::kFixedTimer:
return "Fixed Timer";
}
}
} // namespace
FeedInternalsPageHandler::FeedInternalsPageHandler(
mojo::PendingReceiver<feed_internals::mojom::PageHandler> receiver,
feed::FeedHostService* feed_host_service,
PrefService* pref_service)
: receiver_(this, std::move(receiver)),
feed_scheduler_host_(feed_host_service->GetSchedulerHost()),
feed_offline_host_(feed_host_service->GetOfflineHost()),
pref_service_(pref_service) {}
FeedInternalsPageHandler::~FeedInternalsPageHandler() = default;
void FeedInternalsPageHandler::GetGeneralProperties(
GetGeneralPropertiesCallback callback) {
auto properties = feed_internals::mojom::Properties::New();
properties->is_feed_enabled =
base::FeatureList::IsEnabled(feed::kInterestFeedContentSuggestions);
properties->is_feed_visible =
pref_service_->GetBoolean(feed::prefs::kArticlesListVisible);
properties->is_feed_allowed = IsFeedAllowed();
properties->is_prefetching_enabled =
offline_pages::prefetch_prefs::IsEnabled(pref_service_);
properties->feed_fetch_url = feed::GetFeedFetchUrlForDebugging();
std::move(callback).Run(std::move(properties));
}
void FeedInternalsPageHandler::GetUserClassifierProperties(
GetUserClassifierPropertiesCallback callback) {
auto properties = feed_internals::mojom::UserClassifier::New();
feed::UserClassifier* user_classifier =
feed_scheduler_host_->GetUserClassifierForDebugging();
properties->user_class_description =
user_classifier->GetUserClassDescriptionForDebugging();
properties->avg_hours_between_views = user_classifier->GetEstimatedAvgTime(
feed::UserClassifier::Event::kSuggestionsViewed);
properties->avg_hours_between_uses = user_classifier->GetEstimatedAvgTime(
feed::UserClassifier::Event::kSuggestionsUsed);
std::move(callback).Run(std::move(properties));
}
void FeedInternalsPageHandler::GetLastFetchProperties(
GetLastFetchPropertiesCallback callback) {
auto properties = feed_internals::mojom::LastFetchProperties::New();
properties->last_fetch_status =
feed_scheduler_host_->GetLastFetchStatusForDebugging();
properties->last_fetch_trigger = TriggerTypeToString(
feed_scheduler_host_->GetLastFetchTriggerTypeForDebugging());
properties->last_fetch_time =
ToMojoTime(pref_service_->GetTime(feed::prefs::kLastFetchAttemptTime));
properties->refresh_suppress_time =
ToMojoTime(feed_scheduler_host_->GetSuppressRefreshesUntilForDebugging());
properties->last_bless_nonce =
pref_service_->GetString(feed::prefs::kHostOverrideBlessNonce);
std::move(callback).Run(std::move(properties));
}
void FeedInternalsPageHandler::ClearUserClassifierProperties() {
feed_scheduler_host_->GetUserClassifierForDebugging()
->ClearClassificationForDebugging();
}
void FeedInternalsPageHandler::ClearCachedDataAndRefreshFeed() {
feed::FeedLifecycleBridge::ClearCachedData();
}
void FeedInternalsPageHandler::RefreshFeed() {
feed::TriggerRefreshForDebugging();
}
void FeedInternalsPageHandler::GetCurrentContent(
GetCurrentContentCallback callback) {
if (!IsFeedAllowed()) {
std::move(callback).Run(
std::vector<feed_internals::mojom::SuggestionPtr>());
return;
}
feed_offline_host_->GetCurrentArticleSuggestions(base::BindOnce(
&FeedInternalsPageHandler::OnGetCurrentArticleSuggestionsDone,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void FeedInternalsPageHandler::OnGetCurrentArticleSuggestionsDone(
GetCurrentContentCallback callback,
std::vector<offline_pages::PrefetchSuggestion> results) {
std::vector<feed_internals::mojom::SuggestionPtr> suggestions;
for (offline_pages::PrefetchSuggestion result : results) {
auto suggestion = feed_internals::mojom::Suggestion::New();
suggestion->title = std::move(result.article_title);
suggestion->url = std::move(result.article_url);
suggestion->publisher_name = std::move(result.article_attribution);
suggestion->image_url = std::move(result.thumbnail_url);
suggestion->favicon_url = std::move(result.favicon_url);
suggestions.push_back(std::move(suggestion));
}
std::move(callback).Run(std::move(suggestions));
}
void FeedInternalsPageHandler::GetFeedProcessScopeDump(
GetFeedProcessScopeDumpCallback callback) {
std::move(callback).Run(feed::GetFeedProcessScopeDumpForDebugging());
}
bool FeedInternalsPageHandler::IsFeedAllowed() {
return pref_service_->GetBoolean(feed::prefs::kEnableSnippets);
}
void FeedInternalsPageHandler::GetFeedHistograms(
GetFeedHistogramsCallback callback) {
std::string log;
base::StatisticsRecorder::WriteGraph(kFeedHistogramPrefix, &log);
std::move(callback).Run(log);
}
void FeedInternalsPageHandler::OverrideFeedHost(const std::string& host) {
return pref_service_->SetString(feed::prefs::kHostOverrideHost, host);
}
| [
"[email protected]"
] | |
2025f61152e3a8c0021cd985ef0b715f2f4c1fc3 | bd0bf2438dbe8a16cb79a045ed73f28361af0504 | /GAME_SECOND/bulletPhysics/src/BulletCollision/CollisionShapes/btCollisionShape.cpp | b33bc445700ef5e4c6db72483b348e61abc09924 | [
"Zlib"
] | permissive | RyujiNanjyou/rnGame | bc3d2429457803e3b0cbeba0e4e7bc43b28977df | fb22a4a4cdee14956a73e0d0d1b2e51b1bdb9637 | refs/heads/master | 2021-01-22T03:23:35.219980 | 2017-07-13T02:45:07 | 2017-07-13T02:45:07 | 92,374,788 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,290 | cpp | /*
Bullet Continuous Collision Detection and Physics Library
Copyright (c) 2003-2009 Erwin Coumans http://bulletphysics.org
This software is provided 'as-is', without any express or implied warranty.
In no event will the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it freely,
subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "BulletCollision/CollisionShapes/btCollisionShape.h"
#include "LinearMath/btSerializer.h"
/*
Make sure this dummy function never changes so that it
can be used by probes that are checking whether the
library is actually installed.
*/
extern "C"
{
void btBulletCollisionProbe ();
void btBulletCollisionProbe () {}
}
void btCollisionShape::getBoundingSphere(btVector3& center,btScalar& radius) const
{
btTransform tr;
tr.setIdentity();
btVector3 aabbMin,aabbMax;
getAabb(tr,aabbMin,aabbMax);
radius = (aabbMax-aabbMin).length()*btScalar(0.5);
center = (aabbMin+aabbMax)*btScalar(0.5);
}
btScalar btCollisionShape::getContactBreakingThreshold(btScalar defaultContactThreshold) const
{
return getAngularMotionDisc() * defaultContactThreshold;
}
btScalar btCollisionShape::getAngularMotionDisc() const
{
///@todo cache this value, to improve performance
btVector3 center;
btScalar disc;
getBoundingSphere(center,disc);
disc += (center).length();
return disc;
}
void btCollisionShape::calculateTemporalAabb(const btTransform& curTrans,const btVector3& linvel,const btVector3& angvel,btScalar timeStep, btVector3& temporalAabbMin,btVector3& temporalAabbMax) const
{
//start with static aabb
getAabb(curTrans,temporalAabbMin,temporalAabbMax);
btScalar temporalAabbMaxx = temporalAabbMax.getX();
btScalar temporalAabbMaxy = temporalAabbMax.getY();
btScalar temporalAabbMaxz = temporalAabbMax.getZ();
btScalar temporalAabbMinx = temporalAabbMin.getX();
btScalar temporalAabbMiny = temporalAabbMin.getY();
btScalar temporalAabbMinz = temporalAabbMin.getZ();
// add linear motion
btVector3 linMotion = linvel*timeStep;
///@todo: simd would have a vector max/min operation, instead of per-element access
if (linMotion.x() > btScalar(0.))
temporalAabbMaxx += linMotion.x();
else
temporalAabbMinx += linMotion.x();
if (linMotion.y() > btScalar(0.))
temporalAabbMaxy += linMotion.y();
else
temporalAabbMiny += linMotion.y();
if (linMotion.z() > btScalar(0.))
temporalAabbMaxz += linMotion.z();
else
temporalAabbMinz += linMotion.z();
//add conservative angular motion
btScalar angularMotion = angvel.length() * getAngularMotionDisc() * timeStep;
btVector3 angularMotion3d(angularMotion,angularMotion,angularMotion);
temporalAabbMin = btVector3(temporalAabbMinx,temporalAabbMiny,temporalAabbMinz);
temporalAabbMax = btVector3(temporalAabbMaxx,temporalAabbMaxy,temporalAabbMaxz);
temporalAabbMin -= angularMotion3d;
temporalAabbMax += angularMotion3d;
}
///fills the dataBuffer and returns the struct name (and 0 on failure)
const char* btCollisionShape::serialize(void* dataBuffer, btSerializer* serializer) const
{
btCollisionShapeData* shapeData = (btCollisionShapeData*) dataBuffer;
char* name = (char*) serializer->findNameForPointer(this);
shapeData->m_name = (char*)serializer->getorimaquePointer(name);
if (shapeData->m_name)
{
serializer->serializeName(name);
}
shapeData->m_shapeType = m_shapeType;
//shapeData->m_padding//??
return "btCollisionShapeData";
}
void btCollisionShape::serializeSingleShape(btSerializer* serializer) const
{
int len = calculateSerializeBufferSize();
btChunk* chunk = serializer->allocate(len,1);
const char* structType = serialize(chunk->m_oldPtr, serializer);
serializer->finalizeChunk(chunk,structType,BT_SHAPE_CODE,(void*)this);
} | [
"[email protected]"
] | |
60c209c20172cafec6359051133a097118e8065a | 83b0c001f3655386f2545a3418a545e1d479ff01 | /Guadalajara/InterfaceDefinitions.cpp | f613601d3f5af16b822c7773ba4ab04a63c886e0 | [] | no_license | liamdebellada/Guadalajara | 60766ae3dc225547b1164b9df176261af029c40a | 9e3953bc9fbc28b0066b68188283f9aa4345ff87 | refs/heads/main | 2023-03-21T18:08:51.221129 | 2021-03-10T20:07:05 | 2021-03-10T20:07:05 | 343,461,899 | 1 | 1 | null | 2021-03-04T20:57:07 | 2021-03-01T15:21:40 | null | UTF-8 | C++ | false | false | 923 | cpp | #include "InterfaceDefinitions.h"
#include <Windows.h>
#include <iostream>
InterfaceCollection* Interfaces = nullptr;
typedef void* (*tCreateInterface)(const char* name, int* returnCode);
void* GetInterface(const char* dllName, const char* interfaceName) {
tCreateInterface CreateInterface = (tCreateInterface)GetProcAddress(GetModuleHandle(dllName), "CreateInterface");
int returnCode = 0;
void* Interface = CreateInterface(interfaceName, &returnCode);
return Interface;
}
InterfaceCollection::InterfaceCollection() {
ClientEntityList = (IClientEntityList*)GetInterface("client.dll", "VClientEntityList003");
EngineClient = (IEngineClient*)GetInterface("engine.dll", "VEngineClient014");
InputSystem = (IInputSystem*)GetInterface("inputsystem.dll", "InputSystemVersion001");
Client = (IBaseClientDLL*)GetInterface("client.dll", "VClient018");
ClientMode = **(IClientMode***)((*(DWORD**)Client)[10] + 0x5);
} | [
"[email protected]"
] | |
0179c53350dbe74a138d7c90636b6e417a8cd07f | b8fdb724f7978683678ae6175d091040c2ebc808 | /source/pipeline/Message.h | 38b1a0d1bcf1927917411fb72fe7f189b9f911b3 | [] | no_license | wrawdanik/ApiPack2 | 581fe8413cae2468802daa3a8cb374fbf0184061 | b47610fe2c59d5892dffc3a21e3db11ad1fedea4 | refs/heads/master | 2016-09-13T23:16:48.716971 | 2016-06-01T04:24:28 | 2016-06-01T04:24:28 | 58,285,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 918 | h | //
// Created by warmi on 5/6/16.
//
#ifndef APIPACK2_PUBLICMESSAGE_H
#define APIPACK2_PUBLICMESSAGE_H
#include <cstddef>
namespace ApiPack2
{
enum class PublicMsgType : size_t
{
Update,
OpenRequest,
CloseRequest,
Terminate
};
union PublicMsgFlags
{
struct
{
size_t destroy: 1;
size_t type: 4;
size_t id: 32;
};
uint32_t value;
};
class PublicMsg
{
public:
PublicMsgFlags flags;
void *ptrData;
bool shouldDestroy() const
{
return (flags.destroy==1);
}
PublicMsgType type() const
{
return (PublicMsgType)flags.type;
}
size_t id() const
{
return flags.id;
}
};
}
#endif //APIPACK2_PUBLICMESSAGE_H
| [
"[email protected]"
] | |
418d7c8d614fc9b3cd7961703b6ae5df49be4758 | 40ae6fed66d7ff493b7d26c5756a510700b1e23b | /backend/tests_ssa/arithmetic.cc | 5061d08ce723c7a20ef728daa3511d04165eacdc | [] | no_license | lia-approves/copyofchantcompiler | b82af2fc934baab4b3b8be5a8c943065b55835a8 | 6cccafa0b52876dd1684c0e3e4626906f4f37b9f | refs/heads/master | 2022-03-11T02:19:17.705809 | 2018-10-03T21:57:35 | 2018-10-03T21:57:35 | 151,474,664 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,587 | cc | // Copyright msg for cpplint
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "abstract_syntax/abstract_syntax.h"
#include "backend/ir_v5.h"
#include "gtest/gtest.h"
#include "utility/memory.h"
#include "backend/asm_generator_v5.h"
#include "backend/lowerer_v5.h"
#include "backend/SSA.h"
using cs160::abstract_syntax::version_5::AddExpr;
using cs160::abstract_syntax::version_5::SubtractExpr;
using cs160::abstract_syntax::version_5::MultiplyExpr;
using cs160::abstract_syntax::version_5::DivideExpr;
using cs160::abstract_syntax::version_5::IntegerExpr;
using cs160::abstract_syntax::version_5::VariableExpr;
using cs160::abstract_syntax::version_5::LessThanExpr;
using cs160::abstract_syntax::version_5::Statement;
using cs160::abstract_syntax::version_5::AssignmentFromArithExp;
using cs160::abstract_syntax::version_5::Conditional;
using cs160::abstract_syntax::version_5::FunctionDef;
using cs160::abstract_syntax::version_5::Program;
using cs160::backend::AsmProgram;
using cs160::backend::IrGenVisitor;
using cs160::backend::AsmProgram;
using cs160::backend::SSA;
using cs160::make_unique;
TEST(AE, CanAdd) {
FunctionDef::Block function_defs;
Statement::Block statements;
// 12 + 30
auto ae = make_unique<const AddExpr>(
make_unique<const IntegerExpr>(12),
make_unique<const IntegerExpr>(30));
auto ast = make_unique<const Program>(std::move(function_defs),
std::move(statements), std::move(ae));
IrGenVisitor irGen;
ast->Visit(&irGen);
SSA ssatest = SSA(irGen.GetIR());
ssatest.ComputeCFG();
ssatest.GenerateDomination();
ssatest.DetermineVariableLiveness();
ssatest.InsertSSAFunctions();
ssatest.RenameAllVariables();
ssatest.PrintCFG();
ssatest.PrintDominators();
AsmProgram testasm;
testasm.SSAIRToAsm(ssatest.GetSSAIR());
// save & run assembly with gcc
std::ofstream test_output_file;
test_output_file.open("testfile.s");
test_output_file << testasm.GetASMString();
test_output_file.close();
system("gcc testfile.s && ./a.out > test_output.txt");
// get output of running assembly to compare it to the expected output
std::ifstream output_file;
output_file.open("test_output.txt");
std::string output;
output_file >> output;
output_file.close();
system("rm testfile.s test_output.txt");
// 12 + 30 = 42
// output should be 42
EXPECT_EQ("42", output);
}
TEST(AE, CanSubtract) {
FunctionDef::Block function_defs;
Statement::Block statements;
// 52 - 10
auto ae = make_unique<const SubtractExpr>(
make_unique<const IntegerExpr>(52),
make_unique<const IntegerExpr>(10));
auto ast = make_unique<const Program>(std::move(function_defs),
std::move(statements), std::move(ae));
IrGenVisitor irGen;
ast->Visit(&irGen);
SSA ssatest = SSA(irGen.GetIR());
ssatest.ComputeCFG();
ssatest.GenerateDomination();
ssatest.DetermineVariableLiveness();
ssatest.InsertSSAFunctions();
ssatest.RenameAllVariables();
ssatest.PrintCFG();
ssatest.PrintDominators();
AsmProgram testasm;
testasm.SSAIRToAsm(ssatest.GetSSAIR());
// save & run assembly with gcc
std::ofstream test_output_file;
test_output_file.open("testfile.s");
test_output_file << testasm.GetASMString();
test_output_file.close();
system("gcc testfile.s && ./a.out > test_output.txt");
// get output of running assembly to compare it to the expected output
std::ifstream output_file;
output_file.open("test_output.txt");
std::string output;
output_file >> output;
output_file.close();
system("rm testfile.s test_output.txt");
EXPECT_EQ("42", output);
}
TEST(AE, CanMultiply) {
FunctionDef::Block function_defs;
Statement::Block statements;
auto ae = make_unique<const MultiplyExpr>(
make_unique<const IntegerExpr>(7),
make_unique<const IntegerExpr>(6));
auto ast = make_unique<const Program>(std::move(function_defs),
std::move(statements), std::move(ae));
// generate intermediate representation
IrGenVisitor irGen;
ast->Visit(&irGen);
SSA ssatest = SSA(irGen.GetIR());
ssatest.ComputeCFG();
ssatest.GenerateDomination();
ssatest.DetermineVariableLiveness();
ssatest.InsertSSAFunctions();
ssatest.RenameAllVariables();
ssatest.PrintCFG();
ssatest.PrintDominators();
AsmProgram testasm;
testasm.SSAIRToAsm(ssatest.GetSSAIR());
// save & run assembly with gcc
std::ofstream test_output_file;
test_output_file.open("testfile.s");
test_output_file << testasm.GetASMString();
test_output_file.close();
system("gcc testfile.s && ./a.out > test_output.txt");
// get output of running assembly to compare it to the expected output
std::ifstream output_file;
output_file.open("test_output.txt");
std::string output;
output_file >> output;
output_file.close();
system("rm testfile.s test_output.txt");
EXPECT_EQ("42", output);
}
TEST(AE, CanDivide) {
FunctionDef::Block function_defs;
Statement::Block statements;
auto ae = make_unique<const DivideExpr>(
make_unique<const IntegerExpr>(84),
make_unique<const IntegerExpr>(2));
auto ast = make_unique<const Program>(std::move(function_defs),
std::move(statements), std::move(ae));
// generate intermediate representation
IrGenVisitor irGen;
ast->Visit(&irGen);
SSA ssatest = SSA(irGen.GetIR());
ssatest.ComputeCFG();
ssatest.GenerateDomination();
ssatest.DetermineVariableLiveness();
ssatest.InsertSSAFunctions();
ssatest.RenameAllVariables();
ssatest.PrintCFG();
ssatest.PrintDominators();
AsmProgram testasm;
testasm.SSAIRToAsm(ssatest.GetSSAIR());
// save & run assembly with gcc
std::ofstream test_output_file;
test_output_file.open("testfile.s");
test_output_file << testasm.GetASMString();
test_output_file.close();
system("gcc testfile.s && ./a.out > test_output.txt");
// get output of running assembly to compare it to the expected output
std::ifstream output_file;
output_file.open("test_output.txt");
std::string output;
output_file >> output;
output_file.close();
system("rm testfile.s test_output.txt");
EXPECT_EQ("42", output);
}
TEST(AE, CanConditionalTrue) {
FunctionDef::Block function_defs;
Statement::Block statements;
auto ae = make_unique<const AddExpr>(
make_unique<VariableExpr>("a"),
make_unique<const IntegerExpr>(0));
Statement::Block trueStatements;
Statement::Block falseStatements;
trueStatements.push_back(std::move(make_unique<const AssignmentFromArithExp>(
make_unique<const VariableExpr>("a"),
make_unique<const IntegerExpr>(3))));
falseStatements.push_back(std::move(make_unique<const AssignmentFromArithExp>(
make_unique<const VariableExpr>("a"),
make_unique<const IntegerExpr>(4))));
statements.push_back(std::move(make_unique<const Conditional>(
make_unique<const GreaterThanExpr>(
make_unique<const IntegerExpr>(20),
make_unique<const IntegerExpr>(0)),
std::move(trueStatements), std::move(falseStatements))));
auto ast = make_unique<const Program>(std::move(function_defs),
std::move(statements), std::move(ae));
IrGenVisitor irGen;
ast->Visit(&irGen);
SSA ssatest = SSA(irGen.GetIR());
ssatest.ComputeCFG();
ssatest.GenerateDomination();
ssatest.DetermineVariableLiveness();
ssatest.InsertSSAFunctions();
ssatest.RenameAllVariables();
ssatest.PrintCFG();
ssatest.PrintDominators();
AsmProgram testasm;
testasm.SSAIRToAsm(ssatest.GetSSAIR());
// save & run assembly with gcc
std::ofstream test_output_file;
test_output_file.open("testfile.s");
test_output_file << testasm.GetASMString();
test_output_file.close();
system("gcc testfile.s && ./a.out > test_output.txt");
// get output of running assembly to compare it to the expected output
std::ifstream output_file;
output_file.open("test_output.txt");
std::string output;
output_file >> output;
output_file.close();
system("rm testfile.s test_output.txt");
EXPECT_EQ("3", output);
}
TEST(AE, CanConditionalFalse) {
FunctionDef::Block function_defs;
Statement::Block statements;
auto ae = make_unique<const AddExpr>(
make_unique<VariableExpr>("a"),
make_unique<const IntegerExpr>(0));
Statement::Block trueStatements;
Statement::Block falseStatements;
trueStatements.push_back(std::move(make_unique<const AssignmentFromArithExp>(
make_unique<const VariableExpr>("a"),
make_unique<const IntegerExpr>(3))));
falseStatements.push_back(std::move(make_unique<const AssignmentFromArithExp>(
make_unique<const VariableExpr>("a"),
make_unique<const IntegerExpr>(4))));
statements.push_back(std::move(make_unique<const Conditional>(
make_unique<const LessThanExpr>(
make_unique<const IntegerExpr>(20),
make_unique<const IntegerExpr>(0)),
std::move(trueStatements), std::move(falseStatements))));
auto ast = make_unique<const Program>(std::move(function_defs),
std::move(statements), std::move(ae));
IrGenVisitor irGen;
ast->Visit(&irGen);
SSA ssatest = SSA(irGen.GetIR());
ssatest.ComputeCFG();
ssatest.GenerateDomination();
ssatest.DetermineVariableLiveness();
ssatest.InsertSSAFunctions();
ssatest.RenameAllVariables();
ssatest.PrintCFG();
ssatest.PrintDominators();
AsmProgram testasm;
testasm.SSAIRToAsm(ssatest.GetSSAIR());
// save & run assembly with gcc
std::ofstream test_output_file;
test_output_file.open("testfile.s");
test_output_file << testasm.GetASMString();
test_output_file.close();
system("gcc testfile.s && ./a.out > test_output.txt");
// get output of running assembly to compare it to the expected output
std::ifstream output_file;
output_file.open("test_output.txt");
std::string output;
output_file >> output;
output_file.close();
system("rm testfile.s test_output.txt");
EXPECT_EQ("4", output);
}
TEST(AE, DominatesItself) {
FunctionDef::Block function_defs;
Statement::Block statements;
// ((-4 / 2) - 101) + (15 * 7) =
auto ae = make_unique<const AddExpr>(
make_unique<const SubtractExpr>(
make_unique<const DivideExpr>(make_unique<const IntegerExpr>(-4),
make_unique<const IntegerExpr>(2)),
make_unique<const IntegerExpr>(101)),
make_unique<const MultiplyExpr>(make_unique<const IntegerExpr>(15),
make_unique<const IntegerExpr>(7)));
auto ast = make_unique<const Program>(std::move(function_defs),
std::move(statements), std::move(ae));
// generate intermediate representation
IrGenVisitor irGen;
ast->Visit(&irGen);
SSA ssatest = SSA(irGen.GetIR());
ssatest.ComputeCFG();
ssatest.GenerateDomination();
ssatest.DetermineVariableLiveness();
ssatest.InsertSSAFunctions();
ssatest.RenameAllVariables();
ssatest.PrintCFG();
ssatest.PrintDominators();
AsmProgram testasm;
testasm.SSAIRToAsm(ssatest.GetSSAIR());
// see that the one basic block dominates itself
int dominates = ((ssatest.GetDominators()[0]).GetDominated())[0][0];
// save & run assembly with gcc
std::ofstream test_output_file;
test_output_file.open("testfile.s");
test_output_file << testasm.GetASMString();
test_output_file.close();
system("gcc testfile.s && ./a.out > test_output.txt");
// get output of running assembly to compare it to the expected output
std::ifstream output_file;
output_file.open("test_output.txt");
std::string output;
output_file >> output;
output_file.close();
system("rm testfile.s test_output.txt");
EXPECT_EQ("2", output);
EXPECT_EQ(0, dominates);
}
| [
"[email protected]"
] | |
dca84e876ed2b2a6644df436829880e7eb57db1a | d77d9e9847318056ce9f266b60b63870a06ba980 | /inet_address.cpp | 742827c46654fb0f7e5c77bc23cb6e843d005ca9 | [] | no_license | joeccmou/INET_Practice | 9e5fd789042b2afef0f55bb1fbccb5f875b3f8a9 | 6a3cc49eeb47aa592abdf6598d86f3d586056bac | refs/heads/master | 2022-10-09T05:06:50.092648 | 2020-06-08T13:44:47 | 2020-06-08T13:44:47 | 270,647,185 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 561 | cpp | #include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main()
{
char ip[] = "192.168.0.165";
struct in_addr myaddr;
/* inet_aton */
int iRet = inet_aton(ip, &myaddr);
printf("%x\n", myaddr.s_addr);
/* inet_addr */
printf("%x\n", inet_addr(ip));
/* inet_pton */
iRet = inet_pton(AF_INET, ip, &myaddr);
printf("%x\n", myaddr.s_addr);
myaddr.s_addr = 0xac100ac4;
/* inet_ntoa */
printf("%s\n", inet_ntoa(myaddr));
/* inet_ntop */
inet_ntop(AF_INET, &myaddr, ip, 16);
puts(ip);
return 0;
}
| [
"[email protected]"
] | |
058672dae799e8c2726d24c18821f7bc822aacee | 1580f024f6717a96b5d70edc52aa94f4953b4fcb | /acqu_core/AcquDAQ/src/TVME_VUPROM_Pattern.cc | 15666e7c3cd7ac5d363bc238cc0bc23aaf717531 | [] | no_license | A2-Collaboration/acqu | 7531a981cfe98603a14dfef4304312177f2a4072 | b7571696ec72e2b08d64d7640f9ed5a39eddb9f6 | refs/heads/master | 2023-05-01T07:30:06.743357 | 2019-04-03T16:18:35 | 2019-04-03T16:18:35 | 9,445,853 | 1 | 15 | null | 2022-09-09T08:44:08 | 2013-04-15T10:05:39 | C++ | UTF-8 | C++ | false | false | 4,585 | cc | //--Author A Neiser XXth Nov 2013 Adapt from TVME_VUPROM
//--Rev ...
//--Update JRM Annand 30th Jan 2014 Fix register setup
//
//--Description
// *** AcquDAQ++ <-> Root ***
// DAQ for Sub-Atomic Physics Experiments.
//
// TVME_VUPROM_Pattern
// Hit pattern reading module, configurable via dat file
#include "TVME_VUPROM_Pattern.h"
#include "TDAQexperiment.h"
#include <sstream>
#include <iostream>
#include <string>
enum { EVUPP_ModuleChain=600, EVUPP_Pattern };
using namespace std;
static Map_t kVUPROMPatternKeys[] = {
{"Pattern:", EVUPP_Pattern},
{NULL, -1}
};
//-----------------------------------------------------------------------------
TVME_VUPROM_Pattern::TVME_VUPROM_Pattern( Char_t* name, Char_t* file, FILE* log,
Char_t* line ):
TVMEmodule( name, file, log, line )
{
// Basic initialisation
AddCmdList( kVUPROMPatternKeys ); // VUPROM-specific setup commands
// number of Patterns and registers
// are finally set in SetConfig/PostInit
// since the number of Patterns can be configured
fNreg = 0;
fNChannel = 0;
fPatternOffset = 0;
}
//-----------------------------------------------------------------------------
void TVME_VUPROM_Pattern::SetConfig( Char_t* line, Int_t key)
{
stringstream ss(line);
// Configuration from file
switch(key) {
case EVUPP_Pattern: {
// ugly workaround for some global non-Pattern registers
if(fNreg==0) {
// we add global registers here (not in the constructor)
// this ensures that fNreg is still zero when BaseSetup: is evaluated
// (needed to properly initialize the register pointers later in PostInit)
// the first register entry is the firmware
VMEreg_t firmware = {0x2f00, 0x0, 'l', 0};
fVUPROMregs.push_back(firmware);
fNreg = fVUPROMregs.size();
fPatternOffset = fNreg; // offset where the Pattern blocks start
}
UInt_t offsetAddr; // usually submodule address
ss << hex; // enable hex mode for addresses
if(!(ss >> offsetAddr)) {
PrintError(line,"<VUPROM_Pattern offset address>",EErrFatal);
}
ss << dec; // the number is decimal again
// create the corresponding registers
VMEreg_t Patterns = {offsetAddr, 0x0, 'l', 0};
// remember the Pattern block offset
// before we add them. Note that the size of fVUPROMregs is not
// the correct offset due to the repeat attribute,
fPatternOffsets.push_back(fPatternOffset);
fVUPROMregs.push_back(Patterns);
// add it to the total number
fNChannel += 2;
// Pattern register offset,
fPatternOffset += 1;
break;
}
default:
// default try commands of TVMEmodule
TVMEmodule::SetConfig(line, key);
break;
}
}
//-------------------------------------------------------------------------
void TVME_VUPROM_Pattern::PostInit( )
{
// Check if any general register initialisation has been performed
// If not do the default here
if( fIsInit ) return;
// before we call InitReg,
// add an "end-marker" at the very end
// (well this happens if one uses C-style pointer hell...)
VMEreg_t end = {0xffffffff, 0x0, 'l', 0};
fVUPROMregs.push_back(end);
// this also sets fNReg to the correct value finally!
fNreg = 0;
InitReg( fVUPROMregs.data() );
// init the base class
TVMEmodule::PostInit();
}
//-------------------------------------------------------------------------
Bool_t TVME_VUPROM_Pattern::CheckHardID( )
{
// Read firmware version from register
// Fatal error if it does not match the hardware ID
Int_t id = Read((UInt_t)0); // first one is firmware, see SetConfig()
fprintf(fLogStream,"VUPROM Pattern firmware version Read: %x Expected: %x\n",
id,fHardID);
if( id == fHardID ) return kTRUE;
else
PrintError("","<VUPROM Pattern firmware ID error>",EErrFatal);
return kFALSE;
}
//-----------------------------------------------------------------------------
void TVME_VUPROM_Pattern::ReadIRQ( void** outBuffer )
{
// iterate over the patterns, remember
size_t n = fBaseIndex; // we start at the base index
for(size_t patt=0;patt<fPatternOffsets.size();patt++) {
size_t offset = fPatternOffsets[patt];
UInt_t datum = Read(offset);
UInt_t datum_low = datum & 0xffff;
UInt_t datum_high = datum >> 16;
// use n to get all blocks consecutive
ADCStore(outBuffer, datum_low, n);
n++;
ADCStore(outBuffer, datum_high, n);
n++; // for next iteration, increment!
}
}
ClassImp(TVME_VUPROM_Pattern)
| [
"[email protected]"
] | |
9dd128d2c65f3273f117b47e930832a7d763aead | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir521/dir522/dir572/dir2774/dir2942/file2973.cpp | 65bcae0a0079ba400ea60c648785539f114a625b | [] | no_license | tgeng/HugeProject | 829c3bdfb7cbaf57727c41263212d4a67e3eb93d | 4488d3b765e8827636ce5e878baacdf388710ef2 | refs/heads/master | 2022-08-21T16:58:54.161627 | 2020-05-28T01:54:03 | 2020-05-28T01:54:03 | 267,468,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 111 | cpp | #ifndef file2973
#error "macro file2973 must be defined"
#endif
static const char* file2973String = "file2973"; | [
"[email protected]"
] | |
1a5a58218e86b706f263da87b82a2452528bea1c | 460246fa4f9410bed0906f999b11a3b4c15b7077 | /solitaire/spells.h | b3e14541092e90b098cfd5192bb8693480f5bf2f | [] | no_license | lilrooness/summonerstable | 1ff0be4d80232b57114150575c8a00eb03d1469f | df22ea91ad2a72defd6c7add9293c1da52329ef3 | refs/heads/master | 2022-09-21T08:27:46.501858 | 2020-05-29T10:43:29 | 2020-05-29T10:43:29 | 262,747,710 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,638 | h | #pragma once
#include <map>
#include <algorithm>
#include "game_structs.h"
#include "animation.h"
#include "sprite.h"
void showSpellPopup(Game* game, Spell& spell);
void createNewSpellPopup(Game* game, float x, float y, Spell& spell);
void hideSpellPopup(Game* game, const Spell& spell);
void castSpell(Game* game, Spell& spell);
void tickSpells(Game* game) {
resolveScaleAnimations<Spell>(game->spellSpriteClass, game->spells, game->gameTime);
resolveScaleAnimations<SpellPopup>(game->spellPopupSpriteClass, game->spellPopups, game->gameTime);
for (int i = 0; i < game->spells.size(); i++) {
float spellX = game->spellSpriteClass.Buffer_vertexOffsetData[game->spells[i].sprite.BufferIndex_vertexOffsetData];
float spellY = game->spellSpriteClass.Buffer_vertexOffsetData[game->spells[i].sprite.BufferIndex_vertexOffsetData + 1];
float spellSize = DEFUALT_MODEL_SCALE * 0.5;
if (game->mouseX > spellX && game->mouseX < spellX + spellSize
&& game->mouseY > spellY && game->mouseY < spellY + spellSize) {
if (!game->spells[i].mouseHovering) {
game->spells[i].mouseHovering = true;
game->spells[i].sprite.scaleAnimationReference = queueScaleAnimation(game->spellSpriteClass, i, 0.5, 0.6, 5, game->gameTime);
showSpellPopup(game, game->spells[i]);
}
if (game->spells[i].mouseHovering && game->lmbDown) {
castSpell(game, game->spells[i]);
}
}
else {
if (game->spells[i].mouseHovering) {
game->spells[i].mouseHovering = false;
cancelScaleAnimation(game->spellSpriteClass, game->spells[i].sprite.scaleAnimationReference, game->spells[i].sprite);
int spellPopupIndex = game->spells[i].spellPopupReference.index;
cancelScaleAnimation(game->spellPopupSpriteClass, game->spellPopups[spellPopupIndex].sprite.scaleAnimationReference, game->spellPopups[spellPopupIndex].sprite);
hideSpellPopup(game, game->spells[i]);
}
}
}
}
void hideSpellPopup(Game* game, const Spell& spell) {
if (spell.spellPopupReference.index < game->spellPopups.size() && spell.spellPopupReference.generation == game->spellPopups[spell.spellPopupReference.index].generation) {
game->spellPopupSpriteClass.BufferRefreshFlag_vertexOffsetData = true;
Sprite* sprite = &game->spellPopups[spell.spellPopupReference.index].sprite;
game->spellPopupSpriteClass.Buffer_vertexOffsetData[sprite->BufferIndex_vertexOffsetData] -= 2000.0f;
}
}
void showSpellPopup(Game* game, Spell& spell) {
float spellX = game->spellSpriteClass.Buffer_vertexOffsetData[spell.sprite.BufferIndex_vertexOffsetData];
float spellY = game->spellSpriteClass.Buffer_vertexOffsetData[spell.sprite.BufferIndex_vertexOffsetData + 1];
game->spellPopupSpriteClass.BufferRefreshFlag_scaleValueData = true;
game->spellPopupSpriteClass.BufferRefreshFlag_tintValueData = true;
game->spellPopupSpriteClass.BufferRefreshFlag_vertexOffsetData = true;
game->spellPopupSpriteClass.BufferRefreshFlag_textureOffsetData = true;
for (int i = 0; i < game->spellPopups.size(); i++) {
if (!game->spellPopups[i].showing) {
game->spellPopups[i].showing = true;
int vertexOffsetBufferIndex = game->spellPopups[i].sprite.BufferIndex_vertexOffsetData;
game->spellPopupSpriteClass.Buffer_vertexOffsetData[vertexOffsetBufferIndex] = spellX + 100;
game->spellPopupSpriteClass.Buffer_vertexOffsetData[vertexOffsetBufferIndex + 1] = spellY;
game->spellPopupSpriteClass.Buffer_scaleValueData[game->spellPopups[i].sprite.BufferIndex_scaleValueData] = 0.0f;
IndexReference popupReference;
popupReference.generation = ++game->spellPopups[i].generation;
popupReference.index = i;
spell.spellPopupReference = popupReference;
queueScaleAnimation(game->spellPopupSpriteClass, popupReference.index, 0, 1.0f, 10, game->gameTime);
return;
}
}
createNewSpellPopup(game, spellX, spellY, spell);
}
void createNewSpellPopup(Game* game, float x, float y, Spell& spell) {
SpellPopup spellPopup;
spellPopup.generation = 0;
spellPopup.showing = true;
spellPopup.sprite.BufferIndex_scaleValueData = game->spellPopupSpriteClass.Buffer_scaleValueData.size();
spellPopup.sprite.BufferIndex_textureOffsetData = game->spellPopupSpriteClass.Buffer_textureOffsetData.size();
spellPopup.sprite.BufferIndex_vertexOffsetData = game->spellPopupSpriteClass.Buffer_vertexOffsetData.size();
spellPopup.sprite.BufferIndex_tintValueData = game->spellPopupSpriteClass.Buffer_tintValueData.size();
game->spellPopupSpriteClass.Buffer_vertexOffsetData.push_back(x + 100);
game->spellPopupSpriteClass.Buffer_vertexOffsetData.push_back(y);
game->spellPopupSpriteClass.Buffer_vertexOffsetData.push_back(1.0f);
game->spellPopupSpriteClass.Buffer_tintValueData.push_back(1.0f);
game->spellPopupSpriteClass.Buffer_tintValueData.push_back(1.0f);
game->spellPopupSpriteClass.Buffer_tintValueData.push_back(1.0f);
game->spellPopupSpriteClass.Buffer_textureOffsetData.push_back(spell.type * SPELL_POPUP_SPRITE_WIDTH);
game->spellPopupSpriteClass.Buffer_textureOffsetData.push_back(SPELL_POPUP_SPRITE_ROW);
game->spellPopupSpriteClass.Buffer_scaleValueData.push_back(0.0f);
spell.spellPopupReference.index = game->spellPopups.size();
spell.spellPopupReference.generation = spellPopup.generation;
queueScaleAnimation(game->spellPopupSpriteClass, spell.spellPopupReference.index, 0, 1.0f, 10, game->gameTime);
game->spellPopups.push_back(spellPopup);
}
void summonDemon(Game* game) {
if (game->summonLevel < 9) {
game->Buffer_circleTintValueData[game->summonLevel * 3] = 1.0f;
game->Buffer_circleTintValueData[game->summonLevel * 3 + 1] = 0.0f;
game->Buffer_circleTintValueData[game->summonLevel * 3 + 2] = 1.0f;
game->BufferRefreshFlag_circleTintValueData = true;
}
game->summonLevel++;
}
void castSpell(Game* game, Spell& spell) {
if (spell.type == SpellType::SUMMON_SPELL && !spell.isCasting) {
for (Attack& attack : game->attacks) {
attack.deleted = true;
game->attacksSpriteClass.Buffer_vertexOffsetData[attack.sprite.BufferIndex_vertexOffsetData] = -300;
game->attacksSpriteClass.Buffer_vertexOffsetData[attack.sprite.BufferIndex_vertexOffsetData + 1] = -300;
}
spell.isCasting = true;
float startingPosition = 265.0f;
float gap = 350.0f;
for (int i = 0; i < 4; i++) {
reuseOrCreateAttack(game, 3, startingPosition + gap * i, 1250.0f, i);
}
game->attacksSpriteClass.BufferRefreshFlag_scaleValueData = true;
game->attacksSpriteClass.BufferRefreshFlag_tintValueData = true;
game->attacksSpriteClass.BufferRefreshFlag_textureOffsetData = true;
game->attacksSpriteClass.BufferRefreshFlag_vertexOffsetData = true;
summonDemon(game);
}
}
| [
"[email protected]"
] | |
edbd8c980cae994126d21809d09bd71d028f26e5 | 0a85079f8ca7d385bd4da46ca92c10721df661dc | /1018.cpp | fc9312ee347cce92fff414824074c11b7b75030b | [] | no_license | Tiago-Santos-Andrade/uri | 45920edf5792846f958144d3c861b9950af55f3c | b9a27ac1853d372cc2b8df33b0a6de6ef5db7e4c | refs/heads/master | 2022-12-24T05:19:38.324529 | 2020-10-04T14:16:48 | 2020-10-04T14:16:48 | 290,349,599 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 348 | cpp | #include <stdio.h>
int main(void){
int valori, valor, notas[7] = {100,50,20,10,5,2,1}, qtnotas[7], i;
scanf("%i", &valor);
valori = valor;
for (i = 0; i<7; i++){
qtnotas[i] = valor/notas[i];
valor = valor%notas[i];
}
printf("%i\n", valori);
for (i=0;i<7;i++){
printf("%i nota(s) de R$ %i,00\n", qtnotas[i], notas[i]);
}
return 0;
}
| [
"[email protected]"
] | |
2b0769f274804a81914dc80c52ffa0439b2dce36 | be53be707c24a8751d93e3bd5fce53f8755212e6 | /cpp_without_fear/chap13/list.cpp | efccabe3588e467bba5d5d3e3cb0c15f9c1d33ed | [] | no_license | dboyliao/C_Cpp | b54bfeb0b91085701469bf7d50460f9737469390 | 0c56104107778213217e26d85ed3d9bbc2df532c | refs/heads/master | 2022-06-12T14:44:48.638880 | 2022-05-27T13:11:19 | 2022-05-27T13:11:19 | 46,228,690 | 4 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 484 | cpp | #include <list>
#include <exception>
#include <iostream>
using std::cerr;
using std::endl;
using std::list;
class A
{
};
class MyException
{
public:
MyException(char const *reason_) : reason(reason_) {}
char const *reason;
};
void foo()
{
throw MyException("Hello, error!");
}
int main(int argc, char const *argv[])
{
list<A> l(10);
try
{
foo();
}
catch (const MyException &e)
{
cerr << e.reason << endl;
}
return 0;
}
| [
"[email protected]"
] | |
bd85c4c5cd8b612dfbf93d0d8de0544444253ec3 | dce426f2f49f2fb7fcca307c6f06a7f6187e04bd | /factorial_test.cpp | 43abe087ce3f870564891aa6f2bcb2e08a487ff4 | [
"MIT"
] | permissive | MaxBytes/Performance-comparison-of-fundamental-algorithm-for-computing-factorial | efe4276613ad7189f11e58c1ac5f480458a710ac | 92db29c260d53dc7fccb6981563797e30727ee7d | refs/heads/master | 2021-04-12T11:49:05.005220 | 2018-03-21T15:52:12 | 2018-03-21T15:52:12 | 126,193,534 | 0 | 0 | null | null | null | null | IBM866 | C++ | false | false | 4,874 | cpp | #include <iostream>
#include <fstream>
#include <ctime>
#include <mpirxx.h>
mpz_class Factorial1(unsigned int n)
{
mpz_class x = 1;
for(mpz_class i = 2;i <= n;++i)
{
x *= i; // 1 * 2 * 3 * ... * n
}
return x;
}
mpz_class Factorial2(unsigned int n)
{
mpz_class k = (n / 2) + 1; // select appropriate k
mpz_class m = n;
mpz_class s = 0;
mpz_class result = k;
m -= k;
k *= k;
for(mpz_class i = 1;i <= m;++i)
{
s += ((i << 1) - 1); // s = 1 , 4 , 9 , ...
result *= (k - s);
}
return result; // n! = k * (k^2 - 1) * (k^2 - 4) * (k^2 - 9) * ...
}
mpz_class Factorial3(unsigned int n)
{
mpz_class x = 1;
if (n == 0) return 1;
if (n < 3) return n;
// this algorithm depends on following formulae
// n! = 2^floor(n/2) * (floor(n/2))! * 1 * 3 * 5 * ...
for(mpz_class y = 1;y <= n;y += 2)
{
x *= y; // 1 * 3 * 5 * ...
}
return (x * Factorial3(n >> 1)) << (n >> 1);
}
mpz_class mul_odd(unsigned int high,unsigned int low)
{
if ((high - low) <= 4)
{
if ((high - low) == 0)
{
return high;
}
else if ((high - low) == 2)
{
return mpz_class(high) * low;
}
return mpz_class(high) * low * (low + 2);
}
uint64_t m = high;
m = (m + low) >> 1;
if ((m & 1) == 0) --m;
return mul_odd(high, m + 2 /* (m + 2) might not fit in unsigned int */) * mul_odd(m, low);
}
mpz_class Factorial4(unsigned int n)
{
if (n < 2) return 1;
return (Factorial4(n >> 1) * mul_odd((n & 1) ? n : (n - 1),1)) << (n >> 1);
}
mpz_class mul_odd(uint64_t upper,uint64_t lower)
{
if ((upper - lower) <= 4)
{
if ((upper - lower) == 0)
{
return upper;
}
else if ((upper - lower) == 2)
{
return upper * lower;
}
return mpz_class(upper * lower) * (lower + 2);
}
uint64_t m = (upper + lower) >> 1;
if ((m & 1) == 0) --m;
return mul_odd(upper,m + 2) * mul_odd(m,lower);
}
mpz_class Factorial5(unsigned int n)
{
unsigned int l = 0;
unsigned int total_count_of_even = 0;
unsigned int end = 1,start = 1;
for(unsigned int k = 1;k <= n;k <<= 1) ++l; // number of bits of n
mpz_class x = 1,y = 1;
if (n < 2) return 1;
if (n < 3) return n;
for(unsigned int k = l;k >= 2;k--)
{
end = n >> (k - 2); // now end will be [n / 2^(k - 2)]
total_count_of_even += (end >> 1); // (end >> 1) will be counts of even number less than or equal to [n / 2^(k - 2)]
end = (end & 1) ? end : end - 1; // end must be odd number
y *= mul_odd(end, start);
// y now holds 1 * 3 * 5 * ... * [n / 2^(k - 2)]
x *= y; // x will be Го_[ q = 1 to [log_2(n) - 1] ] ( Го_[ p = 1 to [n / 2^(l - q - 1)] ] (2*p - 1) )
start = end + 2; // update lower bound
}
return x << total_count_of_even;
}
mpz_class Factorial6(unsigned int n)
{
// this is just wrapper of mpz_fac_ui
mpz_t m;
mpz_init(m);
mpz_fac_ui(m,n);
return mpz_class(m);
}
typedef mpz_class (*FACTORIAL_FUNCP)(unsigned int);
unsigned int run_test(FACTORIAL_FUNCP func,unsigned int func_arg,int test_count)
{
clock_t e,s;
unsigned int t = 0;
for(int i = 1;i <= test_count;++i)
{
s = clock();
func(func_arg);
e = clock();
t += (e - s);
}
return t / test_count;
}
int main(void)
{
int test_count = 10;
std::ofstream ofs;
ofs.open("factorial_test_0-50000.csv");
ofs << "n,Algorithm1,Algorithm2,Algorithm3,Algorithm4,Algorithm5,mpz_fac_ui" << std::endl;
std::cout << "Test for algorithm1 to algorithm5" << std::endl;
for(unsigned int n = 0;n <= 50000;n += 1000)
{
std::cout << "Testing " << n << "!\r";
ofs << n;
ofs << ',' << run_test(Factorial1,n,test_count);
ofs << ',' << run_test(Factorial2,n,test_count);
ofs << ',' << run_test(Factorial3,n,test_count);
ofs << ',' << run_test(Factorial4,n,test_count);
ofs << ',' << run_test(Factorial5,n,test_count);
ofs << ',' << run_test(Factorial6,n,test_count);
ofs << std::endl;
}
ofs.close();
ofs.open("factorial_test_50000-500000.csv");
ofs << "n,Algorithm4,Algorithm5,mpz_fac_ui" << std::endl;
std::cout << std::endl << "Test for algorithm4 and algorithm5" << std::endl;
for(unsigned int n = 50000;n <= 500000;n += 10000)
{
std::cout << "Testing " << n << "!\r";
ofs << n;
ofs << ',' << run_test(Factorial4,n,test_count);
ofs << ',' << run_test(Factorial5,n,test_count);
ofs << ',' << run_test(Factorial6,n,test_count);
ofs << std::endl;
}
ofs.close();
ofs.open("factorial_test_500000-1000000.csv");
ofs << "n,Algorithm5,mpz_fac_ui" << std::endl;
std::cout << std::endl << "Test for algorithm5" << std::endl;
for(unsigned int n = 500000;n <= 1000000;n += 10000)
{
std::cout << "Testing " << n << "!\r";
ofs << n;
ofs << ',' << run_test(Factorial5,n,test_count);
ofs << ',' << run_test(Factorial6,n,test_count);
ofs << std::endl;
}
ofs.close();
return 0;
}
| [
"[email protected]"
] | |
46f60ecab5a342ecddffb87df2e4a15204b98638 | bb5b3a13d1fc3cfd0787f49756b91280fc098fd6 | /algorithms/49-suffix_tree/main.cpp | 59b464f907d496c7b55ce5a486c1109054767b07 | [] | no_license | ThomasDetemmerman/C-Coding | 877e74983d602ee65fbc24a20f273800567c6865 | 1a1e4a14a78fbca89d1b834b0982d4c4a49a06b9 | refs/heads/master | 2020-07-31T15:06:45.189670 | 2019-07-29T08:34:22 | 2019-07-29T08:34:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 363 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <memory>
#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
#include "suffix_tree.h"
int main(int argc, char** argv) {
Suffix_Tree suffix_tree;
suffix_tree.add("banana");
suffix_tree.draw("suffix_tree.dot");
return 0;
}; | [
"[email protected]"
] | |
747d916561623b5787cbe96ffd2231dd6dc7acfa | 24843eb41aed8b95ef0d59c6678c88982a8e7e97 | /TPCSimulation/src/CreateTestMuons.cpp | bdaf9347523bec189066b1d0e4fe23c27168825d | [] | no_license | sbu-stuff/TPCGEMSim | f9bc663c9b7f3efcca6aa3c87a5db36f64094b22 | 9a3a2572abe35a81ec633e1be0e9fe74d32dfc67 | refs/heads/master | 2020-05-29T15:41:09.417803 | 2017-04-25T19:51:23 | 2017-04-25T19:51:23 | 63,812,397 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,251 | cpp | #include <TROOT.h>
#include <TFile.h>
#include <TTree.h>
#include <stdlib.h>
#include <iostream>
#include <TParticle.h>
#include <math.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
#include <string>
#define MASS_M 0.10566 //muon 13
#define MASS_Pi 0.13957 //pion -211
#define MASS_K 0.493677 //kaon- -321
#define MASS_P 0.938272 //proton 2212
#define MASS_E 0.000511 //electron 11
using namespace std;
int main(int argc, char* argv[]){
if(argc != 4)
{
cout << "Choose:"<<endl;
cout<< "Number of Muonevents to be craeted" << endl;
cout<< "Chamber Parameter: Radius [mm], Lenght [mm]"<<endl;
exit(1);
}
int events=atoi(argv[1]);
double radius=atof(argv[2])-1;
double length=atof(argv[3]);
const Int_t clonesarraysize = 100000; // size of TClonesArray to store generated particles
gsl_rng *r=gsl_rng_alloc(gsl_rng_mt19937);
char *outfilestring = new char[256];
sprintf(outfilestring,"MuonEvents_N%i_R%.0f_L%.0f.root",events,
(radius+1),length);
TFile* file = new TFile(outfilestring, "recreate");
file->SetCompressionLevel(2);
TTree* tree = new TTree("tree", "Eventtree");
TClonesArray* mcEvent = new TClonesArray("TParticle", clonesarraysize);
tree->Branch("MCEvent", &mcEvent);
TParticle* muon = new TParticle(11,1,10,10,10,10,0,0,0,0,0,0,0,10);
// Event loop section
for(int i=0;i<events;i++)
{
//int numberofmuons=(int)(1+randgaus*drand48());
int numberofmuons=1;
for(int j=0;j<numberofmuons;j++)
{
//starting point is interaction point
double vx = 0;
double vy = 0;
double vz = 0;
//dice energy
double energy= MASS_E*exp(log(250./MASS_E)*drand48());
double P = sqrt(energy*energy-MASS_E*MASS_E);
//split momentum in components
double pz=0.05;
double px=0.005;//sin(0.75)*P+drand48()*(1-sin(0.75))*P;
double py=sqrt(P*P-px*px-pz*pz);
//set TParticle values
muon->SetMomentum(px,py,pz,energy);
muon->SetProductionVertex(vx,vy,vz,0);
muon->SetStatusCode(1);
TClonesArray &particle = *mcEvent;
new(particle[j]) TParticle(*muon);
//new(mcEvent[j]) muon;
//mcEvent[j]=muon;
}
tree->Fill();
mcEvent->Clear();
}
tree->Write();
file->Close();
}
| [
"[email protected]"
] | |
fa2629f42540d207f024eb93f3b56c31e456ff75 | e4437dd9409a63ab093ba01dfddd9d8a41665e5d | /src/render/tabs/visuals_tab.cpp | 3a62d2f8f77717fc34226f47e715c06270652f2b | [] | no_license | somewhatheadless/Sensum | 7a8b884e23d51d8c5b0cbf2ef39e4036c4b486c8 | 2de9bf722146e0ed7d7f419a331fc3cb8c26ed2f | refs/heads/master | 2020-11-28T18:36:40.952929 | 2019-12-23T21:20:57 | 2019-12-23T21:20:57 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 10,861 | cpp | #include "../render.h"
#include "../../globals.h"
#include "../../settings.h"
#include "../../helpers/imdraw.h"
#include "../../helpers/console.h"
#include "../..//features/features.h"
extern void bind_button(const char* eng, const char* rus, int& key);
extern bool hotkey(const char* label, int* k, const ImVec2& size_arg = ImVec2(0.f, 0.f));
namespace render
{
namespace menu
{
void visuals_tab()
{
child("ESP", []()
{
columns(2);
{
checkbox("Enabled", u8"Включено", &settings::esp::enabled);
ImGui::NextColumn();
ImGui::PushItemWidth(-1);
hotkey("##binds.esp", &globals::binds::esp);
ImGui::PopItemWidth();
}
columns(1);
checkbox("Visible Only", u8"Проверка видимости", &settings::esp::visible_only);
checkbox("Name", u8"Имя", &settings::esp::names);
columns(2);
{
checkbox("Weapon", u8"Оружие", &settings::esp::weapons);
ImGui::NextColumn();
const char* weapon_modes[] = {
"Text",
"Icons"
};
ImGui::PushItemWidth(-1);
{
ImGui::Combo("Mode", &settings::esp::weapon_mode, weapon_modes, IM_ARRAYSIZE(weapon_modes));
}
ImGui::PopItemWidth();
}
ImGui::Columns(1);
columns(2);
{
checkbox("Player Info Box", &settings::visuals::player_info_box);
ImGui::NextColumn();
ImGui::PushItemWidth(-1);
{
ImGui::SliderFloatLeftAligned("Alpha##infobox", &settings::visuals::player_info_box_alpha, 0.0f, 1.0f, "%0.1f");
}
ImGui::PopItemWidth();
}
ImGui::Columns(1);
columns(2);
{
checkbox("Grief Box", &settings::visuals::grief_box);
ImGui::NextColumn();
ImGui::PushItemWidth(-1);
{
ImGui::SliderFloatLeftAligned("Alpha##griefbox", &settings::visuals::grief_box_alpha, 0.0f, 1.0f, "%0.1f");
}
ImGui::PopItemWidth();
}
ImGui::Columns(1);
columns(2);
{
checkbox("Boxes", u8"Боксы", &settings::esp::boxes);
ImGui::NextColumn();
const char* box_types[] = {
___("Normal", u8"Обычные"), ___("Corner", u8"Угловые")
};
ImGui::PushItemWidth(-1);
{
ImGui::Combo("##esp.box_type", &settings::esp::box_type, box_types, IM_ARRAYSIZE(box_types));
}
ImGui::PopItemWidth();
}
ImGui::Columns(1);
const char* positions[] =
{
___("Left", u8"Слева"),
___("Right", u8"Справа"),
___("Bottom", u8"Внизу"),
};
const char* HealthPositions[] =
{
___("Left", u8"Слева"),
___("Right", u8"Справа"),
___("Bottom", u8"Внизу"),
___("Number", u8"Внизу"),
};
columns(2);
{
checkbox("Health", u8"Здоровье", &settings::esp::health);
ImGui::NextColumn();
ImGui::PushItemWidth(-1);
ImGui::Combo("##health.position", &settings::esp::health_position, HealthPositions, IM_ARRAYSIZE(HealthPositions));
ImGui::PopItemWidth();
}
columns(1);
columns(2);
{
checkbox("Armor", u8"Броня", &settings::esp::armour);
ImGui::NextColumn();
ImGui::PushItemWidth(-1);
ImGui::Combo("##armor.position", &settings::esp::armour_position, positions, IM_ARRAYSIZE(positions));
ImGui::PopItemWidth();
}
columns(1);
//checkbox("Dormant", &Settings::ESP::dormant);
checkbox("Is Scoped", &settings::esp::is_scoped);
checkbox("Is Flashed", &settings::esp::is_flashed);
checkbox("Is Defusing", &settings::esp::is_defusing);
checkbox("Is Desyncing", &settings::esp::is_desyncing);
checkbox("Has Kit", &settings::esp::haskit);
checkbox("Ammo ESP", &settings::esp::ammo);
checkbox("Money ESP", &settings::esp::money);
checkbox("Choke ESP", &settings::visuals::choke);
checkbox("Sound ESP", &settings::esp::soundesp);
//checkbox("Beams", u8"Лучи света", &settings::esp::beams); //Doesnt work.
//checkbox("Sound Direction (?)", &settings::esp::sound); //Doesnt work.
//tooltip("Sound ESP", u8"Показывает стрелками направление звука, откуда слышно игрока.");
checkbox("Bomb Damage ESP", &settings::esp::bomb_esp);
checkbox("Offscreen ESP", u8"Точка направления (?)", &settings::esp::offscreen);
});
ImGui::NextColumn();
child(___("Chams", u8"Цветные Модели"), []()
{
static const char* ChamsTypes[] = {
"Visible - Normal",
"Visible - Flat",
"Visible - Wireframe",
"Visible - Glass",
"Visible - Metallic",
"XQZ",
"Metallic XQZ",
"Flat XQZ"
};
static const char* bttype[] = {
"Off",
"Last Tick",
"All Ticks"
};
static const char* chamsMaterials[] = {
"Normal",
"Dogtags",
"Flat",
"Metallic",
"Platinum",
"Glass",
"Crystal",
"Gold",
"Dark Chrome",
"Plastic/Gloss",
"Glow"
};
columns(2);
{
checkbox("Enemy", &settings::chams::enemynew);
ImGui::NextColumn();
ImGui::PushItemWidth(-1);
ImGui::Combo("Enemy - Mode", &settings::chams::enemymodenew, ChamsTypes, IM_ARRAYSIZE(ChamsTypes));
ImGui::PopItemWidth();
}
columns(1);
columns(2);
{
checkbox("Team", &settings::chams::teamnew);
ImGui::NextColumn();
ImGui::PushItemWidth(-1);
ImGui::Combo("Team - Mode", &settings::chams::teammodenew, ChamsTypes, IM_ARRAYSIZE(ChamsTypes));
ImGui::PopItemWidth();
}
columns(1);
columns(2);
{
checkbox("Local", &settings::chams::localnew);
ImGui::NextColumn();
ImGui::PushItemWidth(-1);
ImGui::Combo("Local - Mode", &settings::chams::localmodenew, ChamsTypes, IM_ARRAYSIZE(ChamsTypes));
ImGui::PopItemWidth();
}
columns(1);
columns(2);
{
checkbox("Real Angle ", &settings::chams::desync);
ImGui::NextColumn();
ImGui::PushItemWidth(-1);
ImGui::Combo("Material", &settings::chams::desyncChamsMode, chamsMaterials, IM_ARRAYSIZE(chamsMaterials));
ImGui::PopItemWidth();
}
columns(1);
//checkbox("Viewmodel Weapons", &settings::chams::wepchams);
ImGui::SameLine();
checkbox("Planted C4", &settings::chams::plantedc4_chams);
checkbox("Weapons (?) ", &settings::chams::wep_droppedchams);
tooltip("Dropped Weapons Chams");
ImGui::SameLine();
checkbox("Nades", &settings::chams::nade_chams);
checkbox("Health Chams", &settings::chams::health_chams);
//separator("BT Chams - Mode");
//ImGui::Combo("BT Chams Mode", &settings::chams::bttype, bttype, IM_ARRAYSIZE(bttype));
//checkbox("BT Chams - Flat", &settings::chams::btflat);
//ColorEdit4("BT Color", &settings::chams::btColorChams);
/*separator("Arms", u8"Руки");
checkbox("Enabled##arms", u8"Включено##arms", &settings::chams::arms::enabled);
checkbox("Wireframe##arms", u8"Сетка##arms", &settings::chams::arms::wireframe);
ImGui::Separator();
ColorEdit4(___("Visible", u8"Видимый"), &settings::chams::visible_color);
ColorEdit4(___("Occluded", u8"За преградой"), &settings::chams::occluded_color);
ColorEdit4(___("Arms", u8"Руки"), &settings::chams::arms::color); */
child(___("Glow", u8"Цветные Модели"), []()
{
checkbox("Enemy", &settings::glow::glowEnemyEnabled);
ImGui::SameLine();
checkbox("Planted C4", &settings::glow::glowC4PlantedEnabled);
ImGui::SameLine();
checkbox("Nades", &settings::glow::glowNadesEnabled);
checkbox("Team ", &settings::glow::glowTeamEnabled);
ImGui::SameLine();
checkbox("Weapons (?)", &settings::glow::glowDroppedWeaponsEnabled);
tooltip("Dropped Weapons Glow");
});
});
ImGui::NextColumn();
child(___("Extra", u8"Прочее"), []()
{
static const char* cross_types[] = {
"Type: Crosshair",
"Type: Circle"
};
static const char* hitmarkersounds[] = {
"Sound: Cod",
"Sound: Skeet",
"Sound: Punch",
"Sound: Metal",
"Sound: Boom"
};
checkbox("Buy Log", &settings::esp::buylog);
checkbox("Planted C4", &settings::visuals::planted_c4);
checkbox("Defuse Kits", u8"Дефуза", &settings::visuals::defuse_kit);
checkbox("World Weapons", u8"Подсветка оружий", &settings::visuals::dropped_weapons);
checkbox("World Grenades", u8"Подсветка гранат", &settings::visuals::world_grenades);
checkbox("Sniper Crosshair", u8"Снайперский прицел", &settings::visuals::sniper_crosshair);
checkbox("Snap Lines", &settings::esp::snaplines);
checkbox("Armor Status (?)", &settings::esp::kevlarinfo);
tooltip("Will display HK if enemy has kevlar + helmer or K if enemy has kevlar only.");
checkbox("Grenade Prediction", u8"Прогноз полета гранат", &settings::visuals::grenade_prediction);
checkbox("Damage Indicator", &settings::misc::damage_indicator);
checkbox("Aimbot Fov", &settings::esp::drawFov);
checkbox("Spread Crosshair", &settings::visuals::spread_cross);
checkbox("Bullet Tracer", &settings::visuals::bullet_tracer);
checkbox("Hitmarker", &settings::visuals::hitmarker);
ImGui::Combo("Hitmarker Sound", &settings::visuals::hitsound, hitmarkersounds, IM_ARRAYSIZE(hitmarkersounds));
checkbox("RCS Crosshair", &settings::visuals::rcs_cross);
ImGui::Combo("RCS Crosshair Type", &settings::visuals::rcs_cross_mode, cross_types, IM_ARRAYSIZE(cross_types));
if (settings::visuals::rcs_cross_mode == 1)
ImGui::SliderFloatLeftAligned("Radius", &settings::visuals::radius, 8.f, 18.f, "%.1f");
const auto old_night_state = settings::visuals::night_mode;
const auto old_style_state = settings::visuals::newstyle;
checkbox("Night Mode", u8"Ночной режим", &settings::visuals::night_mode);
if (settings::visuals::night_mode)
{
ImGui::SliderFloatLeftAligned(___("Night Mode Intensity:", u8"Радиус:"), &settings::esp::mfts, 0.0f, 1.0f, "%.1f %");
if (ImGui::Button("Apply", ImVec2(ImGui::GetContentRegionAvailWidth(), 0.f)))
{
color_modulation::SetMatForce();
}
}
checkbox("Chance ESP (?)", &settings::misc::esp_random);
tooltip("Enables/disables the esp/chams based on chance, that is generated per round.Set chance manually.");
if (settings::misc::esp_random)
{
ImGui::SliderIntLeftAligned("ESP Chance (?)", &settings::esp::esp_chance, 1, 100, "%.0f %%");
tooltip("Will turn esp/chams on/off if chance is higher/smaller or equal than set value");
}
checkbox("Dark Menu", &settings::visuals::newstyle);
if (old_style_state != settings::visuals::newstyle) //settings::visuals::night_mode
imdraw::apply_style(settings::visuals::newstyle);
});
}
}
} | [
"[email protected]"
] | |
c7c9354b05d95e5e3a3a730510b28ca76e524cd7 | 6422683c474166c8c4cdd81557f4b4f2dac5eec6 | /Gescole 2/Gescole/Formulaire.h | 78938f5c9d16918f1d73ae7b566b9bc8dac04798 | [] | no_license | Phrederik2/Projet-C-2ieme | 27a0cff89bfbcc91d8417152b761393edc200511 | 27c27939d0e226bda048783bc0f432fcbbb459f0 | refs/heads/master | 2020-02-26T14:31:39.687921 | 2016-06-23T17:21:42 | 2016-06-23T17:21:42 | 59,936,232 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,611 | h | #pragma once
#include"Client.h"
#include"Livraison.h"
#include"Commande.h"
#include"RendezVous.h"
#include"Dossier.h"
#include "Message.h"
#include <iostream>
#include "ZoneSaisie.h"
#include"Search.h"
#include"Stream.h"
#include"Lancer.h"
#include"Message.h"
template<class ENTITY>
class Formulaire
{
public:
ZoneSaisie zs;
void operator<<(ENTITY* other);
void operator>>(ENTITY* other);
void Display(ostream& stream, Client* other);
void Display(ostream& stream, Livraison* other);
void Display(ostream& stream, Commande* other);
void Display(ostream& stream, RendezVous* other);
void Display(ostream& stream, Dossier* other);
void Display(ostream& stream, Lancer* other);
void DisplayClient(ostream& stream, Client* temp);
void DisplayLivraison(ostream& stream, Livraison* temp);
void DisplayCommande(ostream& stream, Commande* temp);
void DisplayRendezVous(ostream& stream, RendezVous* temp);
void Encode(Client* other);
void Encode(Livraison* other);
void Encode(Commande* other);
void Encode(RendezVous* other);
void Encode(Dossier* other);
void Encode(Date* other);
void Encode(Lancer* other);
static void getTitle(string* title);
};
template<class ENTITY>
void Formulaire<ENTITY>::operator<<(ENTITY* other)
{
if (other)
{
if (other->IsDelete)return;
cout << endl;
Display(cout, other);
}
}
template<class ENTITY>
void Formulaire<ENTITY>::operator>>(ENTITY* other)
{
if (other->IsDelete)return;
if (other) Encode(other);
}
template<class ENTITY>
inline void Formulaire<ENTITY>::Display(ostream & stream, Client * other)
{
stream << Client_ID Pct_DeuxPoint << other->getID() << endl;
stream << Client_Nom Pct_DeuxPoint << other->getNom() << endl;
stream << Client_Prenom Pct_DeuxPoint << other->getPrenom() << endl;
stream << Client_Societe Pct_DeuxPoint << other->getSociete() << endl;
stream << Client_Localite Pct_DeuxPoint << other->getLocalite() << endl;
stream << Client_Rue Pct_DeuxPoint << other->getRue() << endl;
stream << Client_Numero Pct_DeuxPoint << other->getNumero() << endl;
stream << Client_Boite Pct_DeuxPoint << other->getBoite() << endl;
stream << Client_CodePostal Pct_DeuxPoint << other->getCodePostal() << endl;
}
template<class ENTITY>
inline void Formulaire<ENTITY>::Display(ostream & stream, Livraison * other)
{
stream << Livraison_ID Pct_DeuxPoint << other->getID() << endl;
stream << Livraison_Statut Pct_DeuxPoint << other->getName() << endl;
}
template<class ENTITY>
inline void Formulaire<ENTITY>::Display(ostream & stream, Commande * other)
{
stream << Commande_ID Pct_DeuxPoint << other->getID() << endl;
stream << Commande_Statut Pct_DeuxPoint << other->getName() << endl;
}
template<class ENTITY>
inline void Formulaire<ENTITY>::Display(ostream & stream, RendezVous * other)
{
stream << RDV_ID Pct_DeuxPoint << other->getID() << endl;
stream << RDV_DateDebut Pct_DeuxPoint << other->getDateDebut() << endl;
stream << RDV_DateFin Pct_DeuxPoint << other->getDateFin() << endl;
stream << RDV_Remarque Pct_DeuxPoint << other->getRemark() << endl;
}
template<class ENTITY>
inline void Formulaire<ENTITY>::Display(ostream & stream, Dossier * other)
{
Client* client = new Client;
Livraison* livraison = new Livraison;
Commande* commande = new Commande;
RendezVous* rendezvous = new RendezVous;
Stream sql;
stream << Dossier_ID Pct_DeuxPoint << other->getID() << endl;
stream << Dossier_Client Pct_DeuxPoint << endl;
sql.Write(other->getID_Client(), client, "client");
DisplayClient(stream, client);
stream << Dossier_RDV Pct_DeuxPoint << endl;
sql.Write(other->getID_RDV(), rendezvous, "rendezvous");
DisplayRendezVous(stream, rendezvous);
stream << Dossier_Livraison Pct_DeuxPoint << endl;
sql.Write(other->getID_Livraison(), livraison, "livraison");
DisplayLivraison(stream, livraison);
stream << Dossier_Commande Pct_DeuxPoint << endl;
sql.Write(other->getID_Commande(), commande, "commande");
DisplayCommande(stream, commande);
delete client;
delete livraison;
delete commande;
delete rendezvous;
}
template<class ENTITY>
inline void Formulaire<ENTITY>::Display(ostream & stream, Lancer * other)
{
}
template<typename ENTITY>
inline void Formulaire<ENTITY>::DisplayClient(ostream& stream, Client * temp)
{
if (temp)
{
stream << temp->getNom() << Pct_Espace << temp->getPrenom() << endl;
stream << temp->getSociete() << endl;
stream << temp->getRue() << Pct_Espace << temp->getNumero() << temp->getBoite() << ", " << temp->getCodePostal() <<" " << temp->getLocalite() << endl;
}
}
template<class ENTITY>
inline void Formulaire<ENTITY>::DisplayLivraison(ostream & stream, Livraison * temp)
{
if (temp)
{
stream << temp->getName() << endl;
}
}
template<class ENTITY>
inline void Formulaire<ENTITY>::DisplayCommande(ostream & stream, Commande * temp)
{
if (temp)
{
stream << temp->getName() << endl;
}
}
template<class ENTITY>
inline void Formulaire<ENTITY>::DisplayRendezVous(ostream & stream, RendezVous * temp)
{
if (temp)
{
stream << RDV_Debut Pct_DeuxPoint << temp->getDateDebut() << RDV_Fin Pct_DeuxPoint << temp->getDateFin() << endl;
}
}
template<class ENTITY>
inline void Formulaire<ENTITY>::Encode(Client * other)
{
cout << Client_ID Pct_DeuxPoint << other->getID() << endl;
cout << Client_Nom Pct_DeuxPoint << endl;
if (zs.Ask()) other->setNom(zs.ValString());
cout << Client_Prenom Pct_DeuxPoint << endl;
if (zs.Ask()) other->setPrenom(zs.ValString());
cout << Client_Societe Pct_DeuxPoint << endl;
if (zs.Ask()) other->setSociete(zs.ValString());
cout << Client_Localite Pct_DeuxPoint << endl;
if (zs.Ask()) other->setLocalite(zs.ValString());
cout << Client_Rue Pct_DeuxPoint << endl;
if (zs.Ask()) other->setRue(zs.ValString());
cout << Client_Numero Pct_DeuxPoint << endl;
if (zs.Ask()) other->setNumero(zs.ValInt());
cout << Client_Boite Pct_DeuxPoint << endl;
if (zs.Ask()) other->setBoite(zs.ValChar());
cout << Client_CodePostal Pct_DeuxPoint << endl;
if (zs.Ask()) other->setCodePostal(zs.ValInt());
}
template<class ENTITY>
inline void Formulaire<ENTITY>::Encode(Livraison * other)
{
cout << Livraison_ID Pct_DeuxPoint << other->getID() << endl;
cout << Livraison_Statut Pct_DeuxPoint << endl;
if (zs.Ask()) other->setName(zs.ValString());
}
template<class ENTITY>
inline void Formulaire<ENTITY>::Encode(Commande * other)
{
cout << Commande_ID Pct_DeuxPoint << other->getID() << endl;
cout << Commande_Statut Pct_DeuxPoint << endl;
if (zs.Ask()) other->setName(zs.ValString());
}
template<class ENTITY>
inline void Formulaire<ENTITY>::Encode(RendezVous * other)
{
cout << RDV_ID Pct_DeuxPoint << other->getID() << endl;
cout << RDV_DateDebut Pct_DeuxPoint << endl;
Encode(other->setDateDebut());
cout << RDV_DateFin Pct_DeuxPoint << endl;
Encode(other->setDateFin());
cout << RDV_Remarque Pct_DeuxPoint << endl;
if (zs.Ask()) other->setRemark(zs.ValString());
}
template<class ENTITY>
inline void Formulaire<ENTITY>::Encode(Dossier * other)
{
cout << Dossier_ID Pct_DeuxPoint << other->getID() << endl;
cout << Dossier_Client Pct_DeuxPoint << endl;
cout << endl;
other->setID_Client(Application<Client>::Run(other->getID_Client()));
cout << Dossier_Commande Pct_DeuxPoint << endl;
other->setID_Commande(Application<Commande>::Run(other->getID_Commande()));
cout << Dossier_Livraison Pct_DeuxPoint << endl;
other->setID_Livraison(Application<Livraison>::Run(other->getID_Livraison()));
cout << Dossier_RDV Pct_DeuxPoint << endl;
other->setID_RDV(Application<RendezVous>::Run(other->getID_RDV()));
}
template<class ENTITY>
inline void Formulaire<ENTITY>::Encode(Date * other)
{
cout << Date_Jour Pct_DeuxPoint << endl;
if (zs.Ask()) other->setDay(zs.ValUInt());
cout << Date_Mois Pct_DeuxPoint << endl;
if (zs.Ask()) other->setMonth(zs.ValUInt());
cout << Date_Annee Pct_DeuxPoint << endl;
if (zs.Ask()) other->setYear(zs.ValUInt());
}
template<class ENTITY>
inline void Formulaire<ENTITY>::Encode(Lancer * other)
{
}
template<class ENTITY>
inline void Formulaire<ENTITY>::getTitle(string* title)
{
string entity = typeid(ENTITY).name();
if (entity.find("Lancer") != std::string::npos) *title = Titre_Lancer Pct_DeuxPoint;
if (entity.find("Dossier") != std::string::npos) *title = Titre_Dossier Pct_DeuxPoint;
if (entity.find("Livraison") != std::string::npos) *title = Titre_Livraison Pct_DeuxPoint;
if (entity.find("Commande") != std::string::npos) *title = Titre_Commande Pct_DeuxPoint;
if (entity.find("Client") != std::string::npos) *title = Titre_Client Pct_DeuxPoint;
if (entity.find("RendezVous") != std::string::npos) *title = Titre_RDV Pct_DeuxPoint;
}
| [
"[email protected]"
] | |
2d3fe4c7b39599c00c5cbe7d428c557f1f2232e6 | 2161720e0b3517d25337fd98aaf9a9fbafc836e7 | /Atcoder BC 205/A.cpp | 935f392d7eb107070f0af8b9a827830d986cf597 | [] | no_license | pouriaafshari/Contests-CPP | 455468c4ebac4f653967ebdd89ce9c748965ece7 | da4440b3ede544438ec43587a1af5a20afad9760 | refs/heads/main | 2023-08-01T10:18:06.369486 | 2021-10-03T17:36:06 | 2021-10-03T17:36:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 117 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
double A, B;
cin >> A >> B;
cout << B*A/100;
}
| [
"[email protected]"
] | |
de182d7dc3387a37959c405665216eab980500c4 | 724ab4b95af7786587d442f206f0c3a895b2e2c1 | /chinko_bot/types/game/context/roleplay/BasicAllianceInformations.h | 86e08990ecbc1233377d448c510676c939929fac | [] | no_license | LaCulotte/chinko_bot | 82ade0e6071de4114cc56b1eb6085270d064ccb1 | 29aeba90638d0f2fe54d1394c1c9a2f63524e50e | refs/heads/master | 2023-02-04T21:15:20.344124 | 2020-12-26T08:55:00 | 2020-12-26T08:55:00 | 270,402,722 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 908 | h | #ifndef BASICALLIANCEINFORMATIONS_H
#define BASICALLIANCEINFORMATIONS_H
#include "AbstractSocialGroupInfos.h"
class BasicAllianceInformations : public AbstractSocialGroupInfos {
public:
// Constructor
BasicAllianceInformations() {};
// Copy constructor
BasicAllianceInformations(const BasicAllianceInformations& other) = default;
// Copy operator
BasicAllianceInformations& operator=(const BasicAllianceInformations& other) = default;
// Destructor
~BasicAllianceInformations() = default;
virtual unsigned int getId() override { return typeId; };
static const unsigned int typeId = 1115;
// Turns raw data into the usable data (type's attributes)
virtual bool deserialize(shared_ptr<MessageDataBuffer> input) override;
// Turns the type's attributes into raw data
virtual bool serialize(shared_ptr<MessageDataBuffer> output) override;
string allianceTag;
int allianceId = 0;
};
#endif | [
"[email protected]"
] | |
bd14ba2eb1d1f1fcac08f6e11e5252d0a34c30d8 | 77f308bfc4a2f4515fa9a0b4114691352280ab9b | /LAB7/inc/Node.hh | 12165a56365dc8687e4b629d015110d2db112e75 | [] | no_license | 226319/PAMSI | 202ddf18e16c8b551f965b1d44bddd3422aed609 | 540a2b54526670063e43eb0d7dead0ac62d9e909 | refs/heads/master | 2021-01-22T19:36:38.456699 | 2017-05-29T19:43:23 | 2017-05-29T19:43:23 | 85,222,533 | 0 | 1 | null | 2017-04-04T18:11:47 | 2017-03-16T17:14:45 | C++ | UTF-8 | C++ | false | false | 451 | hh | #ifndef _NODE_HH
#define _NODE_HH
#include "Component.hh"
class Node {
public:
virtual ~Node(){} ;
virtual Node* const getLeft() const {} ;
virtual void setLeft(Node*&) {};
virtual Node* const getRight() const {};
virtual void setRight(Node*&){};
virtual Node* const getParent() {};
virtual void setParent(Node*&) {};
virtual Component* const getElement() const {};
virtual void setElement( Component* ) {};
};
#endif
| [
"[email protected]"
] | |
f91a3eccbda4088a706f496cb2c9ed136a361dfc | 2aabb9b02ceec88ddb81a27dc56b73dfde378bcf | /source/physics/include/GateSourceVoxelImageReaderMessenger.hh | b1d02d87cb884d7f5148b03a56025133599883f4 | [] | no_license | zcourts/gate | 5121ba9f397124b71abca4e38be3dd91d80e68d9 | 3626e9e77e9bbd0200df40d2ccdd3628ddb0b04b | refs/heads/master | 2020-12-11T05:51:37.059209 | 2014-05-15T09:02:32 | 2014-05-15T09:02:32 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 772 | hh | /*----------------------
Copyright (C): OpenGATE Collaboration
This software is distributed under the terms
of the GNU Lesser General Public Licence (LGPL)
See GATE/LICENSE.txt for further details
----------------------*/
#ifndef GateSourceVoxelImageReaderMessenger_h
#define GateSourceVoxelImageReaderMessenger_h 1
#include "GateVSourceVoxelReaderMessenger.hh"
#include "GateSourceVoxelImageReader.hh"
class GateSourceVoxelImageReaderMessenger : public GateVSourceVoxelReaderMessenger
{
public:
GateSourceVoxelImageReaderMessenger(GateSourceVoxelImageReader* voxelReader);
virtual ~GateSourceVoxelImageReaderMessenger();
void SetNewValue(G4UIcommand* command,G4String newValue);
protected:
GateUIcmdWithAVector<G4String>* ReadFileCmd;
};
#endif
| [
"[email protected]"
] | |
50a3c3e307c6497628e6a92c9894b95c4e77b5d3 | e44753ff66856e24a5d189a74dfff365e43cf8c4 | /src/extractor/MetricHistogram.cpp | 7a8d041a496b81dcd530237c850d1f849d9b58ed | [
"MIT"
] | permissive | pedro-stanaka/PgAR-tree | 7ca0c9ce338b50b504da982b3ed81a724b37c721 | 39b5ac3fd267f29151f254d4ef30f125c5c341ea | refs/heads/master | 2020-05-18T19:03:56.470777 | 2013-10-24T13:26:46 | 2013-10-24T13:26:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,564 | cpp | #include <gbdi/extractor/MetricHistogram.hpp>
/**
* Constructor.
*/
UnitNondimensional::UnitNondimensional(){
setGray(0);
setValue(0);
}
/**
* Destructor.
*/
UnitNondimensional::~UnitNondimensional(){
}
/**
* Sets a gray value.
*
* @param gray The gray value what will be set.
*/
void UnitNondimensional::setGray(int gray){
this->gray = gray;
}
/**
* Sets a value.
*
* @param value The value what will be set.
*/
void UnitNondimensional::setValue(float value){
this->value = value;
}
/**
* Sets a gray and a value into a nondimensional unit.
*
* @param gray The gray value what will be set.
* @param value The value what will be set.
*/
void UnitNondimensional::setXYAxis(int gray, float value){
setGray(gray);
setValue(value);
}
/**
* Gets a gray value.
*
* @return Gets a gray value.
*/
int UnitNondimensional::getGray(){
return gray;
}
/**
* Gets a value.
*
* @return Gets value.
*/
float UnitNondimensional::getValue(){
return value;
}
/**
* Constructor.
*/
NondimensionalHistogram::NondimensionalHistogram(){
nondimHistogram.clear();
}
/**
* Destructor.
*/
NondimensionalHistogram::~NondimensionalHistogram(){
nondimHistogram.clear();
}
/**
* Sets a unit nondimensional into a histogram.
*
* @param unit The unit what will be set.
* @param pos The pos in the nondimensional histogram.
*/
void NondimensionalHistogram::setUnitNondimensional(UnitNondimensional unit, int pos){
UnitNondimensional ut;
ut.setGray(0);
ut.setValue(0);
if (nondimHistogram.size() <= pos){
for (int i = nondimHistogram.size(); i <= pos; i++)
nondimHistogram.push_back(ut);
}
nondimHistogram[pos] = unit;
}
/**
* Gets a size of the nondimensional histogram.
*
* @return Gets the size of the non dimensional histogram.
*/
int NondimensionalHistogram::getSize(){
return nondimHistogram.size();
}
/**
* Gets a unit nondimensional.
*
* @param pos The position what will be recovered
* @return The nondimensional unit.
* @throw OutOfBoundsException If pos is not a valid position.
*/
UnitNondimensional NondimensionalHistogram::getUnitNondimensional(int pos) throw (artemis::OutOfBoundsException*){
try{
return nondimHistogram[pos];
}catch(...){
throw new OutOfBoundsException();
}
}
/**
* Clear the non dimensional histogram.
*/
void NondimensionalHistogram::clearHistogram(){
nondimHistogram.clear();
}
| [
"[email protected]"
] | |
ad9ce84dcfb1abe0d13d2f04865e9f35a5d7654e | caa3ab0c914f3197349549c44595b79ccae7b104 | /Enity/Entity.cpp | aa483946c2fdfa3be1802540f6509aad9257ed9e | [] | no_license | Persovt/NECROPHIS | ed282ed931f7f6052e34d5174f5f089add5631e5 | bf0143662f794e95ec168afd6770952494ff53de | refs/heads/master | 2023-05-01T15:39:26.834440 | 2021-05-01T07:17:52 | 2021-05-01T07:17:52 | 363,346,813 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,446 | cpp | #include "Entity.h"
namespace Engine
{
char* CBaseEntity::GetPlayerName()
{
if (IsPlayer())
{
static PlayerInfo Info;
if (Interfaces::Engine()->GetPlayerInfo(EntIndex(), &Info))
return Info.m_szPlayerName;
}
return "";
}
void CBaseEntity::SetEyeAngles(Vector angles)
{
*reinterpret_cast<Vector*>(uintptr_t(this) + Offset::Entity::m_angEyeAngles) = angles;
}
Vector CBaseEntity::GetEyePos()
{
return *(Vector*)((DWORD)this + Offset::Entity::m_vecOrigin + Offset::Entity::m_vecViewOffset);
}
bool CBaseEntity::IsPlayer()
{
typedef bool(__thiscall* IsPlayerFn)(void*);
return GetMethod<IsPlayerFn>(this, 157)(this);
}
void CBaseEntity::UpdateClientAnimation()
{
typedef void(__thiscall* UpdateClientAnimationFn)(void*);
return GetMethod<UpdateClientAnimationFn>(this, 223)(this);
}
bool CBaseEntity::IsValid()
{
return (!IsDead() && GetHealth() > 0 && !IsDormant() );
}
bool CBaseEntity::IsDead()
{
BYTE LifeState = *(PBYTE)((DWORD)this + Offset::Entity::m_lifeState);
return (LifeState != LIFE_ALIVE);
}
bool CBaseEntity::IsVisible(CBaseEntity* pLocalEntity)
{
if (!pLocalEntity->IsValid())
return false;
Vector vSrcOrigin = pLocalEntity->GetEyePosition();
if (vSrcOrigin.IsZero() || !vSrcOrigin.IsValid())
return false;
BYTE bHitBoxCheckVisible[6] = {
HITBOX_HEAD,
HITBOX_BODY,
HITBOX_RIGHT_FOOT,
HITBOX_LEFT_FOOT,
HITBOX_RIGHT_HAND,
HITBOX_LEFT_HAND,
};
CTraceFilter filter;
filter.pSkip = pLocalEntity;
for (int nHit = 0; nHit < 6; nHit++)
{
Vector vHitBox = GetHitboxPosition(bHitBoxCheckVisible[nHit]);
if (vHitBox.IsZero() || !vHitBox.IsValid())
continue;
trace_t tr;
Ray_t ray;
ray.Init(vSrcOrigin, vHitBox);
Interfaces::EngineTrace()->TraceRay(ray, PlayerVisibleMask, &filter, &tr);
if (tr.m_pEnt == (IClientEntity*)this && !tr.allsolid)
return true;
}
return false;
}
int CBaseEntity::GetIndex()
{
return *reinterpret_cast<int*>(uintptr_t(this) + 0x64);
}
int CBaseEntity::GetMoveType()
{
if (this != NULL && this != nullptr && (DWORD)this != 0xE)
{
return *(int*)((DWORD)this + (DWORD)0x25C);
}
}
bool CBaseEntity::HasHelmet()
{
return *(bool*)((DWORD)this + Offset::Entity::m_bHasHelmet);
}
bool CBaseEntity::HasDefuser()
{
return *(bool*)((DWORD)this + Offset::Entity::m_bHasDefuser);
}
int CBaseEntity::IsDefusing()
{
return *(bool*)((DWORD)this + (DWORD)Offset::Entity::m_bIsDefusing);
}
bool* CBaseEntity::IsSpotted()
{
return (bool*)((DWORD)this + Offset::Entity::m_bSpotted);
}
float CBaseEntity::GetFlashDuration() {
return *(float*)((DWORD)this + Offset::Entity::m_flFlashDuration);
}
int CBaseEntity::IsFlashed()
{
return GetFlashDuration() > 0 ? true : false;
}
int CBaseEntity::GetFovStart()
{
return *(PINT)((DWORD)this + Offset::Entity::m_iFOVStart);
}
int CBaseEntity::GetFlags()
{
return *(PINT)((DWORD)this + Offset::Entity::m_fFlags);
}
int CBaseEntity::GetHealth()
{
return *(PINT)((DWORD)this + Offset::Entity::m_iHealth);
}
int CBaseEntity::GetArmor()
{
return *(PINT)((DWORD)this + Offset::Entity::m_ArmorValue);
}
int CBaseEntity::GetTeam()
{
return *(PINT)((DWORD)this + Offset::Entity::m_iTeamNum);
}
short& CBaseWeapon::GetItemDefinitionIndex()
{
return *(short*)((DWORD)this + Offset::Entity::m_iItemDefinitionIndex);
}
void CBaseEntity::SetLowerBodyYaw(float value)
{
*reinterpret_cast<float*>(uintptr_t(this) + Offset::Entity::m_flLowerBodyYawTarget) = value;
}
float CBaseEntity::GetLowerBodyYaw()
{
return *(float*)((DWORD)this + Offset::Entity::m_flLowerBodyYawTarget);
}
float CBaseEntity::GetSimTime()
{
return *(float*)((DWORD)this + Offset::Entity::m_flSimulationTime);
}
int CBaseEntity::GetShotsFired()
{
return *(PINT)((DWORD)this + (DWORD)Offset::Entity::m_iShotsFired);
}
int CBaseEntity::GetIsScoped()
{
return *(bool*)((DWORD)this + (DWORD)Offset::Entity::m_bIsScoped);
}
int CBaseEntity::GetTickBase()
{
return *(PINT)((DWORD)this + (DWORD)Offset::Entity::m_nTickBase);
}
float CBaseEntity::m_hGroundEntity()
{
return *(float*)((DWORD)this + (DWORD)Offset::Entity::m_hGroundEntity);
}
int CBaseEntity::movetype()
{
return *(PINT)((DWORD)this + (DWORD)Offset::Entity::movetype);
}
float CBaseEntity::m_nWaterLevel()
{
return *(float*)((DWORD)this + (DWORD)Offset::Entity::m_nWaterLevel);
}
float CBaseEntity::GetLastShotTime()
{
return *(float*)((DWORD)this + (DWORD)Offset::Entity::m_fLastShotTime);
}
ObserverMode_t CBaseEntity::GetObserverMode()
{
return *(ObserverMode_t*)((DWORD)this + (DWORD)Offset::Entity::m_iObserverMode);
}
PVOID CBaseEntity::GetObserverTarget()
{
return (PVOID)*(PDWORD)((DWORD)this + (DWORD)Offset::Entity::m_hObserverTarget);
}
PVOID CBaseEntity::GetActiveWeapon()
{
return (PVOID)((DWORD)this + (DWORD)Offset::Entity::m_hActiveWeapon);
}
CBaseWeapon* CBaseEntity::GetBaseWeapon()
{
return (CBaseWeapon*)Interfaces::EntityList()->GetClientEntityFromHandle((PVOID)*(PDWORD)GetActiveWeapon());
}
UINT* CBaseEntity::GetWeapons()
{
// DT_BasePlayer -> m_hMyWeapons
return (UINT*)((DWORD)this + Offset::Entity::m_hMyWeapons);
}
UINT* CBaseEntity::GetWearables()
{
return (UINT*)((DWORD)this + Offset::Entity::m_hMyWearables);
}
CBaseViewModel* CBaseEntity::GetViewModel()
{
// DT_BasePlayer -> m_hViewModel
return (CBaseViewModel*)Interfaces::EntityList()->GetClientEntityFromHandle((PVOID)*(PDWORD)((DWORD)this + Offset::Entity::m_hViewModel));
}
Vector CBaseEntity::GetOrigin()
{
return *(Vector*)((DWORD)this + Offset::Entity::m_vecOrigin);
}
Vector* CBaseEntity::GetVAngles()
{
return (Vector*)((uintptr_t)this + Offset::Entity::deadflag + 0x4);
}
Vector CBaseEntity::GetAimPunchAngle()
{
return *(Vector*)((DWORD)this + Offset::Entity::m_aimPunchAngle);
}
Vector CBaseEntity::GetViewPunchAngle()
{
return *(Vector*)((DWORD)this + Offset::Entity::m_viewPunchAngle);
}
Vector CBaseEntity::GetVelocity()
{
return *(Vector*)((DWORD)this + Offset::Entity::m_vecVelocity);
}
Vector CBaseEntity::GetViewOffset()
{
return *(Vector*)((DWORD)this + Offset::Entity::m_vecViewOffset);
}
Vector CBaseEntity::GetEyePosition()
{
return GetRenderOrigin() + GetViewOffset();
}
int CBaseEntity::GetSequenceActivity(int sequence)
{
const auto model = GetModel();
if (!model)
return -1;
const auto hdr = Interfaces::ModelInfo()->GetStudioModel(model);
if (!hdr)
return -1;
static auto offset = (DWORD)CSX::Memory::FindPattern("client_panorama.dll", "55 8B EC 53 8B 5D 08 56 8B F1 83");
static auto GetSequenceActivity = reinterpret_cast<int(__fastcall*)(void*, SDK::studiohdr_t*, int)>(offset);
return GetSequenceActivity(this, hdr, sequence);
}
QAngle CBaseEntity::GetEyeAngles()
{
return *reinterpret_cast<QAngle*>((DWORD)this + Offset::Entity::m_angEyeAngles);
}
CAnimationLayer *CBaseEntity::GetAnimOverlay()
{
return *(CAnimationLayer**)((DWORD)this + Offset::Entity::animlayer);
}
bool CBaseWeapon::IsKnife()
{
if (!this)
return false;
switch (this->GetItemDefinitionIndex())
{
case WEAPON_KNIFE:
case WEAPON_KNIFE_T:
case WEAPON_KNIFE_GUT:
case WEAPON_KNIFE_FLIP:
case WEAPON_KNIFE_M9_BAYONET:
case WEAPON_KNIFE_KARAMBIT:
case WEAPON_KNIFE_TACTICAL:
case WEAPON_KNIFE_BUTTERFLY:
case WEAPON_KNIFE_SURVIVAL_BOWIE:
case WEAPON_KNIFE_FALCHION:
case WEAPON_KNIFE_PUSH:
return true;
default:
return false;
}
}
studiohdr_t* CBaseEntity::GetStudioModel()
{
const model_t* model = nullptr;
model = GetModel();
if (!model)
return nullptr;
studiohdr_t* pStudioModel = Interfaces::ModelInfo()->GetStudioModel(model);
if (!pStudioModel)
return nullptr;
return pStudioModel;
}
mstudiobone_t* CBaseEntity::GetBone(int nBone)
{
mstudiobone_t* pBoneBox = nullptr;
studiohdr_t* pStudioModel = GetStudioModel();
if (!pStudioModel)
return pBoneBox;
mstudiobone_t* pBone = pStudioModel->pBone(nBone);
if (!pBone)
return nullptr;
return pBone;
}
int CBaseEntity::GetHitboxSet_()
{
return *(int*)((DWORD)this + Offset::Entity::m_nHitboxSet);
}
mstudiobbox_t* CBaseEntity::GetHitBox(int nHitbox)
{
if (nHitbox < 0 || nHitbox >= HITBOX_MAX)
return nullptr;
mstudiohitboxset_t* pHitboxSet = nullptr;
mstudiobbox_t* pHitboxBox = nullptr;
pHitboxSet = GetHitBoxSet();
if (!pHitboxSet)
return pHitboxBox;
pHitboxBox = pHitboxSet->pHitbox(nHitbox);
if (!pHitboxBox)
return nullptr;
return pHitboxBox;
}
matrix3x4_t CBaseEntity::GetBoneMatrix(int BoneID)
{
matrix3x4_t matrix;
auto offset = *reinterpret_cast<uintptr_t*>(uintptr_t(this) + Offset::Entity::m_dwBoneMatrix);
if (offset)
matrix = *reinterpret_cast<matrix3x4_t*>(offset + 0x30 * BoneID);
return matrix;
}
void CBaseEntity::FixSetupBones(matrix3x4_t *Matrix) {
static int m_fFlags = g_NetVar.GetOffset("DT_BasePlayer", "m_fFlags");
static int m_nForceBone = g_NetVar.GetOffset("DT_BaseAnimating", "m_nForceBone");
if (this == LocalPlayer)
{
const auto Backup = *(int*)(uintptr_t(this) + ptrdiff_t(0x272));
*(int*)(uintptr_t(this) + ptrdiff_t(0x272)) = -1;
SetupBones(Matrix, 126, 0x00000100 | 0x200, Interfaces::GlobalVars()->curtime);
*(int*)(uintptr_t(this) + ptrdiff_t(0x272)) = Backup;
}
else
{
*reinterpret_cast<int*>(uintptr_t(this) + 0xA30) = Interfaces::GlobalVars()->framecount;
*reinterpret_cast<int*>(uintptr_t(this) + 0xA28) = 0;
const auto Backup = *(int*)(uintptr_t(this) + ptrdiff_t(0x272));
*(int*)(uintptr_t(this) + ptrdiff_t(0x272)) = -1;
SetupBones(Matrix, 126, 0x00000100 | 0x200, Interfaces::GlobalVars()->curtime);
*(int*)(uintptr_t(this) + ptrdiff_t(0x272)) = Backup;
}
}
float CBaseEntity::FireRate()
{
auto weapon = (CBaseWeapon*)Interfaces::EntityList()->GetClientEntityFromHandle(LocalPlayer->GetActiveWeapon());
if (!LocalPlayer)
return 0.f;
if (LocalPlayer->IsDead())
return 0.f;
if (weapon->IsKnife())
return 0.f;
if (!weapon)
return false;
std::string WeaponName = weapon->GetName();
if (WeaponName == "weapon_glock")
return 0.15f;
else if (WeaponName == "weapon_hkp2000")
return 0.169f;
else if (WeaponName == "weapon_p250")//the cz and p250 have the same name idky same with other guns
return 0.15f;
else if (WeaponName == "weapon_tec9")
return 0.12f;
else if (WeaponName == "weapon_elite")
return 0.12f;
else if (WeaponName == "weapon_fiveseven")
return 0.15f;
else if (WeaponName == "weapon_deagle")
return 0.224f;
else if (WeaponName == "weapon_nova")
return 0.882f;
else if (WeaponName == "weapon_sawedoff")
return 0.845f;
else if (WeaponName == "weapon_mag7")
return 0.845f;
else if (WeaponName == "weapon_xm1014")
return 0.35f;
else if (WeaponName == "weapon_mac10")
return 0.075f;
else if (WeaponName == "weapon_ump45")
return 0.089f;
else if (WeaponName == "weapon_mp9")
return 0.070f;
else if (WeaponName == "weapon_bizon")
return 0.08f;
else if (WeaponName == "weapon_mp7")
return 0.08f;
else if (WeaponName == "weapon_p90")
return 0.070f;
else if (WeaponName == "weapon_galilar")
return 0.089f;
else if (WeaponName == "weapon_ak47")
return 0.1f;
else if (WeaponName == "weapon_sg556")
return 0.089f;
else if (WeaponName == "weapon_m4a1")
return 0.089f;
else if (WeaponName == "weapon_aug")
return 0.089f;
else if (WeaponName == "weapon_m249")
return 0.08f;
else if (WeaponName == "weapon_negev")
return 0.0008f;
else if (WeaponName == "weapon_ssg08")
return 1.25f;
else if (WeaponName == "weapon_awp")
return 1.463f;
else if (WeaponName == "weapon_g3sg1")
return 0.25f;
else if (WeaponName == "weapon_scar20")
return 0.25f;
else if (WeaponName == "weapon_mp5sd")
return 0.08f;
else
return .0f;
}
mstudiohitboxset_t* CBaseEntity::GetHitBoxSet()
{
studiohdr_t* pStudioModel = nullptr;
mstudiohitboxset_t* pHitboxSet = nullptr;
pStudioModel = GetStudioModel();
if (!pStudioModel)
return pHitboxSet;
pHitboxSet = pStudioModel->pHitboxSet(0);
if (!pHitboxSet)
return nullptr;
return pHitboxSet;
}
Vector CBaseEntity::GetHitboxPosition(int Hitbox, matrix3x4_t *Matrix, float *Radius)
{
mstudiobbox_t* hitbox = GetHitBox(Hitbox);
if (hitbox)
{
Vector vMin, vMax, vCenter, sCenter;
VectorTransform(hitbox->m_vBbmin, Matrix[hitbox->m_Bone], vMin);
VectorTransform(hitbox->m_vBbmax, Matrix[hitbox->m_Bone], vMax);
vCenter = (vMin + vMax) * 0.5;
*Radius = hitbox->m_flRadius;
return vCenter;
}
return Vector(0, 0, 0);
}
Vector CBaseEntity::GetHitboxPosition(int Hitbox, matrix3x4_t *Matrix)
{
mstudiobbox_t* hitbox = GetHitBox(Hitbox);
if (hitbox)
{
Vector vMin, vMax, vCenter, sCenter;
VectorTransform(hitbox->m_vBbmin, Matrix[hitbox->m_Bone], vMin);
VectorTransform(hitbox->m_vBbmax, Matrix[hitbox->m_Bone], vMax);
vCenter = (vMin + vMax) * 0.5;
return vCenter;
}
return Vector(0, 0, 0);
}
Vector CBaseEntity::GetBonePosition(int HitboxID)
{
matrix3x4_t matrix[MAXSTUDIOBONES];
if (SetupBones(matrix, 128, BONE_USED_BY_HITBOX, GetTickCount64()))
{
return Vector(matrix[HitboxID][0][3], matrix[HitboxID][1][3], matrix[HitboxID][2][3]);
}
return Vector(0, 0, 0);
}
Vector CBaseEntity::GetHitboxPosition(int nHitbox)
{
matrix3x4_t MatrixArray[MAXSTUDIOBONES];
Vector vRet, vMin, vMax;
vRet = Vector(0, 0, 0);
mstudiobbox_t* pHitboxBox = GetHitBox(nHitbox);
if (!pHitboxBox || !IsValid())
return vRet;
if (!SetupBones(MatrixArray, MAXSTUDIOBONES, BONE_USED_BY_HITBOX, 0/*Interfaces::GlobalVars()->curtime*/))
return vRet;
if (!pHitboxBox->m_Bone || !pHitboxBox->m_vBbmin.IsValid() || !pHitboxBox->m_vBbmax.IsValid())
return vRet;
VectorTransform(pHitboxBox->m_vBbmin, MatrixArray[pHitboxBox->m_Bone], vMin);
VectorTransform(pHitboxBox->m_vBbmax, MatrixArray[pHitboxBox->m_Bone], vMax);
vRet = (vMin + vMax) * 0.5f;
return vRet;
}
int CBaseViewModel::GetModelIndex()
{
// DT_BaseViewModel -> m_nModelIndex
return *(int*)((DWORD)this + Offset::Entity::m_nModelIndex);
}
int& CBaseWeapon::GetWeaponID()
{
return *(int*)((DWORD)this + Offset::Entity::m_iWeaponID);
}
bool CBaseWeapon::IsAK47()
{
if (!this)
return false;
switch (this->GetItemDefinitionIndex())
{
case WEAPON_AK47:
return true;
default:
return false;
}
}
bool CBaseWeapon::IsAWP()
{
if (!this)
return false;
switch (this->GetItemDefinitionIndex())
{
case WEAPON_AWP:
return true;
default:
return false;
}
}
bool CBaseWeapon::IsGlock()
{
if (!this)
return false;
switch (this->GetItemDefinitionIndex())
{
case WEAPON_GLOCK:
return true;
default:
return false;
}
}
bool CBaseWeapon::IsM4A4()
{
if (!this)
return false;
switch (this->GetItemDefinitionIndex())
{
case WEAPON_M4A4:
return true;
default:
return false;
}
}
bool CBaseWeapon::IsM4A1S()
{
if (!this)
return false;
switch (this->GetItemDefinitionIndex())
{
case WEAPON_M4A1_SILENCER:
return true;
default:
return false;
}
}
short CBaseWeapon::GetKnifeDefinitionIndex(short iKnifeID)
{
switch (iKnifeID)
{
case 0:
return WEAPON_KNIFE_BAYONET;
case 1:
return WEAPON_KNIFE_FLIP;
case 2:
return WEAPON_KNIFE_GUT;
case 3:
return WEAPON_KNIFE_KARAMBIT;
case 4:
return WEAPON_KNIFE_M9_BAYONET;
case 5:
return WEAPON_KNIFE_FALCHION;
case 6:
return WEAPON_KNIFE_BUTTERFLY;
case 7:
return WEAPON_KNIFE_TACTICAL;
case 8:
return WEAPON_KNIFE_PUSH;
case 9:
return WEAPON_KNIFE_NAVAJA;
case 10:
return WEAPON_KNIFE_URSUS;
case 11:
return WEAPON_KNIFE_STILETTO;
default: return -1;
}
}
bool CBaseWeapon::IsGun()
{
if (!this)
return false;
int id = this->GetWeaponID();
//If your aimbot is broken, this is the reason. Just an FYI.
switch (id)
{
case WEAPON_DEAGLE:
case WEAPON_ELITE:
case WEAPON_FIVESEVEN:
case WEAPON_GLOCK:
case WEAPON_AK47:
case WEAPON_AUG:
case WEAPON_AWP:
case WEAPON_FAMAS:
case WEAPON_G3SG1:
case WEAPON_GALILAR:
case WEAPON_M249:
case WEAPON_M4A4:
case WEAPON_MAC10:
case WEAPON_P90:
case WEAPON_UMP45:
case WEAPON_XM1014:
case WEAPON_BIZON:
case WEAPON_MAG7:
case WEAPON_NEGEV:
case WEAPON_SAWEDOFF:
case WEAPON_TEC9:
return true;
case WEAPON_TASER:
return false;
case WEAPON_HKP2000:
case WEAPON_MP7:
case WEAPON_MP9:
case WEAPON_NOVA:
case WEAPON_P250:
case WEAPON_SCAR20:
case WEAPON_SG553:
case WEAPON_SSG08:
return true;
case WEAPON_KNIFE:
case WEAPON_FLASHBANG:
case WEAPON_HEGRENADE:
case WEAPON_SMOKEGRENADE:
case WEAPON_MOLOTOV:
case WEAPON_DECOY:
case WEAPON_INCGRENADE:
case WEAPON_C4:
case WEAPON_KNIFE_T:
return false;
case WEAPON_M4A1_SILENCER:
case WEAPON_USP_SILENCER:
case WEAPON_CZ75A:
case WEAPON_REVOLVER:
return true;
default:
return false;
}
}
void CBaseViewModel::SetModelIndex(int nModelIndex)
{
VirtualFn(void)(PVOID, int);
GetMethod< OriginalFn >(this, 75)(this, nModelIndex);
}
void CBaseViewModel::SetWeaponModel(const char* Filename, IClientEntity* Weapon)
{
typedef void(__thiscall* SetWeaponModelFn)(void*, const char*, IClientEntity*);
return GetMethod<SetWeaponModelFn>(this, 242)(this, Filename, Weapon);
}
DWORD CBaseViewModel::GetOwner()
{
// DT_BaseViewModel -> m_hOwner
return *(PDWORD)((DWORD)this + Offset::Entity::m_hOwner);
}
Vector* CBaseEntity::GetEyeAnglesPtr()
{
return reinterpret_cast<Vector*>((DWORD)this + Offset::Entity::m_angEyeAngles);
}
int* CBaseEntity::m_hMyWeapons()
{
return reinterpret_cast<int*>(DWORD(this) + Offset::Entity::m_hWeapon);
}
DWORD CBaseViewModel::GetWeapon()
{
// DT_BaseViewModel -> m_hWeapon
return *(PDWORD)((DWORD)this + Offset::Entity::m_hWeapon);
}
void CBaseEntity::SetAngle2(Vector wantedang) {
typedef void(__thiscall* oSetAngle)(void*, const Vector &);
static oSetAngle _SetAngle = (oSetAngle)((uintptr_t)CSX::Memory::FindPattern("client_panorama.dll", "55 8B EC 83 E4 F8 83 EC 64 53 56 57 8B F1"));
_SetAngle(this, wantedang);
}
int CBaseEntity::DrawModel2(int flags, uint8_t alpha)
{
VirtualFn(void)(PVOID, int);
void* pRenderable = (void*)(this + 0x4);
using fn = int(__thiscall*)(void*, int, uint8_t);
return GetMethod<fn>(pRenderable, 9)(pRenderable, flags, alpha);
}
void CBaseEntity::SetAbsAngles(Vector angles)
{
using Fn = void(__thiscall*)(CBaseEntity*, const Vector& angles);
static Fn AbsAngles = (Fn)(CSX::Memory::FindPattern("client_panorama.dll", (BYTE*)"\x55\x8B\xEC\x83\xE4\xF8\x83\xEC\x64\x53\x56\x57\x8B\xF1\xE8", "xxxxxxxxxxxxxxx"));
AbsAngles(this, angles);
}
void CBaseEntity::SetAbsOrigin(Vector ArgOrigin)
{
using Fn = void(__thiscall*)(CBaseEntity*, const Vector &origin);
static Fn func;
if (!func)
func = (Fn)(CSX::Memory::FindPattern("client_panorama.dll", "\x55\x8B\xEC\x83\xE4\xF8\x51\x53\x56\x57\x8B\xF1\xE8\x00\x00"));
func(this, ArgOrigin);
}
model_t* CBaseEntity::GetModel2()
{
return *(model_t**)((DWORD)this + 0x6C);
}
// CBaseWeapon* CBaseEntity::GetWeapon()
// {
// return (CBaseWeapon*)Interfaces::EntityList()->GetClientEntityFromHandle(LocalPlayer->GetActiveWeapon());
// }
CCSGOAnimState* CBaseEntity::GetAnimState()
{
return *reinterpret_cast<CCSGOAnimState**>(uintptr_t(this) + Offset::Entity::animstate);
}
CAnimState* CBaseEntity::GetAnimState2()
{
return *reinterpret_cast<CAnimState**>(uintptr_t(this) + Offset::Entity::animstate);
}
bool CBaseWeapon::IsGrenade()
{
if (!this)
return false;
switch (this->GetItemDefinitionIndex())
{
case WEAPON_SMOKEGRENADE:
case WEAPON_HEGRENADE:
case WEAPON_INCGRENADE:
case WEAPON_FLASHBANG:
case WEAPON_MOLOTOV:
case WEAPON_DECOY:
return true;
default:
return false;
}
}
bool CBaseEntity::SetupBones2(matrix3x4_t* pBoneToWorldOut, int nMaxBones, int boneMask, float currentTime)
{
__asm
{
mov edi, this
lea ecx, dword ptr ds : [edi + 0x4]
mov edx, dword ptr ds : [ecx]
push currentTime
push boneMask
push nMaxBones
push pBoneToWorldOut
call dword ptr ds : [edx + 0x34]
}
}
int CBaseEntity::GetBoneByName(const char* boneName)
{
studiohdr_t* pStudioModel = Interfaces::ModelInfo()->GetStudioModel(this->GetModel2());
if (!pStudioModel)
return -1;
matrix3x4_t pBoneToWorldOut[128];
if (!this->SetupBones(pBoneToWorldOut, 128, 256, 0))
return -1;
for (int i = 0; i < pStudioModel->numbones; i++)
{
mstudiobone_t *pBone = pStudioModel->pBone(i);
if (!pBone)
continue;
if (pBone->pszName() && strcmp(pBone->pszName(), boneName) == 0)
return i;
}
return -1;
}
template< typename t = float >
t minimum(const t &a, const t &b) {
// check type.
static_assert(std::is_arithmetic< t >::value, "Math::min only supports integral types.");
return (t)_mm_cvtss_f32(
_mm_min_ss(_mm_set_ss((float)a),
_mm_set_ss((float)b))
);
}
// sse max.
template< typename t = float >
t maximum(const t &a, const t &b) {
// check type.
static_assert(std::is_arithmetic< t >::value, "Math::max only supports integral types.");
return (t)_mm_cvtss_f32(
_mm_max_ss(_mm_set_ss((float)a),
_mm_set_ss((float)b))
);
}
float CBaseEntity::getmaxdesync()
{
if (!this)
return 0.f;
auto anim_state = this->GetAnimState2();
if (!anim_state)
return 0.f;
if (!anim_state)
return 0.f;
float duck_amount = anim_state->duck_amount;
float speed_fraction = maximum< float >(0, minimum< float >(anim_state->feet_speed_forwards_or_sideways, 1));
float speed_factor = maximum< float >(0, minimum< float >(1, anim_state->feet_speed_unknown_forwards_or_sideways));
float yaw_modifier = (((anim_state->stop_to_full_running_fraction * -0.3f) - 0.2f) * speed_fraction) + 1.0f;
if (duck_amount > 0.f) {
yaw_modifier += ((duck_amount * speed_factor) * (0.5f - yaw_modifier));
}
return anim_state->velocity_subtract_y * yaw_modifier;
}
float& CBaseEntity::m_flAbsRotation() {
return *(float*)((uintptr_t)this + 0x80);
}
float CBaseEntity::get_max_desync_delta(CBaseEntity *local) {
uintptr_t animstate = uintptr_t(local->GetAnimState());
float duckammount = *(float *)(animstate + 0xA4);
float speedfraction = max(0, min(*reinterpret_cast<float*>(animstate + 0xF8), 1));
float speedfactor = max(0, min(1, *reinterpret_cast<float*> (animstate + 0xFC)));
float unk1 = ((*reinterpret_cast<float*> (animstate + 0x11C) * -0.30000001) - 0.19999999) * speedfraction;
float unk2 = unk1 + 1.1f;
float unk3;
if (duckammount > 0) {
unk2 += ((duckammount * speedfactor) * (0.5f - unk2));
}
unk3 = *(float *)(animstate + 0x334) * unk2;
return unk3;
}
void CBaseEntity::ClientAnimations(bool value)
{
*reinterpret_cast<bool*>(uintptr_t(this) + Offset::Entity::m_bClientSideAnimation) = value;
}
float CBaseEntity::GetNextAttack()
{
return *reinterpret_cast<float*>(uint32_t(this) + Offset::Entity::m_flNextAttack);
}
int CBaseEntity::GetActiveWeaponIndex()
{
return *reinterpret_cast<int*>(uintptr_t(this) + Offset::Entity::m_hActiveWeapon) & 0xFFF;
}
}
| [
"[email protected]"
] | |
d40957dcfb9e81aa683f6a7ff635f613834a0276 | ac95321159dd14d342e2a83e15ce136e859b8906 | /test/core/api/client/http_client.hpp | 0b3d2172825a5c95bc86741de7e100921e235026 | [
"Apache-2.0"
] | permissive | blockspacer/kagome | 63003fc497c50da8e329c9e9029a08487ad7b6ab | 693c981dab965fa1d4733ed285a2561e2d507abe | refs/heads/master | 2022-07-16T16:14:59.588847 | 2020-05-13T11:07:06 | 2020-05-13T11:07:06 | 263,882,710 | 0 | 1 | Apache-2.0 | 2020-05-14T10:20:32 | 2020-05-14T10:20:31 | null | UTF-8 | C++ | false | false | 2,587 | hpp | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef KAGOME_TEST_CORE_API_CLIENT_HTTP_CLIENT_HPP
#define KAGOME_TEST_CORE_API_CLIENT_HTTP_CLIENT_HPP
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include "outcome/outcome.hpp"
namespace test {
enum class HttpClientError {
CONNECTION_FAILED = 1,
HTTP_ERROR,
NETWORK_ERROR
};
/**
* Simple synchronous client for api service
* it allows making synchronous http queries to api service
*/
class HttpClient {
using Socket = boost::asio::ip::tcp::socket;
using FlatBuffer = boost::beast::flat_buffer;
using HttpField = boost::beast::http::field;
using HttpError = boost::beast::http::error;
using HttpMethods = boost::beast::http::verb;
using StringBody = boost::beast::http::string_body;
using DynamicBody = boost::beast::http::dynamic_body;
using QueryCallback = void(outcome::result<std::string>);
using Context = boost::asio::io_context;
template <typename Body>
using HttpRequest = boost::beast::http::request<Body>;
template <typename Body>
using HttpResponse = boost::beast::http::response<Body>;
template <class Body>
using RequestParser = boost::beast::http::request_parser<Body>;
static constexpr auto kUserAgent = "Kagome test api client 0.1";
public:
/**
* @param context reference to io context instance
*/
explicit HttpClient(Context &context) : stream_(context) {}
HttpClient(const HttpClient &other) = delete;
HttpClient &operator=(const HttpClient &other) = delete;
HttpClient(HttpClient &&other) noexcept = delete;
HttpClient &operator=(HttpClient &&other) noexcept = delete;
~HttpClient();
/**
* @brief connects to endpoint
* @param endpoint address to connect
* @return error code as outcome::result if failed or success
*/
outcome::result<void> connect(boost::asio::ip::tcp::endpoint endpoint);
/**
* @brief make synchronous query to api service
* @param message api query message
* @param callback instructions to execute on completion
*/
void query(std::string_view message,
std::function<void(outcome::result<std::string>)> &&callback);
/**
* @brief disconnects stream
*/
void disconnect();
private:
boost::beast::tcp_stream stream_;
boost::asio::ip::tcp::endpoint endpoint_;
};
} // namespace test
OUTCOME_HPP_DECLARE_ERROR(test, HttpClientError)
#endif // KAGOME_TEST_CORE_API_CLIENT_HTTP_CLIENT_HPP
| [
"[email protected]"
] | |
cadea9d2b63dd7d8313f3c83b7e46e99ee945337 | 2c48057473142f2bcaf88bcdbf1e868241a47bbd | /opengl-tutorial-qt/00_opengl_window/window.cpp | 2b311eaa3f53a0e9ec95dc1a49bc9965dd3d61b7 | [] | no_license | maze516/opengl-playground | 96939e6b1ac97094de0bec5fad1679d422edaacd | 37ed875d6e0134512c4db6d3cf95e1e27a46c8e4 | refs/heads/master | 2021-05-26T03:34:31.530169 | 2018-05-13T08:58:11 | 2018-05-13T08:58:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,565 | cpp | #include "window.h"
#include <QDebug>
Window::Window(QSurfaceFormat::RenderableType type,
int majorVersion, int minorVersion) : QOpenGLWindow{}
{
/*
* Set OpenGL version information.
* It has to be done before calling show()
*/
QSurfaceFormat format;
format.setProfile(QSurfaceFormat::CoreProfile);
format.setRenderableType(type);
format.setVersion(majorVersion, minorVersion);
format.setSamples(4);
setFormat(format);
}
void Window::initializeGL()
{
initializeOpenGLFunctions();
printOpenGLVersion();
QColor background {"#95e1d3"};
glClearColor(
static_cast<GLclampf>(background.redF()),
static_cast<GLclampf>(background.greenF()),
static_cast<GLclampf>(background.blueF()),
static_cast<GLclampf>(background.alphaF()));
}
void Window::resizeGL(int width, int height)
{
Q_UNUSED(width)
Q_UNUSED(height)
}
void Window::paintGL()
{
glClear(GL_COLOR_BUFFER_BIT);
}
void Window::printOpenGLVersion()
{
QString glType, glVersion, glProfile;
glType = context()->isOpenGLES() ? "OpenGL ES" : "OpenGL";
glVersion = reinterpret_cast<const char*>(glGetString(GL_VERSION));
// Get profile information
#define CASE(c) case QSurfaceFormat::c: glProfile = #c; break
switch (format().profile()) {
CASE(NoProfile);
CASE(CoreProfile);
CASE(CompatibilityProfile);
}
qDebug().noquote().nospace() << "Loaded: " <<
glType << " " << glVersion << " (" <<
glProfile << ")";
}
| [
"[email protected]"
] | |
9a13e04d58e68468ad1eb08968422523b8f86275 | 544206531f578e0502e50d798d73be3dd7e1a919 | /字符串/后缀数组/[JSOI2007]字符加密.cpp | a46b48e0d6821cd755d4df9a18cafe7043ae8061 | [] | no_license | Wankupi/cpp | 3d0e831826ad6a2ba674427764fcf688cbc00431 | ac9d6fe75fe876fdd03d21510415ebb0de0dd463 | refs/heads/master | 2023-04-05T22:40:15.960734 | 2023-03-31T12:21:13 | 2023-03-31T12:21:13 | 217,510,572 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,113 | cpp | #include <cstdio>
#include <cstring>
#include <algorithm>
const int maxn = 200007;
int n = 0, N = 0, m = 0;
char s[200007];
int sa[maxn], A[maxn], B[maxn], t[maxn];
int *rank = A, *tp = B;
inline void Qsort() {
for (int i = 0; i <= m; ++i) t[i] = 0;
for (int i = 1; i <= N; ++i) ++t[rank[i]];
for (int i = 1; i <= m; ++i) t[i] += t[i - 1];
for (int i = N; i >= 1; --i) sa[t[rank[tp[i]]]--] = tp[i];
}
void SurffixSort() {
m = 256;
for (int i = 1; i <= N; ++i) rank[i] = s[i], tp[i] = i;
Qsort();
for (int len = 1, p = 0; len < N && p < N; m = p, len <<= 1) {
p = 0;
for (int i = 1; i <= len; ++i) tp[++p] = N - len + i;
for (int i = 1; i <= N; ++i) if (sa[i] > len) tp[++p] = sa[i] - len;
Qsort();
tp[sa[1]] = p = 1;
for (int i = 2; i <= N; ++i) tp[sa[i]] = (rank[sa[i - 1]] == rank[sa[i]] && rank[sa[i - 1] + len] == rank[sa[i] + len] ? p : ++p);
std::swap(rank, tp);
}
}
int main() {
scanf("%s", s + 1);
n = strlen(s + 1);
for (int i = 1; i <= n; ++i)
s[i + n] = s[i];
N = 2 * n;
SurffixSort();
for (int i = 1; i <= N; ++i) if (sa[i] <= n) putchar(s[sa[i] + n - 1]);
return 0;
}
| [
"[email protected]"
] | |
48fa9b6143005f63c775f9587a9738470e5b342f | 5bb55ef3638f8f5609e07f689c1087d8c28e4f00 | /3257孪生兄弟,c.cpp | f38193955b38f6c4c350a6dd228b4e8ba9664bc9 | [] | no_license | xihaban/C- | 6bb11e1ac1d2965cf1c093cd5a8d4d195ea2d108 | 76b3c824e9ec288e6ce321b30e4b70f178f6c4b5 | refs/heads/master | 2020-03-28T14:27:13.119766 | 2018-09-12T13:49:03 | 2018-09-12T13:49:03 | 148,487,862 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 138 | cpp | #include<stdio.h>
main()
{
double a,b;
while(scanf("%lf %lf",&a,&b)!='\n'){
if(a==b)
printf("YES\n");
else printf("NO\n");
}
} | [
"[email protected]"
] | |
be0f0f90cb7a2f0d214ec851c5fd154aa2ddb710 | fc056b2e63f559087240fed1a77461eb72b2bf8e | /src/server/gameserver/skill/Evade.h | 3de145c8242ef089614c13b8e007d0499fda4e3e | [] | no_license | opendarkeden/server | 0bd3c59b837b1bd6e8c52c32ed6199ceb9fbee38 | 3c2054f5d9e16196fc32db70b237141d4a9738d1 | refs/heads/master | 2023-02-18T20:21:30.398896 | 2023-02-15T16:42:07 | 2023-02-15T16:42:07 | 42,562,951 | 48 | 37 | null | 2023-02-15T16:42:10 | 2015-09-16T03:42:35 | C++ | UTF-8 | C++ | false | false | 980 | h | //////////////////////////////////////////////////////////////////////////////
// Filename : Evade.h
// Written By :
// Description :
//////////////////////////////////////////////////////////////////////////////
#ifndef __SKILL_EVADE_HANDLER_H__
#define __SKILL_EVADE_HANDLER_H__
#include "SkillHandler.h"
//////////////////////////////////////////////////////////////////////////////
// class Evade;
//////////////////////////////////////////////////////////////////////////////
class Evade : public SkillHandler
{
public:
Evade() throw() {}
~Evade() throw() {}
public:
string getSkillHandlerName() const throw() { return "Evade"; }
SkillType_t getSkillType() const throw() { return SKILL_EVADE; }
void execute(Ousters* pOusters, OustersSkillSlot* pOustersSkillSlot, CEffectID_t CEffectID) ;
void computeOutput(const SkillInput& input, SkillOutput& output);
};
// global variable declaration
extern Evade g_Evade;
#endif // __SKILL_EVADE_HANDLER_H__
| [
"[email protected]"
] | |
481b30704d4380c67999d525905305f8e21f5ee9 | b71b8bd385c207dffda39d96c7bee5f2ccce946c | /testcases/CWE762_Mismatched_Memory_Management_Routines/s01/CWE762_Mismatched_Memory_Management_Routines__delete_array_class_realloc_14.cpp | ad2f1b44927c5c420615a7fbb1a6643dd969974c | [] | 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,271 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_class_realloc_14.cpp
Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml
Template File: sources-sinks-14.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: 14 Control flow: if(globalFive==5) and if(globalFive!=5)
* */
#include "std_testcase.h"
namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_class_realloc_14
{
#ifndef OMITBAD
void bad()
{
TwoIntsClass * data;
/* Initialize data*/
data = NULL;
{
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (TwoIntsClass *)realloc(data, 100*sizeof(TwoIntsClass));
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 globalFive==5 to globalFive!=5 */
static void goodB2G1()
{
TwoIntsClass * data;
/* Initialize data*/
data = NULL;
{
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (TwoIntsClass *)realloc(data, 100*sizeof(TwoIntsClass));
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()
{
TwoIntsClass * data;
/* Initialize data*/
data = NULL;
{
data = NULL;
/* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */
data = (TwoIntsClass *)realloc(data, 100*sizeof(TwoIntsClass));
if (data == NULL) {exit(-1);}
}
{
/* FIX: Free memory using free() */
free(data);
}
}
/* goodG2B1() - use goodsource and badsink by changing the first globalFive==5 to globalFive!=5 */
static void goodG2B1()
{
TwoIntsClass * data;
/* Initialize data*/
data = NULL;
{
/* FIX: Allocate memory using new [] */
data = new TwoIntsClass[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()
{
TwoIntsClass * data;
/* Initialize data*/
data = NULL;
{
/* FIX: Allocate memory using new [] */
data = new TwoIntsClass[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_class_realloc_14; /* 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
| [
"[email protected]"
] | |
340b7afd07f2c6b15e91afabf6ad46264336ec34 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/3b/ee15dde88f12c9/main.cpp | 56a54137b498437603b45cea0ea299d344bb9b7f | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,955 | cpp | #include <iostream>
#include <string>
#include <algorithm>
#include <unordered_map>
#define ALPHA "Alpha"
#define BETA "Beta"
#define GAMMA "Gamma"
struct EnumValue
{
EnumValue(std::string _name): name(std::move(_name)), id(gid){++gid;}
std::string name;
int id;
// also provide implicit conversion operators to std::string and int
private:
static int gid;
};
int EnumValue::gid = 0;
class MyEnum
{
public:
static const EnumValue& Alpha;
static const EnumValue& Beta;
static const EnumValue& Gamma;
static const EnumValue& StringToEnumeration(std::string _in)
{
return enumerations.find(_in)->second;
}
static const EnumValue& IDToEnumeration(int _id)
{
auto iter = std::find_if(enumerations.cbegin(), enumerations.cend(),
[_id](const map_value_type& vt)
{
return vt.second.id == _id;
});
return iter->second;
}
static const size_t size()
{
return enumerations.size();
}
private:
typedef std::unordered_map<std::string, EnumValue> map_type ;
typedef map_type::value_type map_value_type ;
static const map_type enumerations;
};
const std::unordered_map<std::string, EnumValue> MyEnum::enumerations =
{
{ALPHA, EnumValue(ALPHA)},
{BETA, EnumValue(BETA)},
{GAMMA, EnumValue(GAMMA)}
};
const EnumValue& MyEnum::Alpha = enumerations.find(ALPHA)->second;
const EnumValue& MyEnum::Beta = enumerations.find(BETA)->second;
const EnumValue& MyEnum::Gamma = enumerations.find(GAMMA)->second;
int main()
{
std::cout << MyEnum::Alpha.name << std::endl; // Alpha
std::cout << MyEnum::Beta.name << std::endl; // Beta
std::cout << MyEnum::Gamma.name << std::endl; // Gamma
std::cout << MyEnum::StringToEnumeration(ALPHA).id << std::endl; //should give 0
std::cout << MyEnum::IDToEnumeration(0).name << std::endl; //should give "Alpha"
}
| [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
71f7edde5fad370e9c5ea587497a90de4ccd7159 | 526e72ebf67f34ef6631c904436e28c0fee52ef2 | /st/SunrinStone/SpriteManager.cpp | ffdc21c5d9936346450e5c2c7088314d3c5113ad | [] | no_license | willtriti03/sunrinStone | e503d8fe9a5ddaebb89a1e11742b2ab0b9f8e259 | 6a44593c825bd2c5d24bf1ec6a98241c1f8b1d67 | refs/heads/master | 2021-01-22T05:54:00.404759 | 2017-05-26T11:29:55 | 2017-05-26T11:29:55 | 92,504,306 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 366 | cpp | #include "stdafx.h"
#include "SpriteManager.h"
#include "Application.h"
SpriteManager::SpriteManager() : m_pSprite(NULL) {}
SpriteManager::~SpriteManager() {}
LPD3DXSPRITE SpriteManager::Sprite() {
return m_pSprite;
}
void SpriteManager::Initialize() {
D3DXCreateSprite(GameApp->GetDevice(), &m_pSprite);
}
void SpriteManager::Release() {
m_pSprite->Release();
} | [
"[email protected]"
] | |
295bf6bbb4a61cbc7cc6ed3ed4f80f42c325b271 | ad21749688f601f41794041b5108944290f97400 | /TUGAS 1. LUAS LINGKARAN.cpp | a5db1f648903f4dc52aa6e08d2332821278ec467 | [] | no_license | ekayuliaa11/luas-lingkaran | 8c8eaff9dc62f7c7c8f793825929aa0f097285dd | 6e1db482909083d50055994617858a26445a868c | refs/heads/master | 2020-04-11T17:31:57.450669 | 2019-01-02T15:32:33 | 2019-01-02T15:32:33 | 161,964,389 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 236 | cpp | #include <iostream>
using namespace std;
int main()
{
int r;
float phi=3.14,luas;
cout<<"masukan jari jari lingkaran:";
cin>>r;
luas=phi*r*r;
cout<<"luas lingkaran adalah "<<luas;
return 0;
}
| [
"[email protected]"
] | |
23dbd64a1ff06b12df321d6b11843253bb976dc6 | b5ed64237b9de164789a86e31cdbf9509879d344 | /v0/0015.cpp | 21f50c41d25fba3ab2a4ecdb9791c079e4c17bb7 | [] | no_license | giwa/aoj | cbf9a5bc37f81bbc6ad5180d83a495ef1e3a773d | f780f27cb8b0574275daf819020bc35f95afd671 | refs/heads/master | 2021-01-19T08:42:14.793830 | 2015-03-17T10:29:30 | 2015-03-17T10:29:30 | 31,995,602 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 903 | cpp | #include <iostream>
#include <algorithm>
#include <string>
using namespace std;
string add(string a, string b){
// cout << a << endl;
// cout << b << endl;
while(a.size() < b.size()) a.insert(0, "0");
while(b.size() < a.size()) b.insert(0, "0");
// cout << a << endl;
// cout << b << endl;
int n = a.size();
string res(n, ' ');
for (int i = n - 1, d = 0; i >= 0; --i){
int p = a[i] - '0';
int q = b[i] - '0';
int r = p + q + d;
d = r / 10;
res[i] = r % 10 + '0';
if (i == 0 && d != 0) res.insert(0, string(1, d + '0'));
// cout << res << endl;
}
return res;
}
int main(){
int Tc;
cin >> Tc;
while(Tc--) {
string a, b;
cin >> a >> b;
string tmp = add(a, b);
if(tmp.size() > 80) cout << "overflow" << endl;
else cout << tmp << endl;
}
return 0;
}
| [
"[email protected]"
] | |
2fe62a9f7e81de193ce4edd658d0984112985bc7 | 2bfd8c9d984c94830ba1fa7f5088083f8518f6ba | /src/test/coins_tests.cpp | 0ebad52a146ccd6420ac38083dd2da23892cf2b4 | [
"MIT"
] | permissive | SenatorJohnMcLaughlin/TestCoin | 8f493d9f07246b21b98d3c19f5f303417fafd166 | 732b4ece3aaf489709ef9231d845d3735bb8dab3 | refs/heads/master | 2021-04-14T09:52:46.878135 | 2020-03-22T20:50:35 | 2020-03-22T20:50:35 | 249,224,647 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 37,440 | cpp | // Copyright (c) 2014-2016 The Testcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "coins.h"
#include "script/standard.h"
#include "uint256.h"
#include "undo.h"
#include "utilstrencodings.h"
#include "test/test_testcoin.h"
#include "validation.h"
#include "consensus/validation.h"
#include <vector>
#include <map>
#include <boost/test/unit_test.hpp>
int ApplyTxInUndo(Coin&& undo, CCoinsViewCache& view, const COutPoint& out);
void UpdateCoins(const CTransaction& tx, CCoinsViewCache& inputs, CTxUndo &txundo, int nHeight);
namespace
{
//! equality test
bool operator==(const Coin &a, const Coin &b) {
// Empty Coin objects are always equal.
if (a.IsSpent() && b.IsSpent()) return true;
return a.fCoinBase == b.fCoinBase &&
a.nHeight == b.nHeight &&
a.out == b.out;
}
class CCoinsViewTest : public CCoinsView
{
uint256 hashBestBlock_;
std::map<COutPoint, Coin> map_;
public:
bool GetCoin(const COutPoint& outpoint, Coin& coin) const override
{
std::map<COutPoint, Coin>::const_iterator it = map_.find(outpoint);
if (it == map_.end()) {
return false;
}
coin = it->second;
if (coin.IsSpent() && InsecureRandBool() == 0) {
// Randomly return false in case of an empty entry.
return false;
}
return true;
}
uint256 GetBestBlock() const override { return hashBestBlock_; }
bool BatchWrite(CCoinsMap& mapCoins, const uint256& hashBlock) override
{
for (CCoinsMap::iterator it = mapCoins.begin(); it != mapCoins.end(); ) {
if (it->second.flags & CCoinsCacheEntry::DIRTY) {
// Same optimization used in CCoinsViewDB is to only write dirty entries.
map_[it->first] = it->second.coin;
if (it->second.coin.IsSpent() && InsecureRandRange(3) == 0) {
// Randomly delete empty entries on write.
map_.erase(it->first);
}
}
mapCoins.erase(it++);
}
if (!hashBlock.IsNull())
hashBestBlock_ = hashBlock;
return true;
}
};
class CCoinsViewCacheTest : public CCoinsViewCache
{
public:
CCoinsViewCacheTest(CCoinsView* _base) : CCoinsViewCache(_base) {}
void SelfTest() const
{
// Manually recompute the dynamic usage of the whole data, and compare it.
size_t ret = memusage::DynamicUsage(cacheCoins);
size_t count = 0;
for (CCoinsMap::iterator it = cacheCoins.begin(); it != cacheCoins.end(); it++) {
ret += it->second.coin.DynamicMemoryUsage();
++count;
}
BOOST_CHECK_EQUAL(GetCacheSize(), count);
BOOST_CHECK_EQUAL(DynamicMemoryUsage(), ret);
}
CCoinsMap& map() { return cacheCoins; }
size_t& usage() { return cachedCoinsUsage; }
};
} // namespace
BOOST_FIXTURE_TEST_SUITE(coins_tests, BasicTestingSetup)
static const unsigned int NUM_SIMULATION_ITERATIONS = 40000;
// This is a large randomized insert/remove simulation test on a variable-size
// stack of caches on top of CCoinsViewTest.
//
// It will randomly create/update/delete Coin entries to a tip of caches, with
// txids picked from a limited list of random 256-bit hashes. Occasionally, a
// new tip is added to the stack of caches, or the tip is flushed and removed.
//
// During the process, booleans are kept to make sure that the randomized
// operation hits all branches.
BOOST_AUTO_TEST_CASE(coins_cache_simulation_test)
{
// Various coverage trackers.
bool removed_all_caches = false;
bool reached_4_caches = false;
bool added_an_entry = false;
bool added_an_unspendable_entry = false;
bool removed_an_entry = false;
bool updated_an_entry = false;
bool found_an_entry = false;
bool missed_an_entry = false;
bool uncached_an_entry = false;
// A simple map to track what we expect the cache stack to represent.
std::map<COutPoint, Coin> result;
// The cache stack.
CCoinsViewTest base; // A CCoinsViewTest at the bottom.
std::vector<CCoinsViewCacheTest*> stack; // A stack of CCoinsViewCaches on top.
stack.push_back(new CCoinsViewCacheTest(&base)); // Start with one cache.
// Use a limited set of random transaction ids, so we do test overwriting entries.
std::vector<uint256> txids;
txids.resize(NUM_SIMULATION_ITERATIONS / 8);
for (unsigned int i = 0; i < txids.size(); i++) {
txids[i] = InsecureRand256();
}
for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {
// Do a random modification.
{
uint256 txid = txids[InsecureRandRange(txids.size())]; // txid we're going to modify in this iteration.
Coin& coin = result[COutPoint(txid, 0)];
// Determine whether to test HaveCoin before or after Access* (or both). As these functions
// can influence each other's behaviour by pulling things into the cache, all combinations
// are tested.
bool test_havecoin_before = InsecureRandBits(2) == 0;
bool test_havecoin_after = InsecureRandBits(2) == 0;
bool result_havecoin = test_havecoin_before ? stack.back()->HaveCoin(COutPoint(txid, 0)) : false;
const Coin& entry = (InsecureRandRange(500) == 0) ? AccessByTxid(*stack.back(), txid) : stack.back()->AccessCoin(COutPoint(txid, 0));
BOOST_CHECK(coin == entry);
BOOST_CHECK(!test_havecoin_before || result_havecoin == !entry.IsSpent());
if (test_havecoin_after) {
bool ret = stack.back()->HaveCoin(COutPoint(txid, 0));
BOOST_CHECK(ret == !entry.IsSpent());
}
if (InsecureRandRange(5) == 0 || coin.IsSpent()) {
Coin newcoin;
newcoin.out.nValue = InsecureRand32();
newcoin.nHeight = 1;
if (InsecureRandRange(16) == 0 && coin.IsSpent()) {
newcoin.out.scriptPubKey.assign(1 + InsecureRandBits(6), OP_RETURN);
BOOST_CHECK(newcoin.out.scriptPubKey.IsUnspendable());
added_an_unspendable_entry = true;
} else {
newcoin.out.scriptPubKey.assign(InsecureRandBits(6), 0); // Random sizes so we can test memory usage accounting
(coin.IsSpent() ? added_an_entry : updated_an_entry) = true;
coin = newcoin;
}
stack.back()->AddCoin(COutPoint(txid, 0), std::move(newcoin), !coin.IsSpent() || InsecureRand32() & 1);
} else {
removed_an_entry = true;
coin.Clear();
stack.back()->SpendCoin(COutPoint(txid, 0));
}
}
// One every 10 iterations, remove a random entry from the cache
if (InsecureRandRange(10) == 0) {
COutPoint out(txids[InsecureRand32() % txids.size()], 0);
int cacheid = InsecureRand32() % stack.size();
stack[cacheid]->Uncache(out);
uncached_an_entry |= !stack[cacheid]->HaveCoinInCache(out);
}
// Once every 1000 iterations and at the end, verify the full cache.
if (InsecureRandRange(1000) == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
for (auto it = result.begin(); it != result.end(); it++) {
bool have = stack.back()->HaveCoin(it->first);
const Coin& coin = stack.back()->AccessCoin(it->first);
BOOST_CHECK(have == !coin.IsSpent());
BOOST_CHECK(coin == it->second);
if (coin.IsSpent()) {
missed_an_entry = true;
} else {
BOOST_CHECK(stack.back()->HaveCoinInCache(it->first));
found_an_entry = true;
}
}
for (const CCoinsViewCacheTest *test : stack) {
test->SelfTest();
}
}
if (InsecureRandRange(100) == 0) {
// Every 100 iterations, flush an intermediate cache
if (stack.size() > 1 && InsecureRandBool() == 0) {
unsigned int flushIndex = InsecureRandRange(stack.size() - 1);
stack[flushIndex]->Flush();
}
}
if (InsecureRandRange(100) == 0) {
// Every 100 iterations, change the cache stack.
if (stack.size() > 0 && InsecureRandBool() == 0) {
//Remove the top cache
stack.back()->Flush();
delete stack.back();
stack.pop_back();
}
if (stack.size() == 0 || (stack.size() < 4 && InsecureRandBool())) {
//Add a new cache
CCoinsView* tip = &base;
if (stack.size() > 0) {
tip = stack.back();
} else {
removed_all_caches = true;
}
stack.push_back(new CCoinsViewCacheTest(tip));
if (stack.size() == 4) {
reached_4_caches = true;
}
}
}
}
// Clean up the stack.
while (stack.size() > 0) {
delete stack.back();
stack.pop_back();
}
// Verify coverage.
BOOST_CHECK(removed_all_caches);
BOOST_CHECK(reached_4_caches);
BOOST_CHECK(added_an_entry);
BOOST_CHECK(added_an_unspendable_entry);
BOOST_CHECK(removed_an_entry);
BOOST_CHECK(updated_an_entry);
BOOST_CHECK(found_an_entry);
BOOST_CHECK(missed_an_entry);
BOOST_CHECK(uncached_an_entry);
}
// Store of all necessary tx and undo data for next test
typedef std::map<COutPoint, std::tuple<CTransaction,CTxUndo,Coin>> UtxoData;
UtxoData utxoData;
UtxoData::iterator FindRandomFrom(const std::set<COutPoint> &utxoSet) {
assert(utxoSet.size());
auto utxoSetIt = utxoSet.lower_bound(COutPoint(InsecureRand256(), 0));
if (utxoSetIt == utxoSet.end()) {
utxoSetIt = utxoSet.begin();
}
auto utxoDataIt = utxoData.find(*utxoSetIt);
assert(utxoDataIt != utxoData.end());
return utxoDataIt;
}
// This test is similar to the previous test
// except the emphasis is on testing the functionality of UpdateCoins
// random txs are created and UpdateCoins is used to update the cache stack
// In particular it is tested that spending a duplicate coinbase tx
// has the expected effect (the other duplicate is overwitten at all cache levels)
BOOST_AUTO_TEST_CASE(updatecoins_simulation_test)
{
bool spent_a_duplicate_coinbase = false;
// A simple map to track what we expect the cache stack to represent.
std::map<COutPoint, Coin> result;
// The cache stack.
CCoinsViewTest base; // A CCoinsViewTest at the bottom.
std::vector<CCoinsViewCacheTest*> stack; // A stack of CCoinsViewCaches on top.
stack.push_back(new CCoinsViewCacheTest(&base)); // Start with one cache.
// Track the txids we've used in various sets
std::set<COutPoint> coinbase_coins;
std::set<COutPoint> disconnected_coins;
std::set<COutPoint> duplicate_coins;
std::set<COutPoint> utxoset;
for (unsigned int i = 0; i < NUM_SIMULATION_ITERATIONS; i++) {
uint32_t randiter = InsecureRand32();
// 19/20 txs add a new transaction
if (randiter % 20 < 19) {
CMutableTransaction tx;
tx.vin.resize(1);
tx.vout.resize(1);
tx.vout[0].nValue = i; //Keep txs unique unless intended to duplicate
tx.vout[0].scriptPubKey.assign(InsecureRand32() & 0x3F, 0); // Random sizes so we can test memory usage accounting
unsigned int height = InsecureRand32();
Coin old_coin;
// 2/20 times create a new coinbase
if (randiter % 20 < 2 || coinbase_coins.size() < 10) {
// 1/10 of those times create a duplicate coinbase
if (InsecureRandRange(10) == 0 && coinbase_coins.size()) {
auto utxod = FindRandomFrom(coinbase_coins);
// Reuse the exact same coinbase
tx = std::get<0>(utxod->second);
// shouldn't be available for reconnection if its been duplicated
disconnected_coins.erase(utxod->first);
duplicate_coins.insert(utxod->first);
}
else {
coinbase_coins.insert(COutPoint(tx.GetHash(), 0));
}
assert(CTransaction(tx).IsCoinBase());
}
// 17/20 times reconnect previous or add a regular tx
else {
COutPoint prevout;
// 1/20 times reconnect a previously disconnected tx
if (randiter % 20 == 2 && disconnected_coins.size()) {
auto utxod = FindRandomFrom(disconnected_coins);
tx = std::get<0>(utxod->second);
prevout = tx.vin[0].prevout;
if (!CTransaction(tx).IsCoinBase() && !utxoset.count(prevout)) {
disconnected_coins.erase(utxod->first);
continue;
}
// If this tx is already IN the UTXO, then it must be a coinbase, and it must be a duplicate
if (utxoset.count(utxod->first)) {
assert(CTransaction(tx).IsCoinBase());
assert(duplicate_coins.count(utxod->first));
}
disconnected_coins.erase(utxod->first);
}
// 16/20 times create a regular tx
else {
auto utxod = FindRandomFrom(utxoset);
prevout = utxod->first;
// Construct the tx to spend the coins of prevouthash
tx.vin[0].prevout = prevout;
assert(!CTransaction(tx).IsCoinBase());
}
// In this simple test coins only have two states, spent or unspent, save the unspent state to restore
old_coin = result[prevout];
// Update the expected result of prevouthash to know these coins are spent
result[prevout].Clear();
utxoset.erase(prevout);
// The test is designed to ensure spending a duplicate coinbase will work properly
// if that ever happens and not resurrect the previously overwritten coinbase
if (duplicate_coins.count(prevout)) {
spent_a_duplicate_coinbase = true;
}
}
// Update the expected result to know about the new output coins
assert(tx.vout.size() == 1);
const COutPoint outpoint(tx.GetHash(), 0);
result[outpoint] = Coin(tx.vout[0], height, CTransaction(tx).IsCoinBase());
// Call UpdateCoins on the top cache
CTxUndo undo;
UpdateCoins(tx, *(stack.back()), undo, height);
// Update the utxo set for future spends
utxoset.insert(outpoint);
// Track this tx and undo info to use later
utxoData.emplace(outpoint, std::make_tuple(tx,undo,old_coin));
} else if (utxoset.size()) {
//1/20 times undo a previous transaction
auto utxod = FindRandomFrom(utxoset);
CTransaction &tx = std::get<0>(utxod->second);
CTxUndo &undo = std::get<1>(utxod->second);
Coin &orig_coin = std::get<2>(utxod->second);
// Update the expected result
// Remove new outputs
result[utxod->first].Clear();
// If not coinbase restore prevout
if (!tx.IsCoinBase()) {
result[tx.vin[0].prevout] = orig_coin;
}
// Disconnect the tx from the current UTXO
// See code in DisconnectBlock
// remove outputs
stack.back()->SpendCoin(utxod->first);
// restore inputs
if (!tx.IsCoinBase()) {
const COutPoint &out = tx.vin[0].prevout;
Coin coin = undo.vprevout[0];
ApplyTxInUndo(std::move(coin), *(stack.back()), out);
}
// Store as a candidate for reconnection
disconnected_coins.insert(utxod->first);
// Update the utxoset
utxoset.erase(utxod->first);
if (!tx.IsCoinBase())
utxoset.insert(tx.vin[0].prevout);
}
// Once every 1000 iterations and at the end, verify the full cache.
if (InsecureRandRange(1000) == 1 || i == NUM_SIMULATION_ITERATIONS - 1) {
for (auto it = result.begin(); it != result.end(); it++) {
bool have = stack.back()->HaveCoin(it->first);
const Coin& coin = stack.back()->AccessCoin(it->first);
BOOST_CHECK(have == !coin.IsSpent());
BOOST_CHECK(coin == it->second);
}
}
// One every 10 iterations, remove a random entry from the cache
if (utxoset.size() > 1 && InsecureRandRange(30) == 0) {
stack[InsecureRand32() % stack.size()]->Uncache(FindRandomFrom(utxoset)->first);
}
if (disconnected_coins.size() > 1 && InsecureRandRange(30) == 0) {
stack[InsecureRand32() % stack.size()]->Uncache(FindRandomFrom(disconnected_coins)->first);
}
if (duplicate_coins.size() > 1 && InsecureRandRange(30) == 0) {
stack[InsecureRand32() % stack.size()]->Uncache(FindRandomFrom(duplicate_coins)->first);
}
if (InsecureRandRange(100) == 0) {
// Every 100 iterations, flush an intermediate cache
if (stack.size() > 1 && InsecureRandBool() == 0) {
unsigned int flushIndex = InsecureRandRange(stack.size() - 1);
stack[flushIndex]->Flush();
}
}
if (InsecureRandRange(100) == 0) {
// Every 100 iterations, change the cache stack.
if (stack.size() > 0 && InsecureRandBool() == 0) {
stack.back()->Flush();
delete stack.back();
stack.pop_back();
}
if (stack.size() == 0 || (stack.size() < 4 && InsecureRandBool())) {
CCoinsView* tip = &base;
if (stack.size() > 0) {
tip = stack.back();
}
stack.push_back(new CCoinsViewCacheTest(tip));
}
}
}
// Clean up the stack.
while (stack.size() > 0) {
delete stack.back();
stack.pop_back();
}
// Verify coverage.
BOOST_CHECK(spent_a_duplicate_coinbase);
}
BOOST_AUTO_TEST_CASE(ccoins_serialization)
{
// Good example
CDataStream ss1(ParseHex("97f23c835800816115944e077fe7c803cfa57f29b36bf87c1d35"), SER_DISK, CLIENT_VERSION);
Coin cc1;
ss1 >> cc1;
BOOST_CHECK_EQUAL(cc1.fCoinBase, false);
BOOST_CHECK_EQUAL(cc1.nHeight, 203998);
BOOST_CHECK_EQUAL(cc1.out.nValue, 60000000000ULL);
BOOST_CHECK_EQUAL(HexStr(cc1.out.scriptPubKey), HexStr(GetScriptForDestination(CKeyID(uint160(ParseHex("816115944e077fe7c803cfa57f29b36bf87c1d35"))))));
// Good example
CDataStream ss2(ParseHex("8ddf77bbd123008c988f1a4a4de2161e0f50aac7f17e7f9555caa4"), SER_DISK, CLIENT_VERSION);
Coin cc2;
ss2 >> cc2;
BOOST_CHECK_EQUAL(cc2.fCoinBase, true);
BOOST_CHECK_EQUAL(cc2.nHeight, 120891);
BOOST_CHECK_EQUAL(cc2.out.nValue, 110397);
BOOST_CHECK_EQUAL(HexStr(cc2.out.scriptPubKey), HexStr(GetScriptForDestination(CKeyID(uint160(ParseHex("8c988f1a4a4de2161e0f50aac7f17e7f9555caa4"))))));
// Smallest possible example
CDataStream ss3(ParseHex("000006"), SER_DISK, CLIENT_VERSION);
Coin cc3;
ss3 >> cc3;
BOOST_CHECK_EQUAL(cc3.fCoinBase, false);
BOOST_CHECK_EQUAL(cc3.nHeight, 0);
BOOST_CHECK_EQUAL(cc3.out.nValue, 0);
BOOST_CHECK_EQUAL(cc3.out.scriptPubKey.size(), 0);
// scriptPubKey that ends beyond the end of the stream
CDataStream ss4(ParseHex("000007"), SER_DISK, CLIENT_VERSION);
try {
Coin cc4;
ss4 >> cc4;
BOOST_CHECK_MESSAGE(false, "We should have thrown");
} catch (const std::ios_base::failure& e) {
}
// Very large scriptPubKey (3*10^9 bytes) past the end of the stream
CDataStream tmp(SER_DISK, CLIENT_VERSION);
uint64_t x = 3000000000ULL;
tmp << VARINT(x);
BOOST_CHECK_EQUAL(HexStr(tmp.begin(), tmp.end()), "8a95c0bb00");
CDataStream ss5(ParseHex("00008a95c0bb00"), SER_DISK, CLIENT_VERSION);
try {
Coin cc5;
ss5 >> cc5;
BOOST_CHECK_MESSAGE(false, "We should have thrown");
} catch (const std::ios_base::failure& e) {
}
}
const static COutPoint OUTPOINT;
const static CAmount PRUNED = -1;
const static CAmount ABSENT = -2;
const static CAmount FAIL = -3;
const static CAmount VALUE1 = 100;
const static CAmount VALUE2 = 200;
const static CAmount VALUE3 = 300;
const static char DIRTY = CCoinsCacheEntry::DIRTY;
const static char FRESH = CCoinsCacheEntry::FRESH;
const static char NO_ENTRY = -1;
const static auto FLAGS = {char(0), FRESH, DIRTY, char(DIRTY | FRESH)};
const static auto CLEAN_FLAGS = {char(0), FRESH};
const static auto ABSENT_FLAGS = {NO_ENTRY};
void SetCoinsValue(CAmount value, Coin& coin)
{
assert(value != ABSENT);
coin.Clear();
assert(coin.IsSpent());
if (value != PRUNED) {
coin.out.nValue = value;
coin.nHeight = 1;
assert(!coin.IsSpent());
}
}
size_t InsertCoinsMapEntry(CCoinsMap& map, CAmount value, char flags)
{
if (value == ABSENT) {
assert(flags == NO_ENTRY);
return 0;
}
assert(flags != NO_ENTRY);
CCoinsCacheEntry entry;
entry.flags = flags;
SetCoinsValue(value, entry.coin);
auto inserted = map.emplace(OUTPOINT, std::move(entry));
assert(inserted.second);
return inserted.first->second.coin.DynamicMemoryUsage();
}
void GetCoinsMapEntry(const CCoinsMap& map, CAmount& value, char& flags)
{
auto it = map.find(OUTPOINT);
if (it == map.end()) {
value = ABSENT;
flags = NO_ENTRY;
} else {
if (it->second.coin.IsSpent()) {
value = PRUNED;
} else {
value = it->second.coin.out.nValue;
}
flags = it->second.flags;
assert(flags != NO_ENTRY);
}
}
void WriteCoinsViewEntry(CCoinsView& view, CAmount value, char flags)
{
CCoinsMap map;
InsertCoinsMapEntry(map, value, flags);
view.BatchWrite(map, {});
}
class SingleEntryCacheTest
{
public:
SingleEntryCacheTest(CAmount base_value, CAmount cache_value, char cache_flags)
{
WriteCoinsViewEntry(base, base_value, base_value == ABSENT ? NO_ENTRY : DIRTY);
cache.usage() += InsertCoinsMapEntry(cache.map(), cache_value, cache_flags);
}
CCoinsView root;
CCoinsViewCacheTest base{&root};
CCoinsViewCacheTest cache{&base};
};
void CheckAccessCoin(CAmount base_value, CAmount cache_value, CAmount expected_value, char cache_flags, char expected_flags)
{
SingleEntryCacheTest test(base_value, cache_value, cache_flags);
test.cache.AccessCoin(OUTPOINT);
test.cache.SelfTest();
CAmount result_value;
char result_flags;
GetCoinsMapEntry(test.cache.map(), result_value, result_flags);
BOOST_CHECK_EQUAL(result_value, expected_value);
BOOST_CHECK_EQUAL(result_flags, expected_flags);
}
BOOST_AUTO_TEST_CASE(ccoins_access)
{
/* Check AccessCoin behavior, requesting a coin from a cache view layered on
* top of a base view, and checking the resulting entry in the cache after
* the access.
*
* Base Cache Result Cache Result
* Value Value Value Flags Flags
*/
CheckAccessCoin(ABSENT, ABSENT, ABSENT, NO_ENTRY , NO_ENTRY );
CheckAccessCoin(ABSENT, PRUNED, PRUNED, 0 , 0 );
CheckAccessCoin(ABSENT, PRUNED, PRUNED, FRESH , FRESH );
CheckAccessCoin(ABSENT, PRUNED, PRUNED, DIRTY , DIRTY );
CheckAccessCoin(ABSENT, PRUNED, PRUNED, DIRTY|FRESH, DIRTY|FRESH);
CheckAccessCoin(ABSENT, VALUE2, VALUE2, 0 , 0 );
CheckAccessCoin(ABSENT, VALUE2, VALUE2, FRESH , FRESH );
CheckAccessCoin(ABSENT, VALUE2, VALUE2, DIRTY , DIRTY );
CheckAccessCoin(ABSENT, VALUE2, VALUE2, DIRTY|FRESH, DIRTY|FRESH);
CheckAccessCoin(PRUNED, ABSENT, ABSENT, NO_ENTRY , NO_ENTRY );
CheckAccessCoin(PRUNED, PRUNED, PRUNED, 0 , 0 );
CheckAccessCoin(PRUNED, PRUNED, PRUNED, FRESH , FRESH );
CheckAccessCoin(PRUNED, PRUNED, PRUNED, DIRTY , DIRTY );
CheckAccessCoin(PRUNED, PRUNED, PRUNED, DIRTY|FRESH, DIRTY|FRESH);
CheckAccessCoin(PRUNED, VALUE2, VALUE2, 0 , 0 );
CheckAccessCoin(PRUNED, VALUE2, VALUE2, FRESH , FRESH );
CheckAccessCoin(PRUNED, VALUE2, VALUE2, DIRTY , DIRTY );
CheckAccessCoin(PRUNED, VALUE2, VALUE2, DIRTY|FRESH, DIRTY|FRESH);
CheckAccessCoin(VALUE1, ABSENT, VALUE1, NO_ENTRY , 0 );
CheckAccessCoin(VALUE1, PRUNED, PRUNED, 0 , 0 );
CheckAccessCoin(VALUE1, PRUNED, PRUNED, FRESH , FRESH );
CheckAccessCoin(VALUE1, PRUNED, PRUNED, DIRTY , DIRTY );
CheckAccessCoin(VALUE1, PRUNED, PRUNED, DIRTY|FRESH, DIRTY|FRESH);
CheckAccessCoin(VALUE1, VALUE2, VALUE2, 0 , 0 );
CheckAccessCoin(VALUE1, VALUE2, VALUE2, FRESH , FRESH );
CheckAccessCoin(VALUE1, VALUE2, VALUE2, DIRTY , DIRTY );
CheckAccessCoin(VALUE1, VALUE2, VALUE2, DIRTY|FRESH, DIRTY|FRESH);
}
void CheckSpendCoins(CAmount base_value, CAmount cache_value, CAmount expected_value, char cache_flags, char expected_flags)
{
SingleEntryCacheTest test(base_value, cache_value, cache_flags);
test.cache.SpendCoin(OUTPOINT);
test.cache.SelfTest();
CAmount result_value;
char result_flags;
GetCoinsMapEntry(test.cache.map(), result_value, result_flags);
BOOST_CHECK_EQUAL(result_value, expected_value);
BOOST_CHECK_EQUAL(result_flags, expected_flags);
};
BOOST_AUTO_TEST_CASE(ccoins_spend)
{
/* Check SpendCoin behavior, requesting a coin from a cache view layered on
* top of a base view, spending, and then checking
* the resulting entry in the cache after the modification.
*
* Base Cache Result Cache Result
* Value Value Value Flags Flags
*/
CheckSpendCoins(ABSENT, ABSENT, ABSENT, NO_ENTRY , NO_ENTRY );
CheckSpendCoins(ABSENT, PRUNED, PRUNED, 0 , DIRTY );
CheckSpendCoins(ABSENT, PRUNED, ABSENT, FRESH , NO_ENTRY );
CheckSpendCoins(ABSENT, PRUNED, PRUNED, DIRTY , DIRTY );
CheckSpendCoins(ABSENT, PRUNED, ABSENT, DIRTY|FRESH, NO_ENTRY );
CheckSpendCoins(ABSENT, VALUE2, PRUNED, 0 , DIRTY );
CheckSpendCoins(ABSENT, VALUE2, ABSENT, FRESH , NO_ENTRY );
CheckSpendCoins(ABSENT, VALUE2, PRUNED, DIRTY , DIRTY );
CheckSpendCoins(ABSENT, VALUE2, ABSENT, DIRTY|FRESH, NO_ENTRY );
CheckSpendCoins(PRUNED, ABSENT, ABSENT, NO_ENTRY , NO_ENTRY );
CheckSpendCoins(PRUNED, PRUNED, PRUNED, 0 , DIRTY );
CheckSpendCoins(PRUNED, PRUNED, ABSENT, FRESH , NO_ENTRY );
CheckSpendCoins(PRUNED, PRUNED, PRUNED, DIRTY , DIRTY );
CheckSpendCoins(PRUNED, PRUNED, ABSENT, DIRTY|FRESH, NO_ENTRY );
CheckSpendCoins(PRUNED, VALUE2, PRUNED, 0 , DIRTY );
CheckSpendCoins(PRUNED, VALUE2, ABSENT, FRESH , NO_ENTRY );
CheckSpendCoins(PRUNED, VALUE2, PRUNED, DIRTY , DIRTY );
CheckSpendCoins(PRUNED, VALUE2, ABSENT, DIRTY|FRESH, NO_ENTRY );
CheckSpendCoins(VALUE1, ABSENT, PRUNED, NO_ENTRY , DIRTY );
CheckSpendCoins(VALUE1, PRUNED, PRUNED, 0 , DIRTY );
CheckSpendCoins(VALUE1, PRUNED, ABSENT, FRESH , NO_ENTRY );
CheckSpendCoins(VALUE1, PRUNED, PRUNED, DIRTY , DIRTY );
CheckSpendCoins(VALUE1, PRUNED, ABSENT, DIRTY|FRESH, NO_ENTRY );
CheckSpendCoins(VALUE1, VALUE2, PRUNED, 0 , DIRTY );
CheckSpendCoins(VALUE1, VALUE2, ABSENT, FRESH , NO_ENTRY );
CheckSpendCoins(VALUE1, VALUE2, PRUNED, DIRTY , DIRTY );
CheckSpendCoins(VALUE1, VALUE2, ABSENT, DIRTY|FRESH, NO_ENTRY );
}
void CheckAddCoinBase(CAmount base_value, CAmount cache_value, CAmount modify_value, CAmount expected_value, char cache_flags, char expected_flags, bool coinbase)
{
SingleEntryCacheTest test(base_value, cache_value, cache_flags);
CAmount result_value;
char result_flags;
try {
CTxOut output;
output.nValue = modify_value;
test.cache.AddCoin(OUTPOINT, Coin(std::move(output), 1, coinbase), coinbase);
test.cache.SelfTest();
GetCoinsMapEntry(test.cache.map(), result_value, result_flags);
} catch (std::logic_error& e) {
result_value = FAIL;
result_flags = NO_ENTRY;
}
BOOST_CHECK_EQUAL(result_value, expected_value);
BOOST_CHECK_EQUAL(result_flags, expected_flags);
}
// Simple wrapper for CheckAddCoinBase function above that loops through
// different possible base_values, making sure each one gives the same results.
// This wrapper lets the coins_add test below be shorter and less repetitive,
// while still verifying that the CoinsViewCache::AddCoin implementation
// ignores base values.
template <typename... Args>
void CheckAddCoin(Args&&... args)
{
for (CAmount base_value : {ABSENT, PRUNED, VALUE1})
CheckAddCoinBase(base_value, std::forward<Args>(args)...);
}
BOOST_AUTO_TEST_CASE(ccoins_add)
{
/* Check AddCoin behavior, requesting a new coin from a cache view,
* writing a modification to the coin, and then checking the resulting
* entry in the cache after the modification. Verify behavior with the
* with the AddCoin potential_overwrite argument set to false, and to true.
*
* Cache Write Result Cache Result potential_overwrite
* Value Value Value Flags Flags
*/
CheckAddCoin(ABSENT, VALUE3, VALUE3, NO_ENTRY , DIRTY|FRESH, false);
CheckAddCoin(ABSENT, VALUE3, VALUE3, NO_ENTRY , DIRTY , true );
CheckAddCoin(PRUNED, VALUE3, VALUE3, 0 , DIRTY|FRESH, false);
CheckAddCoin(PRUNED, VALUE3, VALUE3, 0 , DIRTY , true );
CheckAddCoin(PRUNED, VALUE3, VALUE3, FRESH , DIRTY|FRESH, false);
CheckAddCoin(PRUNED, VALUE3, VALUE3, FRESH , DIRTY|FRESH, true );
CheckAddCoin(PRUNED, VALUE3, VALUE3, DIRTY , DIRTY , false);
CheckAddCoin(PRUNED, VALUE3, VALUE3, DIRTY , DIRTY , true );
CheckAddCoin(PRUNED, VALUE3, VALUE3, DIRTY|FRESH, DIRTY|FRESH, false);
CheckAddCoin(PRUNED, VALUE3, VALUE3, DIRTY|FRESH, DIRTY|FRESH, true );
CheckAddCoin(VALUE2, VALUE3, FAIL , 0 , NO_ENTRY , false);
CheckAddCoin(VALUE2, VALUE3, VALUE3, 0 , DIRTY , true );
CheckAddCoin(VALUE2, VALUE3, FAIL , FRESH , NO_ENTRY , false);
CheckAddCoin(VALUE2, VALUE3, VALUE3, FRESH , DIRTY|FRESH, true );
CheckAddCoin(VALUE2, VALUE3, FAIL , DIRTY , NO_ENTRY , false);
CheckAddCoin(VALUE2, VALUE3, VALUE3, DIRTY , DIRTY , true );
CheckAddCoin(VALUE2, VALUE3, FAIL , DIRTY|FRESH, NO_ENTRY , false);
CheckAddCoin(VALUE2, VALUE3, VALUE3, DIRTY|FRESH, DIRTY|FRESH, true );
}
void CheckWriteCoins(CAmount parent_value, CAmount child_value, CAmount expected_value, char parent_flags, char child_flags, char expected_flags)
{
SingleEntryCacheTest test(ABSENT, parent_value, parent_flags);
CAmount result_value;
char result_flags;
try {
WriteCoinsViewEntry(test.cache, child_value, child_flags);
test.cache.SelfTest();
GetCoinsMapEntry(test.cache.map(), result_value, result_flags);
} catch (std::logic_error& e) {
result_value = FAIL;
result_flags = NO_ENTRY;
}
BOOST_CHECK_EQUAL(result_value, expected_value);
BOOST_CHECK_EQUAL(result_flags, expected_flags);
}
BOOST_AUTO_TEST_CASE(ccoins_write)
{
/* Check BatchWrite behavior, flushing one entry from a child cache to a
* parent cache, and checking the resulting entry in the parent cache
* after the write.
*
* Parent Child Result Parent Child Result
* Value Value Value Flags Flags Flags
*/
CheckWriteCoins(ABSENT, ABSENT, ABSENT, NO_ENTRY , NO_ENTRY , NO_ENTRY );
CheckWriteCoins(ABSENT, PRUNED, PRUNED, NO_ENTRY , DIRTY , DIRTY );
CheckWriteCoins(ABSENT, PRUNED, ABSENT, NO_ENTRY , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(ABSENT, VALUE2, VALUE2, NO_ENTRY , DIRTY , DIRTY );
CheckWriteCoins(ABSENT, VALUE2, VALUE2, NO_ENTRY , DIRTY|FRESH, DIRTY|FRESH);
CheckWriteCoins(PRUNED, ABSENT, PRUNED, 0 , NO_ENTRY , 0 );
CheckWriteCoins(PRUNED, ABSENT, PRUNED, FRESH , NO_ENTRY , FRESH );
CheckWriteCoins(PRUNED, ABSENT, PRUNED, DIRTY , NO_ENTRY , DIRTY );
CheckWriteCoins(PRUNED, ABSENT, PRUNED, DIRTY|FRESH, NO_ENTRY , DIRTY|FRESH);
CheckWriteCoins(PRUNED, PRUNED, PRUNED, 0 , DIRTY , DIRTY );
CheckWriteCoins(PRUNED, PRUNED, PRUNED, 0 , DIRTY|FRESH, DIRTY );
CheckWriteCoins(PRUNED, PRUNED, ABSENT, FRESH , DIRTY , NO_ENTRY );
CheckWriteCoins(PRUNED, PRUNED, ABSENT, FRESH , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(PRUNED, PRUNED, PRUNED, DIRTY , DIRTY , DIRTY );
CheckWriteCoins(PRUNED, PRUNED, PRUNED, DIRTY , DIRTY|FRESH, DIRTY );
CheckWriteCoins(PRUNED, PRUNED, ABSENT, DIRTY|FRESH, DIRTY , NO_ENTRY );
CheckWriteCoins(PRUNED, PRUNED, ABSENT, DIRTY|FRESH, DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(PRUNED, VALUE2, VALUE2, 0 , DIRTY , DIRTY );
CheckWriteCoins(PRUNED, VALUE2, VALUE2, 0 , DIRTY|FRESH, DIRTY );
CheckWriteCoins(PRUNED, VALUE2, VALUE2, FRESH , DIRTY , DIRTY|FRESH);
CheckWriteCoins(PRUNED, VALUE2, VALUE2, FRESH , DIRTY|FRESH, DIRTY|FRESH);
CheckWriteCoins(PRUNED, VALUE2, VALUE2, DIRTY , DIRTY , DIRTY );
CheckWriteCoins(PRUNED, VALUE2, VALUE2, DIRTY , DIRTY|FRESH, DIRTY );
CheckWriteCoins(PRUNED, VALUE2, VALUE2, DIRTY|FRESH, DIRTY , DIRTY|FRESH);
CheckWriteCoins(PRUNED, VALUE2, VALUE2, DIRTY|FRESH, DIRTY|FRESH, DIRTY|FRESH);
CheckWriteCoins(VALUE1, ABSENT, VALUE1, 0 , NO_ENTRY , 0 );
CheckWriteCoins(VALUE1, ABSENT, VALUE1, FRESH , NO_ENTRY , FRESH );
CheckWriteCoins(VALUE1, ABSENT, VALUE1, DIRTY , NO_ENTRY , DIRTY );
CheckWriteCoins(VALUE1, ABSENT, VALUE1, DIRTY|FRESH, NO_ENTRY , DIRTY|FRESH);
CheckWriteCoins(VALUE1, PRUNED, PRUNED, 0 , DIRTY , DIRTY );
CheckWriteCoins(VALUE1, PRUNED, FAIL , 0 , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, PRUNED, ABSENT, FRESH , DIRTY , NO_ENTRY );
CheckWriteCoins(VALUE1, PRUNED, FAIL , FRESH , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, PRUNED, PRUNED, DIRTY , DIRTY , DIRTY );
CheckWriteCoins(VALUE1, PRUNED, FAIL , DIRTY , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, PRUNED, ABSENT, DIRTY|FRESH, DIRTY , NO_ENTRY );
CheckWriteCoins(VALUE1, PRUNED, FAIL , DIRTY|FRESH, DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, VALUE2, VALUE2, 0 , DIRTY , DIRTY );
CheckWriteCoins(VALUE1, VALUE2, FAIL , 0 , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, VALUE2, VALUE2, FRESH , DIRTY , DIRTY|FRESH);
CheckWriteCoins(VALUE1, VALUE2, FAIL , FRESH , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, VALUE2, VALUE2, DIRTY , DIRTY , DIRTY );
CheckWriteCoins(VALUE1, VALUE2, FAIL , DIRTY , DIRTY|FRESH, NO_ENTRY );
CheckWriteCoins(VALUE1, VALUE2, VALUE2, DIRTY|FRESH, DIRTY , DIRTY|FRESH);
CheckWriteCoins(VALUE1, VALUE2, FAIL , DIRTY|FRESH, DIRTY|FRESH, NO_ENTRY );
// The checks above omit cases where the child flags are not DIRTY, since
// they would be too repetitive (the parent cache is never updated in these
// cases). The loop below covers these cases and makes sure the parent cache
// is always left unchanged.
for (CAmount parent_value : {ABSENT, PRUNED, VALUE1})
for (CAmount child_value : {ABSENT, PRUNED, VALUE2})
for (char parent_flags : parent_value == ABSENT ? ABSENT_FLAGS : FLAGS)
for (char child_flags : child_value == ABSENT ? ABSENT_FLAGS : CLEAN_FLAGS)
CheckWriteCoins(parent_value, child_value, parent_value, parent_flags, child_flags, parent_flags);
}
BOOST_AUTO_TEST_SUITE_END()
| [
"[email protected]"
] | |
4277ea88535823e663ae954bb42a43ee5e1af4eb | 1f2745a8176a635415fefb882f3e452960f04e57 | /hw2-meshedit/src/student_code.cpp | efdb1cb92f14fdfa0760396cbc9f06a5054aa860 | [] | no_license | migofan0723/computer-graphics | 9c4d2696bf9dc738996e17cd19d5edf78b769bc4 | b59a2facb0cde2bc6c664aee1f35a771a6347570 | refs/heads/master | 2022-03-03T02:50:53.658798 | 2019-05-25T02:02:44 | 2019-05-25T02:02:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,829 | cpp | #include "student_code.h"
#include "mutablePriorityQueue.h"
using namespace std;
namespace CGL
{
template <class T>
inline T lerp(const T &u, const T &v, double t)
{
return (1 - t) * u + t * v;
}
void BezierCurve::evaluateStep()
{
// TODO Part 1.
// Perform one step of the Bezier curve's evaluation at t using de Casteljau's algorithm for subdivision.
// Store all of the intermediate control points into the 2D vector evaluatedLevels.
const vector<Vector2D>&last_level = evaluatedLevels[evaluatedLevels.size()-1];
vector<Vector2D>new_level;
for(int i=0;i<last_level.size()-1;++i)
{
Vector2D new_point = lerp<Vector2D>(last_level[i], last_level[i+1], this->t);
new_level.push_back(new_point);
}
evaluatedLevels.push_back(new_level);
}
Vector3D BezierPatch::evaluate(double u, double v) const
{
// TODO Part 2.
// Evaluate the Bezier surface at parameters (u, v) through 2D de Casteljau subdivision.
// (i.e. Unlike Part 1 where we performed one subdivision level per call to evaluateStep, this function
// should apply de Casteljau's algorithm until it computes the final, evaluated point on the surface)
vector<Vector3D>bzc;
for(int i=0;i<this->controlPoints.size();++i)
{
bzc.push_back(this->evaluate1D(this->controlPoints[i], u));
}
return this->evaluate1D(bzc, v);
}
Vector3D BezierPatch::evaluate1D(std::vector<Vector3D> points, double t) const
{
// TODO Part 2.
// Optional helper function that you might find useful to implement as an abstraction when implementing BezierPatch::evaluate.
// Given an array of 4 points that lie on a single curve, evaluates the Bezier curve at parameter t using 1D de Casteljau subdivision.
if(points.size() == 1)
return points[0];
else
{
vector<Vector3D>new_level;
for(int i=0;i<points.size()-1;++i)
{
new_level.push_back(lerp<Vector3D>(points[i], points[i+1], t));
}
return this->evaluate1D(new_level, t);
}
}
Vector3D Vertex::normal( void ) const
{
// TODO Part 3.
// TODO Returns an approximate unit normal at this vertex, computed by
// TODO taking the area-weighted average of the normals of neighboring
// TODO triangles, then normalizing.
Vector3D ret = Vector3D(0, 0, 0);
auto h = this->halfedge();
h = h->twin();
auto h_orig = h;
do {
//area += tmp_area;
ret += h->face()->normal();
//h = h->twin()->next();
h = h->next()->twin();
} while (h != h_orig && !h->isBoundary());
return ret.unit();
}
EdgeIter HalfedgeMesh::flipEdge( EdgeIter e0 )
{
// TODO Part 4.
// TODO This method should flip the given edge and return an iterator to the flipped edge.
auto h0 = e0->halfedge(), h3 = h0->twin();
auto h1 = h0->next(), h2 = h1->next();
auto h4 = h3->next(), h5 = h4->next();
auto h6 = h1->twin(), h7 = h2->twin();
auto h8 = h4->twin(), h9 = h5->twin();
auto v1 = h3->vertex(), v0 = h0->vertex(), v2 = h2->vertex(), v3 = h8->vertex();
auto f0 = h0->face(), f1 = h3->face();
auto e1 = h6->edge(), e2 = h7->edge(), e3 = h8->edge(), e4 = h9->edge();
// e0->halfedge's origin point, and next halfedges
if(h0->isBoundary() || h1->isBoundary() || h2->isBoundary()||
h3->isBoundary() || h4->isBoundary() || h5->isBoundary())
return e0;
// cout<<(h->face()==h_next->face()&&h_next->face()==h_next_next->face())<<endl;
// cout<<(h_twin->face()==ht_next->face()&&ht_next->face()==ht_next_next->face())<<endl;
h0->setNeighbors(h1, h3, v3, e0, f0);
h1->setNeighbors(h2, h7, v2, e2, f0);
h2->setNeighbors(h0, h8, v0, e3, f0);
h3->setNeighbors(h4, h0, v2, e0, f1);
h4->setNeighbors(h5, h9, v3, e4, f1);
h5->setNeighbors(h3, h6, v1, e1, f1);
h6->setNeighbors(h6->next(), h5, v2, e1, h6->face());
h7->setNeighbors(h7->next(), h1, v0, e2, h7->face());
h8->setNeighbors(h8->next(), h2, v3, e3, h8->face());
h9->setNeighbors(h9->next(), h4, v1, e4, h9->face());
// assign vertices' edge
v0->halfedge() = h2;
v1->halfedge() = h5;
v2->halfedge() = h3;
v3->halfedge() = h0;
// assign e0's primary halfedge
e0->halfedge() = h0;
e1->halfedge() = h6;
e2->halfedge() = h7;
e3->halfedge() = h8;
e4->halfedge() = h9;
// face
f0->halfedge() = h0;
f1->halfedge() = h3;
return e0;
}
VertexIter HalfedgeMesh::splitEdge( EdgeIter e0 )
{
// TODO Part 5.
// TODO This method should split the given edge and return an iterator to the newly inserted vertex.
// TODO The halfedge of this vertex should point along the edge that was split, rather than the new edges.
// original halfedges
if(e0->isBoundary())
return e0->halfedge()->vertex();
/*
* {
auto h0 = e0->halfedge()->isBoundary()?e0->halfedge()->twin():e0->halfedge(),
h1=h0->next(), h2 = h1->next();
auto f0 = h0->face();
// original vertices
auto v0 = h0->vertex(), v1 = h1->vertex(), v2 = h2->vertex();
auto new_vertex = newVertex();
// add new edges
auto e1 = h1->edge(), e2 = h2->edge();
// add new halfedges
auto h6 = newHalfedge(), h7 = newHalfedge(), h8 = newHalfedge(), h9 = newHalfedge();
// add new edges
auto e5 = newEdge(), e6 = newEdge();
// add new faces
// cout<<"if f0 is boundary: "<<f0->isBoundary()<<endl;
auto f2 = newFace(), b = newBoundary();
// new_vetex's location and halfedge it belongs to
new_vertex->position = (v0->position + v1->position) / 2;
new_vertex->halfedge() = h0;
// set new halfedges
h0->setNeighbors(h1, h0->twin(), new_vertex, e0, f0);
h1->setNeighbors(h8, h1->twin(), v1, e1, f0);
h2->setNeighbors(h6, h2->twin(), v2, e2, f2);
h6->setNeighbors(h7, h9, v0, e6, f2);
h7->setNeighbors(h2, h8, new_vertex, e5, f2);
h8->setNeighbors(h0, h7, v2, e5, f0);
h9->face() = b;
// vertex assignments
new_vertex->isNew = true;
// edge assignments
e5->halfedge() = h8;
e6->halfedge() = h6;
e0->isNew = false;
e5->isNew = true;
e6->isNew = false;
// face assignments
f0->halfedge() = h0;
f2->halfedge() = h2;
b->halfedge() = h9;
return e0->halfedge()->vertex();
// delete previous edge and face
}
else{*/
auto h0 = e0->halfedge(), h1=h0->next(), h2 = h1->next(),
h3 = h0->twin(), h4 = h3->next(), h5 = h4->next();
auto f0 = h0->face(), f1 = h3->face();
// original vertices
auto v0 = h0->vertex(), v1 = h3->vertex(),
v2 = h2->vertex(), v3 = h5->vertex();
auto new_vertex = newVertex();
// add new edges
auto e1 = h1->edge(), e2 = h2->edge(),
e3 = h4->edge(), e4 = h5->edge();
// add new halfedges
auto h6 = newHalfedge(), h7 = newHalfedge(), h8 = newHalfedge(),
h9 = newHalfedge(), h10 = newHalfedge(), h11 = newHalfedge();
// add new edges
auto e5 = newEdge(), e6 = newEdge(), e7 = newEdge();
// add new faces
auto f2 = newFace(), f3 = newFace();
// new_vetex's location and halfedge it belongs to
new_vertex->position = (v0->position + v1->position) / 2;
new_vertex->halfedge() = h0;
// set new halfedges
h0->setNeighbors(h1, h3, new_vertex, e0, f0);
h1->setNeighbors(h8, h1->twin(), v1, e1, f0);
h2->setNeighbors(h6, h2->twin(), v2, e2, f2);
h3->setNeighbors(h11, h0, v1, e0, f1);
h4->setNeighbors(h10, h4->twin(), v0, e3, f3);
h5->setNeighbors(h3, h5->twin(), v3, e4, f1);
h6->setNeighbors(h7, h9, v0, e6, f2);
h7->setNeighbors(h2, h8, new_vertex, e5, f2);
h8->setNeighbors(h0, h7, v2, e5, f0);
h9->setNeighbors(h4, h6, new_vertex, e6, f3);
h10->setNeighbors(h9, h11, v3, e7, f3);
h11->setNeighbors(h5, h10, new_vertex, e7, f1);
// vertex assignments
new_vertex->isNew = true;
// edge assignments
e5->halfedge() = h8;
e6->halfedge() = h6;
e7->halfedge() = h10;
e0->isNew = false;
e5->isNew = true;
e6->isNew = false;
e7->isNew = true;
// face assignments
f0->halfedge() = h0;
f1->halfedge() = h3;
f2->halfedge() = h2;
f3->halfedge() = h4;
// delete previous edge and face
return e0->halfedge()->vertex();
}
void MeshResampler::upsample( HalfedgeMesh& mesh )
{
// TODO Part 6.
// This routine should increase the number of triangles in the mesh using Loop subdivision.
// Each vertex and edge of the original surface can be associated with a vertex in the new (subdivided) surface.
// Therefore, our strategy for computing the subdivided vertex locations is to *first* compute the new positions
// using the connectity of the original (coarse) mesh; navigating this mesh will be much easier than navigating
// the new subdivided (fine) mesh, which has more elements to traverse. We will then assign vertex positions in
// the new mesh based on the values we computed for the original mesh.
// TODO Compute new positions for all the vertices in the input mesh, using the Loop subdivision rule,
// TODO and store them in Vertex::newPosition. At this point, we also want to mark each vertex as being
// TODO a vertex of the original mesh.
// TODO Next, compute the updated vertex positions associated with edges, and store it in Edge::newPosition.
// TODO Next, we're going to split every edge in the mesh, in any order. For future
// TODO reference, we're also going to store some information about which subdivided
// TODO edges come from splitting an edge in the original mesh, and which edges are new,
// TODO by setting the flat Edge::isNew. Note that in this loop, we only want to iterate
// TODO over edges of the original mesh---otherwise, we'll end up splitting edges that we
// TODO just split (and the loop will never end!)
// TODO Now flip any new edge that connects an old and new vertex.
// TODO Finally, copy the new vertex positions into final Vertex::position.
HalfedgeIter h;
VertexIter a, b, c, d;
EdgeIter e1, e2, e3;
FaceIter f1, f2, f3;
int edgeNum = 0;
for (auto e = mesh.edgesBegin(); e != mesh.edgesEnd(); e++)
{
edgeNum += 1;
e->isNew = false;
h = e->halfedge();
a = h->vertex();
c = h->twin()->vertex();
b = h->next()->twin()->vertex();
d = h->twin()->next()->twin()->vertex();
// new vertex postion
e->newPosition = (((a->position + c->position) * 3 + (b->position + d->position)) / 8);
}
for (auto v = mesh.verticesBegin(); v != mesh.verticesEnd(); v++)
{
v->isNew = false;
Vector3D sum(0, 0, 0);
int n = 0;
h = v->halfedge();
do{
n += 1;
sum += h->twin()->vertex()->position;
h = h->twin()->next();
} while (h != v->halfedge());
double u;
u = n==3?3.0 / 16:3.0 / (8 * n);
v->newPosition = ((1 - n * u) * v->position + u * sum);
}
auto e = mesh.edgesBegin();
for (int i = 0; i < edgeNum; i++, ++e)
{
auto v = mesh.splitEdge(e);
v->newPosition = e->newPosition;
}
for (auto e = mesh.edgesBegin(); e != mesh.edgesEnd(); e++)
{
if (e->isNew)
{
h = e->halfedge();
if ((h->vertex()->isNew && !h->twin()->vertex()->isNew)
|| (!h->vertex()->isNew && h->twin()->vertex()->isNew))
{
mesh.flipEdge(e);
}
}
}
for (auto v = mesh.verticesBegin(); v != mesh.verticesEnd(); v++)
{
v->position = v->newPosition;
}
}
}
| [
"[email protected]"
] | |
f0b80002e3c3e24ab019dbe96ed1eac637238893 | 060339a0c7a5b102230684de9251df3c1d277c58 | /Buzz/Buzz.ino | 4d5803a1537dcd43a51a46dba9240c76d777df5a | [] | no_license | insoo223/ATTiny13A_Sketch | 40cb7b636af5f57b97c221d7a71d316a886271e6 | 193523f86d184d9fce7a45a110659ec00563e1b1 | refs/heads/master | 2020-04-14T03:34:59.777175 | 2017-07-21T02:50:18 | 2018-11-17T03:18:38 | 40,429,902 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 241 | ino |
// Target MCU: ATTiny13
#define buzzPin 4
void setup()
{
pinMode(buzzPin,OUTPUT);
}
void loop()
{
const byte DURATION = 200;
digitalWrite(buzzPin, HIGH);
delay(DURATION);
digitalWrite(buzzPin, LOW);
delay(DURATION);
}
| [
"insoo@Acer.(none)"
] | insoo@Acer.(none) |
d81a120ae2d7f6188e0d8448054fa422dd81e17f | 23864fb38e21f5a24533823722adeba835434fac | /frameworks/include/object/object_id.h | 8e802ea485b8d5ffff0e17a7bcfa43dd87b1dc17 | [
"Apache-2.0"
] | permissive | dawmlight/distributeddatamgr_objectstore | d69e350ff880da10f911c3f926b19f439d5b7b6e | d0ae9988a9e88581123b5d6ea62dcedcb9609f85 | refs/heads/master | 2023-07-27T23:42:35.336970 | 2021-09-13T01:57:06 | 2021-09-13T01:57:06 | 406,237,088 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 971 | h | /*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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 OBJECT_ID_H
#define OBJECT_ID_H
#include <string>
namespace OHOS::ObjectStore {
class ObjectId {
public:
ObjectId() = default;
virtual ~ObjectId() = default;
virtual std::string ToUri()
{
return "";
}
virtual bool IsValid()
{
return false;
}
};
} // namespace OHOS::ObjectStore
#endif // OBJECT_ID_H
| [
"[email protected]"
] | |
ce7678e7235602efd047eaf5fb7c4a9c46e53760 | 59184be6febf1288dff0f3ca90c43f82c8c2afaf | /adt-tester/Queue.h | 436f44a1f1582b251301fca635c9e5b9949a7160 | [] | no_license | CodingBash/it279-stackqueue-assignment | 5e3ee829fd8d4d1aa74e81467b02e0c9d018fc5d | 48d574108b89de8143c0f1c93a4a8d7a490f7eaf | refs/heads/master | 2021-01-21T06:38:30.426748 | 2017-03-07T03:27:41 | 2017-03-07T03:27:41 | 82,867,324 | 1 | 1 | null | 2017-03-07T01:01:25 | 2017-02-23T00:42:09 | C++ | UTF-8 | C++ | false | false | 311 | h | #ifndef GUARD_QUEUE_H
#define GUARD_QUEUE_H
#include "NodeQueue.h"
#include <cstdlib>
#include <cstddef>
namespace QueueNS {
class Queue {
public:
QueueNS::Node* head;
std::size_t length;
void queue(QueueNS::NodeQueueData data);
QueueNS::NodeQueueData dequeue();
Queue();
~Queue();
};
}
#endif
| [
"[email protected]"
] | |
9d62bf267a8cb89133e9ab9836ad9c543a41842d | f5ad0edb109ae8334406876408e8a9c874e0d616 | /src/scheduler.h | 194f93aa34585fb3acb3b8da65139e4a87976dbc | [
"MIT"
] | permissive | rhkdck1/RomanceCoin_1 | 2d41c07efe054f9b114dc20b5e047d48e236489d | f0deb06a1739770078a51ed153c6550506490196 | refs/heads/master | 2020-09-14T12:36:48.082891 | 2019-12-23T10:21:36 | 2019-12-23T10:21:36 | 223,129,383 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,526 | h | // Copyright (c) 2015-2018 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef ROMANCE_SCHEDULER_H
#define ROMANCE_SCHEDULER_H
//
// NOTE:
// boost::thread / boost::chrono should be ported to std::thread / std::chrono
// when we support C++11.
//
#include <boost/chrono/chrono.hpp>
#include <boost/thread.hpp>
#include <map>
#include <sync.h>
//
// Simple class for background tasks that should be run
// periodically or once "after a while"
//
// Usage:
//
// CScheduler* s = new CScheduler();
// s->scheduleFromNow(doSomething, 11); // Assuming a: void doSomething() { }
// s->scheduleFromNow(std::bind(Class::func, this, argument), 3);
// boost::thread* t = new boost::thread(boost::bind(CScheduler::serviceQueue, s));
//
// ... then at program shutdown, clean up the thread running serviceQueue:
// t->interrupt();
// t->join();
// delete t;
// delete s; // Must be done after thread is interrupted/joined.
//
class CScheduler
{
public:
CScheduler();
~CScheduler();
typedef std::function<void(void)> Function;
// Call func at/after time t
void schedule(Function f, boost::chrono::system_clock::time_point t=boost::chrono::system_clock::now());
// Convenience method: call f once deltaSeconds from now
void scheduleFromNow(Function f, int64_t deltaMilliSeconds);
// Another convenience method: call f approximately
// every deltaSeconds forever, starting deltaSeconds from now.
// To be more precise: every time f is finished, it
// is rescheduled to run deltaSeconds later. If you
// need more accurate scheduling, don't use this method.
void scheduleEvery(Function f, int64_t deltaMilliSeconds);
// To keep things as simple as possible, there is no unschedule.
// Services the queue 'forever'. Should be run in a thread,
// and interrupted using boost::interrupt_thread
void serviceQueue();
// Tell any threads running serviceQueue to stop as soon as they're
// done servicing whatever task they're currently servicing (drain=false)
// or when there is no work left to be done (drain=true)
void stop(bool drain=false);
// Returns number of tasks waiting to be serviced,
// and first and last task times
size_t getQueueInfo(boost::chrono::system_clock::time_point &first,
boost::chrono::system_clock::time_point &last) const;
// Returns true if there are threads actively running in serviceQueue()
bool AreThreadsServicingQueue() const;
private:
std::multimap<boost::chrono::system_clock::time_point, Function> taskQueue;
boost::condition_variable newTaskScheduled;
mutable boost::mutex newTaskMutex;
int nThreadsServicingQueue;
bool stopRequested;
bool stopWhenEmpty;
bool shouldStop() const { return stopRequested || (stopWhenEmpty && taskQueue.empty()); }
};
/**
* Class used by CScheduler clients which may schedule multiple jobs
* which are required to be run serially. Jobs may not be run on the
* same thread, but no two jobs will be executed
* at the same time and memory will be release-acquire consistent
* (the scheduler will internally do an acquire before invoking a callback
* as well as a release at the end). In practice this means that a callback
* B() will be able to observe all of the effects of callback A() which executed
* before it.
*/
class SingleThreadedSchedulerClient {
private:
CScheduler *m_pscheduler;
CCriticalSection m_cs_callbacks_pending;
std::list<std::function<void (void)>> m_callbacks_pending GUARDED_BY(m_cs_callbacks_pending);
bool m_are_callbacks_running GUARDED_BY(m_cs_callbacks_pending) = false;
void MaybeScheduleProcessQueue();
void ProcessQueue();
public:
explicit SingleThreadedSchedulerClient(CScheduler *pschedulerIn) : m_pscheduler(pschedulerIn) {}
/**
* Add a callback to be executed. Callbacks are executed serially
* and memory is release-acquire consistent between callback executions.
* Practially, this means that callbacks can behave as if they are executed
* in order by a single thread.
*/
void AddToProcessQueue(std::function<void (void)> func);
// Processes all remaining queue members on the calling thread, blocking until queue is empty
// Must be called after the CScheduler has no remaining processing threads!
void EmptyQueue();
size_t CallbacksPending();
};
#endif
| [
"[email protected]"
] | |
18f242b08e81aee686f4fab7792fae017cb835be | 82a3e40b75d0cc4250998702c2bff873590d92db | /src/data/criterion.cpp | 5dca6d2d7d91fd5d670c8a623c53ff3011ed5db5 | [] | no_license | PavelAmialiushka/Aera.demo | 12c7981d0883e8b832c2f3e72fee14234cdeb3b0 | 4beeb315a99da6f90a87ba0bb5b3dffa6c52bd2d | refs/heads/master | 2021-10-11T14:41:00.180456 | 2019-01-27T13:38:21 | 2019-01-27T13:38:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,088 | cpp | //////////////////////////////////////////////////////////////////////////
//
// data library
//
// Written by Pavel Amialiushka
// No commercial use permited.
//
//////////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "criterion.h"
#include <boost/tokenizer.hpp>
#include <boost/lexical_cast.hpp>
#include "stage.h"
namespace monpac
{
criterion::criterion()
: vessel_(0)
{
}
void criterion::set_stage(const stage &stg)
{
stage_=stg;
holds_.clear();
for (unsigned index=0; index<stg.children_.size(); ++index)
{
assert(stg.children_[index]);
const std::vector< shared_ptr<stage> > &vector=
stg.children_[index]->children_;
if (vector.size())
{
for (unsigned jfoo=0; jfoo<vector.size(); ++jfoo)
{
assert( vector[jfoo] );
holds_.push_back( *vector[jfoo] );
}
}
else
{
holds_.push_back( *stg.children_[index] );
}
}
}
stage criterion::get_stage() const
{
return stage_;
}
void criterion::set_vessel(int v)
{
vessel_=v;
}
double criterion::get_threashold() const
{
return vessel_==1
? 60
: 50;
}
const std::vector<hold> &criterion::get_holds() const
{
return holds_;
}
int criterion::get_hold_pause() const
{
return vessel_==0
? 0
: 120;
}
static bool contains(const hold &hld, double time)
{
return hld.start <= time && time <= hld.end;
}
int criterion::get_hold(double time) const
{
std::vector<hold>::const_iterator index
=std::find_if(STL_II(holds_), bind(&contains, _1, time));
if (index==holds_.end() || time - index->start < get_hold_pause())
{
return -1;
}
else
{
return std::distance(holds_.begin(), index);
}
}
int criterion::get_vessel() const
{
return vessel_;
}
int criterion::get_max_hit65() const
{
return 0;
}
double criterion::get_max_duration() const
{
return vessel_==0
? 1000
: vessel_==1
? 9999999
: 2500;
}
int criterion::get_max_total_hits() const
{
return vessel_==0
? std::max(2, 8*5)
: vessel_==1
? 99999999
: 20;
}
unsigned criterion::get_max_hold_hits() const
{
return 2;
// 2
// 2+
// 2+
}
namespace
{
double line(double x, double XA, double ya, double XB, double yb)
{
// (y-a)/(b-a)==(x-A)/(B-A)
return (x-XA)*(yb-ya)/(XB-XA)+ya;
}
}
zip_t criterion::get_zip(unsigned cnt, double h, double s)
{
/*
hi=hid**0.65
s=210.6*sd**0.45
// units of Ex = Amplitude * Counts
const double A=3;
const double B=5;
const double C=6;
const double a=0.01;
const double b=0.04;
const double c= 0.1;
const double d0=0.6;
const double d= 2;
const double e= 10;
// units of Energy
*/
const double A=2.042; // Ax ** 0.65
const double B=2.847;
const double C=3.205;
const double a=26.51; // 210.6 * ax ** 0.45
const double b=49.47;
const double c=74.72;
const double d0=167.35;
const double d=287.69;
const double e=593.55;
if (cnt<10) return zip_na;
if (s<a) return zip_0;
if (s<b && h<A) return zip_a;
// zipb
if (s<c && h<A || s < c && h < B && s < line(h, A, c, B, b)) return zip_b;
// zipc
if (s<d && h<A || s < d0 && h < C && s < line(h, A, d0, C, c) || s < c ) return zip_c;
// zipd
if (s<e && h<C || s < d) return zip_d;
return zip_e;
}
void criterion::set_test_threshold(bool b)
{
test_threshold_=b;
}
bool criterion::get_test_threshold() const
{
return test_threshold_;
}
void criterion::serialization(serl::archiver &ar)
{
ar.serial("vessel_type",
serl::indirect(
this, vessel_,
&criterion::set_vessel,
&criterion::get_vessel));
ar.serial_container("holds", holds_);
ar.serial("use_test_threshold", serl::makeint(test_threshold_));
}
} | [
"[email protected]"
] | |
66e36ba5aba6ddba6d5953b3cff1a6eafe1c4036 | ffa30f1f769e4d7ac0685fd4405dcdf928824c14 | /프로그래머스/Level2/가장큰정사각형찾기.cpp | daf266f4298ec68e613bda8fc1c48b48b234bf90 | [] | no_license | wykim111/algorithm | 4c9b44f5d9657d6d58a817e2a4d14d4a1a9ff7a4 | ef1eef6adebf8df25bb7db8b97670751c8ec3c36 | refs/heads/master | 2023-08-17T23:50:49.453775 | 2023-08-10T14:44:36 | 2023-08-10T14:44:36 | 217,846,215 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,468 | cpp | /*
기준점을 기준으로 왼쪽,위쪽,좌상에 1이 있는지 비교
모두 존재하면 정사각형이므로 기준점 위치 +1 씩 업데이트
단, 왼쪽, 위쪽, 좌상의 데이터 중 값이 다르면,셋 중 최소 값 +1로 업데이트
-> 정사각형이므로 사각형이 1이면 길이가 1이고 2이면 길이가 2인 정사각형 의미
*/
#include <iostream>
#include<vector>
using namespace std;
int solution(vector<vector<int>> board)
{
int answer = 0;
//행과 열의 길이를 구함
int row = board.size();
int col = board[0].size();
//0,0부터 탐색했다면 맵을 벗어나는 예외처리를 추가해야하므로
//(1,1)부터 시작
for(int i=1;i<row;i++)
{
for(int j=1;j<col;j++)
{
//현재 위치가 1이상이면 사각형 체크
if(board[i][j] >= 1)
{
int up = board[i-1][j];
int left = board[i][j-1];
int upLeft = board[i-1][j-1];
board[i][j] = min(min(up,left),upLeft)+1;
}
}
}
int maxData = -1;
for(int i=1;i<row;i++)
{
for(int j=1;j<col;j++)
{
if(maxData < board[i][j])
{
maxData = board[i][j];
}
}
}
answer = maxData*maxData;
return answer;
}
| [
"[email protected]"
] | |
e844a7bd3af723ef05523a404adbc3a2b195767d | 240c347a638ea456697dcacb7c30de6b9bd41559 | /Algorithm/Algorithm/7576.cpp | e85f1063519d0a09006cdd84234b2bbc457052aa | [] | no_license | yunn0504/ycyang | 96df83d430c9e6f5a1135b395e81e601246af47a | bb1e41da0b3de0dc8394c83bf2a0bc9c02dc6779 | refs/heads/master | 2021-09-03T18:48:39.644757 | 2018-01-11T07:25:55 | 2018-01-11T07:25:55 | 88,636,292 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,632 | cpp | #include<cstdio>
#include<queue>
#include<vector>
using namespace std;
int graph[1002][1002];
int visit[1002][1002];
int find1[1002][1002];
int nx[4] = { -1,1,0,0 }; //상 하 좌 우
int ny[4] = { 0,0,-1,1 };
int run = 0;
int count1 = 0;
typedef struct xy
{
int x;
int y;
}xy;
queue<xy> qu;
queue<xy> qu2;
int main()
{
#ifdef _DEBUG
freopen("input2.txt", "rt", stdin);
#endif
int n, m;
int i, j;
scanf("%d %d", &n, &m);
for (i = 0; i <= m + 1; i++)
{
for (j = 0; j <= n + 1; j++)
{
if ((0 < i && i < m + 1) && (0 < j && j < n + 1))
{
scanf("%d", &graph[i][j]);
if (graph[i][j] == 1) {
xy temp;
temp.x = i;
temp.y = j;
qu.push(temp);
find1[i][j] = 1;
}
}
else {
graph[i][j] = -2;
}
}
}
while (1)
{
while (!qu.empty()) {
xy temp;
temp = qu.front();
//printf("%d %d\n", temp.x, temp.y);
for (int k = 0; k < 4; k++)
{
if ((graph[temp.x + nx[k]][temp.y + ny[k]] == 0) && (find1[temp.x + nx[k]][temp.y + ny[k]] == 0)) //안익은 사과면서 탐색안된 사과
{
xy temp2;
temp2.x = temp.x + nx[k];
temp2.y = temp.y + ny[k];
find1[temp.x + nx[k]][temp.y + ny[k]] = 1;
qu2.push(temp2);
//printf("%d %d\n", temp2.x, temp2.y);
}
}
qu.pop();
}
if (!qu2.empty()) {
while (!qu2.empty()) {
xy temp3;
temp3 = qu2.front();
qu2.pop();
graph[temp3.x][temp3.y] = 1;
qu.push(temp3);
}
}
else {
for (i = 1; i <= m + 1; i++)
for (j = 1; j <= n + 1; j++)
if (graph[i][j] == 0)
count1 = -1;
break;
}
count1++;
}
printf("%d\n", count1);
return 0;
} | [
"[email protected]"
] | |
e83b1a271229db4919eabbbbbec8bb06b0db16d3 | c68f791005359cfec81af712aae0276c70b512b0 | /Avito Code Challenge 2018/c.cpp | 2a232d864201193446c7e736ac540658c20495a2 | [] | no_license | luqmanarifin/cp | 83b3435ba2fdd7e4a9db33ab47c409adb088eb90 | 08c2d6b6dd8c4eb80278ec34dc64fd4db5878f9f | refs/heads/master | 2022-10-16T14:30:09.683632 | 2022-10-08T20:35:42 | 2022-10-08T20:35:42 | 51,346,488 | 106 | 46 | null | 2017-04-16T11:06:18 | 2016-02-09T04:26:58 | C++ | UTF-8 | C++ | false | false | 1,053 | cpp | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
vector<int> edge[N];
vector<int> leaf;
// 1 error, 0 oke
bool dfs(int now, int bef) {
//printf("%d %d\n", now, bef);
int child = 0;
for (auto it : edge[now]) {
if (it == bef) continue;
child++;
if (dfs(it, now)) return 1;
}
if (child > 1) return 1;
if (child == 0) {
leaf.push_back(now);
}
return 0;
}
int main() {
int n;
scanf("%d", &n);
for (int i = 1; i < n; i++) {
int u, v;
scanf("%d %d", &u, &v);
edge[u].push_back(v);
edge[v].push_back(u);
}
int root = -1, best = -1;
for (int i = 1; i <= n; i++) {
if ((int) edge[i].size() > best) {
best = edge[i].size();
root = i;
}
}
//printf("root %d\n", root);
bool ret = 0;
for (auto it : edge[root]) {
bool err = dfs(it, root);
if (err) {
ret = 1;
}
}
if (ret) {
puts("No");
return 0;
}
puts("Yes");
printf("%d\n", leaf.size());
for (auto it : leaf) {
printf("%d %d\n", root, it);
}
return 0;
}
| [
"[email protected]"
] | |
c9fb1faec46fc08730ded455871821471fc417b7 | 2798559978124077f6222453839639d2215e0306 | /parfullcms/ins/geant4-10-00-ref-00/examples/extended/electromagnetic/TestEm6/src/DetectorConstruction.cc | 604111b9f74c71a5c62b566262c1e0c371760731 | [
"LicenseRef-scancode-unknown-license-reference",
"CC-BY-4.0"
] | permissive | gpestana/thesis | 015f750ad64e6b5b3170ba013bf55b194327eb23 | 186f81e2a9650e816806d4725d281f5971248b1f | refs/heads/master | 2020-12-29T00:59:41.863202 | 2016-07-09T11:54:57 | 2016-07-09T11:54:57 | 16,997,962 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,561 | cc | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
/// \file electromagnetic/TestEm6/src/DetectorConstruction.cc
/// \brief Implementation of the DetectorConstruction class
//
// $Id: DetectorConstruction.cc 67268 2013-02-13 11:38:40Z ihrivnac $
//
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#include "DetectorConstruction.hh"
#include "DetectorMessenger.hh"
#include "G4Material.hh"
#include "G4Box.hh"
#include "G4LogicalVolume.hh"
#include "G4PVPlacement.hh"
#include "G4UniformMagField.hh"
#include "G4UserLimits.hh"
#include "G4GeometryManager.hh"
#include "G4PhysicalVolumeStore.hh"
#include "G4LogicalVolumeStore.hh"
#include "G4SolidStore.hh"
#include "G4UnitsTable.hh"
#include "G4SystemOfUnits.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
DetectorConstruction::DetectorConstruction()
:G4VUserDetectorConstruction(),
fP_Box(0), fL_Box(0), fBoxSize(500*m), fMaterial(0), fMagField(0),
fUserLimits(0), fDetectorMessenger(0)
{
DefineMaterials();
SetMaterial("Iron");
// create UserLimits
fUserLimits = new G4UserLimits();
// create commands for interactive definition of the detector
fDetectorMessenger = new DetectorMessenger(this);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
DetectorConstruction::~DetectorConstruction()
{ delete fDetectorMessenger;}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
G4VPhysicalVolume* DetectorConstruction::Construct()
{
return ConstructVolumes();
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void DetectorConstruction::DefineMaterials()
{
G4double a, z, density;
new G4Material("Beryllium", z= 4., a= 9.012182*g/mole, density= 1.848*g/cm3);
new G4Material("Carbon", z= 6., a= 12.011*g/mole, density= 2.265*g/cm3);
new G4Material("Iron", z=26., a= 55.85*g/mole, density= 7.870*g/cm3);
G4cout << *(G4Material::GetMaterialTable()) << G4endl;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
G4VPhysicalVolume* DetectorConstruction::ConstructVolumes()
{
G4GeometryManager::GetInstance()->OpenGeometry();
G4PhysicalVolumeStore::GetInstance()->Clean();
G4LogicalVolumeStore::GetInstance()->Clean();
G4SolidStore::GetInstance()->Clean();
G4Box*
sBox = new G4Box("Container", //its name
fBoxSize/2,fBoxSize/2,fBoxSize/2); //its dimensions
fL_Box = new G4LogicalVolume(sBox, //its shape
fMaterial, //its material
fMaterial->GetName()); //its name
fL_Box->SetUserLimits(fUserLimits);
fP_Box = new G4PVPlacement(0, //no rotation
G4ThreeVector(), //at (0,0,0)
fL_Box, //its logical volume
fMaterial->GetName(), //its name
0, //its mother volume
false, //no boolean operation
0); //copy number
PrintParameters();
//
//always return the root volume
//
return fP_Box;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void DetectorConstruction::PrintParameters()
{
G4cout << "\n The Box is " << G4BestUnit(fBoxSize,"Length")
<< " of " << fMaterial->GetName() << G4endl;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void DetectorConstruction::SetMaterial(G4String materialChoice)
{
// search the material by its name
G4Material* pttoMaterial = G4Material::GetMaterial(materialChoice);
if (pttoMaterial) fMaterial = pttoMaterial;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void DetectorConstruction::SetSize(G4double value)
{
fBoxSize = value;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#include "G4FieldManager.hh"
#include "G4TransportationManager.hh"
void DetectorConstruction::SetMagField(G4double fieldValue)
{
//apply a global uniform magnetic field along Z axis
G4FieldManager* fieldMgr
= G4TransportationManager::GetTransportationManager()->GetFieldManager();
if (fMagField) delete fMagField; //delete the existing magn field
if (fieldValue!=0.) // create a new one if non nul
{
fMagField = new G4UniformMagField(G4ThreeVector(0.,0.,fieldValue));
fieldMgr->SetDetectorField(fMagField);
fieldMgr->CreateChordFinder(fMagField);
}
else
{
fMagField = 0;
fieldMgr->SetDetectorField(fMagField);
}
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void DetectorConstruction::SetMaxStepSize(G4double val)
{
// set the maximum allowed step size
//
if (val <= DBL_MIN)
{ G4cout << "\n --->warning from SetMaxStepSize: maxStep "
<< val << " out of range. Command refused" << G4endl;
return;
}
fUserLimits->SetMaxAllowedStep(val);
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
#include "G4RunManager.hh"
void DetectorConstruction::UpdateGeometry()
{
G4RunManager::GetRunManager()->DefineWorldVolume(ConstructVolumes());
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
| [
"[email protected]"
] | |
fd105289427dd1837175c280721ad24ae87aa254 | 3dcef279dc29549722df6f5a1fc7ba657dabc3ef | /cpp/leetcode_100.cc | 8f846327f779a6de6dd1cf9cc50f19065f499316 | [] | no_license | MirrorrorriN/leetcode | 043066b71ff7e74b142525954601be7f2d933f98 | 983a0e0a94d1078bed52e85db5e6c5e3746cc3b2 | refs/heads/master | 2022-04-21T17:03:00.675472 | 2020-04-15T05:58:58 | 2020-04-15T05:58:58 | 58,693,247 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,072 | cc | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
stack<TreeNode*> stack_p;
stack<TreeNode*> stack_q;
if(p) stack_p.push(p);
if(q) stack_q.push(q);
while(!stack_p.empty() && !stack_q.empty()){
TreeNode* cur_p=stack_p.top();
TreeNode* cur_q=stack_q.top();
stack_p.pop();
stack_q.pop();
if(cur_p->val!=cur_q->val) return false;
if(cur_p->left) stack_p.push(cur_p->left);
if(cur_q->left) stack_q.push(cur_q->left);
if(stack_p.size() != stack_q.size()) return false;
if(cur_p->right) stack_p.push(cur_p->right);
if(cur_q->right) stack_q.push(cur_q->right);
if(stack_p.size() != stack_q.size()) return false;
}
return stack_p.size() == stack_q.size();
}
}; | [
"[email protected]"
] | |
031cfed8609ab878a847f56d16d96ade8705d3f9 | c8e10e56a64418a16d7a407c28d62c27309a0f19 | /PhoneBook/addrecord.h | 2b5cefe387c4bb8f7bdf7592ec8cfd6a848fa09d | [] | no_license | janindu2r/phonebook | 99eb21ed0349583909452acf3d60118af7a00522 | 917b2f9b320b69d475a674cf0626e07af1d80346 | refs/heads/master | 2021-01-10T10:32:36.567993 | 2015-12-19T05:54:50 | 2015-12-19T05:54:50 | 48,270,050 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 439 | h | #ifndef ADDRECORD_H
#define ADDRECORD_H
#include <QDialog>
#include <contact.h>
namespace Ui {
class AddRecord;
}
class AddRecord : public QDialog
{
Q_OBJECT
public:
explicit AddRecord(QWidget *parent = nullptr);
~AddRecord();
Contact addContact();
private slots:
void on_buttonBox_accepted();
void on_buttonBox_rejected();
private:
Ui::AddRecord *ui;
Contact varContact;
};
#endif // ADDRECORD_H
| [
"[email protected]"
] | |
83c4b3da9c7cfcb6ecf1e073437c9f9c6c51c8e2 | a2e917510007f3dae45691de800017f839a0cf55 | /VirtualCity/VirtualCity/Robot_Arm.cpp | 1a06464026c4d764cb17afbb73155440fb1518ee | [] | no_license | TenYearsADream/2016_ComputerGraph | ab0c21539a89c8fbf1984a396abd15d27a2839a7 | 6f9978745d4a8d651a6a0549356f0bea36257626 | refs/heads/master | 2020-07-16T15:12:37.427272 | 2016-07-20T06:43:00 | 2016-07-20T06:43:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,387 | cpp | #include "stdafx.h"
#include "Robot_Arm.h"
/*
pi = 3.1415926
1 degree = 2*pi/360 = 0.017445 radian
#define degree 0.017445
*/
void DrawPosition(void) {
Robot_Position.Base_DP_X1 = Robot_Arm.Base_X / My_Ortho.Value;
Robot_Position.Base_DP_Y1 = Robot_Arm.Base_Y / My_Ortho.Value;
Robot_Position.Link1_RP_Y1 = Robot_Arm.BaseHeight / My_Ortho.Value;
Robot_Position.Link1_DP_Y2 = Robot_Arm.Link1_Height / My_Ortho.Value;
Robot_Position.Link2_DP_X1 = (Robot_Arm.Link1_Length / My_Ortho.Value) + (Robot_Arm.Link2_Length / My_Ortho.Value);
Robot_Position.Link2_DP_Y1 = (Robot_Arm.Link1_Height / My_Ortho.Value) - (Robot_Arm.Link2_Height / My_Ortho.Value);
Robot_Position.Cube1_DP_X1 = (Robot_Arm.Link2_Length / My_Ortho.Value) - (Robot_Arm.Cube1_Length / My_Ortho.Value);
Robot_Position.Cube1_DP_Y1 = -(Robot_Arm.Link2_Height / My_Ortho.Value) - (Robot_Arm.Cube1_Height / My_Ortho.Value);
Robot_Position.Link3_DP_Y1 = -(Robot_Arm.Cube1_Height / My_Ortho.Value) - (Robot_Arm.Link3_Height / My_Ortho.Value);
Robot_Position.Link4_DP_Y1 = -(Robot_Arm.Link3_Height / My_Ortho.Value) - (Robot_Arm.Link4_Height / My_Ortho.Value);
Robot_Position.Link5_DP_Y1 = -(Robot_Arm.Link4_Height / My_Ortho.Value) - (Robot_Arm.Link5_Height / My_Ortho.Value);
Robot_Position.Link6_DP_Y1 = 0; // the same Link5 DP Y1
Robot_Position.Link5_DP_X1 = -(Robot_Arm.GripperWidth / My_Ortho.Value) - (Robot_Arm.Link5_Length / My_Ortho.Value);
Robot_Position.Link6_DP_X1 = -2 * Robot_Position.Link5_DP_X1; // Link5 的對稱位置
}
void DrawRobotArm(void) {
// glTranslated 、 glRotatef ..等,每呼叫一次函式 都會累加
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluLookAt(My_LookAt.X, My_LookAt.Y, My_LookAt.Z, My_LookAt.Watch_X, My_LookAt.Watch_Y, My_LookAt.Watch_Z, My_LookAt.Forward_X, My_LookAt.Forward_Y, My_LookAt.Forward_Z);
// Draw Base G
glColor3f(0.0, 1.0, 0.0);
glTranslated(Robot_Position.Base_DP_X1, Robot_Position.Base_DP_Y1, 0);
DrawCube(Robot_Arm.BaseLength, Robot_Arm.BaseHeight, Robot_Arm.BaseWidth);
// Draw Link1 R
glColor3f(1.0, 0.0, 0.0);
glTranslated(0, Robot_Position.Link1_RP_Y1, 0);
glRotated(Robot_Arm.Link1_theta, 0.0, 1.0, 0.0);
glTranslated(0, Robot_Position.Link1_DP_Y2, 0);
DrawCube(Robot_Arm.Link1_Length, Robot_Arm.Link1_Height, Robot_Arm.Link1_Width);
// Draw Link2 G
glColor3f(0.0, 1.0, 0.0);
glTranslated(Robot_Position.Link2_DP_X1, Robot_Position.Link2_DP_Y1, 0);
DrawCube(Robot_Arm.Link2_Length, Robot_Arm.Link2_Height, Robot_Arm.Link2_Width);
// Draw Cube1 G
glColor3f(0.0, 1.0, 0.0);
glTranslated(Robot_Position.Cube1_DP_X1, Robot_Position.Cube1_DP_Y1, 0);
DrawCube(Robot_Arm.Cube1_Length, Robot_Arm.Cube1_Height, Robot_Arm.Cube1_Width);
// Draw Link3 R
glColor3f(1.0, 0.0, 0.0);
glTranslated(0, Robot_Position.Link3_DP_Y1, 0);
DrawCube(Robot_Arm.Link3_Length, Robot_Arm.Link3_Height, Robot_Arm.Link3_Width);
// Draw Link4 G
glColor3f(0.0, 1.0, 0.0);
glTranslated(0, Robot_Position.Link4_DP_Y1, 0);
DrawCube(Robot_Arm.Link4_Length, Robot_Arm.Link4_Height, Robot_Arm.Link4_Width);
// Draw Link5 R
glColor3f(1.0, 0.0, 0.0);
glTranslated(Robot_Position.Link5_DP_X1, Robot_Position.Link5_DP_Y1, 0);
DrawCube(Robot_Arm.Link5_Length, Robot_Arm.Link5_Height, Robot_Arm.Link5_Width);
// Draw Link6 R
glColor3f(1.0, 0.0, 0.0);
glTranslated(Robot_Position.Link6_DP_X1, Robot_Position.Link6_DP_Y1, 0);
DrawCube(Robot_Arm.Link6_Length, Robot_Arm.Link6_Height, Robot_Arm.Link6_Width);
}
void DrawCube(float Length, float Height, float Width) {
//glBegin(GL_LINE_LOOP);
GLfloat DrawRange[16][3] = {
{ Length,Height,Width },{ Length,Height,-Width },{ -Length,Height,-Width },
{ -Length,Height,Width },{ Length,Height,Width },{ Length,-Height,Width },
{ Length,-Height,-Width },{ -Length,-Height,-Width },{ -Length,-Height,Width },
{ Length,-Height,Width },{ Length,-Height,-Width },{ Length,Height,-Width },
{ -Length,Height,-Width },{ -Length,-Height,-Width },{ -Length,-Height,Width },{ -Length,Height,Width } };
GLfloat DrawPoint[3] = { 0.0,0.0,0.0 };
glBegin(GL_POLYGON);
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 3; j++) {
DrawPoint[j] = DrawRange[i][j];
}
glNormal3fv(DrawPoint);
glVertex3fv(DrawPoint);
}
glEnd();
// glBegin(GL_POLYGON);
// glVertex3f(Length, Height, Width);
// glVertex3f(Length, Height, -Width);
// glVertex3f(-Length, Height, -Width);
// glVertex3f(-Length, Height, Width);
// glVertex3f(Length, Height, Width);
// glVertex3f(Length, -Height, Width);
// glVertex3f(Length, -Height, -Width);
// glVertex3f(-Length, -Height, -Width);
// glVertex3f(-Length, -Height, Width);
// glVertex3f(Length, -Height, Width);
// glVertex3f(Length, -Height, -Width);
// glVertex3f(Length, Height, -Width);
// glVertex3f(-Length, Height, -Width);
// glVertex3f(-Length, -Height, -Width);
// glVertex3f(-Length, -Height, Width);
// glVertex3f(-Length, Height, Width);
// glEnd();
}
void DrawCube_Lib(float scaleX, float scaleY, float scaleZ) {
glPushMatrix();
glScalef(scaleX, scaleY, scaleZ);
glutWireCube(1.0);
glPopMatrix();
}
void X_DirectionMenuFunc(int id) {
switch (id) {
case 1: // Increase
Robot_Arm.Base_X += 0.1;
break;
case 2: // Decrease
Robot_Arm.Base_X -= 0.1;
break;
}/* End of swtich*/
Robot_Position.Base_DP_X1 = Robot_Arm.Base_X / My_Ortho.Value;
printf(" Robot_Arm.Base_X = %f \r\n", Robot_Arm.Base_X);
glutPostRedisplay();
}
void Y_DirectionMenuFunc(int id) {
switch (id) {
case 1: // Increase
Robot_Arm.Base_Y += 0.1;
break;
case 2: // Decrease
Robot_Arm.Base_Y -= 0.1;
break;
}/* End of swtich*/
Robot_Position.Base_DP_Y1 = Robot_Arm.Base_Y / My_Ortho.Value;
printf(" Robot_Arm.Base_Y = %f \r\n", Robot_Arm.Base_Y);
glutPostRedisplay();
}
void ArmRotationMenuFunc(int id) {
switch (id) {
case 1: // Clockwise
Robot_Arm.Link1_theta+=5;
break;
case 2: // CounterClockwise
Robot_Arm.Link1_theta-=5;
break;
}/* End of swtich*/
printf(" Robot_Arm.Link1_theta = %f \r\n", Robot_Arm.Link1_theta);
glutPostRedisplay();
}
void GripperHeightMenuFunc(int id) {
switch (id) {
case 1: // Up
if (Robot_Arm.Link3_Height > 0.1)
Robot_Arm.Link3_Height -= 0.1;
else
Robot_Arm.Link3_Height = 0.0;
break;
case 2: // Down
if (Robot_Arm.Link3_Height < 0.2)
Robot_Arm.Link3_Height += 0.1;
else
Robot_Arm.Link3_Height = 0.2;
break;
}/* End of swtich*/
Robot_Position.Link3_DP_Y1 = -(Robot_Arm.Cube1_Height / My_Ortho.Value) - (Robot_Arm.Link3_Height / My_Ortho.Value);
Robot_Position.Link4_DP_Y1 = -(Robot_Arm.Link3_Height / My_Ortho.Value) - (Robot_Arm.Link4_Height / My_Ortho.Value);
printf(" Robot_Arm.Link3_Height = %f \r\n", Robot_Arm.Link3_Height);
glutPostRedisplay();
}
void GripperControlMenuFunc(int id) {
switch (id) {
case 1: // Open
if (Robot_Arm.GripperWidth < 0.2)
Robot_Arm.GripperWidth += 0.1;
else
Robot_Arm.GripperWidth = 0.2;
break;
case 2: // Close
if (Robot_Arm.GripperWidth > 0.1)
Robot_Arm.GripperWidth -= 0.1;
else
Robot_Arm.GripperWidth = 0;
break;
}/* End of swtich*/
Robot_Position.Link5_DP_X1 = -(Robot_Arm.GripperWidth / My_Ortho.Value) - (Robot_Arm.Link5_Length / My_Ortho.Value);
Robot_Position.Link6_DP_X1 = -2 * Robot_Position.Link5_DP_X1;
printf(" Robot_Arm.GripperWidth = %f \r\n", Robot_Arm.GripperWidth);
glutPostRedisplay();
}
| [
"BowenHsu"
] | BowenHsu |
7e1a5b178739fc0402f9395a4434e0271bf5c95d | 2220908fbae36a53cc64c942388f83a612c0a2b8 | /DisPG/DisPGLoader/symbolManagement.cpp | 07ce84d4cb58d52e253b069942b79d5a49251834 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Eva1216/PgResarch | e1288992b6d38ae42957144fbbfa45c3e57c7807 | 6f359529f8830a73666fbfeb42c8d46c6417d3ea | refs/heads/master | 2023-05-28T10:24:38.642301 | 2016-10-04T16:11:26 | 2016-10-04T16:11:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,530 | cpp | #include "stdafx.h"
#include "symbolManagement.h"
// C/C++ standard headers
// Other external headers
// Windows headers
// Original headers
#include "util.h"
#include "SymbolResolver.h"
#include "SymbolAddressDeriver.h"
////////////////////////////////////////////////////////////////////////////////
//
// macro utilities
//
////////////////////////////////////////////////////////////////////////////////
//
// constants and macros
//
////////////////////////////////////////////////////////////////////////////////
//
// types
//
namespace {
using DriverInfo = std::pair<std::uintptr_t, std::basic_string<TCHAR>>;
using DriverInfoList = std::vector<DriverInfo>;
} // End of namespace {unnamed}
////////////////////////////////////////////////////////////////////////////////
//
// prototypes
//
namespace {
DriverInfoList GetDriverList();
std::vector<std::basic_string<TCHAR>> GetRequireSymbolNames();
} // End of namespace {unnamed}
////////////////////////////////////////////////////////////////////////////////
//
// variables
//
////////////////////////////////////////////////////////////////////////////////
//
// implementations
//
// Resolve all necessary symbols and register the addresses to the registry.
// This functions gets the list of kernel modules and checks if the module is
// needed to resolve a symbol one by one.
bool RegisterSymbolInformation(
__in const std::basic_string<TCHAR>& RegistryPath)
{
// Get a full path of system32
std::array<TCHAR, MAX_PATH> sysDir_;
::GetSystemDirectory(sysDir_.data(), static_cast<UINT>(sysDir_.size()));
std::basic_string<TCHAR> sysDir(sysDir_.data());
sysDir += TEXT("\\");
// Get a name list of required symbols
const auto requireSymbols = GetRequireSymbolNames();
SymbolResolver resolver;
// Do follow for each driver files loaded in the kernel.
for (const auto& driverInfo : GetDriverList())
{
// Get a base name of the driver
const auto driverBaseName = driverInfo.second.substr(
0, driverInfo.second.find(TEXT('.')));
// Check if this driver is in the required list
for (const auto& requireSymbol : requireSymbols)
{
// Get a base name of the required symbol name
const auto requireBaseName = requireSymbol.substr(
0, requireSymbol.find(TEXT('!')));
// ignore if it is a different module
if (requireBaseName != driverBaseName)
{
continue;
}
// Get an address of the symbol
SymbolAddressDeriver deriver(&resolver,
sysDir + driverInfo.second, driverInfo.first);
const auto address = deriver.getAddress(requireSymbol);
if (!address)
{
std::basic_stringstream<TCHAR> ss;
ss << requireSymbol << TEXT(" could not be solved.");
const auto str = ss.str();
PrintErrorMessage(str.c_str());
return false;
}
// Save the address to the registry
if (!RegWrite64Value(RegistryPath, requireSymbol, address))
{
PrintErrorMessage(TEXT("RegSetPtr failed."));
return false;
}
_tprintf(_T("%016llX : %s\n"), address, requireSymbol.c_str());
}
}
return true;
}
namespace {
// Get a list of file names of drivers that are currently loaded in the kernel.
DriverInfoList GetDriverList()
{
// Determine the current number of drivers
DWORD needed = 0;
std::array<void*, 1000> baseAddresses;
if (!::EnumDeviceDrivers(baseAddresses.data(),
static_cast<DWORD>(baseAddresses.size() * sizeof(void*)), &needed))
{
ThrowRuntimeError(TEXT("EnumDeviceDrivers failed."));
}
// Collect their base names
DriverInfoList list;
const auto numberOfDrivers = needed / sizeof(baseAddresses.at(0));
for (std::uint32_t i = 0; i < numberOfDrivers; ++i)
{
std::array<TCHAR, MAX_PATH> name;
if (!::GetDeviceDriverBaseName(baseAddresses.at(i),
name.data(), static_cast<DWORD>(name.size())))
{
ThrowRuntimeError(TEXT("GetDeviceDriverBaseName failed."));
}
std::transform(name.begin(), name.end(), name.begin(), ::tolower);
list.emplace_back(
reinterpret_cast<std::uintptr_t>(baseAddresses.at(i)),
name.data());
}
return list;
}
// Returns a list of required symbols
std::vector<std::basic_string<TCHAR>> GetRequireSymbolNames()
{
std::vector<std::basic_string<TCHAR>> list;
// All platforms
list.emplace_back(TEXT("ntoskrnl!ExAcquireResourceSharedLite"));
if (IsWindows8Point1OrGreater())
{
// 8.1
list.emplace_back(TEXT("ntoskrnl!KiScbQueueScanWorker"));
list.emplace_back(TEXT("ntoskrnl!HalPerformEndOfInterrupt"));
list.emplace_back(TEXT("ntoskrnl!KiCommitThreadWait"));
list.emplace_back(TEXT("ntoskrnl!KiAttemptFastRemovePriQueue"));
list.emplace_back(TEXT("ntoskrnl!KeDelayExecutionThread"));
list.emplace_back(TEXT("ntoskrnl!KeWaitForSingleObject"));
}
else
{
// 7, Vista, XP
list.emplace_back(TEXT("ntoskrnl!PoolBigPageTable"));
list.emplace_back(TEXT("ntoskrnl!PoolBigPageTableSize"));
list.emplace_back(TEXT("ntoskrnl!MmNonPagedPoolStart"));
}
return list;
}
} // End of namespace {unnamed}
| [
"[email protected]"
] | |
1500010b7f33262325ccd36bb7ab5c1cacfcb8bf | 5d3329d6f1ffe4ca8052bb21107fb07d23e2876c | /ipt/year_2/semester_1/algorithms_and_structures/labs/lab5/main.cpp | f6100b71f78821b0d5b4feab20ad58ab5c2078a2 | [] | no_license | Nikita-L/Study | 8dae8935500ace6b44815199c47cee90cd1e3c36 | 581c1dda7711f113b0fc4ea0da73e5a3f510635a | refs/heads/master | 2021-09-13T12:46:21.127610 | 2018-02-06T10:33:57 | 2018-02-06T10:33:57 | 110,699,268 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 1,196 | cpp | #include "header.h"
void main ()
{
string answer;
usi i = 1;
TreeElement *tree = nullptr;
setlocale( LC_ALL,"Russian" );
mainMenu();
while (i)
{
cin >> answer;
if (answer == "1") // Заполнить/Создать дерево (только буквы)
{
treeGetElement(&tree);
mainMenu();
}
else if (answer == "2") // Удалить элемент
{
treeGetDeleteElement (&tree);
mainMenu();
}
else if (answer == "3") // Отобразить дерево
{
system ("CLS");
if (tree)
treeShow (tree, 0);
getch();
mainMenu();
}
else if (answer == "4") // Удалить повторяющиеся буквы
{
treeGetDeleteRepeatElement (&tree);
mainMenu();
}
else if (answer == "5") // Отобразить дерево постфиксным обходом
{
system ("CLS");
if (tree)
treePostfixShow (tree, 0);
getch();
mainMenu();
}
else if (answer == "6") // Очистить дерево
{
treeDelete(&tree);
mainMenu();
}
else if (answer == "0") // Выход
{
treeDelete(&tree);
return;
}
else
mainMenu();
}
} | [
"[email protected]"
] | |
8c62328f6caaac35fbe074691c4212d845e41e9c | 819506e59300756d657a328ce9418825eeb2c9cc | /codeforces/364/a.cpp | 83d1fcb1389002cbdb05386a2131fb402e7a0800 | [] | no_license | zerolxf/zero | 6a996c609e2863503b963d6798534c78b3c9847c | d8c73a1cc00f8a94c436dc2a40c814c63f9fa132 | refs/heads/master | 2021-06-27T04:13:00.721188 | 2020-10-08T07:45:46 | 2020-10-08T07:45:46 | 48,839,896 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,924 | cpp | /*************************************************************************
> File Name: a.cpp
> Author: liangxianfeng
> Mail: [email protected]
> Created Time: 2016年07月23日 星期六 00时35分08秒
************************************************************************/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<stack>
#include<map>
#include<set>
#include<vector>
#include<queue>
#include<string>
#include<cmath>
using namespace std;
#define ll long long
#define rep(i,n) for(int i =0; i < n; ++i)
#define CLR(x) memset(x,0,sizeof x)
#define MEM(a,b) memset(a,b,sizeof a)
#define pr(x) cout << #x << " = " << x << " ";
#define prln(x) cout << #x << " = " << x << endl;
const int maxn = 4e5+100;
const int INF = 0x3f3f3f3f;
vector<int> G[maxn];
bool vis[maxn];
int getid(int x){
int usize = G[x].size();
for(int i = 0; i < usize; ++i){
int v = G[x][i];
if(vis[v]) continue;
vis[v] = true;
return v;
}
}
int a[maxn];
int main(){
#ifdef LOCAL
freopen("/home/zeroxf/桌面/in.txt","r",stdin);
//freopen("/home/zeroxf/桌面/out.txt","w",stdout);
#endif
ll sum, x, n;
while(cin >> n){
for(int i = 0; i <= 100; ++i){
G[i].clear();
vis[i] = false;
}
sum =0;
//prln(n);
for(int i = 0; i < n; ++i){
cin >> x;
a[i+1] =x;
//G[x].push_back(i+1);
sum += x;
}
memset(vis, 0, sizeof vis);
ll ans = sum*2/n;
//prln(ans);
for(int i = 1; i <= n; ++i){
if(!vis[i]){
for(int j = i+1; j <= n; ++j){
if(a[j]+a[i]==ans&&!vis[j]){
vis[i] = vis[j] = true;
printf("%d %d\n", i, j);
}
}
}
}
}
return 0;
}
| [
"[email protected]"
] | |
add41ca144e758dc3c95c9e2f82ea7121ad41c39 | 4c23be1a0ca76f68e7146f7d098e26c2bbfb2650 | /ic8h18/0.008/HC6H12OOH-F | af0d77c797e406fea0b671abe599a15e766799b8 | [] | no_license | labsandy/OpenFOAM_workspace | a74b473903ddbd34b31dc93917e3719bc051e379 | 6e0193ad9dabd613acf40d6b3ec4c0536c90aed4 | refs/heads/master | 2022-02-25T02:36:04.164324 | 2019-08-23T02:27:16 | 2019-08-23T02:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 843 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.008";
object HC6H12OOH-F;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField uniform 4.06944e-45;
boundaryField
{
boundary
{
type empty;
}
}
// ************************************************************************* //
| [
"[email protected]"
] | ||
73a37081410afb9adb35289d9dafc6a96f638e6f | bf7fe9c190e45d80200706bf39359716ba41587d | /Particles/ParticleSystem.cpp | deed46214c34dab78d29e4c90ae0f23b9077dd06 | [] | no_license | VladislavKoleda/CosmicDefender--master | de1a34f9ebe0bff764152b94d170710642809a98 | 042097567af4a3e6eba147971ce067a3a982907a | refs/heads/master | 2020-11-23T21:04:17.911131 | 2019-12-13T10:53:43 | 2019-12-13T10:53:43 | 227,819,746 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,020 | cpp | #include "ParticleSystem.h"
#include "Particle.h"
using namespace SFML::Graphics;
using namespace SFML::System;
namespace ComicDefender
{
const std::wstring ParticleSystem::CONTENT_DIRICTORY = L"..\\Content\\Textures\\";
ParticleSystem::ParticleSystem(unsigned int count)
{
_count = static_cast<int>(count);
m_particles = std::vector<Particle*>(static_cast<int>(count));
m_vertices = new VertexArray(PrimitiveType::Points);
for (int i = 0; i < count; i++)
{
float Angle = R->Next(1, 360);
// float _speed = R.Next(0, 1000);
float _speed = R->Next(1, 20) / 100.0f;
float deltaX = static_cast<float>(std::cos(M_PI * (Angle - 90) / 180.0f)) * _speed;
float deltaY = static_cast<float>(std::sin(M_PI * (Angle - 90) / 180.0f)) * _speed;
float X = R->Next(1, 1280);
float Y = R->Next(1, 720);
float Q = ((R->Next(1, 4)) / 10.0f);
int flag = R->Next(0, 1);
Particle tempVar(Angle, _speed, deltaX, deltaY, X, Y, Q, flag);
m_particles.push_back(&tempVar);
m_vertices->Append(Vertex(Vector2f(X, Y), Color::White));
}
}
void ParticleSystem::Draw(RenderTarget *target, RenderStates states)
{
states.Texture = nullptr;
states.Transform *= getTransform();
target->Draw(m_vertices, states);
}
void ParticleSystem::Update()
{
for (int i = 0; i != m_particles.size()(); i++)
{
auto temp = m_vertices[static_cast<unsigned int>(i)];
m_particles[i]->X += m_particles[i]->DX;
m_particles[i]->Y += m_particles[i]->DY;
temp.Position = Vector2f(m_particles[i]->X, m_particles[i]->Y);
if (m_particles[i]->q < 0.4 && m_particles[i]->flag == 1)
{
m_particles[i]->q += 0.001f;
m_particles[i]->flag = 1;
}
else
{
m_particles[i]->flag = 0;
}
if (m_particles[i]->q > 0.1 && m_particles[i]->flag == 0)
{
m_particles[i]->q -= 0.001f;
}
else
{
m_particles[i]->flag = 1;
}
temp.Color.A = static_cast<unsigned char>(m_particles[i]->q * 255);
m_vertices[static_cast<unsigned int>(i)] = temp;
}
}
}
| [
"[email protected]"
] | |
ccf5c21aac9a0c82ff174b61b83e5ffe7619103d | 045116f898baa6b278b5d1112d1ce1d739c87847 | /WS03/in_lab/Mark.cpp | 5479b221d9265ba17af42e81fac15351c725fade | [] | no_license | nathanolah/OOP244_Repo | 73e44d45ed55f7a52c331377af97e1250b415732 | 02edfc9e1e63578ba37cf9024cf98c44a5d3e082 | refs/heads/master | 2022-06-05T08:10:23.877703 | 2020-01-10T18:01:51 | 2020-01-10T18:01:51 | 233,087,936 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,583 | cpp | // Nathan Olah
// Student Number: 124723198
// Email: [email protected]
// September 24, 2019
// Mark.cpp implementation file contains the necessary function definitions
// needed for the input and output of validated values used for the Mark module.
#include <iostream> // Includes standard input and output stream
using namespace std;
#include "Mark.h" // Includes class Mark's data members with member functions and constant int values
namespace sdds
{
// Clears buffer
void Mark::flushKeyboard()const {
cin.clear();
cin.ignore(1000, '\n'); // Removes up to specified number of characters, or up to newline delimiter
}
// Sets member variable m_displayMode to the incoming argument displayMode
void Mark::set(int displayMode) {
m_displayMode = displayMode;
}
// Sets member variables m_mark and m_outOf to the corresponding arguments.
// outOf argument has a default value of 1, if an argument is not provided.
void Mark::set(double mark, int outOf) {
m_mark = mark;
m_outOf = outOf;
}
// Sets m_displayMode to DSP_UNDEFINED, m_mark to -1,
// and m_outOf to 100.
void Mark::setEmpty() {
m_displayMode = DSP_UNDEFINED;
m_mark = -1;
m_outOf = 100;
}
// Returns boolean true, if Mark object is empty
bool Mark::isEmpty()const {
return m_displayMode == DSP_UNDEFINED
&& m_mark == -1
&& m_outOf == 100;
}
// Gets the percentage by, dividing m_mark by m_outOf, then multiplies
// by 100, then adds 0.5, and casts the value to an int type and returns the value.
int Mark::percent()const {
return (int)(0.5 + (100 * (m_mark / m_outOf)));
}
// Returns the result of m_mark divided by m_outOf
double Mark::rawValue()const {
return m_mark / m_outOf;
}
// Reads an inputted mark of a fractional format, cin.get()'s the slash character. cin.fail()
// check for any other character value other than a number with either a floating-point or integer value.
// Returns boolean value if the input was valid or invalid.
bool Mark::read(const char* prompt) {
char slash;
char newline;
bool done = true;
cout << prompt;
cin >> m_mark; // Input of mark value
slash = cin.get(); // Extracts the slash
if (cin.fail() || slash != '/') { // cin.fail() returns boolean value if input was a number, and if slash is not equal to slash
flushKeyboard(); // Clear buffer
setEmpty();
done = false;
}
else {
cin >> m_outOf; // Input of mark out of value
newline = cin.get();
if (cin.fail() || newline != '\n') {
flushKeyboard();
setEmpty();
done = false;
}
}
return done;
}
// Checks for value of m_displayMode, depending on the value of m_displayMode
// a specified sequence will occur, else the next condition will be evaluated.
// Returns the object cout.
ostream& Mark::display()const {
if (isEmpty()) {
return cout << "Empty Mark object!";
}
else if (m_displayMode == DSP_RAW) {
cout << rawValue();
}
else if (m_displayMode == DSP_PERCENT) {
cout << "%" << percent();
}
else if (m_displayMode == DSP_ASIS) {
cout << m_mark << "/" << m_outOf;
}
else if (m_displayMode == DSP_UNDEFINED) {
cout << "Display mode not set!";
}
else {
cout << "Invalid Mark Display setting!";
}
return cout;
}
} | [
"[email protected]"
] | |
a4a80bd83ba733e184d111cc2ed57d8ab24862ab | debe1c0fbb03a88da943fcdfd7661dd31b756cfc | /src/optimizers/optimizerSet/cplex/constraints/regulation/RampConstraintReg.cpp | 1112ee9c925218bcfda0cec400b1834c22691b3f | [] | no_license | pnnl/eom | 93e2396aad4df8653bec1db3eed705e036984bbc | 9ec5eb8ab050b755898d06760f918f649ab85db5 | refs/heads/master | 2021-08-08T04:51:15.798420 | 2021-06-29T18:19:50 | 2021-06-29T18:19:50 | 137,411,396 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,842 | cpp | /* ***************************************************************************
* Author : Kevin Glass
* Date : Jul 12, 2010
* File : ReserveConstraint.cpp
* Project : rim
*
*
* Contents :
*
* Assumptions :
*
* ---------------------------------------------------------------------------
*/
#include "constraints/regulation/RampConstraintReg.hpp"
#include "simulation/SDInterface.hpp"
namespace model {
/*
* optimizer variables
*
* generatorData[j].output.outputPower -- generator
* powerTargetSchedule -- scheduleData array
* generatorDeltaPower -- Cplex variable
* maxGeneratorRampUp -- generator parameter
* maxGeneratorRampDown -- generator parameter
*/
void
RampConstraintReg::load()
{
/*
for (int32_t gen = 0; gen < data.nGenerators; gen++){
optData.iloRampStatus[0][gen] = optData.iloGenIsOn[0][gen] + optData.iloGenStarting[0][gen];
optData.iloRampUpConstraint[0][gen] = IloIfThen(optData.control.iloEnv,
((data.ucRampSchedule[gen][23].targetPower <= optData.iloGenPower[0][gen]) &&
optData.iloRampStatus[0][gen] == 1),
((optData.iloGenPower[0][gen] - data.ucRampSchedule[gen][23].targetPower) <=
data.genRampUpRate[gen]));
optData.iloRampDownConstraint[0][gen] = IloIfThen(optData.control.iloEnv,
((data.ucRampSchedule[gen][23].targetPower >= optData.iloGenPower[0][gen]) &&
optData.iloRampStatus[0][gen] == 1),
((data.ucRampSchedule[gen][23].targetPower - optData.iloGenPower[0][gen]) <=
data.genRampDownRate[gen]) && (optData.iloGenStarting[0][gen]>=0));
optData.control.iloModel.add(optData.iloRampUpConstraint[0][gen]);
optData.control.iloModel.add(optData.iloRampDownConstraint[0][gen]);
}
for (INTEGER step = 1; step < data.ucLength; step++) {
for (INTEGER gen = 0; gen < data.nGenerators; gen++){
optData.iloRampStatus[step][gen] = optData.iloGenIsOn[step][gen] + optData.iloGenStarting[step][gen];
optData.iloRampUpConstraint[step][gen] = IloIfThen(optData.control.iloEnv,
((optData.iloGenPower[step-1][gen] <= optData.iloGenPower[step][gen]) && optData.iloRampStatus[step][gen] == 1),
((optData.iloGenPower[step][gen] - optData.iloGenPower[step-1][gen]) <= data.genRampUpRate[gen]));
optData.iloRampDownConstraint[step][gen] = IloIfThen(optData.control.iloEnv,
((optData.iloGenPower[step-1][gen] >= optData.iloGenPower[step][gen]) && optData.iloRampStatus[step][gen] == 1),
((optData.iloGenPower[step-1][gen] - optData.iloGenPower[step][gen]) <= data.genRampDownRate[gen]));
optData.control.iloModel.add(optData.iloRampUpConstraint[step][gen]);
optData.control.iloModel.add(optData.iloRampDownConstraint[step][gen]);
}
}
*/
}
void
RampConstraintReg::printErrorState()
{
}
} /* END OF NAMESPACE model */
| [
"[email protected]"
] | |
d8c2e3c47bf228cdf76033e3a2f0bf656f0f1939 | 09f872ea3be98ddceb4106c48e3169a3acb7a418 | /src/Zlang/zsharp/AST/AstVariable.h | 2dbcc8c9b04a067bc6f165c7ea0bd3a83586c598 | [] | no_license | obiwanjacobi/Zlang | ce51c3e5cdfcde13510a23b862519ea7947617e1 | c9dea8b6a3dc6fd9bb6a556cdf515413d6e299dc | refs/heads/master | 2021-07-15T17:48:36.377567 | 2020-10-11T15:13:43 | 2020-10-11T15:13:43 | 216,856,286 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,386 | h | #pragma once
#include "AstNode.h"
#include "AstCodeBlock.h"
#include "AstIdentifier.h"
#include "AstType.h"
#include "../grammar/parser/zsharp_parserParser.h"
class AstVariable : public AstCodeBlockItem, public AstIdentifierSite
{
public:
bool SetIdentifier(std::shared_ptr<AstIdentifier> identifier) override {
if (AstIdentifierSite::SetIdentifier(identifier)) {
bool success = identifier->setParent(this);
guard(success && "setParent failed.");
return true;
}
return false;
}
protected:
AstVariable()
: AstCodeBlockItem(AstNodeType::Variable)
{}
};
class AstVariableDefinition : public AstVariable, public AstTypeReferenceSite
{
public:
AstVariableDefinition(zsharp_parserParser::Variable_def_typedContext* ctx)
: _typedCtx(ctx), _typedInitCtx(nullptr), _assignCtx(nullptr)
{}
AstVariableDefinition(zsharp_parserParser::Variable_def_typed_initContext* ctx)
: _typedCtx(nullptr), _typedInitCtx(ctx), _assignCtx(nullptr)
{}
AstVariableDefinition(zsharp_parserParser::Variable_assign_autoContext* ctx)
: _typedCtx(nullptr), _typedInitCtx(nullptr), _assignCtx(ctx)
{}
bool SetTypeReference(std::shared_ptr<AstTypeReference> type) override {
if (AstTypeReferenceSite::SetTypeReference(type)) {
bool success = type->setParent(this);
guard(success && "setParent failed.");
return true;
}
return false;
}
void Accept(AstVisitor* visitor) override;
void VisitChildren(AstVisitor* visitor) override;
private:
zsharp_parserParser::Variable_def_typedContext* _typedCtx;
zsharp_parserParser::Variable_def_typed_initContext* _typedInitCtx;
zsharp_parserParser::Variable_assign_autoContext* _assignCtx;
};
class AstVariableReference : public AstVariable
{
public:
AstVariableReference(zsharp_parserParser::Variable_refContext* ctx)
: _refContext(ctx), _assignCtx(nullptr)
{}
AstVariableReference(zsharp_parserParser::Variable_assign_autoContext* ctx)
: _refContext(nullptr), _assignCtx(ctx)
{}
void Accept(AstVisitor* visitor) override;
void VisitChildren(AstVisitor* visitor) override;
private:
zsharp_parserParser::Variable_assign_autoContext* _assignCtx;
zsharp_parserParser::Variable_refContext* _refContext;
};
| [
"[email protected]"
] | |
1bf45fa83ee672263d3757d1531fc95600551837 | 7cc70bcb2b98b43e5d0b72e7d6c54e2170831506 | /app/src/mspsp-qt-app/settings.cpp | dcc5a48173aee2a358284f86d9490c86e25a3cd6 | [
"MIT"
] | permissive | semihyagcioglu/mspsp-qt | 9c9f6e389a3480c4e8062d579cf8fe15adb8cb34 | 11e0c800984ec74405aeed629d4e6ab6320b38be | refs/heads/master | 2021-03-12T23:42:43.512562 | 2014-07-19T16:32:37 | 2014-07-19T16:32:37 | 9,443,120 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,377 | cpp | #include "settings.h"
Settings::Settings()
{
SetToDefaultValues();
}
Settings::Settings(int maximumScheduleLimit, int populationSize)
{
this->MAXIMUM_SCHEDULE_LIMIT = maximumScheduleLimit;
this->POPULATION_SIZE = populationSize;
}
Settings::~Settings()
{
}
// Set to default values.
void Settings::SetToDefaultValues()
{
this->FILE_PATH="..\\";
this->REPORT_PATH = "..\\Reports\\";
this->INSTANCE_PATH = "..\\Instances\\";
this->INSTANCE_TYPE ="*.sm";
this->POPULATION_SIZE = 30;
this->CROSSOVER_PROBABILITY = 1.00;
this->MUTATION_PROBABILITY = 0.1;
this->TOURNAMENT_SIZE = 2;
this->ELITE_RATE = 0.1;
this->IS_ELITES_ALLOWED = true;
this->ELITE_SIZE = this->POPULATION_SIZE * this->ELITE_RATE;
this->SELECT_ONE_PARENT_FROM_ELITES = true;
this->MUTATE_ONLY_ON_IMPROVEMENT = true;
this->IS_ADAPTIVE = true;
this->SELECTION_METHOD = TOURNAMENT_SELECTION;
this->CROSSOVER_METHOD = SINGLE_POINT_CROSS_OVER;
this->MUTATION_METHOD = SWAP_ACTIVITY_AND_TEAM_MEMBER_ASSIGNMENT;
this->REPLACEMENT_METHOD = PERCENT90_REPLACEMENT;
this->SCHEDULE_COEFFICIENT = 250;
this->MAXIMUM_SCHEDULE_LIMIT = this->POPULATION_SIZE * this->SCHEDULE_COEFFICIENT;
this->MAXIMUM_TIME_LIMIT = 0;
this->CONVERGENCE_COUNT = 1000;
this->ALLOW_IMMIGRATION = false;
this->IMMIGRATION_RATIO = 0.6;
}
| [
"[email protected]"
] | |
79d7bc75d281383ac88c67ac2d4a21c3062a3af9 | 7e6bdbc23b7bafe4bd21f48794696e65fdab0f1b | /practica4_Interaccion/face_tracker.h | 0de1fa78fe97cb08c41ae3bb053707681ea40c9a | [] | no_license | JulyMaker/RVI | be9b464edda588c8b271769f62ea4868fb001c52 | 1cb149a6fefb3d4e9cdc2c53153fe875e86c3828 | refs/heads/master | 2021-05-28T20:37:38.487658 | 2015-03-13T13:38:03 | 2015-03-13T13:38:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 734 | h |
#include <opencv2/opencv.hpp>
#include <osg/PositionAttitudeTransform>
#include <OpenThreads/Thread>
#include <iostream>
using namespace cv;
class FaceTracker : public OpenThreads::Thread
{
public:
FaceTracker::FaceTracker();
virtual void run();
void getFace2DPosition(osg::Vec2d & face_2d_position);
void printFace2DPosition();
void close() { done = true; }
private:
bool init();
std::string TheInputVideo;
cv::VideoCapture TheVideoCapturer;
cv::Mat TheInputImage;
cv::Mat TheInputImageCopy;
cv::Mat TheInputImageFace;
bool done;
osg::Vec3d tracked_pos;
osg::Vec2d face_pos;
CascadeClassifier faceCade;
Mat camFrames, grayFrames;
vector<Rect> faces;
long imageIndex;
}; | [
"[email protected]"
] | |
fd655c347c9fa30666bc4d35a7847b0170e69224 | 8c234fb2a81e3596a01779b5ecb16be1051a5606 | /NimCefExample/NimCefExample.cpp | 502c3e54d7c3cbc21a1c8e9ab670b737e8c18e98 | [] | no_license | ljb200788/NimCefExample | 07ea19a0a0ff2bfe0cb0b0c6c990356a7e7cf44c | f09185efcfe67a90717d8d2dc90d7d5481761544 | refs/heads/master | 2022-04-16T22:19:12.507652 | 2020-04-16T10:13:06 | 2020-04-16T10:13:06 | 256,176,263 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 300 | cpp | // NimCefExample.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include <iostream>
#include <windows.h>
using namespace std;
int main()
{
ShowWindow(GetConsoleWindow(), SW_HIDE);
Sleep(9000);
MessageBox(NULL, _T("退出了"), _T("你好!"), MB_OK);
return 0;
}
| [
"[email protected]"
] | |
a4987942e9a5b6b2b3f3a0702280b1500a2e4bf5 | 377f318ca087d80c3b7b4e9f4d0d09691f082d6e | /1030.cpp | b4d4c6322d15dc980d9b813dc24173972001133b | [] | no_license | BAKAMiku/ACMSolution | 543da5e15964f7b87a59a6b4f361183e07dc7b73 | 58113b0dd76d64730daafad6bdc8cc84c9948168 | refs/heads/master | 2021-09-01T02:19:51.208832 | 2017-12-24T10:55:50 | 2017-12-24T10:55:50 | 114,458,415 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 159 | cpp | #include <stdio.h>
int main(){
int m,n,i;
scanf("%d %d",&m,&n);
i=(m>n?n:m);
while(!(m%i==0&&n%i==0)){
i--;
}
printf("%d",i);
} | [
"[email protected]"
] | |
dd8d6e81b43620b8fa0e742d45cfa9de3e393661 | 19eb97436a3be9642517ea9c4095fe337fd58a00 | /private/shell/ext/cscui/viewer/config.cpp | db0d8e2abec700321d0eae1e307e7af82a4b520f | [] | no_license | oturan-boga/Windows2000 | 7d258fd0f42a225c2be72f2b762d799bd488de58 | 8b449d6659840b6ba19465100d21ca07a0e07236 | refs/heads/main | 2023-04-09T23:13:21.992398 | 2021-04-22T11:46:21 | 2021-04-22T11:46:21 | 360,495,781 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,686 | cpp | //+-------------------------------------------------------------------------
//
// Microsoft Windows
//
// Copyright (C) Microsoft Corporation, 1997 - 1999
//
// File: config.cpp
//
//--------------------------------------------------------------------------
#include "pch.h"
#pragma hdrstop
#include <shlwapi.h>
#include "regstr.h"
#include "config.h"
#include "util.h"
//
// Determine if a character is a DBCS lead byte.
// If build is UNICODE, always returns false.
//
inline bool DBCSLEADBYTE(TCHAR ch)
{
if (sizeof(ch) == sizeof(char))
return boolify(IsDBCSLeadByte((BYTE)ch));
return false;
}
LPCTSTR CConfig::s_rgpszSubkeys[] = { REGSTR_KEY_OFFLINEFILES,
REGSTR_KEY_OFFLINEFILESPOLICY };
LPCTSTR CConfig::s_rgpszValues[] = { REGSTR_VAL_DEFCACHESIZE,
REGSTR_VAL_CSCENABLED,
REGSTR_VAL_GOOFFLINEACTION,
REGSTR_VAL_NOCONFIGCACHE,
REGSTR_VAL_NOCACHEVIEWER,
REGSTR_VAL_NOMAKEAVAILABLEOFFLINE,
REGSTR_VAL_SYNCATLOGOFF,
REGSTR_VAL_NOREMINDERS,
REGSTR_VAL_REMINDERFREQMINUTES,
REGSTR_VAL_INITIALBALLOONTIMEOUTSECONDS,
REGSTR_VAL_REMINDERBALLOONTIMEOUTSECONDS,
REGSTR_VAL_EVENTLOGGINGLEVEL,
REGSTR_VAL_PURGEATLOGOFF,
REGSTR_VAL_FIRSTPINWIZARDSHOWN,
REGSTR_VAL_SLOWLINKSPEED,
REGSTR_VAL_ALWAYSPINSUBFOLDERS};
//
// Returns the single instance of the CConfig class.
// Note that by making the singleton instance a function static
// object it is not created until the first call to GetSingleton.
//
CConfig& CConfig::GetSingleton(
void
)
{
static CConfig TheConfig;
return TheConfig;
}
//
// This is the workhorse of the CSCUI policy code for scalar values.
// The caller passes in a value (iVAL_XXXXXX) identifier from the eValues
// enumeration to identify the policy/preference value of interest.
// Known keys in the registry are scanned until a value is found.
// The scanning order enforces the precedence of policy vs. default vs.
// preference and machine vs. user.
//
DWORD CConfig::GetValue(
eValues iValue,
bool *pbSetByPolicy
) const
{
//
// This table identifies each DWORD policy/preference item used by CSCUI.
// The entries MUST be ordered the same as the eValues enumeration.
// Each entry describes the possible sources for data and a default value
// to be used if no registry entries are present or if there's a problem reading
// the registry.
//
static const struct Item
{
DWORD fSrc; // Mask indicating the reg locations to read.
DWORD dwDefault; // Hard-coded default.
} rgItems[] = {
// Value ID eSRC_PREF_CU | eSRC_PREF_LM | eSRC_POL_CU | eSRC_POL_LM Default value
// -------------------------------------- ------------ ------------ ----------- ----------- -------------------
/* iVAL_DEFCACHESIZE */ { eSRC_POL_LM, 1000 },
/* iVAL_CSCENABLED */ { eSRC_POL_LM, 1 },
/* iVAL_GOOFFLINEACTION */ { eSRC_PREF_CU | eSRC_POL_CU | eSRC_POL_LM, eGoOfflineSilent },
/* iVAL_NOCONFIGCACHE */ { eSRC_POL_CU | eSRC_POL_LM, 0 },
/* iVAL_NOCACHEVIEWER */ { eSRC_POL_CU | eSRC_POL_LM, 0 },
/* iVAL_NOMAKEAVAILABLEOFFLINE */ { eSRC_POL_CU | eSRC_POL_LM, 0 },
/* iVAL_SYNCATLOGOFF */ { eSRC_PREF_CU | eSRC_POL_CU | eSRC_POL_LM, eSyncFull },
/* iVAL_NOREMINDERS */ { eSRC_PREF_CU | eSRC_POL_CU | eSRC_POL_LM, 0 },
/* iVAL_REMINDERFREQMINUTES */ { eSRC_PREF_CU | eSRC_POL_CU | eSRC_POL_LM, 60 },
/* iVAL_INITIALBALLOONTIMEOUTSECONDS */ { eSRC_POL_CU | eSRC_POL_LM, 30 },
/* iVAL_REMINDERBALLOONTIMEOUTSECONDS */ { eSRC_POL_CU | eSRC_POL_LM, 15 },
/* iVAL_EVENTLOGGINGLEVEL */ { eSRC_PREF_CU | eSRC_PREF_LM | eSRC_POL_CU | eSRC_POL_LM, 0 },
/* iVAL_PURGEATLOGOFF */ { eSRC_POL_LM, 0 },
/* iVAL_FIRSTPINWIZARDSHOWN */ { eSRC_PREF_CU , 0 },
/* iVAL_SLOWLINKSPEED */ { eSRC_PREF_CU | eSRC_PREF_LM | eSRC_POL_CU | eSRC_POL_LM, 640 },
/* iVAL_ALWAYSPINSUBFOLDERS */ { eSRC_POL_LM, 0 }
};
//
// This table maps registry keys and subkey names to our
// source mask values. The array is ordered with the highest
// precedence sources first. A policy level mask is also
// associated with each entry so that we honor the "big switch"
// for enabling/disabling CSCUI policies.
//
static const struct Source
{
eSources fSrc; // Source for reg data.
HKEY hkeyRoot; // Root key in registry (hkcu, hklm).
eSubkeys iSubkey; // Index into s_rgpszSubkeys[]
} rgSrcs[] = { { eSRC_POL_LM, HKEY_LOCAL_MACHINE, iSUBKEY_POL },
{ eSRC_POL_CU, HKEY_CURRENT_USER, iSUBKEY_POL },
{ eSRC_PREF_CU, HKEY_CURRENT_USER, iSUBKEY_PREF },
{ eSRC_PREF_LM, HKEY_LOCAL_MACHINE, iSUBKEY_PREF }
};
const Item& item = rgItems[iValue];
DWORD dwResult = item.dwDefault; // Set default return value.
bool bSetByPolicy = false;
//
// Iterate over all of the sources until we find one that is specified
// for this item. For each iteration, if we're able to read the value,
// that's the one we return. If not we drop down to the next source
// in the precedence order (rgSrcs[]) and try to read it's value. If
// we've tried all of the sources without a successful read we return the
// hard-coded default.
//
for (int i = 0; i < ARRAYSIZE(rgSrcs); i++)
{
const Source& src = rgSrcs[i];
//
// Is this source valid for this item?
//
if (0 != (src.fSrc & item.fSrc))
{
//
// This source is valid for this item. Read it.
//
DWORD cbResult = sizeof(dwResult);
DWORD dwType;
if (ERROR_SUCCESS == SHGetValue(src.hkeyRoot,
s_rgpszSubkeys[src.iSubkey],
s_rgpszValues[iValue],
&dwType,
&dwResult,
&cbResult))
{
//
// We read a value from the registry so we're done.
//
bSetByPolicy = (0 != (eSRC_POL & src.fSrc));
break;
}
}
}
if (NULL != pbSetByPolicy)
*pbSetByPolicy = bSetByPolicy;
return dwResult;
}
//
// Save a custom GoOfflineAction list to the registry.
// See comments for LoadCustomGoOfflineActions for formatting details.
//
HRESULT
CConfig::SaveCustomGoOfflineActions(
RegKey& key,
const CArray<CConfig::CustomGOA>& rgCustomGOA
)
{
DBGTRACE((DM_CONFIG, DL_MID, TEXT("CConfig::SaveCustomGoOfflineActions")));
DBGPRINT((DM_CONFIG, DL_LOW, TEXT("Saving %d actions"), rgCustomGOA.Count()));
HRESULT hr = NOERROR;
int cValuesNotDeleted = 0;
key.DeleteAllValues(&cValuesNotDeleted);
if (0 != cValuesNotDeleted)
{
DBGERROR((TEXT("%d GoOfflineAction values not deleted from registry"),
cValuesNotDeleted));
}
CString strServer;
TCHAR szAction[20];
int cGOA = rgCustomGOA.Count();
for (int i = 0; i < cGOA; i++)
{
//
// Write each sharename-action pair to the registry.
// The action value must be converted to ASCII to be
// compatible with the values generated by poledit.
//
wsprintf(szAction, TEXT("%d"), DWORD(rgCustomGOA[i].GetAction()));
rgCustomGOA[i].GetServerName(&strServer);
hr = key.SetValue(strServer, szAction);
if (FAILED(hr))
{
DBGERROR((TEXT("Error 0x%08X saving GoOfflineAction for \"%s\" to registry."),
hr, strServer.Cstr()));
break;
}
}
return hr;
}
bool
CConfig::CustomGOAExists(
const CArray<CustomGOA>& rgGOA,
const CustomGOA& goa
)
{
int cEntries = rgGOA.Count();
CString strServer;
for (int i = 0; i < cEntries; i++)
{
if (0 == goa.CompareByServer(rgGOA[i]))
return true;
}
return false;
}
//
// Builds an array of Go-offline actions.
// Each entry is a server-action pair.
//
void
CConfig::GetCustomGoOfflineActions(
CArray<CustomGOA> *prgGOA,
bool *pbSetByPolicy // optional. Can be NULL.
)
{
static const struct Source
{
eSources fSrc; // Source for reg data.
HKEY hkeyRoot; // Root key in registry (hkcu, hklm).
eSubkeys iSubkey; // Index into s_rgpszSubkeys[]
} rgSrcs[] = { { eSRC_POL_LM, HKEY_LOCAL_MACHINE, iSUBKEY_POL },
{ eSRC_POL_CU, HKEY_CURRENT_USER, iSUBKEY_POL },
{ eSRC_PREF_CU, HKEY_CURRENT_USER, iSUBKEY_PREF }
};
prgGOA->Clear();
CString strName;
HRESULT hr;
bool bSetByPolicyAny = false;
bool bSetByPolicy = false;
//
// Iterate over all of the possible sources.
//
for (int i = 0; i < ARRAYSIZE(rgSrcs); i++)
{
const Source& src = rgSrcs[i];
//
// Is this source valid for the current policy level?
// Note that policy level is ignored if source is preference.
//
if (0 != (eSRC_PREF & src.fSrc))
{
RegKey key(src.hkeyRoot, s_rgpszSubkeys[src.iSubkey]);
if (SUCCEEDED(key.Open(KEY_READ)))
{
RegKey keyGOA(key, REGSTR_SUBKEY_CUSTOMGOOFFLINEACTIONS);
if (SUCCEEDED(keyGOA.Open(KEY_READ)))
{
TCHAR szValue[20];
DWORD dwType;
DWORD cbValue = sizeof(szValue);
RegKey::ValueIterator iter = keyGOA.CreateValueIterator();
while(S_OK == (hr = iter.Next(&strName, &dwType, (LPBYTE)szValue, &cbValue)))
{
if (REG_SZ == dwType)
{
//
// Convert from "0","1","2" to 0,1,2
//
DWORD dwValue = szValue[0] - TEXT('0');
if (IsValidGoOfflineAction(dwValue))
{
//
// Only add if value is of proper type and value.
// Protects against someone manually adding garbage
// to the registry.
//
// Server names can also be entered into the registry
// using poledit (and winnt.adm). This entry mechanism
// can't validate format so we need to ensure the entry
// doesn't have leading '\' or space characters.
//
LPCTSTR pszServer = strName.Cstr();
while(*pszServer && (TEXT('\\') == *pszServer || TEXT(' ') == *pszServer))
pszServer++;
bSetByPolicy = (0 != (src.fSrc & eSRC_POL));
bSetByPolicyAny = bSetByPolicyAny || bSetByPolicy;
CustomGOA goa = CustomGOA(pszServer,
(CConfig::OfflineAction)dwValue,
bSetByPolicy);
if (!CustomGOAExists(*prgGOA, goa))
{
prgGOA->Append(goa);
}
}
else
{
DBGERROR((TEXT("GoOfflineAction value %d invalid for \"%s\""),
dwValue, strName.Cstr()));
}
}
else
{
DBGERROR((TEXT("GoOfflineAction for \"%s\" has invalid reg type %d"),
strName.Cstr(), dwType));
}
}
}
}
}
}
if (NULL != pbSetByPolicy)
*pbSetByPolicy = bSetByPolicyAny;
}
//
// Retrieve the go-offline action for a specific server. If the server
// has a "customized" action defined by either system policy or user
// setting, that action is used. Otherwise, the "default" action is
// used.
//
int
CConfig::GoOfflineAction(
LPCTSTR pszServer
) const
{
DBGTRACE((DM_CONFIG, DL_HIGH, TEXT("CConfig::GoOfflineAction(server)")));
DBGPRINT((DM_CONFIG, DL_HIGH, TEXT("\tServer = \"%s\""), pszServer ? pszServer : TEXT("<null>")));
int iAction = GoOfflineAction(); // Get default action.
if (NULL == pszServer)
return iAction;
DBGASSERT((NULL != pszServer));
//
// Skip passed any leading backslashes for comparison.
// The values we store in the registry don't have a leading "\\".
//
while(*pszServer && TEXT('\\') == *pszServer)
pszServer++;
CConfig::OfflineActionInfo info;
CConfig::OfflineActionIter iter = CreateOfflineActionIter();
while(iter.Next(&info))
{
if (0 == lstrcmpi(pszServer, info.szServer))
{
DBGPRINT((DM_CONFIG, DL_HIGH, TEXT("Action is %d for share \"%s\""), info.iAction, info.szServer));
iAction = info.iAction; // Return custom action.
break;
}
}
//
// Guard against bogus reg data.
//
if (eNumOfflineActions <= iAction || 0 > iAction)
iAction = eGoOfflineSilent;
DBGPRINT((DM_CONFIG, DL_HIGH, TEXT("Action is %d (default)"), iAction));
return iAction;
}
//-----------------------------------------------------------------------------
// CConfig::CustomGOA
// "GOA" is "Go Offline Action"
//-----------------------------------------------------------------------------
bool
CConfig::CustomGOA::operator < (
const CustomGOA& rhs
) const
{
int diff = CompareByServer(rhs);
if (0 == diff)
diff = m_action - rhs.m_action;
return diff < 0;
}
//
// Compare two CustomGoOfflineAction objects by their
// server names. Comparison is case-insensitive.
// Returns: <0 = *this < rhs
// 0 = *this == rhs
// >0 = *this > rhs
//
int
CConfig::CustomGOA::CompareByServer(
const CustomGOA& rhs
) const
{
return GetServerName().CompareNoCase(rhs.GetServerName());
}
//-----------------------------------------------------------------------------
// CConfig::OfflineActionIter
//-----------------------------------------------------------------------------
bool
CConfig::OfflineActionIter::Next(
OfflineActionInfo *pInfo
)
{
bool bResult = false;
//
// Exception-phobic code may be calling this.
//
try
{
if (-1 == m_iAction)
{
m_pConfig->GetCustomGoOfflineActions(&m_rgGOA);
m_iAction = 0;
}
if (m_iAction < m_rgGOA.Count())
{
CString s;
m_rgGOA[m_iAction].GetServerName(&s);
lstrcpyn(pInfo->szServer, s, ARRAYSIZE(pInfo->szServer));
pInfo->iAction = (DWORD)m_rgGOA[m_iAction++].GetAction();
bResult = true;
}
}
catch(...)
{
}
return bResult;
}
#ifdef _USE_EXT_EXCLUSION_LIST
/*
//
// I originally wrote this code assuming our UI code would want to
// know about excluded extensions. As it turns out, only the CSC agent
// cares about these and ShishirP has his own code for reading these
// entries. I've left the code more as documentation for how the list
// is implemented and how one might merge multiple lists into a single
// list. It's also been left in case the UI code does eventually need
// access to excluded extensions. [brianau - 3/15/99]
//
//
// Refresh the "excluded file extension" list from the registry.
// The resulting list is a double-nul terminated list of filename extensions.
// The lists from HKLM and HKCU are merged together to form one list.
// Duplicates are removed.
// Leading spaces and periods are removed from each entry.
// Trailing whitespace is removed from each entry.
// Embedded whitespace is preserved for each entry.
// On exit, m_ptrExclExt points to the new list or contains NULL if there is no list.
//
// i.e.: ".PDB; DBF ,CPP, Html File\0" -> "PDB\0DBF\0CPP\0Html File\0\0"
//
// Note that code must be DBCS aware.
//
void
CConfig::RefreshExclusionList(
RegKey& keyLM,
RegKey& keyCU
) const
{
DBGTRACE((DM_CONFIG, DL_MID, TEXT("CConfig::RefreshExclusionList")));
HRESULT hr = NOERROR;
m_ptrExclExt = NULL;
CArray<CString> rgExtsLM;
CArray<CString> rgExtsCU;
CArray<CString> rgExts;
//
// Get each exclusion array (LM and CU) then merge them together
// into one (removing duplicates).
//
GetOneExclusionArray(keyLM, &rgExtsLM);
GetOneExclusionArray(keyCU, &rgExtsCU);
MergeStringArrays(rgExtsLM, rgExtsCU, &rgExts);
//
// Calculate how many characters are needed to create a single
// double-nul term list of the extensions. We could use the
// merged array as the final holding place for the extensions
// however that's not very efficient for storing lot's of very
// short strings (i.e. extensions). This way the array objects
// are only temporary.
//
int i;
int cch = 0;
int n = rgExts.Count();
for (i = 0; i < n; i++)
{
cch += rgExts[i].Length() + 1; // +1 for nul term.
}
if (0 < cch)
{
cch++; // Final nul term.
LPTSTR s0;
LPTSTR s = s0 = new TCHAR[cch];
for (i = 0; i < n; i++)
{
lstrcpy(s, rgExts[i]);
s += rgExts[i].Length() + 1;
}
*s = TEXT('\0'); // Final nul term.
m_ptrExclExt = s0;
}
}
//
// Advance a character pointer past any space or dot characters.
//
LPCTSTR
CConfig::SkipDotsAndSpaces( // [ static ]
LPCTSTR s
)
{
while(s && *s && (TEXT('.') == *s || TEXT(' ') == *s))
s++;
return s;
}
//
// Removes any duplicate extension strings from a CString array.
// This function assumes the array is sorted.
//
void
CConfig::RemoveDuplicateStrings(
CArray<CString> *prgExt
) const
{
DBGTRACE((DM_CONFIG, DL_LOW, TEXT("CConfig::RemoveDuplicateStrings")));
CArray<CString>& rg = *prgExt;
int n = rg.Count();
while(0 < --n)
{
if (rg[n] == rg[n-1])
rg.Delete(n);
}
}
//
// Merge two arrays of CString objects into a single
// array containing no duplicates. The returned array is
// in sorted order.
//
void
CConfig::MergeStringArrays(
CArray<CString>& rgExtsA,
CArray<CString>& rgExtsB,
CArray<CString> *prgMerged
) const
{
DBGTRACE((DM_CONFIG, DL_LOW, TEXT("CConfig::MergeStringArrays")));
int nA = rgExtsA.Count();
int nB = rgExtsB.Count();
if (0 == nA || 0 == nB)
{
//
// A quick optimization if one of the arrays is empty.
// We can just copy the non-empty one.
//
if (0 == nA)
*prgMerged = rgExtsB;
else
*prgMerged = rgExtsA;
prgMerged->BubbleSort();
}
else
{
//
// Both arrays have content so we must merge.
//
rgExtsA.BubbleSort();
rgExtsB.BubbleSort();
prgMerged->Clear();
int iA = 0;
int iB = 0;
for (int i = 0; i < nA+nB; i++)
{
if (iA >= nA)
{
prgMerged->Append(rgExtsB[iB++]); // 'A' list exhausted.
}
else if (iB >= nB)
{
prgMerged->Append(rgExtsA[iA++]); // 'B' list exhausted.
}
else
{
int diff = rgExtsA[iA].CompareNoCase(rgExtsB[iB]);
prgMerged->Append((0 >= diff ? rgExtsA[iA++] : rgExtsB[iB++]));
}
}
}
RemoveDuplicateStrings(prgMerged);
}
//
// Read one extension exclusion list from the registry.
// Break it up into the individual extensions, skipping any
// leading spaces and periods. Each extension is appended
// to an array of extension strings.
//
void
CConfig::GetOneExclusionArray(
RegKey& key,
CArray<CString> *prgExts
) const
{
DBGTRACE((DM_CONFIG, DL_LOW, TEXT("CConfig::GetOneExclusionArray")));
prgExts->Clear();
if (key.IsOpen() && S_OK == key.ValueExists(REGSTR_VAL_EXTEXCLUSIONLIST))
{
AutoLockCs lock(m_cs);
CString s;
HRESULT hr = key.GetValue(REGSTR_VAL_EXTEXCLUSIONLIST, &s);
if (SUCCEEDED(hr))
{
//
// Build an array of CStrings. One element for each of the
// extensions in the policy value.
//
LPTSTR ps0;
LPTSTR ps = ps0 = s.GetBuffer(); // No need for Release() later.
LPTSTR psEnd = ps + s.Length();
while(ps <= psEnd)
{
bool bAddThis = false;
if (!DBCSLEADBYTE(*ps))
{
if (TEXT('.') != *ps)
{
//
// Skip leading periods.
// Replace semicolons and commas with nul.
//
if (TEXT(';') == *ps || TEXT(',') == *ps)
{
*ps = TEXT('\0');
bAddThis = true;
}
}
}
if (ps == psEnd)
{
//
// Pick up last item in list.
//
bAddThis = true;
}
if (bAddThis)
{
CString sAdd(SkipDotsAndSpaces(ps0));
sAdd.Rtrim();
if (0 < sAdd.Length()) // Don't add a blank string.
prgExts->Append(sAdd);
ps0 = ps + 1;
}
ps++;
}
}
else
{
DBGERROR((TEXT("Error 0x%08X reading reg value \"%s\""),
hr, REGSTR_VAL_EXTEXCLUSIONLIST));
}
}
}
//
// Determine if a particular file extension is included in the
// exclusion list.
//
bool
CConfig::ExtensionExcluded(
LPCTSTR pszExt
) const
{
bool bExcluded = false;
ExcludedExtIter iter = CreateExcludedExtIter();
LPCTSTR psz;
while(iter.Next(&psz))
{
if (0 == lstrcmpi(psz, pszExt))
{
bExcluded = true;
break;
}
}
return bExcluded;
}
//-----------------------------------------------------------------------------
// CConfig::ExcludedExtIter
//-----------------------------------------------------------------------------
CConfig::ExcludedExtIter::ExcludedExtIter(
const CConfig::ExcludedExtIter& rhs
) : m_pszExts(NULL)
{
*this = rhs;
}
CConfig::ExcludedExtIter&
CConfig::ExcludedExtIter::operator = (
const CConfig::ExcludedExtIter& rhs
)
{
if (&rhs != this)
{
delete[] m_pszExts;
m_pszExts = NULL;
if (NULL != rhs.m_pszExts)
m_pszExts = CopyDblNulList(rhs.m_pszExts);
m_iter.Attach(m_pszExts);
}
return *this;
}
//
// Returns length of required buffer in characters
// including the final nul terminator.
//
int
CConfig::ExcludedExtIter::DblNulListLen(
LPCTSTR psz
)
{
int len = 0;
while(psz && (*psz || *(psz+1)))
{
len++;
psz++;
}
return psz ? len + 2 : 0;
}
//
// Copies a double-nul terminated list. Returns address
// of new copy. Caller must free new list using delete[].
//
LPTSTR
CConfig::ExcludedExtIter::CopyDblNulList(
LPCTSTR psz
)
{
LPTSTR s0 = NULL;
if (NULL != psz)
{
int cch = DblNulListLen(psz); // Incl final nul.
LPTSTR s = s0 = new TCHAR[cch];
while(0 < cch--)
*s++ = *psz++;
}
return s0;
}
*/
#endif // _USE_EXT_EXCLUSION_LIST
| [
"[email protected]"
] | |
192077e80d5eeb0288eb1b8b443ba390df4c5e0d | 711e5c8b643dd2a93fbcbada982d7ad489fb0169 | /XPSP1/NT/net/ias/providers/ntuser/eap/eaptype.h | 988cfbd4dca1dc124c53cbf67236e92cf4052412 | [] | no_license | aurantst/windows-XP-SP1 | 629a7763c082fd04d3b881e0d32a1cfbd523b5ce | d521b6360fcff4294ae6c5651c539f1b9a6cbb49 | refs/heads/master | 2023-03-21T01:08:39.870106 | 2020-09-28T08:10:11 | 2020-09-28T08:10:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,627 | h | ///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 1998, Microsoft Corp. All rights reserved.
//
// FILE
//
// EAPType.h
//
// SYNOPSIS
//
// This file describes the class EAPType.
//
// MODIFICATION HISTORY
//
// 01/15/1998 Original version.
// 09/12/1998 Add standaloneSupported flag.
//
///////////////////////////////////////////////////////////////////////////////
#ifndef _EAPTYPE_H_
#define _EAPTYPE_H_
#include <nocopy.h>
#include <raseapif.h>
#include <iaslsa.h>
#include <iastlutl.h>
using namespace IASTL;
///////////////////////////////////////////////////////////////////////////////
//
// CLASS
//
// EAPType
//
// DESCRIPTION
//
// This class provides a wrapper around a DLL implementing a particular
// EAP type.
//
///////////////////////////////////////////////////////////////////////////////
class EAPType
: public PPP_EAP_INFO, private NonCopyable
{
public:
EAPType(PCWSTR name, DWORD typeID, BOOL standalone);
~EAPType() throw ();
DWORD load(PCWSTR dllPath) throw ();
const IASAttribute& getFriendlyName() const throw ()
{ return eapFriendlyName; }
BOOL isSupported() const throw ()
{ return standaloneSupported || IASGetRole() != IAS_ROLE_STANDALONE; }
protected:
// The friendly name of the provider.
IASAttribute eapFriendlyName;
// TRUE if this type is supported on stand-alone servers.
BOOL standaloneSupported;
// The DLL containing the EAP provider extension.
HINSTANCE dll;
};
#endif // _EAPTYPE_H_
| [
"[email protected]"
] | |
4f3080be805f6901ccf6d980e509e8cab46b573f | 7b382c6ee032d1ecd4618baf317f3f91d0ab52c2 | /dfs/sample-pseudocode-impl.cpp | 42b6eecc8c18498526a2d1492ec7abf9c1076567 | [] | no_license | shubhampathak09/codejam | 3a632cc67a3f81945f2b452eaf7807c0c8ef90bf | 2f497cfdb9d318dd6482236f93c5e14234bea613 | refs/heads/master | 2021-06-29T03:54:44.785611 | 2020-12-29T11:51:09 | 2020-12-29T11:51:09 | 147,506,585 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,751 | cpp | ////
//1. make real face from portraits
//deep learning + ai
//search a lot
//class Solution {
//public:
// int orangesRotting(vector<vector<int>>& grid) {
// int M = grid.size();
// int N = grid[0].size();
// queue<pair<int, int>> q;
// bool hasrotten = 0;
// for (int i = 0; i < M; i++) {
// for (int j = 0; j < N; j++) {
// if (grid[i][j] == 2) {
// q.push({i,j});
// grid[i][j] = 0;
// hasrotten = 1;
// }
// }
// }
// int minute = 0;
// while (!q.empty()) {
// int size = q.size();
// for (int i = 0; i < size; i++) {
// int r = q.front().first;
// int c = q.front().second;
// q.pop();
// if (r > 0 && grid[r-1][c] == 1) {
// q.push({r-1,c});
// grid[r-1][c] = 0;
// }
// if (c > 0 && grid[r][c-1] == 1) {
// q.push({r,c-1});
// grid[r][c-1] = 0;
// }
// if (r < M-1 && grid[r+1][c] == 1) {
// q.push({r+1,c});
// grid[r+1][c] = 0;
// }
// if (c < N-1 && grid[r][c+1] == 1) {
// q.push({r,c+1});
// grid[r][c+1] = 0;
// }
// }
// minute++;
// }
// minute -= 1;
// if (!hasrotten) minute = 0;
// for (int i = 0; i < M; i++) {
// for (int j = 0; j < N; j++) {
// if (grid[i][j] == 1) return -1;
// }
// }
// return minute;
// }
//};
| [
"[email protected]"
] | |
a7d92acb57df7c154a63e7dc33a888ff8a03ae91 | 184180d341d2928ab7c5a626d94f2a9863726c65 | /issuestests/icosa/inst/testfiles/EvenInterpolation_/libFuzzer_EvenInterpolation_/EvenInterpolation__DeepState_TestHarness.cpp | 04004f885e582ecafa381ad298289b4f5f68b106 | [] | no_license | akhikolla/RcppDeepStateTest | f102ddf03a22b0fc05e02239d53405c8977cbc2b | 97e73fe4f8cb0f8e5415f52a2474c8bc322bbbe5 | refs/heads/master | 2023-03-03T12:19:31.725234 | 2021-02-12T21:50:12 | 2021-02-12T21:50:12 | 254,214,504 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,059 | cpp | // AUTOMATICALLY GENERATED BY RCPPDEEPSTATE PLEASE DO NOT EDIT BY HAND, INSTEAD EDIT
// EvenInterpolation__DeepState_TestHarness_generation.cpp and EvenInterpolation__DeepState_TestHarness_checks.cpp
#include <fstream>
#include <RInside.h>
#include <iostream>
#include <RcppDeepState.h>
#include <qs.h>
#include <DeepState.hpp>
NumericVector EvenInterpolation_(NumericMatrix xyz, NumericVector origin, double critValue);
TEST(icosa_deepstate_test,EvenInterpolation__test){
static int rinside_flag = 0;
if(rinside_flag == 0)
{
rinside_flag = 1;
RInside R;
} std::time_t current_timestamp = std::time(0);
std::cout << "input starts" << std::endl;
NumericMatrix xyz = RcppDeepState_NumericMatrix();
std::string xyz_t = "/home/akhila/fuzzer_packages/fuzzedpackages/icosa/inst/testfiles/EvenInterpolation_/libFuzzer_EvenInterpolation_/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_xyz.qs";
qs::c_qsave(xyz,xyz_t,
"high", "zstd", 1, 15, true, 1);
std::cout << "xyz values: "<< xyz << std::endl;
NumericVector origin = RcppDeepState_NumericVector();
std::string origin_t = "/home/akhila/fuzzer_packages/fuzzedpackages/icosa/inst/testfiles/EvenInterpolation_/libFuzzer_EvenInterpolation_/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_origin.qs";
qs::c_qsave(origin,origin_t,
"high", "zstd", 1, 15, true, 1);
std::cout << "origin values: "<< origin << std::endl;
NumericVector critValue(1);
critValue[0] = RcppDeepState_double();
std::string critValue_t = "/home/akhila/fuzzer_packages/fuzzedpackages/icosa/inst/testfiles/EvenInterpolation_/libFuzzer_EvenInterpolation_/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_critValue.qs";
qs::c_qsave(critValue,critValue_t,
"high", "zstd", 1, 15, true, 1);
std::cout << "critValue values: "<< critValue << std::endl;
std::cout << "input ends" << std::endl;
try{
EvenInterpolation_(xyz,origin,critValue[0]);
}
catch(Rcpp::exception& e){
std::cout<<"Exception Handled"<<std::endl;
}
}
| [
"[email protected]"
] | |
b84c8086137fa333eded0f8952ca3f513853a3e9 | e5344eb6b99c3e1c990d26602c2b7eaee12ad630 | /Sort.cpp | 3c03c2411c481ba1096e0676ee3789a3e43791cc | [] | no_license | shhr3y/CPP | 4f25d3f11b5a6e9d6770ebffc9bb011f51259284 | 5d51e704c11022f8fdff1f95b5118dd35982189c | refs/heads/master | 2022-04-27T16:07:41.204753 | 2020-04-25T16:34:03 | 2020-04-25T16:34:03 | 258,823,321 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,116 | cpp | #include<iostream>
using namespace std;
int partition(int *arr,int start,int end){//Quick Sort
int i;
int pivot = arr[end];
int partitionIndx = start;
for(i=start;i<end;i++){
if(arr[i]<=pivot){
swap(arr[i],arr[partitionIndx]);
partitionIndx++;
}
}
swap(arr[partitionIndx],arr[end]);
return partitionIndx;
}void quicksort(int *arr,int start,int end){//Quick Sort
if(start < end){
int partitionIndx = partition(arr,start,end);
quicksort(arr,start,partitionIndx-1);
quicksort(arr,partitionIndx+1,end);
}
}
void selectionsort(int *arr,int num){// Selection Sort
int i,j;
int minIdx;
for(i = 0; i<num-1 ; i++){
minIdx = i;
for(j = i+1; j<num ; j++){
if(arr[j]<arr[minIdx])
minIdx = j;
}
if(minIdx!=i)
swap(arr[minIdx],arr[i]);
}
}
void insertionsort(int *arr,int num){//Insertion Sort
int i,hole,value;
for(i=1;i<num;i++){
value = arr[i];
hole = i;
while(hole>0 && arr[hole-1]>value){
arr[hole] = arr[hole-1];
hole--;
}
arr[hole] = value;
}
}
int main(){
int a[]={1,6,3,9,4,7};
insertionsort(a,6);
for(int i = 0;i<6;i++)
cout<<a[i]<<"\t";
} | [
"[email protected]"
] | |
bd6cf3ee6b63978d2ba02f98150b36b802531e6d | 1ec55de30cbb2abdbaed005bc756b37eafcbd467 | /Nacro/SDK/FN_Hospital_MountedTV_classes.hpp | deb2c52c27e3bb0543966c42c9096ddf74746e0b | [
"BSD-2-Clause"
] | permissive | GDBOI101/Nacro | 6e91dc63af27eaddd299b25351c82e4729013b0b | eebabf662bbce6d5af41820ea0342d3567a0aecc | refs/heads/master | 2023-07-01T04:55:08.740931 | 2021-08-09T13:52:43 | 2021-08-09T13:52:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 634 | hpp | #pragma once
// Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass Hospital_MountedTV.Hospital_MountedTV_C
// 0x0000 (0x0FD0 - 0x0FD0)
class AHospital_MountedTV_C : public ABuildingProp
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass Hospital_MountedTV.Hospital_MountedTV_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
1fffb09c62908166ff71e99e63d88cb0ef701795 | ee8d49632b7b50c146207f953484b658d938b528 | /compilador/compilador.h | e574f209798aa6f158807b1b11472bb601f80c64 | [] | no_license | DiegoMora2112/Compilador | 9396bb61f0d84bae4ad84869b8ac422aac8664d7 | ef1aba8157630557a1cd130618b3761e39b0ef5a | refs/heads/master | 2020-03-21T06:30:43.811950 | 2018-06-22T23:47:15 | 2018-06-22T23:47:15 | 138,225,160 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,813 | h | #include <string>
#include <fstream>
#include <iostream>
#include <stdlib.h>
#include <sstream>
#include <utility>
#include <map>
#include <iomanip>
#include <vector>
#include <cstring>
#include <stdio.h>
#include <ctype.h>
#include <map>
using namespace std;
typedef pair<string, int> clase;
class compilador{
private:
string fuente;
vector <string> lineas;
int nlineas, L_objeto;
vector <string> reservadas;
map <string,int> lpropiedades;
vector <string> numeros,operador,alpha;
//Este metodo se utiliza para crear las listas asociativas de los elmentos del token
void setPropiedades();
//Este metodo se encarga de identificar las lineas ingresadas en el archivo fuente
void setLineas(string);
vector <string> f_reservadas, f_operadores, f_ids, f_numeros,oper, lineas_objeto, nombres_f;
int L_var=0;
int L_ref=0;
string code;
map<string,string> funciones;
public:
//El constructor inserta la gramatica a las propiedades del objeto instanciado
compilador();
~compilador(){}
//Funcion para establecer las propiedades del compilador, lineas y fuente
void setCompilador(compilador*);
//Obtiene la cantidad de palabras reservadas
int getNreservadas();
//Muestra las palabras reservadas
void showReservadas();
//Metodo utilizado para abrir y obtener la informacion del archivo fuente
//Este metodo retorna un vector de caracteres
string getFuente();
//Este metodo se encarga de mostrar por consola las lineas encontradas en el archivo fuente
void showLineas();
//Este metodo devuelve la cantidad de lineas encontradas en el archivo fuente
int getNlineas();
//Este metodo se encarga de almacenar la informacion de las lineas del archivo fuente en un vector de
//Strings
void getLineas(vector <string>&);
//Este metodo se encarga de almacenar la informacion de las palabras reservadas del lenguaje en un vector de
//Strings, almacena las palabras reservadas encontradas en 1 linea en el vector pasado como parametro
void getReservadas(vector <string>&);
//Este metodo se encarga de almacenar la informacion de los operadores del lenguaje en un vector de
//Strings, almacena los operadores encontradas en 1 linea en el vector pasado como parametro
void getOperadores(vector <string>&);
//Este metodo revisa si en el vector de caracteres pasado como parametro existen palabras reservadas, si es el caso
//regresa la posicion inicial y final dentro del vector de caracteres en donde fue encontrada dicha palabra
string esReservada(string);
//Este metodo sobrecargado solo indica si existe una palabra reservada en un vector de caracteres
string setReservadas(string);
//Solo regresa el operador encontrado
string esOperador(string);
//Metodo que actualiza los operadores encontrados en el proceso de la creacion de los token
string setOperadores(string);
//Este metodo obtien todos los cracteres dentro del alfabeto {a-z} y {A-Z}
string getTexto(string);
//Recibe un vector de caracteres y regresa el identificador
string setIdentificadores(string);
//Este metodo se encarga de almacenar la informacion de los identificadores encontrados en un vector de
//Strings, almacena los identificadores encontrados en 1 linea en el vector pasado como parametro
void getIdentificadores(vector <string>&);
//Muestra las propiedades del token generadas a partir del analizis de una linea
void showlProp();
//Esto metodo regresa el numero encontrado dentro de un vector de caracteres
string setNumeros(string,bool&);
string setNumeros(string);
//Este metodo se encarga de almacenar la informacion de los numeros del lenguaje en un vector de
//Strings, almacena los numeros encontradas en 1 linea en el vector pasado como parametro
void getNumeros(vector <string>&);
//Este metodo crea y actualiza la informacion de los tokens generados, ademas de detectar si un numero es entero o flotante
void crearToken(string,compilador*, vector<string>&, vector<string>&,vector<string>&,vector<string>&,bool&);
//Este metodo se encarga de insertar el codigo en el archivo objeto
void emit();
//Este metodo recibe la informacion previamente analizada y genera el codigo intermedio
void generate(string &);
//Esta funcion revisa si los operadores involucrados en alguna posicion tiene el formato correcto
string getOperadores(string);
//Este metodo se utiliza para limpiar los vectores resultantes de la etapa de parseo
void clearVectors();
//Este metodo parsea los tokens generados en expresiones que seran recibidas por el metodo generate
string createLine(int);
//Metodo que crea las variables a utilizar en el archivo objeto
string createVar(int);
//Metodo que guarda la referencia a las lineas para realizar los branch (jumps)
string createRefLine(int);
};
| [
"[email protected]"
] | |
bc7e014821ab6c56f4513ebb8106e7b22569d226 | 5218656a16189e979d5b772dda679cbc39c194fc | /arrays/arrays-pointer.cpp | 961b1fd2b680dd830d83d3ef2c165f6f34f73bf8 | [] | no_license | wangqi0314/c.test | 9e92f944f864bd5d962a4869580cd8c4369f7957 | 42d62dab9e47fa30661eababa3ed0366dbf63a55 | refs/heads/master | 2020-04-20T11:11:57.963211 | 2019-02-02T08:00:52 | 2019-02-02T08:00:52 | 168,809,263 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,772 | cpp | #include <iostream>
using namespace std;
/**
* C++ 指向数组的指针
*
* 数组名是一个指向数组中第一个元素的常量指针
*
* 声明 : double balance[50]; double *p;
* p = balance; //这里的地址符号 '&' 可以省略,因为,数组变量名默认就是第一个元素的地址
* *(p + i) ; *(balance + i); //这两种表示方式,是相同的结果, 原理就是在指针的上一个位置加一;
*
*/
int main ()
{
// 带有 5 个元素的整型数组
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
p = balance;
// 输出数组中每个元素的值
cout << " 使用指针的数组值 " << endl;
for ( int i = 0; i < 5; i++ )
{
cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
cout << " (p + " << i << ") : ";
cout << (p + i) << endl;
}
cout << " 使用 balance 作为地址的数组值 " << endl;
for ( int i = 0; i < 5; i++ )
{
cout << "*(balance + " << i << ") : ";
cout << *(balance + i) << endl;
cout << " (balance + " << i << ") : ";
cout << (balance + i) << endl;
}
return 0;
}
// #include <stdio.h>
// int main ()
// {
// /* 带有 5 个元素的整型数组 */
// double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
// double *p;
// int i;
// p = balance;
// /* 输出数组中每个元素的值 */
// printf( "使用指针的数组值\n");
// for ( i = 0; i < 5; i++ )
// {
// printf("*(p + %d) : %f\n", i, *(p + i) );
// }
// printf( "使用 balance 作为地址的数组值\n");
// for ( i = 0; i < 5; i++ )
// {
// printf("*(balance + %d) : %f\n", i, *(balance + i) );
// }
// return 0;
// } | [
"[email protected]"
] | |
c902facc008a2a07bcdd6cdc2ea655ce1b9e5ba7 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/CMake/CMake-gumtree/Kitware_CMake_repos_basic_block_block_20885.cpp | 707ac5236ac8ecb50ae2afee538ec708765a36b7 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 411 | cpp | (UV_SUCCEEDED_WITHOUT_IOCP(success)) {
/* Process the req without IOCP. */
handle->reqs_pending++;
REGISTER_HANDLE_REQ(loop, handle, req);
uv_insert_pending_req(loop, (uv_req_t*)req);
} else if (UV_SUCCEEDED_WITH_IOCP(success)) {
/* The req will be processed with IOCP. */
handle->reqs_pending++;
REGISTER_HANDLE_REQ(loop, handle, req);
} else {
return WSAGetLastError();
} | [
"[email protected]"
] | |
2ae0ff81732f78b36d47fc3df47ec6f35fad1bd3 | 1d0b642683814c1369dbb0d84d897783d6c06f00 | /02-37.cpp | 8414f5bf10c8c0958b731faf9e0e3b577814bfe4 | [] | no_license | MisaghTavanpour/cppPrimer5thEdition | 78ed72382ef45a698de34e49220132884371b65a | a3516a9e126c84d2aead9205be77e51468da7a4d | refs/heads/main | 2023-01-29T20:34:21.137177 | 2020-12-08T03:29:46 | 2020-12-08T03:29:46 | 319,513,509 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 123 | cpp | int main() {
int a = 3, b = 4;
decltype(a) c = a; // int c = a;
decltype(a = b) d = a; // int &d = a
}
| [
"[email protected]"
] | |
d653b3029c2ed13d0646a70c5ced6db6ed94be93 | 489ed209c5efcc05a00690d8a14aaa7c5b387eb2 | /unittest/ast_test.cc | b026472ead65161ad6d3674aa0f2da8e1e7be1d4 | [
"MIT"
] | permissive | suluke/jnsn | 0f79bd05c1cfba32759574a82a0afcf7c3874a6e | ada62d75ea0b7adaed735333c60e412495fd4b42 | refs/heads/master | 2021-09-03T01:48:01.228299 | 2018-01-04T16:57:19 | 2018-01-04T17:07:23 | 105,984,947 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,808 | cc | #include "jnsn/js/ast.h"
#include "jnsn/js/ast_analysis.h"
#include "jnsn/js/ast_walker.h"
#include "gtest/gtest.h"
#include <sstream>
using namespace jnsn;
struct name_checker : public const_ast_node_visitor<const char *> {
#define NODE(NAME, CHILD_NODES) \
const char *accept(const NAME##_node &) override { return #NAME; }
#define DERIVED(NAME, ANCESTORS, CHILD_NODES) NODE(NAME, ANCESTOR)
#include "jnsn/js/ast.def"
};
TEST(ast_test, visitor) {
name_checker checker;
#define NODE_CHECK(NAME) \
{ \
NAME##_node node({}); \
ast_node &as_base = node; \
auto *res = checker.visit(as_base); \
ASSERT_STREQ(res, #NAME); \
}
#define NODE(NAME, CHILD_NODES) NODE_CHECK(NAME)
#define DERIVED(NAME, ANCESTORS, CHILD_NODES) NODE_CHECK(NAME)
#include "jnsn/js/ast.def"
#undef NODE_CHECK
}
TEST(ast_test, walker) {
std::stringstream ss;
ast_node_store store;
auto *node = store.make_module({});
auto *block1 = store.make_block({});
auto *block2 = store.make_block({});
node->stmts.emplace_back(block1);
node->stmts.emplace_back(block2);
struct walker : public ast_walker<walker> {
std::stringstream &ss;
walker(std::stringstream &ss) : ss(ss) {}
bool on_enter(const module_node &mod) override {
ss << "enter mod;";
return true;
}
void on_leave(const module_node &mod) override { ss << "leave mod;"; }
bool on_enter(const block_node &mod) override {
ss << "enter block;";
return true;
}
void on_leave(const block_node &mod) override { ss << "leave block;"; }
} wlk(ss);
wlk.visit(*node);
ASSERT_STREQ(
ss.str().c_str(),
"enter mod;enter block;leave block;enter block;leave block;leave mod;");
// Test early exit
ss.str("");
struct walker2 : public ast_walker<walker2> {
std::stringstream &ss;
walker2(std::stringstream &ss) : ss(ss) {}
bool on_enter(const module_node &mod) override {
ss << "enter mod;";
return false;
}
void on_leave(const module_node &mod) override { ss << "leave mod;"; }
bool on_enter(const block_node &mod) override {
ss << "enter block;";
return true;
}
void on_leave(const block_node &mod) override { ss << "leave block;"; }
} wlk2(ss);
wlk2.visit(*node);
ASSERT_STREQ(ss.str().c_str(), "enter mod;leave mod;");
}
TEST(ast_test, node_store) {
ast_node_store store;
auto node = store.make_module({});
name_checker checker;
auto res = checker.visit(*node);
ASSERT_STREQ(res, "module");
// stress test container insertion
constexpr int mod_count = 5000;
constexpr int stmt_count = 100;
std::vector<module_node *> modules;
modules.reserve(mod_count);
for (int i = 0; i < mod_count; i++) {
modules.emplace_back(store.make_module({}));
}
auto *stmt = store.make_empty_stmt({});
for (auto *mod : modules) {
for (int i = 0; i < stmt_count; i++) {
mod->stmts.emplace_back(stmt);
}
}
for (int i = 0; i < mod_count; i++) {
store.make_module({});
}
for (auto *mod : modules) {
ASSERT_EQ(mod->stmts.size(), (size_t)stmt_count);
}
}
TEST(ast_test, printing) {
ast_node_store store;
auto *node = store.make_module({});
std::stringstream ss;
ss << node;
ASSERT_EQ(ss.str(), "{\"type\": \"module\", \"stmts\": []}\n");
}
TEST(ast_test, analysis) {
ast_node_store store;
auto *node = store.make_function_expr({});
auto report = analyze_js_ast(*node);
ASSERT_TRUE(report);
}
| [
"[email protected]"
] | |
30d542c7ffeb6c2e447b4858039be2fe4e465190 | 8f11b828a75180161963f082a772e410ad1d95c6 | /tools/vision_tool_v2/src/Frame.cpp | cc6f259b0fd69c6a99ed82999d5924100f6d421e | [] | no_license | venkatarajasekhar/tortuga | c0d61703d90a6f4e84d57f6750c01786ad21d214 | f6336fb4d58b11ddfda62ce114097703340e9abd | refs/heads/master | 2020-12-25T23:57:25.036347 | 2017-02-17T05:01:47 | 2017-02-17T05:01:47 | 43,284,285 | 0 | 0 | null | 2017-02-17T05:01:48 | 2015-09-28T06:39:21 | C++ | UTF-8 | C++ | false | false | 14,173 | cpp | /*
* Copyright (C) 2008 Robotics at Maryland
* Copyright (C) 2008 Joseph Lisee <[email protected]>
* All rights reserved.
*
* Author: Joseph Lisee <[email protected]>
* File: tools/vision_tool/src/App.cpp
*/
// STD Includes
#include <iostream>
// Library Includes
#include <wx/frame.h>
#include <wx/menu.h>
#include <wx/sizer.h>
#include <wx/msgdlg.h>
#include <wx/dirdlg.h>
#include <wx/filedlg.h>
#include <wx/timer.h>
#include <wx/button.h>
#include <wx/textctrl.h>
#include <wx/utils.h>
#include <wx/filename.h>
#include <wx/stattext.h>
// For cvSaveImage
#include "highgui.h"
// Project Includes
#include "Frame.h"
#include "IPLMovie.h"
#include "MediaControlPanel.h"
#include "DetectorControlPanel.h"
#include "Model.h"
#include "vision/include/Image.h"
namespace ram {
namespace tools {
namespace visiontool {
BEGIN_EVENT_TABLE(Frame, wxFrame)
EVT_MENU(ID_Quit, Frame::onQuit)
EVT_MENU(ID_About, Frame::onAbout)
EVT_MENU(ID_OpenFile, Frame::onOpenFile)
EVT_MENU(ID_OpenCamera, Frame::onOpenCamera)
EVT_MENU(ID_OpenForwardCamera, Frame::onOpenForwardCamera)
EVT_MENU(ID_OpenDownwardCamera, Frame::onOpenDownwardCamera)
EVT_MENU(ID_SetDir, Frame::onSetDirectory)
EVT_MENU(ID_SaveImage, Frame::onSaveImage)
EVT_MENU(ID_SaveAsImage, Frame::onSaveAsImage)
END_EVENT_TABLE()
Frame::Frame(const wxString& title, const wxPoint& pos, const wxSize& size) :
wxFrame((wxFrame *)NULL, -1, title, pos, size),
m_mediaControlPanel(0),
m_rawMovie(0),
m_detectorMovie(0),
m_model(new Model),
m_idNum(1)
{
// File Menu
wxMenu *menuFile = new wxMenu;
menuFile->Append(ID_OpenFile, _T("Open Video &File"));
menuFile->Append(ID_OpenCamera, _T("Open Local CV &Camera"));
menuFile->Append(ID_OpenForwardCamera, _T("Open tortuga4:50000"));
menuFile->Append(ID_OpenDownwardCamera, _T("Open tortuga4:50001"));
menuFile->Append(ID_About, _T("&About..."));
menuFile->AppendSeparator();
menuFile->Append(ID_Quit, _T("E&xit\tCtrl+Q"));
// Image Menu
wxMenu *menuImage = new wxMenu;
menuImage->Append(ID_SetDir, _T("Set &Directory..."));
menuImage->AppendSeparator();
menuImage->Append(ID_SaveImage, _T("&Save\tCtrl+S"));
menuImage->Append(ID_SaveAsImage, _T("Save &Image..."));
wxMenuBar *menuBar = new wxMenuBar;
menuBar->Append( menuFile, _T("&File") );
menuBar->Append( menuImage, _T("&Image") );
SetMenuBar( menuBar );
// Create our controls
m_mediaControlPanel = new MediaControlPanel(m_model, this);
m_rawMovie = new IPLMovie(this, m_model, Model::NEW_RAW_IMAGE);
m_detectorMovie = new IPLMovie(this, m_model, Model::NEW_PROCESSED_IMAGE);
m_ch1Movie = new IPLMovie(this, m_model, Model::NEW_CH1_IMAGE, wxSize(320, 240));
m_ch2Movie = new IPLMovie(this, m_model, Model::NEW_CH2_IMAGE, wxSize(320, 240));
m_ch3Movie = new IPLMovie(this, m_model, Model::NEW_CH3_IMAGE, wxSize(320, 240));
m_ch1HistMovie = new IPLMovie(this, m_model, Model::NEW_CH1_HIST_IMAGE,
wxSize(120, 120));
m_ch2HistMovie = new IPLMovie(this, m_model, Model::NEW_CH2_HIST_IMAGE,
wxSize(120, 120));
m_ch3HistMovie = new IPLMovie(this, m_model, Model::NEW_CH3_HIST_IMAGE,
wxSize(120, 120));
m_ch12HistMovie = new IPLMovie(this, m_model, Model::NEW_CH12_HIST_IMAGE,
wxSize(120, 120));
m_ch23HistMovie = new IPLMovie(this, m_model, Model::NEW_CH23_HIST_IMAGE,
wxSize(120, 120));
m_ch13HistMovie = new IPLMovie(this, m_model, Model::NEW_CH13_HIST_IMAGE,
wxSize(120, 120));
wxButton* config = new wxButton(this, wxID_ANY, wxT("Config File"));
wxString defaultPath;
wxGetEnv(_T("RAM_SVN_DIR"), &defaultPath);
m_configText = new wxTextCtrl(this, wxID_ANY, defaultPath,
wxDefaultPosition, wxDefaultSize,
wxTE_READONLY);
wxButton* detectorHide = new wxButton(this, wxID_ANY,
wxT("Show/Hide Detector"));
// Place controls in the sizer
wxBoxSizer* sizer = new wxBoxSizer(wxVERTICAL);
sizer->Add(m_mediaControlPanel, 0, wxEXPAND, 0);
wxBoxSizer* row = new wxBoxSizer(wxHORIZONTAL);
row->Add(config, 0, wxALL, 3);
row->Add(m_configText, 1, wxALIGN_CENTER | wxTOP | wxBOTTOM, 3);
row->Add(detectorHide, 0, wxALL, 3);
sizer->Add(row, 0, wxEXPAND, 0);
wxBoxSizer* movieTitleSizer = new wxBoxSizer(wxHORIZONTAL);
movieTitleSizer->Add(
new wxStaticText(this, wxID_ANY, _T("Raw Image")),
1, wxEXPAND | wxALL, 2);
movieTitleSizer->Add(
new wxStaticText(this, wxID_ANY, _T("Detector Debug Output")),
1, wxEXPAND | wxALL, 2);
m_rawMovie->SetWindowStyle(wxBORDER_RAISED);
m_detectorMovie->SetWindowStyle(wxBORDER_RAISED);
wxBoxSizer* movieSizer = new wxBoxSizer(wxHORIZONTAL);
movieSizer->Add(m_rawMovie, 1, wxSHAPED | wxALL, 2);
movieSizer->Add(m_detectorMovie, 1, wxSHAPED | wxALL, 2);
sizer->Add(movieTitleSizer, 0, wxEXPAND | wxLEFT | wxRIGHT, 5);
sizer->Add(movieSizer, 4, wxEXPAND | wxLEFT | wxRIGHT, 5);
// Single Channel Histogram Sizers
wxBoxSizer *ch1HistSizer = new wxBoxSizer(wxVERTICAL);
wxStaticText *ch1HistText = new wxStaticText(this, wxID_ANY, _T("Ch1 Hist"));
ch1HistSizer->Add(ch1HistText, 0, wxEXPAND | wxALL, 1);
ch1HistSizer->Add(m_ch1HistMovie, 1, wxSHAPED);
wxBoxSizer *ch2HistSizer = new wxBoxSizer(wxVERTICAL);
wxStaticText *ch2HistText = new wxStaticText(this, wxID_ANY, _T("Ch2 Hist"));
ch2HistSizer->Add(ch2HistText, 0, wxEXPAND | wxALL, 1);
ch2HistSizer->Add(m_ch2HistMovie, 1, wxSHAPED);
wxBoxSizer *ch3HistSizer = new wxBoxSizer(wxVERTICAL);
wxStaticText *ch3HistText = new wxStaticText(this, wxID_ANY, _T("Ch3 Hist"));
ch3HistSizer->Add(ch3HistText, 0, wxEXPAND | wxALL, 1);
ch3HistSizer->Add(m_ch3HistMovie, 1, wxSHAPED);
// 2D Histogram Sizers
wxBoxSizer *ch12HistSizer = new wxBoxSizer(wxVERTICAL);
wxStaticText *ch12HistText = new wxStaticText(this, wxID_ANY, _T("Ch1 vs. Ch2 Hist"));
ch12HistSizer->Add(ch12HistText, 0, wxEXPAND | wxALL, 1);
ch12HistSizer->Add(m_ch12HistMovie, 1, wxSHAPED);
wxBoxSizer *ch23HistSizer = new wxBoxSizer(wxVERTICAL);
wxStaticText *ch23HistText = new wxStaticText(this, wxID_ANY, _T("Ch2 vs. Ch3 Hist"));
ch23HistSizer->Add(ch23HistText, 0, wxEXPAND | wxALL, 1);
ch23HistSizer->Add(m_ch23HistMovie, 1, wxSHAPED);
wxBoxSizer *ch13HistSizer = new wxBoxSizer(wxVERTICAL);
wxStaticText *ch13HistText = new wxStaticText(this, wxID_ANY, _T("Ch1 vs. Ch3 Hist"));
ch13HistSizer->Add(ch13HistText, 0, wxEXPAND | wxALL, 1);
ch13HistSizer->Add(m_ch13HistMovie, 1, wxSHAPED);
// Overall Sizer for Histograms
wxFlexGridSizer *histImgMovieSizer = new wxFlexGridSizer(2, 3, 0, 0);
histImgMovieSizer->Add(ch1HistSizer, 1, wxEXPAND | wxALL, 1);
histImgMovieSizer->Add(ch2HistSizer, 1, wxEXPAND | wxALL, 1);
histImgMovieSizer->Add(ch3HistSizer, 1, wxEXPAND | wxALL, 1);
histImgMovieSizer->Add(ch12HistSizer, 1, wxEXPAND | wxALL, 1);
histImgMovieSizer->Add(ch23HistSizer, 1, wxEXPAND | wxALL, 1);
histImgMovieSizer->Add(ch13HistSizer, 1, wxEXPAND | wxALL, 1);
// Individual Channel Image Sizers
wxBoxSizer *ch1Sizer = new wxBoxSizer(wxVERTICAL);
ch1Sizer->Add(
new wxStaticText(this, wxID_ANY, _T("Channel 1"), wxDefaultPosition,
wxDefaultSize, wxALIGN_LEFT),
0, wxEXPAND | wxLEFT | wxRIGHT, 5);
ch1Sizer->Add(m_ch1Movie, 1, wxSHAPED);
wxBoxSizer *ch2Sizer = new wxBoxSizer(wxVERTICAL);
ch2Sizer->Add(
new wxStaticText(this, wxID_ANY, _T("Channel 2"), wxDefaultPosition,
wxDefaultSize, wxALIGN_LEFT),
0, wxEXPAND | wxLEFT | wxRIGHT, 5);
ch2Sizer->Add(m_ch2Movie, 1, wxSHAPED);
wxBoxSizer *ch3Sizer = new wxBoxSizer(wxVERTICAL);
ch3Sizer->Add(
new wxStaticText(this, wxID_ANY, _T("Channel 3"), wxDefaultPosition,
wxDefaultSize, wxALIGN_LEFT),
0, wxEXPAND | wxLEFT | wxRIGHT, 5);
ch3Sizer->Add(m_ch3Movie, 1, wxSHAPED);
wxBoxSizer *smallMovieSizer = new wxBoxSizer(wxHORIZONTAL);
smallMovieSizer->Add(ch1Sizer, 1, wxSHAPED | wxALL, 2);
smallMovieSizer->Add(ch2Sizer, 1, wxSHAPED | wxALL, 2);
smallMovieSizer->Add(ch3Sizer, 1, wxSHAPED | wxALL, 2);
smallMovieSizer->Add(histImgMovieSizer, 1, wxEXPAND | wxALL, 2);
sizer->Add(smallMovieSizer, 2, wxEXPAND | wxRIGHT | wxLEFT | wxBOTTOM, 5);
sizer->SetSizeHints(this);
SetSizer(sizer);
// Create the seperate frame for the detector panel
wxPoint framePosition = GetPosition();
framePosition.x += GetSize().GetWidth();
wxSize frameSize(GetSize().GetWidth()/3, GetSize().GetHeight());
m_detectorFrame =
new wxFrame(this, wxID_ANY, _T("Detector Control"),
framePosition, frameSize);
// Add a sizer and the detector control panel to it
sizer = new wxBoxSizer(wxVERTICAL);
wxPanel* detectorControlPanel = new DetectorControlPanel(
m_model, m_detectorFrame);
sizer->Add(detectorControlPanel, 1, wxEXPAND, 0);
m_detectorFrame->SetSizer(sizer);
m_detectorFrame->Show();
// Register for events
Connect(detectorHide->GetId(), wxEVT_COMMAND_BUTTON_CLICKED,
wxCommandEventHandler(Frame::onShowHideDetector));
Connect(config->GetId(), wxEVT_COMMAND_BUTTON_CLICKED,
wxCommandEventHandler(Frame::onSetConfigPath));
// Connect(GetId(), wxEVT_CLOSE_WINDOW,
// wxCloseEventHandler(Frame::onClose), this);
// Connect(m_detectorFrame->GetId(), wxEVT_CLOSE_WINDOW,
// wxCloseEventHandler(Frame::onDetectorFrameClose), this);
}
void Frame::onQuit(wxCommandEvent& WXUNUSED(event))
{
m_model->stop();
Close(true);
}
void Frame::onClose(wxCloseEvent& event)
{
// Stop video playback when we shut down
Destroy();
}
void Frame::onAbout(wxCommandEvent& WXUNUSED(event))
{
wxMessageBox(_T("An application to view live or recored video"),
_T("About Vision Tool"), wxOK | wxICON_INFORMATION, this);
}
void Frame::onOpenFile(wxCommandEvent& event)
{
wxString filepath = wxFileSelector(_T("Choose a video file to open"));
if ( !filepath.empty() )
{
// Have the model open the file
m_model->openFile(std::string(filepath.mb_str()));
// Place the file name in the title bar
wxString filename;
wxString extension;
wxFileName::SplitPath(filepath, NULL, &filename, &extension);
SetTitle(wxString(_T("Vision Tool - ")) + filename + _T(".") +
extension);
}
}
void Frame::onOpenCamera(wxCommandEvent& event)
{
m_model->openCamera();
}
void Frame::onOpenForwardCamera(wxCommandEvent& event)
{
m_model->openNetworkCamera("tortuga4", 50000);
}
void Frame::onOpenDownwardCamera(wxCommandEvent& event)
{
m_model->openNetworkCamera("tortuga4", 50001);
}
void Frame::onSetDirectory(wxCommandEvent& event)
{
wxDirDialog chooser(this);
int id = chooser.ShowModal();
if (id == wxID_OK) {
m_saveDir = chooser.GetPath();
m_idNum = 1;
}
}
bool Frame::saveImage(wxString pathname, bool suppressError)
{
vision::Image* image = m_model->getLatestImage();
image->setPixelFormat(ram::vision::Image::PF_BGR_8);
// Check that there is an image to save
if (image == NULL) {
// Don't create the message dialog if we suppress the window
if (suppressError)
return false;
// Create a message saying there was an error saving
wxMessageDialog messageWindow(this,
_T("Error: Could not save the image.\n"
"(The video cannot be playing while "
"saving an image)"),
_T("ERROR!"), wxOK);
messageWindow.ShowModal();
return false;
}
// No error, save the image
image->setPixelFormat(ram::vision::Image::PF_BGR_8);
cvSaveImage(pathname.mb_str(wxConvUTF8),
image->asIplImage());
return true;
}
void Frame::onSaveAsImage(wxCommandEvent& event)
{
wxFileDialog saveWindow(this, _T("Save file..."), _T(""), _T(""),
_T("*.*"), wxSAVE | wxOVERWRITE_PROMPT);
int result = saveWindow.ShowModal();
if (result == wxID_OK) {
saveImage(saveWindow.GetPath());
}
}
wxString Frame::numToString(int num)
{
wxString s = wxString::Format(_T("%d"), num);
short zeros = 4 - s.length();
wxString ret;
ret.Append(_T('0'), zeros);
ret.Append(s);
ret.Append(_T(".png"));
return ret;
}
void Frame::onSaveImage(wxCommandEvent& event)
{
// Save to the default path
// Find a file that doesn't exist
wxFileName filename(m_saveDir, numToString(m_idNum));
while (filename.FileExists()) {
m_idNum++;
filename = wxFileName(m_saveDir, numToString(m_idNum));
}
wxString fullpath(filename.GetFullPath());
std::cout << "Quick save to " << fullpath.mb_str(wxConvUTF8) << std::endl;
// Save image and suppress any error to be handled by this function
bool ret = saveImage(fullpath, true);
if (!ret) {
std::cerr << "Quick save failed. Try stopping the video.\n";
}
}
void Frame::onShowHideDetector(wxCommandEvent& event)
{
// Toggle the shown status of the frame
m_detectorFrame->Show(!m_detectorFrame->IsShown());
}
void Frame::onDetectorFrameClose(wxCloseEvent& event)
{
// If we don't have to close, just hide the window
if (event.CanVeto())
{
m_detectorFrame->Hide();
event.Veto();
}
else
{
m_detectorFrame->Destroy();
}
}
void Frame::onSetConfigPath(wxCommandEvent& event)
{
wxString filename = wxFileSelector(_T("Choose a config file"),
m_configText->GetValue());
if ( !filename.empty() )
{
m_configText->SetValue(filename);
m_model->setConfigPath(std::string(filename.mb_str()));
}
}
} // namespace visiontool
} // namespace tools
} // namespace ram
| [
"[email protected]"
] | |
c7fc4795095f1e6bb39fc47ace18bba293c778bb | 5bc6877b9195cad9f0dce2d069e1e4ff81eeabc9 | /counted.cpp | c89ff43434045f05e075bed4462fa9df2eb55041 | [] | no_license | CamilaKhammatova/CPP-2019-2020-HW5 | 6c3d9bef1987969b0aeda906e4266fd22ecf6251 | 21fe516a251239f9d5bce4e24bb492ddef9d37b3 | refs/heads/master | 2020-09-23T20:38:30.320796 | 2019-12-08T19:17:14 | 2019-12-08T19:17:14 | 225,581,850 | 0 | 0 | null | 2019-12-03T09:34:27 | 2019-12-03T09:34:26 | null | UTF-8 | C++ | false | false | 176 | cpp | #include "counted.h"
int Counted::count_ = 0;
Counted::Counted()
{
count_++;
id_ = count_;
}
Counted::~Counted()
{
count_--;
}
int Counted::getId()
{
return id_;
}
| [
"[email protected]"
] | |
c29d2134b47fe52aec157d0a413f74dc7cf09283 | cdea61d0902389baf23ad46e269adaeb88f3f9a2 | /defineParameters.cpp | a1bfdd1306bb2eb070424c71eecd20a6636512aa | [] | no_license | roelkers/chrono-platform-model | 737546c5a5adc29f0eb13dba24c91346808d8774 | d2d6cde4a7e09645b413cae57781de712c115693 | refs/heads/master | 2021-05-05T01:03:30.322944 | 2018-04-06T11:33:16 | 2018-04-06T11:33:16 | 119,533,402 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 718 | cpp | #include "params.h"
#include "defineParameters.h"
#include "chrono/core/ChLog.h"
params defineParameters(){
params p;
p.towerHeight=100;
p.towerRadius=5;
p.towerDensity=600;
p.towerInitPos = ChVector<>(0, 0, 0);
p.towerInitDir = ChVector<>(0, 0, 1);
p.mooringLineNr = 3;
p.mooringDiameter = 0.15;
p.mooringYoungModulus = 200e9;
p.mooringRaleyghDamping = 0.000;
p.mooringNrElements = 5;
p.mooringL = 100;
p.mooringPosFairleadZ = 0;
p.mooringPosBottomZ = -100;
double sectionLength = p.mooringL/p.mooringNrElements;
GetLog() << "sectionLength: " << sectionLength << "\n";
p.mooringRestLength = sectionLength*0.3;
p.seaLevel = 0;
p.rhoWater = 1000;
p.g = 9.81;
return p;
}
| [
"[email protected]"
] | |
4730565361c0a63332b2e6631a3b07c649704f77 | c07cffaef958b70eded200b217e59ca2a3a815ac | /src/Vortex/Vortex.cpp | 883551ea94bdd60e559b9bfa4401ae3b9f8a0131 | [] | no_license | PietjeBell88/Vortex3D | a15eb97f7fe4e6ca27e7ddde75d9e8e69c1363ac | 5d45dec615be5a4eb894db0b5db795a6557bbc51 | refs/heads/master | 2021-01-20T00:50:29.745426 | 2009-11-29T15:17:22 | 2009-11-29T15:17:22 | 442,764 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,063 | cpp | // Copyright (c) 2009, Pietje Bell <[email protected]>
// 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 Pietje Bell Group 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.
///////////
// Headers
#include "Vortex.h"
/////////////
// Namespace
using std::string;
using blitz::TinyMatrix;
///////////////
// Constructor
Vortex::Vortex( const Vortex3dParam ¶m )
{
this->radius = param.radius;
this->velocity = param.velocity;
this->angle = param.angle;
this->fl_mu = param.fl_mu;
this->fl_density = param.fl_density;
this->fl_nu = param.fl_nu;
this->interpolate = param.interpolate;
this->rotategrav = param.rotategrav;
this->grid = param.roi_grid;
this->delimiter = param.roi_delimiter;
this->dx = param.roi_dx;
this->dy = param.roi_dy;
this->dz = param.roi_dz;
}
//////////////
// Destructor
Vortex::~Vortex() {}
////////////////////////////
// Initialize Interpolation
// Can't do interpolation initialization in the constructor, results in pure function call.
// As MSDN says: "Do not call overridable methods in constructors".
void Vortex::initInterpolate()
{
v.resize( grid(0), grid(1), grid(2) );
accelfluid.resize( grid(0), grid(1), grid(2) );
SetupVortexGrid( &v, &accelfluid );
}
////////////////////
// Public Functions
bool Vortex::outsideBox( const Vector3d &pos )
{
if ( pos(0) <= delimiter(0, 0) || pos(0) > delimiter(0, 1) ||
pos(1) <= delimiter(1, 0) || pos(1) > delimiter(1, 1) ||
pos(2) <= delimiter(2, 0) || pos(2) > delimiter(2, 1) )
{
return true;
}
return false;
}
Vector3d Vortex::getDuDtAt( const Vector3d &pos )
{
if ( interpolate == true )
return Interpolate3DCube( accelfluid, pos );
else
return dudtAngle( pos );
}
Vector3d Vortex::getVelocityAt( const Vector3d &pos )
{
if ( interpolate == true )
return Interpolate3DCube( v, pos );
else
return velocityAngle( pos );
}
VectorField Vortex::getVectorField()
{
return v;
}
///////////////////////////////////////////////////////////////////
// Transformation matrix from [v_r, v_phi, v_z] to [v_x, v_y, v_z]
TinyMatrix<double, 3, 3> Vortex::cil2Cart( double phi )
{
TinyMatrix<double, 3, 3> M;
M = cos(phi), -sin(phi), 0,
sin(phi), cos(phi), 0,
0, 0, 1;
return M;
}
//////////////////////////////////////////////////////////////////////////////////////
// Rotation matrix for rotation around the x axis ("folding the y-axis to the z-axis")
TinyMatrix<double, 3, 3> Vortex::rotate_x( double angle )
{
TinyMatrix<double, 3, 3> M;
M = 1, 0, 0,
0, cos(angle), -sin(angle),
0, sin(angle), cos(angle);
return M;
}
///////////////////
// Interpolation
Vector3d Vortex::Interpolate3DCube( const VectorField &v, const Vector3d &pos )
{
/*
This function interpolates the velocity in matrix U to the position of a particle at P.
It does this by interpolating linearly by assigning weights to each corner of the surrounding box.
This function requires uniform gridspacing.
*/
/*
Start by finding the lower index values of the box surrounding the particle.
Of course, this step requires that the size of the index does not exceed the integer gridRange.
*/
int i = static_cast<int> (floor((pos(0) - delimiter(0, 0)) / dx));
int j = static_cast<int> (floor((pos(1) - delimiter(1, 0)) / dy));
int k = static_cast<int> (floor((pos(2) - delimiter(2, 0)) / dz));
/*
* Calculate the weighting factors for each corner of the box
* Note: 0 <= x < 1 (and same for y and z)
* Because the position of the particle can be negative, make it positive first
* and then do a modulo. Doing modulo on a negavite value can be confusing and inconsistent.
*/
double x = fmod(pos(0) - delimiter(0, 0), dx) / dx;
double y = fmod(pos(1) - delimiter(1, 0), dy) / dy;
double z = fmod(pos(2) - delimiter(2, 0), dz) / dz;
//Do a weighted addition of all the corners of the cube surrounding the particle.
//Please note that v(i,j,k) is indeed a Vector3d
return v(i, j, k) * (1 - x) * (1 - y) * (1 - z) + v(i + 1, j, k) * x * (1
- y) * (1 - z) + v(i, j + 1, k) * (1 - x) * y * (1 - z) + v(i, j, k
+ 1) * (1 - x) * (1 - y) * z + v(i + 1, j, k + 1) * x * (1 - y) * z
+ v(i, j + 1, k + 1) * (1 - x) * y * z + v(i + 1, j + 1, k) * x * y
* (1 - z) + v(i + 1, j + 1, k + 1) * x * y * z;
}
////////////////////////////////////////
// Vortex Velocity and Du/Dt Getters
Vector3d Vortex::velocityCarthesian( const Vector3d &pos )
{
const double &x = pos(0);
const double &y = pos(1);
const double &z = pos(2);
double r = sqrt( x * x + y * y );
double phi = atan2( y, x );
return product( cil2Cart( phi ), velocityCylinder( r, phi, z ) );
}
Vector3d Vortex::dudtCarthesian( const Vector3d &pos )
{
const double &x = pos(0);
const double &y = pos(1);
const double &z = pos(2);
double r = sqrt( x * x + y * y );
double phi = atan2( y, x );
return product( cil2Cart( phi ), dudtCylinder( r, phi, z ) );
}
Vector3d Vortex::velocityAngle( const Vector3d &pos )
{
if (rotategrav)
return velocityCarthesian( pos );
else
return product( rotate_x( angle ), velocityCarthesian( product( rotate_x( -angle ), pos ) ) );
}
Vector3d Vortex::dudtAngle( const Vector3d &pos )
{
if (rotategrav)
return dudtCarthesian( pos );
else
return product( rotate_x( angle ), dudtCarthesian( product( rotate_x( -angle ), pos ) ) );
}
//////////////////////////
// Initialize Vortex Grid
void Vortex::SetupVortexGrid(VectorField *v, VectorField *accelfluid)
{
#pragma omp parallel for
for ( int i = 0; i < grid(0); i++ )
{
// What x-coordinate are we at?
double x = delimiter(0, 0) + i * dx;
for ( int j = 0; j < grid(1); j++ )
{
// What y-coordinate are we at?
double y = delimiter(1, 0) + j * dy;
for ( int k = 0; k < grid(2); k++ )
{
// What z-coordinate are we at?
double z = delimiter(2, 0) + k * dz;
// Calculate and set the velocities for each direction in the VectorField
// Of course you can't have a negative index, so save each at their index+1
(*v)(i, j, k) = velocityAngle( Vector3d( x, y, z ) );
(*accelfluid)(i, j, k) = dudtAngle( Vector3d( x, y, z ) );
}
}
}
}
| [
"[email protected]"
] | |
1f8edf1eb017079c774c537a594bb4dba85e32e7 | a9c268b492d91d3267683449f205b785785fcf28 | /GameEngine/Engine/Physics/Contacts.h | 4c5ca3539174078704745c9aa3d9a5a9d407631f | [] | no_license | oneillsimon/GameEngine_Old | 707698588c2108d82c8aaf50b775deacf8434cfa | 7dc3004fe34524067340f768afea65be99f588bf | refs/heads/master | 2021-05-28T14:17:01.750369 | 2015-03-02T15:27:50 | 2015-03-02T15:27:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,337 | h | #ifndef CONTACTS_H
#define CONTACTS_H
#include <math.h>
#include "../Core/Math3D.h"
#include "RigidBody.h"
class ContactResolver;
class Contact
{
private:
RigidBody* m_body[2];
float m_friction;
float m_restitution;
Vector3 m_contactPoint;
Vector3 m_contactNormal;
float m_penetration;
Matrix3 m_contactToWorld;
Vector3 m_contactVelocity;
float m_desiredDeltaVelocity;
Vector3 m_relativeContactPosition[2];
public:
void setBodyData(RigidBody* one, RigidBody* two, float friction, float restitution);
void calculateInternals(float duration);
void swapBodies();
void matchAwakeState();
void calculateDesiredDeltaVelocity(float duration);
Vector3 calculateLocalVelocity(unsigned bodyIndex, float duration);
void calculateContactBasis();
void applyImpulse(const Vector3& impulse, RigidBody* body, Vector3* veloctyChange, Vector3* rotationChange);
void applyVelocityChange(Vector3 velocityChange[2], Vector3 angularChange[2]);
void applyPositionChange(Vector3 linearChange[2], Vector3 angularChange[2], float penetration);
Vector3 calculateFrictionlessImpulse(Matrix3* inverseIntertiaTensor);
Vector3 calculateFrictionImpulse(Matrix3* inverseIntertiaTensor);
void addContactVelocity(const Vector3& deltaVelocity);
void addPenetration(float deltaPenetration);
RigidBody* getBody(unsigned index);
float getFriction();
float getRestitution();
Vector3 getContactPoint() const;
Vector3 getContactNormal() const;
float getPenetration();
Matrix3 getContactToWorld() const;
Vector3 getContactVelocity() const;
float getDesiredDeltaVelocity();
Vector3 getRelativeContactPosition(unsigned index);
void setBody(RigidBody* body, unsigned index);
void setFriction(float friction);
void setRestitution(float restitution);
void setContactPoint(const Vector3& contactPoint);
void setContactNormal(const Vector3& contactNormal);
void setPenetration(float penetration);
void setContactToWorld(const Matrix3& contactToWorld);
void setContactVelocity(const Vector3& contactVelocity);
void setDesiredDeltaVelocity(float desiredDeltaVelocity);
void setRelativeContactPosition(const Vector3& contactPosition, unsigned index);
};
class ContactResolver
{
protected:
unsigned m_velocityIterations;
unsigned m_positionIterations;
float m_velocityEpsilon;
float m_positionEpsilon;
public:
unsigned m_velocityIterationsUsed;
unsigned m_positionIterationsUsed;
private:
bool m_validSettings;
public:
ContactResolver(unsigned iterations, float velocityEpsilon = 0.01f, float positionEpsilon = 0.01f);
ContactResolver(unsigned velocityIterations, unsigned positionIterations, float velocityEpsilon = 0.01f, float positionEpsilon = 0.01f);
bool isValid();
void setIterations(unsigned velocityIterations, unsigned positionIterations);
void setIterations(unsigned iterations);
void setEpsilon(float velocityEpsilon, float positionEpsilon);
void resolveContacts(Contact* contactArray, unsigned numContacts, float duration);
protected:
void prepareContacts(Contact* contactArray, unsigned numContacts, float duration);
void adjustVelocities(Contact* contactArray, unsigned numContacts, float duration);
void adjustPositions(Contact* contacts, unsigned numContacts, float duration);
};
class ContactGenerator
{
public:
virtual unsigned addContact(Contact* contact, unsigned limit) const = 0;
};
#endif | [
"[email protected]"
] | |
8806ccb50c87813b03f9719a7ac8463674e0027c | 80609332c2eca5527a19337a463a6f5543c5f103 | /P3Lab7_HectorReyes/Persona.cpp | 6927ce8949a86892fe4bd37100f872bcf1d32bd8 | [] | no_license | OnasisReyes9/P3Lab7_HectorReyes | ff3f4f13add4c311370503012421855a32dff2a6 | fca03a52dfccb50701098c4b011e4ed3d584ae40 | refs/heads/master | 2023-01-18T19:00:27.596664 | 2020-11-28T00:30:15 | 2020-11-28T00:30:15 | 316,581,739 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,684 | cpp | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/*
* File: Persona.cpp
* Author: Onasis Reyes
*
* Created on 27 de noviembre de 2020, 01:24 PM
*/
#include "Persona.h"
Persona::Persona() {
}
Persona::Persona(string nombre, string apellido, string password, int llave, int pos_en_registro) {
this -> nombre = nombre;
this -> apellido = apellido;
this -> password = password;
this -> llave = llave;
this -> pos_en_registro = pos_en_registro;
}
Persona::Persona(const Persona& orig) {
}
Persona::~Persona() {
}
void Persona::setNombre(string nombre) {
this -> nombre = nombre;
}
string Persona::getNombre() {
return nombre;
}
void Persona::setApellido(string apellido) {
this -> apellido = apellido;
}
string Persona::getApellido() {
return apellido;
}
void Persona::setPassword(string password) {
this -> password = password;
}
string Persona::getPassword() {
return password;
}
void Persona::setLlave(int llave) {
this -> llave = llave;
}
int Persona::getLlave() {
return llave;
}
int Persona::getPosicion_de_Registro() {
return pos_en_registro;
}
void Persona::setPosicion_de_Registro(int pos_de_registro) {
this -> pos_en_registro = pos_de_registro;
}
void Persona::setMensaje(string mensaje){
mensajes_recibidos.push_back(mensaje);
}
string Persona::getMensaje(int posicion){
return mensajes_recibidos.at(posicion);
}
string Persona::to_string() {
//string nombre_persona = nombre << apellido << "\n";
return nombre + " " + apellido + "\n";
} | [
"[email protected]"
] | |
59c5209e856baf961ef114ba7b884f59206872e8 | 9f16ceb7f674234889f796a5b99d342f9edf3399 | /sldWindowMax.cpp | ccb89f2ffaae9b47d1c5a8d09d4f14df8cd5ccf7 | [] | no_license | Segfred/leetcode | 382297025b790790a38f079d5938e158c3bd8260 | b102c4d9abea9caad0b08b7df0d9e89bc6dbc115 | refs/heads/master | 2021-06-11T05:10:21.853331 | 2021-04-03T02:42:59 | 2021-04-03T02:42:59 | 87,050,255 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,239 | cpp | class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
if(nums.size()<k) return {};
vector<int> res{};
deque<int> deq{};
for(int i=0;i<(int)nums.size();++i){
if(!deq.empty()&&deq.back()==i-k) deq.pop_back();//也可以先判断是否窗口满了,这样不会超过size,并且更快
while(!deq.empty()&&nums[i]>=nums[deq.front()]) deq.pop_front();//是和nums[front]比较,不是和front比较,注意存的是下标!
deq.emplace_front(i);//存的是下标,不是数本身,先存入新数,再判断窗口是否满了
if(i>=k-1) res.emplace_back(nums[deq.back()]);//存到结果的是nums[]下标,不是下标
}
return res;
}
};
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
if(nums.size()<k) return {};
vector<int> res{};
deque<int> deq{};//decreasing deque to save the index
int i=0;
while(i<(int)nums.size()){
while(!deq.empty()&&nums[i]>nums[deq.front()]) deq.pop_front();//在删掉我之前,我的潜力最大
deq.push_front(i);
if(i++>=k-1) res.push_back(nums[deq.back()]);//maximum is on the bottom,只是加1还没参与计算,deq元素个数所以不会超
if(deq.back()==i-k) deq.pop_back();
}
return res;
}
};
| [
"[email protected]"
] | |
12f1ce850cc74124a04aa684bddaac08b95c5192 | f6ad1c5e9736c548ee8d41a7aca36b28888db74a | /gdgzez/yhx-lxl/day5/B/B.cpp | d69c38d9fc600f404ca7e955977ee144e8736174 | [] | no_license | cnyali-czy/code | 7fabf17711e1579969442888efe3af6fedf55469 | a86661dce437276979e8c83d8c97fb72579459dd | refs/heads/master | 2021-07-22T18:59:15.270296 | 2021-07-14T08:01:13 | 2021-07-14T08:01:13 | 122,709,732 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 5,013 | cpp | /*
Problem: B.cpp
Time: 2021-06-23 18:49
Author: CraZYali
E-Mail: [email protected]
*/
#define REP(i, s, e) for (register int i(s), end_##i(e); i <= end_##i; i++)
#define DEP(i, s, e) for (register int i(s), end_##i(e); i >= end_##i; i--)
#define DEBUG fprintf(stderr, "Passing [%s] in Line %d\n", __FUNCTION__, __LINE__)
#define chkmax(a, b) (a < (b) ? a = (b) : a)
#define chkmin(a, b) (a > (b) ? a = (b) : a)
#ifdef CraZYali
#include <ctime>
#endif
#include <algorithm>
#include <set>
#include <vector>
#include <iostream>
#include <cstdio>
#define i64 long long
using namespace std;
const int maxn = 3e5 + 10;
template <typename T>
inline T read()
{
T ans = 0, flag = 1;
char c = getchar();
while (!isdigit(c))
{
if (c == '-') flag = -1;
c = getchar();
}
while (isdigit(c))
{
ans = ans * 10 + (c - 48);
c = getchar();
}
return ans * flag;
}
#define file(FILE_NAME) freopen(FILE_NAME".in", "r", stdin), freopen(FILE_NAME".out", "w", stdout)
int n, q, a[maxn];
namespace bf
{
void work()
{
while (q--)
{
int opt = read<int>(), l = read<int>(), r = read<int>();
if (opt == 1)
{
int x = read<int>();
static int b[maxn];
REP(i, l, r) b[i] = a[i];
REP(i, l, r) a[x + i - l] = b[i];
}
else if (opt == 2) REP(i, l, r) a[i] >>= 1;
else
{
i64 ans = 0;
REP(i, l, r) ans += a[i];
printf("%lld\n", ans);
}
}
}
}
namespace cheat
{
const int b1 = 500, b2 = 4000;
int blg[maxn], L[maxn], R[maxn];
struct node
{
vector <int> a;
mutable vector <i64> s;
mutable int l, r, k;
node(int l = 0) : l(l) {}
node(int l, int r, vector <int> a, int k = 0) : l(l), r(r), a(a), k(k)
{
if (k <= 30) for (auto &i : a) i >>= k;
else a = vector <int> (a.size(), 0);
k = 0;
s.clear();
i64 sum = 0;
auto b = a;
do
{
sum = 0;
for (auto &i : b) sum += i, i /= 2;
s.emplace_back(sum);
}while (sum);
reverse(s.begin(), s.end());
}
inline bool operator < (const node &B) const {return l < B.l;}
};
set <node> ssr;
#define IT set <node> :: iterator
IT split(int pos)
{
if (pos > n) return ssr.end();
auto it = ssr.lower_bound(node(pos));
if (it != ssr.end() && it -> l == pos) return it;
if (it == ssr.begin())
return ssr.emplace(pos, pos, vector <int> {0}).first;
--it;
int l = it -> l, r = it -> r, k = it -> k;
vector <int> a1, a2, a = it -> a;
ssr.erase(it);
if (r < pos)
return ssr.emplace(pos, pos, vector <int> {0}).first;
if (k <= 30)
{
for (auto &i : a) i >>= k;
k = 0;
}
else
return ssr.emplace(pos, pos, vector <int> {0}).first;
REP(i, l, pos - 1) a1.emplace_back(a[i - l]);
REP(i, pos, r) a2.emplace_back(a[i - l]);
int L = l, R = pos - 1;vector <int> real;
while (L <= R && !a1[L - l]) L++;
while (L <= R && !a1.back()) a1.pop_back(), R--;
REP(i, L, R) real.emplace_back(a1[i - l]);
if (L <= R) ssr.emplace(L, R, real, k);
L = pos;R = r;real.clear();
while (L <= R && !a2[L - pos]) L++;
while (L <= R && !a2.back()) a2.pop_back(), R--;
REP(i, L, R) real.emplace_back(a2[i - pos]);
if (L <= R) return ssr.emplace(L, R, real).first;
return ssr.emplace(pos, pos, vector <int> {0}).first;
}
void rebuild_a()
{
REP(i, 1, n) a[i] = 0;
for (auto i : ssr)
REP(j, i.l, i.r) a[j] = i.k <= 30 ? i.a[j - i.l] >> i.k : 0;
}
void rebuild_s()
{
ssr.clear();
REP(i, 1, blg[n])
{
vector <int> A;
int flg = 0;
REP(j, L[i], R[i]) A.emplace_back(a[j]), flg |= a[j];
if (!flg) continue;
ssr.emplace(L[i], R[i], A);
}
}
void rebuild()
{
rebuild_a();
rebuild_s();
}
void work()
{
REP(i, 1, n) blg[i] = (i - 1) / b1 + 1;
REP(i, 1, n) R[blg[i]] = i;
DEP(i, n, 1) L[blg[i]] = i;
rebuild_s();
REP(Case, 1, q)
{
int opt = read<int>(), l = read<int>(), r = read<int>();
if (opt == 1)
{
int x = read<int>();
auto itr = split(r + 1), itl = split(l);
vector <node> vec;
for (auto it = itl; it != itr; it++) vec.emplace_back(*it);
itr = split(x + r - l + 1), itl = split(x);
ssr.erase(itl, itr);
for (auto i : vec)
{
auto t = i;
t.l += x - l;t.r += x - l;
ssr.emplace(t);
}
}
else if (opt == 2)
{
auto itr = split(r + 1), itl = split(l);
for (auto it = itl; it != itr;)
{
it -> k++;
if (it -> s.size() > 1)
{
it -> s.pop_back();
it++;
}else it = ssr.erase(it);
}
}
else
{
i64 ans = 0;
auto itr = split(r + 1), itl = split(l);
for (auto it = itl; it != itr; it++) ans += it -> s.back();
printf("%lld\n", ans);
}
if (ssr.size() > b2) rebuild();
if (Case % 5000 == 0) fprintf(stderr, "Done %d / %d = %.2lf%%\n", Case, q, Case * 100. / q);
}
}
}
int main()
{
#ifdef CraZYali
file("B");
#endif
n = read<int>();
REP(i, 1, n) a[i] = read<int>();
q = read<int>();
if (n <= 3e4 && q <= 3e4) bf :: work();
else cheat :: work();
#ifdef CraZYali
cerr << clock() * 1. / CLOCKS_PER_SEC << endl;
#endif
return 0;
}
| [
"[email protected]"
] | |
ea9679d5617568af440e354607944e3a081b0c8d | 885fc7aa7aa0e60a8e48e310fd6a5447970a08f3 | /CanvasEngine/Header Files/HelperClasses/Task.h | 2d4a4425b1336d2042d6263ce587706af4dde2ee | [] | no_license | JakeScrivener/CanvasDrawingApp | b46b19da7685f3ec05bcc147eba89fdf9c18aa29 | 310badbcf9925a9c84b2dab0f3c8cb16c7fbe8f6 | refs/heads/master | 2020-06-04T07:20:14.622130 | 2019-06-14T10:19:14 | 2019-06-14T10:19:14 | 191,921,586 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 425 | h | #pragma once
#include <functional>
#include <vector>
class Task
{
private:
std::function<void(void*, void*)> mFunction;
void* mData1;
void* mData2;
std::vector<int> mCores;
public:
Task(std::function<void(void*, void*)> pFunction, void* pData1, void* pData2, std::vector<int> pCores);
~Task();
std::function<void(void*, void*)> Function() const;
std::pair<void*, void*> Data();
std::vector<int> Cores() const;
};
| [
"[email protected]"
] | |
ad6445721e232339a226acb1760589b09bb85723 | 8f794474974201d465308793f12a84bf8aa6cd07 | /Laba6/C.cpp | 23cc4501f0120c9224d5d71d2d1dc02238b504a9 | [] | no_license | ilyaShevchuk/-Algorithms-and-data-structures | 17731300c639268a50392236028eeacc598caf39 | 2eea40624f6d904d1c70e2d3babd7ae1ac902327 | refs/heads/main | 2023-02-18T06:26:46.916188 | 2021-01-21T12:33:47 | 2021-01-21T12:33:47 | 331,571,313 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,464 | cpp | #include <iostream>
#include <fstream>
#include <vector>
#include <string>
using namespace std;
class Tree {
public:
struct Node {
int value;
Node *left = nullptr;
Node *right = nullptr;
Node(int value) : value{value}, left{nullptr}, right{nullptr} {}
};
Node *root = nullptr;
int next(Node *New_Node, int key, Node *result) {
if (New_Node == nullptr)
return result->value;
if (New_Node->value <= key) {
next(New_Node->right, key, result);
} else {
result->value = New_Node->value;
next(New_Node->left, key, result);
}
return (result->value);
}
int prev(Node *New_Node, int key, Node *result) {
if (New_Node == nullptr)
return result->value;
if (New_Node->value >= key) {
prev(New_Node->left, key, result);
} else {
result->value = New_Node->value;
prev(New_Node->right, key, result);
}
return (result->value);
}
string exists(int key) {
if(this->root == nullptr)
return "false";
Node* New_Node = this->root;
while (New_Node != nullptr){
if(New_Node->value == key)
return "true";
if(key < New_Node->value)
New_Node = New_Node->left;
else
New_Node = New_Node->right;
}
return "false";
}
void insert(int key) {
Node *New_Node = this->root;
if (New_Node == nullptr) {
this->root = new Node(key);
} else {
while (true) {
if (New_Node->value == key) return;
if (key < New_Node->value) {
if (New_Node->left == nullptr) {
New_Node->left = new Node(key);
return;
} else
New_Node = New_Node->left;
} else {
if (New_Node->right == nullptr) {
New_Node->right = new Node(key);
return;
} else
New_Node = New_Node->right;
}
}
}
}
void remove(int key) {
if(this->root == nullptr)
return;
Node *New_Node = root, *parent = nullptr;
while (New_Node != nullptr){
if(New_Node->value == key)
break;
parent = New_Node;
if(key < New_Node->value)
New_Node = New_Node->left;
else
New_Node = New_Node->right;
}
if(New_Node == nullptr)
return;
if(New_Node->right == nullptr){
if(parent == nullptr)
root = New_Node->left;
else
if(New_Node == parent->left)
parent->left = New_Node->left;
else
parent->right = New_Node->left;
} else {
Node *mostLeft = New_Node->right;
parent = nullptr;
while (mostLeft->left != nullptr) {
parent = mostLeft;
mostLeft = mostLeft->left;
}
if(parent != nullptr)
parent->left = mostLeft->right;
else
New_Node->right = mostLeft->right;
New_Node->value = mostLeft->value;
}
}
};
int main() {
ifstream fin("bstsimple.in");
ofstream fout("bstsimple.out");
Tree Wood;
string comm;
int key, x;
while (fin >> comm >> key) {
if (comm == "insert") {
Wood.insert(key);
} else if (comm == "delete") {
Wood.remove(key);
} else if (comm == "exists") {
auto res = Wood.exists(key);
fout << res << endl;
} else if (comm == "next") {
auto result = new Tree::Node(key);
int m = Wood.next(Wood.root, key, result);
if (m != key) {
fout << m << endl;
} else {
fout << "none" << endl;
}
} else if (comm == "prev") {
auto result = new Tree::Node(key);
int m = Wood.prev(Wood.root, key, result);
if (m != key) {
fout << m << endl;
} else {
fout << "none" << endl;
}
}
}
} | [
"[email protected]"
] |