blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e2c938e9d4aa5a443afeb71345d14e269a7d4b40 | 48e9625fcc35e6bf790aa5d881151906280a3554 | /Sources/Elastos/LibCore/src/org/apache/http/impl/cookie/DateUtils.cpp | fc21f88cd075e46ad52d2f296a6f490d27c99086 | [
"Apache-2.0"
] | permissive | suchto/ElastosRT | f3d7e163d61fe25517846add777690891aa5da2f | 8a542a1d70aebee3dbc31341b7e36d8526258849 | refs/heads/master | 2021-01-22T20:07:56.627811 | 2017-03-17T02:37:51 | 2017-03-17T02:37:51 | 85,281,630 | 4 | 2 | null | 2017-03-17T07:08:49 | 2017-03-17T07:08:49 | null | UTF-8 | C++ | false | false | 7,459 | cpp | //=========================================================================
// Copyright (C) 2012 The Elastos Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "org/apache/http/impl/cookie/DateUtils.h"
#include "elastos/core/CString.h"
#include "elastos/text/CSimpleDateFormat.h"
#include "elastos/utility/CTimeZoneHelper.h"
#include "elastos/utility/CCalendarHelper.h"
#include "elastos/utility/CLocale.h"
#include "elastos/utility/CHashMap.h"
#include "elastos/utility/logging/Logger.h"
using Elastos::Core::CString;
using Elastos::Text::CSimpleDateFormat;
using Elastos::Text::IDateFormat;
using Elastos::Utility::CTimeZoneHelper;
using Elastos::Utility::CCalendarHelper;
using Elastos::Utility::ICalendar;
using Elastos::Utility::CLocale;
using Elastos::Utility::IHashMap;
using Elastos::Utility::CHashMap;
using Elastos::Utility::Logging::Logger;
namespace Org {
namespace Apache {
namespace Http {
namespace Impl {
namespace Cookie {
//==============================================================================
// DateUtils::DateFormatHolder
//==============================================================================
AutoPtr<ISimpleDateFormat> DateUtils::DateFormatHolder::FormatFor(
/* [in] */ const String& pattern)
{
// SoftReference<Map<String, SimpleDateFormat>> ref = THREADLOCAL_FORMATS.get();
// Map<String, SimpleDateFormat> formats = ref.get();
AutoPtr<IHashMap> formats;
if (formats == NULL) {
CHashMap::New((IHashMap**)&formats);
// THREADLOCAL_FORMATS.set(
// new SoftReference<Map<String, SimpleDateFormat>>(formats));
}
AutoPtr<CString> cs;
CString::NewByFriend(pattern, (CString**)&cs);
AutoPtr<IInterface> value;
formats->Get(cs->Probe(EIID_IInterface), (IInterface**)&value);
AutoPtr<ISimpleDateFormat> format = ISimpleDateFormat::Probe(value);
if (format == NULL) {
CSimpleDateFormat::New(pattern, CLocale::US, (ISimpleDateFormat**)&format);
AutoPtr<CTimeZoneHelper> helper;
CTimeZoneHelper::AcquireSingletonByFriend((CTimeZoneHelper**)&helper);
AutoPtr<ITimeZone> timeZone;
helper->GetTimeZone(String("GMT"), (ITimeZone**)&timeZone);
IDateFormat::Probe(format)->SetTimeZone(timeZone);
formats->Put(cs->Probe(EIID_IInterface), format);
}
return format;
}
//==============================================================================
// DateUtils
//==============================================================================
const String DateUtils::PATTERN_RFC1123("EEE, dd MMM yyyy HH:mm:ss zzz");
const String DateUtils::PATTERN_RFC1036("EEEE, dd-MMM-yy HH:mm:ss zzz");
const String DateUtils::PATTERN_ASCTIME("EEE MMM d HH:mm:ss yyyy");
static AutoPtr<ITimeZone> InitGMT()
{
AutoPtr<CTimeZoneHelper> helper;
CTimeZoneHelper::AcquireSingletonByFriend((CTimeZoneHelper**)&helper);
AutoPtr<ITimeZone> timeZone;
helper->GetTimeZone(String("GMT"), (ITimeZone**)&timeZone);
return timeZone;
}
const AutoPtr<ITimeZone> DateUtils::GMT = InitGMT();
static AutoPtr< ArrayOf<String> > InitDefaultPatterns()
{
AutoPtr< ArrayOf<String> > patterns = ArrayOf<String>::Alloc(3);
(*patterns)[0] = DateUtils::PATTERN_RFC1036;
(*patterns)[1] = DateUtils::PATTERN_RFC1123;
(*patterns)[2] = DateUtils::PATTERN_ASCTIME;
return patterns;
}
const AutoPtr< ArrayOf<String> > DateUtils::DEFAULT_PATTERNS = InitDefaultPatterns();
static AutoPtr<IDate> InitDefaultTwoDigitYearStart()
{
AutoPtr<CCalendarHelper> helper;
CCalendarHelper::AcquireSingletonByFriend((CCalendarHelper**)&helper);
AutoPtr<ICalendar> calender;
helper->GetInstance((ICalendar**)&calender);
calender->SetTimeZone(DateUtils::GMT);
calender->Set(2000, ICalendar::JANUARY, 1, 0, 0, 0);
calender->Set(ICalendar::MILLISECOND, 0);
AutoPtr<IDate> date;
calender->GetTime((IDate**)&date);
return date;
}
const AutoPtr<IDate> DateUtils::DEFAULT_TWO_DIGIT_YEAR_START = InitDefaultTwoDigitYearStart();
ECode DateUtils::ParseDate(
/* [in] */ const String& _dateValue,
/* [in] */ ArrayOf<String>* dateFormats,
/* [in] */ IDate* startDate,
/* [out] */ IDate** date)
{
VALIDATE_NOT_NULL(date)
*date = NULL;
String dateValue = _dateValue;
if (dateValue.IsNull()) {
Logger::E("DateUtils", "dateValue is null");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
if (dateFormats == NULL) {
dateFormats = DEFAULT_PATTERNS;
}
if (startDate == NULL) {
startDate = DEFAULT_TWO_DIGIT_YEAR_START;
}
// trim single quotes around date if present
// see issue #5279
if ((dateValue.GetLength() > 1) && dateValue.StartWith("'")
&& dateValue.EndWith("'")) {
dateValue = dateValue.Substring (1, dateValue.GetLength() - 1);
}
for (Int32 i = 0; i < dateFormats->GetLength(); ++i) {
String dateFormat = (*dateFormats)[i];
AutoPtr<ISimpleDateFormat> dateParser = DateFormatHolder::FormatFor(dateFormat);
dateParser->Set2DigitYearStart(startDate);
// try {
return IDateFormat::Probe(dateParser)->Parse(dateValue, date);
// } catch (ParseException pe) {
// // ignore this exception, we will try the next format
// }
}
// we were unable to parse the date
Logger::E("DateUtils", "Unable to parse the date %s", dateValue.string());
return E_DATE_PARSE_EXCEPTION;
// throw new DateParseException("Unable to parse the date " + dateValue);
}
ECode DateUtils::ParseDate(
/* [in] */ const String& dateValue,
/* [out] */ IDate** date)
{
VALIDATE_NOT_NULL(date)
return ParseDate(dateValue, NULL, NULL, date);
}
ECode DateUtils::ParseDate(
/* [in] */ const String& dateValue,
/* [in] */ ArrayOf<String>* dateFormats,
/* [out] */ IDate** date)
{
VALIDATE_NOT_NULL(date)
return ParseDate(dateValue, dateFormats, NULL, date);
}
ECode DateUtils::FormatDate(
/* [in] */ IDate* date,
/* [out] */ String* formatDate)
{
VALIDATE_NOT_NULL(formatDate)
return FormatDate(date, PATTERN_RFC1123, formatDate);
}
ECode DateUtils::FormatDate(
/* [in] */ IDate* date,
/* [in] */ const String& pattern,
/* [out] */ String* formatDate)
{
VALIDATE_NOT_NULL(formatDate)
*formatDate = String(NULL);
if (date == NULL) {
Logger::E("DateUtils", "date is null");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
if (pattern.IsNull()) {
Logger::E("DateUtils", "pattern is null");
return E_ILLEGAL_ARGUMENT_EXCEPTION;
}
AutoPtr<ISimpleDateFormat> formatter = DateFormatHolder::FormatFor(pattern);
return IDateFormat::Probe(formatter)->Format(date, formatDate);
}
} // namespace Cookie
} // namespace Impl
} // namespace Http
} // namespace Apache
} // namespace Org | [
"cao.jing@kortide.com"
] | cao.jing@kortide.com |
8c182bc0f763b1caa498066765098cc4cba82c22 | 8380b5eb12e24692e97480bfa8939a199d067bce | /Carberp Botnet/source - absource/pro/all source/keys/Source/Core/DllLoader.cpp | dc275ab16c2b12fe680bbbbe0d7c690ab7cb3436 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | RamadhanAmizudin/malware | 788ee745b5bb23b980005c2af08f6cb8763981c2 | 62d0035db6bc9aa279b7c60250d439825ae65e41 | refs/heads/master | 2023-02-05T13:37:18.909646 | 2023-01-26T08:43:18 | 2023-01-26T08:43:18 | 53,407,812 | 873 | 291 | null | 2023-01-26T08:43:19 | 2016-03-08T11:44:21 | C++ | UTF-8 | C++ | false | false | 10,265 | cpp | #include <windows.h>
#include "GetApi.h"
#include "Memory.h"
#include "Strings.h"
#include "DllLoader.h"
typedef struct
{
PIMAGE_NT_HEADERS headers;
unsigned char *codeBase;
HMODULE *modules;
int numModules;
int initialized;
} MEMORYMODULE, *PMEMORYMODULE;
#define IMAGE_SIZEOF_BASE_RELOCATION 8
typedef BOOL ( WINAPI *DllEntryProc )( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved );
#define GET_HEADER_DICTIONARY( module, idx ) &(module)->headers->OptionalHeader.DataDirectory[idx]
void CopySections( const unsigned char *data, PIMAGE_NT_HEADERS old_headers, PMEMORYMODULE module )
{
int i, size;
unsigned char *codeBase = module->codeBase;
unsigned char *dest;
PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION( module->headers );
for ( i = 0; i < module->headers->FileHeader.NumberOfSections; i++, section++ )
{
if ( section->SizeOfRawData == 0 )
{
size = old_headers->OptionalHeader.SectionAlignment;
if ( size > 0 )
{
dest = (unsigned char *)pVirtualAlloc( codeBase + section->VirtualAddress, size, MEM_COMMIT, PAGE_READWRITE );
section->Misc.PhysicalAddress = (DWORD)dest;
m_memset( dest, 0, size );
}
continue;
}
dest = (unsigned char *)pVirtualAlloc( codeBase + section->VirtualAddress,
section->SizeOfRawData,
MEM_COMMIT,
PAGE_READWRITE );
m_memcpy( dest, data + section->PointerToRawData, section->SizeOfRawData );
section->Misc.PhysicalAddress = (DWORD)dest;
}
}
int ProtectionFlags[2][2][2] = {
{
{PAGE_NOACCESS, PAGE_WRITECOPY},
{PAGE_READONLY, PAGE_READWRITE},
},
{
{PAGE_EXECUTE, PAGE_EXECUTE_WRITECOPY},
{PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE},
},
};
void FinalizeSections( PMEMORYMODULE module )
{
int i;
PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION( module->headers );
for ( i = 0; i < module->headers->FileHeader.NumberOfSections; i++, section++ )
{
DWORD protect, oldProtect, size;
int executable = (section->Characteristics & IMAGE_SCN_MEM_EXECUTE) != 0;
int readable = (section->Characteristics & IMAGE_SCN_MEM_READ) != 0;
int writeable = (section->Characteristics & IMAGE_SCN_MEM_WRITE) != 0;
if ( section->Characteristics & IMAGE_SCN_MEM_DISCARDABLE )
{
//pVirtualFree((LPVOID)section->Misc.PhysicalAddress, section->SizeOfRawData, MEM_DECOMMIT);
continue;
}
protect = ProtectionFlags[executable][readable][writeable];
if ( section->Characteristics & IMAGE_SCN_MEM_NOT_CACHED )
{
protect |= PAGE_NOCACHE;
}
size = section->SizeOfRawData;
if ( size == 0 )
{
if ( section->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA )
{
size = module->headers->OptionalHeader.SizeOfInitializedData;
}
else if ( section->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA )
{
size = module->headers->OptionalHeader.SizeOfUninitializedData;
}
}
if ( size > 0 )
{
if ( pVirtualProtect((LPVOID)section->Misc.PhysicalAddress, section->SizeOfRawData, protect, &oldProtect) == 0 )
{
return;
}
}
}
}
void PerformBaseRelocation( PMEMORYMODULE module, DWORD delta )
{
DWORD i;
unsigned char *codeBase = module->codeBase;
PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY( module, IMAGE_DIRECTORY_ENTRY_BASERELOC );
if ( directory->Size > 0 )
{
PIMAGE_BASE_RELOCATION relocation = (PIMAGE_BASE_RELOCATION)( codeBase + directory->VirtualAddress );
for (; relocation->VirtualAddress > 0; )
{
unsigned char *dest = (unsigned char *)(codeBase + relocation->VirtualAddress);
unsigned short *relInfo = (unsigned short *)((unsigned char *)relocation + IMAGE_SIZEOF_BASE_RELOCATION);
for ( i = 0; i < ((relocation->SizeOfBlock-IMAGE_SIZEOF_BASE_RELOCATION) / 2 ); i++, relInfo++ )
{
DWORD *patchAddrHL;
int type, offset;
type = *relInfo >> 12;
offset = *relInfo & 0xfff;
switch ( type )
{
case IMAGE_REL_BASED_ABSOLUTE:
break;
case IMAGE_REL_BASED_HIGHLOW:
patchAddrHL = (DWORD *)(dest + offset);
*patchAddrHL += delta;
break;
default:
break;
}
}
relocation = (PIMAGE_BASE_RELOCATION)(((DWORD)relocation) + relocation->SizeOfBlock);
}
}
}
int BuildImportTable(PMEMORYMODULE module)
{
int result=1;
unsigned char *codeBase = module->codeBase;
PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY(module, IMAGE_DIRECTORY_ENTRY_IMPORT);
if ( directory->Size > 0 )
{
PIMAGE_IMPORT_DESCRIPTOR importDesc = (PIMAGE_IMPORT_DESCRIPTOR)(codeBase + directory->VirtualAddress);
for ( ; !pIsBadReadPtr(importDesc, sizeof(IMAGE_IMPORT_DESCRIPTOR)) && importDesc->Name; importDesc++ )
{
DWORD *thunkRef, *funcRef;
HMODULE handle = (HMODULE)pLoadLibraryA( (LPCSTR)(codeBase + importDesc->Name) );
if (handle == INVALID_HANDLE_VALUE)
{
result = 0;
break;
}
HMODULE *p = (HMODULE*)MemRealloc( module->modules, (module->numModules+1)*(sizeof(HMODULE)) );
module->modules = p;
if (module->modules == NULL)
{
result = 0;
break;
}
module->modules[module->numModules++] = handle;
if (importDesc->OriginalFirstThunk)
{
thunkRef = (DWORD *)(codeBase + importDesc->OriginalFirstThunk);
funcRef = (DWORD *)(codeBase + importDesc->FirstThunk);
} else {
thunkRef = (DWORD *)(codeBase + importDesc->FirstThunk);
funcRef = (DWORD *)(codeBase + importDesc->FirstThunk);
}
for (; *thunkRef; thunkRef++, funcRef++)
{
if IMAGE_SNAP_BY_ORDINAL(*thunkRef)
{
*funcRef = (DWORD)pGetProcAddress( handle, (LPCSTR)IMAGE_ORDINAL(*thunkRef) );
}
else
{
PIMAGE_IMPORT_BY_NAME thunkData = (PIMAGE_IMPORT_BY_NAME)(codeBase + *thunkRef);
*funcRef = (DWORD)pGetProcAddress( handle, (LPCSTR)&thunkData->Name );
}
if (*funcRef == 0)
{
result = 0;
break;
}
}
if (!result)
break;
}
}
return result;
}
void MemoryFreeLibrary(HMEMORYMODULE mod)
{
int i;
PMEMORYMODULE module = (PMEMORYMODULE)mod;
if (module != NULL)
{
if (module->initialized != 0)
{
DllEntryProc DllEntry = (DllEntryProc)(module->codeBase + module->headers->OptionalHeader.AddressOfEntryPoint);
(*DllEntry)((HINSTANCE)module->codeBase, DLL_PROCESS_DETACH, 0);
module->initialized = 0;
}
if (module->modules != NULL)
{
for (i=0; i<module->numModules; i++)
if (module->modules[i] != INVALID_HANDLE_VALUE)
pFreeLibrary(module->modules[i]);
MemFree(module->modules);
}
if (module->codeBase != NULL)
pVirtualFree(module->codeBase, 0, MEM_RELEASE);
MemFree( module);
}
}
#pragma optimize("", off)
HMEMORYMODULE MemoryLoadLibrary(const void *data)
{
PMEMORYMODULE result;
PIMAGE_DOS_HEADER dos_header;
PIMAGE_NT_HEADERS old_header;
unsigned char *code, *headers;
DWORD locationDelta;
DllEntryProc DllEntry;
BOOL successfull;
dos_header = (PIMAGE_DOS_HEADER)data;
if (dos_header->e_magic != IMAGE_DOS_SIGNATURE)
{
return NULL;
}
old_header = (PIMAGE_NT_HEADERS)&((const unsigned char *)(data))[dos_header->e_lfanew];
if (old_header->Signature != IMAGE_NT_SIGNATURE)
{
return NULL;
}
code = (unsigned char *)pVirtualAlloc((LPVOID)(old_header->OptionalHeader.ImageBase),
old_header->OptionalHeader.SizeOfImage,
MEM_RESERVE,
PAGE_READWRITE);
if (code == NULL)
code = (unsigned char *)pVirtualAlloc(NULL,
old_header->OptionalHeader.SizeOfImage,
MEM_RESERVE,
PAGE_READWRITE);
if (code == NULL)
{
return NULL;
}
result = (PMEMORYMODULE)MemAlloc( sizeof(MEMORYMODULE) );
result->codeBase = code;
result->numModules = 0;
result->modules = NULL;
result->initialized = 0;
pVirtualAlloc(code,
old_header->OptionalHeader.SizeOfImage,
MEM_COMMIT,
PAGE_READWRITE);
headers = (unsigned char *)pVirtualAlloc(code,
old_header->OptionalHeader.SizeOfHeaders,
MEM_COMMIT,
PAGE_READWRITE);
m_memcpy(headers, dos_header, dos_header->e_lfanew + old_header->OptionalHeader.SizeOfHeaders);
result->headers = (PIMAGE_NT_HEADERS)&((const unsigned char *)(headers))[dos_header->e_lfanew];
result->headers->OptionalHeader.ImageBase = (DWORD)code;
CopySections((const unsigned char*)data, old_header, result);
locationDelta = (DWORD)(code - old_header->OptionalHeader.ImageBase);
if (locationDelta != 0)
PerformBaseRelocation(result, locationDelta);
if (!BuildImportTable(result))
goto error;
FinalizeSections(result);
if (result->headers->OptionalHeader.AddressOfEntryPoint != 0)
{
DllEntry = (DllEntryProc)(code + result->headers->OptionalHeader.AddressOfEntryPoint);
if (DllEntry == 0)
{
goto error;
}
successfull = (*DllEntry)((HINSTANCE)code, DLL_PROCESS_ATTACH, 0);
if (!successfull)
{
goto error;
}
result->initialized = 1;
}
return (HMEMORYMODULE)result;
error:
MemoryFreeLibrary(result);
return NULL;
}
FARPROC MemoryGetProcAddress(HMEMORYMODULE module, const char *name)
{
unsigned char *codeBase = ((PMEMORYMODULE)module)->codeBase;
int idx=-1;
DWORD i, *nameRef;
WORD *ordinal;
PIMAGE_EXPORT_DIRECTORY exports;
PIMAGE_DATA_DIRECTORY directory = GET_HEADER_DICTIONARY((PMEMORYMODULE)module, IMAGE_DIRECTORY_ENTRY_EXPORT);
if (directory->Size == 0)
return NULL;
exports = (PIMAGE_EXPORT_DIRECTORY)(codeBase + directory->VirtualAddress);
if (exports->NumberOfNames == 0 || exports->NumberOfFunctions == 0)
return NULL;
nameRef = (DWORD *)(codeBase + exports->AddressOfNames);
ordinal = (WORD *)(codeBase + exports->AddressOfNameOrdinals);
for (i=0; i<exports->NumberOfNames; i++, nameRef++, ordinal++)
if ( plstrcmpiA(name, (const char *)(codeBase + *nameRef)) == 0 )
{
idx = *ordinal;
break;
}
if (idx == -1)
return NULL;
if ((DWORD)idx > exports->NumberOfFunctions)
return NULL;
return (FARPROC)(codeBase + *(DWORD *)(codeBase + exports->AddressOfFunctions + (idx*4)));
}
| [
"fdiskyou@users.noreply.github.com"
] | fdiskyou@users.noreply.github.com |
bf3477c047864ffd3f63352ce5e32f9ea50ce796 | bd35e90c881bc7f9260f57474592f4867259baa5 | /src/search/core/SearchItemsStorrage.cpp | d4331c2e7dfb95e1fd771e5d9210ab6d6090161d | [] | no_license | sunpeng196/CuteTorrent | 7b5fbd93ccb0522769653d2d8a2b8f134c853fb6 | f2b879b6152fad23cebebe915bb540ebd5f379e3 | refs/heads/master | 2021-01-12T20:06:04.962205 | 2015-07-22T20:39:03 | 2015-07-22T20:39:03 | 39,623,679 | 2 | 0 | null | 2015-07-24T09:33:09 | 2015-07-24T09:33:09 | null | UTF-8 | C++ | false | false | 2,436 | cpp | #include "SearchItemsStorrage.h"
SearchItemsStorrage* SearchItemsStorrage::m_pInstance = NULL;
int SearchItemsStorrage::m_nInstanceCount = 0;
SearchItemsStorrage::SearchItemsStorrage() : m_sEngineName("")
{
m_items.clear();
m_filteredItems.clear();
}
SearchItemsStorrage::~SearchItemsStorrage()
{
qDeleteAll(m_items);
}
void SearchItemsStorrage::filterData()
{
if(m_sEngineName.isEmpty())
{
m_filteredItems = m_items;
}
else
{
m_filteredItems.clear();
int nCount = m_items.length();
for(int i = 0; i < nCount; i++)
{
SearchResult* item = m_items.at(i);
if(item->Engine().compare(m_sEngineName, Qt::CaseInsensitive) == 0)
{
m_filteredItems.append(item);
}
}
}
emit reset();
}
void SearchItemsStorrage::setFilter(QString engineName)
{
m_sEngineName = engineName;
filterData();
}
SearchItemsStorrage* SearchItemsStorrage::getInstance()
{
if(m_pInstance == NULL)
{
m_pInstance = new SearchItemsStorrage();
}
m_nInstanceCount++;
return m_pInstance;
}
void SearchItemsStorrage::freeInstance()
{
m_nInstanceCount--;
if(m_nInstanceCount == 0)
{
delete m_pInstance;
}
}
void SearchItemsStorrage::append(SearchResult* item)
{
if(m_items.contains(item))
{
return;
}
m_items.append(item);
if(m_sEngineName.isEmpty())
{
m_filteredItems.append(item);
}
else
{
if(item->Engine().compare(m_sEngineName, Qt::CaseInsensitive))
{
m_filteredItems.append(item);
}
}
}
void SearchItemsStorrage::append(QList<SearchResult*>& items)
{
int nCount = items.length();
for(int i = 0; i < nCount; i++)
{
append(items.at(i));
}
}
void SearchItemsStorrage::remove(SearchResult* item)
{
int itemIndex = m_items.indexOf(item);
if(itemIndex < 0)
{
return;
}
int iterIndex = m_filteredItems.indexOf(item);
if(iterIndex >= 0)
{
m_filteredItems.removeAt(iterIndex);
}
m_items.removeAt(itemIndex);
}
bool SearchItemsStorrage::contains(SearchResult* item)
{
int itemIndex = m_items.indexOf(item);
if(itemIndex < 0)
{
return false;
}
int iterIndex = m_filteredItems.indexOf(item);
if(iterIndex >= 0)
{
return true;
}
return false;
}
SearchResult* SearchItemsStorrage::operator[](int index)
{
SearchResult* pItem = m_filteredItems.at(index);
return pItem;
}
void SearchItemsStorrage::clear()
{
qDeleteAll(m_items);
m_items.clear();
m_filteredItems.clear();
}
int SearchItemsStorrage::length()
{
return m_filteredItems.length();
}
| [
"ruslan.fedoseenko.91@gmail.com"
] | ruslan.fedoseenko.91@gmail.com |
47586b0259e1ed58d9de96fe8b1317b566b879c7 | 5c9eb0c093d36ece2cc158cb5020ea46177f67e4 | /CPP05/ex03/ShrubberyCreationForm.cpp | 6d377a95a2660222c3e415543689d26ab3a29e6d | [] | no_license | cquiana/CPP_pisc | 651a082dfd05415aa801cab791bea651010ddf30 | 96cf6a74076af7389e860c9ee1284abb9770a1f4 | refs/heads/master | 2023-03-14T20:57:38.045063 | 2021-03-30T10:39:49 | 2021-03-30T10:39:49 | 345,763,811 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,528 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ShrubberyCreationForm.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cquiana <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/23 16:04:42 by cquiana #+# #+# */
/* Updated: 2021/03/29 18:37:38 by cquiana ### ########.fr */
/* */
/* ************************************************************************** */
#include "ShrubberyCreationForm.hpp"
ShrubberyCreationForm::ShrubberyCreationForm() : Form("Shrubbery Creation", 145, 137, "no target")
{
}
ShrubberyCreationForm::ShrubberyCreationForm(std::string const &target) : Form("Shrubbery Creation", 145, 137, target)
{
}
ShrubberyCreationForm::~ShrubberyCreationForm()
{
}
ShrubberyCreationForm::ShrubberyCreationForm(ShrubberyCreationForm const &old) :
Form(old.getName(), old.getGradeToSign(), old.getGradeToExec(), old.getTarget())
{
*this = old;
}
ShrubberyCreationForm &ShrubberyCreationForm::operator=(ShrubberyCreationForm const &old)
{
(void)old;
return (*this);
}
void ShrubberyCreationForm::execute(Bureaucrat const &bureauc) const
{
if (!getIsSign())
throw Form::isSignedException();
if (bureauc.getGrade() > getGradeToExec())
throw Form::GradeTooLowException();
std::string fName = Form::getTarget().append("_shrubbery");
std::ofstream fOut;
fOut.open(fName);
if (!fOut.is_open())
throw ShrubberyCreationForm::ShrubberyFormExeption();
fOut << " " << std::endl;
fOut << " + " << std::endl;
fOut << " *4* " << std::endl;
fOut << " **2** " << std::endl;
fOut << " ~~~~~~~ " << std::endl;
fOut << " ********* " << std::endl;
fOut << " ~~~~~~~~~~~ " << std::endl;
fOut << " ************* " << std::endl;
fOut << " ############### " << std::endl;
fOut << " ||| " << std::endl;
fOut.close();
}
const char *ShrubberyCreationForm::ShrubberyFormExeption::what() const throw ()
{
return ("File creation fail!");
}
| [
"atulyakov@gmail.com"
] | atulyakov@gmail.com |
324e718a006a3ed82d3573b046a6a5b2d0cbe30f | d61f2cac3bd9ed39f95184b89dd40952c6482786 | /testCase/results/10/T.foam | f5949ec01e0fd18024b0bf9341789bc4727e8f7d | [] | no_license | karimimp/PUFoam | 4b3a5b427717aa0865889fa2342112cc3d24ce66 | 9d16e06d63e141607491219924018bea99cbb9e5 | refs/heads/master | 2022-06-24T08:51:18.370701 | 2022-04-28T18:33:03 | 2022-04-28T18:33:03 | 120,094,729 | 6 | 3 | null | 2022-04-27T09:46:38 | 2018-02-03T13:43:52 | C++ | UTF-8 | C++ | false | false | 1,197 | foam | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 3.0.1 |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "10";
object T.foam;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 1 0 0 0];
internalField uniform 300;
boundaryField
{
Wall
{
type zeroGradient;
}
frontAndBack
{
type empty;
}
atmosphere
{
type inletOutlet;
inletValue uniform 300;
value uniform 300;
}
}
// ************************************************************************* //
| [
"mohsenk@outlook.com"
] | mohsenk@outlook.com |
b3f9309d26225123de7203f144849da21448bb71 | 60c9d985436e81a18e5b4b1332f14212312f6e7a | /backup/edbee-data/code/cpp/listener.cpp | 07f98a2fa9b88ee3b0b3c360ec0faff8577ed0a3 | [] | no_license | visualambda/simpleIDE | 53b69e47de6e4f9ad333ae9d00d3bfb3a571048c | 37e3395c5fffa2cf1ca74652382461eadaffa9aa | refs/heads/master | 2020-03-23T07:22:19.938662 | 2018-08-16T03:43:26 | 2018-08-16T03:43:26 | 141,267,532 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 27,428 | cpp | ////////// GENERATED FILE, EDITS WILL BE LOST //////////
#include "listener.hpp"
#include <iostream>
ListenerBool::ListenerBool(ListenerBool::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerBool::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerBool::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(bool)));
return connected_;
}
void ListenerBool::invoke(bool arg1) {
f_(arg1);
}
ListenerDockWidgetArea::ListenerDockWidgetArea(ListenerDockWidgetArea::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerDockWidgetArea::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerDockWidgetArea::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(Qt::DockWidgetArea)));
return connected_;
}
void ListenerDockWidgetArea::invoke(Qt::DockWidgetArea arg1) {
f_(arg1);
}
ListenerDockWidgetAreas::ListenerDockWidgetAreas(ListenerDockWidgetAreas::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerDockWidgetAreas::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerDockWidgetAreas::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(Qt::DockWidgetAreas)));
return connected_;
}
void ListenerDockWidgetAreas::invoke(Qt::DockWidgetAreas arg1) {
f_(arg1);
}
ListenerDouble::ListenerDouble(ListenerDouble::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerDouble::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerDouble::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(double)));
return connected_;
}
void ListenerDouble::invoke(double arg1) {
f_(arg1);
}
ListenerInt::ListenerInt(ListenerInt::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerInt::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerInt::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(int)));
return connected_;
}
void ListenerInt::invoke(int arg1) {
f_(arg1);
}
ListenerIntBool::ListenerIntBool(ListenerIntBool::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerIntBool::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerIntBool::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(int,bool)));
return connected_;
}
void ListenerIntBool::invoke(int arg1, bool arg2) {
f_(arg1, arg2);
}
ListenerIntInt::ListenerIntInt(ListenerIntInt::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerIntInt::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerIntInt::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(int,int)));
return connected_;
}
void ListenerIntInt::invoke(int arg1, int arg2) {
f_(arg1, arg2);
}
ListenerOrientation::ListenerOrientation(ListenerOrientation::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerOrientation::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerOrientation::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(Qt::Orientation)));
return connected_;
}
void ListenerOrientation::invoke(Qt::Orientation arg1) {
f_(arg1);
}
ListenerPtrQAbstractButton::ListenerPtrQAbstractButton(ListenerPtrQAbstractButton::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerPtrQAbstractButton::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerPtrQAbstractButton::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QAbstractButton*)));
return connected_;
}
void ListenerPtrQAbstractButton::invoke(QAbstractButton* arg1) {
f_(arg1);
}
ListenerPtrQAbstractButtonBool::ListenerPtrQAbstractButtonBool(ListenerPtrQAbstractButtonBool::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerPtrQAbstractButtonBool::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerPtrQAbstractButtonBool::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QAbstractButton*,bool)));
return connected_;
}
void ListenerPtrQAbstractButtonBool::invoke(QAbstractButton* arg1, bool arg2) {
f_(arg1, arg2);
}
ListenerPtrQAbstractItemModel::ListenerPtrQAbstractItemModel(ListenerPtrQAbstractItemModel::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerPtrQAbstractItemModel::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerPtrQAbstractItemModel::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QAbstractItemModel*)));
return connected_;
}
void ListenerPtrQAbstractItemModel::invoke(QAbstractItemModel* arg1) {
f_(arg1);
}
ListenerPtrQAction::ListenerPtrQAction(ListenerPtrQAction::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerPtrQAction::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerPtrQAction::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QAction*)));
return connected_;
}
void ListenerPtrQAction::invoke(QAction* arg1) {
f_(arg1);
}
ListenerPtrQObject::ListenerPtrQObject(ListenerPtrQObject::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerPtrQObject::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerPtrQObject::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QObject*)));
return connected_;
}
void ListenerPtrQObject::invoke(QObject* arg1) {
f_(arg1);
}
ListenerPtrQTreeWidgetItem::ListenerPtrQTreeWidgetItem(ListenerPtrQTreeWidgetItem::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerPtrQTreeWidgetItem::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerPtrQTreeWidgetItem::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QTreeWidgetItem*)));
return connected_;
}
void ListenerPtrQTreeWidgetItem::invoke(QTreeWidgetItem* arg1) {
f_(arg1);
}
ListenerPtrQTreeWidgetItemInt::ListenerPtrQTreeWidgetItemInt(ListenerPtrQTreeWidgetItemInt::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerPtrQTreeWidgetItemInt::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerPtrQTreeWidgetItemInt::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QTreeWidgetItem*,int)));
return connected_;
}
void ListenerPtrQTreeWidgetItemInt::invoke(QTreeWidgetItem* arg1, int arg2) {
f_(arg1, arg2);
}
ListenerPtrQTreeWidgetItemPtrQTreeWidgetItem::ListenerPtrQTreeWidgetItemPtrQTreeWidgetItem(ListenerPtrQTreeWidgetItemPtrQTreeWidgetItem::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerPtrQTreeWidgetItemPtrQTreeWidgetItem::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerPtrQTreeWidgetItemPtrQTreeWidgetItem::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QTreeWidgetItem*,QTreeWidgetItem*)));
return connected_;
}
void ListenerPtrQTreeWidgetItemPtrQTreeWidgetItem::invoke(QTreeWidgetItem* arg1, QTreeWidgetItem* arg2) {
f_(arg1, arg2);
}
ListenerPtrQWidgetPtrQWidget::ListenerPtrQWidgetPtrQWidget(ListenerPtrQWidgetPtrQWidget::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerPtrQWidgetPtrQWidget::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerPtrQWidgetPtrQWidget::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QWidget*,QWidget*)));
return connected_;
}
void ListenerPtrQWidgetPtrQWidget::invoke(QWidget* arg1, QWidget* arg2) {
f_(arg1, arg2);
}
ListenerQAbstractSliderAction::ListenerQAbstractSliderAction(ListenerQAbstractSliderAction::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerQAbstractSliderAction::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerQAbstractSliderAction::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QAbstractSlider::SliderAction)));
return connected_;
}
void ListenerQAbstractSliderAction::invoke(QAbstractSlider::SliderAction arg1) {
f_(arg1);
}
ListenerQClipboardMode::ListenerQClipboardMode(ListenerQClipboardMode::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerQClipboardMode::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerQClipboardMode::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QClipboard::Mode)));
return connected_;
}
void ListenerQClipboardMode::invoke(QClipboard::Mode arg1) {
f_(arg1);
}
ListenerQDate::ListenerQDate(ListenerQDate::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerQDate::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerQDate::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QDate)));
return connected_;
}
void ListenerQDate::invoke(QDate arg1) {
f_(arg1);
}
ListenerQDockWidgetFeatures::ListenerQDockWidgetFeatures(ListenerQDockWidgetFeatures::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerQDockWidgetFeatures::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerQDockWidgetFeatures::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QDockWidget::DockWidgetFeatures)));
return connected_;
}
void ListenerQDockWidgetFeatures::invoke(QDockWidget::DockWidgetFeatures arg1) {
f_(arg1);
}
ListenerQModelIndex::ListenerQModelIndex(ListenerQModelIndex::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerQModelIndex::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerQModelIndex::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QModelIndex)));
return connected_;
}
void ListenerQModelIndex::invoke(QModelIndex arg1) {
f_(arg1);
}
ListenerQModelIndexIntInt::ListenerQModelIndexIntInt(ListenerQModelIndexIntInt::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerQModelIndexIntInt::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerQModelIndexIntInt::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QModelIndex,int,int)));
return connected_;
}
void ListenerQModelIndexIntInt::invoke(QModelIndex arg1, int arg2, int arg3) {
f_(arg1, arg2, arg3);
}
ListenerQModelIndexIntIntQModelIndexInt::ListenerQModelIndexIntIntQModelIndexInt(ListenerQModelIndexIntIntQModelIndexInt::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerQModelIndexIntIntQModelIndexInt::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerQModelIndexIntIntQModelIndexInt::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QModelIndex,int,int,QModelIndex,int)));
return connected_;
}
void ListenerQModelIndexIntIntQModelIndexInt::invoke(QModelIndex arg1, int arg2, int arg3, QModelIndex arg4, int arg5) {
f_(arg1, arg2, arg3, arg4, arg5);
}
ListenerQModelIndexQModelIndex::ListenerQModelIndexQModelIndex(ListenerQModelIndexQModelIndex::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerQModelIndexQModelIndex::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerQModelIndexQModelIndex::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QModelIndex,QModelIndex)));
return connected_;
}
void ListenerQModelIndexQModelIndex::invoke(QModelIndex arg1, QModelIndex arg2) {
f_(arg1, arg2);
}
ListenerQModelIndexQModelIndexQVectorInt::ListenerQModelIndexQModelIndexQVectorInt(ListenerQModelIndexQModelIndexQVectorInt::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerQModelIndexQModelIndexQVectorInt::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerQModelIndexQModelIndexQVectorInt::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QModelIndex,QModelIndex,QVector<int>)));
return connected_;
}
void ListenerQModelIndexQModelIndexQVectorInt::invoke(QModelIndex arg1, QModelIndex arg2, QVector<int> arg3) {
f_(arg1, arg2, arg3);
}
ListenerQPoint::ListenerQPoint(ListenerQPoint::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerQPoint::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerQPoint::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QPoint)));
return connected_;
}
void ListenerQPoint::invoke(QPoint arg1) {
f_(arg1);
}
ListenerQreal::ListenerQreal(ListenerQreal::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerQreal::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerQreal::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(qreal)));
return connected_;
}
void ListenerQreal::invoke(qreal arg1) {
f_(arg1);
}
ListenerQSize::ListenerQSize(ListenerQSize::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerQSize::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerQSize::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QSize)));
return connected_;
}
void ListenerQSize::invoke(QSize arg1) {
f_(arg1);
}
ListenerQString::ListenerQString(ListenerQString::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerQString::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerQString::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QString)));
return connected_;
}
void ListenerQString::invoke(QString arg1) {
f_(arg1);
}
ListenerQSystemTrayIconActivationReason::ListenerQSystemTrayIconActivationReason(ListenerQSystemTrayIconActivationReason::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerQSystemTrayIconActivationReason::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerQSystemTrayIconActivationReason::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QSystemTrayIcon::ActivationReason)));
return connected_;
}
void ListenerQSystemTrayIconActivationReason::invoke(QSystemTrayIcon::ActivationReason arg1) {
f_(arg1);
}
#if QT_VERSION >= 0x050000
ListenerQWindowVisibility::ListenerQWindowVisibility(ListenerQWindowVisibility::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerQWindowVisibility::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerQWindowVisibility::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(QWindow::Visibility)));
return connected_;
}
void ListenerQWindowVisibility::invoke(QWindow::Visibility arg1) {
f_(arg1);
}
#endif
ListenerRefConstQIcon::ListenerRefConstQIcon(ListenerRefConstQIcon::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerRefConstQIcon::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerRefConstQIcon::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(const QIcon&)));
return connected_;
}
void ListenerRefConstQIcon::invoke(const QIcon& arg1) {
f_(arg1);
}
ListenerRefConstQItemSelectionRefConstQItemSelection::ListenerRefConstQItemSelectionRefConstQItemSelection(ListenerRefConstQItemSelectionRefConstQItemSelection::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerRefConstQItemSelectionRefConstQItemSelection::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerRefConstQItemSelectionRefConstQItemSelection::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(const QItemSelection&,const QItemSelection&)));
return connected_;
}
void ListenerRefConstQItemSelectionRefConstQItemSelection::invoke(const QItemSelection& arg1, const QItemSelection& arg2) {
f_(arg1, arg2);
}
#if QT_VERSION >= 0x050000
ListenerScreenOrientation::ListenerScreenOrientation(ListenerScreenOrientation::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerScreenOrientation::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerScreenOrientation::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(Qt::ScreenOrientation)));
return connected_;
}
void ListenerScreenOrientation::invoke(Qt::ScreenOrientation arg1) {
f_(arg1);
}
#endif
ListenerToolBarAreas::ListenerToolBarAreas(ListenerToolBarAreas::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerToolBarAreas::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerToolBarAreas::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(Qt::ToolBarAreas)));
return connected_;
}
void ListenerToolBarAreas::invoke(Qt::ToolBarAreas arg1) {
f_(arg1);
}
ListenerToolButtonStyle::ListenerToolButtonStyle(ListenerToolButtonStyle::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerToolButtonStyle::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerToolButtonStyle::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(Qt::ToolButtonStyle)));
return connected_;
}
void ListenerToolButtonStyle::invoke(Qt::ToolButtonStyle arg1) {
f_(arg1);
}
ListenerWindowModality::ListenerWindowModality(ListenerWindowModality::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerWindowModality::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerWindowModality::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(Qt::WindowModality)));
return connected_;
}
void ListenerWindowModality::invoke(Qt::WindowModality arg1) {
f_(arg1);
}
ListenerWindowState::ListenerWindowState(ListenerWindowState::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool ListenerWindowState::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"ListenerWindowState::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke(Qt::WindowState)));
return connected_;
}
void ListenerWindowState::invoke(Qt::WindowState arg1) {
f_(arg1);
}
Listener::Listener(Listener::callback f, QObject* parent) :
QObject(parent), f_(f), connected_(false) {}
bool Listener::connectListener(QObject* source, const std::string& signal) {
if (connected_) {
std::cerr <<
"Listener::connectListener: Internal error, already connected. "
"Not connecting again.\n" << std::flush;
return false;
}
setParent(source);
connected_ = connect(source, signal.c_str(), SLOT(invoke()));
return connected_;
}
void Listener::invoke() {
f_();
}
| [
"jellyzone@gmail.com"
] | jellyzone@gmail.com |
ede5e4ce958f1f78ffbf3e3b81f15624729100e8 | 4471ba52c1eca0459c425fb07f7695cbc74c5cfa | /MiniBlog/MiniBlog/PubTool/md5.h | 17da68a328559e00edc2c7cff45b5a5ac8d5b3ba | [] | no_license | shzhqiu/weibo | 84ecff15f31d71dda44eb41b18b627a74355122f | 809938338f2496d182d16295db5ae2f4fbd5e2e8 | refs/heads/master | 2016-08-04T00:45:11.332321 | 2011-11-11T15:19:47 | 2011-11-11T15:19:47 | 2,589,026 | 1 | 0 | null | null | null | null | ISO-8859-3 | C++ | false | false | 1,852 | h | /*
This is the C++ implementation of the MD5 Message-Digest
Algorithm desrcipted in RFC 1321.
I translated the C code from this RFC to C++.
There is now warranty.
Feb. 12. 2005
Benjamin Grüdelbach
*/
/* Copyright (C) 1991-2, RSA Data Security, Inc. Created 1991. All
rights reserved.
License to copy and use this software is granted provided that it
is identified as the "RSA Data Security, Inc. MD5 Message-Digest
Algorithm" in all material mentioning or referencing this software
or this function.
License is also granted to make and use derivative works provided
that such works are identified as "derived from the RSA Data
Security, Inc. MD5 Message-Digest Algorithm" in all material
mentioning or referencing the derived work.
RSA Data Security, Inc. makes no representations concerning either
the merchantability of this software or the suitability of this
software for any particular purpose. It is provided "as is"
without express or implied warranty of any kind.
These notices must be retained in any copies of any part of this
documentation and/or software.
*/
typedef unsigned char *POINTER;
/* MD5 context. */
typedef struct
{
unsigned long int state[4]; /* state (ABCD) */
unsigned long int count[2]; /* number of bits, modulo 2^64 (lsb first) */
unsigned char buffer[64]; /* input buffer */
} MD5_CTX;
class MD5
{
private:
void MD5Transform (unsigned long int state[4], unsigned char block[64]);
void Encode (unsigned char*, unsigned long int*, unsigned int);
void Decode (unsigned long int*, unsigned char*, unsigned int);
void MD5_memcpy (POINTER, POINTER, unsigned int);
void MD5_memset (POINTER, int, unsigned int);
public:
void MD5Init (MD5_CTX*);
void MD5Update (MD5_CTX*, unsigned char*, unsigned int);
void MD5Final (unsigned char [16], MD5_CTX*);
MD5(){};
~MD5(){};
};
| [
"shzhqiu.cn@gmail.com"
] | shzhqiu.cn@gmail.com |
706cd6260677af4672e1744d9333ea41606abff6 | 7f468bce4f663da4471dc612d59211a70d822e76 | /ros1/encoder/src/encoder_node.cpp | 71a253597dea907d18c3bc29644445dcce0ff6f7 | [] | no_license | lowlandsolution/ros_examples | 1adeb95c44dd7515c9bd706d4f76dedf173b591c | 4ea2c87168b2d6a91acadad2a30eb43479b315df | refs/heads/master | 2020-06-10T20:27:12.594645 | 2019-07-22T22:22:29 | 2019-07-22T22:22:29 | 193,736,980 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 786 | cpp | #include <ros/ros.h>
#include <encoder_msgs/EncoderFeedback.h>
int main(int argc, char** argv, char** envp)
{
ros::init(argc, argv, "encoder");
ros::NodeHandle nh;
ros::NodeHandle pn("~");
int cycle_rate;
pn.param<int>("cycle_rate", cycle_rate, 1);
ros::Publisher encoder_pub =
nh.advertise<encoder_msgs::EncoderFeedback>("encoder_feedback", 1);
unsigned int ticks = 0;
unsigned int maxTicks = 4096;
ros::Rate cycle(cycle_rate);
while (ros::ok()) {
// Publish linearly increasing encoder feedback
encoder_msgs::EncoderFeedback msg;
ticks = (ticks + 1) % maxTicks;
msg.ticks = ticks;
msg.angle = ticks * 2 * M_PI / maxTicks;
encoder_pub.publish(msg);
cycle.sleep();
}
}
| [
"lowlandsolution@gmail.com"
] | lowlandsolution@gmail.com |
83e304f7f35f0c6f89f7b3493924b6c3aa43ffdd | e3286dd07b79b3424a8e12bff7eaa800f1eea00e | /grumfork-src/src/main.h | 3c61a69ede3fbc82d6da54d2d37c629c03da2cf1 | [
"MIT"
] | permissive | grumfork/SRC | eab433a59f0ffc8911f08e05c7fd9883bfb3df55 | 7cae7c9fb3e9b9aed285bd1eadc5ab20ee8db2af | refs/heads/master | 2021-01-19T15:26:05.180645 | 2017-04-14T00:05:06 | 2017-04-14T00:05:06 | 88,216,144 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 45,215 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_MAIN_H
#define BITCOIN_MAIN_H
#include "bignum.h"
#include "sync.h"
#include "net.h"
#include "script.h"
#include "scrypt.h"
#include "zerocoin/Zerocoin.h"
#include <list>
class CWallet;
class CBlock;
class CBlockIndex;
class CKeyItem;
class CReserveKey;
class COutPoint;
class CAddress;
class CInv;
class CRequestTracker;
class CNode;
class CTxMemPool;
static const int LAST_POW_BLOCK = 500000;
/** The maximum allowed size for a serialized block, in bytes (network rule) */
static const unsigned int MAX_BLOCK_SIZE = 1000000;
/** The maximum size for mined blocks */
static const unsigned int MAX_BLOCK_SIZE_GEN = MAX_BLOCK_SIZE/2;
/** The maximum size for transactions we're willing to relay/mine **/
static const unsigned int MAX_STANDARD_TX_SIZE = MAX_BLOCK_SIZE_GEN/5;
/** The maximum allowed number of signature check operations in a block (network rule) */
static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE/50;
/** The maximum number of orphan transactions kept in memory */
static const unsigned int MAX_ORPHAN_TRANSACTIONS = MAX_BLOCK_SIZE/100;
/** The maximum number of entries in an 'inv' protocol message */
static const unsigned int MAX_INV_SZ = 50000;
/** Fees smaller than this (in satoshi) are considered zero fee (for transaction creation) */
static const int64_t MIN_TX_FEE = 10000;
/** Fees smaller than this (in satoshi) are considered zero fee (for relaying) */
static const int64_t MIN_RELAY_TX_FEE = MIN_TX_FEE;
/** No amount larger than this (in satoshi) is valid */
static const int64_t MAX_MONEY = 16453608 * COIN;
inline bool MoneyRange(int64_t nValue) { return (nValue >= 0 && nValue <= MAX_MONEY); }
/** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
static const int64_t COIN_YEAR_REWARD = 2 * CENT;
static const uint256 hashGenesisBlock("0x0000095c5aa6c964138f3c60113cd52f2f4e8e4df85a02d684652425eef82e35");
static const uint256 hashGenesisBlockTestNet("0x0000095c5aa6c964138f3c60113cd52f2f4e8e4df85a02d684652425eef82e35");
inline int64_t PastDrift(int64_t nTime) { return nTime - 10 * 60; } // up to 10 minutes from the past
inline int64_t FutureDrift(int64_t nTime) { return nTime + 10 * 60; } // up to 10 minutes from the future
extern libzerocoin::Params* ZCParams;
extern CScript COINBASE_FLAGS;
extern CCriticalSection cs_main;
extern std::map<uint256, CBlockIndex*> mapBlockIndex;
extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
extern CBlockIndex* pindexGenesisBlock;
extern unsigned int nTargetSpacing;
extern unsigned int nStakeMinAge;
extern unsigned int nStakeMaxAge;
extern unsigned int nNodeLifespan;
extern int nCoinbaseMaturity;
extern int nBestHeight;
extern uint256 nBestChainTrust;
extern uint256 nBestInvalidTrust;
extern uint256 hashBestChain;
extern CBlockIndex* pindexBest;
extern unsigned int nTransactionsUpdated;
extern uint64_t nLastBlockTx;
extern uint64_t nLastBlockSize;
extern int64_t nLastCoinStakeSearchInterval;
extern const std::string strMessageMagic;
extern int64_t nTimeBestReceived;
extern CCriticalSection cs_setpwalletRegistered;
extern std::set<CWallet*> setpwalletRegistered;
extern unsigned char pchMessageStart[4];
extern std::map<uint256, CBlock*> mapOrphanBlocks;
// Settings
extern int64_t nTransactionFee;
extern int64_t nReserveBalance;
extern int64_t nMinimumInputValue;
extern bool fUseFastIndex;
extern unsigned int nDerivationMethodIndex;
extern bool fEnforceCanonical;
// Minimum disk space required - used in CheckDiskSpace()
static const uint64_t nMinDiskSpace = 52428800;
class CReserveKey;
class CTxDB;
class CTxIndex;
void RegisterWallet(CWallet* pwalletIn);
void UnregisterWallet(CWallet* pwalletIn);
void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL, bool fUpdate = false, bool fConnect = true);
bool ProcessBlock(CNode* pfrom, CBlock* pblock);
bool CheckDiskSpace(uint64_t nAdditionalBytes=0);
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode="rb");
FILE* AppendBlockFile(unsigned int& nFileRet);
bool LoadBlockIndex(bool fAllowNew=true);
void PrintBlockTree();
CBlockIndex* FindBlockByHeight(int nHeight);
bool ProcessMessages(CNode* pfrom);
bool SendMessages(CNode* pto, bool fSendTrickle);
bool LoadExternalBlockFile(FILE* fileIn);
bool CheckProofOfWork(uint256 hash, unsigned int nBits);
unsigned int GetNextTargetRequired(const CBlockIndex* pindexLast, bool fProofOfStake);
int64_t GetProofOfWorkReward(int64_t nFees);
int64_t GetProofOfStakeReward(int64_t nCoinAge, int64_t nFees);
unsigned int ComputeMinWork(unsigned int nBase, int64_t nTime);
unsigned int ComputeMinStake(unsigned int nBase, int64_t nTime, unsigned int nBlockTime);
int GetNumBlocksOfPeers();
bool IsInitialBlockDownload();
std::string GetWarnings(std::string strFor);
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock);
uint256 WantedByOrphan(const CBlock* pblockOrphan);
const CBlockIndex* GetLastBlockIndex(const CBlockIndex* pindex, bool fProofOfStake);
void StakeMiner(CWallet *pwallet);
void ResendWalletTransactions(bool fForce = false);
/** (try to) add transaction to memory pool **/
bool AcceptToMemoryPool(CTxMemPool& pool, CTransaction &tx,
bool* pfMissingInputs);
bool GetWalletFile(CWallet* pwallet, std::string &strWalletFileOut);
/** Position on disk for a particular transaction. */
class CDiskTxPos
{
public:
unsigned int nFile;
unsigned int nBlockPos;
unsigned int nTxPos;
CDiskTxPos()
{
SetNull();
}
CDiskTxPos(unsigned int nFileIn, unsigned int nBlockPosIn, unsigned int nTxPosIn)
{
nFile = nFileIn;
nBlockPos = nBlockPosIn;
nTxPos = nTxPosIn;
}
IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
void SetNull() { nFile = (unsigned int) -1; nBlockPos = 0; nTxPos = 0; }
bool IsNull() const { return (nFile == (unsigned int) -1); }
friend bool operator==(const CDiskTxPos& a, const CDiskTxPos& b)
{
return (a.nFile == b.nFile &&
a.nBlockPos == b.nBlockPos &&
a.nTxPos == b.nTxPos);
}
friend bool operator!=(const CDiskTxPos& a, const CDiskTxPos& b)
{
return !(a == b);
}
std::string ToString() const
{
if (IsNull())
return "null";
else
return strprintf("(nFile=%u, nBlockPos=%u, nTxPos=%u)", nFile, nBlockPos, nTxPos);
}
void print() const
{
printf("%s", ToString().c_str());
}
};
/** An inpoint - a combination of a transaction and an index n into its vin */
class CInPoint
{
public:
CTransaction* ptx;
unsigned int n;
CInPoint() { SetNull(); }
CInPoint(CTransaction* ptxIn, unsigned int nIn) { ptx = ptxIn; n = nIn; }
void SetNull() { ptx = NULL; n = (unsigned int) -1; }
bool IsNull() const { return (ptx == NULL && n == (unsigned int) -1); }
};
/** An outpoint - a combination of a transaction hash and an index n into its vout */
class COutPoint
{
public:
uint256 hash;
unsigned int n;
COutPoint() { SetNull(); }
COutPoint(uint256 hashIn, unsigned int nIn) { hash = hashIn; n = nIn; }
IMPLEMENT_SERIALIZE( READWRITE(FLATDATA(*this)); )
void SetNull() { hash = 0; n = (unsigned int) -1; }
bool IsNull() const { return (hash == 0 && n == (unsigned int) -1); }
friend bool operator<(const COutPoint& a, const COutPoint& b)
{
return (a.hash < b.hash || (a.hash == b.hash && a.n < b.n));
}
friend bool operator==(const COutPoint& a, const COutPoint& b)
{
return (a.hash == b.hash && a.n == b.n);
}
friend bool operator!=(const COutPoint& a, const COutPoint& b)
{
return !(a == b);
}
std::string ToString() const
{
return strprintf("COutPoint(%s, %u)", hash.ToString().substr(0,10).c_str(), n);
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** An input of a transaction. It contains the location of the previous
* transaction's output that it claims and a signature that matches the
* output's public key.
*/
class CTxIn
{
public:
COutPoint prevout;
CScript scriptSig;
unsigned int nSequence;
CTxIn()
{
nSequence = std::numeric_limits<unsigned int>::max();
}
explicit CTxIn(COutPoint prevoutIn, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
{
prevout = prevoutIn;
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
CTxIn(uint256 hashPrevTx, unsigned int nOut, CScript scriptSigIn=CScript(), unsigned int nSequenceIn=std::numeric_limits<unsigned int>::max())
{
prevout = COutPoint(hashPrevTx, nOut);
scriptSig = scriptSigIn;
nSequence = nSequenceIn;
}
IMPLEMENT_SERIALIZE
(
READWRITE(prevout);
READWRITE(scriptSig);
READWRITE(nSequence);
)
bool IsFinal() const
{
return (nSequence == std::numeric_limits<unsigned int>::max());
}
friend bool operator==(const CTxIn& a, const CTxIn& b)
{
return (a.prevout == b.prevout &&
a.scriptSig == b.scriptSig &&
a.nSequence == b.nSequence);
}
friend bool operator!=(const CTxIn& a, const CTxIn& b)
{
return !(a == b);
}
std::string ToStringShort() const
{
return strprintf(" %s %d", prevout.hash.ToString().c_str(), prevout.n);
}
std::string ToString() const
{
std::string str;
str += "CTxIn(";
str += prevout.ToString();
if (prevout.IsNull())
str += strprintf(", coinbase %s", HexStr(scriptSig).c_str());
else
str += strprintf(", scriptSig=%s", scriptSig.ToString().substr(0,24).c_str());
if (nSequence != std::numeric_limits<unsigned int>::max())
str += strprintf(", nSequence=%u", nSequence);
str += ")";
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** An output of a transaction. It contains the public key that the next input
* must be able to sign with to claim it.
*/
class CTxOut
{
public:
int64_t nValue;
CScript scriptPubKey;
CTxOut()
{
SetNull();
}
CTxOut(int64_t nValueIn, CScript scriptPubKeyIn)
{
nValue = nValueIn;
scriptPubKey = scriptPubKeyIn;
}
IMPLEMENT_SERIALIZE
(
READWRITE(nValue);
READWRITE(scriptPubKey);
)
void SetNull()
{
nValue = -1;
scriptPubKey.clear();
}
bool IsNull()
{
return (nValue == -1);
}
void SetEmpty()
{
nValue = 0;
scriptPubKey.clear();
}
bool IsEmpty() const
{
return (nValue == 0 && scriptPubKey.empty());
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
friend bool operator==(const CTxOut& a, const CTxOut& b)
{
return (a.nValue == b.nValue &&
a.scriptPubKey == b.scriptPubKey);
}
friend bool operator!=(const CTxOut& a, const CTxOut& b)
{
return !(a == b);
}
std::string ToStringShort() const
{
return strprintf(" out %s %s", FormatMoney(nValue).c_str(), scriptPubKey.ToString(true).c_str());
}
std::string ToString() const
{
if (IsEmpty()) return "CTxOut(empty)";
return strprintf("CTxOut(nValue=%s, scriptPubKey=%s)", FormatMoney(nValue).c_str(), scriptPubKey.ToString().c_str());
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
enum GetMinFee_mode
{
GMF_BLOCK,
GMF_RELAY,
GMF_SEND,
};
typedef std::map<uint256, std::pair<CTxIndex, CTransaction> > MapPrevTx;
/** The basic transaction that is broadcasted on the network and contained in
* blocks. A transaction can contain multiple inputs and outputs.
*/
class CTransaction
{
public:
static const int CURRENT_VERSION=1;
int nVersion;
unsigned int nTime;
std::vector<CTxIn> vin;
std::vector<CTxOut> vout;
unsigned int nLockTime;
// Denial-of-service detection:
mutable int nDoS;
bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
CTransaction()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(nTime);
READWRITE(vin);
READWRITE(vout);
READWRITE(nLockTime);
)
void SetNull()
{
nVersion = CTransaction::CURRENT_VERSION;
nTime = GetAdjustedTime();
vin.clear();
vout.clear();
nLockTime = 0;
nDoS = 0; // Denial-of-service prevention
}
bool IsNull() const
{
return (vin.empty() && vout.empty());
}
uint256 GetHash() const
{
return SerializeHash(*this);
}
bool IsNewerThan(const CTransaction& old) const
{
if (vin.size() != old.vin.size())
return false;
for (unsigned int i = 0; i < vin.size(); i++)
if (vin[i].prevout != old.vin[i].prevout)
return false;
bool fNewer = false;
unsigned int nLowest = std::numeric_limits<unsigned int>::max();
for (unsigned int i = 0; i < vin.size(); i++)
{
if (vin[i].nSequence != old.vin[i].nSequence)
{
if (vin[i].nSequence <= nLowest)
{
fNewer = false;
nLowest = vin[i].nSequence;
}
if (old.vin[i].nSequence < nLowest)
{
fNewer = true;
nLowest = old.vin[i].nSequence;
}
}
}
return fNewer;
}
bool IsCoinBase() const
{
return (vin.size() == 1 && vin[0].prevout.IsNull() && vout.size() >= 1);
}
bool IsCoinStake() const
{
// ppcoin: the coin stake transaction is marked with the first output empty
return (vin.size() > 0 && (!vin[0].prevout.IsNull()) && vout.size() >= 2 && vout[0].IsEmpty());
}
/** Check for standard transaction types
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return True if all inputs (scriptSigs) use only standard transaction forms
@see CTransaction::FetchInputs
*/
bool AreInputsStandard(const MapPrevTx& mapInputs) const;
/** Count ECDSA signature operations the old-fashioned (pre-0.6) way
@return number of sigops this transaction's outputs will produce when spent
@see CTransaction::FetchInputs
*/
unsigned int GetLegacySigOpCount() const;
/** Count ECDSA signature operations in pay-to-script-hash inputs.
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return maximum number of sigops required to validate this transaction's inputs
@see CTransaction::FetchInputs
*/
unsigned int GetP2SHSigOpCount(const MapPrevTx& mapInputs) const;
/** Amount of bitcoins spent by this transaction.
@return sum of all outputs (note: does not include fees)
*/
int64_t GetValueOut() const
{
int64_t nValueOut = 0;
BOOST_FOREACH(const CTxOut& txout, vout)
{
nValueOut += txout.nValue;
if (!MoneyRange(txout.nValue) || !MoneyRange(nValueOut))
throw std::runtime_error("CTransaction::GetValueOut() : value out of range");
}
return nValueOut;
}
/** Amount of bitcoins coming in to this transaction
Note that lightweight clients may not know anything besides the hash of previous transactions,
so may not be able to calculate this.
@param[in] mapInputs Map of previous transactions that have outputs we're spending
@return Sum of value of all inputs (scriptSigs)
@see CTransaction::FetchInputs
*/
int64_t GetValueIn(const MapPrevTx& mapInputs) const;
int64_t GetMinFee(unsigned int nBlockSize=1, enum GetMinFee_mode mode=GMF_BLOCK, unsigned int nBytes = 0) const;
bool ReadFromDisk(CDiskTxPos pos, FILE** pfileRet=NULL)
{
CAutoFile filein = CAutoFile(OpenBlockFile(pos.nFile, 0, pfileRet ? "rb+" : "rb"), SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CTransaction::ReadFromDisk() : OpenBlockFile failed");
// Read transaction
if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
return error("CTransaction::ReadFromDisk() : fseek failed");
try {
filein >> *this;
}
catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
// Return file pointer
if (pfileRet)
{
if (fseek(filein, pos.nTxPos, SEEK_SET) != 0)
return error("CTransaction::ReadFromDisk() : second fseek failed");
*pfileRet = filein.release();
}
return true;
}
friend bool operator==(const CTransaction& a, const CTransaction& b)
{
return (a.nVersion == b.nVersion &&
a.nTime == b.nTime &&
a.vin == b.vin &&
a.vout == b.vout &&
a.nLockTime == b.nLockTime);
}
friend bool operator!=(const CTransaction& a, const CTransaction& b)
{
return !(a == b);
}
std::string ToStringShort() const
{
std::string str;
str += strprintf("%s %s", GetHash().ToString().c_str(), IsCoinBase()? "base" : (IsCoinStake()? "stake" : "user"));
return str;
}
std::string ToString() const
{
std::string str;
str += IsCoinBase()? "Coinbase" : (IsCoinStake()? "Coinstake" : "CTransaction");
str += strprintf("(hash=%s, nTime=%d, ver=%d, vin.size=%"PRIszu", vout.size=%"PRIszu", nLockTime=%d)\n",
GetHash().ToString().substr(0,10).c_str(),
nTime,
nVersion,
vin.size(),
vout.size(),
nLockTime);
for (unsigned int i = 0; i < vin.size(); i++)
str += " " + vin[i].ToString() + "\n";
for (unsigned int i = 0; i < vout.size(); i++)
str += " " + vout[i].ToString() + "\n";
return str;
}
void print() const
{
printf("%s", ToString().c_str());
}
bool ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet);
bool ReadFromDisk(CTxDB& txdb, COutPoint prevout);
bool ReadFromDisk(COutPoint prevout);
bool DisconnectInputs(CTxDB& txdb);
/** Fetch from memory and/or disk. inputsRet keys are transaction hashes.
@param[in] txdb Transaction database
@param[in] mapTestPool List of pending changes to the transaction index database
@param[in] fBlock True if being called to add a new best-block to the chain
@param[in] fMiner True if being called by CreateNewBlock
@param[out] inputsRet Pointers to this transaction's inputs
@param[out] fInvalid returns true if transaction is invalid
@return Returns true if all inputs are in txdb or mapTestPool
*/
bool FetchInputs(CTxDB& txdb, const std::map<uint256, CTxIndex>& mapTestPool,
bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid);
/** Sanity check previous transactions, then, if all checks succeed,
mark them as spent by this transaction.
@param[in] inputs Previous transactions (from FetchInputs)
@param[out] mapTestPool Keeps track of inputs that need to be updated on disk
@param[in] posThisTx Position of this transaction on disk
@param[in] pindexBlock
@param[in] fBlock true if called from ConnectBlock
@param[in] fMiner true if called from CreateNewBlock
@return Returns true if all checks succeed
*/
bool ConnectInputs(CTxDB& txdb, MapPrevTx inputs,
std::map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner);
bool CheckTransaction() const;
bool GetCoinAge(CTxDB& txdb, uint64_t& nCoinAge) const; // ppcoin: get transaction coin age
protected:
const CTxOut& GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const;
};
/** Check for standard transaction types
@return True if all outputs (scriptPubKeys) use only standard transaction forms
*/
bool IsStandardTx(const CTransaction& tx);
bool IsFinalTx(const CTransaction &tx, int nBlockHeight = 0, int64_t nBlockTime = 0);
/** A transaction with a merkle branch linking it to the block chain. */
class CMerkleTx : public CTransaction
{
private:
int GetDepthInMainChainINTERNAL(CBlockIndex* &pindexRet) const;
public:
uint256 hashBlock;
std::vector<uint256> vMerkleBranch;
int nIndex;
// memory only
mutable bool fMerkleVerified;
CMerkleTx()
{
Init();
}
CMerkleTx(const CTransaction& txIn) : CTransaction(txIn)
{
Init();
}
void Init()
{
hashBlock = 0;
nIndex = -1;
fMerkleVerified = false;
}
IMPLEMENT_SERIALIZE
(
nSerSize += SerReadWrite(s, *(CTransaction*)this, nType, nVersion, ser_action);
nVersion = this->nVersion;
READWRITE(hashBlock);
READWRITE(vMerkleBranch);
READWRITE(nIndex);
)
int SetMerkleBranch(const CBlock* pblock=NULL);
// Return depth of transaction in blockchain:
// -1 : not in blockchain, and not in memory pool (conflicted transaction)
// 0 : in memory pool, waiting to be included in a block
// >=1 : this many blocks deep in the main chain
int GetDepthInMainChain(CBlockIndex* &pindexRet) const;
int GetDepthInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChain(pindexRet); }
bool IsInMainChain() const { CBlockIndex *pindexRet; return GetDepthInMainChainINTERNAL(pindexRet) > 0; }
int GetBlocksToMaturity() const;
bool AcceptToMemoryPool();
};
/** A txdb record that contains the disk location of a transaction and the
* locations of transactions that spend its outputs. vSpent is really only
* used as a flag, but having the location is very helpful for debugging.
*/
class CTxIndex
{
public:
CDiskTxPos pos;
std::vector<CDiskTxPos> vSpent;
CTxIndex()
{
SetNull();
}
CTxIndex(const CDiskTxPos& posIn, unsigned int nOutputs)
{
pos = posIn;
vSpent.resize(nOutputs);
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(pos);
READWRITE(vSpent);
)
void SetNull()
{
pos.SetNull();
vSpent.clear();
}
bool IsNull()
{
return pos.IsNull();
}
friend bool operator==(const CTxIndex& a, const CTxIndex& b)
{
return (a.pos == b.pos &&
a.vSpent == b.vSpent);
}
friend bool operator!=(const CTxIndex& a, const CTxIndex& b)
{
return !(a == b);
}
int GetDepthInMainChain() const;
};
/** Nodes collect new transactions into a block, hash them into a hash tree,
* and scan through nonce values to make the block's hash satisfy proof-of-work
* requirements. When they solve the proof-of-work, they broadcast the block
* to everyone and the block is added to the block chain. The first transaction
* in the block is a special one that creates a new coin owned by the creator
* of the block.
*
* Blocks are appended to blk0001.dat files on disk. Their location on disk
* is indexed by CBlockIndex objects in memory.
*/
class CBlock
{
public:
// header
static const int CURRENT_VERSION=6;
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
// network and disk
std::vector<CTransaction> vtx;
// ppcoin: block signature - signed by one of the coin base txout[N]'s owner
std::vector<unsigned char> vchBlockSig;
// memory only
mutable std::vector<uint256> vMerkleTree;
// Denial-of-service detection:
mutable int nDoS;
bool DoS(int nDoSIn, bool fIn) const { nDoS += nDoSIn; return fIn; }
CBlock()
{
SetNull();
}
IMPLEMENT_SERIALIZE
(
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(hashPrevBlock);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
// ConnectBlock depends on vtx following header to generate CDiskTxPos
if (!(nType & (SER_GETHASH|SER_BLOCKHEADERONLY)))
{
READWRITE(vtx);
READWRITE(vchBlockSig);
}
else if (fRead)
{
const_cast<CBlock*>(this)->vtx.clear();
const_cast<CBlock*>(this)->vchBlockSig.clear();
}
)
void SetNull()
{
nVersion = CBlock::CURRENT_VERSION;
hashPrevBlock = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
vtx.clear();
vchBlockSig.clear();
vMerkleTree.clear();
nDoS = 0;
}
bool IsNull() const
{
return (nBits == 0);
}
uint256 GetHash() const
{
return GetPoWHash();
}
uint256 GetPoWHash() const
{
return scrypt_blockhash(CVOIDBEGIN(nVersion));
}
int64_t GetBlockTime() const
{
return (int64_t)nTime;
}
void UpdateTime(const CBlockIndex* pindexPrev);
// entropy bit for stake modifier if chosen by modifier
unsigned int GetStakeEntropyBit() const
{
// Take last bit of block hash as entropy bit
unsigned int nEntropyBit = ((GetHash().Get64()) & 1llu);
if (fDebug && GetBoolArg("-printstakemodifier"))
printf("GetStakeEntropyBit: hashBlock=%s nEntropyBit=%u\n", GetHash().ToString().c_str(), nEntropyBit);
return nEntropyBit;
}
// ppcoin: two types of block: proof-of-work or proof-of-stake
bool IsProofOfStake() const
{
return (vtx.size() > 1 && vtx[1].IsCoinStake());
}
bool IsProofOfWork() const
{
return !IsProofOfStake();
}
std::pair<COutPoint, unsigned int> GetProofOfStake() const
{
return IsProofOfStake()? std::make_pair(vtx[1].vin[0].prevout, vtx[1].nTime) : std::make_pair(COutPoint(), (unsigned int)0);
}
// ppcoin: get max transaction timestamp
int64_t GetMaxTransactionTime() const
{
int64_t maxTransactionTime = 0;
BOOST_FOREACH(const CTransaction& tx, vtx)
maxTransactionTime = std::max(maxTransactionTime, (int64_t)tx.nTime);
return maxTransactionTime;
}
uint256 BuildMerkleTree() const
{
vMerkleTree.clear();
BOOST_FOREACH(const CTransaction& tx, vtx)
vMerkleTree.push_back(tx.GetHash());
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
for (int i = 0; i < nSize; i += 2)
{
int i2 = std::min(i+1, nSize-1);
vMerkleTree.push_back(Hash(BEGIN(vMerkleTree[j+i]), END(vMerkleTree[j+i]),
BEGIN(vMerkleTree[j+i2]), END(vMerkleTree[j+i2])));
}
j += nSize;
}
return (vMerkleTree.empty() ? 0 : vMerkleTree.back());
}
std::vector<uint256> GetMerkleBranch(int nIndex) const
{
if (vMerkleTree.empty())
BuildMerkleTree();
std::vector<uint256> vMerkleBranch;
int j = 0;
for (int nSize = vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
int i = std::min(nIndex^1, nSize-1);
vMerkleBranch.push_back(vMerkleTree[j+i]);
nIndex >>= 1;
j += nSize;
}
return vMerkleBranch;
}
static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex)
{
if (nIndex == -1)
return 0;
BOOST_FOREACH(const uint256& otherside, vMerkleBranch)
{
if (nIndex & 1)
hash = Hash(BEGIN(otherside), END(otherside), BEGIN(hash), END(hash));
else
hash = Hash(BEGIN(hash), END(hash), BEGIN(otherside), END(otherside));
nIndex >>= 1;
}
return hash;
}
bool WriteToDisk(unsigned int& nFileRet, unsigned int& nBlockPosRet)
{
// Open history file to append
CAutoFile fileout = CAutoFile(AppendBlockFile(nFileRet), SER_DISK, CLIENT_VERSION);
if (!fileout)
return error("CBlock::WriteToDisk() : AppendBlockFile failed");
// Write index header
unsigned int nSize = fileout.GetSerializeSize(*this);
fileout << FLATDATA(pchMessageStart) << nSize;
// Write block
long fileOutPos = ftell(fileout);
if (fileOutPos < 0)
return error("CBlock::WriteToDisk() : ftell failed");
nBlockPosRet = fileOutPos;
fileout << *this;
// Flush stdio buffers and commit to disk before returning
fflush(fileout);
if (!IsInitialBlockDownload() || (nBestHeight+1) % 500 == 0)
FileCommit(fileout);
return true;
}
bool ReadFromDisk(unsigned int nFile, unsigned int nBlockPos, bool fReadTransactions=true)
{
SetNull();
// Open history file to read
CAutoFile filein = CAutoFile(OpenBlockFile(nFile, nBlockPos, "rb"), SER_DISK, CLIENT_VERSION);
if (!filein)
return error("CBlock::ReadFromDisk() : OpenBlockFile failed");
if (!fReadTransactions)
filein.nType |= SER_BLOCKHEADERONLY;
// Read block
try {
filein >> *this;
}
catch (std::exception &e) {
return error("%s() : deserialize or I/O error", __PRETTY_FUNCTION__);
}
// Check the header
if (fReadTransactions && IsProofOfWork() && !CheckProofOfWork(GetPoWHash(), nBits))
return error("CBlock::ReadFromDisk() : errors in block header");
return true;
}
void print() const
{
printf("CBlock(hash=%s, ver=%d, hashPrevBlock=%s, hashMerkleRoot=%s, nTime=%u, nBits=%08x, nNonce=%u, vtx=%"PRIszu", vchBlockSig=%s)\n",
GetHash().ToString().c_str(),
nVersion,
hashPrevBlock.ToString().c_str(),
hashMerkleRoot.ToString().c_str(),
nTime, nBits, nNonce,
vtx.size(),
HexStr(vchBlockSig.begin(), vchBlockSig.end()).c_str());
for (unsigned int i = 0; i < vtx.size(); i++)
{
printf(" ");
vtx[i].print();
}
printf(" vMerkleTree: ");
for (unsigned int i = 0; i < vMerkleTree.size(); i++)
printf("%s ", vMerkleTree[i].ToString().substr(0,10).c_str());
printf("\n");
}
bool DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex);
bool ConnectBlock(CTxDB& txdb, CBlockIndex* pindex, bool fJustCheck=false);
bool ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions=true);
bool SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew);
bool AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos, const uint256& hashProof);
bool CheckBlock(bool fCheckPOW=true, bool fCheckMerkleRoot=true, bool fCheckSig=true) const;
bool AcceptBlock();
bool GetCoinAge(uint64_t& nCoinAge) const; // ppcoin: calculate total coin age spent in block
bool SignBlock(CWallet& keystore, int64_t nFees);
bool CheckBlockSignature() const;
private:
bool SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew);
};
/** The block chain is a tree shaped structure starting with the
* genesis block at the root, with each block potentially having multiple
* candidates to be the next block. pprev and pnext link a path through the
* main/longest chain. A blockindex may have multiple pprev pointing back
* to it, but pnext will only point forward to the longest branch, or will
* be null if the block is not part of the longest chain.
*/
class CBlockIndex
{
public:
const uint256* phashBlock;
CBlockIndex* pprev;
CBlockIndex* pnext;
unsigned int nFile;
unsigned int nBlockPos;
uint256 nChainTrust; // ppcoin: trust score of block chain
int nHeight;
int64_t nMint;
int64_t nMoneySupply;
unsigned int nFlags; // ppcoin: block index flags
enum
{
BLOCK_PROOF_OF_STAKE = (1 << 0), // is proof-of-stake block
BLOCK_STAKE_ENTROPY = (1 << 1), // entropy bit for stake modifier
BLOCK_STAKE_MODIFIER = (1 << 2), // regenerated stake modifier
};
uint64_t nStakeModifier; // hash modifier for proof-of-stake
unsigned int nStakeModifierChecksum; // checksum of index; in-memeory only
// proof-of-stake specific fields
COutPoint prevoutStake;
unsigned int nStakeTime;
uint256 hashProof;
// block header
int nVersion;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
CBlockIndex()
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nFile = 0;
nBlockPos = 0;
nHeight = 0;
nChainTrust = 0;
nMint = 0;
nMoneySupply = 0;
nFlags = 0;
nStakeModifier = 0;
nStakeModifierChecksum = 0;
hashProof = 0;
prevoutStake.SetNull();
nStakeTime = 0;
nVersion = 0;
hashMerkleRoot = 0;
nTime = 0;
nBits = 0;
nNonce = 0;
}
CBlockIndex(unsigned int nFileIn, unsigned int nBlockPosIn, CBlock& block)
{
phashBlock = NULL;
pprev = NULL;
pnext = NULL;
nFile = nFileIn;
nBlockPos = nBlockPosIn;
nHeight = 0;
nChainTrust = 0;
nMint = 0;
nMoneySupply = 0;
nFlags = 0;
nStakeModifier = 0;
nStakeModifierChecksum = 0;
hashProof = 0;
if (block.IsProofOfStake())
{
SetProofOfStake();
prevoutStake = block.vtx[1].vin[0].prevout;
nStakeTime = block.vtx[1].nTime;
}
else
{
prevoutStake.SetNull();
nStakeTime = 0;
}
nVersion = block.nVersion;
hashMerkleRoot = block.hashMerkleRoot;
nTime = block.nTime;
nBits = block.nBits;
nNonce = block.nNonce;
}
CBlock GetBlockHeader() const
{
CBlock block;
block.nVersion = nVersion;
if (pprev)
block.hashPrevBlock = pprev->GetBlockHash();
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
return block;
}
uint256 GetBlockHash() const
{
return *phashBlock;
}
int64_t GetBlockTime() const
{
return (int64_t)nTime;
}
uint256 GetBlockTrust() const;
bool IsInMainChain() const
{
return (pnext || this == pindexBest);
}
bool CheckIndex() const
{
return true;
}
int64_t GetPastTimeLimit() const
{
return GetMedianTimePast();
}
enum { nMedianTimeSpan=11 };
int64_t GetMedianTimePast() const
{
int64_t pmedian[nMedianTimeSpan];
int64_t* pbegin = &pmedian[nMedianTimeSpan];
int64_t* pend = &pmedian[nMedianTimeSpan];
const CBlockIndex* pindex = this;
for (int i = 0; i < nMedianTimeSpan && pindex; i++, pindex = pindex->pprev)
*(--pbegin) = pindex->GetBlockTime();
std::sort(pbegin, pend);
return pbegin[(pend - pbegin)/2];
}
/**
* Returns true if there are nRequired or more blocks of minVersion or above
* in the last nToCheck blocks, starting at pstart and going backwards.
*/
static bool IsSuperMajority(int minVersion, const CBlockIndex* pstart,
unsigned int nRequired, unsigned int nToCheck);
bool IsProofOfWork() const
{
return !(nFlags & BLOCK_PROOF_OF_STAKE);
}
bool IsProofOfStake() const
{
return (nFlags & BLOCK_PROOF_OF_STAKE);
}
void SetProofOfStake()
{
nFlags |= BLOCK_PROOF_OF_STAKE;
}
unsigned int GetStakeEntropyBit() const
{
return ((nFlags & BLOCK_STAKE_ENTROPY) >> 1);
}
bool SetStakeEntropyBit(unsigned int nEntropyBit)
{
if (nEntropyBit > 1)
return false;
nFlags |= (nEntropyBit? BLOCK_STAKE_ENTROPY : 0);
return true;
}
bool GeneratedStakeModifier() const
{
return (nFlags & BLOCK_STAKE_MODIFIER);
}
void SetStakeModifier(uint64_t nModifier, bool fGeneratedStakeModifier)
{
nStakeModifier = nModifier;
if (fGeneratedStakeModifier)
nFlags |= BLOCK_STAKE_MODIFIER;
}
std::string ToString() const
{
return strprintf("CBlockIndex(nprev=%p, pnext=%p, nFile=%u, nBlockPos=%-6d nHeight=%d, nMint=%s, nMoneySupply=%s, nFlags=(%s)(%d)(%s), nStakeModifier=%016"PRIx64", nStakeModifierChecksum=%08x, hashProof=%s, prevoutStake=(%s), nStakeTime=%d merkle=%s, hashBlock=%s)",
pprev, pnext, nFile, nBlockPos, nHeight,
FormatMoney(nMint).c_str(), FormatMoney(nMoneySupply).c_str(),
GeneratedStakeModifier() ? "MOD" : "-", GetStakeEntropyBit(), IsProofOfStake()? "PoS" : "PoW",
nStakeModifier, nStakeModifierChecksum,
hashProof.ToString().c_str(),
prevoutStake.ToString().c_str(), nStakeTime,
hashMerkleRoot.ToString().c_str(),
GetBlockHash().ToString().c_str());
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** Used to marshal pointers into hashes for db storage. */
class CDiskBlockIndex : public CBlockIndex
{
private:
uint256 blockHash;
public:
uint256 hashPrev;
uint256 hashNext;
CDiskBlockIndex()
{
hashPrev = 0;
hashNext = 0;
blockHash = 0;
}
explicit CDiskBlockIndex(CBlockIndex* pindex) : CBlockIndex(*pindex)
{
hashPrev = (pprev ? pprev->GetBlockHash() : 0);
hashNext = (pnext ? pnext->GetBlockHash() : 0);
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(hashNext);
READWRITE(nFile);
READWRITE(nBlockPos);
READWRITE(nHeight);
READWRITE(nMint);
READWRITE(nMoneySupply);
READWRITE(nFlags);
READWRITE(nStakeModifier);
if (IsProofOfStake())
{
READWRITE(prevoutStake);
READWRITE(nStakeTime);
}
else if (fRead)
{
const_cast<CDiskBlockIndex*>(this)->prevoutStake.SetNull();
const_cast<CDiskBlockIndex*>(this)->nStakeTime = 0;
}
READWRITE(hashProof);
// block header
READWRITE(this->nVersion);
READWRITE(hashPrev);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
READWRITE(blockHash);
)
uint256 GetBlockHash() const
{
if (fUseFastIndex && (nTime < GetAdjustedTime() - 24 * 60 * 60) && blockHash != 0)
return blockHash;
CBlock block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrev;
block.hashMerkleRoot = hashMerkleRoot;
block.nTime = nTime;
block.nBits = nBits;
block.nNonce = nNonce;
const_cast<CDiskBlockIndex*>(this)->blockHash = block.GetHash();
return blockHash;
}
std::string ToString() const
{
std::string str = "CDiskBlockIndex(";
str += CBlockIndex::ToString();
str += strprintf("\n hashBlock=%s, hashPrev=%s, hashNext=%s)",
GetBlockHash().ToString().c_str(),
hashPrev.ToString().c_str(),
hashNext.ToString().c_str());
return str;
}
void print() const
{
printf("%s\n", ToString().c_str());
}
};
/** Describes a place in the block chain to another node such that if the
* other node doesn't have the same branch, it can find a recent common trunk.
* The further back it is, the further before the fork it may be.
*/
class CBlockLocator
{
protected:
std::vector<uint256> vHave;
public:
CBlockLocator()
{
}
explicit CBlockLocator(const CBlockIndex* pindex)
{
Set(pindex);
}
explicit CBlockLocator(uint256 hashBlock)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi != mapBlockIndex.end())
Set((*mi).second);
}
CBlockLocator(const std::vector<uint256>& vHaveIn)
{
vHave = vHaveIn;
}
IMPLEMENT_SERIALIZE
(
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vHave);
)
void SetNull()
{
vHave.clear();
}
bool IsNull()
{
return vHave.empty();
}
void Set(const CBlockIndex* pindex)
{
vHave.clear();
int nStep = 1;
while (pindex)
{
vHave.push_back(pindex->GetBlockHash());
// Exponentially larger steps back
for (int i = 0; pindex && i < nStep; i++)
pindex = pindex->pprev;
if (vHave.size() > 10)
nStep *= 2;
}
vHave.push_back((!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet));
}
int GetDistanceBack()
{
// Retrace how far back it was in the sender's branch
int nDistance = 0;
int nStep = 1;
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return nDistance;
}
nDistance += nStep;
if (nDistance > 10)
nStep *= 2;
}
return nDistance;
}
CBlockIndex* GetBlockIndex()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return pindex;
}
}
return pindexGenesisBlock;
}
uint256 GetBlockHash()
{
// Find the first block the caller has in the main chain
BOOST_FOREACH(const uint256& hash, vHave)
{
std::map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hash);
if (mi != mapBlockIndex.end())
{
CBlockIndex* pindex = (*mi).second;
if (pindex->IsInMainChain())
return hash;
}
}
return (!fTestNet ? hashGenesisBlock : hashGenesisBlockTestNet);
}
int GetHeight()
{
CBlockIndex* pindex = GetBlockIndex();
if (!pindex)
return 0;
return pindex->nHeight;
}
};
class CTxMemPool
{
public:
mutable CCriticalSection cs;
std::map<uint256, CTransaction> mapTx;
std::map<COutPoint, CInPoint> mapNextTx;
bool addUnchecked(const uint256& hash, CTransaction &tx);
bool remove(const CTransaction &tx, bool fRecursive = false);
bool removeConflicts(const CTransaction &tx);
void clear();
void queryHashes(std::vector<uint256>& vtxid);
unsigned long size() const
{
LOCK(cs);
return mapTx.size();
}
bool exists(uint256 hash) const
{
LOCK(cs);
return (mapTx.count(hash) != 0);
}
bool lookup(uint256 hash, CTransaction& result) const
{
LOCK(cs);
std::map<uint256, CTransaction>::const_iterator i = mapTx.find(hash);
if (i == mapTx.end()) return false;
result = i->second;
return true;
}
};
extern CTxMemPool mempool;
#endif
| [
"grumpfork@gmail.com"
] | grumpfork@gmail.com |
568611beb058d5819933259511de0915b94984f6 | f86d2eb4d91ef1fd946a57f66918144f9a4634e7 | /TheTreeInt/src/SegmentTree.h | ac62c7dc4a4ea9efb55d68fda964a6430155a8fb | [] | no_license | vijaykotnoor/TheTreeInt | 714932d924bdcbed0749dd45e58b10fa37223175 | 460eacda2feed01d23ee6d18b2c86ac25ee3faa2 | refs/heads/master | 2020-04-08T06:12:47.499972 | 2018-12-03T15:13:03 | 2018-12-03T15:13:03 | 159,089,160 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 571 | h | /*
* segmentTree.h
*
* Created on: 26-Nov-2018
* Author: vijay
*/
#ifndef SEGMENTTREE_H_
#define SEGMENTTREE_H_
#include <vector>
class SegmentTree {
public:
SegmentTree(int size);
virtual ~SegmentTree();
void buildAddition(std::vector<int>& inputArray);
void buildMinimum(std::vector<int>& inputArray);
void updateAdditionTree(int idx, int val);
void updateMinimumTree(int idx, int val);
void printTree();
int queryAddition(int l, int r);
int queryMinimum(int l, int r);
private:
int size_;
std::vector<int> tree_;
};
#endif /* SEGMENTTREE_H_ */
| [
"vijay@192.168.0.17"
] | vijay@192.168.0.17 |
1f30a7379596d653547a84e42ff2c650e269ce40 | 9a45c7750372697364481b441a12c7751d0dcb0d | /mySqrt_biSearch.cpp | 265a71933575345d042d21bfdd01822a9dae4056 | [] | no_license | ginobilinie/codeBook | 5879c4b714ab0f618d43e86d79599bf0cbf42ef5 | 6c16e0aeab16cca9a4c75cf91880b27bf37f5e1d | refs/heads/master | 2021-01-12T07:14:26.705431 | 2019-04-05T03:18:01 | 2019-04-05T03:18:01 | 76,921,542 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 517 | cpp | class Solution {
public:
#define eps 1e-1
int mySqrt(int x) {
if (x==0||x==1)
return x;
int l=0, r=x, mid, res;
while(l<=r)
{
mid = (l+r)/2;
if (mid==x/mid)
{
res = mid;
break;
}
else if (mid<x/mid)//right side
{
l = mid+1;
}
else
r = mid -1;
}
res = (l+r)/2;
return res;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
5e53d207bcaaaeeb7d47466eafb935d797d18e84 | 1942a0d16bd48962e72aa21fad8d034fa9521a6c | /aws-cpp-sdk-apigateway/include/aws/apigateway/model/DeleteBasePathMappingRequest.h | efd44db5e234a12bfd3da4aaaf643fcb1a3567ff | [
"Apache-2.0",
"JSON",
"MIT"
] | permissive | yecol/aws-sdk-cpp | 1aff09a21cfe618e272c2c06d358cfa0fb07cecf | 0b1ea31e593d23b5db49ee39d0a11e5b98ab991e | refs/heads/master | 2021-01-20T02:53:53.557861 | 2018-02-11T11:14:58 | 2018-02-11T11:14:58 | 83,822,910 | 0 | 1 | null | 2017-03-03T17:17:00 | 2017-03-03T17:17:00 | null | UTF-8 | C++ | false | false | 4,289 | h | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/apigateway/APIGateway_EXPORTS.h>
#include <aws/apigateway/APIGatewayRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace APIGateway
{
namespace Model
{
/**
* <p>A request to delete the <a>BasePathMapping</a> resource.</p><p><h3>See
* Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/apigateway-2015-07-09/DeleteBasePathMappingRequest">AWS
* API Reference</a></p>
*/
class AWS_APIGATEWAY_API DeleteBasePathMappingRequest : public APIGatewayRequest
{
public:
DeleteBasePathMappingRequest();
Aws::String SerializePayload() const override;
/**
* <p>The domain name of the <a>BasePathMapping</a> resource to delete.</p>
*/
inline const Aws::String& GetDomainName() const{ return m_domainName; }
/**
* <p>The domain name of the <a>BasePathMapping</a> resource to delete.</p>
*/
inline void SetDomainName(const Aws::String& value) { m_domainNameHasBeenSet = true; m_domainName = value; }
/**
* <p>The domain name of the <a>BasePathMapping</a> resource to delete.</p>
*/
inline void SetDomainName(Aws::String&& value) { m_domainNameHasBeenSet = true; m_domainName = value; }
/**
* <p>The domain name of the <a>BasePathMapping</a> resource to delete.</p>
*/
inline void SetDomainName(const char* value) { m_domainNameHasBeenSet = true; m_domainName.assign(value); }
/**
* <p>The domain name of the <a>BasePathMapping</a> resource to delete.</p>
*/
inline DeleteBasePathMappingRequest& WithDomainName(const Aws::String& value) { SetDomainName(value); return *this;}
/**
* <p>The domain name of the <a>BasePathMapping</a> resource to delete.</p>
*/
inline DeleteBasePathMappingRequest& WithDomainName(Aws::String&& value) { SetDomainName(value); return *this;}
/**
* <p>The domain name of the <a>BasePathMapping</a> resource to delete.</p>
*/
inline DeleteBasePathMappingRequest& WithDomainName(const char* value) { SetDomainName(value); return *this;}
/**
* <p>The base path name of the <a>BasePathMapping</a> resource to delete.</p>
*/
inline const Aws::String& GetBasePath() const{ return m_basePath; }
/**
* <p>The base path name of the <a>BasePathMapping</a> resource to delete.</p>
*/
inline void SetBasePath(const Aws::String& value) { m_basePathHasBeenSet = true; m_basePath = value; }
/**
* <p>The base path name of the <a>BasePathMapping</a> resource to delete.</p>
*/
inline void SetBasePath(Aws::String&& value) { m_basePathHasBeenSet = true; m_basePath = value; }
/**
* <p>The base path name of the <a>BasePathMapping</a> resource to delete.</p>
*/
inline void SetBasePath(const char* value) { m_basePathHasBeenSet = true; m_basePath.assign(value); }
/**
* <p>The base path name of the <a>BasePathMapping</a> resource to delete.</p>
*/
inline DeleteBasePathMappingRequest& WithBasePath(const Aws::String& value) { SetBasePath(value); return *this;}
/**
* <p>The base path name of the <a>BasePathMapping</a> resource to delete.</p>
*/
inline DeleteBasePathMappingRequest& WithBasePath(Aws::String&& value) { SetBasePath(value); return *this;}
/**
* <p>The base path name of the <a>BasePathMapping</a> resource to delete.</p>
*/
inline DeleteBasePathMappingRequest& WithBasePath(const char* value) { SetBasePath(value); return *this;}
private:
Aws::String m_domainName;
bool m_domainNameHasBeenSet;
Aws::String m_basePath;
bool m_basePathHasBeenSet;
};
} // namespace Model
} // namespace APIGateway
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
4a1602f35603faf8c4c2caed11103179bc91c4e1 | 9626c3ddf9d799624107ce7bd19beaf879a5df13 | /src/ide/gfxeditor.h | 329d9f71eab26708629ffd515a5157a12ec0bfe4 | [
"MIT"
] | permissive | gbozelli/lowertriad | 5ce15c34aa21cdf0ee977921d2521fb31af84f92 | 550837df5a7d580821da8fe8e8d1715805792e8a | refs/heads/master | 2022-03-15T22:25:35.571009 | 2016-07-21T04:24:01 | 2016-07-21T04:24:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,878 | h | /*
* Copyright (c) 2016 tildearrow
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
*The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "includes.h"
#include "font.h"
class gfxeditor {
std::vector<unsigned char*>* data;
SDL_Texture* datadraw;
int width;
int height;
int curtool;
bool fgorbg;
SDL_Color bg, fg;
SDL_Point temppoint;
SDL_Rect temprect;
SDL_Color color[16];
SDL_Renderer* r;
int* mX;
int* mY;
unsigned int* mB;
unsigned int* mBold;
font* gf;
void drawcolorpicker();
public:
int offX, offY, w, h;
void draw();
void mouse();
void setfont(font* fontset);
void setrenderer(SDL_Renderer* renderer);
void setdata(std::vector<unsigned char*>* thedata, int thewidth, int theheight);
void setmouse(int* x, int* y, unsigned int* b, unsigned int* bold);
void setcolor(int colindex, SDL_Color colcol);
gfxeditor();
}; | [
"tildearrow@users.noreply.github.com"
] | tildearrow@users.noreply.github.com |
5e4437952fc78e5dd45eee7dca8d07d001370d8e | 24c90f7abb75bfafcad15ac5a6c7e053c96f095a | /Cube/Cube_Struct.h | ee7c9f08b88d47ffa784494c2237c6af9af10640 | [
"MIT"
] | permissive | MikeAndroulakis/LSH_CUBE_CLUSTERING | f57f8a20e2d19ad9105e05d6562e3df5a9b95014 | fa2c3d83fcc324ec7a5c4705a193cb2428d6af8a | refs/heads/main | 2023-03-28T12:31:53.639945 | 2021-04-01T22:37:24 | 2021-04-01T22:37:24 | 353,838,331 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 292 | h | #ifndef CUBE_STRUCT_H
#define CUBE_STRUCT_H
#include <vector>
using namespace std;
class Corner{
int Num_of_Corner;
vector <int> pictures;
public:
Corner(int Num_of_Corner);
void Display();
void InsertItem(int num_of_picture);
void Loadhash(vector <int>* pictures);
};
#endif
| [
"noreply@github.com"
] | noreply@github.com |
0f589e199dd1c20b20ed0964356f023a32f0e0c4 | 5b435cc3e896974ee23acaabf87395e18d9814a3 | /linux-code/ch9/use_select.cpp | 185a657b2eeea1f4c30f35695e71e8d0b390a553 | [] | no_license | wuduozhi/unix-coding | 7edfcdbd8d25751e0653b026dffb6d4ff3955b81 | 522332ee26a8e08580354496f46716dbb8f4b0f8 | refs/heads/master | 2020-05-18T17:01:34.584073 | 2019-07-25T08:45:03 | 2019-07-25T08:45:03 | 184,541,155 | 28 | 11 | null | null | null | null | UTF-8 | C++ | false | false | 2,516 | cpp | #include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>
int main( int argc, char* argv[] )
{
if( argc <= 2 )
{
printf( "usage: %s ip_address port_number\n", basename( argv[0] ) );
return 1;
}
const char* ip = argv[1];
int port = atoi( argv[2] );
printf( "ip is %s and port is %d\n", ip, port );
int ret = 0;
struct sockaddr_in address;
bzero( &address, sizeof( address ) );
address.sin_family = AF_INET;
inet_pton( AF_INET, ip, &address.sin_addr );
address.sin_port = htons( port );
int listenfd = socket( PF_INET, SOCK_STREAM, 0 );
assert( listenfd >= 0 );
ret = bind( listenfd, ( struct sockaddr* )&address, sizeof( address ) );
assert( ret != -1 );
ret = listen( listenfd, 5 );
assert( ret != -1 );
struct sockaddr_in client_address;
socklen_t client_addrlength = sizeof( client_address );
int connfd = accept( listenfd, ( struct sockaddr* )&client_address, &client_addrlength );
if ( connfd < 0 )
{
printf( "errno is: %d\n", errno );
close( listenfd );
}
char remote_addr[INET_ADDRSTRLEN];
printf( "connected with ip: %s and port: %d\n", inet_ntop( AF_INET, &client_address.sin_addr, remote_addr, INET_ADDRSTRLEN ), ntohs( client_address.sin_port ) );
char buf[1024];
fd_set read_fds;
fd_set exception_fds;
FD_ZERO( &read_fds );
FD_ZERO( &exception_fds );
int nReuseAddr = 1;
setsockopt( connfd, SOL_SOCKET, SO_OOBINLINE, &nReuseAddr, sizeof( nReuseAddr ) );
while( 1 )
{
memset( buf, '\0', sizeof( buf ) );
FD_SET( connfd, &read_fds );
FD_SET( connfd, &exception_fds );
ret = select( connfd + 1, &read_fds, NULL, &exception_fds, NULL );
printf( "select one\n" );
if ( ret < 0 )
{
printf( "selection failure\n" );
break;
}
if ( FD_ISSET( connfd, &read_fds ) )
{
ret = recv( connfd, buf, sizeof( buf )-1, 0 );
if( ret <= 0 )
{
break;
}
printf( "get %d bytes of normal data: %s\n", ret, buf );
}
else if( FD_ISSET( connfd, &exception_fds ) )
{
ret = recv( connfd, buf, sizeof( buf )-1, MSG_OOB );
if( ret <= 0 )
{
break;
}
printf( "get %d bytes of oob data: %s\n", ret, buf );
}
}
close( connfd );
close( listenfd );
return 0;
}
| [
"1220555415@qq.com"
] | 1220555415@qq.com |
1e6a445f775a6779cbc1d3040164d89e07cebb0b | 3179943d68996d3ca2d81961be0ac207300b7e4a | /ds-zju/e07-02-SaveBondHard.cpp | 41db3e758c097ab0b9c0a0f7997cbb67cd5b1265 | [] | no_license | xucaimao/netlesson | 8425a925fa671fb9fd372610c19b499b0d8a6fc2 | 088004a9b758387ae6860e2a44b587b54dbbd525 | refs/heads/master | 2021-06-07T06:24:35.276948 | 2020-05-30T07:04:02 | 2020-05-30T07:04:02 | 110,668,572 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,750 | cpp | /*中国大学MOOC-陈越、何钦铭-数据结构-2017秋
* 07-图5 Saving James Bond - Hard Version (30 分)
* wirte by xucaimao,2018-10-18
* 在距离判断的时候,采用直接判断平方的方式,提供运算速度与精度
* 注意题目中的这一句
* If there are many shortest paths, just output the one with the minimum first jump, which is guaranteed to be unique.
* */
#include <cstdio>
#include <cmath>
#include <cstring>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;
const int diameterOfIsland=15;
const int halfWidthOfLake=50;
const int maxN=110;
int NumOfCrocdile,DistOfJump;
struct Pos{
int x,y;
};
Pos G[maxN];
int first[maxN]; //用于储存第一跳的鳄鱼在G[]中的下标
int fN; //能满足第一跳的鳄鱼的数量
int preVertex[maxN],minPreVertex[maxN]; //某一点的前驱点
int dist[maxN],minDist[maxN];
//判断能否从小岛上首先调到的鳄鱼的位置
bool firstJump(Pos p){
double r=diameterOfIsland/2.0;
return p.x*p.x + p.y*p.y <= (DistOfJump+r)*(DistOfJump+r);
}
bool comp(int p1,int p2){
int x1=G[p1].x;
int y1=G[p1].y;
int x2=G[p2].x;
int y2=G[p2].y;
return (x1*x1+y1*y1)<(x2*x2+y2*y2);
}
//判断能否直接跳到岸边
bool jumpToBank(Pos p){
int x,y;
if(p.x<0) x=p.x*(-1);
else x=p.x;
if(p.y<0) y=p.y*(-1);
else y=p.y;
return ( halfWidthOfLake-x <= DistOfJump || halfWidthOfLake-y <= DistOfJump); //判断垂直距离
}
//判断能否从一个鳄鱼跳到另外一个鳄鱼
bool jumpToCrocdile(Pos p1,Pos p2){
int dx=(p2.x-p1.x);
int dy=p2.y-p1.y;
return (dx*dx+dy*dy) <= DistOfJump*DistOfJump;
}
//从出岛后的第一个点u开始遍历
int bfs(int u){
memset(dist,-1, sizeof(dist));
memset(preVertex,-1, sizeof(preVertex));
queue<int> q;
int lastPoint=-1;
dist[0]=0;
dist[u]=1; //从岛跳到这个点,已经用了一步
preVertex[u]=0;
q.push(u);
while(!q.empty()){
int v=q.front();
q.pop();
if( jumpToBank(G[v]) ){ //能从这一点跳到岸上,则返回该点的序号
lastPoint=v;
break;
}
//对应v的每一个邻接点
for(int w=1; w<=NumOfCrocdile;w++){
if(dist[w]==-1 && w!=v){
if( jumpToCrocdile(G[v],G[w]) ){ //能从一个鳄鱼v跳到另外一个鳄鱼w
q.push(w);
dist[w]=dist[v]+1;
preVertex[w]=v;
}
}
}
}
return lastPoint;
}
int main(){
freopen("F:\\xcmprogram\\netlesson\\ds-zju\\in.txt","r",stdin);
scanf("%d %d",&NumOfCrocdile,&DistOfJump);
fN=0;
//读入鳄鱼位置数据,并找出能完成第一跳的鳄鱼位置,并记录其位置(在G中的下标)
//编号0代表小岛
double r=diameterOfIsland/2.0;
for(int i=1;i<=NumOfCrocdile;){
scanf("%d %d",&G[i].x,&G[i].y);
if(firstJump(G[i]))
first[fN++]=i;
i++;
}
//对可以完成的第一跳进行排序,开始时题目没看清楚
sort(first,first+fN,comp);
int lastPoint=-1;
int minStep=maxN;
if(DistOfJump>=42.5){ //直接从岛跳到岸上
lastPoint=0;
dist[0]=0;
minStep=1;
}
else{ //从第一跳的鳄鱼开始遍历
int Case=0;
for(int i=0;i<fN;i++){
int curLastPoint=bfs(first[i]);
// if(curLastPoint>=0){
// printf("Case %d ,the step is %d ; Last Point is: %d[%d,%d] \n",
// ++Case,dist[curLastPoint]+1,curLastPoint,G[curLastPoint].x,G[curLastPoint].y);
// }
//找到一条路径,同时该路径必以前的短,记录该路径及先关数据
//也就是说,如果找到两条长度一样的路径,也是输出第一条找到的
//这里找到的是最后一个点,通过该点可以跳到岸上,所以记录的步数应该加1
if(curLastPoint>=0 && dist[curLastPoint]+1<minStep){
minStep=dist[curLastPoint]+1;
lastPoint=curLastPoint;
memcpy(minDist,dist,sizeof(dist));
memcpy(minPreVertex,preVertex,sizeof(preVertex));
}
}
}
if(lastPoint>=0){
//打印路径
printf("%d\n",minStep);
stack<int> s;
//刚开始这里开始写成 i=preVertex[lastPoint]造成死循环
for(int i=lastPoint;i>0;i=minPreVertex[i])
s.push(i);
while(!s.empty()){
int p=s.top();
s.pop();
printf("%d %d\n",G[p].x,G[p].y);
}
}
else
printf("0\n");
return 0;
} | [
"xcmgj@163.com"
] | xcmgj@163.com |
30b5fb01fff6bfcd969b203c4b0e1ecf822f3099 | 20572294594cf352a05a2adf35d1a1d6f2d86a7c | /clients/gtest/set_get_atomics_mode_gtest.cpp | 281571211cf5bbd9ff649b761fa96fde9d1e3f25 | [
"MIT"
] | permissive | pruthvistony/rocBLAS | e38e26e7e839d740d9a68f1777157bf46e6c51b7 | 9463526235e38f505caeaf29cf41bac22c1ab238 | refs/heads/develop | 2021-07-25T22:51:33.022138 | 2020-09-15T17:34:32 | 2020-09-15T17:34:32 | 244,205,402 | 0 | 0 | MIT | 2020-09-15T17:34:33 | 2020-03-01T18:52:49 | null | UTF-8 | C++ | false | false | 2,379 | cpp | /* ************************************************************************
* Copyright 2020 Advanced Micro Devices, Inc.
* ************************************************************************ */
#include "rocblas.hpp"
#include "rocblas_data.hpp"
#include "rocblas_datatype2string.hpp"
#include "rocblas_test.hpp"
#include "utility.hpp"
#include <string>
namespace
{
template <typename...>
struct testing_set_get_atomics_mode : rocblas_test_valid
{
void operator()(const Arguments&)
{
rocblas_atomics_mode mode = rocblas_atomics_mode(-1);
rocblas_handle handle;
CHECK_ROCBLAS_ERROR(rocblas_create_handle(&handle));
// Make sure the default atomics_mode is rocblas_atomics_allowed
CHECK_ROCBLAS_ERROR(rocblas_get_atomics_mode(handle, &mode));
EXPECT_EQ(rocblas_atomics_allowed, mode);
// Make sure set()/get() functions work
CHECK_ROCBLAS_ERROR(rocblas_set_atomics_mode(handle, rocblas_atomics_not_allowed));
CHECK_ROCBLAS_ERROR(rocblas_get_atomics_mode(handle, &mode));
EXPECT_EQ(rocblas_atomics_not_allowed, mode);
CHECK_ROCBLAS_ERROR(rocblas_set_atomics_mode(handle, rocblas_atomics_allowed));
CHECK_ROCBLAS_ERROR(rocblas_get_atomics_mode(handle, &mode));
EXPECT_EQ(rocblas_atomics_allowed, mode);
CHECK_ROCBLAS_ERROR(rocblas_destroy_handle(handle));
}
};
struct set_get_atomics_mode : RocBLAS_Test<set_get_atomics_mode, testing_set_get_atomics_mode>
{
// Filter for which types apply to this suite
static bool type_filter(const Arguments&)
{
return true;
}
// Filter for which functions apply to this suite
static bool function_filter(const Arguments& arg)
{
return !strcmp(arg.function, "set_get_atomics_mode");
}
// Google Test name suffix based on parameters
static std::string name_suffix(const Arguments& arg)
{
return RocBLAS_TestName<set_get_atomics_mode>(arg.name);
}
};
TEST_P(set_get_atomics_mode, auxilliary)
{
CATCH_SIGNALS_AND_EXCEPTIONS_AS_FAILURES(testing_set_get_atomics_mode<>{}(GetParam()));
}
INSTANTIATE_TEST_CATEGORIES(set_get_atomics_mode)
} // namespace
| [
"noreply@github.com"
] | noreply@github.com |
0860e4d7fe62709061f19bb12817b37ee3a8e7b0 | e5872448c5ddef60ac2ff961728b338fd819531f | /Sandbox/SimpleGame/Random.cpp | 45b900e30ff7db4e3d42f257fa83da59e88af11d | [
"Apache-2.0"
] | permissive | rocketman123456/RocketGE | 8d8882a8f2d728e78975215826106be9830f170a | dd8b6de286ce5d2abebc55454fbdf67968558535 | refs/heads/main | 2023-02-14T14:40:12.385393 | 2020-12-21T12:46:13 | 2020-12-21T12:46:13 | 312,870,148 | 2 | 0 | Apache-2.0 | 2020-12-21T12:46:14 | 2020-11-14T17:48:30 | C++ | UTF-8 | C++ | false | false | 139 | cpp | #include "Random.h"
std::mt19937 Random::s_RandomEngine;
std::uniform_int_distribution<std::mt19937::result_type> Random::s_Distribution;
| [
"759094438@qq.com"
] | 759094438@qq.com |
15a6e05e5c9881b920141eda5f58dad0fcdcfed6 | 1f40c78234c563fd6a1b4bd63a7e38d544d6032f | /sources/monsters/shocker.cpp | 615afe5b0b80772295bf2f6669d6b633fdcf910e | [
"MIT"
] | permissive | ucpu/degrid | d77e8cadddd9992730b838c4d3b7e01022232cbf | a05042906e28d4ba802fb12c513c0399320f04fc | refs/heads/master | 2023-05-28T06:27:46.131027 | 2023-05-23T10:23:21 | 2023-05-23T10:23:21 | 125,419,583 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,244 | cpp | #include <cage-core/entitiesVisitor.h>
#include "monsters.h"
namespace
{
struct ShockerComponent
{
Real radius;
Real speedFactor;
};
const auto engineInitListener = controlThread().initialize.listen([]() {
engineEntities()->defineComponent(ShockerComponent());
});
void lightning(const Vec3 &a, const Vec3 &b, const Vec3 &color)
{
const Real d = distance(a, b);
const Vec3 v = normalize(b - a);
Vec3 c = (a + b) * 0.5;
if (d > 25)
{
const Vec3 side = normalize(cross(v, Vec3(0, 1, 0)));
c += side * (d * randomRange(-0.2, 0.2));
lightning(a, c, color);
lightning(c, b, color);
return;
}
Entity *e = engineEntities()->createUnique();
TransformComponent &t = e->value<TransformComponent>();
t.position = c;
t.orientation = Quat(v, Vec3(0, 1, 0), true);
RenderComponent &r = e->value<RenderComponent>();
r.object = HashString("degrid/monster/shocker/lightning.object");
r.color = color;
e->value<TextureAnimationComponent>().offset = randomChance();
e->value<TimeoutComponent>().ttl = 3;
e->add(entitiesPhysicsEvenWhenPaused);
LightComponent &light = e->value<LightComponent>();
light.color = colorVariation(color);
light.intensity = 10;
light.lightType = LightTypeEnum::Point;
light.attenuation = Vec3(0, 0, 0.01);
}
const auto engineUpdateListener = controlThread().update.listen([]() {
if (game.paused)
{
entitiesVisitor([&](Entity *e, const ShockerComponent &) {
e->remove<SoundComponent>();
}, engineEntities(), false);
return;
}
const TransformComponent &playerTransform = game.playerEntity->value<TransformComponent>();
VelocityComponent &playerVelocity = game.playerEntity->value<VelocityComponent>();
entitiesVisitor([&](Entity *e, TransformComponent &tr, const ShockerComponent &sh) {
const Vec3 v = tr.position - playerTransform.position;
const Real d = length(v);
// stay away from the player
if (d < sh.radius * 0.8 && d > 1e-7)
e->value<VelocityComponent>().velocity += normalize(v) * 0.3;
// lightning
if (d < sh.radius)
{
playerVelocity.velocity *= sh.speedFactor;
if (((statistics.updateIterationIgnorePause + e->name()) % 3) == 0)
lightning(tr.position + randomDirection3() * tr.scale, playerTransform.position + randomDirection3() * playerTransform.scale, e->value<RenderComponent>().color);
if (!e->has<SoundComponent>())
{
SoundComponent &v = e->value<SoundComponent>();
v.name = HashString("degrid/monster/shocker/lightning.flac");
v.startTime = uint64(e->name()) * 10000;
}
}
else
e->remove<SoundComponent>();
}, engineEntities(), false);
});
}
void spawnShocker(const Vec3 &spawnPosition, const Vec3 &color)
{
uint32 special = 0;
Entity *shocker = initializeSimple(spawnPosition, color, 3, HashString("degrid/monster/shocker/shocker.object"), HashString("degrid/monster/shocker/bum-shocker.ogg"), 5, 3 + monsterMutation(special), 0.3, 1, 0.7, 0.05, 0.7, 0, interpolate(Quat(), randomDirectionQuat(), 0.01));
ShockerComponent &sh = shocker->value<ShockerComponent>();
sh.radius = randomRange(70, 80) + 10 * monsterMutation(special);
sh.speedFactor = 3.2 / (monsterMutation(special) + 4);
monsterReflectMutation(shocker, special);
}
| [
"malytomas@ucpu.cz"
] | malytomas@ucpu.cz |
c34ea4e9f3ff733ce2c94836b4db7e14e547fbba | 55d560fe6678a3edc9232ef14de8fafd7b7ece12 | /libs/parameter/test/literate/deduced-parameters0.cpp | 5e76681966b90432c8c1ef3dba75f35289815ba9 | [
"BSL-1.0"
] | permissive | stardog-union/boost | ec3abeeef1b45389228df031bf25b470d3d123c5 | caa4a540db892caa92e5346e0094c63dea51cbfb | refs/heads/stardog/develop | 2021-06-25T02:15:10.697006 | 2020-11-17T19:50:35 | 2020-11-17T19:50:35 | 148,681,713 | 0 | 0 | BSL-1.0 | 2020-11-17T19:50:36 | 2018-09-13T18:38:54 | C++ | UTF-8 | C++ | false | false | 1,355 | cpp |
#include <boost/parameter.hpp>
BOOST_PARAMETER_NAME(name)
BOOST_PARAMETER_NAME(func)
BOOST_PARAMETER_NAME(docstring)
BOOST_PARAMETER_NAME(keywords)
BOOST_PARAMETER_NAME(policies)
struct default_call_policies
{};
struct no_keywords
{};
struct keywords
{};
template <class T>
struct is_keyword_expression
: boost::mpl::false_
{};
template <>
struct is_keyword_expression<keywords>
: boost::mpl::true_
{};
default_call_policies some_policies;
void f()
{}
namespace mpl = boost::mpl;
BOOST_PARAMETER_FUNCTION(
(void), def, tag,
(required (name,(char const*)) (func,*) ) // nondeduced
(deduced
(optional
(docstring, (char const*), "")
(keywords
, *(is_keyword_expression<mpl::_>) // see 5
, no_keywords())
(policies
, *(mpl::not_<
mpl::or_<
boost::is_convertible<mpl::_, char const*>
, is_keyword_expression<mpl::_> // see 5
>
>)
, default_call_policies()
)
)
)
)
{
}
int main()
{
def("f", &f, some_policies, "Documentation for f");
def("f", &f, "Documentation for f", some_policies);
def(
"f", &f
, _policies = some_policies, "Documentation for f");
}
| [
"james.pack@stardog.com"
] | james.pack@stardog.com |
ea9e4db74b96c83a976a1af1d9ed0322f4e3c497 | 4ef69f0044f45be4fbce54f7b7c0319e4c5ec53d | /include/cv/core/cmd/out/zhgeqz.inl | 8a988d9db84a15f4c8e994b2f7058dd0a73f4dec | [] | no_license | 15831944/cstd | c6c3996103953ceda7c06625ee1045127bf79ee8 | 53b7e5ba73cbdc9b5bbc61094a09bf3d5957f373 | refs/heads/master | 2021-09-15T13:44:37.937208 | 2018-06-02T10:14:16 | 2018-06-02T10:14:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 227 | inl | #ifndef __zhgeqz__
#define __zhgeqz__
#define c_b1 c_b1_zhgeqz
#define c_b2 c_b2_zhgeqz
#define c__1 c__1_zhgeqz
#define c__2 c__2_zhgeqz
#include "zhgeqz.c"
#undef c_b1
#undef c_b2
#undef c__1
#undef c__2
#endif // __zhgeqz__
| [
"31720406@qq.com"
] | 31720406@qq.com |
bb2c81505d46acfd759d738b1b2b4ad1d9a56b31 | c3a79a4708a9e99fe22964a6291990b861313b7d | /A_Puzzle_From_the_Future.cpp | 878e2d60e5377ee80cd4bd57afa79c99c3e98f28 | [] | no_license | parthkris13/CC-Solutions | d04ef8f15e5c9e019d2cf8d84ca1649d84b4f51d | d190294bfb44449b803799819ee1f06f5f6c5a17 | refs/heads/main | 2023-04-11T11:04:11.042172 | 2021-04-29T14:15:33 | 2021-04-29T14:15:33 | 323,133,672 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,110 | cpp | #include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
#define int long long int
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
const int N = 3e5 + 7;
int32_t main(){
IOS;
int t;
cin >> t;
while(t--){
int n;
cin >> n;
string s;
cin >> s;
string ans = "1";
int p;
if(s[0] == '1') p = 2;
else p = 1;
for(int i=1; i<n; i++){
if(s[i] == '1' && p == 2){
ans+='0';
p=1;
}
else if(s[i] == '1' && p == 1){
ans+='1';
p=2;
}
else if(s[i] == '1' && p == 0){
ans+='1';
p=2;
}
else if(s[i] == '0' && p == 2){
ans+='1';
p=1;
}
else if(s[i] == '0' && p == 0){
ans+='1';
p=1;
}
else {
ans+='0';
p=0;
}
}
cout << ans << endl;
}
return 0;
} | [
"parthkrishna99@gmail.com"
] | parthkrishna99@gmail.com |
0232dff38c5bdc23155546632652e1b95c8d1694 | 58fc843305fe9f745677d195ca9c0277a24e77f1 | /src/tools/string.cpp | 0e8d79695ee82496eac1661c07f2c6f5e244389f | [
"MIT"
] | permissive | gionellef/occa | 61fc79555d027215ab2f2834bf286bf55e5ad8e5 | d7fa75a9d5e422f3c80a694acdd2097a10056911 | refs/heads/master | 2022-08-16T01:32:36.835014 | 2020-05-22T03:10:25 | 2020-05-22T03:10:25 | 265,815,861 | 0 | 0 | MIT | 2020-05-21T10:08:17 | 2020-05-21T10:08:16 | null | UTF-8 | C++ | false | false | 9,343 | cpp | #include <occa/defines.hpp>
#if (OCCA_OS & (OCCA_LINUX_OS | OCCA_MACOS_OS))
# include <stdio.h>
#else // OCCA_WINDOWS_OS
# include <windows.h>
#endif
#include <occa/tools/env.hpp>
#include <occa/tools/lex.hpp>
#include <occa/tools/string.hpp>
#include <occa/tools/sys.hpp>
namespace occa {
std::string strip(const std::string &str) {
const char *start = str.c_str();
const char *end = start + str.size() - 1;
while ((*start != '\0') &&
lex::isWhitespace(*start)) {
++start;
}
while ((start < end) &&
lex::isWhitespace(*end)) {
--end;
}
++end;
return std::string(start, end - start);
}
std::string escape(const std::string &str,
const char c,
const char escapeChar) {
const int chars = (int) str.size();
const char *cstr = str.c_str();
std::string ret;
for (int i = 0; i < chars; ++i) {
if (cstr[i] != c) {
ret += cstr[i];
} else {
if (i && escapeChar) {
ret += escapeChar;
}
ret += c;
}
}
return ret;
}
std::string unescape(const std::string &str,
const char c,
const char escapeChar) {
std::string ret;
const int chars = (int) str.size();
const char *cstr = str.c_str();
for (int i = 0; i < chars; ++i) {
if (escapeChar &&
(cstr[i] == escapeChar) &&
(cstr[i + 1] == c)) {
continue;
}
ret += cstr[i];
}
return ret;
}
strVector split(const std::string &s,
const char delimeter,
const char escapeChar) {
strVector sv;
const char *c = s.c_str();
while (*c != '\0') {
const char *cStart = c;
lex::skipTo(c, delimeter, escapeChar);
sv.push_back(std::string(cStart, c - cStart));
if (*c != '\0') {
++c;
}
}
return sv;
}
std::string uppercase(const char *c,
const int chars) {
std::string ret(c, chars);
for (int i = 0; i < chars; ++i) {
ret[i] = uppercase(ret[i]);
}
return ret;
}
std::string lowercase(const char *c,
const int chars) {
std::string ret(chars, '\0');
for (int i = 0; i < chars; ++i) {
ret[i] = lowercase(c[i]);
}
return ret;
}
template <>
std::string toString<std::string>(const std::string &t) {
return t;
}
template <>
std::string toString<bool>(const bool &t) {
return t ? "true" : "false";
}
template <>
std::string toString<float>(const float &t) {
std::stringstream ss;
ss << std::scientific << std::setprecision(8) << t << 'f';
return ss.str();
}
template <>
std::string toString<double>(const double &t) {
std::stringstream ss;
ss << std::scientific << std::setprecision(16) << t;
return ss.str();
}
template <>
bool fromString(const std::string &s) {
if (s == "0") {
return false;
}
const std::string sUp = uppercase(s);
return !((sUp == "N") ||
(sUp == "NO") ||
(sUp == "FALSE"));
}
template <>
std::string fromString(const std::string &s) {
return s;
}
udim_t atoi(const char *c) {
udim_t ret = 0;
const char *c0 = c;
bool negative = false;
bool unsigned_ = false;
int longs = 0;
lex::skipWhitespace(c);
if ((*c == '+') || (*c == '-')) {
negative = (*c == '-');
++c;
}
if (c[0] == '0')
return atoiBase2(c0);
while(('0' <= *c) && (*c <= '9')) {
ret *= 10;
ret += *(c++) - '0';
}
while(*c != '\0') {
const char C = uppercase(*c);
if (C == 'L') {
++longs;
} else if (C == 'U') {
unsigned_ = true;
} else {
break;
}
++c;
}
if (negative) {
ret = ((~ret) + 1);
}
if (longs == 0) {
if (!unsigned_) {
ret = ((udim_t) ((int) ret));
} else {
ret = ((udim_t) ((unsigned int) ret));
}
} else if (longs == 1) {
if (!unsigned_) {
ret = ((udim_t) ((long) ret));
} else {
ret = ((udim_t) ((unsigned long) ret));
}
}
// else it's already in udim_t form
return ret;
}
udim_t atoiBase2(const char*c) {
udim_t ret = 0;
#if !OCCA_UNSAFE
const char *c0 = c;
int maxDigitValue = 10;
char maxDigitChar = '9';
#endif
bool negative = false;
int bits = 3;
lex::skipWhitespace(c);
if ((*c == '+') || (*c == '-')) {
negative = (*c == '-');
++c;
}
if (*c == '0') {
++c;
const char C = uppercase(*c);
if (C == 'X') {
bits = 4;
++c;
#if !OCCA_UNSAFE
maxDigitValue = 16;
maxDigitChar = 'F';
#endif
} else if (C == 'B') {
bits = 1;
++c;
#if !OCCA_UNSAFE
maxDigitValue = 2;
maxDigitChar = '1';
#endif
}
}
while(true) {
if (('0' <= *c) && (*c <= '9')) {
const char digitValue = *(c++) - '0';
OCCA_ERROR("Number [" << std::string(c0, c - c0)
<< "...] must contain digits in the [0,"
<< maxDigitChar << "] range",
digitValue < maxDigitValue);
ret <<= bits;
ret += digitValue;
} else {
const char C = uppercase(*c);
if (('A' <= C) && (C <= 'F')) {
const char digitValue = 10 + (C - 'A');
++c;
OCCA_ERROR("Number [" << std::string(c0, c - c0)
<< "...] must contain digits in the [0,"
<< maxDigitChar << "] range",
digitValue < maxDigitValue);
ret <<= bits;
ret += digitValue;
} else {
break;
}
}
}
if (negative) {
ret = ((~ret) + 1);
}
return ret;
}
udim_t atoi(const std::string &str) {
return occa::atoi((const char*) str.c_str());
}
double atof(const char *c) {
return ::atof(c);
}
double atof(const std::string &str) {
return ::atof(str.c_str());
}
double atod(const char *c) {
double ret;
#if (OCCA_OS & (OCCA_LINUX_OS | OCCA_MACOS_OS))
sscanf(c, "%lf", &ret);
#else
sscanf_s(c, "%lf", &ret);
#endif
return ret;
}
double atod(const std::string &str) {
return occa::atod(str.c_str());
}
std::string stringifyBytes(udim_t bytes) {
if (0 < bytes) {
std::stringstream ss;
uint64_t bigBytes = bytes;
if (bigBytes < (((uint64_t) 1) << 10)) {
ss << bigBytes << " bytes";
} else if (bigBytes < (((uint64_t) 1) << 20)) {
ss << (bigBytes >> 10);
stringifyBytesFraction(ss, bigBytes >> 0);
ss << " KB";
} else if (bigBytes < (((uint64_t) 1) << 30)) {
ss << (bigBytes >> 20);
stringifyBytesFraction(ss, bigBytes >> 10);
ss << " MB";
} else if (bigBytes < (((uint64_t) 1) << 40)) {
ss << (bigBytes >> 30);
stringifyBytesFraction(ss, bigBytes >> 20);
ss << " GB";
} else if (bigBytes < (((uint64_t) 1) << 50)) {
ss << (bigBytes >> 40);
stringifyBytesFraction(ss, bigBytes >> 30);
ss << " TB";
} else {
ss << bigBytes << " bytes";
}
return ss.str();
}
return "";
}
void stringifyBytesFraction(std::stringstream &ss,
uint64_t fraction) {
const int part = (int) (100.0 * (fraction % 1024) / 1024.0);
if (part) {
ss << '.' << part;
}
}
//---[ Color Strings ]----------------
namespace color {
const char fgMap[9][7] = {
"\033[39m",
"\033[30m", "\033[31m", "\033[32m", "\033[33m",
"\033[34m", "\033[35m", "\033[36m", "\033[37m"
};
const char bgMap[9][7] = {
"\033[49m",
"\033[40m", "\033[41m", "\033[42m", "\033[43m",
"\033[44m", "\033[45m", "\033[46m", "\033[47m"
};
std::string string(const std::string &s,
color_t fg) {
if (!env::OCCA_COLOR_ENABLED) {
return s;
}
std::string ret = fgMap[fg];
ret += s;
ret += fgMap[normal];
return ret;
}
std::string string(const std::string &s,
color_t fg,
color_t bg) {
if (!env::OCCA_COLOR_ENABLED) {
return s;
}
std::string ret = fgMap[fg];
ret += bgMap[bg];
ret += s;
ret += fgMap[normal];
ret += bgMap[normal];
return ret;
}
}
std::string black(const std::string &s) {
return color::string(s, color::black);
}
std::string red(const std::string &s) {
return color::string(s, color::red);
}
std::string green(const std::string &s) {
return color::string(s, color::green);
}
std::string yellow(const std::string &s) {
return color::string(s, color::yellow);
}
std::string blue(const std::string &s) {
return color::string(s, color::blue);
}
std::string magenta(const std::string &s) {
return color::string(s, color::magenta);
}
std::string cyan(const std::string &s) {
return color::string(s, color::cyan);
}
std::string white(const std::string &s) {
return color::string(s, color::white);
}
//====================================
}
| [
"dmed256@gmail.com"
] | dmed256@gmail.com |
afb2349118f4de03e597bb3e82bc761366249094 | 29eec4f8c2e5356ed3ea9d0748f8fdcce42a008c | /src/CloudDelayCenter.cc | 11edad97a0129fe3ecbb1b42514fe55e6c6ccb97 | [] | no_license | mions1/Fog | 0d021bbc4d26680ed8d89411bf5aa96acf3aab32 | e37d17a6356c31343e23750362f27e9fdcfff081 | refs/heads/master | 2020-05-05T03:28:34.641508 | 2019-08-21T00:26:33 | 2019-08-21T00:26:33 | 179,673,964 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,668 | cc | //
// This file is part of an OMNeT++/OMNEST simulation example.
//
// Copyright (C) 2006-2008 OpenSim Ltd.
//
// This file is distributed WITHOUT ANY WARRANTY. See the file
// `license' for details on this and other legal matters.
//
#include "CloudDelayCenter.h"
#include "FogJob_m.h"
#include "CloudCongestionUpdate_m.h"
#include "FogSource.h"
#define CONGESTIONGATENAME "congestionControl"
namespace fog {
Define_Module(CloudDelayCenter);
void CloudDelayCenter::initialize() {
currentlyStored = 0;
maxDelay=par("maxDelay");
timeout=par("timeout");
//delayedJobsSignal = registerSignal("delayedJobs");
//emit(delayedJobsSignal, 0);
//WATCH(currentlyStored);
congested=false;
congestionMultiplier=1.0;
jobs.clear();
totalJobs=0;
droppedJobsTimeout=0;
}
void CloudDelayCenter::processNewCloudAppJob(cMessage *msg){
EV << "CloudDelayCenter::processNewCloudAppJob()" << endl;
FogJob *job = check_and_cast<FogJob *>(msg);
// if it is not a self-message, send it to ourselves with a delay
currentlyStored++;
totalJobs++;
simtime_t delay = par("delay");
simtime_t now=simTime();
if (maxDelay>0 && delay>maxDelay) {delay=maxDelay;}
delay=delay * congestionMultiplier;
jobs[job->getId()]=job;
scheduleAt(now + delay, job);
/*if (timeout>0){
EV << "Setting up timeout" <<endl;
// create new timeout message (name=TIMEOUTMESSAGENAME)
cMessage *to=new cMessage(TIMEOUTMESSAGENAME);
// FIXME: cannot add a message that is already scheduled
// add job to timeout message
to->addObject(job);
// add timeout message to job
job->addObject(to);
// schedule at now+timeout
scheduleAt(now+timeout, to);
}*/
}
void CloudDelayCenter::processReturningCloudAppJob(cMessage *msg){
EV << "CloudDelayCenter::processReturningCloudAppJob()" << endl;
FogJob *job = check_and_cast<FogJob *>(msg);
job->setDelayCount(job->getDelayCount()+1);
simtime_t d = simTime() - job->getSendingTime();
job->setDelayTime(job->getDelayTime() + d);
// if it was a self message (ie. we have already delayed) so we send it out
currentlyStored--;
jobs.erase(job->getId());
/*// remove timeout from job
cObject * to=job->removeObject(TIMEOUTMESSAGENAME);
if (to != NULL){
// cancel and delete timeout event
cancelAndDelete(check_and_cast<cMessage *>(to));
}*/
// if timeout --> discard job
if (!checkTimeoutExpired(check_and_cast<FogJob *>(job))){
send(job, "out");
}
}
bool CloudDelayCenter::checkTimeoutExpired(FogJob *job, bool autoremove){
if (job==NULL){return false;}
simtime_t now=simTime();
if ((timeout>0) && (now - job->getStartTime()>timeout)){
if (autoremove){
//EV << "Dropping job from checkTimeoutExpired()";
// drop and increase droppedJobTimeout
droppedJobsTimeout++;
delete job;
}
return true;
}
return false;
}
void CloudDelayCenter::processCloudCongestionUpdateMessage(cMessage *msg){
EV << "CloudDelayCenter::processCloudCongestionUpdateMessage()" << endl;
CloudCongestionUpdate *umsg=check_and_cast<CloudCongestionUpdate *>(msg);
double oldCongestionMultiplier=congestionMultiplier;
jobMapIterator it;
congested=umsg->getCongestion();
if (congested){
congestionMultiplier=umsg->getMultiplier();
} else {
congestionMultiplier=1.0;
}
// dispose of congestionUpdate message
delete umsg;
if (currentlyStored >0){
// iterate over waiting jobs and update remaining time
for(it = jobs.begin(); it != jobs.end(); it++) {
// it->first = key
// it->second = value
FogJob *job=check_and_cast<FogJob *>(it->second);
cancelEvent(job);
simtime_t remainingTime=job->getArrivalTime() - simTime();
scheduleAt(simTime()+(remainingTime * congestionMultiplier/oldCongestionMultiplier), job);
}
}
}
void CloudDelayCenter::handleMessage(cMessage *msg) {
if (msg->isSelfMessage()) {
processReturningCloudAppJob(msg);
} else {
if (strcmp(msg->getArrivalGate()->getName(), CONGESTIONGATENAME)==0) {
processCloudCongestionUpdateMessage(msg);
} else {
processNewCloudAppJob(msg);
}
}
}
void CloudDelayCenter::finish()
{
// totalJobs, droppedJobs
recordScalar("totalJobs", totalJobs);
recordScalar("droppedJobsTimout", droppedJobsTimeout);
recordScalar("droppedJobsTotal", droppedJobsTimeout);
}
}; //namespace
| [
"simone.mione1@gmail.com"
] | simone.mione1@gmail.com |
9fab5371dca8e7787069e8cb2eaf7ef362eaf189 | d31d744f62c09cb298022f42bcaf9de03ad9791c | /runtime/backends/cpu/lib/ops/test/example_ops.cc | 90545a30a3f1c9ad5418c8d5517847b85bc02ad9 | [
"Apache-2.0"
] | permissive | yuhuofei/TensorFlow-1 | b2085cb5c061aefe97e2e8f324b01d7d8e3f04a0 | 36eb6994d36674604973a06159e73187087f51c6 | refs/heads/master | 2023-02-22T13:57:28.886086 | 2021-01-26T14:18:18 | 2021-01-26T14:18:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,939 | cc | // Copyright 2020 The TensorFlow Runtime Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//===- examples_ops.cc ----------------------------------------------------===//
//
// This file defines some example op implementations in the "tfrt_test."
// namespace.
//
//===----------------------------------------------------------------------===//
#include "../../kernels/cpu_kernels.h"
#include "llvm/Support/Casting.h"
#include "llvm_derived/Support/raw_ostream.h"
#include "tfrt/core_runtime/op_attrs.h"
#include "tfrt/core_runtime/op_utils.h"
#include "tfrt/cpu/core_runtime/cpu_op_registry.h"
#include "tfrt/cpu/ops/test/cpu_ops_and_kernels.h"
#include "tfrt/host_context/async_value_ref.h"
#include "tfrt/host_context/chain.h"
#include "tfrt/host_context/parallel_for.h"
#include "tfrt/support/error_util.h"
#include "tfrt/tensor/dense_host_tensor_view.h"
#include "tfrt/tensor/scalar_host_tensor.h"
namespace tfrt {
//===----------------------------------------------------------------------===//
// test.odd_collector op
//===----------------------------------------------------------------------===//
// This implements a function "x = test.odd_collector(y)" that takes a 1d input
// and returns a 1d output containing only the odd values of the input.
//
// This is a test op for dynamic output results.
static Expected<DenseHostTensor> OddCollectorOp(
const DenseHostTensor& input, const ExecutionContext& exec_ctx) {
if (input.shape().GetRank() != 1)
return MakeStringError("expected a 1D tensor input");
if (input.dtype().kind() != DType::I32)
return MakeStringError("expected a i32 element type");
// Figure out how big the result tensor will be.
DHTArrayView<int32_t> input_view(&input);
size_t result_size = 0;
for (auto& elt : input_view)
if (elt & 1) ++result_size;
// Allocate the result.
auto result = DenseHostTensor::CreateUninitialized<int32_t>(
TensorShape{result_size}, exec_ctx.host());
if (!result.hasValue()) return MakeStringError("cannot allocate tensor");
// Fill in the result.
MutableDHTArrayView<int32_t> result_view(result.getPointer());
size_t result_elt = 0;
for (auto& elt : input_view)
if (elt & 1) result_view[result_elt++] = elt;
return std::move(result.getValue());
}
//===----------------------------------------------------------------------===//
// test.create_from_scalar op
//===----------------------------------------------------------------------===//
template <typename T>
static AsyncValueRef<HostTensor> DoCreateFromScalar(
const TensorMetadata& dest_md, T value, const ExecutionContext& exec_ctx) {
return MakeAvailableAsyncValueRef<ScalarHostTensor<T>>(exec_ctx.host(),
dest_md, value);
}
// result = test.create_from_scalar(value=V, shape=Shape)
//
static AsyncValueRef<HostTensor> TestCreateFromScalarOp(
const OpAttrsRef& attrs, const TensorMetadata& dest_md,
const ExecutionContext& exec_ctx) {
auto& value = attrs.GetRawAsserting("value");
assert(!value.IsArray() && "shape function failure");
switch (value.type) {
default:
assert(0 && "shape function failure");
return {};
#define OP_ATTR_TYPE(ENUM, CPP_TYPE) \
case OpAttrType::ENUM: \
return DoCreateFromScalar(dest_md, value.GetScalarData<CPP_TYPE>(), \
exec_ctx);
#include "tfrt/core_runtime/op_attr_type.def"
}
}
//===----------------------------------------------------------------------===//
// test.add op
//===----------------------------------------------------------------------===//
namespace {
template <typename T>
AsyncValueRef<HostTensor> TestAddOpImpl(const HostTensor& lhs_ref,
const HostTensor& rhs_ref,
const ExecutionContext& exec_ctx) {
HostContext* host = exec_ctx.host();
auto* lhs = &lhs_ref;
auto* rhs = &rhs_ref;
// We handle Scalar+Scalar, Scalar+Dense, Dense+Dense below. Swap
// Dense+Scalar to simplify the logic since add is commutative.
if (isa<DenseHostTensor>(lhs) && isa<AnyScalarHostTensor>(rhs))
std::swap(lhs, rhs);
// Handle scalar+scalar.
if (auto* srhs = dyn_cast<ScalarHostTensor<T>>(rhs)) {
auto* slhs = cast<ScalarHostTensor<T>>(lhs);
auto result = slhs->GetValue() + srhs->GetValue();
return MakeAvailableAsyncValueRef<ScalarHostTensor<T>>(
host, slhs->metadata(), result);
}
auto dest = DenseHostTensor::CreateUninitialized(lhs->metadata(), host);
if (!dest)
return MakeErrorAsyncValueRef(host, "out of memory allocating result");
MutableDHTArrayView<T> dest_view(dest.getPointer());
// Handle scalar+dense.
DHTArrayView<T> rhs_view(cast<DenseHostTensor>(rhs));
if (auto* slhs = dyn_cast<ScalarHostTensor<T>>(lhs)) {
// Add a scalar to a dense tensor.
auto lhs = slhs->GetValue();
for (size_t i = 0, e = dest_view.NumElements(); i != e; ++i)
dest_view[i] = lhs + rhs_view[i];
} else {
// Add two dense tensors.
DHTArrayView<T> lhs_view(cast<DenseHostTensor>(lhs));
for (size_t i = 0, e = dest_view.NumElements(); i != e; ++i)
dest_view[i] = lhs_view[i] + rhs_view[i];
}
return MakeAvailableAsyncValueRef<DenseHostTensor>(
host, std::move(dest.getValue()));
}
} // namespace
// This implements the test.add op.
static AsyncValueRef<HostTensor> TestAddOp(const HostTensor& lhs,
const HostTensor& rhs,
const ExecutionContext& exec_ctx) {
switch (lhs.dtype().kind()) {
default:
assert(0 && "shape function failure");
return {};
#define DTYPE_TRIVIAL(ENUM) \
case DType::ENUM: \
return TestAddOpImpl<TypeForDTypeKind<DType::ENUM>>(lhs, rhs, exec_ctx);
#include "tfrt/dtype/dtype.def"
}
}
//===----------------------------------------------------------------------===//
// test.add.denseonly op
//===----------------------------------------------------------------------===//
template <typename T>
static void TestAddDenseOnlyImpl(DHTArrayView<T> lhs_view,
DHTArrayView<T> rhs_view,
MutableDHTArrayView<T> dest_view,
size_t begin_idx, size_t end_idx) {
// Add two dense tensors.
for (size_t i = begin_idx; i != end_idx; ++i)
dest_view[i] = lhs_view[i] + rhs_view[i];
}
// This implements the test.add.denseonly op, which is a simple add operation,
// but whose implementation intentionally only supports dense tensors. This is
// used to test type conversion by the CPU device.
static Expected<DenseHostTensor> TestAddDenseOnlyOp(
const DenseHostTensor& lhs, const DenseHostTensor& rhs,
const ExecutionContext& exec_ctx) {
auto dest =
DenseHostTensor::CreateUninitialized(lhs.metadata(), exec_ctx.host());
if (!dest) {
return MakeStringError("out of memory allocating result");
}
auto* dest_ptr = dest.getPointer();
switch (lhs.dtype().kind()) {
default:
assert(0 && "shape function failure");
break;
#define DTYPE_TRIVIAL(ENUM) \
case DType::ENUM: \
TestAddDenseOnlyImpl<TypeForDTypeKind<DType::ENUM>>(&lhs, &rhs, dest_ptr, \
0, lhs.NumElements()); \
break;
#include "tfrt/dtype/dtype.def"
}
return std::move(dest.getValue());
}
// This implements the test.add.denseonly op, which is a simple add operation,
// but whose implementation intentionally only supports dense tensors. This is
// used to test type conversion by the CPU device.
static AsyncValueRef<DenseHostTensor> TestAddDenseOnly2Op(
const DenseHostTensor& lhs, const DenseHostTensor& rhs,
const ExecutionContext& exec_ctx) {
// Allocate the result buffer, and exit if an error occurred.
auto dht = DenseHostTensor::MakeConstructedAsyncValueRef(lhs.metadata(),
exec_ctx.host());
if (!dht) {
return MakeErrorAsyncValueRef(exec_ctx.host(),
"out of memory allocating result");
}
switch (lhs.dtype().kind()) {
default:
assert(0 && "shape function failure");
break;
#define DTYPE_TRIVIAL(ENUM) \
case DType::ENUM: \
TestAddDenseOnlyImpl<TypeForDTypeKind<DType::ENUM>>( \
&lhs, &rhs, &dht.get(), 0, lhs.NumElements()); \
break;
#include "tfrt/dtype/dtype.def"
}
dht.SetStateConcrete();
return dht;
}
// This implements the test.add.denseonly op, which is a simple add operation,
// but whose implementation intentionally only supports dense tensors. This is
// used to test type conversion by the CPU device.
static AsyncValueRef<DenseHostTensor> TestAddDenseOnly3Op(
const DenseHostTensor& lhs, const DenseHostTensor& rhs,
const ExecutionContext& exec_ctx) {
HostContext* host = exec_ctx.host();
// Allocate the result buffer, and exit if an error occurred.
auto dht =
DenseHostTensor::MakeConstructedAsyncValueRef(lhs.metadata(), host);
if (!dht) {
return MakeErrorAsyncValueRef(host, "out of memory allocating result");
}
// Note the captured dht is of type DenseHostTensor*. dht is guaranteed to be
// alive since we capture the AsyncValueRef<DenseHostTensor> that contains the
// dht in the ParallelFor call.
auto add_impl = [dht = &dht.get(), lhs = lhs.CopyRef(), rhs = rhs.CopyRef()](
size_t begin_elt, size_t end_elt) mutable {
switch (lhs.dtype().kind()) {
default:
assert(0 && "shape function failure");
break;
#define DTYPE_TRIVIAL(ENUM) \
case DType::ENUM: \
return TestAddDenseOnlyImpl<TypeForDTypeKind<DType::ENUM>>( \
&lhs, &rhs, dht, begin_elt, end_elt);
#include "tfrt/dtype/dtype.def"
}
};
// Add two dense tensors in parallel. This one is intentionally using min
// block size of 1 to trigger parallel block execution.
ParallelFor(exec_ctx).Execute(
lhs.NumElements(), ParallelFor::BlockSizes::Min(1), std::move(add_impl),
[dht = dht.CopyRef()]() mutable { dht.SetStateConcrete(); });
return dht;
}
//===----------------------------------------------------------------------===//
// test.print op
//===----------------------------------------------------------------------===//
static AsyncValueRef<Chain> PrintOp(const HostTensor& input,
const ExecutionContext& exec_ctx) {
input.Print(tfrt::outs());
tfrt::outs() << '\n';
tfrt::outs().flush();
return GetReadyChain(exec_ctx.host());
}
//===----------------------------------------------------------------------===//
// test.print_address op
//===----------------------------------------------------------------------===//
static AsyncValueRef<Chain> PrintAddressOp(const HostTensor& input,
const ExecutionContext& exec_ctx) {
if (auto* dht = dyn_cast<DenseHostTensor>(&input)) {
tfrt::outs() << "DenseHostTensor: buffer=" << dht->buffer()->data();
} else {
tfrt::outs() << "Unsupported tensor type";
}
tfrt::outs() << '\n';
tfrt::outs().flush();
return GetReadyChain(exec_ctx.host());
}
//===----------------------------------------------------------------------===//
// test.identity op
//===----------------------------------------------------------------------===//
static DenseHostTensor IdentityOp(const HostTensor& input) {
return llvm::cast<DenseHostTensor>(input).CopyRef();
}
//===----------------------------------------------------------------------===//
// test.async.noop op
//===----------------------------------------------------------------------===//
// Copy the input to the output and force it to happen asynchronously, for
// testing.
static RCReference<AsyncValue> AsyncNoopOp(const HostTensor& src,
const ExecutionContext& exec_ctx) {
HostContext* host = exec_ctx.host();
auto dest_ind = MakeIndirectAsyncValue(host);
auto copy = ConvertTensorOnHost(exec_ctx, src, src.tensor_type());
EnqueueWork(exec_ctx, [dest_ind = dest_ind.CopyRef(),
copy = std::move(copy)]() mutable {
dest_ind->ForwardTo(std::move(copy).ReleaseRCRef());
});
return dest_ind;
}
//===----------------------------------------------------------------------===//
// test.error.tensor op
//===----------------------------------------------------------------------===//
// This is an op that has a metadata function but whose op implementation
// produces an error for the tensor result. This allows us to test handling of
// TensorHandle's that have a valid metadata but an error tensor value.
static RCReference<AsyncValue> ErrorTensorOp(const HostTensor& src,
const ExecutionContext& exec_ctx) {
return MakeErrorAsyncValueRef(exec_ctx.host(),
"error from test.error.tensor implementation");
}
//===----------------------------------------------------------------------===//
// Op registration
//===----------------------------------------------------------------------===//
void RegisterTestCpuOps(CpuOpRegistry* op_registry) {
op_registry->AddOp("tfrt_test.odd_collector", TFRT_CPU_OP(OddCollectorOp),
CpuOpFlags::NoSideEffects);
op_registry->AddOp("tfrt_test.create_from_scalar",
TFRT_CPU_OP(TestCreateFromScalarOp),
CpuOpFlags::NoSideEffects, {"value"});
op_registry->AddOp("tfrt_test.add", TFRT_CPU_OP(TestAddOp),
CpuOpFlags::NoSideEffects | CpuOpFlags::AllowsScalar);
op_registry->AddOp("tfrt_test.add.denseonly", TFRT_CPU_OP(TestAddDenseOnlyOp),
CpuOpFlags::NoSideEffects);
op_registry->AddOp("tfrt_test.add.denseonly2",
TFRT_CPU_OP(TestAddDenseOnly2Op),
CpuOpFlags::NoSideEffects);
op_registry->AddOp("tfrt_test.add.denseonly3",
TFRT_CPU_OP(TestAddDenseOnly3Op),
CpuOpFlags::NoSideEffects);
op_registry->AddOp("tfrt_test.print", TFRT_CPU_OP(PrintOp),
CpuOpFlags::AllowsScalar | CpuOpFlags::AllowsString |
CpuOpFlags::AllowsCoo);
op_registry->AddOp("tfrt_test.print_address", TFRT_CPU_OP(PrintAddressOp),
CpuOpFlags::AllowsScalar | CpuOpFlags::AllowsCoo);
op_registry->AddOp("tfrt_test.identity", TFRT_CPU_OP(IdentityOp),
CpuOpFlags::NoSideEffects);
op_registry->AddOp("tfrt_test.async.noop", TFRT_CPU_OP(AsyncNoopOp),
CpuOpFlags::NoSideEffects | CpuOpFlags::AllowsScalar);
// Register another AsyncNoopOp but with no metadata function.
op_registry->AddOp("tfrt_test.async.noop_no_md", TFRT_CPU_OP(AsyncNoopOp),
CpuOpFlags::NoSideEffects | CpuOpFlags::AllowsScalar);
op_registry->AddOp("tfrt_test.error.tensor", TFRT_CPU_OP(ErrorTensorOp),
CpuOpFlags::NoSideEffects | CpuOpFlags::AllowsScalar);
}
} // namespace tfrt
| [
"nateweiler84@gmail.com"
] | nateweiler84@gmail.com |
bceec26d1108c00e7bed67c3a7c07a0979c4b6de | a7413d9ce83654f1f34cacb09c20deeb6bd523ea | /gadgets/hyper/CMRTGadget.h | 84d2e5f3f2e8d40677b41aad3ee7d0f1e652ad77 | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | hansenms/gadgetron | 1e40b1a6265a96cc6f518d0a28cecb0a1d65d292 | 10531591411fea4e16a074a574cd449a60d28ef8 | refs/heads/master | 2022-02-01T23:52:52.993704 | 2021-12-10T23:31:52 | 2021-12-10T23:31:52 | 28,053,346 | 3 | 1 | NOASSERTION | 2021-12-21T23:41:07 | 2014-12-15T19:54:00 | C++ | UTF-8 | C++ | false | false | 2,682 | h | #pragma once
#include "Gadget.h"
#include "hoNDArray.h"
#include "cuNDArray.h"
#include "gadgetron_hyper_export.h"
#include "CMRTOperator.h"
#include <ismrmrd/ismrmrd.h>
#include <complex>
namespace Gadgetron{
class EXPORTGADGETSHYPER CMRTGadget :
public Gadget3< ISMRMRD::AcquisitionHeader, hoNDArray< std::complex<float> >, hoNDArray<float> >
{
public:
CMRTGadget(): num_frames(0) {
}
~CMRTGadget() {}
protected:
GADGET_PROPERTY(golden_ratio,bool,"Use golden ratio trajectories",false);
GADGET_PROPERTY(use_TV,bool,"Use total variation",false);
GADGET_PROPERTY(projections_per_recon,int,"Number of projections per reconstruction",0);
GADGET_PROPERTY(iterations,int,"Number of iterations",30);
virtual int process_config(ACE_Message_Block* mb);
virtual int process(GadgetContainerMessage< ISMRMRD::AcquisitionHeader > *m1, // header
GadgetContainerMessage< hoNDArray< std::complex<float> > > *m2, // data
GadgetContainerMessage< hoNDArray<float> > *m3 ); // traj/dcw
protected:
template<class T> GadgetContainerMessage< hoNDArray<T> >*
duplicate_array( GadgetContainerMessage< hoNDArray<T> > *array );
boost::shared_ptr< hoNDArray<float_complext> >
extract_samples_from_queue ( ACE_Message_Queue<ACE_MT_SYNCH> *queue );
boost::shared_ptr< hoNDArray<float> >
extract_trajectory_from_queue ( ACE_Message_Queue<ACE_MT_SYNCH> *queue );
void extract_trajectory_and_dcw_from_queue
( ACE_Message_Queue<ACE_MT_SYNCH> *queue, boost::shared_ptr< hoNDArray<floatd2> > & traj, boost::shared_ptr< hoNDArray<float> > & dcw );
/***
* Combines all stored frames and resets the frame buffer
*/
boost::shared_ptr<cuNDArray<float_complext> > get_combined_frames();
protected:
std::vector<size_t> image_space_dimensions_3D_;
unsigned int projections_per_recon_;
boost::shared_ptr< ACE_Message_Queue<ACE_MT_SYNCH> > frame_readout_queue_;
boost::shared_ptr< ACE_Message_Queue<ACE_MT_SYNCH> > frame_traj_queue_;
std::vector<size_t> dimensions_;
std::vector<float> field_of_view_;
size_t repetitions_;
size_t samples_per_readout_;
size_t num_coils_;
size_t num_trajectory_dims_; // 2 for trajectories only, 3 for both trajectories + dcw
std::vector<boost::shared_ptr<hoNDArray<float_complext> > > frames;
boost::shared_ptr<hoNDArray<float> > dcw;
boost::shared_ptr<hoNDArray<floatd2> > traj;
unsigned int num_frames;
unsigned int iterations_;
bool golden_ratio_;
bool use_TV_;
};
}
| [
"dch@cs.au.dk"
] | dch@cs.au.dk |
e6eb8b290932234f9ef4a26460507c6adeed07ab | cacf70e80d6fa364037396680b588a037cc521e3 | /physical/createcats.cpp | 06d998160b4dcb37424fc9a42ebcb4d4ee7d22af | [] | no_license | sama28/project2 | 72c7f4ad57662638ed8b04a74dc14e0d3acc43f4 | 769e69b9a162aa5ad2fe0bf540aabeb909f8debf | refs/heads/master | 2021-08-18T19:42:22.491116 | 2017-11-20T13:47:02 | 2017-11-20T13:47:02 | 110,422,255 | 0 | 0 | null | 2017-11-19T16:17:22 | 2017-11-12T10:09:05 | C++ | UTF-8 | C++ | false | false | 13,756 | cpp | //------cumpulsory header--------------
#include "../include/defs.h"
#include "../include/error.h"
#include "../include/globals.h"
#include "../include/mrdtypes.h"
#include <stdio.h>
//-------------------------------------
//-----additional header---------
//-------------------------------------
//-----for int mkdir(const char *pathname, mode_t mode),lseek();
#include <sys/stat.h>
#include <sys/types.h>
//------------------------------------
//for errno and EEXIST
#include<errno.h>
//-----------------------------------
#include<string.h>
//------------------------------------
//for file and directory permission ----------
//for :- open(),chmod(),lseek()
#include <fcntl.h>
#include <unistd.h>
#include<errno.h>
// ssize_t write(int fd, const void *buf, size_t count);
int CreateCats(char *d)//d should be d=HOME/data/[dbname]/data
{
//chmod("./testsbit",S_IRWXU| S_ISVTX|O_DIRECTORY);
char path[MAX_PATH_LENGTH],path1[MAX_PATH_LENGTH],*c,*ca,catpath[MAX_PATH_LENGTH];
int status;
FILE *fd,*fda;
long long offset;
//long int temp;
//-------------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------
//---------------------------CATALOG SPECIFIC--------------------------------------------------------
//part1 FOR RELCAT
//-------------------------------------------------------------------------------------------------------------------------
char relName[RELNAME]="relcat";//size=s[0]
char readrel[RELNAME];
unsigned recLength;//size=s[1]
unsigned recPerPg;//size=s[2]
unsigned short numAttrs;//size=s[3]
unsigned numpages;//size=s[8]
unsigned numrecs;//size=s[9]
unsigned s[10];
int i;
Rid recid;//s[5]//corresponding to ,the rid of 1st attribute of relcat, in attrCats
PageRelCat pg;//s[4]
PageAttrCat pg1;
unsigned int bitmssize;
//size of relcat attribute------------------
s[0]=sizeof(relName);
s[1]=sizeof(recLength);
s[2]=sizeof(recPerPg);
s[3]=sizeof(numAttrs);
//--------------------
s[5]=sizeof(recid.pid);
s[6]=sizeof(recid.slotnum);
//--------------------------
s[8]=sizeof(numpages);
s[9]=sizeof(numrecs);
//-------------------------------------------------
//s[4]=sizeof(pg.slotmap);//bitmap size priveously used
bitmssize=MR_RELCAT_BITMS_NUM;//(PAGESIZE-PGTAIL_SPACE)/(8*MR_RELCAT_REC_SIZE+1);
s[4]=bitmssize;
//----------------this memory space wastage (in array s[7]) could be saved -------
s[7]=sizeof(pg.slotmap[0]);//size of slot of bitmap(which nothing but unsigned char)
//----------------------------------------------
//previously used
//for(int i =0 ;i<bitmssize;i++)
for(int i =0 ;i<MR_RELCAT_BITMS_NUM;i++)
{
pg.slotmap[i]=0x00;
}
pg.slotmap[0]=0xc0;//setting 1st 2 bit of bitmap slot to 1,
//for record slot num1 =1(correspnds relcat)
//for record slot num2 =1(correspnds attrcat)
printf("\nvalue of 1st bitmap slot is in decimal %d in octal %o",pg.slotmap[0],pg.slotmap[0]);
numpages=1;
numrecs=2;//attrcat+relcat
numAttrs=8;
recid.pid=0; //this shows 1st atrribute of this relation(relcat) is at page 0;
recid.slotnum=0; ////this shows 1s(t atrribute of this relation(relcat) is at slotnum=0; in attrcat
recLength=s[0]+s[1]+s[2]+s[3]+s[5]+s[6]+s[8]+s[9];
recPerPg=(PAGESIZE-PGTAIL_SPACE-s[4])/recLength;//s[4]*8;
//recPerPg=(PAGESIZE - (space intentionally left blank in ech page) -bitmap size)/recLemgth
//printf("\n s0 %d s1 %d s2 %d s3 %d s4 %d recLength = %d,recPerPg=%d",s[0],s[1],s[2],s[3],s[4],recLength,recPerPg);
//------------------------------------------------------------------------------------------------------------------
//-------------------------------------------------------------------------------------------------------------------------
//part2 FOR ATTRCAT
char name[ATTRLEN];
unsigned ofst;
unsigned attrl=ATTRLEN;
short type;
unsigned arecLength;
unsigned arecPerPg;
unsigned short anumAttrs;
unsigned as[8];
Rid arecid;
//----------------------------
as[0]=sizeof(name);
as[1]=sizeof(ofst);
as[2]=sizeof(attrl);
as[3]=sizeof(type);
//------Storing values, to be write in relcat, for attrcat relation
strcpy(name,"attrcat");
anumAttrs=4;
arecid.pid=0; //this shows 1st atrribute of this relation(attrcat) is at page 0;
arecid.slotnum=numAttrs; ////this shows that
//1st atrribute of this relation(attrcat) is at which record in attrcat
//(in this case it is(8-numAttrs in relcat) beacuse relcat have 8 attribute)
arecLength=as[0]+as[1]+as[2]+as[3];//two entries ar 's'
arecPerPg=(PAGESIZE-PGTAIL_SPACE-s[4])/arecLength;//note -> s[4]==bitmap size
//--------------------------------------------------------------------
strcpy(path,d);
c=strcat(path,"/catalog");//C=HOME_MINIREL/[DB1]/data/catalog
strcpy(catpath,c);
//--------------------------------------------------------
// printf(" \n \npath comes in cats is :- %s \n\n",d);
// printf(" \n \npath in cats is :- %s \n\n",c);
status=mkdir(c,S_IRWXU);//making C=HOME_MINIREL/[DB1]/data/catalog
//printf("\nerrno :- %d",errno);
//printf("\nstautus is :- %d",status);
if(status==-1)
{
if(errno==EEXIST)
{
printf("\n---------------------------------------------------");
printf("\nCATLOG DIRECTORY ALREADY EXISTS....");
printf("\n---------------------------------------------------\n");
}
else
{
printf("\n---------------------------------------------------");
printf("\nSOMETHING GOES WRONG MAY BE PERMISSION,PATH OR SPACE PROBLEM......");
printf("\n---------------------------------------------------\n");
}
}
else if(status==0)
{
printf("\n---------------------------------------------------");
printf("\nCATALOG DIRECTORY CREATED......");
strcpy(path,c);
strcpy(path1,c);
c=strcat(path,"/relcat");
ca=strcat(path1,"/attrcat");
printf("%s",ca);
fd=fopen(c,"rb");//C=HOME_MINIREL/data/[DB1]/data/catalog/relcat
fda=fopen(ca,"rb");//C=HOME_MINIREL/data/[DB1]/data/catalog/attrcat
printf("fd=%d fda=%d",fd,fda);
if(fd<=0 && fda<=0)
{
//fd=open(c,O_RDWR|O_CREAT,S_IRWXU);
fd=fopen(c,"wb+");//C=HOME_MINIREL/[DB1]/data/catalog/relcat
fda=fopen(ca,"wb+");//C=HOME_MINIREL/[DB1]/data/catalog/attrcat
//printf(" \n \npath is :- %s \n\n",c);
if(fd > 0 && fda > 0)
{
//----------------------------------------------------------
//----------WRITTING data of relcat relation TO relcat(its own data to itself)-----
//relcat(relName,recLength,rcPerPg,numPgs,numRecs,numAttrs,pid,rid)
//fwrite(buf,4*MR_RELCAT_BITMS_NUM,1,fd);
//printf("file opened successfully fd= %d,offset=%d",fd,offset);//debug code
//
//fseek(fd,offset,SEEK_SET); //setting pointer to 1st Record slot (just one byte after bitmap)
for(int i = 0 ;i<MR_RELCAT_BITMS_NUM;i++)
{
fwrite(&(&pg)->slotmap[i],s[7],1,fd); //writing bitmap
}
offset=s[4];//size of bitmapslot;
fseek(fd,offset,SEEK_SET); //setting pointer to 1st Record slot (just one byte after bitmap)
fwrite(relName,s[0],1,fd);
//fread(readrel,32,1,fd);
//printf("\n%d data written to file and read back is %s",len,readrel);
fwrite(&recLength,s[1],1,fd);
//printf("\n%d NOF data written to file reclength ",len);
fwrite(&recPerPg,s[2],1,fd);
fwrite(&numpages,s[8],1,fd);
fwrite(&numrecs,s[9],1,fd);
fwrite(&numAttrs,s[3],1,fd);
fwrite(&(&recid)->pid,s[5],1,fd);
fwrite(&(&recid)->slotnum,s[6],1,fd);
//-----------------------------------------------------
//printf("file opened successfully fd= %d,offset=%d",fd,offset);//debug code, can be removed
//----------------------------------------------------------
//---------- : WRITTING data of attrcat relation TO relcat : -----
fseek(fd,s[4]+recLength,SEEK_SET);//offset to 2nd record slot of page
fwrite(name,s[0],1,fd);
fwrite(&arecLength,s[1],1,fd);
fwrite(&arecPerPg,s[2],1,fd);
numpages=1;//total pagerequired to store atrributes of relcat+attrcat
fwrite(&numpages,s[8],1,fd);
numrecs=12;//total #of atributes in relacat+attrcat
fwrite(&numrecs,s[9],1,fd);
fwrite(&anumAttrs,s[3],1,fd);
fwrite(&(&arecid)->pid,s[5],1,fd);
fwrite(&(&arecid)->slotnum,s[6],1,fd);
//-------------------------------------------
fflush(fd);
fclose(fd);
chmod(c,S_IRUSR| S_ISVTX|O_DIRECTORY);
//chmod(catpath,S_IRUSR|S_IXUSR|O_DIRECTORY);
//.........................................
//----WRITTING INTO ATRRCAT RELATION------------
//-------------------------------------------------
//setting bitmapslot
//since total 12 records are going to be added in the attrcat hence
//setting the 1st 12 bit of bitmap to 1;
pg1.slotmap[0]=0xff;//hex=1111 1111
pg1.slotmap[1]=0xf0;//1111 0000
fwrite(&(&pg1)->slotmap[0],s[7],1,fda); //writing bitmap
fwrite(&(&pg1)->slotmap[1],s[7],1,fda); //writing bitmap
for(i = 2 ;i<MR_ATTRCAT_BITMS_NUM;i++)
{
pg1.slotmap[i]=0x00;
fwrite(&(&pg)->slotmap[i],s[7],1,fda); //writing bitmap
}
//--------------------------------------------------
//writing 1st attribute to attrcat
//1st 8 attributes are from relcat relation since relcat point attribute pointer point to pid=0 rid=0
//relcat(relName,recLength,rcPerPg,numPgs,numRecs,numAttrs,pid,rid)
strcpy(name,"relName");
//printf("\n\n it shoul be relName %s",name);
ofst=0;
attrl=ATTRLEN;
type=DTSTRING;
//-----------------------------------------------------------
s[4]=MR_ATTRCAT_BITMS_NUM;//(PAGESIZE-PGTAIL_SPACE)/(8*MR_ATTRCAT_REC_SIZE+1);//bitmap size in byte
//----------------------------------------------------------------
fseek(fda,s[4],SEEK_SET);//setting fd to 1st record slot of attrcat
fwrite(name,as[0],1,fda);
fwrite(&ofst,as[1],1,fda);
fwrite(&attrl,as[2],1,fda);
fwrite(&type,as[3],1,fda);
//second attribute
strcpy(name,"recLength");
ofst=1;
attrl=4;
type=DTUNSIGNED_INT;
fseek(fda,s[4]+arecLength,SEEK_SET);//adjusting bit boundary;
fwrite(name,as[0],1,fda);
fwrite(&ofst,as[1],1,fda);
fwrite(&attrl,as[2],1,fda);
fwrite(&type,as[3],1,fda);
//3rd attribute
strcpy(name,"recPerPg");
ofst=2;
attrl=4;
type=DTUNSIGNED_INT;
fseek(fda,s[4]+2*arecLength,SEEK_SET);//adjusting bit boundary;
fwrite(name,as[0],1,fda);
fwrite(&ofst,as[1],1,fda);
fwrite(&attrl,as[2],1,fda);
fwrite(&type,as[3],1,fda);
//4th attribute
strcpy(name,"numPgs");
ofst=3;
attrl=4;
type=DTUNSIGNED_INT;
fseek(fda,s[4]+3*arecLength,SEEK_SET);//adjusting bit boundary;
fwrite(name,as[0],1,fda);
fwrite(&ofst,as[1],1,fda);
fwrite(&attrl,as[2],1,fda);
fwrite(&type,as[3],1,fda);
//5th attribute
strcpy(name,"numRecs");
ofst=4;
attrl=4;
type=DTUNSIGNED_INT;
fseek(fda,s[4]+4*arecLength,SEEK_SET);//adjusting bit boundary;
fwrite(name,as[0],1,fda);
fwrite(&ofst,as[1],1,fda);
fwrite(&attrl,as[2],1,fda);
fwrite(&type,as[3],1,fda);
//6th attribute
strcpy(name,"numAttrs");
ofst=5;
attrl=2;
type=DTUNSIGNED_SHORT;
fseek(fda,s[4]+5*arecLength,SEEK_SET);//adjusting bit boundary;
fwrite(name,as[0],1,fda);
fwrite(&ofst,as[1],1,fda);
fwrite(&attrl,as[2],1,fda);
fwrite(&type,as[3],1,fda);
//7th attribute
strcpy(name,"attr0Pid");
ofst=6;
attrl=4;
type=DTUNSIGNED_INT;
fseek(fda,s[4]+6*arecLength,SEEK_SET);//adjusting bit boundary;
fwrite(name,as[0],1,fda);
fwrite(&ofst,as[1],1,fda);
fwrite(&attrl,as[2],1,fda);
fwrite(&type,as[3],1,fda);
//8th attribute
strcpy(name,"attr0Slotnum");
ofst=7;
attrl=4;
type=DTUNSIGNED_INT;
fseek(fda,s[4]+7*arecLength,SEEK_SET);//adjusting bit boundary;
fwrite(name,as[0],1,fda);
fwrite(&ofst,as[1],1,fda);
fwrite(&attrl,as[2],1,fda);
fwrite(&type,as[3],1,fda);
//-------------------------------
//writting attribute of attribute catalog into itsel
//1st attribute of attrcat
strcpy(name,"attrName");
ofst=0;
attrl=ATTRLEN;
type=DTSTRING;
fseek(fda,s[4]+8*arecLength,SEEK_SET);//adjusting bit boundary;
fwrite(name,as[0],1,fda);
fwrite(&ofst,as[1],1,fda);
fwrite(&attrl,as[2],1,fda);
fwrite(&type,as[3],1,fda);
//2nd attribute
strcpy(name,"offset");
ofst=1;
attrl=4;
type=DTUNSIGNED_INT;
fseek(fda,s[4]+9*arecLength,SEEK_SET);//adjusting bit boundary;
fwrite(name,as[0],1,fda);
fwrite(&ofst,as[1],1,fda);
fwrite(&attrl,as[2],1,fda);
fwrite(&type,as[3],1,fda);
//3rd attribute
strcpy(name,"length");
ofst=2;
attrl=4;
type=DTUNSIGNED_INT;
fseek(fda,s[4]+10*arecLength,SEEK_SET);//adjusting bit boundary;
fwrite(name,as[0],1,fda);
fwrite(&ofst,as[1],1,fda);
fwrite(&attrl,as[2],1,fda);
fwrite(&type,as[3],1,fda);
//4th attribute
strcpy(name,"type");
ofst=3;
attrl=2;
type=DTSHORT;
fseek(fda,s[4]+11*arecLength,SEEK_SET);//adjusting bit boundary;
fwrite(name,as[0],1,fda);
fwrite(&ofst,as[1],1,fda);
fwrite(&attrl,as[2],1,fda);
fwrite(&type,as[3],1,fda);
fflush(fda);
fclose(fda);
chmod(ca,S_IRUSR| S_ISVTX|O_DIRECTORY);
chmod(catpath,S_IRUSR|S_IXUSR|O_DIRECTORY);
//changeing the permission so that people can not change catalog
}
else
{
printf("atleast one catlog can not be created relcat fd %d attrcat fd %d errno %d",fd,fda,errno);//debug code
}
}
else
{
printf("\n some catalog already exists...%d %d",fd,fda);
}
}
//--------------------------------------------------------------------
}
| [
"samadhans@iisc.ac.in"
] | samadhans@iisc.ac.in |
5f36db404a379406252240f77ad2d4341112dbe6 | d9725d8ec9e215c31895318780d825a6064d4f31 | /05.DataStructure/RMQ-plain/main.cpp | 1dca6bcf0bd3c3bdf74cdc54dd5751458bcb4fdf | [
"MIT"
] | permissive | Yangjiaxi/alg-template | 17b2ab09d492014ea1d9048f3d1787b2277dfc15 | 2765f264ab699d0b0ea29d9cf56de8759ef062c3 | refs/heads/master | 2022-09-11T18:47:35.252641 | 2022-08-26T08:54:10 | 2022-08-26T08:54:10 | 232,580,127 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,322 | cpp | #include "utils.h"
#include <iostream>
#include <vector>
using namespace std;
const int MAXN = 1005;
int d[MAXN][MAXN];
/*
d[i][j]:
从i开始,长度为2^j的一段元素中的最小值
因此具有递推关系:
d[i][j] = min(d[i][j-1], d[i+2^{j-1}][j-1])
*/
void RMQ_init(const vector<int> &A) {
int n = A.size();
for (int i = 0; i < n; ++i) d[i][0] = A[i];
for (int j = 1; (1 << j) <= n; ++j) {
for (int i = 0; i + (1 << j) - 1 < n; ++i) {
d[i][j] = min(d[i][j - 1], d[i + (1 << (j - 1))][j - 1]);
}
}
}
int RMQ(size_t L, size_t R) {
int k = 0;
while (1 << (k + 1) <= R - L + 1) ++k;
return min(d[L][k], d[R - (1 << k) + 1][k]);
}
int main() {
const int N = 10;
// vector<int> A = array_init(N);
vector<int> A{40, 64, 11, 52, 77, 83, 13, 29, 56, 79};
RMQ_init(A);
cout << "Array D:" << endl;
for (int i = 0; i < N; ++i) {
cout << "\t";
for (int j = 1; (1 << j) <= N; ++j) printf("d[%d][%d]=%d\t", i, j, d[i][j]);
cout << endl;
}
output_array(A, true);
cout << endl << "RMQ:" << endl;
for (int L = 0; L < N; ++L) {
cout << "\t";
for (int R = L + 1; R < N; ++R) printf("[%d,%d]=%d\t", L, R, RMQ(L, R));
cout << endl;
}
return 0;
} | [
"1468764755@qq.com"
] | 1468764755@qq.com |
56f205071cc3bf6a2812933e4dce5f65e931d566 | 00e0f58d45fb0f7b9b16f77e85ce12302f865cee | /VuMeters.cpp | dba54966f1c4eaa9600d4a998295776090040413 | [] | no_license | cristianvogel/PFMCPP_Project5 | 3abf01e44fc76e4b45d095c2ca22d04a57659063 | 49f26c47755f62b8ebdfeb0f1f7a8430d308244f | refs/heads/master | 2020-12-14T15:50:34.410555 | 2020-01-31T20:41:55 | 2020-01-31T20:41:55 | 234,795,959 | 0 | 0 | null | 2020-01-31T20:41:57 | 2020-01-18T20:49:18 | C++ | UTF-8 | C++ | false | false | 155 | cpp | #include "VuMeters.h"
VuMeters::VuMeters()
{
vu.vuMeterMain(vu);
}
VuMeters::~VuMeters()
{
std::cout << "\n Destructing Meter Segments \n\n";
}
| [
"cristian.vogel55@gmail.com"
] | cristian.vogel55@gmail.com |
3e26e079771ad31785989c9be5369e8f005565cf | 0ab070e12002fbe783c79afa6445f040bae3ed68 | /serial_input.ino | efdfb5068f269dab4ee221f09d419b27cd786694 | [] | no_license | shridam1207/Nigahein | da76c4a6a57a1140925918ba6d07e65b47d0c7e6 | 991de8576f7e30becd1d03a0832db77ea8f6365f | refs/heads/master | 2020-05-01T02:07:43.667366 | 2019-10-18T10:45:33 | 2019-10-18T10:45:33 | 177,211,439 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 435 | ino | int input = 0;
void setup() {
// put your setup code here, to run once:
pinMode(13, OUTPUT);
Serial.begin(115200);
digitalWrite(13, LOW);
}
void loop() {
// put your main code here, to run repeatedly:
if (Serial.available() > 0) {
input = Serial.read();
Serial.print("I received: ");
Serial.println(input);
if (input == 1) digitalWrite(13, HIGH);
else if (input == 0) digitalWrite(13, LOW);
}
}
| [
"noreply@github.com"
] | noreply@github.com |
4e4bf6a9e10fa160b504f6f9374fe721ae41bbad | 60cf5dd7ade09c10981cae855df9b2fc44a6946b | /TaskLayer/MyFileManager.h | c6cdb95c350643dbf354c6f53a085506c62305f6 | [
"MIT"
] | permissive | PSTL-UH/HPCMetaMorpheus | ee15951693ded3c8d9b18ce043d47704e0925c5d | 578d880a9ab6780752c762f324f0bc1ec95c8b8c | refs/heads/master | 2023-06-25T00:33:47.618202 | 2021-07-31T18:35:02 | 2021-07-31T18:35:02 | 283,815,009 | 2 | 3 | MIT | 2021-07-31T18:42:55 | 2020-07-30T15:44:57 | C++ | UTF-8 | C++ | false | false | 1,310 | h | #pragma once
#include <string>
#include <unordered_map>
#include <optional>
#include <mutex>
#include "tangible_filesystem.h"
#include "EventHandler.h"
#include "../EngineLayer/EventArgs/StringEventArgs.h"
#include "../EngineLayer/CommonParameters.h"
using namespace EngineLayer;
using namespace MassSpectrometry;
namespace TaskLayer
{
class MyFileManager
{
public:
enum class ThermoMsFileReaderVersionCheck
{
DllsNotFound,
IncorrectVersion,
CorrectVersion,
SomeDllsMissing
};
private:
const bool DisposeOfFileWhenDone;
std::unordered_map<std::string, MsDataFile*> MyMsDataFiles = std::unordered_map<std::string, MsDataFile*>();
std::mutex FileLoadingLock;
public:
MyFileManager(bool disposeOfFileWhenDone);
bool SeeIfOpen(const std::string path);
MsDataFile *LoadFile(const std::string &origDataFile, std::optional<int> topNpeaks, std::optional<double> minRatio,
bool trimMs1Peaks, bool trimMsMsPeaks, CommonParameters *commonParameters);
void DoneWithFile(const std::string &origDataFile);
private:
void Warn(const std::string &v);
};
}
| [
"egabriel@central.uh.edu"
] | egabriel@central.uh.edu |
d415d5dfafca6769d699d08318601c94b3747af4 | f8309ab662496d779838c7c621cf4d8060df540c | /Labs/Lab6/Part2/btNode.cpp | e6fab3f7365b247ce899b8d0efcee9a662fc05c2 | [] | no_license | mcsanchez093/CS3358-Data-Structures | 5cef235e6c0e9a3ce143db2e38d4f3fcdb29e01b | 1bec276ec0108d67f467aa90e964ff6b124f0ad3 | refs/heads/master | 2021-01-20T02:13:33.731381 | 2017-04-25T19:10:11 | 2017-04-25T19:10:11 | 89,392,248 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,204 | cpp |
#include "btNode.h"
void dumpToArrayInOrder(btNode* bst_root, int* dumpArray)
{
if (bst_root == 0) return;
int dumpIndex = 0;
dumpToArrayInOrderAux(bst_root, dumpArray, dumpIndex);
}
void dumpToArrayInOrderAux(btNode* bst_root, int* dumpArray, int& dumpIndex)
{
if (bst_root == 0) return;
dumpToArrayInOrderAux(bst_root->left, dumpArray, dumpIndex);
dumpArray[dumpIndex++] = bst_root->data;
dumpToArrayInOrderAux(bst_root->right, dumpArray, dumpIndex);
}
void tree_clear(btNode*& root)
{
if (root == 0) return;
tree_clear(root->left);
tree_clear(root->right);
delete root;
root = 0;
}
int bst_size(btNode* bst_root)
{
if (bst_root == 0) return 0;
return 1 + bst_size(bst_root->left) + bst_size(bst_root->right);
}
void bst_insert(btNode*& root, int newInt)
{
if (root == 0)
{
btNode* new_node = new btNode;
new_node -> data = newInt;
new_node -> left = 0;
new_node -> right = 0;
root = new_node;
}
else
{
btNode* cursor = root;
bool done = false;
while (!done)
{
if (newInt == cursor ->data)
{
done = true;
}
else if (newInt < cursor -> data)
{
if (cursor -> left == 0)
{
btNode* new_node = new btNode;
new_node -> data = newInt;
new_node -> left = 0;
new_node -> right = 0;
cursor -> left = new_node;
done = true;
}
else
{
cursor = cursor -> right;
}
}
else
{
if (cursor -> right == 0)
{
btNode* new_node = new btNode;
new_node -> data = newInt;
new_node -> left = 0;
new_node -> right = 0;
cursor -> right = new_node;
done = true;
}
else
{
cursor = cursor -> right;
}
}
}
}
}
bool bst_remove(btNode*& root, int remInt)
{
if (root == 0)
{
return false;
}
if (remInt < root -> data)
{
return bst_remove(root -> left, remInt);
}
if(remInt > root -> data)
{
return bst_remove(root -> right, remInt);
}
if (remInt == root -> data)
{
if(root -> left == 0)
{
btNode* oldroot_ptr = root;
root = root -> right;
delete oldroot_ptr;
return true;
}
bst_remove_max(root -> left, root ->data);
return true;
}
return false;
}
void bst_remove_max(btNode*& root, int& rootData)
{
if (root -> right != 0)
{
return bst_remove_max(root -> right, rootData);
}
rootData = root -> data;
if (root -> left == 0)
{
root = 0;
return;
}
root = root -> left;
return;
}
| [
"noreply@github.com"
] | noreply@github.com |
b8cfd82483636a62f792f04b117c3425980fcff0 | a89a30a000a6c7eef6853aacbe051985f1965d6a | /usaco/2/2.2/subset/2.cpp | d09293a65eb093fe859ec085419d1d9332fde173 | [] | no_license | ak795/acm | 9edd7d18ddb6efeed8184b91489005aec7425caa | 81787e16e23ce54bf956714865b7162c0188eb3a | refs/heads/master | 2021-01-15T19:36:00.052971 | 2012-02-06T02:25:23 | 2012-02-06T02:25:23 | 44,054,046 | 1 | 0 | null | 2015-10-11T13:53:25 | 2015-10-11T13:53:23 | null | UTF-8 | C++ | false | false | 1,052 | cpp | /*
ID: rock2to1
LANG: C++
PROG: subset
*/
#include <cctype>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <bitset>
#include <deque>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <utility>
#include <vector>
using namespace std;
ifstream fin("subset.in");
ofstream fout("subset.out");
////////////////////////////////////////////////////////////////////////////////
long long dp[500][500];
long long aux[500][500];
int main()
{
int n;
fin>>n;
if (n*(n+1)%4) { fout<<0<<endl; return 0; }
int x=n*(n+1)/4;
dp[0][0]=1;
for (int i=1; i<=n; ++i) {
memset(aux, 0, sizeof(aux));
for (int j=0; j<=x; ++j) {
for (int k=0; k<=x; ++k) {
long long a=dp[j][k];
aux[i+j][k]+=a;
aux[j][i+k]+=a;
}
}
memcpy(dp, aux, sizeof(aux));
}
// cout<<x<<endl;
fout<<dp[x][x]/2<<endl;
}
| [
"rock.spartacus@gmail.com"
] | rock.spartacus@gmail.com |
1f72866ac97aea34b49795ab0f8dc8db57a355c5 | 1d8484881e4433d6a7436d0d3467fd99ed266362 | /include/bit/stl/functional/extraction/use_first.hpp | 59eb66ee8d163861125b6cf4de6d64c9e483dfc4 | [
"MIT",
"LicenseRef-scancode-free-unknown"
] | permissive | bitwizeshift/bit-stl | a8497a46abc0d104aa10ed3e8d00739301bbe05a | cec555fbda2ea1b6e126fa719637dde8d3f2ddd3 | refs/heads/develop | 2021-01-11T14:56:30.998822 | 2018-08-15T21:22:28 | 2018-08-15T21:22:28 | 80,256,758 | 8 | 1 | MIT | 2019-04-11T17:22:15 | 2017-01-28T00:10:46 | C++ | UTF-8 | C++ | false | false | 2,320 | hpp | /*****************************************************************************
* \file
* \brief TODO: Add description
*****************************************************************************/
/*
The MIT License (MIT)
Bit Standard Template Library.
https://github.com/bitwizeshift/bit-stl
Copyright (c) 2018 Matthew Rodusek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
#ifndef BIT_STL_FUNCTIONAL_EXTRACTION_USE_FIRST_HPP
#define BIT_STL_FUNCTIONAL_EXTRACTION_USE_FIRST_HPP
#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)
#include "../../traits/composition/bool_constant.hpp"
#include "../../traits/composition/void_t.hpp"
#include "../../utilities/tuple_utilities.hpp" // adl::get
#include <type_traits> // std::declval, std::enable_if_t
#include <utility> // std::forward
namespace bit {
namespace stl {
struct use_first
{
template<typename Tuple>
constexpr decltype(auto) operator()( Tuple&& tuple );
};
} // namespace stl
} // namespace bit
template<typename Tuple>
inline constexpr decltype(auto) bit::stl::use_first::operator()( Tuple&& tuple )
{
using ::bit::stl::adl::get;
return get<0>( std::forward<Tuple>(tuple) );
}
#endif /* BIT_STL_FUNCTIONAL_EXTRACTION_USE_FIRST_HPP */
| [
"noreply@github.com"
] | noreply@github.com |
144ebbfa320aa9542c518fd047525111bcddc5cf | d483f73be201ca76e4511da107a18c202a43b06a | /testing_code/HLS_demo_code/Vivado_HLS_Tutorial/Design_Optimization/lab1/matrixmul_prj/solution6/.autopilot/db/matrixmul.pragma.2.cpp | 9963b4b774cec4a06a76b1b502d4e84489ad559f | [] | no_license | thnguyn2/ECE_527_testing_code | 03b39ad7f959dfb37c1438fad978807db7dcd23e | c15d653f2fdecedc366f182e2e8968736f0e48b6 | refs/heads/master | 2016-08-06T02:18:09.896453 | 2015-10-16T12:32:52 | 2015-10-16T12:32:52 | 41,923,498 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 158,851 | cpp | # 1 "/home/parallels/source_code/ECE_527_testing_code/testing_code/HLS_demo_code/Vivado_HLS_Tutorial/Design_Optimization/lab1/matrixmul_prj/solution6/.autopilot/db/matrixmul.pragma.1.cpp"
# 1 "/home/parallels/source_code/ECE_527_testing_code/testing_code/HLS_demo_code/Vivado_HLS_Tutorial/Design_Optimization/lab1/matrixmul_prj/solution6/.autopilot/db/matrixmul.pragma.1.cpp" 1
# 1 "<built-in>" 1
# 1 "<built-in>" 3
# 155 "<built-in>" 3
# 1 "<command line>" 1
# 1 "/opt/Xilinx/Vivado_HLS/2015.1/common/technology/autopilot/etc/autopilot_ssdm_op.h" 1
/* autopilot_ssdm_op.h*/
/*
#- (c) Copyright 2011-2015 Xilinx, Inc. All rights reserved.
#-
#- This file contains confidential and proprietary information
#- of Xilinx, Inc. and is protected under U.S. and
#- international copyright and other intellectual property
#- laws.
#-
#- DISCLAIMER
#- This disclaimer is not a license and does not grant any
#- rights to the materials distributed herewith. Except as
#- otherwise provided in a valid license issued to you by
#- Xilinx, and to the maximum extent permitted by applicable
#- law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
#- WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
#- AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
#- BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
#- INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
#- (2) Xilinx shall not be liable (whether in contract or tort,
#- including negligence, or under any other theory of
#- liability) for any loss or damage of any kind or nature
#- related to, arising under or in connection with these
#- materials, including for any direct, or any indirect,
#- special, incidental, or consequential loss or damage
#- (including loss of data, profits, goodwill, or any type of
#- loss or damage suffered as a result of any action brought
#- by a third party) even if such damage or loss was
#- reasonably foreseeable or Xilinx had been advised of the
#- possibility of the same.
#-
#- CRITICAL APPLICATIONS
#- Xilinx products are not designed or intended to be fail-
#- safe, or for use in any application requiring fail-safe
#- performance, such as life-support or safety devices or
#- systems, Class III medical devices, nuclear facilities,
#- applications related to the deployment of airbags, or any
#- other applications that could lead to death, personal
#- injury, or severe property or environmental damage
#- (individually and collectively, "Critical
#- Applications"). Customer assumes the sole risk and
#- liability of any use of Xilinx products in Critical
#- Applications, subject only to applicable laws and
#- regulations governing limitations on product liability.
#-
#- THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
#- PART OF THIS FILE AT ALL TIMES.
#- ************************************************************************
*
* $Id$
*/
# 145 "/opt/Xilinx/Vivado_HLS/2015.1/common/technology/autopilot/etc/autopilot_ssdm_op.h"
/*#define AP_SPEC_ATTR __attribute__ ((pure))*/
extern "C" {
/****** SSDM Intrinsics: OPERATIONS ***/
// Interface operations
//typedef unsigned int __attribute__ ((bitwidth(1))) _uint1_;
typedef bool _uint1_;
void _ssdm_op_IfRead(...) __attribute__ ((nothrow));
void _ssdm_op_IfWrite(...) __attribute__ ((nothrow));
_uint1_ _ssdm_op_IfNbRead(...) __attribute__ ((nothrow));
_uint1_ _ssdm_op_IfNbWrite(...) __attribute__ ((nothrow));
_uint1_ _ssdm_op_IfCanRead(...) __attribute__ ((nothrow));
_uint1_ _ssdm_op_IfCanWrite(...) __attribute__ ((nothrow));
// Stream Intrinsics
void _ssdm_StreamRead(...) __attribute__ ((nothrow));
void _ssdm_StreamWrite(...) __attribute__ ((nothrow));
_uint1_ _ssdm_StreamNbRead(...) __attribute__ ((nothrow));
_uint1_ _ssdm_StreamNbWrite(...) __attribute__ ((nothrow));
_uint1_ _ssdm_StreamCanRead(...) __attribute__ ((nothrow));
_uint1_ _ssdm_StreamCanWrite(...) __attribute__ ((nothrow));
// Misc
void _ssdm_op_MemShiftRead(...) __attribute__ ((nothrow));
void _ssdm_op_Wait(...) __attribute__ ((nothrow));
void _ssdm_op_Poll(...) __attribute__ ((nothrow));
void _ssdm_op_Return(...) __attribute__ ((nothrow));
/* SSDM Intrinsics: SPECIFICATIONS */
void _ssdm_op_SpecSynModule(...) __attribute__ ((nothrow));
void _ssdm_op_SpecTopModule(...) __attribute__ ((nothrow));
void _ssdm_op_SpecProcessDecl(...) __attribute__ ((nothrow));
void _ssdm_op_SpecProcessDef(...) __attribute__ ((nothrow));
void _ssdm_op_SpecPort(...) __attribute__ ((nothrow));
void _ssdm_op_SpecConnection(...) __attribute__ ((nothrow));
void _ssdm_op_SpecChannel(...) __attribute__ ((nothrow));
void _ssdm_op_SpecSensitive(...) __attribute__ ((nothrow));
void _ssdm_op_SpecModuleInst(...) __attribute__ ((nothrow));
void _ssdm_op_SpecPortMap(...) __attribute__ ((nothrow));
void _ssdm_op_SpecReset(...) __attribute__ ((nothrow));
void _ssdm_op_SpecPlatform(...) __attribute__ ((nothrow));
void _ssdm_op_SpecClockDomain(...) __attribute__ ((nothrow));
void _ssdm_op_SpecPowerDomain(...) __attribute__ ((nothrow));
int _ssdm_op_SpecRegionBegin(...) __attribute__ ((nothrow));
int _ssdm_op_SpecRegionEnd(...) __attribute__ ((nothrow));
void _ssdm_op_SpecLoopName(...) __attribute__ ((nothrow));
void _ssdm_op_SpecLoopTripCount(...) __attribute__ ((nothrow));
int _ssdm_op_SpecStateBegin(...) __attribute__ ((nothrow));
int _ssdm_op_SpecStateEnd(...) __attribute__ ((nothrow));
void _ssdm_op_SpecInterface(...) __attribute__ ((nothrow));
void _ssdm_op_SpecPipeline(...) __attribute__ ((nothrow));
void _ssdm_op_SpecDataflowPipeline(...) __attribute__ ((nothrow));
void _ssdm_op_SpecLatency(...) __attribute__ ((nothrow));
void _ssdm_op_SpecParallel(...) __attribute__ ((nothrow));
void _ssdm_op_SpecProtocol(...) __attribute__ ((nothrow));
void _ssdm_op_SpecOccurrence(...) __attribute__ ((nothrow));
void _ssdm_op_SpecResource(...) __attribute__ ((nothrow));
void _ssdm_op_SpecResourceLimit(...) __attribute__ ((nothrow));
void _ssdm_op_SpecCHCore(...) __attribute__ ((nothrow));
void _ssdm_op_SpecFUCore(...) __attribute__ ((nothrow));
void _ssdm_op_SpecIFCore(...) __attribute__ ((nothrow));
void _ssdm_op_SpecIPCore(...) __attribute__ ((nothrow));
void _ssdm_op_SpecKeepValue(...) __attribute__ ((nothrow));
void _ssdm_op_SpecMemCore(...) __attribute__ ((nothrow));
void _ssdm_op_SpecExt(...) __attribute__ ((nothrow));
/*void* _ssdm_op_SpecProcess(...) SSDM_SPEC_ATTR;
void* _ssdm_op_SpecEdge(...) SSDM_SPEC_ATTR; */
/* Presynthesis directive functions */
void _ssdm_SpecArrayDimSize(...) __attribute__ ((nothrow));
void _ssdm_RegionBegin(...) __attribute__ ((nothrow));
void _ssdm_RegionEnd(...) __attribute__ ((nothrow));
void _ssdm_Unroll(...) __attribute__ ((nothrow));
void _ssdm_UnrollRegion(...) __attribute__ ((nothrow));
void _ssdm_InlineAll(...) __attribute__ ((nothrow));
void _ssdm_InlineLoop(...) __attribute__ ((nothrow));
void _ssdm_Inline(...) __attribute__ ((nothrow));
void _ssdm_InlineSelf(...) __attribute__ ((nothrow));
void _ssdm_InlineRegion(...) __attribute__ ((nothrow));
void _ssdm_SpecArrayMap(...) __attribute__ ((nothrow));
void _ssdm_SpecArrayPartition(...) __attribute__ ((nothrow));
void _ssdm_SpecArrayReshape(...) __attribute__ ((nothrow));
void _ssdm_SpecStream(...) __attribute__ ((nothrow));
void _ssdm_SpecExpr(...) __attribute__ ((nothrow));
void _ssdm_SpecExprBalance(...) __attribute__ ((nothrow));
void _ssdm_SpecDependence(...) __attribute__ ((nothrow));
void _ssdm_SpecLoopMerge(...) __attribute__ ((nothrow));
void _ssdm_SpecLoopFlatten(...) __attribute__ ((nothrow));
void _ssdm_SpecLoopRewind(...) __attribute__ ((nothrow));
void _ssdm_SpecFuncInstantiation(...) __attribute__ ((nothrow));
void _ssdm_SpecFuncBuffer(...) __attribute__ ((nothrow));
void _ssdm_SpecFuncExtract(...) __attribute__ ((nothrow));
void _ssdm_SpecConstant(...) __attribute__ ((nothrow));
void _ssdm_DataPack(...) __attribute__ ((nothrow));
void _ssdm_SpecDataPack(...) __attribute__ ((nothrow));
void _ssdm_op_SpecBitsMap(...) __attribute__ ((nothrow));
void _ssdm_op_SpecLicense(...) __attribute__ ((nothrow));
}
# 403 "/opt/Xilinx/Vivado_HLS/2015.1/common/technology/autopilot/etc/autopilot_ssdm_op.h"
/*#define _ssdm_op_WaitUntil(X) while (!(X)) _ssdm_op_Wait(1);
#define _ssdm_op_Delayed(X) X */
# 6 "<command line>" 2
# 1 "<built-in>" 2
# 1 "/home/parallels/source_code/ECE_527_testing_code/testing_code/HLS_demo_code/Vivado_HLS_Tutorial/Design_Optimization/lab1/matrixmul_prj/solution6/.autopilot/db/matrixmul.pragma.1.cpp" 2
# 1 "matrixmul.cpp"
# 1 "matrixmul.cpp" 1
# 1 "<built-in>" 1
# 1 "<built-in>" 3
# 155 "<built-in>" 3
# 1 "<command line>" 1
# 1 "/opt/Xilinx/Vivado_HLS/2015.1/common/technology/autopilot/etc/autopilot_ssdm_op.h" 1
/* autopilot_ssdm_op.h*/
/*
#- (c) Copyright 2011-2015 Xilinx, Inc. All rights reserved.
#-
#- This file contains confidential and proprietary information
#- of Xilinx, Inc. and is protected under U.S. and
#- international copyright and other intellectual property
#- laws.
#-
#- DISCLAIMER
#- This disclaimer is not a license and does not grant any
#- rights to the materials distributed herewith. Except as
#- otherwise provided in a valid license issued to you by
#- Xilinx, and to the maximum extent permitted by applicable
#- law: (1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND
#- WITH ALL FAULTS, AND XILINX HEREBY DISCLAIMS ALL WARRANTIES
#- AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY, INCLUDING
#- BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-
#- INFRINGEMENT, OR FITNESS FOR ANY PARTICULAR PURPOSE; and
#- (2) Xilinx shall not be liable (whether in contract or tort,
#- including negligence, or under any other theory of
#- liability) for any loss or damage of any kind or nature
#- related to, arising under or in connection with these
#- materials, including for any direct, or any indirect,
#- special, incidental, or consequential loss or damage
#- (including loss of data, profits, goodwill, or any type of
#- loss or damage suffered as a result of any action brought
#- by a third party) even if such damage or loss was
#- reasonably foreseeable or Xilinx had been advised of the
#- possibility of the same.
#-
#- CRITICAL APPLICATIONS
#- Xilinx products are not designed or intended to be fail-
#- safe, or for use in any application requiring fail-safe
#- performance, such as life-support or safety devices or
#- systems, Class III medical devices, nuclear facilities,
#- applications related to the deployment of airbags, or any
#- other applications that could lead to death, personal
#- injury, or severe property or environmental damage
#- (individually and collectively, "Critical
#- Applications"). Customer assumes the sole risk and
#- liability of any use of Xilinx products in Critical
#- Applications, subject only to applicable laws and
#- regulations governing limitations on product liability.
#-
#- THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS
#- PART OF THIS FILE AT ALL TIMES.
#- ************************************************************************
*
* $Id$
*/
# 145 "/opt/Xilinx/Vivado_HLS/2015.1/common/technology/autopilot/etc/autopilot_ssdm_op.h"
/*#define AP_SPEC_ATTR __attribute__ ((pure))*/
extern "C" {
/****** SSDM Intrinsics: OPERATIONS ***/
// Interface operations
//typedef unsigned int __attribute__ ((bitwidth(1))) _uint1_;
typedef bool _uint1_;
void _ssdm_op_IfRead(...) __attribute__ ((nothrow));
void _ssdm_op_IfWrite(...) __attribute__ ((nothrow));
_uint1_ _ssdm_op_IfNbRead(...) __attribute__ ((nothrow));
_uint1_ _ssdm_op_IfNbWrite(...) __attribute__ ((nothrow));
_uint1_ _ssdm_op_IfCanRead(...) __attribute__ ((nothrow));
_uint1_ _ssdm_op_IfCanWrite(...) __attribute__ ((nothrow));
// Stream Intrinsics
void _ssdm_StreamRead(...) __attribute__ ((nothrow));
void _ssdm_StreamWrite(...) __attribute__ ((nothrow));
_uint1_ _ssdm_StreamNbRead(...) __attribute__ ((nothrow));
_uint1_ _ssdm_StreamNbWrite(...) __attribute__ ((nothrow));
_uint1_ _ssdm_StreamCanRead(...) __attribute__ ((nothrow));
_uint1_ _ssdm_StreamCanWrite(...) __attribute__ ((nothrow));
// Misc
void _ssdm_op_MemShiftRead(...) __attribute__ ((nothrow));
void _ssdm_op_Wait(...) __attribute__ ((nothrow));
void _ssdm_op_Poll(...) __attribute__ ((nothrow));
void _ssdm_op_Return(...) __attribute__ ((nothrow));
/* SSDM Intrinsics: SPECIFICATIONS */
void _ssdm_op_SpecSynModule(...) __attribute__ ((nothrow));
void _ssdm_op_SpecTopModule(...) __attribute__ ((nothrow));
void _ssdm_op_SpecProcessDecl(...) __attribute__ ((nothrow));
void _ssdm_op_SpecProcessDef(...) __attribute__ ((nothrow));
void _ssdm_op_SpecPort(...) __attribute__ ((nothrow));
void _ssdm_op_SpecConnection(...) __attribute__ ((nothrow));
void _ssdm_op_SpecChannel(...) __attribute__ ((nothrow));
void _ssdm_op_SpecSensitive(...) __attribute__ ((nothrow));
void _ssdm_op_SpecModuleInst(...) __attribute__ ((nothrow));
void _ssdm_op_SpecPortMap(...) __attribute__ ((nothrow));
void _ssdm_op_SpecReset(...) __attribute__ ((nothrow));
void _ssdm_op_SpecPlatform(...) __attribute__ ((nothrow));
void _ssdm_op_SpecClockDomain(...) __attribute__ ((nothrow));
void _ssdm_op_SpecPowerDomain(...) __attribute__ ((nothrow));
int _ssdm_op_SpecRegionBegin(...) __attribute__ ((nothrow));
int _ssdm_op_SpecRegionEnd(...) __attribute__ ((nothrow));
void _ssdm_op_SpecLoopName(...) __attribute__ ((nothrow));
void _ssdm_op_SpecLoopTripCount(...) __attribute__ ((nothrow));
int _ssdm_op_SpecStateBegin(...) __attribute__ ((nothrow));
int _ssdm_op_SpecStateEnd(...) __attribute__ ((nothrow));
void _ssdm_op_SpecInterface(...) __attribute__ ((nothrow));
void _ssdm_op_SpecPipeline(...) __attribute__ ((nothrow));
void _ssdm_op_SpecDataflowPipeline(...) __attribute__ ((nothrow));
void _ssdm_op_SpecLatency(...) __attribute__ ((nothrow));
void _ssdm_op_SpecParallel(...) __attribute__ ((nothrow));
void _ssdm_op_SpecProtocol(...) __attribute__ ((nothrow));
void _ssdm_op_SpecOccurrence(...) __attribute__ ((nothrow));
void _ssdm_op_SpecResource(...) __attribute__ ((nothrow));
void _ssdm_op_SpecResourceLimit(...) __attribute__ ((nothrow));
void _ssdm_op_SpecCHCore(...) __attribute__ ((nothrow));
void _ssdm_op_SpecFUCore(...) __attribute__ ((nothrow));
void _ssdm_op_SpecIFCore(...) __attribute__ ((nothrow));
void _ssdm_op_SpecIPCore(...) __attribute__ ((nothrow));
void _ssdm_op_SpecKeepValue(...) __attribute__ ((nothrow));
void _ssdm_op_SpecMemCore(...) __attribute__ ((nothrow));
void _ssdm_op_SpecExt(...) __attribute__ ((nothrow));
/*void* _ssdm_op_SpecProcess(...) SSDM_SPEC_ATTR;
void* _ssdm_op_SpecEdge(...) SSDM_SPEC_ATTR; */
/* Presynthesis directive functions */
void _ssdm_SpecArrayDimSize(...) __attribute__ ((nothrow));
void _ssdm_RegionBegin(...) __attribute__ ((nothrow));
void _ssdm_RegionEnd(...) __attribute__ ((nothrow));
void _ssdm_Unroll(...) __attribute__ ((nothrow));
void _ssdm_UnrollRegion(...) __attribute__ ((nothrow));
void _ssdm_InlineAll(...) __attribute__ ((nothrow));
void _ssdm_InlineLoop(...) __attribute__ ((nothrow));
void _ssdm_Inline(...) __attribute__ ((nothrow));
void _ssdm_InlineSelf(...) __attribute__ ((nothrow));
void _ssdm_InlineRegion(...) __attribute__ ((nothrow));
void _ssdm_SpecArrayMap(...) __attribute__ ((nothrow));
void _ssdm_SpecArrayPartition(...) __attribute__ ((nothrow));
void _ssdm_SpecArrayReshape(...) __attribute__ ((nothrow));
void _ssdm_SpecStream(...) __attribute__ ((nothrow));
void _ssdm_SpecExpr(...) __attribute__ ((nothrow));
void _ssdm_SpecExprBalance(...) __attribute__ ((nothrow));
void _ssdm_SpecDependence(...) __attribute__ ((nothrow));
void _ssdm_SpecLoopMerge(...) __attribute__ ((nothrow));
void _ssdm_SpecLoopFlatten(...) __attribute__ ((nothrow));
void _ssdm_SpecLoopRewind(...) __attribute__ ((nothrow));
void _ssdm_SpecFuncInstantiation(...) __attribute__ ((nothrow));
void _ssdm_SpecFuncBuffer(...) __attribute__ ((nothrow));
void _ssdm_SpecFuncExtract(...) __attribute__ ((nothrow));
void _ssdm_SpecConstant(...) __attribute__ ((nothrow));
void _ssdm_DataPack(...) __attribute__ ((nothrow));
void _ssdm_SpecDataPack(...) __attribute__ ((nothrow));
void _ssdm_op_SpecBitsMap(...) __attribute__ ((nothrow));
void _ssdm_op_SpecLicense(...) __attribute__ ((nothrow));
}
# 403 "/opt/Xilinx/Vivado_HLS/2015.1/common/technology/autopilot/etc/autopilot_ssdm_op.h"
/*#define _ssdm_op_WaitUntil(X) while (!(X)) _ssdm_op_Wait(1);
#define _ssdm_op_Delayed(X) X */
# 6 "<command line>" 2
# 1 "<built-in>" 2
# 1 "matrixmul.cpp" 2
/*******************************************************************************
Vendor: Xilinx
Associated Filename: matrixmul.cpp
Purpose: Vivado HLS tutorial example
Device: All
Revision History: March 1, 2013 - initial release
*******************************************************************************
Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
This file contains confidential and proprietary information of Xilinx, Inc. and
is protected under U.S. and international copyright and other intellectual
property laws.
DISCLAIMER
This disclaimer is not a license and does not grant any rights to the materials
distributed herewith. Except as otherwise provided in a valid license issued to
you by Xilinx, and to the maximum extent permitted by applicable law:
(1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND WITH ALL FAULTS, AND XILINX
HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT, OR
FITNESS FOR ANY PARTICULAR PURPOSE; and (2) Xilinx shall not be liable (whether
in contract or tort, including negligence, or under any other theory of
liability) for any loss or damage of any kind or nature related to, arising under
or in connection with these materials, including for any direct, or any indirect,
special, incidental, or consequential loss or damage (including loss of data,
profits, goodwill, or any type of loss or damage suffered as a result of any
action brought by a third party) even if such damage or loss was reasonably
foreseeable or Xilinx had been advised of the possibility of the same.
CRITICAL APPLICATIONS
Xilinx products are not designed or intended to be fail-safe, or for use in any
application requiring fail-safe performance, such as life-support or safety
devices or systems, Class III medical devices, nuclear facilities, applications
related to the deployment of airbags, or any other applications that could lead
to death, personal injury, or severe property or environmental damage
(individually and collectively, "Critical Applications"). Customer asresultes the
sole risk and liability of any use of Xilinx products in Critical Applications,
subject only to applicable laws and regulations governing limitations on product
liability.
THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS PART OF THIS FILE AT
ALL TIMES.
*******************************************************************************/
# 1 "./matrixmul.h" 1
/*******************************************************************************
Vendor: Xilinx
Associated Filename: matrixmul.h
Purpose: Vivado HLS tutorial example
Device: All
Revision History: March 1, 2013 - initial release
*******************************************************************************
Copyright 2008 - 2013 Xilinx, Inc. All rights reserved.
This file contains confidential and proprietary information of Xilinx, Inc. and
is protected under U.S. and international copyright and other intellectual
property laws.
DISCLAIMER
This disclaimer is not a license and does not grant any rights to the materials
distributed herewith. Except as otherwise provided in a valid license issued to
you by Xilinx, and to the maximum extent permitted by applicable law:
(1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND WITH ALL FAULTS, AND XILINX
HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT, OR
FITNESS FOR ANY PARTICULAR PURPOSE; and (2) Xilinx shall not be liable (whether
in contract or tort, including negligence, or under any other theory of
liability) for any loss or damage of any kind or nature related to, arising under
or in connection with these materials, including for any direct, or any indirect,
special, incidental, or consequential loss or damage (including loss of data,
profits, goodwill, or any type of loss or damage suffered as a result of any
action brought by a third party) even if such damage or loss was reasonably
foreseeable or Xilinx had been advised of the possibility of the same.
CRITICAL APPLICATIONS
Xilinx products are not designed or intended to be fail-safe, or for use in any
application requiring fail-safe performance, such as life-support or safety
devices or systems, Class III medical devices, nuclear facilities, applications
related to the deployment of airbags, or any other applications that could lead
to death, personal injury, or severe property or environmental damage
(individually and collectively, "Critical Applications"). Customer asresultes the
sole risk and liability of any use of Xilinx products in Critical Applications,
subject only to applicable laws and regulations governing limitations on product
liability.
THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS PART OF THIS FILE AT
ALL TIMES.
*******************************************************************************/
# 1 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 1 3
// -*- C++ -*- C forwarding header.
// Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
// 2006, 2007, 2008, 2009, 2010, 2011
// Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file include/cmath
* This is a Standard C++ Library file. You should @c \#include this file
* in your programs, rather than any of the @a *.h implementation files.
*
* This is the C++ version of the Standard C Library header @c math.h,
* and its contents are (mostly) the same as that header, but are all
* contained in the namespace @c std (except for names which are defined
* as macros in C).
*/
//
// ISO C++ 14882: 26.5 C library
//
# 41 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 3
# 1 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/c++config.h" 1 3
// Predefined symbols and macros -*- C++ -*-
// Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
// 2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file bits/c++config.h
* This is an internal header file, included by other library headers.
* Do not attempt to use it directly. @headername{iosfwd}
*/
// The current version of the C++ library in compressed ISO date format.
// Macros for various attributes.
// _GLIBCXX_PURE
// _GLIBCXX_CONST
// _GLIBCXX_NORETURN
// _GLIBCXX_NOTHROW
// _GLIBCXX_VISIBILITY
# 63 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/c++config.h" 3
// Macros for visibility attributes.
// _GLIBCXX_HAVE_ATTRIBUTE_VISIBILITY
// _GLIBCXX_VISIBILITY
# 76 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/c++config.h" 3
// Macros for deprecated attributes.
// _GLIBCXX_USE_DEPRECATED
// _GLIBCXX_DEPRECATED
# 91 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/c++config.h" 3
// Macro for constexpr, to support in mixed 03/0x mode.
# 102 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/c++config.h" 3
// Macro for extern template, ie controling template linkage via use
// of extern keyword on template declaration. As documented in the g++
// manual, it inhibits all implicit instantiations and is used
// throughout the library to avoid multiple weak definitions for
// required types that are already explicitly instantiated in the
// library binary. This substantially reduces the binary size of
// resulting executables.
// Special case: _GLIBCXX_EXTERN_TEMPLATE == -1 disallows extern
// templates only in basic_string, thus activating its debug-mode
// checks even at -O0.
/*
Outline of libstdc++ namespaces.
namespace std
{
namespace __debug { }
namespace __parallel { }
namespace __profile { }
namespace __cxx1998 { }
namespace __detail { }
namespace rel_ops { }
namespace tr1
{
namespace placeholders { }
namespace regex_constants { }
namespace __detail { }
}
namespace decimal { }
namespace chrono { }
namespace placeholders { }
namespace regex_constants { }
namespace this_thread { }
}
namespace abi { }
namespace __gnu_cxx
{
namespace __detail { }
}
For full details see:
http://gcc.gnu.org/onlinedocs/libstdc++/latest-doxygen/namespaces.html
*/
namespace std
{
typedef long unsigned int size_t;
typedef long int ptrdiff_t;
}
// Defined if inline namespaces are used for versioning.
// Inline namespace for symbol versioning.
# 208 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/c++config.h" 3
// Inline namespaces for special modes: debug, parallel, profile.
# 255 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/c++config.h" 3
// Macros for namespace scope. Either namespace std:: or the name
// of some nested namespace within it corresponding to the active mode.
// _GLIBCXX_STD_A
// _GLIBCXX_STD_C
//
// Macros for opening/closing conditional namespaces.
// _GLIBCXX_BEGIN_NAMESPACE_ALGO
// _GLIBCXX_END_NAMESPACE_ALGO
// _GLIBCXX_BEGIN_NAMESPACE_CONTAINER
// _GLIBCXX_END_NAMESPACE_CONTAINER
# 307 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/c++config.h" 3
// GLIBCXX_ABI Deprecated
// Define if compatibility should be provided for -mlong-double-64.
// Inline namespace for long double 128 mode.
# 326 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/c++config.h" 3
// Assert.
# 352 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/c++config.h" 3
// Macros for race detectors.
// _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(A) and
// _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(A) should be used to explain
// atomic (lock-free) synchronization to race detectors:
// the race detector will infer a happens-before arc from the former to the
// latter when they share the same argument pointer.
//
// The most frequent use case for these macros (and the only case in the
// current implementation of the library) is atomic reference counting:
// void _M_remove_reference()
// {
// _GLIBCXX_SYNCHRONIZATION_HAPPENS_BEFORE(&this->_M_refcount);
// if (__gnu_cxx::__exchange_and_add_dispatch(&this->_M_refcount, -1) <= 0)
// {
// _GLIBCXX_SYNCHRONIZATION_HAPPENS_AFTER(&this->_M_refcount);
// _M_destroy(__a);
// }
// }
// The annotations in this example tell the race detector that all memory
// accesses occurred when the refcount was positive do not race with
// memory accesses which occurred after the refcount became zero.
// Macros for C linkage: define extern "C" linkage only when using C++.
# 390 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/c++config.h" 3
// First includes.
// Pick up any OS-specific definitions.
# 1 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/os_defines.h" 1 3
// Specific definitions for GNU/Linux -*- C++ -*-
// Copyright (C) 2000, 2001, 2002, 2003, 2009, 2010
// Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file bits/os_defines.h
* This is an internal header file, included by other library headers.
* Do not attempt to use it directly. @headername{iosfwd}
*/
// System-specific #define, typedefs, corrections, etc, go here. This
// file will come before all others.
// This keeps isanum, et al from being propagated as macros.
# 1 "/usr/include/features.h" 1 3 4
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* These are defined by the user (or the compiler)
to specify the desired environment:
__STRICT_ANSI__ ISO Standard C.
_ISOC99_SOURCE Extensions to ISO C89 from ISO C99.
_ISOC11_SOURCE Extensions to ISO C99 from ISO C11.
_POSIX_SOURCE IEEE Std 1003.1.
_POSIX_C_SOURCE If ==1, like _POSIX_SOURCE; if >=2 add IEEE Std 1003.2;
if >=199309L, add IEEE Std 1003.1b-1993;
if >=199506L, add IEEE Std 1003.1c-1995;
if >=200112L, all of IEEE 1003.1-2004
if >=200809L, all of IEEE 1003.1-2008
_XOPEN_SOURCE Includes POSIX and XPG things. Set to 500 if
Single Unix conformance is wanted, to 600 for the
sixth revision, to 700 for the seventh revision.
_XOPEN_SOURCE_EXTENDED XPG things and X/Open Unix extensions.
_LARGEFILE_SOURCE Some more functions for correct standard I/O.
_LARGEFILE64_SOURCE Additional functionality from LFS for large files.
_FILE_OFFSET_BITS=N Select default filesystem interface.
_BSD_SOURCE ISO C, POSIX, and 4.3BSD things.
_SVID_SOURCE ISO C, POSIX, and SVID things.
_ATFILE_SOURCE Additional *at interfaces.
_GNU_SOURCE All of the above, plus GNU extensions.
_DEFAULT_SOURCE The default set of features (taking precedence over
__STRICT_ANSI__).
_REENTRANT Select additionally reentrant object.
_THREAD_SAFE Same as _REENTRANT, often used by other systems.
_FORTIFY_SOURCE If set to numeric value > 0 additional security
measures are defined, according to level.
The `-ansi' switch to the GNU C compiler, and standards conformance
options such as `-std=c99', define __STRICT_ANSI__. If none of
these are defined, or if _DEFAULT_SOURCE is defined, the default is
to have _SVID_SOURCE, _BSD_SOURCE, and _POSIX_SOURCE set to one and
_POSIX_C_SOURCE set to 200809L. If more than one of these are
defined, they accumulate. For example __STRICT_ANSI__,
_POSIX_SOURCE and _POSIX_C_SOURCE together give you ISO C, 1003.1,
and 1003.2, but nothing else.
These are defined by this file and are used by the
header files to decide what to declare or define:
__USE_ISOC11 Define ISO C11 things.
__USE_ISOC99 Define ISO C99 things.
__USE_ISOC95 Define ISO C90 AMD1 (C95) things.
__USE_POSIX Define IEEE Std 1003.1 things.
__USE_POSIX2 Define IEEE Std 1003.2 things.
__USE_POSIX199309 Define IEEE Std 1003.1, and .1b things.
__USE_POSIX199506 Define IEEE Std 1003.1, .1b, .1c and .1i things.
__USE_XOPEN Define XPG things.
__USE_XOPEN_EXTENDED Define X/Open Unix things.
__USE_UNIX98 Define Single Unix V2 things.
__USE_XOPEN2K Define XPG6 things.
__USE_XOPEN2KXSI Define XPG6 XSI things.
__USE_XOPEN2K8 Define XPG7 things.
__USE_XOPEN2K8XSI Define XPG7 XSI things.
__USE_LARGEFILE Define correct standard I/O things.
__USE_LARGEFILE64 Define LFS things with separate names.
__USE_FILE_OFFSET64 Define 64bit interface as default.
__USE_BSD Define 4.3BSD things.
__USE_SVID Define SVID things.
__USE_MISC Define things common to BSD and System V Unix.
__USE_ATFILE Define *at interfaces and AT_* constants for them.
__USE_GNU Define GNU extensions.
__USE_REENTRANT Define reentrant/thread-safe *_r functions.
__USE_FORTIFY_LEVEL Additional security measures used, according to level.
The macros `__GNU_LIBRARY__', `__GLIBC__', and `__GLIBC_MINOR__' are
defined by this file unconditionally. `__GNU_LIBRARY__' is provided
only for compatibility. All new code should use the other symbols
to test for features.
All macros listed above as possibly being defined by this file are
explicitly undefined if they are not explicitly defined.
Feature-test macros that are not defined by the user or compiler
but are implied by the other feature-test macros defined (or by the
lack of any definitions) are defined by the file. */
/* Undefine everything, so we get a clean slate. */
# 128 "/usr/include/features.h" 3 4
/* Suppress kernel-name space pollution unless user expressedly asks
for it. */
/* Convenience macros to test the versions of glibc and gcc.
Use them like this:
#if __GNUC_PREREQ (2,8)
... code requiring gcc 2.8 or later ...
#endif
Note - they won't work for gcc1 or glibc1, since the _MINOR macros
were not defined then. */
# 149 "/usr/include/features.h" 3 4
/* If _GNU_SOURCE was defined by the user, turn on all the other features. */
# 177 "/usr/include/features.h" 3 4
/* If nothing (other than _GNU_SOURCE and _DEFAULT_SOURCE) is defined,
define _DEFAULT_SOURCE, _BSD_SOURCE and _SVID_SOURCE. */
# 193 "/usr/include/features.h" 3 4
/* This is to enable the ISO C11 extension. */
/* This is to enable the ISO C99 extension. */
/* This is to enable the ISO C90 Amendment 1:1995 extension. */
/* This is to enable compatibility for ISO C++11.
So far g++ does not provide a macro. Check the temporary macro for
now, too. */
/* If none of the ANSI/POSIX macros are defined, or if _DEFAULT_SOURCE
is defined, use POSIX.1-2008 (or another version depending on
_XOPEN_SOURCE). */
# 350 "/usr/include/features.h" 3 4
/* Get definitions of __STDC_* predefined macros, if the compiler has
not preincluded this header automatically. */
# 1 "/usr/include/stdc-predef.h" 1 3 4
/* Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* This header is separate from features.h so that the compiler can
include it implicitly at the start of every compilation. It must
not itself include <features.h> or any other header that includes
<features.h> because the implicit include comes before any feature
test macros that may be defined in a source file before it first
explicitly includes a system header. GCC knows the name of this
header in order to preinclude it. */
/* glibc's intent is to support the IEC 559 math functionality, real
and complex. If the GCC (4.9 and later) predefined macros
specifying compiler intent are available, use them to determine
whether the overall intent is to support these features; otherwise,
presume an older compiler has intent to support these features and
define these macros by default. */
# 52 "/usr/include/stdc-predef.h" 3 4
/* wchar_t uses ISO/IEC 10646 (2nd ed., published 2011-03-15) /
Unicode 6.0. */
/* We do not support C11 <threads.h>. */
# 353 "/usr/include/features.h" 2 3 4
/* This macro indicates that the installed library is the GNU C Library.
For historic reasons the value now is 6 and this will stay from now
on. The use of this variable is deprecated. Use __GLIBC__ and
__GLIBC_MINOR__ now (see below) when you want to test for a specific
GNU C library version and use the values in <gnu/lib-names.h> to get
the sonames of the shared libraries. */
/* Major and minor version number of the GNU C library package. Use
these macros to test for features in specific releases. */
/* This is here only because every header file already includes this one. */
# 1 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 1 3 4
/* Copyright (C) 1992-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* We are almost always included from features.h. */
/* The GNU libc does not support any K&R compilers or the traditional mode
of ISO C compilers anymore. Check for some of the combinations not
anymore supported. */
/* Some user header file might have defined this before. */
/* All functions, except those with callbacks or those that
synchronize memory, are leaf functions. */
# 49 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4
/* GCC can always grok prototypes. For C++ programs we add throw()
to help it optimize the function calls. But this works only with
gcc 2.8.x and egcs. For gcc 3.2 and up we even mark C functions
as non-throwing using a function attribute since programs can use
the -fexceptions options for C code as well. */
# 80 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4
/* These two macros are not used in glibc anymore. They are kept here
only because some other projects expect the macros to be defined. */
/* For these things, GCC behaves the ANSI way normally,
and the non-ANSI way under -traditional. */
/* This is not a typedef so `const __ptr_t' does the right thing. */
/* C++ needs to know that types and declarations are C, not C++. */
# 106 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4
/* The standard library needs the functions from the ISO C90 standard
in the std namespace. At the same time we want to be safe for
future changes and we include the ISO C99 code in the non-standard
namespace __c99. The C++ wrapper header take case of adding the
definitions to the global namespace. */
# 119 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4
/* For compatibility we do not add the declarations into any
namespace. They will end up in the global namespace which is what
old code expects. */
# 131 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4
/* Fortify support. */
# 148 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4
/* Support for flexible arrays. */
/* GCC 2.97 supports C99 flexible array members. */
# 166 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4
/* __asm__ ("xyz") is used throughout the headers to rename functions
at the assembly language level. This is wrapped by the __REDIRECT
macro, in order to support compilers that can do this some other
way. When compilers don't support asm-names at all, we have to do
preprocessor tricks instead (which don't have exactly the right
semantics, but it's the best we can do).
Example:
int __REDIRECT(setpgrp, (__pid_t pid, __pid_t pgrp), setpgid); */
# 193 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4
/*
#elif __SOME_OTHER_COMPILER__
# define __REDIRECT(name, proto, alias) name proto; \
_Pragma("let " #name " = " #alias)
*/
/* GCC has various useful declarations that can be made with the
`__attribute__' syntax. All of the ways we use this do fine if
they are omitted for compilers that don't understand it. */
/* At some point during the gcc 2.96 development the `malloc' attribute
for functions was introduced. We don't want to use it unconditionally
(although this would be possible) since it generates warnings. */
/* Tell the compiler which arguments to an allocation function
indicate the size of the allocation. */
/* At some point during the gcc 2.96 development the `pure' attribute
for functions was introduced. We don't want to use it unconditionally
(although this would be possible) since it generates warnings. */
/* This declaration tells the compiler that the value is constant. */
/* At some point during the gcc 3.1 development the `used' attribute
for functions was introduced. We don't want to use it unconditionally
(although this would be possible) since it generates warnings. */
# 253 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4
/* gcc allows marking deprecated functions. */
/* At some point during the gcc 2.8 development the `format_arg' attribute
for functions was introduced. We don't want to use it unconditionally
(although this would be possible) since it generates warnings.
If several `format_arg' attributes are given for the same function, in
gcc-3.0 and older, all but the last one are ignored. In newer gccs,
all designated arguments are considered. */
/* At some point during the gcc 2.97 development the `strfmon' format
attribute for functions was introduced. We don't want to use it
unconditionally (although this would be possible) since it
generates warnings. */
/* The nonull function attribute allows to mark pointer parameters which
must not be NULL. */
/* If fortification mode, we warn about unused results of certain
function calls which can lead to problems. */
# 306 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4
/* Forces a function to be always inlined. */
/* Associate error messages with the source location of the call site rather
than with the source location inside the function. */
/* One of these will be defined if the __gnu_inline__ attribute is
available. In C++, __GNUC_GNU_INLINE__ will be defined even though
__inline does not use the GNU inlining rules. If neither macro is
defined, this version of GCC only supports GNU inline semantics. */
# 339 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4
/* GCC 4.3 and above allow passing all anonymous arguments of an
__extern_always_inline function to some other vararg function. */
/* It is possible to compile containing GCC extensions even if GCC is
run in pedantic mode if the uses are carefully marked using the
`__extension__' keyword. But this is not generally available before
version 2.8. */
/* __restrict is known in EGCS 1.2 and above. */
/* ISO C99 also allows to declare arrays as non-overlapping. The syntax is
array_name[restrict]
GCC 3.1 supports this. */
# 385 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4
/* Determine the wordsize from the preprocessor defines. */
# 11 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 3 4
/* Both x86-64 and x32 use the 64-bit system call interface. */
# 386 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 2 3 4
# 375 "/usr/include/features.h" 2 3 4
/* If we don't have __REDIRECT, prototypes will be missing if
__USE_FILE_OFFSET64 but not __USE_LARGEFILE[64]. */
/* Decide whether we can define 'extern inline' functions in headers. */
/* This is here only because every header file already includes this one.
Get the definitions of all the appropriate `__stub_FUNCTION' symbols.
<gnu/stubs.h> contains `#define __stub_FUNCTION' when FUNCTION is a stub
that will always return failure (and set errno to ENOSYS). */
# 1 "/usr/include/x86_64-linux-gnu/gnu/stubs.h" 1 3 4
/* This file is automatically generated.
This file selects the right generated file of `__stub_FUNCTION' macros
based on the architecture being compiled for. */
# 1 "/usr/include/x86_64-linux-gnu/gnu/stubs-64.h" 1 3 4
/* This file is automatically generated.
It defines a symbol `__stub_FUNCTION' for each function
in the C library which is a stub, meaning it will fail
every time called, usually setting errno to ENOSYS. */
# 11 "/usr/include/x86_64-linux-gnu/gnu/stubs.h" 2 3 4
# 399 "/usr/include/features.h" 2 3 4
# 41 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/os_defines.h" 2 3
# 394 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/c++config.h" 2 3
// Pick up any CPU-specific definitions.
# 1 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/cpu_defines.h" 1 3
// Specific definitions for generic platforms -*- C++ -*-
// Copyright (C) 2005, 2009, 2010 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file bits/cpu_defines.h
* This is an internal header file, included by other library headers.
* Do not attempt to use it directly. @headername{iosfwd}
*/
# 397 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/x86_64-unknown-linux-gnu/bits/c++config.h" 2 3
// If platform uses neither visibility nor psuedo-visibility,
// specify empty default for namespace annotation macros.
// Certain function definitions that are meant to be overridable from
// user code are decorated with this macro. For some targets, this
// macro causes these definitions to be weak.
// The remainder of the prewritten config is automatic; all the
// user hooks are listed above.
// Create a boolean flag to be used to determine if --fast-math is set.
// This marks string literals in header files to be extracted for eventual
// translation. It is primarily used for messages in thrown exceptions; see
// src/functexcept.cc. We use __N because the more traditional _N is used
// for something else under certain OSes (see BADNAMES).
// For example, <windows.h> is known to #define min and max as macros...
// End of prewritten config; the settings discovered at configure time follow.
/* config.h. Generated from config.h.in by configure. */
/* config.h.in. Generated from configure.ac by autoheader. */
/* Define to 1 if you have the `acosf' function. */
/* Define to 1 if you have the `acosl' function. */
/* Define to 1 if you have the `asinf' function. */
/* Define to 1 if you have the `asinl' function. */
/* Define to 1 if the target assembler supports .symver directive. */
/* Define to 1 if you have the `atan2f' function. */
/* Define to 1 if you have the `atan2l' function. */
/* Define to 1 if you have the `atanf' function. */
/* Define to 1 if you have the `atanl' function. */
/* Define to 1 if the target assembler supports thread-local storage. */
/* #undef _GLIBCXX_HAVE_CC_TLS */
/* Define to 1 if you have the `ceilf' function. */
/* Define to 1 if you have the `ceill' function. */
/* Define to 1 if you have the <complex.h> header file. */
/* Define to 1 if you have the `cosf' function. */
/* Define to 1 if you have the `coshf' function. */
/* Define to 1 if you have the `coshl' function. */
/* Define to 1 if you have the `cosl' function. */
/* Define to 1 if you have the <dlfcn.h> header file. */
/* Define if EBADMSG exists. */
/* Define if ECANCELED exists. */
/* Define if EIDRM exists. */
/* Define to 1 if you have the <endian.h> header file. */
/* Define if ENODATA exists. */
/* Define if ENOLINK exists. */
/* Define if ENOSR exists. */
/* Define if ENOSTR exists. */
/* Define if ENOTRECOVERABLE exists. */
/* Define if ENOTSUP exists. */
/* Define if EOVERFLOW exists. */
/* Define if EOWNERDEAD exists. */
/* Define if EPROTO exists. */
/* Define if ETIME exists. */
/* Define if ETXTBSY exists. */
/* Define to 1 if you have the <execinfo.h> header file. */
/* Define to 1 if you have the `expf' function. */
/* Define to 1 if you have the `expl' function. */
/* Define to 1 if you have the `fabsf' function. */
/* Define to 1 if you have the `fabsl' function. */
/* Define to 1 if you have the <fenv.h> header file. */
/* Define to 1 if you have the `finite' function. */
/* Define to 1 if you have the `finitef' function. */
/* Define to 1 if you have the `finitel' function. */
/* Define to 1 if you have the <float.h> header file. */
/* Define to 1 if you have the `floorf' function. */
/* Define to 1 if you have the `floorl' function. */
/* Define to 1 if you have the `fmodf' function. */
/* Define to 1 if you have the `fmodl' function. */
/* Define to 1 if you have the `fpclass' function. */
/* #undef _GLIBCXX_HAVE_FPCLASS */
/* Define to 1 if you have the <fp.h> header file. */
/* #undef _GLIBCXX_HAVE_FP_H */
/* Define to 1 if you have the `frexpf' function. */
/* Define to 1 if you have the `frexpl' function. */
/* Define if _Unwind_GetIPInfo is available. */
/* Define if gthr-default.h exists (meaning that threading support is
enabled). */
/* Define to 1 if you have the `hypot' function. */
/* Define to 1 if you have the `hypotf' function. */
/* Define to 1 if you have the `hypotl' function. */
/* Define if you have the iconv() function. */
/* Define to 1 if you have the <ieeefp.h> header file. */
/* #undef _GLIBCXX_HAVE_IEEEFP_H */
/* Define if int64_t is available in <stdint.h>. */
/* Define if int64_t is a long. */
/* Define if int64_t is a long long. */
/* #undef _GLIBCXX_HAVE_INT64_T_LONG_LONG */
/* Define to 1 if you have the <inttypes.h> header file. */
/* Define to 1 if you have the `isinf' function. */
/* Define to 1 if you have the `isinff' function. */
/* Define to 1 if you have the `isinfl' function. */
/* Define to 1 if you have the `isnan' function. */
/* Define to 1 if you have the `isnanf' function. */
/* Define to 1 if you have the `isnanl' function. */
/* Defined if iswblank exists. */
/* Define if LC_MESSAGES is available in <locale.h>. */
/* Define to 1 if you have the `ldexpf' function. */
/* Define to 1 if you have the `ldexpl' function. */
/* Define to 1 if you have the <libintl.h> header file. */
/* Only used in build directory testsuite_hooks.h. */
/* Only used in build directory testsuite_hooks.h. */
/* Only used in build directory testsuite_hooks.h. */
/* Only used in build directory testsuite_hooks.h. */
/* Only used in build directory testsuite_hooks.h. */
/* Define if futex syscall is available. */
/* Define to 1 if you have the <locale.h> header file. */
/* Define to 1 if you have the `log10f' function. */
/* Define to 1 if you have the `log10l' function. */
/* Define to 1 if you have the `logf' function. */
/* Define to 1 if you have the `logl' function. */
/* Define to 1 if you have the <machine/endian.h> header file. */
/* #undef _GLIBCXX_HAVE_MACHINE_ENDIAN_H */
/* Define to 1 if you have the <machine/param.h> header file. */
/* #undef _GLIBCXX_HAVE_MACHINE_PARAM_H */
/* Define if mbstate_t exists in wchar.h. */
/* Define to 1 if you have the <memory.h> header file. */
/* Define to 1 if you have the `modf' function. */
/* Define to 1 if you have the `modff' function. */
/* Define to 1 if you have the `modfl' function. */
/* Define to 1 if you have the <nan.h> header file. */
/* #undef _GLIBCXX_HAVE_NAN_H */
/* Define if poll is available in <poll.h>. */
/* Define to 1 if you have the `powf' function. */
/* Define to 1 if you have the `powl' function. */
/* Define to 1 if you have the `qfpclass' function. */
/* #undef _GLIBCXX_HAVE_QFPCLASS */
/* Define to 1 if you have the `setenv' function. */
/* Define to 1 if you have the `sincos' function. */
/* Define to 1 if you have the `sincosf' function. */
/* Define to 1 if you have the `sincosl' function. */
/* Define to 1 if you have the `sinf' function. */
/* Define to 1 if you have the `sinhf' function. */
/* Define to 1 if you have the `sinhl' function. */
/* Define to 1 if you have the `sinl' function. */
/* Define to 1 if you have the `sqrtf' function. */
/* Define to 1 if you have the `sqrtl' function. */
/* Define to 1 if you have the <stdbool.h> header file. */
/* Define to 1 if you have the <stdint.h> header file. */
/* Define to 1 if you have the <stdlib.h> header file. */
/* Define if strerror_l is available in <string.h>. */
/* #undef _GLIBCXX_HAVE_STRERROR_L */
/* Define if strerror_r is available in <string.h>. */
/* Define to 1 if you have the <strings.h> header file. */
/* Define to 1 if you have the <string.h> header file. */
/* Define to 1 if you have the `strtof' function. */
/* Define to 1 if you have the `strtold' function. */
/* Define if strxfrm_l is available in <string.h>. */
/* Define to 1 if the target runtime linker supports binding the same symbol
to different versions. */
/* Define to 1 if you have the <sys/filio.h> header file. */
/* #undef _GLIBCXX_HAVE_SYS_FILIO_H */
/* Define to 1 if you have the <sys/ioctl.h> header file. */
/* Define to 1 if you have the <sys/ipc.h> header file. */
/* Define to 1 if you have the <sys/isa_defs.h> header file. */
/* #undef _GLIBCXX_HAVE_SYS_ISA_DEFS_H */
/* Define to 1 if you have the <sys/machine.h> header file. */
/* #undef _GLIBCXX_HAVE_SYS_MACHINE_H */
/* Define to 1 if you have the <sys/param.h> header file. */
/* Define to 1 if you have the <sys/resource.h> header file. */
/* Define to 1 if you have the <sys/sem.h> header file. */
/* Define to 1 if you have the <sys/stat.h> header file. */
/* Define to 1 if you have the <sys/time.h> header file. */
/* Define to 1 if you have the <sys/types.h> header file. */
/* Define to 1 if you have the <sys/uio.h> header file. */
/* Define if S_IFREG is available in <sys/stat.h>. */
/* #undef _GLIBCXX_HAVE_S_IFREG */
/* Define if S_IFREG is available in <sys/stat.h>. */
/* Define to 1 if you have the `tanf' function. */
/* Define to 1 if you have the `tanhf' function. */
/* Define to 1 if you have the `tanhl' function. */
/* Define to 1 if you have the `tanl' function. */
/* Define to 1 if you have the <tgmath.h> header file. */
/* Define to 1 if the target supports thread-local storage. */
/* Define to 1 if you have the <unistd.h> header file. */
/* Defined if vfwscanf exists. */
/* Defined if vswscanf exists. */
/* Defined if vwscanf exists. */
/* Define to 1 if you have the <wchar.h> header file. */
/* Defined if wcstof exists. */
/* Define to 1 if you have the <wctype.h> header file. */
/* Define if writev is available in <sys/uio.h>. */
/* Define to 1 if you have the `_acosf' function. */
/* #undef _GLIBCXX_HAVE__ACOSF */
/* Define to 1 if you have the `_acosl' function. */
/* #undef _GLIBCXX_HAVE__ACOSL */
/* Define to 1 if you have the `_asinf' function. */
/* #undef _GLIBCXX_HAVE__ASINF */
/* Define to 1 if you have the `_asinl' function. */
/* #undef _GLIBCXX_HAVE__ASINL */
/* Define to 1 if you have the `_atan2f' function. */
/* #undef _GLIBCXX_HAVE__ATAN2F */
/* Define to 1 if you have the `_atan2l' function. */
/* #undef _GLIBCXX_HAVE__ATAN2L */
/* Define to 1 if you have the `_atanf' function. */
/* #undef _GLIBCXX_HAVE__ATANF */
/* Define to 1 if you have the `_atanl' function. */
/* #undef _GLIBCXX_HAVE__ATANL */
/* Define to 1 if you have the `_ceilf' function. */
/* #undef _GLIBCXX_HAVE__CEILF */
/* Define to 1 if you have the `_ceill' function. */
/* #undef _GLIBCXX_HAVE__CEILL */
/* Define to 1 if you have the `_cosf' function. */
/* #undef _GLIBCXX_HAVE__COSF */
/* Define to 1 if you have the `_coshf' function. */
/* #undef _GLIBCXX_HAVE__COSHF */
/* Define to 1 if you have the `_coshl' function. */
/* #undef _GLIBCXX_HAVE__COSHL */
/* Define to 1 if you have the `_cosl' function. */
/* #undef _GLIBCXX_HAVE__COSL */
/* Define to 1 if you have the `_expf' function. */
/* #undef _GLIBCXX_HAVE__EXPF */
/* Define to 1 if you have the `_expl' function. */
/* #undef _GLIBCXX_HAVE__EXPL */
/* Define to 1 if you have the `_fabsf' function. */
/* #undef _GLIBCXX_HAVE__FABSF */
/* Define to 1 if you have the `_fabsl' function. */
/* #undef _GLIBCXX_HAVE__FABSL */
/* Define to 1 if you have the `_finite' function. */
/* #undef _GLIBCXX_HAVE__FINITE */
/* Define to 1 if you have the `_finitef' function. */
/* #undef _GLIBCXX_HAVE__FINITEF */
/* Define to 1 if you have the `_finitel' function. */
/* #undef _GLIBCXX_HAVE__FINITEL */
/* Define to 1 if you have the `_floorf' function. */
/* #undef _GLIBCXX_HAVE__FLOORF */
/* Define to 1 if you have the `_floorl' function. */
/* #undef _GLIBCXX_HAVE__FLOORL */
/* Define to 1 if you have the `_fmodf' function. */
/* #undef _GLIBCXX_HAVE__FMODF */
/* Define to 1 if you have the `_fmodl' function. */
/* #undef _GLIBCXX_HAVE__FMODL */
/* Define to 1 if you have the `_fpclass' function. */
/* #undef _GLIBCXX_HAVE__FPCLASS */
/* Define to 1 if you have the `_frexpf' function. */
/* #undef _GLIBCXX_HAVE__FREXPF */
/* Define to 1 if you have the `_frexpl' function. */
/* #undef _GLIBCXX_HAVE__FREXPL */
/* Define to 1 if you have the `_hypot' function. */
/* #undef _GLIBCXX_HAVE__HYPOT */
/* Define to 1 if you have the `_hypotf' function. */
/* #undef _GLIBCXX_HAVE__HYPOTF */
/* Define to 1 if you have the `_hypotl' function. */
/* #undef _GLIBCXX_HAVE__HYPOTL */
/* Define to 1 if you have the `_isinf' function. */
/* #undef _GLIBCXX_HAVE__ISINF */
/* Define to 1 if you have the `_isinff' function. */
/* #undef _GLIBCXX_HAVE__ISINFF */
/* Define to 1 if you have the `_isinfl' function. */
/* #undef _GLIBCXX_HAVE__ISINFL */
/* Define to 1 if you have the `_isnan' function. */
/* #undef _GLIBCXX_HAVE__ISNAN */
/* Define to 1 if you have the `_isnanf' function. */
/* #undef _GLIBCXX_HAVE__ISNANF */
/* Define to 1 if you have the `_isnanl' function. */
/* #undef _GLIBCXX_HAVE__ISNANL */
/* Define to 1 if you have the `_ldexpf' function. */
/* #undef _GLIBCXX_HAVE__LDEXPF */
/* Define to 1 if you have the `_ldexpl' function. */
/* #undef _GLIBCXX_HAVE__LDEXPL */
/* Define to 1 if you have the `_log10f' function. */
/* #undef _GLIBCXX_HAVE__LOG10F */
/* Define to 1 if you have the `_log10l' function. */
/* #undef _GLIBCXX_HAVE__LOG10L */
/* Define to 1 if you have the `_logf' function. */
/* #undef _GLIBCXX_HAVE__LOGF */
/* Define to 1 if you have the `_logl' function. */
/* #undef _GLIBCXX_HAVE__LOGL */
/* Define to 1 if you have the `_modf' function. */
/* #undef _GLIBCXX_HAVE__MODF */
/* Define to 1 if you have the `_modff' function. */
/* #undef _GLIBCXX_HAVE__MODFF */
/* Define to 1 if you have the `_modfl' function. */
/* #undef _GLIBCXX_HAVE__MODFL */
/* Define to 1 if you have the `_powf' function. */
/* #undef _GLIBCXX_HAVE__POWF */
/* Define to 1 if you have the `_powl' function. */
/* #undef _GLIBCXX_HAVE__POWL */
/* Define to 1 if you have the `_qfpclass' function. */
/* #undef _GLIBCXX_HAVE__QFPCLASS */
/* Define to 1 if you have the `_sincos' function. */
/* #undef _GLIBCXX_HAVE__SINCOS */
/* Define to 1 if you have the `_sincosf' function. */
/* #undef _GLIBCXX_HAVE__SINCOSF */
/* Define to 1 if you have the `_sincosl' function. */
/* #undef _GLIBCXX_HAVE__SINCOSL */
/* Define to 1 if you have the `_sinf' function. */
/* #undef _GLIBCXX_HAVE__SINF */
/* Define to 1 if you have the `_sinhf' function. */
/* #undef _GLIBCXX_HAVE__SINHF */
/* Define to 1 if you have the `_sinhl' function. */
/* #undef _GLIBCXX_HAVE__SINHL */
/* Define to 1 if you have the `_sinl' function. */
/* #undef _GLIBCXX_HAVE__SINL */
/* Define to 1 if you have the `_sqrtf' function. */
/* #undef _GLIBCXX_HAVE__SQRTF */
/* Define to 1 if you have the `_sqrtl' function. */
/* #undef _GLIBCXX_HAVE__SQRTL */
/* Define to 1 if you have the `_tanf' function. */
/* #undef _GLIBCXX_HAVE__TANF */
/* Define to 1 if you have the `_tanhf' function. */
/* #undef _GLIBCXX_HAVE__TANHF */
/* Define to 1 if you have the `_tanhl' function. */
/* #undef _GLIBCXX_HAVE__TANHL */
/* Define to 1 if you have the `_tanl' function. */
/* #undef _GLIBCXX_HAVE__TANL */
/* Define as const if the declaration of iconv() needs const. */
/* Define to the sub-directory in which libtool stores uninstalled libraries.
*/
/* Name of package */
/* #undef _GLIBCXX_PACKAGE */
/* Define to the address where bug reports for this package should be sent. */
/* Define to the full name of this package. */
/* Define to the full name and version of this package. */
/* Define to the one symbol short name of this package. */
/* Define to the home page for this package. */
/* Define to the version of this package. */
/* The size of `char', as computed by sizeof. */
/* #undef SIZEOF_CHAR */
/* The size of `int', as computed by sizeof. */
/* #undef SIZEOF_INT */
/* The size of `long', as computed by sizeof. */
/* #undef SIZEOF_LONG */
/* The size of `short', as computed by sizeof. */
/* #undef SIZEOF_SHORT */
/* The size of `void *', as computed by sizeof. */
/* #undef SIZEOF_VOID_P */
/* Define to 1 if you have the ANSI C header files. */
/* Version number of package */
/* #undef _GLIBCXX_VERSION */
/* Define if builtin atomic operations for bool are supported on this host. */
/* Define if builtin atomic operations for short are supported on this host.
*/
/* Define if builtin atomic operations for int are supported on this host. */
/* Define if builtin atomic operations for long long are supported on this
host. */
/* Define to use concept checking code from the boost libraries. */
/* #undef _GLIBCXX_CONCEPT_CHECKS */
/* Define if a fully dynamic basic_string is wanted. */
/* #undef _GLIBCXX_FULLY_DYNAMIC_STRING */
/* Define if gthreads library is available. */
/* Define to 1 if a full hosted library is built, or 0 if freestanding. */
/* Define if compatibility should be provided for -mlong-double-64. */
/* Define if ptrdiff_t is int. */
/* #undef _GLIBCXX_PTRDIFF_T_IS_INT */
/* Define if using setrlimit to set resource limits during "make check" */
/* Define if size_t is unsigned int. */
/* #undef _GLIBCXX_SIZE_T_IS_UINT */
/* Define if the compiler is configured for setjmp/longjmp exceptions. */
/* #undef _GLIBCXX_SJLJ_EXCEPTIONS */
/* Define to the value of the EOF integer constant. */
/* Define to the value of the SEEK_CUR integer constant. */
/* Define to the value of the SEEK_END integer constant. */
/* Define to use symbol versioning in the shared library. */
/* Define to use darwin versioning in the shared library. */
/* #undef _GLIBCXX_SYMVER_DARWIN */
/* Define to use GNU versioning in the shared library. */
/* Define to use GNU namespace versioning in the shared library. */
/* #undef _GLIBCXX_SYMVER_GNU_NAMESPACE */
/* Define to use Sun versioning in the shared library. */
/* #undef _GLIBCXX_SYMVER_SUN */
/* Define if C99 functions or macros from <wchar.h>, <math.h>, <complex.h>,
<stdio.h>, and <stdlib.h> can be used or exposed. */
/* Define if C99 functions in <complex.h> should be used in <complex>. Using
compiler builtins for these functions requires corresponding C99 library
functions to be present. */
/* Define if C99 functions in <complex.h> should be used in <tr1/complex>.
Using compiler builtins for these functions requires corresponding C99
library functions to be present. */
/* Define if C99 functions in <ctype.h> should be imported in <tr1/cctype> in
namespace std::tr1. */
/* Define if C99 functions in <fenv.h> should be imported in <tr1/cfenv> in
namespace std::tr1. */
/* Define if C99 functions in <inttypes.h> should be imported in
<tr1/cinttypes> in namespace std::tr1. */
/* Define if wchar_t C99 functions in <inttypes.h> should be imported in
<tr1/cinttypes> in namespace std::tr1. */
/* Define if C99 functions or macros in <math.h> should be imported in <cmath>
in namespace std. */
/* Define if C99 functions or macros in <math.h> should be imported in
<tr1/cmath> in namespace std::tr1. */
/* Define if C99 types in <stdint.h> should be imported in <tr1/cstdint> in
namespace std::tr1. */
/* Defined if clock_gettime has monotonic clock support. */
/* #undef _GLIBCXX_USE_CLOCK_MONOTONIC */
/* Defined if clock_gettime has realtime clock support. */
/* #undef _GLIBCXX_USE_CLOCK_REALTIME */
/* Define if ISO/IEC TR 24733 decimal floating point types are supported on
this host. */
/* Defined if gettimeofday is available. */
/* Define if LFS support is available. */
/* Define if code specialized for long long should be used. */
/* Defined if nanosleep is available. */
/* #undef _GLIBCXX_USE_NANOSLEEP */
/* Define if NLS translations are to be used. */
/* Define if /dev/random and /dev/urandom are available for the random_device
of TR1 (Chapter 5.1). */
/* Defined if sched_yield is available. */
/* #undef _GLIBCXX_USE_SCHED_YIELD */
/* Define if code specialized for wchar_t should be used. */
# 43 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 2 3
# 1 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/bits/cpp_type_traits.h" 1 3
// The -*- C++ -*- type traits classes for internal use in libstdc++
// Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2009, 2010
// Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file bits/cpp_type_traits.h
* This is an internal header file, included by other library headers.
* Do not attempt to use it directly. @headername{ext/type_traits}
*/
// Written by Gabriel Dos Reis <dosreis@cmla.ens-cachan.fr>
# 36 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/bits/cpp_type_traits.h" 3
//
// This file provides some compile-time information about various types.
// These representations were designed, on purpose, to be constant-expressions
// and not types as found in <bits/type_traits.h>. In particular, they
// can be used in control structures and the optimizer hopefully will do
// the obvious thing.
//
// Why integral expressions, and not functions nor types?
// Firstly, these compile-time entities are used as template-arguments
// so function return values won't work: We need compile-time entities.
// We're left with types and constant integral expressions.
// Secondly, from the point of view of ease of use, type-based compile-time
// information is -not- *that* convenient. On has to write lots of
// overloaded functions and to hope that the compiler will select the right
// one. As a net effect, the overall structure isn't very clear at first
// glance.
// Thirdly, partial ordering and overload resolution (of function templates)
// is highly costly in terms of compiler-resource. It is a Good Thing to
// keep these resource consumption as least as possible.
//
// See valarray_array.h for a case use.
//
// -- Gaby (dosreis@cmla.ens-cachan.fr) 2000-03-06.
//
// Update 2005: types are also provided and <bits/type_traits.h> has been
// removed.
//
// Forward declaration hack, should really include this from somewhere.
namespace __gnu_cxx __attribute__ ((__visibility__ ("default")))
{
template<typename _Iterator, typename _Container>
class __normal_iterator;
} // namespace
namespace std __attribute__ ((__visibility__ ("default")))
{
struct __true_type { };
struct __false_type { };
template<bool>
struct __truth_type
{ typedef __false_type __type; };
template<>
struct __truth_type<true>
{ typedef __true_type __type; };
// N.B. The conversions to bool are needed due to the issue
// explained in c++/19404.
template<class _Sp, class _Tp>
struct __traitor
{
enum { __value = bool(_Sp::__value) || bool(_Tp::__value) };
typedef typename __truth_type<__value>::__type __type;
};
// Compare for equality of types.
template<typename, typename>
struct __are_same
{
enum { __value = 0 };
typedef __false_type __type;
};
template<typename _Tp>
struct __are_same<_Tp, _Tp>
{
enum { __value = 1 };
typedef __true_type __type;
};
// Holds if the template-argument is a void type.
template<typename _Tp>
struct __is_void
{
enum { __value = 0 };
typedef __false_type __type;
};
template<>
struct __is_void<void>
{
enum { __value = 1 };
typedef __true_type __type;
};
//
// Integer types
//
template<typename _Tp>
struct __is_integer
{
enum { __value = 0 };
typedef __false_type __type;
};
// Thirteen specializations (yes there are eleven standard integer
// types; <em>long long</em> and <em>unsigned long long</em> are
// supported as extensions)
template<>
struct __is_integer<bool>
{
enum { __value = 1 };
typedef __true_type __type;
};
template<>
struct __is_integer<char>
{
enum { __value = 1 };
typedef __true_type __type;
};
template<>
struct __is_integer<signed char>
{
enum { __value = 1 };
typedef __true_type __type;
};
template<>
struct __is_integer<unsigned char>
{
enum { __value = 1 };
typedef __true_type __type;
};
template<>
struct __is_integer<wchar_t>
{
enum { __value = 1 };
typedef __true_type __type;
};
# 198 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/bits/cpp_type_traits.h" 3
template<>
struct __is_integer<short>
{
enum { __value = 1 };
typedef __true_type __type;
};
template<>
struct __is_integer<unsigned short>
{
enum { __value = 1 };
typedef __true_type __type;
};
template<>
struct __is_integer<int>
{
enum { __value = 1 };
typedef __true_type __type;
};
template<>
struct __is_integer<unsigned int>
{
enum { __value = 1 };
typedef __true_type __type;
};
template<>
struct __is_integer<long>
{
enum { __value = 1 };
typedef __true_type __type;
};
template<>
struct __is_integer<unsigned long>
{
enum { __value = 1 };
typedef __true_type __type;
};
template<>
struct __is_integer<long long>
{
enum { __value = 1 };
typedef __true_type __type;
};
template<>
struct __is_integer<unsigned long long>
{
enum { __value = 1 };
typedef __true_type __type;
};
//
// Floating point types
//
template<typename _Tp>
struct __is_floating
{
enum { __value = 0 };
typedef __false_type __type;
};
// three specializations (float, double and 'long double')
template<>
struct __is_floating<float>
{
enum { __value = 1 };
typedef __true_type __type;
};
template<>
struct __is_floating<double>
{
enum { __value = 1 };
typedef __true_type __type;
};
template<>
struct __is_floating<long double>
{
enum { __value = 1 };
typedef __true_type __type;
};
//
// Pointer types
//
template<typename _Tp>
struct __is_pointer
{
enum { __value = 0 };
typedef __false_type __type;
};
template<typename _Tp>
struct __is_pointer<_Tp*>
{
enum { __value = 1 };
typedef __true_type __type;
};
//
// Normal iterator type
//
template<typename _Tp>
struct __is_normal_iterator
{
enum { __value = 0 };
typedef __false_type __type;
};
template<typename _Iterator, typename _Container>
struct __is_normal_iterator< __gnu_cxx::__normal_iterator<_Iterator,
_Container> >
{
enum { __value = 1 };
typedef __true_type __type;
};
//
// An arithmetic type is an integer type or a floating point type
//
template<typename _Tp>
struct __is_arithmetic
: public __traitor<__is_integer<_Tp>, __is_floating<_Tp> >
{ };
//
// A fundamental type is `void' or and arithmetic type
//
template<typename _Tp>
struct __is_fundamental
: public __traitor<__is_void<_Tp>, __is_arithmetic<_Tp> >
{ };
//
// A scalar type is an arithmetic type or a pointer type
//
template<typename _Tp>
struct __is_scalar
: public __traitor<__is_arithmetic<_Tp>, __is_pointer<_Tp> >
{ };
//
// For use in std::copy and std::find overloads for streambuf iterators.
//
template<typename _Tp>
struct __is_char
{
enum { __value = 0 };
typedef __false_type __type;
};
template<>
struct __is_char<char>
{
enum { __value = 1 };
typedef __true_type __type;
};
template<>
struct __is_char<wchar_t>
{
enum { __value = 1 };
typedef __true_type __type;
};
template<typename _Tp>
struct __is_byte
{
enum { __value = 0 };
typedef __false_type __type;
};
template<>
struct __is_byte<char>
{
enum { __value = 1 };
typedef __true_type __type;
};
template<>
struct __is_byte<signed char>
{
enum { __value = 1 };
typedef __true_type __type;
};
template<>
struct __is_byte<unsigned char>
{
enum { __value = 1 };
typedef __true_type __type;
};
//
// Move iterator type
//
template<typename _Tp>
struct __is_move_iterator
{
enum { __value = 0 };
typedef __false_type __type;
};
# 422 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/bits/cpp_type_traits.h" 3
} // namespace
# 44 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 2 3
# 1 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/ext/type_traits.h" 1 3
// -*- C++ -*-
// Copyright (C) 2005, 2006, 2007, 2009, 2010, 2011
// Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the terms
// of the GNU General Public License as published by the Free Software
// Foundation; either version 3, or (at your option) any later
// version.
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file ext/type_traits.h
* This file is a GNU extension to the Standard C++ Library.
*/
# 33 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/ext/type_traits.h" 3
namespace __gnu_cxx __attribute__ ((__visibility__ ("default")))
{
// Define a nested type if some predicate holds.
template<bool, typename>
struct __enable_if
{ };
template<typename _Tp>
struct __enable_if<true, _Tp>
{ typedef _Tp __type; };
// Conditional expression for types. If true, first, if false, second.
template<bool _Cond, typename _Iftrue, typename _Iffalse>
struct __conditional_type
{ typedef _Iftrue __type; };
template<typename _Iftrue, typename _Iffalse>
struct __conditional_type<false, _Iftrue, _Iffalse>
{ typedef _Iffalse __type; };
// Given an integral builtin type, return the corresponding unsigned type.
template<typename _Tp>
struct __add_unsigned
{
private:
typedef __enable_if<std::__is_integer<_Tp>::__value, _Tp> __if_type;
public:
typedef typename __if_type::__type __type;
};
template<>
struct __add_unsigned<char>
{ typedef unsigned char __type; };
template<>
struct __add_unsigned<signed char>
{ typedef unsigned char __type; };
template<>
struct __add_unsigned<short>
{ typedef unsigned short __type; };
template<>
struct __add_unsigned<int>
{ typedef unsigned int __type; };
template<>
struct __add_unsigned<long>
{ typedef unsigned long __type; };
template<>
struct __add_unsigned<long long>
{ typedef unsigned long long __type; };
// Declare but don't define.
template<>
struct __add_unsigned<bool>;
template<>
struct __add_unsigned<wchar_t>;
// Given an integral builtin type, return the corresponding signed type.
template<typename _Tp>
struct __remove_unsigned
{
private:
typedef __enable_if<std::__is_integer<_Tp>::__value, _Tp> __if_type;
public:
typedef typename __if_type::__type __type;
};
template<>
struct __remove_unsigned<char>
{ typedef signed char __type; };
template<>
struct __remove_unsigned<unsigned char>
{ typedef signed char __type; };
template<>
struct __remove_unsigned<unsigned short>
{ typedef short __type; };
template<>
struct __remove_unsigned<unsigned int>
{ typedef int __type; };
template<>
struct __remove_unsigned<unsigned long>
{ typedef long __type; };
template<>
struct __remove_unsigned<unsigned long long>
{ typedef long long __type; };
// Declare but don't define.
template<>
struct __remove_unsigned<bool>;
template<>
struct __remove_unsigned<wchar_t>;
// For use in string and vstring.
template<typename _Type>
inline bool
__is_null_pointer(_Type* __ptr)
{ return __ptr == 0; }
template<typename _Type>
inline bool
__is_null_pointer(_Type)
{ return false; }
// For complex and cmath
template<typename _Tp, bool = std::__is_integer<_Tp>::__value>
struct __promote
{ typedef double __type; };
// No nested __type member for non-integer non-floating point types,
// allows this type to be used for SFINAE to constrain overloads in
// <cmath> and <complex> to only the intended types.
template<typename _Tp>
struct __promote<_Tp, false>
{ };
template<>
struct __promote<long double>
{ typedef long double __type; };
template<>
struct __promote<double>
{ typedef double __type; };
template<>
struct __promote<float>
{ typedef float __type; };
template<typename _Tp, typename _Up,
typename _Tp2 = typename __promote<_Tp>::__type,
typename _Up2 = typename __promote<_Up>::__type>
struct __promote_2
{
typedef __typeof__(_Tp2() + _Up2()) __type;
};
template<typename _Tp, typename _Up, typename _Vp,
typename _Tp2 = typename __promote<_Tp>::__type,
typename _Up2 = typename __promote<_Up>::__type,
typename _Vp2 = typename __promote<_Vp>::__type>
struct __promote_3
{
typedef __typeof__(_Tp2() + _Up2() + _Vp2()) __type;
};
template<typename _Tp, typename _Up, typename _Vp, typename _Wp,
typename _Tp2 = typename __promote<_Tp>::__type,
typename _Up2 = typename __promote<_Up>::__type,
typename _Vp2 = typename __promote<_Vp>::__type,
typename _Wp2 = typename __promote<_Wp>::__type>
struct __promote_4
{
typedef __typeof__(_Tp2() + _Up2() + _Vp2() + _Wp2()) __type;
};
} // namespace
# 45 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 2 3
extern "C" {
# 1 "/usr/include/math.h" 1 3 4
/* Declarations for math functions.
Copyright (C) 1991-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/*
* ISO C99 Standard: 7.12 Mathematics <math.h>
*/
extern "C" {
/* Get machine-dependent HUGE_VAL value (returned on overflow).
On all IEEE754 machines, this is +Infinity. */
# 1 "/usr/include/x86_64-linux-gnu/bits/huge_val.h" 1 3 4
/* `HUGE_VAL' constant for IEEE 754 machines (where it is infinity).
Used by <stdlib.h> and <math.h> functions for overflow.
Copyright (C) 1992-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* IEEE positive infinity (-HUGE_VAL is negative infinity). */
# 33 "/usr/include/math.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/huge_valf.h" 1 3 4
/* `HUGE_VALF' constant for IEEE 754 machines (where it is infinity).
Used by <stdlib.h> and <math.h> functions for overflow.
Copyright (C) 1992-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* IEEE positive infinity (-HUGE_VAL is negative infinity). */
# 35 "/usr/include/math.h" 2 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/huge_vall.h" 1 3 4
/* `HUGE_VALL' constant for ix86 (where it is infinity).
Used by <stdlib.h> and <math.h> functions for overflow.
Copyright (C) 1992-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
# 36 "/usr/include/math.h" 2 3 4
/* Get machine-dependent INFINITY value. */
# 1 "/usr/include/x86_64-linux-gnu/bits/inf.h" 1 3 4
/* `INFINITY' constant for IEEE 754 machines.
Copyright (C) 2004-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* IEEE positive infinity. */
# 39 "/usr/include/math.h" 2 3 4
/* Get machine-dependent NAN value (returned for some domain errors). */
# 1 "/usr/include/x86_64-linux-gnu/bits/nan.h" 1 3 4
/* `NAN' constant for IEEE 754 machines.
Copyright (C) 1992-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* IEEE Not A Number. */
# 42 "/usr/include/math.h" 2 3 4
/* Get general and ISO C99 specific information. */
# 1 "/usr/include/x86_64-linux-gnu/bits/mathdef.h" 1 3 4
/* Copyright (C) 2001-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
# 26 "/usr/include/x86_64-linux-gnu/bits/mathdef.h" 3 4
/* The x86-64 architecture computes values with the precission of the
used type. Similarly for -m32 -mfpmath=sse. */
typedef float float_t; /* `float' expressions are evaluated as `float'. */
typedef double double_t; /* `double' expressions are evaluated
as `double'. */
# 41 "/usr/include/x86_64-linux-gnu/bits/mathdef.h" 3 4
/* The values returned by `ilogb' for 0 and NaN respectively. */
/* The GCC 4.6 compiler will define __FP_FAST_FMA{,F,L} if the fma{,f,l}
builtins are supported. */
# 46 "/usr/include/math.h" 2 3 4
/* The file <bits/mathcalls.h> contains the prototypes for all the
actual math functions. These macros are used for those prototypes,
so we can easily declare each function as both `name' and `__name',
and can declare the float versions `namef' and `__namef'. */
# 69 "/usr/include/math.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 1 3 4
/* Prototype declarations for math functions; helper file for <math.h>.
Copyright (C) 1996-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* NOTE: Because of the special way this file is used by <math.h>, this
file must NOT be protected from multiple inclusion as header files
usually are.
This file provides prototype declarations for the math functions.
Most functions are declared using the macro:
__MATHCALL (NAME,[_r], (ARGS...));
This means there is a function `NAME' returning `double' and a function
`NAMEf' returning `float'. Each place `_Mdouble_' appears in the
prototype, that is actually `double' in the prototype for `NAME' and
`float' in the prototype for `NAMEf'. Reentrant variant functions are
called `NAME_r' and `NAMEf_r'.
Functions returning other types like `int' are declared using the macro:
__MATHDECL (TYPE, NAME,[_r], (ARGS...));
This is just like __MATHCALL but for a function returning `TYPE'
instead of `_Mdouble_'. In all of these cases, there is still
both a `NAME' and a `NAMEf' that takes `float' arguments.
Note that there must be no whitespace before the argument passed for
NAME, to make token pasting work with -traditional. */
/* Trigonometric functions. */
/* Arc cosine of X. */
extern double acos (double __x) throw (); extern double __acos (double __x) throw ();
/* Arc sine of X. */
extern double asin (double __x) throw (); extern double __asin (double __x) throw ();
/* Arc tangent of X. */
extern double atan (double __x) throw (); extern double __atan (double __x) throw ();
/* Arc tangent of Y/X. */
extern double atan2 (double __y, double __x) throw (); extern double __atan2 (double __y, double __x) throw ();
/* Cosine of X. */
extern double cos (double __x) throw (); extern double __cos (double __x) throw ();
/* Sine of X. */
extern double sin (double __x) throw (); extern double __sin (double __x) throw ();
/* Tangent of X. */
extern double tan (double __x) throw (); extern double __tan (double __x) throw ();
/* Hyperbolic functions. */
/* Hyperbolic cosine of X. */
extern double cosh (double __x) throw (); extern double __cosh (double __x) throw ();
/* Hyperbolic sine of X. */
extern double sinh (double __x) throw (); extern double __sinh (double __x) throw ();
/* Hyperbolic tangent of X. */
extern double tanh (double __x) throw (); extern double __tanh (double __x) throw ();
/* Cosine and sine of X. */
extern void sincos (double __x, double *__sinx, double *__cosx) throw (); extern void __sincos (double __x, double *__sinx, double *__cosx) throw ();
/* Hyperbolic arc cosine of X. */
extern double acosh (double __x) throw (); extern double __acosh (double __x) throw ();
/* Hyperbolic arc sine of X. */
extern double asinh (double __x) throw (); extern double __asinh (double __x) throw ();
/* Hyperbolic arc tangent of X. */
extern double atanh (double __x) throw (); extern double __atanh (double __x) throw ();
/* Exponential and logarithmic functions. */
/* Exponential function of X. */
extern double exp (double __x) throw (); extern double __exp (double __x) throw ();
/* Break VALUE into a normalized fraction and an integral power of 2. */
extern double frexp (double __x, int *__exponent) throw (); extern double __frexp (double __x, int *__exponent) throw ();
/* X times (two to the EXP power). */
extern double ldexp (double __x, int __exponent) throw (); extern double __ldexp (double __x, int __exponent) throw ();
/* Natural logarithm of X. */
extern double log (double __x) throw (); extern double __log (double __x) throw ();
/* Base-ten logarithm of X. */
extern double log10 (double __x) throw (); extern double __log10 (double __x) throw ();
/* Break VALUE into integral and fractional parts. */
extern double modf (double __x, double *__iptr) throw (); extern double __modf (double __x, double *__iptr) throw () __attribute__ ((__nonnull__ (2)));
/* A function missing in all standards: compute exponent to base ten. */
extern double exp10 (double __x) throw (); extern double __exp10 (double __x) throw ();
/* Another name occasionally used. */
extern double pow10 (double __x) throw (); extern double __pow10 (double __x) throw ();
/* Return exp(X) - 1. */
extern double expm1 (double __x) throw (); extern double __expm1 (double __x) throw ();
/* Return log(1 + X). */
extern double log1p (double __x) throw (); extern double __log1p (double __x) throw ();
/* Return the base 2 signed integral exponent of X. */
extern double logb (double __x) throw (); extern double __logb (double __x) throw ();
/* Compute base-2 exponential of X. */
extern double exp2 (double __x) throw (); extern double __exp2 (double __x) throw ();
/* Compute base-2 logarithm of X. */
extern double log2 (double __x) throw (); extern double __log2 (double __x) throw ();
/* Power functions. */
/* Return X to the Y power. */
extern double pow (double __x, double __y) throw (); extern double __pow (double __x, double __y) throw ();
/* Return the square root of X. */
extern double sqrt (double __x) throw (); extern double __sqrt (double __x) throw ();
/* Return `sqrt(X*X + Y*Y)'. */
extern double hypot (double __x, double __y) throw (); extern double __hypot (double __x, double __y) throw ();
/* Return the cube root of X. */
extern double cbrt (double __x) throw (); extern double __cbrt (double __x) throw ();
/* Nearest integer, absolute value, and remainder functions. */
/* Smallest integral value not less than X. */
extern double ceil (double __x) throw () __attribute__ ((__const__)); extern double __ceil (double __x) throw () __attribute__ ((__const__));
/* Absolute value of X. */
extern double fabs (double __x) throw () __attribute__ ((__const__)); extern double __fabs (double __x) throw () __attribute__ ((__const__));
/* Largest integer not greater than X. */
extern double floor (double __x) throw () __attribute__ ((__const__)); extern double __floor (double __x) throw () __attribute__ ((__const__));
/* Floating-point modulo remainder of X/Y. */
extern double fmod (double __x, double __y) throw (); extern double __fmod (double __x, double __y) throw ();
/* Return 0 if VALUE is finite or NaN, +1 if it
is +Infinity, -1 if it is -Infinity. */
extern int __isinf (double __value) throw () __attribute__ ((__const__));
/* Return nonzero if VALUE is finite and not NaN. */
extern int __finite (double __value) throw () __attribute__ ((__const__));
/* Return 0 if VALUE is finite or NaN, +1 if it
is +Infinity, -1 if it is -Infinity. */
extern int isinf (double __value) throw () __attribute__ ((__const__));
/* Return nonzero if VALUE is finite and not NaN. */
extern int finite (double __value) throw () __attribute__ ((__const__));
/* Return the remainder of X/Y. */
extern double drem (double __x, double __y) throw (); extern double __drem (double __x, double __y) throw ();
/* Return the fractional part of X after dividing out `ilogb (X)'. */
extern double significand (double __x) throw (); extern double __significand (double __x) throw ();
/* Return X with its signed changed to Y's. */
extern double copysign (double __x, double __y) throw () __attribute__ ((__const__)); extern double __copysign (double __x, double __y) throw () __attribute__ ((__const__));
/* Return representation of qNaN for double type. */
extern double nan (const char *__tagb) throw () __attribute__ ((__const__)); extern double __nan (const char *__tagb) throw () __attribute__ ((__const__));
/* Return nonzero if VALUE is not a number. */
extern int __isnan (double __value) throw () __attribute__ ((__const__));
/* Return nonzero if VALUE is not a number. */
extern int isnan (double __value) throw () __attribute__ ((__const__));
/* Bessel functions. */
extern double j0 (double) throw (); extern double __j0 (double) throw ();
extern double j1 (double) throw (); extern double __j1 (double) throw ();
extern double jn (int, double) throw (); extern double __jn (int, double) throw ();
extern double y0 (double) throw (); extern double __y0 (double) throw ();
extern double y1 (double) throw (); extern double __y1 (double) throw ();
extern double yn (int, double) throw (); extern double __yn (int, double) throw ();
/* Error and gamma functions. */
extern double erf (double) throw (); extern double __erf (double) throw ();
extern double erfc (double) throw (); extern double __erfc (double) throw ();
extern double lgamma (double) throw (); extern double __lgamma (double) throw ();
/* True gamma function. */
extern double tgamma (double) throw (); extern double __tgamma (double) throw ();
/* Obsolete alias for `lgamma'. */
extern double gamma (double) throw (); extern double __gamma (double) throw ();
/* Reentrant version of lgamma. This function uses the global variable
`signgam'. The reentrant version instead takes a pointer and stores
the value through it. */
extern double lgamma_r (double, int *__signgamp) throw (); extern double __lgamma_r (double, int *__signgamp) throw ();
/* Return the integer nearest X in the direction of the
prevailing rounding mode. */
extern double rint (double __x) throw (); extern double __rint (double __x) throw ();
/* Return X + epsilon if X < Y, X - epsilon if X > Y. */
extern double nextafter (double __x, double __y) throw () __attribute__ ((__const__)); extern double __nextafter (double __x, double __y) throw () __attribute__ ((__const__));
extern double nexttoward (double __x, long double __y) throw () __attribute__ ((__const__)); extern double __nexttoward (double __x, long double __y) throw () __attribute__ ((__const__));
/* Return the remainder of integer divison X / Y with infinite precision. */
extern double remainder (double __x, double __y) throw (); extern double __remainder (double __x, double __y) throw ();
/* Return X times (2 to the Nth power). */
extern double scalbn (double __x, int __n) throw (); extern double __scalbn (double __x, int __n) throw ();
/* Return the binary exponent of X, which must be nonzero. */
extern int ilogb (double __x) throw (); extern int __ilogb (double __x) throw ();
/* Return X times (2 to the Nth power). */
extern double scalbln (double __x, long int __n) throw (); extern double __scalbln (double __x, long int __n) throw ();
/* Round X to integral value in floating-point format using current
rounding direction, but do not raise inexact exception. */
extern double nearbyint (double __x) throw (); extern double __nearbyint (double __x) throw ();
/* Round X to nearest integral value, rounding halfway cases away from
zero. */
extern double round (double __x) throw () __attribute__ ((__const__)); extern double __round (double __x) throw () __attribute__ ((__const__));
/* Round X to the integral value in floating-point format nearest but
not larger in magnitude. */
extern double trunc (double __x) throw () __attribute__ ((__const__)); extern double __trunc (double __x) throw () __attribute__ ((__const__));
/* Compute remainder of X and Y and put in *QUO a value with sign of x/y
and magnitude congruent `mod 2^n' to the magnitude of the integral
quotient x/y, with n >= 3. */
extern double remquo (double __x, double __y, int *__quo) throw (); extern double __remquo (double __x, double __y, int *__quo) throw ();
/* Conversion functions. */
/* Round X to nearest integral value according to current rounding
direction. */
extern long int lrint (double __x) throw (); extern long int __lrint (double __x) throw ();
__extension__
extern long long int llrint (double __x) throw (); extern long long int __llrint (double __x) throw ();
/* Round X to nearest integral value, rounding halfway cases away from
zero. */
extern long int lround (double __x) throw (); extern long int __lround (double __x) throw ();
__extension__
extern long long int llround (double __x) throw (); extern long long int __llround (double __x) throw ();
/* Return positive difference between X and Y. */
extern double fdim (double __x, double __y) throw (); extern double __fdim (double __x, double __y) throw ();
/* Return maximum numeric value from X and Y. */
extern double fmax (double __x, double __y) throw () __attribute__ ((__const__)); extern double __fmax (double __x, double __y) throw () __attribute__ ((__const__));
/* Return minimum numeric value from X and Y. */
extern double fmin (double __x, double __y) throw () __attribute__ ((__const__)); extern double __fmin (double __x, double __y) throw () __attribute__ ((__const__));
/* Classify given number. */
extern int __fpclassify (double __value) throw ()
__attribute__ ((__const__));
/* Test for negative number. */
extern int __signbit (double __value) throw ()
__attribute__ ((__const__));
/* Multiply-add function computed as a ternary operation. */
extern double fma (double __x, double __y, double __z) throw (); extern double __fma (double __x, double __y, double __z) throw ();
/* Test for signaling NaN. */
extern int __issignaling (double __value) throw ()
__attribute__ ((__const__));
/* Return X times (2 to the Nth power). */
extern double scalb (double __x, double __n) throw (); extern double __scalb (double __x, double __n) throw ();
# 70 "/usr/include/math.h" 2 3 4
/* Include the file of declarations again, this time using `float'
instead of `double' and appending f to each function name. */
# 88 "/usr/include/math.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 1 3 4
/* Prototype declarations for math functions; helper file for <math.h>.
Copyright (C) 1996-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* NOTE: Because of the special way this file is used by <math.h>, this
file must NOT be protected from multiple inclusion as header files
usually are.
This file provides prototype declarations for the math functions.
Most functions are declared using the macro:
__MATHCALL (NAME,[_r], (ARGS...));
This means there is a function `NAME' returning `double' and a function
`NAMEf' returning `float'. Each place `_Mdouble_' appears in the
prototype, that is actually `double' in the prototype for `NAME' and
`float' in the prototype for `NAMEf'. Reentrant variant functions are
called `NAME_r' and `NAMEf_r'.
Functions returning other types like `int' are declared using the macro:
__MATHDECL (TYPE, NAME,[_r], (ARGS...));
This is just like __MATHCALL but for a function returning `TYPE'
instead of `_Mdouble_'. In all of these cases, there is still
both a `NAME' and a `NAMEf' that takes `float' arguments.
Note that there must be no whitespace before the argument passed for
NAME, to make token pasting work with -traditional. */
/* Trigonometric functions. */
/* Arc cosine of X. */
extern float acosf (float __x) throw (); extern float __acosf (float __x) throw ();
/* Arc sine of X. */
extern float asinf (float __x) throw (); extern float __asinf (float __x) throw ();
/* Arc tangent of X. */
extern float atanf (float __x) throw (); extern float __atanf (float __x) throw ();
/* Arc tangent of Y/X. */
extern float atan2f (float __y, float __x) throw (); extern float __atan2f (float __y, float __x) throw ();
/* Cosine of X. */
extern float cosf (float __x) throw (); extern float __cosf (float __x) throw ();
/* Sine of X. */
extern float sinf (float __x) throw (); extern float __sinf (float __x) throw ();
/* Tangent of X. */
extern float tanf (float __x) throw (); extern float __tanf (float __x) throw ();
/* Hyperbolic functions. */
/* Hyperbolic cosine of X. */
extern float coshf (float __x) throw (); extern float __coshf (float __x) throw ();
/* Hyperbolic sine of X. */
extern float sinhf (float __x) throw (); extern float __sinhf (float __x) throw ();
/* Hyperbolic tangent of X. */
extern float tanhf (float __x) throw (); extern float __tanhf (float __x) throw ();
/* Cosine and sine of X. */
extern void sincosf (float __x, float *__sinx, float *__cosx) throw (); extern void __sincosf (float __x, float *__sinx, float *__cosx) throw ();
/* Hyperbolic arc cosine of X. */
extern float acoshf (float __x) throw (); extern float __acoshf (float __x) throw ();
/* Hyperbolic arc sine of X. */
extern float asinhf (float __x) throw (); extern float __asinhf (float __x) throw ();
/* Hyperbolic arc tangent of X. */
extern float atanhf (float __x) throw (); extern float __atanhf (float __x) throw ();
/* Exponential and logarithmic functions. */
/* Exponential function of X. */
extern float expf (float __x) throw (); extern float __expf (float __x) throw ();
/* Break VALUE into a normalized fraction and an integral power of 2. */
extern float frexpf (float __x, int *__exponent) throw (); extern float __frexpf (float __x, int *__exponent) throw ();
/* X times (two to the EXP power). */
extern float ldexpf (float __x, int __exponent) throw (); extern float __ldexpf (float __x, int __exponent) throw ();
/* Natural logarithm of X. */
extern float logf (float __x) throw (); extern float __logf (float __x) throw ();
/* Base-ten logarithm of X. */
extern float log10f (float __x) throw (); extern float __log10f (float __x) throw ();
/* Break VALUE into integral and fractional parts. */
extern float modff (float __x, float *__iptr) throw (); extern float __modff (float __x, float *__iptr) throw () __attribute__ ((__nonnull__ (2)));
/* A function missing in all standards: compute exponent to base ten. */
extern float exp10f (float __x) throw (); extern float __exp10f (float __x) throw ();
/* Another name occasionally used. */
extern float pow10f (float __x) throw (); extern float __pow10f (float __x) throw ();
/* Return exp(X) - 1. */
extern float expm1f (float __x) throw (); extern float __expm1f (float __x) throw ();
/* Return log(1 + X). */
extern float log1pf (float __x) throw (); extern float __log1pf (float __x) throw ();
/* Return the base 2 signed integral exponent of X. */
extern float logbf (float __x) throw (); extern float __logbf (float __x) throw ();
/* Compute base-2 exponential of X. */
extern float exp2f (float __x) throw (); extern float __exp2f (float __x) throw ();
/* Compute base-2 logarithm of X. */
extern float log2f (float __x) throw (); extern float __log2f (float __x) throw ();
/* Power functions. */
/* Return X to the Y power. */
extern float powf (float __x, float __y) throw (); extern float __powf (float __x, float __y) throw ();
/* Return the square root of X. */
extern float sqrtf (float __x) throw (); extern float __sqrtf (float __x) throw ();
/* Return `sqrt(X*X + Y*Y)'. */
extern float hypotf (float __x, float __y) throw (); extern float __hypotf (float __x, float __y) throw ();
/* Return the cube root of X. */
extern float cbrtf (float __x) throw (); extern float __cbrtf (float __x) throw ();
/* Nearest integer, absolute value, and remainder functions. */
/* Smallest integral value not less than X. */
extern float ceilf (float __x) throw () __attribute__ ((__const__)); extern float __ceilf (float __x) throw () __attribute__ ((__const__));
/* Absolute value of X. */
extern float fabsf (float __x) throw () __attribute__ ((__const__)); extern float __fabsf (float __x) throw () __attribute__ ((__const__));
/* Largest integer not greater than X. */
extern float floorf (float __x) throw () __attribute__ ((__const__)); extern float __floorf (float __x) throw () __attribute__ ((__const__));
/* Floating-point modulo remainder of X/Y. */
extern float fmodf (float __x, float __y) throw (); extern float __fmodf (float __x, float __y) throw ();
/* Return 0 if VALUE is finite or NaN, +1 if it
is +Infinity, -1 if it is -Infinity. */
extern int __isinff (float __value) throw () __attribute__ ((__const__));
/* Return nonzero if VALUE is finite and not NaN. */
extern int __finitef (float __value) throw () __attribute__ ((__const__));
/* Return 0 if VALUE is finite or NaN, +1 if it
is +Infinity, -1 if it is -Infinity. */
extern int isinff (float __value) throw () __attribute__ ((__const__));
/* Return nonzero if VALUE is finite and not NaN. */
extern int finitef (float __value) throw () __attribute__ ((__const__));
/* Return the remainder of X/Y. */
extern float dremf (float __x, float __y) throw (); extern float __dremf (float __x, float __y) throw ();
/* Return the fractional part of X after dividing out `ilogb (X)'. */
extern float significandf (float __x) throw (); extern float __significandf (float __x) throw ();
/* Return X with its signed changed to Y's. */
extern float copysignf (float __x, float __y) throw () __attribute__ ((__const__)); extern float __copysignf (float __x, float __y) throw () __attribute__ ((__const__));
/* Return representation of qNaN for double type. */
extern float nanf (const char *__tagb) throw () __attribute__ ((__const__)); extern float __nanf (const char *__tagb) throw () __attribute__ ((__const__));
/* Return nonzero if VALUE is not a number. */
extern int __isnanf (float __value) throw () __attribute__ ((__const__));
/* Return nonzero if VALUE is not a number. */
extern int isnanf (float __value) throw () __attribute__ ((__const__));
/* Bessel functions. */
extern float j0f (float) throw (); extern float __j0f (float) throw ();
extern float j1f (float) throw (); extern float __j1f (float) throw ();
extern float jnf (int, float) throw (); extern float __jnf (int, float) throw ();
extern float y0f (float) throw (); extern float __y0f (float) throw ();
extern float y1f (float) throw (); extern float __y1f (float) throw ();
extern float ynf (int, float) throw (); extern float __ynf (int, float) throw ();
/* Error and gamma functions. */
extern float erff (float) throw (); extern float __erff (float) throw ();
extern float erfcf (float) throw (); extern float __erfcf (float) throw ();
extern float lgammaf (float) throw (); extern float __lgammaf (float) throw ();
/* True gamma function. */
extern float tgammaf (float) throw (); extern float __tgammaf (float) throw ();
/* Obsolete alias for `lgamma'. */
extern float gammaf (float) throw (); extern float __gammaf (float) throw ();
/* Reentrant version of lgamma. This function uses the global variable
`signgam'. The reentrant version instead takes a pointer and stores
the value through it. */
extern float lgammaf_r (float, int *__signgamp) throw (); extern float __lgammaf_r (float, int *__signgamp) throw ();
/* Return the integer nearest X in the direction of the
prevailing rounding mode. */
extern float rintf (float __x) throw (); extern float __rintf (float __x) throw ();
/* Return X + epsilon if X < Y, X - epsilon if X > Y. */
extern float nextafterf (float __x, float __y) throw () __attribute__ ((__const__)); extern float __nextafterf (float __x, float __y) throw () __attribute__ ((__const__));
extern float nexttowardf (float __x, long double __y) throw () __attribute__ ((__const__)); extern float __nexttowardf (float __x, long double __y) throw () __attribute__ ((__const__));
/* Return the remainder of integer divison X / Y with infinite precision. */
extern float remainderf (float __x, float __y) throw (); extern float __remainderf (float __x, float __y) throw ();
/* Return X times (2 to the Nth power). */
extern float scalbnf (float __x, int __n) throw (); extern float __scalbnf (float __x, int __n) throw ();
/* Return the binary exponent of X, which must be nonzero. */
extern int ilogbf (float __x) throw (); extern int __ilogbf (float __x) throw ();
/* Return X times (2 to the Nth power). */
extern float scalblnf (float __x, long int __n) throw (); extern float __scalblnf (float __x, long int __n) throw ();
/* Round X to integral value in floating-point format using current
rounding direction, but do not raise inexact exception. */
extern float nearbyintf (float __x) throw (); extern float __nearbyintf (float __x) throw ();
/* Round X to nearest integral value, rounding halfway cases away from
zero. */
extern float roundf (float __x) throw () __attribute__ ((__const__)); extern float __roundf (float __x) throw () __attribute__ ((__const__));
/* Round X to the integral value in floating-point format nearest but
not larger in magnitude. */
extern float truncf (float __x) throw () __attribute__ ((__const__)); extern float __truncf (float __x) throw () __attribute__ ((__const__));
/* Compute remainder of X and Y and put in *QUO a value with sign of x/y
and magnitude congruent `mod 2^n' to the magnitude of the integral
quotient x/y, with n >= 3. */
extern float remquof (float __x, float __y, int *__quo) throw (); extern float __remquof (float __x, float __y, int *__quo) throw ();
/* Conversion functions. */
/* Round X to nearest integral value according to current rounding
direction. */
extern long int lrintf (float __x) throw (); extern long int __lrintf (float __x) throw ();
__extension__
extern long long int llrintf (float __x) throw (); extern long long int __llrintf (float __x) throw ();
/* Round X to nearest integral value, rounding halfway cases away from
zero. */
extern long int lroundf (float __x) throw (); extern long int __lroundf (float __x) throw ();
__extension__
extern long long int llroundf (float __x) throw (); extern long long int __llroundf (float __x) throw ();
/* Return positive difference between X and Y. */
extern float fdimf (float __x, float __y) throw (); extern float __fdimf (float __x, float __y) throw ();
/* Return maximum numeric value from X and Y. */
extern float fmaxf (float __x, float __y) throw () __attribute__ ((__const__)); extern float __fmaxf (float __x, float __y) throw () __attribute__ ((__const__));
/* Return minimum numeric value from X and Y. */
extern float fminf (float __x, float __y) throw () __attribute__ ((__const__)); extern float __fminf (float __x, float __y) throw () __attribute__ ((__const__));
/* Classify given number. */
extern int __fpclassifyf (float __value) throw ()
__attribute__ ((__const__));
/* Test for negative number. */
extern int __signbitf (float __value) throw ()
__attribute__ ((__const__));
/* Multiply-add function computed as a ternary operation. */
extern float fmaf (float __x, float __y, float __z) throw (); extern float __fmaf (float __x, float __y, float __z) throw ();
/* Test for signaling NaN. */
extern int __issignalingf (float __value) throw ()
__attribute__ ((__const__));
/* Return X times (2 to the Nth power). */
extern float scalbf (float __x, float __n) throw (); extern float __scalbf (float __x, float __n) throw ();
# 89 "/usr/include/math.h" 2 3 4
# 121 "/usr/include/math.h" 3 4
/* Include the file of declarations again, this time using `long double'
instead of `double' and appending l to each function name. */
# 132 "/usr/include/math.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/mathcalls.h" 1 3 4
/* Prototype declarations for math functions; helper file for <math.h>.
Copyright (C) 1996-2014 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<http://www.gnu.org/licenses/>. */
/* NOTE: Because of the special way this file is used by <math.h>, this
file must NOT be protected from multiple inclusion as header files
usually are.
This file provides prototype declarations for the math functions.
Most functions are declared using the macro:
__MATHCALL (NAME,[_r], (ARGS...));
This means there is a function `NAME' returning `double' and a function
`NAMEf' returning `float'. Each place `_Mdouble_' appears in the
prototype, that is actually `double' in the prototype for `NAME' and
`float' in the prototype for `NAMEf'. Reentrant variant functions are
called `NAME_r' and `NAMEf_r'.
Functions returning other types like `int' are declared using the macro:
__MATHDECL (TYPE, NAME,[_r], (ARGS...));
This is just like __MATHCALL but for a function returning `TYPE'
instead of `_Mdouble_'. In all of these cases, there is still
both a `NAME' and a `NAMEf' that takes `float' arguments.
Note that there must be no whitespace before the argument passed for
NAME, to make token pasting work with -traditional. */
/* Trigonometric functions. */
/* Arc cosine of X. */
extern long double acosl (long double __x) throw (); extern long double __acosl (long double __x) throw ();
/* Arc sine of X. */
extern long double asinl (long double __x) throw (); extern long double __asinl (long double __x) throw ();
/* Arc tangent of X. */
extern long double atanl (long double __x) throw (); extern long double __atanl (long double __x) throw ();
/* Arc tangent of Y/X. */
extern long double atan2l (long double __y, long double __x) throw (); extern long double __atan2l (long double __y, long double __x) throw ();
/* Cosine of X. */
extern long double cosl (long double __x) throw (); extern long double __cosl (long double __x) throw ();
/* Sine of X. */
extern long double sinl (long double __x) throw (); extern long double __sinl (long double __x) throw ();
/* Tangent of X. */
extern long double tanl (long double __x) throw (); extern long double __tanl (long double __x) throw ();
/* Hyperbolic functions. */
/* Hyperbolic cosine of X. */
extern long double coshl (long double __x) throw (); extern long double __coshl (long double __x) throw ();
/* Hyperbolic sine of X. */
extern long double sinhl (long double __x) throw (); extern long double __sinhl (long double __x) throw ();
/* Hyperbolic tangent of X. */
extern long double tanhl (long double __x) throw (); extern long double __tanhl (long double __x) throw ();
/* Cosine and sine of X. */
extern void sincosl (long double __x, long double *__sinx, long double *__cosx) throw (); extern void __sincosl (long double __x, long double *__sinx, long double *__cosx) throw ();
/* Hyperbolic arc cosine of X. */
extern long double acoshl (long double __x) throw (); extern long double __acoshl (long double __x) throw ();
/* Hyperbolic arc sine of X. */
extern long double asinhl (long double __x) throw (); extern long double __asinhl (long double __x) throw ();
/* Hyperbolic arc tangent of X. */
extern long double atanhl (long double __x) throw (); extern long double __atanhl (long double __x) throw ();
/* Exponential and logarithmic functions. */
/* Exponential function of X. */
extern long double expl (long double __x) throw (); extern long double __expl (long double __x) throw ();
/* Break VALUE into a normalized fraction and an integral power of 2. */
extern long double frexpl (long double __x, int *__exponent) throw (); extern long double __frexpl (long double __x, int *__exponent) throw ();
/* X times (two to the EXP power). */
extern long double ldexpl (long double __x, int __exponent) throw (); extern long double __ldexpl (long double __x, int __exponent) throw ();
/* Natural logarithm of X. */
extern long double logl (long double __x) throw (); extern long double __logl (long double __x) throw ();
/* Base-ten logarithm of X. */
extern long double log10l (long double __x) throw (); extern long double __log10l (long double __x) throw ();
/* Break VALUE into integral and fractional parts. */
extern long double modfl (long double __x, long double *__iptr) throw (); extern long double __modfl (long double __x, long double *__iptr) throw () __attribute__ ((__nonnull__ (2)));
/* A function missing in all standards: compute exponent to base ten. */
extern long double exp10l (long double __x) throw (); extern long double __exp10l (long double __x) throw ();
/* Another name occasionally used. */
extern long double pow10l (long double __x) throw (); extern long double __pow10l (long double __x) throw ();
/* Return exp(X) - 1. */
extern long double expm1l (long double __x) throw (); extern long double __expm1l (long double __x) throw ();
/* Return log(1 + X). */
extern long double log1pl (long double __x) throw (); extern long double __log1pl (long double __x) throw ();
/* Return the base 2 signed integral exponent of X. */
extern long double logbl (long double __x) throw (); extern long double __logbl (long double __x) throw ();
/* Compute base-2 exponential of X. */
extern long double exp2l (long double __x) throw (); extern long double __exp2l (long double __x) throw ();
/* Compute base-2 logarithm of X. */
extern long double log2l (long double __x) throw (); extern long double __log2l (long double __x) throw ();
/* Power functions. */
/* Return X to the Y power. */
extern long double powl (long double __x, long double __y) throw (); extern long double __powl (long double __x, long double __y) throw ();
/* Return the square root of X. */
extern long double sqrtl (long double __x) throw (); extern long double __sqrtl (long double __x) throw ();
/* Return `sqrt(X*X + Y*Y)'. */
extern long double hypotl (long double __x, long double __y) throw (); extern long double __hypotl (long double __x, long double __y) throw ();
/* Return the cube root of X. */
extern long double cbrtl (long double __x) throw (); extern long double __cbrtl (long double __x) throw ();
/* Nearest integer, absolute value, and remainder functions. */
/* Smallest integral value not less than X. */
extern long double ceill (long double __x) throw () __attribute__ ((__const__)); extern long double __ceill (long double __x) throw () __attribute__ ((__const__));
/* Absolute value of X. */
extern long double fabsl (long double __x) throw () __attribute__ ((__const__)); extern long double __fabsl (long double __x) throw () __attribute__ ((__const__));
/* Largest integer not greater than X. */
extern long double floorl (long double __x) throw () __attribute__ ((__const__)); extern long double __floorl (long double __x) throw () __attribute__ ((__const__));
/* Floating-point modulo remainder of X/Y. */
extern long double fmodl (long double __x, long double __y) throw (); extern long double __fmodl (long double __x, long double __y) throw ();
/* Return 0 if VALUE is finite or NaN, +1 if it
is +Infinity, -1 if it is -Infinity. */
extern int __isinfl (long double __value) throw () __attribute__ ((__const__));
/* Return nonzero if VALUE is finite and not NaN. */
extern int __finitel (long double __value) throw () __attribute__ ((__const__));
/* Return 0 if VALUE is finite or NaN, +1 if it
is +Infinity, -1 if it is -Infinity. */
extern int isinfl (long double __value) throw () __attribute__ ((__const__));
/* Return nonzero if VALUE is finite and not NaN. */
extern int finitel (long double __value) throw () __attribute__ ((__const__));
/* Return the remainder of X/Y. */
extern long double dreml (long double __x, long double __y) throw (); extern long double __dreml (long double __x, long double __y) throw ();
/* Return the fractional part of X after dividing out `ilogb (X)'. */
extern long double significandl (long double __x) throw (); extern long double __significandl (long double __x) throw ();
/* Return X with its signed changed to Y's. */
extern long double copysignl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double __copysignl (long double __x, long double __y) throw () __attribute__ ((__const__));
/* Return representation of qNaN for double type. */
extern long double nanl (const char *__tagb) throw () __attribute__ ((__const__)); extern long double __nanl (const char *__tagb) throw () __attribute__ ((__const__));
/* Return nonzero if VALUE is not a number. */
extern int __isnanl (long double __value) throw () __attribute__ ((__const__));
/* Return nonzero if VALUE is not a number. */
extern int isnanl (long double __value) throw () __attribute__ ((__const__));
/* Bessel functions. */
extern long double j0l (long double) throw (); extern long double __j0l (long double) throw ();
extern long double j1l (long double) throw (); extern long double __j1l (long double) throw ();
extern long double jnl (int, long double) throw (); extern long double __jnl (int, long double) throw ();
extern long double y0l (long double) throw (); extern long double __y0l (long double) throw ();
extern long double y1l (long double) throw (); extern long double __y1l (long double) throw ();
extern long double ynl (int, long double) throw (); extern long double __ynl (int, long double) throw ();
/* Error and gamma functions. */
extern long double erfl (long double) throw (); extern long double __erfl (long double) throw ();
extern long double erfcl (long double) throw (); extern long double __erfcl (long double) throw ();
extern long double lgammal (long double) throw (); extern long double __lgammal (long double) throw ();
/* True gamma function. */
extern long double tgammal (long double) throw (); extern long double __tgammal (long double) throw ();
/* Obsolete alias for `lgamma'. */
extern long double gammal (long double) throw (); extern long double __gammal (long double) throw ();
/* Reentrant version of lgamma. This function uses the global variable
`signgam'. The reentrant version instead takes a pointer and stores
the value through it. */
extern long double lgammal_r (long double, int *__signgamp) throw (); extern long double __lgammal_r (long double, int *__signgamp) throw ();
/* Return the integer nearest X in the direction of the
prevailing rounding mode. */
extern long double rintl (long double __x) throw (); extern long double __rintl (long double __x) throw ();
/* Return X + epsilon if X < Y, X - epsilon if X > Y. */
extern long double nextafterl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double __nextafterl (long double __x, long double __y) throw () __attribute__ ((__const__));
extern long double nexttowardl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double __nexttowardl (long double __x, long double __y) throw () __attribute__ ((__const__));
/* Return the remainder of integer divison X / Y with infinite precision. */
extern long double remainderl (long double __x, long double __y) throw (); extern long double __remainderl (long double __x, long double __y) throw ();
/* Return X times (2 to the Nth power). */
extern long double scalbnl (long double __x, int __n) throw (); extern long double __scalbnl (long double __x, int __n) throw ();
/* Return the binary exponent of X, which must be nonzero. */
extern int ilogbl (long double __x) throw (); extern int __ilogbl (long double __x) throw ();
/* Return X times (2 to the Nth power). */
extern long double scalblnl (long double __x, long int __n) throw (); extern long double __scalblnl (long double __x, long int __n) throw ();
/* Round X to integral value in floating-point format using current
rounding direction, but do not raise inexact exception. */
extern long double nearbyintl (long double __x) throw (); extern long double __nearbyintl (long double __x) throw ();
/* Round X to nearest integral value, rounding halfway cases away from
zero. */
extern long double roundl (long double __x) throw () __attribute__ ((__const__)); extern long double __roundl (long double __x) throw () __attribute__ ((__const__));
/* Round X to the integral value in floating-point format nearest but
not larger in magnitude. */
extern long double truncl (long double __x) throw () __attribute__ ((__const__)); extern long double __truncl (long double __x) throw () __attribute__ ((__const__));
/* Compute remainder of X and Y and put in *QUO a value with sign of x/y
and magnitude congruent `mod 2^n' to the magnitude of the integral
quotient x/y, with n >= 3. */
extern long double remquol (long double __x, long double __y, int *__quo) throw (); extern long double __remquol (long double __x, long double __y, int *__quo) throw ();
/* Conversion functions. */
/* Round X to nearest integral value according to current rounding
direction. */
extern long int lrintl (long double __x) throw (); extern long int __lrintl (long double __x) throw ();
__extension__
extern long long int llrintl (long double __x) throw (); extern long long int __llrintl (long double __x) throw ();
/* Round X to nearest integral value, rounding halfway cases away from
zero. */
extern long int lroundl (long double __x) throw (); extern long int __lroundl (long double __x) throw ();
__extension__
extern long long int llroundl (long double __x) throw (); extern long long int __llroundl (long double __x) throw ();
/* Return positive difference between X and Y. */
extern long double fdiml (long double __x, long double __y) throw (); extern long double __fdiml (long double __x, long double __y) throw ();
/* Return maximum numeric value from X and Y. */
extern long double fmaxl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double __fmaxl (long double __x, long double __y) throw () __attribute__ ((__const__));
/* Return minimum numeric value from X and Y. */
extern long double fminl (long double __x, long double __y) throw () __attribute__ ((__const__)); extern long double __fminl (long double __x, long double __y) throw () __attribute__ ((__const__));
/* Classify given number. */
extern int __fpclassifyl (long double __value) throw ()
__attribute__ ((__const__));
/* Test for negative number. */
extern int __signbitl (long double __value) throw ()
__attribute__ ((__const__));
/* Multiply-add function computed as a ternary operation. */
extern long double fmal (long double __x, long double __y, long double __z) throw (); extern long double __fmal (long double __x, long double __y, long double __z) throw ();
/* Test for signaling NaN. */
extern int __issignalingl (long double __value) throw ()
__attribute__ ((__const__));
/* Return X times (2 to the Nth power). */
extern long double scalbl (long double __x, long double __n) throw (); extern long double __scalbl (long double __x, long double __n) throw ();
# 133 "/usr/include/math.h" 2 3 4
# 147 "/usr/include/math.h" 3 4
/* This variable is used by `gamma' and `lgamma'. */
extern int signgam;
/* ISO C99 defines some generic macros which work on any data type. */
/* Get the architecture specific values describing the floating-point
evaluation. The following symbols will get defined:
float_t floating-point type at least as wide as `float' used
to evaluate `float' expressions
double_t floating-point type at least as wide as `double' used
to evaluate `double' expressions
FLT_EVAL_METHOD
Defined to
0 if `float_t' is `float' and `double_t' is `double'
1 if `float_t' and `double_t' are `double'
2 if `float_t' and `double_t' are `long double'
else `float_t' and `double_t' are unspecified
INFINITY representation of the infinity value of type `float'
FP_FAST_FMA
FP_FAST_FMAF
FP_FAST_FMAL
If defined it indicates that the `fma' function
generally executes about as fast as a multiply and an add.
This macro is defined only iff the `fma' function is
implemented directly with a hardware multiply-add instructions.
FP_ILOGB0 Expands to a value returned by `ilogb (0.0)'.
FP_ILOGBNAN Expands to a value returned by `ilogb (NAN)'.
DECIMAL_DIG Number of decimal digits supported by conversion between
decimal and all internal floating-point formats.
*/
/* All floating-point numbers can be put in one of these categories. */
enum
{
FP_NAN =
0,
FP_INFINITE =
1,
FP_ZERO =
2,
FP_SUBNORMAL =
3,
FP_NORMAL =
4
};
/* Return number of classification appropriate for X. */
# 220 "/usr/include/math.h" 3 4
/* Return nonzero value if sign of X is negative. */
# 232 "/usr/include/math.h" 3 4
/* Return nonzero value if X is not +-Inf or NaN. */
# 244 "/usr/include/math.h" 3 4
/* Return nonzero value if X is neither zero, subnormal, Inf, nor NaN. */
/* Return nonzero value if X is a NaN. We could use `fpclassify' but
we already have this functions `__isnan' and it is faster. */
# 260 "/usr/include/math.h" 3 4
/* Return nonzero value if X is positive or negative infinity. */
# 272 "/usr/include/math.h" 3 4
/* Bitmasks for the math_errhandling macro. */
/* By default all functions support both errno and exception handling.
In gcc's fast math mode and if inline functions are defined this
might not be true. */
/* Return nonzero value if X is a signaling NaN. */
# 300 "/usr/include/math.h" 3 4
/* Support for various different standard error handling behaviors. */
typedef enum
{
_IEEE_ = -1, /* According to IEEE 754/IEEE 854. */
_SVID_, /* According to System V, release 4. */
_XOPEN_, /* Nowadays also Unix98. */
_POSIX_,
_ISOC_ /* Actually this is ISO C99. */
} _LIB_VERSION_TYPE;
/* This variable can be changed at run-time to any of the values above to
affect floating point error handling behavior (it may also be necessary
to change the hardware FPU exception settings). */
extern _LIB_VERSION_TYPE _LIB_VERSION;
/* In SVID error handling, `matherr' is called with this description
of the exceptional condition.
We have a problem when using C++ since `exception' is a reserved
name in C++. */
struct __exception
{
int type;
char *name;
double arg1;
double arg2;
double retval;
};
extern int matherr (struct __exception *__exc) throw ();
/* Types of exceptions in the `type' field. */
/* SVID mode specifies returning this large value instead of infinity. */
# 365 "/usr/include/math.h" 3 4
/* Some useful constants. */
# 382 "/usr/include/math.h" 3 4
/* The above constants are not adequate for computation using `long double's.
Therefore we provide as an extension constants with similar names as a
GNU extension. Provide enough digits for the 128-bit IEEE quad. */
# 402 "/usr/include/math.h" 3 4
/* When compiling in strict ISO C compatible mode we must not use the
inline functions since they, among other things, do not set the
`errno' variable correctly. */
/* ISO C99 defines some macros to compare number while taking care for
unordered numbers. Many FPUs provide special instructions to support
these operations. Generic support in GCC for these as builtins went
in before 3.0.0, but not all cpus added their patterns. We define
versions that use the builtins here, and <bits/mathinline.h> will
undef/redefine as appropriate for the specific GCC version in use. */
# 424 "/usr/include/math.h" 3 4
/* Get machine-dependent inline versions (if there are any). */
/* Define special entry points to use when the compiler got told to
only expect finite results. */
/* If we've still got undefined comparison macros, provide defaults. */
/* Return nonzero value if X is greater than Y. */
/* Return nonzero value if X is greater than or equal to Y. */
/* Return nonzero value if X is less than Y. */
/* Return nonzero value if X is less than or equal to Y. */
/* Return nonzero value if either X is less than Y or Y is less than X. */
/* Return nonzero value if arguments are unordered. */
# 488 "/usr/include/math.h" 3 4
}
# 46 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 2 3
}
# 46 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath"
// Get rid of those macros defined in <math.h> in lieu of real functions.
# 76 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 3
namespace std __attribute__ ((__visibility__ ("default")))
{
inline double
abs(double __x)
{ return __builtin_fabs(__x); }
inline float
abs(float __x)
{ return __builtin_fabsf(__x); }
inline long double
abs(long double __x)
{ return __builtin_fabsl(__x); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
abs(_Tp __x)
{ return __builtin_fabs(__x); }
using ::acos;
inline float
acos(float __x)
{ return __builtin_acosf(__x); }
inline long double
acos(long double __x)
{ return __builtin_acosl(__x); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
acos(_Tp __x)
{ return __builtin_acos(__x); }
using ::asin;
inline float
asin(float __x)
{ return __builtin_asinf(__x); }
inline long double
asin(long double __x)
{ return __builtin_asinl(__x); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
asin(_Tp __x)
{ return __builtin_asin(__x); }
using ::atan;
inline float
atan(float __x)
{ return __builtin_atanf(__x); }
inline long double
atan(long double __x)
{ return __builtin_atanl(__x); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
atan(_Tp __x)
{ return __builtin_atan(__x); }
using ::atan2;
inline float
atan2(float __y, float __x)
{ return __builtin_atan2f(__y, __x); }
inline long double
atan2(long double __y, long double __x)
{ return __builtin_atan2l(__y, __x); }
template<typename _Tp, typename _Up>
inline
typename __gnu_cxx::__promote_2<_Tp, _Up>::__type
atan2(_Tp __y, _Up __x)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return atan2(__type(__y), __type(__x));
}
using ::ceil;
inline float
ceil(float __x)
{ return __builtin_ceilf(__x); }
inline long double
ceil(long double __x)
{ return __builtin_ceill(__x); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
ceil(_Tp __x)
{ return __builtin_ceil(__x); }
using ::cos;
inline float
cos(float __x)
{ return __builtin_cosf(__x); }
inline long double
cos(long double __x)
{ return __builtin_cosl(__x); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
cos(_Tp __x)
{ return __builtin_cos(__x); }
using ::cosh;
inline float
cosh(float __x)
{ return __builtin_coshf(__x); }
inline long double
cosh(long double __x)
{ return __builtin_coshl(__x); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
cosh(_Tp __x)
{ return __builtin_cosh(__x); }
using ::exp;
inline float
exp(float __x)
{ return __builtin_expf(__x); }
inline long double
exp(long double __x)
{ return __builtin_expl(__x); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
exp(_Tp __x)
{ return __builtin_exp(__x); }
using ::fabs;
inline float
fabs(float __x)
{ return __builtin_fabsf(__x); }
inline long double
fabs(long double __x)
{ return __builtin_fabsl(__x); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
fabs(_Tp __x)
{ return __builtin_fabs(__x); }
using ::floor;
inline float
floor(float __x)
{ return __builtin_floorf(__x); }
inline long double
floor(long double __x)
{ return __builtin_floorl(__x); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
floor(_Tp __x)
{ return __builtin_floor(__x); }
using ::fmod;
inline float
fmod(float __x, float __y)
{ return __builtin_fmodf(__x, __y); }
inline long double
fmod(long double __x, long double __y)
{ return __builtin_fmodl(__x, __y); }
using ::frexp;
inline float
frexp(float __x, int* __exp)
{ return __builtin_frexpf(__x, __exp); }
inline long double
frexp(long double __x, int* __exp)
{ return __builtin_frexpl(__x, __exp); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
frexp(_Tp __x, int* __exp)
{ return __builtin_frexp(__x, __exp); }
using ::ldexp;
inline float
ldexp(float __x, int __exp)
{ return __builtin_ldexpf(__x, __exp); }
inline long double
ldexp(long double __x, int __exp)
{ return __builtin_ldexpl(__x, __exp); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
ldexp(_Tp __x, int __exp)
{ return __builtin_ldexp(__x, __exp); }
using ::log;
inline float
log(float __x)
{ return __builtin_logf(__x); }
inline long double
log(long double __x)
{ return __builtin_logl(__x); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
log(_Tp __x)
{ return __builtin_log(__x); }
using ::log10;
inline float
log10(float __x)
{ return __builtin_log10f(__x); }
inline long double
log10(long double __x)
{ return __builtin_log10l(__x); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
log10(_Tp __x)
{ return __builtin_log10(__x); }
using ::modf;
inline float
modf(float __x, float* __iptr)
{ return __builtin_modff(__x, __iptr); }
inline long double
modf(long double __x, long double* __iptr)
{ return __builtin_modfl(__x, __iptr); }
using ::pow;
inline float
pow(float __x, float __y)
{ return __builtin_powf(__x, __y); }
inline long double
pow(long double __x, long double __y)
{ return __builtin_powl(__x, __y); }
// _GLIBCXX_RESOLVE_LIB_DEFECTS
// DR 550. What should the return type of pow(float,int) be?
inline double
pow(double __x, int __i)
{ return __builtin_powi(__x, __i); }
inline float
pow(float __x, int __n)
{ return __builtin_powif(__x, __n); }
inline long double
pow(long double __x, int __n)
{ return __builtin_powil(__x, __n); }
template<typename _Tp, typename _Up>
inline
typename __gnu_cxx::__promote_2<_Tp, _Up>::__type
pow(_Tp __x, _Up __y)
{
typedef typename __gnu_cxx::__promote_2<_Tp, _Up>::__type __type;
return pow(__type(__x), __type(__y));
}
using ::sin;
inline float
sin(float __x)
{ return __builtin_sinf(__x); }
inline long double
sin(long double __x)
{ return __builtin_sinl(__x); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
sin(_Tp __x)
{ return __builtin_sin(__x); }
using ::sinh;
inline float
sinh(float __x)
{ return __builtin_sinhf(__x); }
inline long double
sinh(long double __x)
{ return __builtin_sinhl(__x); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
sinh(_Tp __x)
{ return __builtin_sinh(__x); }
using ::sqrt;
inline float
sqrt(float __x)
{ return __builtin_sqrtf(__x); }
inline long double
sqrt(long double __x)
{ return __builtin_sqrtl(__x); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
sqrt(_Tp __x)
{ return __builtin_sqrt(__x); }
using ::tan;
inline float
tan(float __x)
{ return __builtin_tanf(__x); }
inline long double
tan(long double __x)
{ return __builtin_tanl(__x); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
tan(_Tp __x)
{ return __builtin_tan(__x); }
using ::tanh;
inline float
tanh(float __x)
{ return __builtin_tanhf(__x); }
inline long double
tanh(long double __x)
{ return __builtin_tanhl(__x); }
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_integer<_Tp>::__value,
double>::__type
tanh(_Tp __x)
{ return __builtin_tanh(__x); }
} // namespace
// These are possible macros imported from C99-land.
# 480 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 3
namespace std __attribute__ ((__visibility__ ("default")))
{
# 730 "/opt/Xilinx/Vivado_HLS/2015.1/lnx64/tools/gcc/lib/gcc/x86_64-unknown-linux-gnu/4.6.3/../../../../include/c++/4.6.3/cmath" 3
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
fpclassify(_Tp __f)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_fpclassify(0, 1, 4,
3, 2, __type(__f));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
isfinite(_Tp __f)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_isfinite(__type(__f));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
isinf(_Tp __f)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_isinf(__type(__f));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
isnan(_Tp __f)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_isnan(__type(__f));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
isnormal(_Tp __f)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_isnormal(__type(__f));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
signbit(_Tp __f)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_signbit(__type(__f));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
isgreater(_Tp __f1, _Tp __f2)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_isgreater(__type(__f1), __type(__f2));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
isgreaterequal(_Tp __f1, _Tp __f2)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_isgreaterequal(__type(__f1), __type(__f2));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
isless(_Tp __f1, _Tp __f2)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_isless(__type(__f1), __type(__f2));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
islessequal(_Tp __f1, _Tp __f2)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_islessequal(__type(__f1), __type(__f2));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
islessgreater(_Tp __f1, _Tp __f2)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_islessgreater(__type(__f1), __type(__f2));
}
template<typename _Tp>
inline typename __gnu_cxx::__enable_if<__is_arithmetic<_Tp>::__value,
int>::__type
isunordered(_Tp __f1, _Tp __f2)
{
typedef typename __gnu_cxx::__promote<_Tp>::__type __type;
return __builtin_isunordered(__type(__f1), __type(__f2));
}
} // namespace
# 50 "./matrixmul.h" 2
using namespace std;
// Compare TB vs HW C-model and/or RTL
typedef char mat_a_t;
typedef char mat_b_t;
typedef short result_t;
// Prototype of top level function for C-synthesis
void matrixmul(
mat_a_t a[3][3],
mat_b_t b[3][3],
result_t res[3][3]);
# 47 "matrixmul.cpp" 2
void matrixmul(
mat_a_t a[3][3],
mat_b_t b[3][3],
result_t res[3][3])
{_ssdm_SpecArrayDimSize(a,3);_ssdm_SpecArrayDimSize(res,3);_ssdm_SpecArrayDimSize(b,3);
_ssdm_op_SpecPipeline(1, 1, 1, 0, "");
# 52 "matrixmul.cpp"
_ssdm_op_SpecInterface(res, "ap_fifo", 0, 0, 0, 0, "", "", "");
# 52 "matrixmul.cpp"
_ssdm_op_SpecInterface(b, "ap_fifo", 0, 0, 0, 0, "", "", "");
# 52 "matrixmul.cpp"
_ssdm_op_SpecInterface(a, "ap_fifo", 0, 0, 0, 0, "", "", "");
# 52 "matrixmul.cpp"
_ssdm_SpecArrayReshape( b, 1, "COMPLETE", 0, "");
# 52 "matrixmul.cpp"
_ssdm_SpecArrayReshape( a, 2, "COMPLETE", 0, "");
# 52 "matrixmul.cpp"
// Iterate over the rows of the A matrix
Row: for(int i = 0; i < 3; i++) {
// Iterate over the columns of the B matrix
Col: for(int j = 0; j < 3; j++) {
res[i][j] = 0;
// Do the inner product of a row of A and col of B
Product: for(int k = 0; k < 3; k++) {
_ssdm_op_SpecPipeline(1, 1, 1, 0, "");
# 59 "matrixmul.cpp"
res[i][j] += a[i][k] * b[k][j];
}
}
}
}
| [
"thnguyn2@illinois.edu"
] | thnguyn2@illinois.edu |
4006e1275a8814d35aa33b12458da58c9f66194b | 6ac472b164ab25ba3341738abb590c7acd58e1f6 | /functions.cpp | 086b68d9bf7d074e3e005bb7810d9bcc0edf393c | [] | no_license | Hilwynn/codecademy-ufo-hangman | f16e8304a82443cf46716303a80159482e209986 | 63e13296155827f3baf6162743f4e49d526bbd2f | refs/heads/master | 2020-12-08T13:53:54.510185 | 2020-01-10T10:45:09 | 2020-01-10T10:45:09 | 232,997,320 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,515 | cpp | #include <iostream>
#include <vector>
void greet()
{
std::cout << "\n\n";
std::cout << "=============\n";
std::cout << "UFO: The Game\n";
std::cout << "=============\n";
std::cout << "Instructions: save your friend from alien abduction\nby guessing the letters in the codeword.\n";
}
void display_misses(int misses)
{
if (misses == 0 || misses == 1)
{
std::cout << " . \n";
std::cout << " | \n";
std::cout << " .-\"^\"-. \n";
std::cout << " /_....._\\ \n";
std::cout << " .-\"` `\"-. \n";
std::cout << " ( ooo ooo ooo ) \n";
std::cout << " '-.,_________,.-' ,-----------. \n";
std::cout << " / \\ ( Send help! ) \n";
std::cout << " / 0 \\ / `-----------' \n";
std::cout << " / --|-- \\ / \n";
std::cout << " / | \\ \n";
std::cout << " / / \\ \\ \n";
std::cout << " / \\ \n";
}
else if (misses == 2)
{
std::cout << " . \n";
std::cout << " | \n";
std::cout << " .-\"^\"-. \n";
std::cout << " /_....._\\ \n";
std::cout << " .-\"` `\"-. \n";
std::cout << " ( ooo ooo ooo ) \n";
std::cout << " '-.,_________,.-' ,-----------. \n";
std::cout << " / 0 \\ ( Send help! ) \n";
std::cout << " / --|-- \\ / `-----------' \n";
std::cout << " / | \\ / \n";
std::cout << " / / \\ \\ \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
}
else if (misses == 3)
{
std::cout << " . \n";
std::cout << " | \n";
std::cout << " .-\"^\"-. \n";
std::cout << " /_....._\\ \n";
std::cout << " .-\"` `\"-. \n";
std::cout << " ( ooo ooo ooo ) \n";
std::cout << " '-.,_________,.-' ,-----------. \n";
std::cout << " /--|--\\ ( Send help! ) \n";
std::cout << " / | \\ / `-----------' \n";
std::cout << " / / \\ \\ / \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
}
else if (misses == 3)
{
std::cout << " . \n";
std::cout << " | \n";
std::cout << " .-\"^\"-. \n";
std::cout << " /_....._\\ \n";
std::cout << " .-\"` `\"-. \n";
std::cout << " ( ooo ooo ooo ) \n";
std::cout << " '-.,_________,.-' ,-----------. \n";
std::cout << " /--|--\\ ( Send help! ) \n";
std::cout << " / | \\ / `-----------' \n";
std::cout << " / / \\ \\ / \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
}
else if (misses == 4)
{
std::cout << " . \n";
std::cout << " | \n";
std::cout << " .-\"^\"-. \n";
std::cout << " /_....._\\ \n";
std::cout << " .-\"` `\"-. \n";
std::cout << " ( ooo ooo ooo ) \n";
std::cout << " '-.,_________,.-' ,-----------. \n";
std::cout << " / | \\ ( Send help! ) \n";
std::cout << " / / \\ \\ / `-----------' \n";
std::cout << " / \\ / \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
}
else if (misses == 5)
{
std::cout << " . \n";
std::cout << " | \n";
std::cout << " .-\"^\"-. \n";
std::cout << " /_....._\\ \n";
std::cout << " .-\"` `\"-. \n";
std::cout << " ( ooo ooo ooo ) \n";
std::cout << " '-.,_________,.-' ,-----------. \n";
std::cout << " / / \\ \\ ( Send help! )\n";
std::cout << " / \\ / `-----------' \n";
std::cout << " / \\ / \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
}
else if (misses == 6)
{
std::cout << " . \n";
std::cout << " | \n";
std::cout << " .-\"^\"-. \n";
std::cout << " /_....._\\ \n";
std::cout << " .-\"` `\"-. \n";
std::cout << " ( ooo ooo ooo ) \n";
std::cout << " '-.,_________,.-' ,-----------. \n";
std::cout << " / \\ ( Send help! ) \n";
std::cout << " / \\ / `-----------' \n";
std::cout << " / \\ / \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
std::cout << " / \\ \n";
}
}
void display_status(std::vector<char> incorrect, std::string answer)
{
std::cout << "\nIncorrect Guesses:\n";
for (int i = 0; i < incorrect.size(); i++)
{
std::cout << incorrect[i] << ' ';
}
std::cout << "\nCodeword:\n";
for (int i = 0; i < answer.length(); i++)
{
std::cout << answer[i] << ' ';
}
}
void end_game(std::string answer, std::string codeword)
{
if (answer == codeword)
{
std::cout << "Hooray! You saved the person and earned a medal of honor!\n";
}
else
{
std::cout << "Oh no! The UFO just flew away with another person!\n";
std::cout << "The correct word was \"" << codeword << "\".\n";
}
} | [
"anna.erkers@willandskill.se"
] | anna.erkers@willandskill.se |
b1833af2237723128ccc95dc682a092b5eaf853a | 194a52ea520eddedebf2bb7bf1a81edfeb28d671 | /doc/polybar/src/components/parser.cpp | eb5069a9f6226fe38aa2966b499e1aaf3c0390be | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | Cris-lml007/AUTO-BSPWM | df73cd02d257985ed30dface004be9251954b210 | dc4b32b922fbf9eccab90461e3189b33e951cf2b | refs/heads/master | 2023-07-06T07:08:12.336261 | 2021-08-14T06:55:43 | 2021-08-14T06:55:43 | 395,891,311 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,747 | cpp | #include "components/parser.hpp"
#include <cassert>
#include "components/types.hpp"
#include "events/signal.hpp"
#include "events/signal_emitter.hpp"
#include "settings.hpp"
#include "utils/color.hpp"
#include "utils/factory.hpp"
#include "utils/memory.hpp"
#include "utils/string.hpp"
POLYBAR_NS
using namespace signals::parser;
/**
* Create instance
*/
parser::make_type parser::make() {
return factory_util::unique<parser>(signal_emitter::make());
}
/**
* Construct parser instance
*/
parser::parser(signal_emitter& emitter) : m_sig(emitter) {}
/**
* Process input string
*/
void parser::parse(const bar_settings& bar, string data) {
while (!data.empty()) {
size_t pos{string::npos};
if (data.compare(0, 2, "%{") == 0 && (pos = data.find('}')) != string::npos) {
codeblock(data.substr(2, pos - 2), bar);
data.erase(0, pos + 1);
} else if ((pos = data.find("%{")) != string::npos) {
data.erase(0, text(data.substr(0, pos)));
} else {
data.erase(0, text(data.substr(0)));
}
}
if (!m_actions.empty()) {
throw unclosed_actionblocks(to_string(m_actions.size()) + " unclosed action block(s)");
}
}
/**
* Process contents within tag blocks, i.e: %{...}
*/
void parser::codeblock(string&& data, const bar_settings& bar) {
size_t pos;
while (data.length()) {
data = string_util::ltrim(move(data), ' ');
if (data.empty()) {
break;
}
char tag{data[0]};
/*
* Contains the string from the current position to the next space or
* closing curly bracket (})
*
* This may be unsuitable for some tags (e.g. action tag) to use
* These MUST set value to the actual string they parsed from the beginning
* of data (or a string with the same length). The length of value is used
* to progress the cursor further.
*
* example:
*
* data = A1:echo "test": ...}
*
* erase(0,1)
* -> data = 1:echo "test": ...}
*
* case 'A', parse_action_cmd
* -> value = echo "test"
*
* Padding value
* -> value = echo "test"0::
*
* erase(0, value.length())
* -> data = ...}
*
*/
string value;
// Remove the tag
data.erase(0, 1);
if ((pos = data.find_first_of(" }")) != string::npos) {
value = data.substr(0, pos);
} else {
value = data;
}
switch (tag) {
case 'B':
m_sig.emit(change_background{parse_color(value, bar.background)});
break;
case 'F':
m_sig.emit(change_foreground{parse_color(value, bar.foreground)});
break;
case 'T':
m_sig.emit(change_font{parse_fontindex(value)});
break;
case 'U':
m_sig.emit(change_underline{parse_color(value, bar.underline.color)});
m_sig.emit(change_overline{parse_color(value, bar.overline.color)});
break;
case 'u':
m_sig.emit(change_underline{parse_color(value, bar.underline.color)});
break;
case 'o':
m_sig.emit(change_overline{parse_color(value, bar.overline.color)});
break;
case 'R':
m_sig.emit(reverse_colors{});
break;
case 'O':
m_sig.emit(offset_pixel{static_cast<int>(std::strtol(value.c_str(), nullptr, 10))});
break;
case 'l':
m_sig.emit(change_alignment{alignment::LEFT});
break;
case 'c':
m_sig.emit(change_alignment{alignment::CENTER});
break;
case 'r':
m_sig.emit(change_alignment{alignment::RIGHT});
break;
case '+':
m_sig.emit(attribute_set{parse_attr(value[0])});
break;
case '-':
m_sig.emit(attribute_unset{parse_attr(value[0])});
break;
case '!':
m_sig.emit(attribute_toggle{parse_attr(value[0])});
break;
case 'A': {
bool has_btn_id = (data[0] != ':');
if (isdigit(data[0]) || !has_btn_id) {
value = parse_action_cmd(data.substr(has_btn_id ? 1 : 0));
mousebtn btn = parse_action_btn(data);
m_actions.push_back(static_cast<int>(btn));
// Unescape colons inside command before sending it to the renderer
auto cmd = string_util::replace_all(value, "\\:", ":");
m_sig.emit(action_begin{action{btn, cmd}});
/*
* make sure value has the same length as the inside of the action
* tag which is btn_id + ':' + value + ':'
*/
if (has_btn_id) {
value += "0";
}
value += "::";
} else if (!m_actions.empty()) {
m_sig.emit(action_end{parse_action_btn(value)});
m_actions.pop_back();
}
break;
}
// Internal Polybar control tags
case 'P':
m_sig.emit(control{parse_control(value)});
break;
default:
throw unrecognized_token("Unrecognized token '" + string{tag} + "'");
}
if (!data.empty()) {
// Remove the parsed string from data
data.erase(0, !value.empty() ? value.length() : 1);
}
}
}
/**
* Process text contents
*/
size_t parser::text(string&& data) {
#ifdef DEBUG_WHITESPACE
string::size_type p;
while ((p = data.find(' ')) != string::npos) {
data.replace(p, 1, "-"s);
}
#endif
m_sig.emit(signals::parser::text{forward<string>(data)});
return data.size();
}
/**
* Process color hex string and convert it to the correct value
*/
rgba parser::parse_color(const string& s, rgba fallback) {
if (!s.empty() && s[0] != '-') {
rgba ret = rgba{s};
if (!ret.has_color() || ret.type() == rgba::ALPHA_ONLY) {
logger::make().warn(
"Invalid color in formatting tag detected: \"%s\", using fallback \"%s\". This is an issue with one of your "
"formatting tags. If it is not, please report this as a bug.",
s, static_cast<string>(fallback));
return fallback;
}
return ret;
}
return fallback;
}
/**
* Process font index and convert it to the correct value
*/
int parser::parse_fontindex(const string& s) {
if (s.empty() || s[0] == '-') {
return 0;
}
try {
return std::stoul(s, nullptr, 10);
} catch (const std::invalid_argument& err) {
return 0;
}
}
/**
* Process attribute token and convert it to the correct value
*/
attribute parser::parse_attr(const char attr) {
switch (attr) {
case 'o':
return attribute::OVERLINE;
case 'u':
return attribute::UNDERLINE;
default:
throw unrecognized_token("Unrecognized attribute '" + string{attr} + "'");
}
}
/**
* Process action button token and convert it to the correct value
*/
mousebtn parser::parse_action_btn(const string& data) {
if (data[0] == ':') {
return mousebtn::LEFT;
} else if (isdigit(data[0])) {
return static_cast<mousebtn>(data[0] - '0');
} else if (!m_actions.empty()) {
return static_cast<mousebtn>(m_actions.back());
} else {
return mousebtn::NONE;
}
}
/**
* Process action command string
*
* data is the action cmd surrounded by unescaped colons followed by an
* arbitrary string
*
* Returns everything inside the unescaped colons as is
*/
string parser::parse_action_cmd(string&& data) {
if (data[0] != ':') {
return "";
}
size_t end{1};
while ((end = data.find(':', end)) != string::npos && data[end - 1] == '\\') {
end++;
}
if (end == string::npos) {
return "";
}
return data.substr(1, end - 1);
}
controltag parser::parse_control(const string& data) {
if (data.length() != 1) {
return controltag::NONE;
}
switch (data[0]) {
case 'R':
return controltag::R;
break;
default:
return controltag::NONE;
break;
}
}
POLYBAR_NS_END
| [
"cristianmanuel007@gmail.com"
] | cristianmanuel007@gmail.com |
c6faeb2371007fc91924e7cedddbd89de58e7d67 | f2279faca9b56f013988a88f9ba01555f1134889 | /Sept24/StaticDataFunc.cpp | df182a54dc301189dd7d4cf55b4b1b287ddc97eb | [] | no_license | nish235/C-CppAssignments | c8f36ff83a06391799feb6eb7efab6cd4c8d52bf | 5eb8bf3d2f91fcc7a8527ecf81efec3f5dda1dda | refs/heads/master | 2022-12-27T03:19:41.868628 | 2020-10-09T11:52:29 | 2020-10-09T11:52:29 | 292,768,840 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 535 | cpp | #include<iostream>
using namespace std;
class one
{
static int Number;
int n;
public:
void set_n()
{
n = ++Number;
}
void show_n()
{
cout<<"value of n = "<<n<<endl;
}
static void show_Number()
{
cout<<"value of Number = "<<Number<<endl;
}
};
int one:: Number;
int main()
{
one ex1, ex2;
ex1.set_n();
ex2.set_n();
ex1.show_n();
ex2.show_n();
one::show_Number();
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
5d3150f239bc4cb5e23b323086691369b354716d | b998b3161d8501f6d9361f0b85ede0d7b5b4e6a4 | /src/MMap/MMapFile.cc | 68834395185a62b044adb260936c0d8c5593d3cd | [] | permissive | revivalfx/DataFrame | 42d4405d746ca0eacb2572a5a45c8ab60d3f129a | b99cbc604f87be861cf682d53dafa24067706b0c | refs/heads/master | 2021-01-14T06:42:24.349525 | 2020-03-11T03:34:58 | 2020-03-11T03:34:58 | 242,629,833 | 0 | 0 | BSD-3-Clause | 2020-02-24T02:31:02 | 2020-02-24T02:31:02 | null | UTF-8 | C++ | false | false | 3,541 | cc | // Hossein Moein
// May 28, 2019
/*
Copyright (c) 2019-2022, Hossein Moein
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 Hossein Moein and/or the DataFrame 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 <COPYRIGHT HOLDER> BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _WIN32
#include <DataFrame/MMap/MMapFile.h>
#include <DataFrame/Utils/FixedSizeString.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
// ----------------------------------------------------------------------------
namespace hmdf
{
bool MMapFile::open () {
if (is_open ())
throw std::runtime_error (
"MMapFile::open(): The device is already open");
_file_desc = ::open (get_file_name (), _file_open_flags, _file_open_mode);
if (_file_desc > 0) {
struct stat stat_data;
if (! ::fstat (_file_desc, &stat_data))
_file_size = stat_data.st_size;
else {
String2K err;
err.printf ("MMapFile::open(): ::fstat(): (%d) %s -- %s",
errno, strerror (errno), get_file_name ());
::close (_file_desc);
_file_desc = 0;
throw std::runtime_error (err.c_str ());
}
}
else {
String2K err;
err.printf ("MMapFile::open(): ::open(): (%d) %s -- %s",
errno, ::strerror (errno), get_file_name ());
_file_desc = 0;
throw std::runtime_error (err.c_str ());
}
return (_initial_map (_file_size, _mmap_prot, _mmap_flags, _file_desc));
}
// ----------------------------------------------------------------------------
void MMapFile::unlink () {
if (is_open ())
close ();
if (::unlink (get_file_name ()) < 0) {
String2K err;
err.printf ("MMapFile::unlink(): ::unlink(): (%d) %s -- %s",
errno, ::strerror (errno), get_file_name ());
throw std::runtime_error (err.c_str ());
}
return;
}
} // namespace hmdf
#endif // _WIN32
// ----------------------------------------------------------------------------
// Local Variables:
// mode:C++
// tab-width:4
// c-basic-offset:4
// End:
| [
"hossein.moein@kensho.com"
] | hossein.moein@kensho.com |
420ede90a9ae27148cf7ed84d43bbb5305a7ebd2 | 7767d050a80638b8dc2f80175eca3155ddedfeaf | /widget.cpp | ae38a2d3a6a28ac7b2f7b1acf779991479ddc842 | [] | no_license | knipl/Tanks | a0ff62f87032e3ebb11cba45d9166fe7592047a9 | 74738930504f3ddb0e702f36e2fc1cab832da90d | refs/heads/master | 2021-01-10T08:28:04.502132 | 2015-05-25T04:16:22 | 2015-05-25T04:16:22 | 36,188,413 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 213 | cpp | #include "widget.hpp"
Widget::Widget(float _x, float _y, float _mx, float _my)
{
x=_x;
y=_y;
mx=_mx;
my=_my;
fokuszalva = 0;
}
void Widget::rajzol() {}
void Widget::klikk(genv::event ev) {}
| [
"knipl.gergely@gmail.com"
] | knipl.gergely@gmail.com |
e23f901e32e5bc55eb8142bc702321418baba087 | 2af28d499c4865311d7b350d7b8f96305af05407 | /inference-engine/src/mkldnn_plugin/nodes/common/softmax.cpp | 53eee18eb967ddb4d5f647a7a3ae5db3ec300662 | [
"Apache-2.0"
] | permissive | Dipet/dldt | cfccedac9a4c38457ea49b901c8c645f8805a64b | 549aac9ca210cc5f628a63174daf3e192b8d137e | refs/heads/master | 2021-02-15T11:19:34.938541 | 2020-03-05T15:12:30 | 2020-03-05T15:12:30 | 244,893,475 | 1 | 0 | Apache-2.0 | 2020-03-04T12:22:46 | 2020-03-04T12:22:45 | null | UTF-8 | C++ | false | false | 6,845 | cpp | // Copyright (C) 2019 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//
#include <vector>
#include <algorithm>
#include <ie_parallel.hpp>
#include "jit_generator.hpp"
#include "jit_uni_eltwise.hpp"
#include "softmax.h"
using namespace InferenceEngine;
using namespace mkldnn::impl::cpu;
using namespace mkldnn::impl::utils;
#define GET_OFF(field) offsetof(jit_args_softmax, field)
struct jit_args_softmax {
const float* src;
const float* dst;
size_t stride;
size_t work_amount;
};
struct jit_uni_softmax_kernel {
void (*ker_)(const jit_args_softmax *);
void operator()(const jit_args_softmax *args) { assert(ker_); ker_(args); }
jit_uni_softmax_kernel() : ker_(nullptr) {}
virtual ~jit_uni_softmax_kernel() {}
};
template <cpu_isa_t isa>
struct jit_uni_softmax_kernel_f32 : public jit_uni_softmax_kernel, public jit_generator {
DECLARE_CPU_JIT_AUX_FUNCTIONS(jit_uni_softmax_kernel_f32)
jit_uni_softmax_kernel_f32() : jit_uni_softmax_kernel(), jit_generator() {
exp_injector.reset(new jit_uni_eltwise_injector_f32<isa>(this, alg_kind::eltwise_exp, 0.f, 0.f));
this->preamble();
mov(reg_src, ptr[reg_params + GET_OFF(src)]);
mov(reg_dst, ptr[reg_params + GET_OFF(dst)]);
mov(reg_stride, ptr[reg_params + GET_OFF(stride)]);
mov(reg_work_amount, ptr[reg_params + GET_OFF(work_amount)]);
Xbyak::Label max_loop_label;
Xbyak::Label max_loop_end_label;
Xbyak::Label exp_loop_label;
Xbyak::Label exp_loop_end_label;
Xbyak::Label div_loop_label;
Xbyak::Label div_loop_end_label;
mov(aux_reg_work_amount, reg_work_amount);
mov(aux_reg_src, reg_src);
uni_vmovups(vmm_max, ptr[aux_reg_src]);
L(max_loop_label); {
cmp(aux_reg_work_amount, 0);
jle(max_loop_end_label, T_NEAR);
uni_vmovups(vmm_val, ptr[aux_reg_src]);
if (isa == sse42) {
uni_vmovups(vmm_mask, vmm_val);
uni_vcmpgtps(vmm_mask, vmm_mask, vmm_max);
} else if (isa == avx2) {
uni_vcmpgtps(vmm_mask, vmm_val, vmm_max);
} else {
vcmpps(k_mask, vmm_val, vmm_max, _cmp_nle_us);
}
if (isa == avx512_common) {
vptestmd(k_mask, vmm_mask, vmm_mask);
vblendmps(vmm_max | k_mask, vmm_max, vmm_val);
} else {
uni_vblendvps(vmm_max, vmm_max, vmm_val, vmm_mask);
}
add(aux_reg_src, reg_stride);
sub(aux_reg_work_amount, 1);
jmp(max_loop_label, T_NEAR);
}
L(max_loop_end_label);
mov(aux_reg_work_amount, reg_work_amount);
mov(aux_reg_src, reg_src);
mov(aux_reg_dst, reg_dst);
uni_vpxor(vmm_exp_sum, vmm_exp_sum, vmm_exp_sum);
L(exp_loop_label); {
cmp(aux_reg_work_amount, 0);
jle(exp_loop_end_label, T_NEAR);
uni_vmovups(vmm_val, ptr[aux_reg_src]);
uni_vsubps(vmm_val, vmm_val, vmm_max);
exp_injector->compute_vector_range(vmm_val.getIdx(), vmm_val.getIdx() + 1);
uni_vaddps(vmm_exp_sum, vmm_exp_sum, vmm_val);
uni_vmovups(ptr[aux_reg_dst], vmm_val);
add(aux_reg_src, reg_stride);
add(aux_reg_dst, reg_stride);
sub(aux_reg_work_amount, 1);
jmp(exp_loop_label, T_NEAR);
}
L(exp_loop_end_label);
mov(aux_reg_work_amount, reg_work_amount);
mov(aux_reg_dst, reg_dst);
L(div_loop_label); {
cmp(aux_reg_work_amount, 0);
jle(div_loop_end_label, T_NEAR);
uni_vmovups(vmm_val, ptr[aux_reg_dst]);
uni_vdivps(vmm_val, vmm_val, vmm_exp_sum);
uni_vmovups(ptr[aux_reg_dst], vmm_val);
add(aux_reg_dst, reg_stride);
sub(aux_reg_work_amount, 1);
jmp(div_loop_label, T_NEAR);
}
L(div_loop_end_label);
this->postamble();
exp_injector->prepare_table();
ker_ = (decltype(ker_))this->getCode();
}
private:
using Vmm = typename conditional3<isa == sse42, Xbyak::Xmm, isa == avx2, Xbyak::Ymm, Xbyak::Zmm>::type;
size_t vlen = cpu_isa_traits<isa>::vlen;
Xbyak::Reg64 reg_src = r8;
Xbyak::Reg64 aux_reg_src = r13;
Xbyak::Reg64 reg_dst = r9;
Xbyak::Reg64 aux_reg_dst = r15;
Xbyak::Reg64 reg_work_amount = r11;
Xbyak::Reg64 aux_reg_work_amount = r12;
Xbyak::Reg64 reg_stride = r14;
Xbyak::Reg64 reg_params = abi_param1;
Vmm vmm_mask = Vmm(0);
Vmm vmm_val = Vmm(1);
Vmm vmm_max = Vmm(2);
Vmm vmm_exp_sum = Vmm(3);
const Xbyak::Opmask k_mask = Xbyak::Opmask(1);
std::shared_ptr<jit_uni_eltwise_injector_f32<isa>> exp_injector;
};
SoftmaxGeneric::SoftmaxGeneric() {
block_size = 1;
if (mayiuse(avx512_common)) {
softmax_kernel.reset(new jit_uni_softmax_kernel_f32<avx512_common>());
block_size = 16;
} else if (mayiuse(avx2)) {
softmax_kernel.reset(new jit_uni_softmax_kernel_f32<avx2>());
block_size = 8;
} else if (mayiuse(sse42)) {
softmax_kernel.reset(new jit_uni_softmax_kernel_f32<sse42>());
block_size = 4;
}
}
void SoftmaxGeneric::execute(const float *src_data, float *dst_data, int B, int C, int H, int W) {
for (int b = 0; b < B; b++) {
int tail_start = 0;
if (softmax_kernel) {
int blocks_num = H*W / block_size;
parallel_for(blocks_num, [&](int ib) {
auto arg = jit_args_softmax();
arg.src = src_data + b * C * H * W + ib * block_size;
arg.dst = dst_data + b * C * H * W + ib * block_size;
arg.stride = static_cast<size_t>(H * W * sizeof(float));
arg.work_amount = static_cast<size_t>(C);
(*softmax_kernel)(&arg);
});
tail_start = (H*W / block_size) * block_size;
}
parallel_for(H * W - tail_start, [&](int i) {
int offset = i + tail_start;
float max = src_data[b * C * H * W + offset];
for (int c = 0; c < C; c++) {
float val = src_data[b * C * H * W + c * H * W + offset];
if (val > max) max = val;
}
float expSum = 0;
for (int c = 0; c < C; c++) {
dst_data[b * C * H * W + c * H * W + offset] = exp(src_data[b * C * H * W + c * H * W + offset] - max);
expSum += dst_data[b * C * H * W + c * H * W + offset];
}
for (int c = 0; c < C; c++) {
dst_data[b * C * H * W + c * H * W + offset] = dst_data[b * C * H * W + c * H * W + offset] / expSum;
}
});
}
}
| [
"alexey.suhov@intel.com"
] | alexey.suhov@intel.com |
fa89124c3b70dd88258b031dac98ca710a2aa13d | e7e0614ba51af810c11ca30d3319836044678bcd | /Coding Questions Company Wise/Facebook/Converting Decimal Number lying between 1 to 3999 to Roman Numerals/main.cpp | a1fa17b6bfdf2a622ad61889a67dd7010943c919 | [] | no_license | kabir-kakkar/Coding-Profile | 7fdc2cc1306ca0a6879d77cf58fde3e0cfb60da2 | ebbcee798f2fd1d6c9e168ba8350eba40e42755f | refs/heads/master | 2022-12-18T16:51:37.907766 | 2020-09-23T07:29:52 | 2020-09-23T07:29:52 | 275,813,548 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 627 | cpp | #include <bits/stdc++.h>
using namespace std;
string convertToRoman (int n) {
string romans[] = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "C", "CD", "D", "CM", "M"};
int nums[] = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
string res = "";
for (int i = 12; i >= 0; i--) {
while (n >= nums[i]) {
res += romans[i];
n -= nums[i];
}
}
return res;
}
int main()
{
freopen("input.txt", "r", stdin);
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
cout << convertToRoman(n) << endl;
}
return 0;
}
| [
"kabir.kakkar4@gmail.com"
] | kabir.kakkar4@gmail.com |
53cb741db0c3b44d221c82afd38531b160a2c669 | d3e028b03d4908139c0dcc6549a82e26cb971097 | /2016adventofcode/1/1.cpp | 1dd224c716d29b43353bb27e87670c5f09d44344 | [] | no_license | gzgreg/ACM | 064c99bc2f8f32ee973849631291bedfcda38247 | 1187c5f9e02ca5a1ec85e68891134f7d57cf6693 | refs/heads/master | 2020-05-21T20:27:46.976555 | 2018-06-30T18:16:36 | 2018-06-30T18:16:36 | 62,960,665 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 769 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pii;
typedef vector<int> vi;
#define endl '\n'
int main(){
ios::sync_with_stdio(0);
complex<int> loc(0, 0);
complex<int> dir(0, 1);
set<pair<int, int>> visited;
string s;
while(cin >> s) {
if(s[0] == 'L') {
dir = dir * complex<int>(0, 1);
} else {
dir = dir * complex<int>(0, -1);
}
int dist = atoi(s.substr(1, s.size() - 2).c_str());
for(int i = 1; i <= dist; i++) {
if(visited.count({loc.real(), loc.imag()})) {
cout << abs(loc.real()) + abs(loc.imag()) << endl;
return 0;
}
visited.insert({loc.real(), loc.imag()});
loc += dir;
}
}
cout << abs(loc.real()) + abs(loc.imag()) << endl;
return 0;
} | [
"gzgregoryzhang@gmail.com"
] | gzgregoryzhang@gmail.com |
545bf1c2803faf9d76284a0e652a0fd69f5aee81 | 65f9576021285bc1f9e52cc21e2d49547ba77376 | /LINUX/android/vendor/qcom/proprietary/gps/utils/eventObserver/EventObserver.cpp | 8da29e8a5ef5e5c4e582ad92ac5bc6d671da5c09 | [] | no_license | AVCHD/qcs605_root_qcom | 183d7a16e2f9fddc9df94df9532cbce661fbf6eb | 44af08aa9a60c6ca724c8d7abf04af54d4136ccb | refs/heads/main | 2023-03-18T21:54:11.234776 | 2021-02-26T11:03:59 | 2021-02-26T11:03:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,762 | cpp | /*====*====*====*====*====*====*====*====*====*====*====*====*====*====*====*
Copyright (c) 2015 Qualcomm Technologies, Inc.
All Rights Reserved.
Confidential and Proprietary - Qualcomm Technologies, Inc.
=============================================================================*/
#include <errno.h>
#include <string.h>
#include "EventObserver.h"
#include <log_util.h>
#include <ulp_service.h>
#include <loc_pla.h>
void *evtRxThread(void * arg1)
{
EventObserver *evtObsPtr = ((EventObserver *)arg1);
evtObsPtr->evtObserverRxThread();
return NULL;
}
EventObserver::EventObserver():
mObserverRole(EVENT_OBSERVER_PRODUCER),
mFifoFd(0),
mFifoFd_rw(0),
mSendEvent(1),
mObserverCb(NULL)
{
int result;
LOC_LOGV("TX Thread constructor called..\n");
strlcpy(mFifoName, EVENT_OBSERVER_FIFO_NAME, strlen(EVENT_OBSERVER_FIFO_NAME)+1);
result = createFifo();
if (result != 0)
{
LOC_LOGE("%s: createFifo Failed - %s, err= %d \n", __func__, mFifoName, errno);
}
}
EventObserver::EventObserver(eventObserver_cb systemEventCallbackFn):
mObserverRole(EVENT_OBSERVER_CONSUMER),
mFifoFd(0),
mFifoFd_rw(0),
mSendEvent(0),
mObserverCb(systemEventCallbackFn)
{
int result;
pthread_t thread_id;
const char *msg = "evtObsRxThrd";
LOC_LOGV("RXThread constructor called.. FIFOLen: %zu\n", strlen(EVENT_OBSERVER_FIFO_NAME));
strlcpy(mFifoName, EVENT_OBSERVER_FIFO_NAME, strlen(EVENT_OBSERVER_FIFO_NAME)+1);
result = createFifo();
if (result != 0)
{
LOC_LOGE("%s: createFifo Failed - %s, err= %d \n", __func__, mFifoName, errno);
}
result = pthread_create( &thread_id, NULL, evtRxThread, (void*) this);
if(0 != result)
{
LOC_LOGE("%s: RX thread creation failed - %s, err= %d \n", __func__, mFifoName, errno);
}
}
EventObserver::~EventObserver()
{
if(0 != mFifoFd)
{
close(mFifoFd);
mFifoFd = 0;
}
if (0 != mFifoFd_rw)
{
close(mFifoFd_rw);
mFifoFd_rw = 0;
}
}
int EventObserver::createFifo()
{
int result = EINVAL, fd = 0, fd_rw = 0;
if( access( mFifoName, F_OK ) == 0 ) {
// file exists
LOC_LOGV("FIFO Exists..\n");
} else {
result = mkfifo(mFifoName, 0660);
if (result != 0)
{
LOC_LOGE("%s: failed to create FIFO %s, err = %d, ignore \n", __func__, mFifoName, errno);
}
}
result = chmod (mFifoName, 0660);
if (result != 0)
{
LOC_LOGE("%s: failed to change mode for %s, error = %d\n", __func__, mFifoName, errno);
}
struct group * gps_group = getgrnam("gps");
if (gps_group != NULL)
{
result = chown (mFifoName, -1, gps_group->gr_gid);
if (result != 0)
{
LOC_LOGE("%s: chown for pipe failed, gid = %d, result = %d, error code = %d\n", __func__, gps_group->gr_gid, result, errno);
}
}
else
{
LOC_LOGE("%s: getgrnam for gps failed, error code = %d\n", __func__, errno);
}
// To avoid deadlock, we open for RDWR first
fd_rw = open(mFifoName, O_RDWR);
LOC_LOGD("%s: open pipe for read name = %s, fd_rw = %d\n", __func__, mFifoName, fd);
if (fd_rw == -1)
{
LOC_LOGE("%s: open pipe for RD/WR failed: name = %s, err = %d\n", __func__, mFifoName, errno);
return -1;
}
else {
mFifoFd_rw = fd_rw;
}
// Open the pipe for non-blocking write/read, so if the pipe is full, the write will return instead of running into deadlock
if (mObserverRole == EVENT_OBSERVER_PRODUCER)
{
//Event Producer
fd = open(mFifoName, O_WRONLY | O_NONBLOCK);
}
else {
//Event Consumer
fd = open(mFifoName, O_RDONLY);
}
LOC_LOGD("%s: open pipe for write name = %s, fd = %d\n", __func__, mFifoName, fd);
if (fd == -1)
{
LOC_LOGE("%s: open pipe for write failed: name = %s, err = %d\n", __func__, mFifoName, errno);
return -1;
}
else
{
mFifoFd = fd;
}
return result;
}
int EventObserver::sendSystemEvent(unsigned int SystemEvent)
{
int writeLen = 0;
if (ULP_LOC_EVENT_OBSERVER_STOP_EVENT_TX == SystemEvent)
{
mSendEvent = 0;
LOC_LOGV("%s: STOP SENDING SYSTEM EVENT \n", __func__);
return true;
}
if ((mFifoFd != 0) && (mSendEvent))
{
EventObserverMsg evtMsg(SystemEvent);
writeLen = write(mFifoFd,&evtMsg, sizeof(EventObserverMsg));
if(writeLen < 0)
{
LOC_LOGE("%s: Send Failed, err = %d\n", __func__, errno);
}
} else {
LOC_LOGE("%s: Send Failed, mFifoFd == 0\n", __func__);
}
return writeLen;
}
int EventObserver::evtObserverRxThread()
{
int result = 0, errorCount = 0;
EventObserverMsg evtMsg(0);
while(mFifoFd)
{
result = read(mFifoFd, &evtMsg, sizeof(EventObserverMsg));
if (result <= 0)
{
LOC_LOGE("evtObserverRxThread read Error -- %d\n",errno);
if(errorCount++ > FIFO_MAX_READ_ERROR)
{
LOC_LOGE("evtObserverRxThread MAX read error -- exit thread\n");
break;
}
else{
continue;
}
}
LOC_LOGV("%s: SYSTEM EVENT = %d\n", __func__, evtMsg.eventId);
if(NULL != mObserverCb)
{
/*Deliver received SystemEvent*/
mObserverCb(evtMsg.eventId);
}
}
return result;
}
| [
"jagadeshkumar.s@pathpartnertech.com"
] | jagadeshkumar.s@pathpartnertech.com |
fc3698368866e4b4c99afb2ce5d39e98d05332fb | 0c670cccaaa02e5ebb3a5d7f0464bfb3316c5393 | /Zadatak01/Point.h | 0b1788799a0a16e6b270bfe24596b8e294fd0ec1 | [] | no_license | IvoRadibratovic/spa-dz03 | 9fe8d686352b90696dd429b9ab68785ce9410d0f | 603ed749eeee0159d96e0696121d31835691fa6c | refs/heads/master | 2020-06-05T18:59:43.505597 | 2019-06-18T17:22:12 | 2019-06-18T17:22:12 | 192,518,580 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 186 | h | #pragma once
class Point
{
private:
int x;
int y;
public:
Point(int x, int y);
void setPointX(int x);
void setPointY(int y);
int getPointX();
int getPointY();
};
| [
"noreply@github.com"
] | noreply@github.com |
a3ca6e8f8a56633b7d328214ab5d16141dc8d69e | 840078abc8111575e2aaced282c3761a6b55f79b | /libs/MotionPlanning/tree_builder.cpp | 18eb7d32ede1ce63bf757a6691ce5d5e2fca5d36 | [] | no_license | ControlTrees/tamp | bb9a64f3f50fb1e4d3c480afd23b4286c6255e5e | ea50b4d813758221a6980503ac85016a188d36db | refs/heads/master | 2023-01-23T06:03:23.494209 | 2020-11-15T11:22:13 | 2020-11-15T11:22:13 | 311,160,013 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,923 | cpp | #include <tree_builder.h>
#include <list>
namespace mp
{
bool operator==(const _Branch& a, const _Branch& b)
{
return (a.p == b.p) && (a.local_to_global == b.local_to_global) && (a.global_to_local == b.global_to_local) && (a.leaf_id == b.leaf_id);
}
bool operator<(const _Branch& a, const _Branch& b)
{
return a.leaf_id < b.leaf_id;
}
bool operator==(const TaskSpec& a, const TaskSpec& b)
{
return (a.vars == b.vars) && (a.scales == b.scales);
}
static TimeInterval normalize(const TimeInterval & interval, const _Branch & branch, uint steps)
{
auto from = interval.from;
auto to = interval.to;
// handle the case of to == -1
if(from > to && to < 0 || (to > branch.local_to_global.size() - 1))
{
to = branch.local_to_global.size() - 1;
}
// handle the case of from == to
if(from == to)
{
from -= (1.0 - 0.0001)/ steps;
}
if(from < 0 && to > 0)
{
from = 0;
}
return {from, to};
}
bool empty_row(const arr & m, uint i)
{
CHECK(i < m.d0, "wrong row dimensions");
for(auto j = 0; j < m.d1; ++j)
{
if(m(i, j) != 0)
{
return false;
}
}
return true;
};
bool empty_col(const arr & m, uint j)
{
CHECK(j < m.d1, "wrong col dimensions");
for(auto i = 0; i < m.d0; ++i)
{
if(m(i, j) != 0)
{
return false;
}
}
return true;
};
TreeBuilder::TreeBuilder(double p, uint d)
: adjacency_matrix_ ( arr(uint(0), uint(0)) )
, p_(p)
, d_(d)
{
}
uint TreeBuilder::n_nodes() const
{
return get_nodes().size();
}
bool TreeBuilder::has_node(uint n) const
{
//if(n == 0 && adjacency_matrix_.d1) return true;
if(n >= adjacency_matrix_.d1) return false;
return !empty_col(adjacency_matrix_, n) || !empty_row(adjacency_matrix_, n);
}
double TreeBuilder::p(uint from, uint to) const
{
double p = 1.0;
auto path = get_path(from, to);
for(auto i = 1; i < path.size(); ++i)
{
p *= adjacency_matrix_(path[i-1], path[i]);
}
return p;
}
uint TreeBuilder::get_root() const
{
std::vector<uint> roots;
for(auto i = 0; i < adjacency_matrix_.d0; ++i)
{
if(!empty_row(adjacency_matrix_, i) && empty_col(adjacency_matrix_, i))
{
roots.push_back(i);
}
}
CHECK_EQ(1, roots.size(), "tree should have exactly one root!");
return roots.front();
}
std::vector<uint> TreeBuilder::get_nodes() const
{
std::vector<uint> nodes;
for(auto i = 0; i < adjacency_matrix_.d0; ++i)
{
if(!empty_row(adjacency_matrix_, i) || !empty_col(adjacency_matrix_, i))
{
nodes.push_back(i);
}
}
return nodes;
}
std::vector<uint> TreeBuilder::get_leaves() const
{
std::vector<uint> leafs;
for(auto i = 0; i < adjacency_matrix_.d0; ++i)
{
if(empty_row(adjacency_matrix_, i) && !empty_col(adjacency_matrix_, i))
{
leafs.push_back(i);
}
}
return leafs;
}
std::vector<uint> TreeBuilder::get_parents(uint node) const
{
std::vector<uint> parents;
auto col = adjacency_matrix_.col(node);
for(uint i = 0; i < col.d0; ++i)
{
if(col(i, 0) != 0)
{
parents.push_back(i);
}
}
return parents;
}
std::vector<uint> TreeBuilder::get_children(uint node) const
{
std::vector<uint> children;
auto row = adjacency_matrix_.row(node);
for(uint i = 0; i < row.d1; ++i)
{
if(row(0, i) != 0)
{
children.push_back(i);
}
}
return children;
}
std::vector<uint> TreeBuilder::get_grand_children(uint node, uint step) const
{
std::vector<uint> parents;
std::vector<uint> children;
parents.push_back(node);
for(auto s = 1; s <= step; ++s)
{
children.clear();
for(auto n: parents)
{
auto _children = get_children(n);
children.insert(children.begin(), _children.begin(), _children.end());
}
if(s == step)
{
return children;
}
else
{
parents = children;
}
}
return std::vector<uint>({node});
}
std::vector<uint> TreeBuilder::get_grand_children_with_backtracking(uint node, uint step) const
{
std::vector<uint> grand_children;
{
auto _step = step;
grand_children = get_grand_children(node, _step);
while(grand_children.empty() && _step > 1)
{
_step--;
grand_children = get_grand_children(node, _step);
}
}
return grand_children;
}
std::vector<uint> TreeBuilder::get_leaves_from(uint node) const
{
std::vector<uint> leaves;
std::list<uint> queue;
queue.push_back(node);
while(!queue.empty())
{
auto p = queue.back();
queue.pop_back();
auto children = get_children(p);
if(children.size() == 0)
{
leaves.push_back(p);
}
else
{
for(const auto& q: children)
{
queue.push_back(q);
}
}
}
return leaves;
}
std::vector<uint> TreeBuilder::get_path(uint from, uint to) const
{
std::vector<uint> path;
uint current = to;
while(current!=from)
{
path.push_back(current);
auto parents = get_parents(current);
CHECK(parents.size() <= 1, "graph not yet supported");
//CHECK(parents.size() > 0, "path doesn't exist");
if(parents.empty())
return std::vector<uint>();
current = parents.front();
}
path.push_back(from);
std::reverse(path.begin(), path.end());
return path;
}
_Branch TreeBuilder::_get_branch(uint leaf) const
{
_Branch branch;
auto current = leaf;
auto parents = get_parents(current);
CHECK(parents.size() > 0, "No parents for this leaf!");
CHECK(parents.size() < 2, "Not implemented yet!, needs graph support!");
branch.p = p(parents[0], leaf);
branch.leaf_id = leaf;
while(parents.size())
{
auto parent = parents[0];
auto p = this->p(parent, current);
branch.local_to_global.push_back(current);
current = parent;
parents = get_parents(current);
}
branch.local_to_global.push_back(get_root());
std::reverse(branch.local_to_global.begin(), branch.local_to_global.end());
branch.global_to_local = std::vector< int >(adjacency_matrix_.d0, -1);
for( auto local = 0; local < branch.local_to_global.size(); ++local )
{
auto global = branch.local_to_global[local];
branch.global_to_local[global] = local;
}
return branch;
}
TreeBuilder TreeBuilder::get_subtree_from(uint node) const
{
TreeBuilder tree(p(0, node), 0);
std::list<uint> queue;
queue.push_back(node);
while(!queue.empty())
{
auto p = queue.back();
queue.pop_back();
auto children = get_children(p);
for(const auto& q: children)
{
tree.add_edge(p, q);
queue.push_back(q);
}
}
return tree;
}
TreeBuilder TreeBuilder::compressed(Mapping & mapping) const
{
mapping.orig_to_compressed = intA(adjacency_matrix_.d0);
for(auto i = 0; i < adjacency_matrix_.d0; ++i)
{
if(!empty_col(adjacency_matrix_, i) || !empty_row(adjacency_matrix_, i))
{
mapping.compressed_to_orig.append(i);
mapping.orig_to_compressed(i) = mapping.compressed_to_orig.d0 - 1;
}
else
{
mapping.orig_to_compressed(i) = -1;
}
}
arr adj = zeros(mapping.compressed_to_orig.d0, mapping.compressed_to_orig.d0);
for(auto i = 0; i < adj.d0; ++i)
{
auto I = mapping.compressed_to_orig(i);
for(auto j = 0; j < adj.d0; ++j)
{
auto J = mapping.compressed_to_orig(j);
adj(i, j) = adjacency_matrix_(I, J);
}
}
TreeBuilder compressed(p_, d_);
compressed.adjacency_matrix_ = adj;
return compressed;
}
std::vector<_Branch> TreeBuilder::get_branches() const
{
std::vector<_Branch> branches;
for(auto l : get_leaves())
{
branches.push_back(_get_branch(l));
}
return branches;
}
TreeBuilder TreeBuilder::get_branch(uint leaf) const
{
TreeBuilder branch(p(0, leaf), 0);
auto current = leaf;
auto parents = get_parents(current);
CHECK(parents.size() > 0, "No parents for this leaf!");
CHECK(parents.size() < 2, "Not implemented yet!, needs graph support!");
while(parents.size())
{
auto parent = parents[0];
//auto p = this->p(parent, current);
branch.add_edge(parent, current, 1.0); // could be p here eventually, but here we assume here that we are on the common part "knowing that we will branch"
current = parent;
parents = get_parents(current);
}
return branch;
}
intA TreeBuilder::get_vars0(const TimeInterval& interval, const _Branch& branch, uint steps) const
{
auto from = interval.from;
auto to = interval.to;
const auto duration = to - from; //ceil(to - from);
uint d0 = duration > 0 ? ceil(duration * steps) : 0;
int from_step = from * steps;
intA vars(d0);
for(auto t=0; t < d0; ++t)
{
CHECK(t < vars.d0, "bug");
int k = from_step + t;
if(k < 0) // prefix handling (we don't branch during the prefix)
{
int from_node = branch.local_to_global[0];
int to_node = branch.local_to_global[1];
vars(t) = from_node * steps + k;
}
else
{
auto i = floor(k / double(steps));
auto j = ceil(k / double(steps) + 0.00001);
CHECK(i >= 0 && i < branch.local_to_global.size(), "bug");
CHECK(j >= 0 && j < branch.local_to_global.size(), "bug");
int from_node = branch.local_to_global[i];
int to_node = branch.local_to_global[j];
int r = k % steps;
vars(t) = (steps > 1 ? to_node - 1 : from_node) * steps + r; // in new branched phase
}
}
return vars;
}
intA TreeBuilder::get_vars(const TimeInterval& interval, uint leaf, uint order, uint steps) const
{
auto branch = _get_branch(leaf);
auto it = normalize(interval, branch, steps);
auto from = it.from;
auto to = it.to;
// if frm and to are negative, return early
if(from < 0 && to <= 0)
{
return intA();
}
std::vector<intA> splitted_vars(order+1);// = get_vars0(from, to, leaf, steps);
for(auto j = 0; j < order+1; ++j)
{
auto delta = double(j) / steps;
splitted_vars[j] = get_vars0({from - delta, to - delta}, branch, steps);
}
auto d0 = splitted_vars.front().d0;
intA vars(d0, order + 1);
for(auto i = 0; i < d0; ++i)
{
for(auto j = 0; j < order+1; ++j)
{
vars(i, order - j) = splitted_vars[j](i);
}
}
return vars;
}
arr TreeBuilder::get_scales(const TimeInterval& interval, uint leaf, uint steps) const
{
auto branch = _get_branch(leaf);
auto it = normalize(interval, branch, steps);
const auto& from = it.from;
const auto& to = it.to;
// if frm and to are negative, return early
if(from < 0 && to <= 0)
{
return arr();
}
const auto duration = to - from;
uint d0 = duration > 0 ? ceil(duration * steps) : 0;
uint from_step = from * steps;
arr full_scale = arr((branch.local_to_global.size() - 1) * steps);
double p = 1.0;
for(auto i = 0; i < branch.local_to_global.size() - 1; ++i)
{
auto global_i = branch.local_to_global[i];
auto global_j = branch.local_to_global[i+1];
p *= adjacency_matrix_(global_i, global_j);
for(auto s = 0; s < steps; ++s)
{
full_scale(steps * i + s) = p;
}
}
arr scale(d0);
for(auto i = 0; i < d0; ++i)
{
scale(i) = full_scale(i + from_step);
}
return scale;
}
TaskSpec TreeBuilder::get_spec(uint order, uint steps) const
{
// get leaves fron start_edge
std::vector<uint> leaves = get_leaves();
std::sort(leaves.begin(), leaves.end()); // unnecessary but easier to debug
return get_spec({0, -1.0}, leaves, order, steps);
}
TaskSpec TreeBuilder::get_spec(const TimeInterval& interval, const Edge& start_edge, uint order, uint steps) const
{
// get leaves fron start_edge
std::vector<uint> leaves = get_leaves_from(start_edge.to);
std::sort(leaves.begin(), leaves.end()); // unnecessary but easier to debug
return get_spec(interval, leaves, order, steps);
}
TaskSpec TreeBuilder::get_spec(const TimeInterval& interval, const std::vector<uint> & leaves, uint order, uint steps) const
{
// get vars for each leaf
std::vector<std::vector<intA>> slitted_varss(leaves.size());
std::vector<arr> scaless(leaves.size());
for(auto i = 0; i < leaves.size(); ++i)
{
auto vars = get_vars(interval, leaves[i], order, steps);
auto scales = get_scales(interval, leaves[i], steps);
std::vector<intA> splitted_vars = std::vector<intA>(vars.size() / (order+1));
for(auto s = 0; s < vars.size() / (order+1); ++s)
{
auto steps = intA(order+1, 1);
for(auto j = 0; j < order + 1; ++j)
{
steps(j, 0) = vars(s, j);
}
splitted_vars[s] = steps;
}
slitted_varss[i] = splitted_vars;
scaless[i] = scales;
}
// remove doubles
std::vector<intA> splitted_no_doubles_vars;
arr no_doubles_scales;
for(auto i = 0; i < slitted_varss.size(); ++i)
{
for(auto s = 0; s < slitted_varss[i].size(); ++s)
{
const auto & steps = slitted_varss[i][s];
double scale = scaless[i](s);
if(std::find(splitted_no_doubles_vars.begin(), splitted_no_doubles_vars.end(), steps) == splitted_no_doubles_vars.end())
{
splitted_no_doubles_vars.push_back(steps);
no_doubles_scales.append(scale);
}
}
}
// flatten
intA vars(splitted_no_doubles_vars.size(), (order + 1));
for(auto s = 0; s < splitted_no_doubles_vars.size(); ++s)
{
for(auto j = 0; j < order + 1; ++j)
{
vars(s, j) = splitted_no_doubles_vars[s](j, 0);
}
}
CHECK(vars.d0 == no_doubles_scales.d0, "size corruption");
return TaskSpec{std::move(vars), std::move(no_doubles_scales)};
}
int TreeBuilder::get_step(double time, const Edge& edge, uint steps) const
{
//int step = time * microSteps - 1;
//return order0(step, 0);
auto spec = get_spec({time, time}, edge, 0, steps);
if(spec.vars.d0 == 0) // out of the time interval
return -1;
CHECK(spec.vars.d0 == 1, "wrong spec!");
return spec.vars.front();
}
void TreeBuilder::add_edge(uint from, uint to, double p)
{
uint max = std::max(from, to);
auto size = max+1;
if(adjacency_matrix_.d0 < size)
{
auto old_adjacency_matrix = adjacency_matrix_;
const auto& old_size = old_adjacency_matrix.d0;
auto adjacency_matrix = arr(size, size);
adjacency_matrix.setMatrixBlock(old_adjacency_matrix, 0, 0);
adjacency_matrix_ = adjacency_matrix;
}
adjacency_matrix_(from, to) = p;
}
std::ostream& operator<<(std::ostream& os, const TreeBuilder & tree)
{
std::list<uint> queue;
queue.push_back(0);
while(!queue.empty())
{
auto p = queue.back();
queue.pop_back();
auto children = tree.get_children(p);
for(const auto& q: children)
{
std::cout << p << "->" << q << std::endl;
queue.push_back(q);
}
if(children.empty() && p < tree.adjacency_matrix().d0 - 1)
queue.push_back(p+1);
}
return os;
}
bool operator==(const Edge& a, const Edge& b)
{
return a.from == b.from && a.to == b.to;
}
bool operator==(const TreeBuilder& a, const TreeBuilder& b)
{
return a.adjacency_matrix() == b.adjacency_matrix() && a.p() == b.p() && a.d() == b.d();
}
}
| [
"camille.phiquepal@gmail.com"
] | camille.phiquepal@gmail.com |
c6c9b73858218658a68fc3c8fd1dfbbdac350fd2 | 4adf8d064c33e7498b0e5baaf6767c30261cb71b | /totalProblem(CN)/98.验证二叉搜索树.cpp | fa6ea52b550ceec79470eb9df884b5dd35597150 | [] | no_license | codingClaire/leetcode | 0f679b526c14083ccf6d35937e5d845c9fa27f71 | 45fd500d2e2f52df0adc9d47ccc9fd29993dbef1 | refs/heads/main | 2023-05-25T12:34:27.952866 | 2023-05-20T15:09:02 | 2023-05-20T15:09:02 | 148,796,605 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,129 | cpp | /*
* @lc app=leetcode.cn id=98 lang=cpp
*
* [98] 验证二叉搜索树
*/
// @lc code=start
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
// 81.82 % 74.16 %
//[98] 验证二叉搜索树
class Solution
{
public:
bool helper(TreeNode *root, long left_value, long right_value)
{
if (root == NULL)
return true;
if (root->val <= left_value || root->val >= right_value)
{
return false;
}
bool left = helper(root->left, left_value, root->val);
bool right = helper(root->right, root->val, right_value);
return left && right;
}
bool isValidBST(TreeNode *root)
{
return helper(root, LONG_MIN, LONG_MAX);
}
};
// @lc code=end
//[5,4,6,null,null,3,7] 这个结果是false
// 需要考虑左右的界
//错误地解法
class Solution
{
public:
bool isValidBST(TreeNode *root)
{
if (root == NULL)
return true;
bool leftcur = false, rightcur = false;
if (root->left == NULL || root->left->val < root->val)
leftcur = true;
if (root->right == NULL || root->right->val > root->val)
rightcur = true;
bool left = isValidBST(root->left);
bool right = isValidBST(root->right);
return leftcur && rightcur && left && right;
}
};
class Solution
{
public:
bool helper(TreeNode *root, long left_value, long right_value)
{
if (root == nullptr)
return true;
if (root->val <= left_value)
return false;
if (root->val >= right_value)
return false;
return helper(root->left, left_value, root->val) & helper(root->right, root->val, right_value);
}
bool isValidBST(TreeNode *root)
{
return helper(root, LONG_MIN, LONG_MAX);
}
}; | [
"suyueyinyin@126.com"
] | suyueyinyin@126.com |
69b7a9b486c678123215bf9c4694979d665cfea2 | 239ae3528027868f1698bcffe4dd1941a963a18c | /desy_setup/CMSSW_5_3_9_patch3/src/AnalysisDataFormats/TauAnalysis/src/NSVfitEventHypothesis.cc | 48da2d18d4102e7001b291a0ecdb1797d58637d9 | [] | no_license | saxenapooja/HTauTau | 2ff61e337fd0b0ee2319982d64174b7495d7fd9f | 46343cba7a6a4aeeacfd91e44f7ffc1a358a0295 | refs/heads/master | 2016-09-06T08:27:31.588092 | 2014-08-22T10:26:31 | 2014-08-22T10:26:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 904 | cc | #include "AnalysisDataFormats/TauAnalysis/interface/NSVfitEventHypothesis.h"
NSVfitEventHypothesis::NSVfitEventHypothesis(const NSVfitEventHypothesis& bluePrint)
: NSVfitEventHypothesisBase(bluePrint),
p4_(bluePrint.p4_),
dp4_(bluePrint.dp4_),
p4MEt_(bluePrint.p4MEt_)
{
size_t numResonances = resonances_.size();
for ( size_t iResonance = 0; iResonance < numResonances; ++iResonance ) {
this->resonance(iResonance)->setEventHypothesis(this);
}
}
NSVfitEventHypothesis& NSVfitEventHypothesis::operator=(const NSVfitEventHypothesis& bluePrint)
{
NSVfitEventHypothesisBase::operator=(bluePrint);
p4_ = bluePrint.p4_;
dp4_ = bluePrint.dp4_;
p4MEt_ = bluePrint.p4MEt_;
size_t numResonances = resonances_.size();
for ( size_t iResonance = 0; iResonance < numResonances; ++iResonance ) {
this->resonance(iResonance)->setEventHypothesis(this);
}
return (*this);
}
| [
"pooja.saxena@cern.ch"
] | pooja.saxena@cern.ch |
215d9d134fa372779b14e3dd721b95f6c34fef59 | d820289bdf60f775e61f84a993d800596e3480de | /Classes/Scene/Init/InitLayer.cpp | 664f25263cf6ad8465158d47421b07ba09cceb6c | [] | no_license | Crasader/SampleR01 | 658072f82c0afed10f1f82e4364bda1a86c4ce0c | c1fe381c8d64faf1a4e0ab846b2782233300c102 | refs/heads/master | 2020-11-29T10:47:09.616439 | 2015-07-26T07:27:51 | 2015-07-26T07:27:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,124 | cpp | #include "InitLayer.h"
#include "Scene/SceneManager.h"
//#include "Data/DataManager.h"
#include "Common/CommonDialog.h"
USING_NS_CC;
InitLayer::InitLayer()
{
}
InitLayer::~InitLayer()
{
}
bool InitLayer::init()
{
if (!TLayer::init())
{
return false;
}
auto listener = EventListenerTouchOneByOne::create();
listener->onTouchBegan = [](Touch *touch, Event*event)->bool{ return true; };
listener->onTouchEnded = CC_CALLBACK_2(InitLayer::onTouchEnded, this);
this->getEventDispatcher()->addEventListenerWithSceneGraphPriority(listener, this);
// rapidjson Test
//readJsonTest();
return true;
}
void InitLayer::onTouchEnded(Touch *pTouch, Event *pEvent)
{
SceneManager::changeScene(SceneManager::SCENE_TITLE, true);
}
// json sample
void InitLayer::readJsonTest()
{
char* buffer = NULL;
rapidjson::Document reader;
if (t_utility::readJson("data/data_monster.json", buffer, reader)) {
rapidjson::Value& monsters = reader["monsters"];
int i, l = monsters.Size();
for (i = 0; i < l; i++) {
log("%s", monsters[rapidjson::SizeType(i)]["Name"].GetString());
}
CC_SAFE_DELETE_ARRAY(buffer);
}
}
| [
"rokube@hotmail.co.jp"
] | rokube@hotmail.co.jp |
1ac6c5722cd202f391e7b17c0e6d79a577f311e3 | bd37d9bdb1e9663dbac150a3ec252637dd920167 | /Assignment_04/Assign_04_01 - File Encrypt/Assign_04_01 - File Encrypt/stdafx.cpp | e4ae450a859201eae8734d692ce365ebba886598 | [] | no_license | taquayle/ITAD133 | f8cc2481676ff23ca47e30e6d856442dfd55af35 | df58a81669707d30e7efc24230a8f3172ee12b3e | refs/heads/master | 2021-01-16T23:20:53.721412 | 2017-02-23T08:54:15 | 2017-02-23T08:54:15 | 82,905,956 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 306 | cpp | // stdafx.cpp : source file that includes just the standard includes
// Assign_04_01 - File Encrypt.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"taquayle@uw.edu"
] | taquayle@uw.edu |
d40746bb165e1e3828b969ed5986cc3cf749c900 | 3c37e6800742b0a4820c1048ddc0e93ad4e0260a | /Uebung_Lotto/Uebung_Lotto/main.cpp | ad67bd09e0ee46e0dbbd74f9aaeacd0b493e39fc | [] | no_license | MarcelSchm/TutoriumPr1 | 111b3b5f6a0756f456d4b2b07aaccd43063b29f0 | 5892f4fff1542ad2b9a3b3e75bf0a1d37beeb946 | refs/heads/master | 2021-01-18T21:54:58.695469 | 2016-05-31T15:46:25 | 2016-05-31T15:46:25 | 55,598,141 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 1,924 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <iostream>
#include <stdbool.h> // damit bool nutzbar ist
#pragma warning (disable:4996) // beschissene scanf warnung aus
#define ue 129
bool check(int a[], int x) {
for (int i = 0; i < 6; i++) {
if (x == a[i]) {
return true;
}
}
return false;
}
void initArray(int a[]) {
srand(time(NULL)); // zufallszahlen brauchen eine berechnungsgrundlage. hier wird die zeit zum Zeitpunkt null als quelle(seed) genommen
int zufall = 0;
for (int i = 0; i < 6; i++) {
zufall= rand() % 49 + 1;//Zufallszahl zwischen 0 und 48+1
while (check(a,zufall)){//solange ein array element gleich der zufallszahl ist(=true) , neue zahl
zufall= rand() % 49 + 1; //Zufallszahl zwischen 0 und 48+1
}
a[i] = zufall;
}
}
void show(int a[]) {
for (int i = 0; i < 6; i++) {
printf("a[%d]= %d\n", i, a[i]);
}
}
int treffer(int a[], int tippschein[]) {
int richtige = 0;
for (int i = 0; i < 6; i++) {
for (int j = 0; j < 6; j++) {
if (tippschein[i] == a[j]) {
richtige++;
}
}
}
return richtige;
}
int main() {
int ziehung[6] = { 0 };
int tippschein[6] = { 0 };
printf("Geben sie Ihre Tipps ein:\n");
//in dieser schleife könnte man noch implementieren, dass keine doppelten Tipps eingetragen werden
// bis jetzt wird auf die gutmütigkkeit des Benutzers vertraut
for (int i = 0; i < 6; i++) {
printf("\nTipp Nr.%d:\t", i);
scanf("%d", &tippschein[i]);
fflush(stdin); //puffer leeren damit nicht zufällig zwei werte doppelt gelesen werden
}
printf("\n\nDie Eingabe ist vollendet. Die Lottozahlen sind: \n");
initArray(ziehung); //Hier werden die zufälligen Lottozahlen bestimmt
show(ziehung); // Ausgabe in der Konsole der Lottozahlen
printf("\nHerzlichen Gl%cckwunsch! Sie haben %d Richtige!\n",ue, treffer(ziehung, tippschein)); //Gewinnausschüttung
system("pause");
return 0;
}
| [
"marcel.schmid@haw-hamburg.de"
] | marcel.schmid@haw-hamburg.de |
c742466f913b6995a6a1a79104aef9cebff2fe89 | c708d04689d7baad2a9077ee76cfb1ed1e955f25 | /common/graphics/persistent_cache.cc | efbf676cc2cedb551a30a282e567729655be0e95 | [
"BSD-3-Clause"
] | permissive | Piinks/engine | 0cdc62979169a5425e398adeffea96d46591da1d | 04b04518565ef18b3197a63a1a3407f84527b9a3 | refs/heads/master | 2023-08-22T14:26:29.627064 | 2021-03-15T21:28:01 | 2021-03-15T21:28:01 | 348,140,618 | 1 | 0 | BSD-3-Clause | 2021-03-15T22:29:08 | 2021-03-15T22:29:08 | null | UTF-8 | C++ | false | false | 13,737 | cc | // Copyright 2013 The Flutter 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 "flutter/common/graphics/persistent_cache.h"
#include <future>
#include <memory>
#include <string>
#include <string_view>
#include "flutter/fml/base32.h"
#include "flutter/fml/file.h"
#include "flutter/fml/logging.h"
#include "flutter/fml/make_copyable.h"
#include "flutter/fml/mapping.h"
#include "flutter/fml/paths.h"
#include "flutter/fml/trace_event.h"
#include "flutter/shell/version/version.h"
#include "rapidjson/document.h"
#include "third_party/skia/include/utils/SkBase64.h"
namespace flutter {
std::string PersistentCache::cache_base_path_;
std::shared_ptr<AssetManager> PersistentCache::asset_manager_;
std::mutex PersistentCache::instance_mutex_;
std::unique_ptr<PersistentCache> PersistentCache::gPersistentCache;
std::string PersistentCache::SkKeyToFilePath(const SkData& data) {
if (data.data() == nullptr || data.size() == 0) {
return "";
}
std::string_view view(reinterpret_cast<const char*>(data.data()),
data.size());
auto encode_result = fml::Base32Encode(view);
if (!encode_result.first) {
return "";
}
return encode_result.second;
}
bool PersistentCache::gIsReadOnly = false;
std::atomic<bool> PersistentCache::cache_sksl_ = false;
std::atomic<bool> PersistentCache::strategy_set_ = false;
void PersistentCache::SetCacheSkSL(bool value) {
if (strategy_set_ && value != cache_sksl_) {
FML_LOG(ERROR) << "Cache SkSL can only be set before the "
"GrContextOptions::fShaderCacheStrategy is set.";
return;
}
cache_sksl_ = value;
}
PersistentCache* PersistentCache::GetCacheForProcess() {
std::scoped_lock lock(instance_mutex_);
if (gPersistentCache == nullptr) {
gPersistentCache.reset(new PersistentCache(gIsReadOnly));
}
return gPersistentCache.get();
}
void PersistentCache::ResetCacheForProcess() {
std::scoped_lock lock(instance_mutex_);
gPersistentCache.reset(new PersistentCache(gIsReadOnly));
strategy_set_ = false;
}
void PersistentCache::SetCacheDirectoryPath(std::string path) {
cache_base_path_ = path;
}
bool PersistentCache::Purge() {
// Make sure that this is called after the worker task runner setup so all the
// file system modifications would happen on that single thread to avoid
// racing.
FML_CHECK(GetWorkerTaskRunner());
std::promise<bool> removed;
GetWorkerTaskRunner()->PostTask([&removed,
cache_directory = cache_directory_]() {
if (cache_directory->is_valid()) {
// Only remove files but not directories.
FML_LOG(INFO) << "Purge persistent cache.";
fml::FileVisitor delete_file = [](const fml::UniqueFD& directory,
const std::string& filename) {
// Do not delete directories. Return true to continue with other files.
if (fml::IsDirectory(directory, filename.c_str())) {
return true;
}
return fml::UnlinkFile(directory, filename.c_str());
};
removed.set_value(VisitFilesRecursively(*cache_directory, delete_file));
} else {
removed.set_value(false);
}
});
return removed.get_future().get();
}
namespace {
constexpr char kEngineComponent[] = "flutter_engine";
static void FreeOldCacheDirectory(const fml::UniqueFD& cache_base_dir) {
fml::UniqueFD engine_dir =
fml::OpenDirectoryReadOnly(cache_base_dir, kEngineComponent);
if (!engine_dir.is_valid()) {
return;
}
fml::VisitFiles(engine_dir, [](const fml::UniqueFD& directory,
const std::string& filename) {
if (filename != GetFlutterEngineVersion()) {
auto dir = fml::OpenDirectory(directory, filename.c_str(), false,
fml::FilePermission::kReadWrite);
if (dir.is_valid()) {
fml::RemoveDirectoryRecursively(directory, filename.c_str());
}
}
return true;
});
}
static std::shared_ptr<fml::UniqueFD> MakeCacheDirectory(
const std::string& global_cache_base_path,
bool read_only,
bool cache_sksl) {
fml::UniqueFD cache_base_dir;
if (global_cache_base_path.length()) {
cache_base_dir = fml::OpenDirectory(global_cache_base_path.c_str(), false,
fml::FilePermission::kRead);
} else {
cache_base_dir = fml::paths::GetCachesDirectory();
}
if (cache_base_dir.is_valid()) {
FreeOldCacheDirectory(cache_base_dir);
std::vector<std::string> components = {
kEngineComponent, GetFlutterEngineVersion(), "skia", GetSkiaVersion()};
if (cache_sksl) {
components.push_back(PersistentCache::kSkSLSubdirName);
}
return std::make_shared<fml::UniqueFD>(
CreateDirectory(cache_base_dir, components,
read_only ? fml::FilePermission::kRead
: fml::FilePermission::kReadWrite));
} else {
return std::make_shared<fml::UniqueFD>();
}
}
} // namespace
sk_sp<SkData> ParseBase32(const std::string& input) {
std::pair<bool, std::string> decode_result = fml::Base32Decode(input);
if (!decode_result.first) {
FML_LOG(ERROR) << "Base32 can't decode: " << input;
return nullptr;
}
const std::string& data_string = decode_result.second;
return SkData::MakeWithCopy(data_string.data(), data_string.length());
}
sk_sp<SkData> ParseBase64(const std::string& input) {
SkBase64::Error error;
size_t output_len;
error = SkBase64::Decode(input.c_str(), input.length(), nullptr, &output_len);
if (error != SkBase64::Error::kNoError) {
FML_LOG(ERROR) << "Base64 decode error: " << error;
FML_LOG(ERROR) << "Base64 can't decode: " << input;
return nullptr;
}
sk_sp<SkData> data = SkData::MakeUninitialized(output_len);
void* output = data->writable_data();
error = SkBase64::Decode(input.c_str(), input.length(), output, &output_len);
if (error != SkBase64::Error::kNoError) {
FML_LOG(ERROR) << "Base64 decode error: " << error;
FML_LOG(ERROR) << "Base64 can't decode: " << input;
return nullptr;
}
return data;
}
std::vector<PersistentCache::SkSLCache> PersistentCache::LoadSkSLs() {
TRACE_EVENT0("flutter", "PersistentCache::LoadSkSLs");
std::vector<PersistentCache::SkSLCache> result;
fml::FileVisitor visitor = [&result](const fml::UniqueFD& directory,
const std::string& filename) {
sk_sp<SkData> key = ParseBase32(filename);
sk_sp<SkData> data = LoadFile(directory, filename);
if (key != nullptr && data != nullptr) {
result.push_back({key, data});
} else {
FML_LOG(ERROR) << "Failed to load: " << filename;
}
return true;
};
// Only visit sksl_cache_directory_ if this persistent cache is valid.
// However, we'd like to continue visit the asset dir even if this persistent
// cache is invalid.
if (IsValid()) {
// In case `rewinddir` doesn't work reliably, load SkSLs from a freshly
// opened directory (https://github.com/flutter/flutter/issues/65258).
fml::UniqueFD fresh_dir =
fml::OpenDirectoryReadOnly(*cache_directory_, kSkSLSubdirName);
if (fresh_dir.is_valid()) {
fml::VisitFiles(fresh_dir, visitor);
}
}
std::unique_ptr<fml::Mapping> mapping = nullptr;
if (asset_manager_ != nullptr) {
mapping = asset_manager_->GetAsMapping(kAssetFileName);
}
if (mapping == nullptr) {
FML_LOG(INFO) << "No sksl asset found.";
} else {
FML_LOG(INFO) << "Found sksl asset. Loading SkSLs from it...";
rapidjson::Document json_doc;
rapidjson::ParseResult parse_result =
json_doc.Parse(reinterpret_cast<const char*>(mapping->GetMapping()),
mapping->GetSize());
if (parse_result != rapidjson::ParseErrorCode::kParseErrorNone) {
FML_LOG(ERROR) << "Failed to parse json file: " << kAssetFileName;
} else {
for (auto& item : json_doc["data"].GetObject()) {
sk_sp<SkData> key = ParseBase32(item.name.GetString());
sk_sp<SkData> sksl = ParseBase64(item.value.GetString());
if (key != nullptr && sksl != nullptr) {
result.push_back({key, sksl});
} else {
FML_LOG(ERROR) << "Failed to load: " << item.name.GetString();
}
}
}
}
return result;
}
PersistentCache::PersistentCache(bool read_only)
: is_read_only_(read_only),
cache_directory_(MakeCacheDirectory(cache_base_path_, read_only, false)),
sksl_cache_directory_(
MakeCacheDirectory(cache_base_path_, read_only, true)) {
if (!IsValid()) {
FML_LOG(WARNING) << "Could not acquire the persistent cache directory. "
"Caching of GPU resources on disk is disabled.";
}
}
PersistentCache::~PersistentCache() = default;
bool PersistentCache::IsValid() const {
return cache_directory_ && cache_directory_->is_valid();
}
sk_sp<SkData> PersistentCache::LoadFile(const fml::UniqueFD& dir,
const std::string& file_name) {
auto file = fml::OpenFileReadOnly(dir, file_name.c_str());
if (!file.is_valid()) {
return nullptr;
}
auto mapping = std::make_unique<fml::FileMapping>(file);
if (mapping->GetSize() == 0) {
return nullptr;
}
return SkData::MakeWithCopy(mapping->GetMapping(), mapping->GetSize());
}
// |GrContextOptions::PersistentCache|
sk_sp<SkData> PersistentCache::load(const SkData& key) {
TRACE_EVENT0("flutter", "PersistentCacheLoad");
if (!IsValid()) {
return nullptr;
}
auto file_name = SkKeyToFilePath(key);
if (file_name.size() == 0) {
return nullptr;
}
auto result = PersistentCache::LoadFile(*cache_directory_, file_name);
if (result != nullptr) {
TRACE_EVENT0("flutter", "PersistentCacheLoadHit");
}
return result;
}
static void PersistentCacheStore(fml::RefPtr<fml::TaskRunner> worker,
std::shared_ptr<fml::UniqueFD> cache_directory,
std::string key,
std::unique_ptr<fml::Mapping> value) {
auto task = fml::MakeCopyable([cache_directory, //
file_name = std::move(key), //
mapping = std::move(value) //
]() mutable {
TRACE_EVENT0("flutter", "PersistentCacheStore");
if (!fml::WriteAtomically(*cache_directory, //
file_name.c_str(), //
*mapping) //
) {
FML_LOG(WARNING) << "Could not write cache contents to persistent store.";
}
});
if (!worker) {
FML_LOG(WARNING)
<< "The persistent cache has no available workers. Performing the task "
"on the current thread. This slow operation is going to occur on a "
"frame workload.";
task();
} else {
worker->PostTask(std::move(task));
}
}
// |GrContextOptions::PersistentCache|
void PersistentCache::store(const SkData& key, const SkData& data) {
stored_new_shaders_ = true;
if (is_read_only_) {
return;
}
if (!IsValid()) {
return;
}
auto file_name = SkKeyToFilePath(key);
if (file_name.size() == 0) {
return;
}
auto mapping = std::make_unique<fml::DataMapping>(
std::vector<uint8_t>{data.bytes(), data.bytes() + data.size()});
if (mapping == nullptr || mapping->GetSize() == 0) {
return;
}
PersistentCacheStore(GetWorkerTaskRunner(),
cache_sksl_ ? sksl_cache_directory_ : cache_directory_,
std::move(file_name), std::move(mapping));
}
void PersistentCache::DumpSkp(const SkData& data) {
if (is_read_only_ || !IsValid()) {
FML_LOG(ERROR) << "Could not dump SKP from read-only or invalid persistent "
"cache.";
return;
}
std::stringstream name_stream;
auto ticks = fml::TimePoint::Now().ToEpochDelta().ToNanoseconds();
name_stream << "shader_dump_" << std::to_string(ticks) << ".skp";
std::string file_name = name_stream.str();
FML_LOG(INFO) << "Dumping " << file_name;
auto mapping = std::make_unique<fml::DataMapping>(
std::vector<uint8_t>{data.bytes(), data.bytes() + data.size()});
PersistentCacheStore(GetWorkerTaskRunner(), cache_directory_,
std::move(file_name), std::move(mapping));
}
void PersistentCache::AddWorkerTaskRunner(
fml::RefPtr<fml::TaskRunner> task_runner) {
std::scoped_lock lock(worker_task_runners_mutex_);
worker_task_runners_.insert(task_runner);
}
void PersistentCache::RemoveWorkerTaskRunner(
fml::RefPtr<fml::TaskRunner> task_runner) {
std::scoped_lock lock(worker_task_runners_mutex_);
auto found = worker_task_runners_.find(task_runner);
if (found != worker_task_runners_.end()) {
worker_task_runners_.erase(found);
}
}
fml::RefPtr<fml::TaskRunner> PersistentCache::GetWorkerTaskRunner() const {
fml::RefPtr<fml::TaskRunner> worker;
std::scoped_lock lock(worker_task_runners_mutex_);
if (!worker_task_runners_.empty()) {
worker = *worker_task_runners_.begin();
}
return worker;
}
void PersistentCache::SetAssetManager(std::shared_ptr<AssetManager> value) {
TRACE_EVENT_INSTANT0("flutter", "PersistentCache::SetAssetManager");
asset_manager_ = value;
}
std::vector<std::unique_ptr<fml::Mapping>>
PersistentCache::GetSkpsFromAssetManager() const {
if (!asset_manager_) {
FML_LOG(ERROR)
<< "PersistentCache::GetSkpsFromAssetManager: Asset manager not set!";
return std::vector<std::unique_ptr<fml::Mapping>>();
}
return asset_manager_->GetAsMappings(".*\\.skp$");
}
} // namespace flutter
| [
"noreply@github.com"
] | noreply@github.com |
d18a0c89d5586fe768b4b27faecbaf9de83a7def | 0d57efbffd8a65b5cf31020e893a6d64f1f52e64 | /Brew.js/Include/bjs/platform/libctru/ctr/Model.hpp | 3b4b0b8c95053e271a9e719c4a1bb5e0a7a0e949 | [
"MIT"
] | permissive | stubobis1/Brew.js | 7b4c650828866e3e1af76893623ec86fe17479d1 | 998f82cbfe5ed245825b0ad8252f09691788dc6c | refs/heads/master | 2020-12-02T12:02:41.466241 | 2019-04-17T07:26:57 | 2019-04-17T07:26:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 698 | hpp |
/**
@file System.hpp
@brief Brew.js API - libctru - 'ctr' module
@author XorTroll
@copyright Brew.js project
*/
#pragma once
#include <bjs/js.hpp>
namespace bjs::libctru::ctr
{
/**
@brief API JS Function: "ctr.isNew3DS() → Boolean"
@note Returns whether the current console is a new 3DS. This description is for using the function with JavaScript.
*/
js::Function isNew3DS(js::NativeContext Context);
/**
@brief API JS Function: "ctr.is2DS() → Boolean"
@note Returns whether the current console is a 2DS. This description is for using the function with JavaScript.
*/
js::Function is2DS(js::NativeContext Context);
} | [
"33005497+XorTroll@users.noreply.github.com"
] | 33005497+XorTroll@users.noreply.github.com |
fc738c8f8c1194b3978c7bdc1f98e13a1514666c | ba96d7f21540bd7504e61954f01a6d77f88dea6f | /build/Android/Preview/app/src/main/include/_root.fa_link.h | 7477353afbaae30fcc680cde1b45953fdf486d59 | [] | no_license | GetSomefi/haslaamispaivakirja | 096ff35fe55e3155293e0030c91b4bbeafd512c7 | 9ba6766987da4af3b662e33835231b5b88a452b3 | refs/heads/master | 2020-03-21T19:54:24.148074 | 2018-11-09T06:44:18 | 2018-11-09T06:44:18 | 138,976,977 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,359 | h | // This file was generated based on '/Users/petervirtanen/OneDrive/Fuse projektit/Häsläämispäiväkirja/build/Android/Preview/cache/ux15/fa_link.g.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Animations.IResize.h>
#include <Fuse.Binding.h>
#include <Fuse.Controls.Text.h>
#include <Fuse.IActualPlacement.h>
#include <Fuse.INotifyUnrooted.h>
#include <Fuse.IProperties.h>
#include <Fuse.ISourceLocation.h>
#include <Fuse.ITemplateSource.h>
#include <Fuse.Node.h>
#include <Fuse.Scripting.IScriptObject.h>
#include <Fuse.Triggers.Actions.IHide.h>
#include <Fuse.Triggers.Actions.IShow.h>
#include <Fuse.Triggers.Actions-ea70af1f.h>
#include <Fuse.Triggers.IValue-1.h>
#include <Fuse.Visual.h>
#include <Uno.Collections.ICollection-1.h>
#include <Uno.Collections.IEnumerable-1.h>
#include <Uno.Collections.IList-1.h>
#include <Uno.String.h>
#include <Uno.UX.IPropertyListener.h>
namespace g{struct fa_link;}
namespace g{
// public partial sealed class fa_link :2
// {
::g::Fuse::Controls::TextControl_type* fa_link_typeof();
void fa_link__ctor_8_fn(fa_link* __this);
void fa_link__InitializeUX1_fn(fa_link* __this);
void fa_link__New4_fn(fa_link** __retval);
struct fa_link : ::g::Fuse::Controls::Text
{
void ctor_8();
void InitializeUX1();
static fa_link* New4();
};
// }
} // ::g
| [
"peyte.com@gmail.com"
] | peyte.com@gmail.com |
aba9ba66118c8305e1e9cb7a30cc92cdc4a14a95 | 171b27ba265922de7836df0ac14db9ac1377153a | /include/eve/module/real/core/function/fuzzy/generic/is_greater_equal.hpp | 4e448575967a85daf70082e4a2f26067d26e9085 | [
"MIT"
] | permissive | JPenuchot/eve | 30bb84af4bfb4763910fab96f117931343beb12b | aeb09001cd6b7d288914635cb7bae66a98687972 | refs/heads/main | 2023-08-21T21:03:07.469433 | 2021-10-16T19:36:50 | 2021-10-16T19:36:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,050 | hpp | //==================================================================================================
/*
EVE - Expressive Vector Engine
Copyright : EVE Contributors & Maintainers
SPDX-License-Identifier: MIT
*/
//==================================================================================================
#pragma once
#include <eve/detail/implementation.hpp>
#include <eve/function/fuzzy.hpp>
#include <eve/function/saturated.hpp>
#include <eve/function/abs.hpp>
#include <eve/function/is_greater_equal.hpp>
#include <eve/function/saturated/prev.hpp>
#include <eve/function/saturated/sub.hpp>
#include <eve/concept/value.hpp>
#include <eve/concept/compatible.hpp>
#include <eve/constant/eps.hpp>
#include <eve/detail/apply_over.hpp>
#include <eve/detail/skeleton_calls.hpp>
namespace eve::detail
{
template<floating_real_value T, floating_real_value U>
EVE_FORCEINLINE auto is_greater_equal_(EVE_SUPPORTS(cpu_)
, almost_type const &
, T const &a
, U const &b) noexcept
requires compatible_values<T, U>
{
return arithmetic_call(almost(is_greater_equal), a, b, 3*eps(as(a)));
}
template<floating_real_value T, floating_real_value U>
EVE_FORCEINLINE auto is_greater_equal_(EVE_SUPPORTS(cpu_)
, almost_type const &
, logical<T> const &a
, logical<U> const &b) noexcept
requires compatible_values<T, U>
{
return arithmetic_call(is_greater_equal, a, b);
}
template<floating_real_value T, floating_real_value U, real_value V>
EVE_FORCEINLINE auto is_greater_equal_(EVE_SUPPORTS(cpu_)
, almost_type const &
, T const &a
, U const &b
, V const &tol) noexcept
requires compatible_values<T, U>
{
if constexpr(integral_value<V>)
{
using c_t = std::conditional_t<scalar_value<T>, U, T>;
c_t aa(a);
c_t bb(b);
return almost(is_greater_equal)(aa, bb, tol);
}
else return arithmetic_call(almost(is_greater_equal), a, b, tol);
}
template<floating_real_value T, value V>
EVE_FORCEINLINE auto is_greater_equal_(EVE_SUPPORTS(cpu_)
, almost_type const &
, T const &a
, T const &b
, [[maybe_unused]] V const &tol) noexcept
{
if constexpr(integral_value<V>)
{
if constexpr(simd_value<V> && scalar_value<T>)
{
using c_t = as_wide_t<T, cardinal_t<V>>;
using i_t = as_integer_t<T, unsigned>;
return almost(is_greater_equal)(c_t(a), c_t(b), convert(tol, as<i_t>()));
}
else
{
return is_greater_equal(a, saturated(prev)(b, tol));
}
}
else
{
return is_greater_equal(a, saturated(sub)(b, tol*max(eve::abs(a), eve::abs(b))));
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
4e46eddcbe77a8cc969389b8d4847128de26b77c | ec02c45b6a77c25c55d8dae787e06ab62c170fec | /sbpl-dev/src/planners/ADStar/adplanner.h | 6b2af250d91d4aa9dcc853f6e4ad7040eb6ebe23 | [] | no_license | Beryl-bingqi/footstep_dynamic_planner | 5400d866a74f0ed557dadc9177f18b6ba20cf33f | 99851122d400de0e6ad73f787de0201cb991880e | refs/heads/master | 2020-07-05T05:57:57.885423 | 2013-07-01T14:29:38 | 2013-07-01T14:29:38 | 11,093,592 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,828 | h | /*
* Copyright (c) 2008, Maxim Likhachev
* 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 University of Pennsylvania 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.
*/
#ifndef __ADPLANNER_H_
#define __ADPLANNER_H_
//---configuration----
//control of EPS
//initial suboptimality bound (cost solution <= cost(eps*cost optimal solution)
#define AD_DEFAULT_INITIAL_EPS 10.0
//as planning time exist, AD* decreases epsilon bound
#define AD_DECREASE_EPS 0.2
//final epsilon bound
#define AD_FINAL_EPS 1.0
//---------------------
#define AD_INCONS_LIST_ID 0
class CMDP;
class CMDPSTATE;
class CMDPACTION;
class CHeap;
class CList;
//-------------------------------------------------------------
/** \brief generic state structure in the search tree generated by AD*
*/
typedef class ADSEARCHSTATEDATA : public AbstractSearchState
{
public:
/** \brief the MDP state itself (pointer to the graph represented as MDPstates)
*/
CMDPSTATE* MDPstate;
/** \brief AD* relevant data
*/
unsigned int v;
/** \brief AD* relevant data
*/
unsigned int g;
/** \brief AD* relevant data
*/
short unsigned int iterationclosed;
/** \brief AD* relevant data
*/
short unsigned int callnumberaccessed;
#if DEBUG
/** \brief AD* relevant data
*/
short unsigned int numofexpands;
#endif
/** \brief best predecessor and the action from it, used only in forward searches
*/
CMDPSTATE *bestpredstate;
/** \brief the next state if executing best action
*/
CMDPSTATE *bestnextstate;
unsigned int costtobestnextstate;
int h;
public:
ADSEARCHSTATEDATA() {};
~ADSEARCHSTATEDATA() {};
} ADState;
/** \brief statespace of AD*
*/
typedef struct ADSEARCHSTATESPACE
{
double eps;
double eps_satisfied;
CHeap* heap;
CList* inconslist;
short unsigned int searchiteration;
short unsigned int callnumber;
CMDPSTATE* searchgoalstate;
CMDPSTATE* searchstartstate;
CMDP searchMDP;
bool bReevaluatefvals;
bool bReinitializeSearchStateSpace;
bool bRebuildOpenList;
} ADSearchStateSpace_t;
/** \brief Anytime D* search planner: all states are uniquely defined by stateIDs
*/
class ADPlanner : public SBPLPlanner
{
public:
/** \brief replan a path within the allocated time, return the solution in the vector
*/
virtual int replan(double allocated_time_secs, vector<int>* solution_stateIDs_V);
/** \brief replan a path within the allocated time, return the solution in the vector, also returns solution cost
*/
virtual int replan(double allocated_time_secs, vector<int>* solution_stateIDs_V, int* solcost);
/** \brief works same as replan function with time and solution states, but it let's you fill out all the parameters for the search
*/
virtual int replan(std::vector<int>* solution_stateIDs_V, ReplanParams params);
/** \brief works same as replan function with time, solution states, and cost, but it let's you fill out all the parameters for the search
*/
virtual int replan(std::vector<int>* solution_stateIDs_V, ReplanParams params, int* solcost);
/** \brief set the goal state
*/
virtual int set_goal(int goal_stateID);
/** \brief set the start state
*/
virtual int set_start(int start_stateID);
/** \brief set a flag to get rid of the previous search efforts, and re-initialize the search, when the next replan is called
*/
virtual int force_planning_from_scratch();
/** \brief Gets rid of the previous search efforts, release the memory and re-initialize the search.
*/
virtual int force_planning_from_scratch_and_free_memory();
/** \brief you can either search forwards or backwards
*/
virtual int set_search_mode(bool bSearchUntilFirstSolution);
/** \brief inform the search about the new edge costs
*/
virtual void costs_changed(StateChangeQuery const & stateChange);
/** \brief direct form of informing the search about the new edge costs
\param succsIDV array of successors of changed edges
\note this is used when the search is run forwards
*/
virtual void update_succs_of_changededges(vector<int>* succsIDV);
/** \brief direct form of informing the search about the new edge costs
\param predsIDV array of predecessors of changed edges
\note this is used when the search is run backwards
*/
virtual void update_preds_of_changededges(vector<int>* predsIDV);
/** \brief returns the suboptimality bound on the currently found solution
*/
virtual double get_solution_eps() const {return pSearchStateSpace_->eps_satisfied;};
/** \brief returns the number of states expanded so far
*/
virtual int get_n_expands() const { return searchexpands; }
/** \brief returns the initial epsilon
*/
virtual double get_initial_eps(){return finitial_eps;};
/** \brief returns the time taken to find the first solution
*/
virtual double get_initial_eps_planning_time(){return finitial_eps_planning_time;}
/** \brief returns the time taken to get the final solution
*/
virtual double get_final_eps_planning_time(){return final_eps_planning_time;};
/** \brief returns the number of expands to find the first solution
*/
virtual int get_n_expands_init_solution(){return num_of_expands_initial_solution;};
/** \brief returns the final epsilon achieved during the search
*/
virtual double get_final_epsilon(){return final_eps;};
/** \brief returns the value of the initial epsilon (suboptimality bound) used
*/
virtual void set_initialsolution_eps(double initialsolution_eps) {finitial_eps = initialsolution_eps;};
/** \brief fills out a vector of stats from the search
*/
virtual void get_search_stats(vector<PlannerStats>* s);
/** \brief constructor
*/
ADPlanner(DiscreteSpaceInformation* environment, bool bForwardSearch);
/** \brief destructor
*/
~ADPlanner();
protected:
//member variables
double finitial_eps, finitial_eps_planning_time, final_eps_planning_time, final_eps, dec_eps, final_epsilon;
double repair_time;
bool use_repair_time;
int num_of_expands_initial_solution;
MDPConfig* MDPCfg_;
vector<PlannerStats> stats;
bool bforwardsearch;
bool bsearchuntilfirstsolution; //if true, then search until first solution (see planner.h for search modes)
ADSearchStateSpace_t* pSearchStateSpace_;
unsigned int searchexpands;
int MaxMemoryCounter;
clock_t TimeStarted;
FILE *fDeb;
//member functions
virtual void Initialize_searchinfo(CMDPSTATE* state, ADSearchStateSpace_t* pSearchStateSpace);
virtual CMDPSTATE* CreateState(int stateID, ADSearchStateSpace_t* pSearchStateSpace);
virtual CMDPSTATE* GetState(int stateID, ADSearchStateSpace_t* pSearchStateSpace);
virtual int ComputeHeuristic(CMDPSTATE* MDPstate, ADSearchStateSpace_t* pSearchStateSpace);
//initialization of a state
virtual void InitializeSearchStateInfo(ADState* state, ADSearchStateSpace_t* pSearchStateSpace);
//re-initialization of a state
virtual void ReInitializeSearchStateInfo(ADState* state, ADSearchStateSpace_t* pSearchStateSpace);
virtual void DeleteSearchStateData(ADState* state);
//used for backward search
virtual void UpdatePredsofOverconsState(ADState* state, ADSearchStateSpace_t* pSearchStateSpace);
virtual void UpdatePredsofUnderconsState(ADState* state, ADSearchStateSpace_t* pSearchStateSpace);
//used for forward search
virtual void UpdateSuccsofOverconsState(ADState* state, ADSearchStateSpace_t* pSearchStateSpace);
virtual void UpdateSuccsofUnderconsState(ADState* state, ADSearchStateSpace_t* pSearchStateSpace);
virtual void UpdateSetMembership(ADState* state);
virtual void Recomputegval(ADState* state);
virtual int GetGVal(int StateID, ADSearchStateSpace_t* pSearchStateSpace);
//returns 1 if the solution is found, 0 if the solution does not exist and 2 if it ran out of time
virtual int ComputePath(ADSearchStateSpace_t* pSearchStateSpace, double MaxNumofSecs);
virtual void BuildNewOPENList(ADSearchStateSpace_t* pSearchStateSpace);
virtual void Reevaluatefvals(ADSearchStateSpace_t* pSearchStateSpace);
//creates (allocates memory) search state space
//does not initialize search statespace
virtual int CreateSearchStateSpace(ADSearchStateSpace_t* pSearchStateSpace);
//deallocates memory used by SearchStateSpace
virtual void DeleteSearchStateSpace(ADSearchStateSpace_t* pSearchStateSpace);
//reset properly search state space
//needs to be done before deleting states
virtual int ResetSearchStateSpace(ADSearchStateSpace_t* pSearchStateSpace);
//initialization before each search
virtual void ReInitializeSearchStateSpace(ADSearchStateSpace_t* pSearchStateSpace);
//very first initialization
virtual int InitializeSearchStateSpace(ADSearchStateSpace_t* pSearchStateSpace);
virtual int SetSearchGoalState(int SearchGoalStateID, ADSearchStateSpace_t* pSearchStateSpace);
virtual int SetSearchStartState(int SearchStartStateID, ADSearchStateSpace_t* pSearchStateSpace);
//reconstruct path functions are only relevant for forward search
virtual int ReconstructPath(ADSearchStateSpace_t* pSearchStateSpace);
virtual void PrintSearchState(ADState* searchstateinfo, FILE* fOut);
virtual void PrintSearchPath(ADSearchStateSpace_t* pSearchStateSpace, FILE* fOut);
virtual int getHeurValue(ADSearchStateSpace_t* pSearchStateSpace, int StateID);
//get path
virtual vector<int> GetSearchPath(ADSearchStateSpace_t* pSearchStateSpace, int& solcost);
virtual bool Search(ADSearchStateSpace_t* pSearchStateSpace, vector<int>& pathIds, int & PathCost, bool bFirstSolution, bool bOptimalSolution, double MaxNumofSecs);
virtual CKey ComputeKey(ADState* state);
virtual void Update_SearchSuccs_of_ChangedEdges(vector<int> const * statesIDV);
};
/**
\brief See comments in sbpl/src/planners/planner.h about the what and why
of this class.
*/
class StateChangeQuery
{
public:
virtual ~StateChangeQuery() {}
virtual std::vector<int> const * getPredecessors() const = 0;
virtual std::vector<int> const * getSuccessors() const = 0;
};
#endif
| [
"icy397@hotmail.com"
] | icy397@hotmail.com |
ad81aedc5a502889a4c8cc55c35baa56f5ef615f | 8d36dc91401a6c4793b8d25adcbf0048263b3feb | /qt/01_随堂笔记/07_EasyMusic_EventSystem/Code/build-EasyMusic-Desktop_Qt_5_5_1_MinGW_32bit-Release/release/moc_easymusic.cpp | 1b2bf399ef3c46e0572978dc1ad3533e99fb5793 | [] | no_license | zhaohanqing1996/test | fdff3a3a460b1ac839cd261176dba32b7f7d18a8 | 080adf71018c5aef43d092662650ca6f1021b683 | refs/heads/master | 2020-06-18T14:24:03.851056 | 2020-04-15T02:12:20 | 2020-04-15T02:12:20 | 196,330,917 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,176 | cpp | /****************************************************************************
** Meta object code from reading C++ file 'easymusic.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../EasyMusic/easymusic.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'easymusic.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.5.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_EasyMusic_t {
QByteArrayData data[18];
char stringdata0[253];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_EasyMusic_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_EasyMusic_t qt_meta_stringdata_EasyMusic = {
{
QT_MOC_LITERAL(0, 0, 9), // "EasyMusic"
QT_MOC_LITERAL(1, 10, 11), // "addSongSlot"
QT_MOC_LITERAL(2, 22, 0), // ""
QT_MOC_LITERAL(3, 23, 14), // "updateShowList"
QT_MOC_LITERAL(4, 38, 19), // "updateShowListState"
QT_MOC_LITERAL(5, 58, 20), // "updateMediaPlayState"
QT_MOC_LITERAL(6, 79, 18), // "updatePlayBackMode"
QT_MOC_LITERAL(7, 98, 1), // "n"
QT_MOC_LITERAL(8, 100, 17), // "updateShowListRow"
QT_MOC_LITERAL(9, 118, 21), // "updateRateSliderRange"
QT_MOC_LITERAL(10, 140, 3), // "dur"
QT_MOC_LITERAL(11, 144, 21), // "updateRateSliderValue"
QT_MOC_LITERAL(12, 166, 3), // "pos"
QT_MOC_LITERAL(13, 170, 17), // "updatePlayPostion"
QT_MOC_LITERAL(14, 188, 22), // "disconnectSliderPlayer"
QT_MOC_LITERAL(15, 211, 17), // "updateCurrentTime"
QT_MOC_LITERAL(16, 229, 13), // "updatePlayTip"
QT_MOC_LITERAL(17, 243, 9) // "playMusic"
},
"EasyMusic\0addSongSlot\0\0updateShowList\0"
"updateShowListState\0updateMediaPlayState\0"
"updatePlayBackMode\0n\0updateShowListRow\0"
"updateRateSliderRange\0dur\0"
"updateRateSliderValue\0pos\0updatePlayPostion\0"
"disconnectSliderPlayer\0updateCurrentTime\0"
"updatePlayTip\0playMusic"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_EasyMusic[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
13, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
0, // signalCount
// slots: name, argc, parameters, tag, flags
1, 0, 79, 2, 0x0a /* Public */,
3, 0, 80, 2, 0x0a /* Public */,
4, 0, 81, 2, 0x0a /* Public */,
5, 0, 82, 2, 0x0a /* Public */,
6, 1, 83, 2, 0x0a /* Public */,
8, 1, 86, 2, 0x0a /* Public */,
9, 1, 89, 2, 0x0a /* Public */,
11, 1, 92, 2, 0x0a /* Public */,
13, 0, 95, 2, 0x0a /* Public */,
14, 0, 96, 2, 0x0a /* Public */,
15, 1, 97, 2, 0x0a /* Public */,
16, 0, 100, 2, 0x0a /* Public */,
17, 0, 101, 2, 0x0a /* Public */,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::Int, 7,
QMetaType::Void, QMetaType::Int, 7,
QMetaType::Void, QMetaType::LongLong, 10,
QMetaType::Void, QMetaType::LongLong, 12,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::LongLong, 12,
QMetaType::Void,
QMetaType::Void,
0 // eod
};
void EasyMusic::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
EasyMusic *_t = static_cast<EasyMusic *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->addSongSlot(); break;
case 1: _t->updateShowList(); break;
case 2: _t->updateShowListState(); break;
case 3: _t->updateMediaPlayState(); break;
case 4: _t->updatePlayBackMode((*reinterpret_cast< int(*)>(_a[1]))); break;
case 5: _t->updateShowListRow((*reinterpret_cast< int(*)>(_a[1]))); break;
case 6: _t->updateRateSliderRange((*reinterpret_cast< qint64(*)>(_a[1]))); break;
case 7: _t->updateRateSliderValue((*reinterpret_cast< qint64(*)>(_a[1]))); break;
case 8: _t->updatePlayPostion(); break;
case 9: _t->disconnectSliderPlayer(); break;
case 10: _t->updateCurrentTime((*reinterpret_cast< qint64(*)>(_a[1]))); break;
case 11: _t->updatePlayTip(); break;
case 12: _t->playMusic(); break;
default: ;
}
}
}
const QMetaObject EasyMusic::staticMetaObject = {
{ &QWidget::staticMetaObject, qt_meta_stringdata_EasyMusic.data,
qt_meta_data_EasyMusic, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *EasyMusic::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *EasyMusic::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_EasyMusic.stringdata0))
return static_cast<void*>(const_cast< EasyMusic*>(this));
return QWidget::qt_metacast(_clname);
}
int EasyMusic::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QWidget::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 13)
qt_static_metacall(this, _c, _id, _a);
_id -= 13;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 13)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 13;
}
return _id;
}
QT_END_MOC_NAMESPACE
| [
"zhaohanqing1996@outlook.com"
] | zhaohanqing1996@outlook.com |
861a9f229036ba65812247c5cd4728db5366e77d | 21d95c8e302242eb03e334d97ff51b9fee8fff90 | /server/include/_jMetalCpp/problems/singleObjective/cec2005Competition/F13ShiftedExpandedGriewankRosenbrock.h | 6c33859d30381997f8626c491cbde1377cdc2d6d | [] | no_license | nszknao/master | 8e909336476efba112e27bd5c4478373a191db12 | ef7fd255209e7ef3d63a483ae03a55b54727a194 | refs/heads/master | 2023-04-30T16:23:17.485757 | 2023-04-26T07:26:17 | 2023-04-26T07:26:17 | 45,908,367 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,734 | h | // F13ShiftedExpandedGriewankRosenbrock.h
//
// Authors:
// Esteban López-Camacho <esteban@lcc.uma.es>
// Antonio J. Nebro <antonio@lcc.uma.es>
//
// Copyright (c) 2014 Antonio J. Nebro
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
#ifndef __F13_SHIFTED_EXPANDED_GRIEWANK_ROSENBROCK__
#define __F13_SHIFTED_EXPANDED_GRIEWANK_ROSENBROCK__
#include <Benchmark.h>
#include <TestFunc.h>
class F13ShiftedExpandedGriewankRosenbrock : public TestFunc {
private:
// Fixed (class) parameters
static const string FUNCTION_NAME;
static const string DEFAULT_FILE_DATA;
// Shifted global optimum
double * m_o;
// In order to avoid excessive memory allocation,
// a fixed memory buffer is allocated for each function object.
double * m_z;
public:
F13ShiftedExpandedGriewankRosenbrock(int dimension, double bias);
F13ShiftedExpandedGriewankRosenbrock(int dimension, double bias, string file_data);
~F13ShiftedExpandedGriewankRosenbrock();
double f (double * x);
}; // F13ShiftedExpandedGriewankRosenbrock
#endif /* __F13_SHIFTED_EXPANDED_GRIEWANK_ROSENBROCK__ */
| [
"iloilo_has@yahoo.co.jp"
] | iloilo_has@yahoo.co.jp |
df874df3f026f77366effe5ba5d1e5c710a9076e | 0abee70995525b07d8f329ca69a2f4e5e88a3163 | /backup/Dijkstra/main.cpp | a329aff4d3dbf78ba145a1a799e29094c0abce1f | [] | no_license | hosh0425/BachelorThesis | a843742efa6d5e20d856ff59a7796848632114bc | 1da8301b8f33d4d41d834c9dcb26dfae3cdeaae5 | refs/heads/master | 2020-12-29T10:43:25.981280 | 2020-02-06T00:58:49 | 2020-02-06T00:58:49 | 238,578,975 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,062 | cpp | #include <QCoreApplication>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <QDebug>
using namespace std;
float points[28][3]={{2.6,3,1.2},{2.8,1.2,0.7},{1.7,1.9,1.7},{1,2.9,-2},{0.4,1.2,0.3},//badi 5
{1.3,0.8,-0.9},{2.9,0,1},{1.7,-0.7,-2},{2.7,-2,-0.5},{2.8,-4,0.6} //badi10
,{2.2,-3.2,2.5},{0.7,-0.8,0.5},{1,-2.2,-0.3},{0,-3.2,-3},{-0.7,-1.8,2.9},//badi15
{0,0,-0.7},{1.5,-4,1.7},{-1.5,-2,-0.9},{-1.2,-0.8,-2.2},{-0.8,0.8,0.8},//badi20
{-0.6,1.5,2.5},{-1.2,3,1},{-2,2.7,1.9},{-1.5,1.2,-2},{-1.9,0.1,-3},//badi25
{-1.5,-3.5,3},{-0.5,2.5,0.2},{-1,3,0.9}};
int edges[28][28]={
{0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{1,0,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{1,1,0,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{1,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0},
{0,0,1,1,0,1,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,0,0,1,0,0,1,0},
{0,1,1,0,1,0,1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0},
{0,1,0,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,1,1,0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,1,0,0,1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,1,0,1,0,0,0,0,1,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,1,1,0,1,1,0,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1,1,0,0,0,0,0,0,0,1,0,0},
{0,0,0,0,0,0,0,0,0,0,0,1,1,1,0,1,0,1,1,0,0,0,0,0,0,1,0,0},
{0,0,0,0,1,1,0,1,0,0,0,1,0,0,1,0,0,0,1,1,1,0,0,1,1,0,0,0},
{0,0,0,0,0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0,1,0,0},
{0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,0,1,0,1,0,0,0,0,1,0,0,0},
{0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,1,0,1,0,0,1,1,0,1,0},
{0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,1,1,1,1,0,1,1},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,0,0,1,1},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,1,0,0,1,1},
{0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,1,1,1,0,1,0,1,1},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,1,1,1,0,0,1,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0},
{0,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,0,1},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,0,0,1,0}
};
float distances[28][28]={
{0,181.108,142.127,160.312,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{181.108,0,130.384,0,0,155.242,120.416,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{142.127,130.384,0,122.066,147.648,117.047,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{160.312,0,122.066,0,180.278,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,155.242,0},
{0,0,147.648,180.278,0,98.4886,0,0,0,0,0,0,0,0,0,126.491,0,0,0,126.491,104.403,0,0,190,0,0,158.114,0},
{0,155.242,117.047,0,98.4886,0,178.885,155.242,0,0,0,170.88,0,0,0,152.643,0,0,0,0,0,0,0,0,0,0,0,0},
{0,120.416,0,0,0,178.885,0,138.924,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,155.242,138.924,0,164.012,0,0,100.499,165.529,0,0,183.848,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,164.012,0,0,130,0,171.172,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,100,0,0,0,0,0,130,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,130,100,0,0,156.205,0,0,0,106.301,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,170.88,0,100.499,0,0,0,0,143.178,0,172.047,106.301,0,0,190,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,165.529,171.172,0,156.205,143.178,0,141.421,174.642,0,186.815,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,141.421,0,156.525,0,170,192.094,0,0,0,0,0,0,0,152.971,0,0},
{0,0,0,0,0,0,0,0,0,0,0,172.047,174.642,156.525,0,193.132,0,82.4621,111.803,0,0,0,0,0,0,187.883,0,0},
{0,0,0,0,126.491,152.643,0,183.848,0,0,0,106.301,0,0,193.132,0,0,0,144.222,113.137,161.555,0,0,192.094,190.263,0,0,0},
{0,0,0,0,0,0,0,0,0,130,106.301,0,186.815,170,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,192.094,82.4621,0,0,0,123.693,0,0,0,0,0,0,150,0,0},
{0,0,0,0,0,0,0,0,0,0,0,190,0,0,111.803,144.222,0,123.693,0,164.924,0,0,0,0,114.018,0,0,0},
{0,0,0,0,126.491,0,0,0,0,0,0,0,0,0,0,113.137,0,0,164.924,0,72.8011,0,0,80.6226,130.384,0,172.627,0},
{0,0,0,0,104.403,0,0,0,0,0,0,0,0,0,0,161.555,0,0,0,72.8011,0,161.555,184.391,94.8683,191.05,0,100.499,155.242},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,161.555,0,85.44,182.483,0,0,86.0233,20},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,184.391,85.44,0,158.114,0,0,151.327,104.403},
{0,0,0,0,190,0,0,0,0,0,0,0,0,0,0,192.094,0,0,0,80.6226,94.8683,182.483,158.114,0,117.047,0,164.012,186.815},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,190.263,0,0,114.018,130.384,191.05,0,0,117.047,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,152.971,187.883,0,0,150,0,0,0,0,0,0,0,0,0,0},
{0,0,0,155.242,158.114,0,0,0,0,0,0,0,0,0,0,0,0,0,0,172.627,100.499,86.0233,151.327,164.012,0,0,0,70.7107},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,155.242,20,104.403,186.815,0,0,70.7107,0}
};
float theta_error[28][28]={
{0,-2.66005,2.82357,2.00092,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0.978361,0,1.87177,0,0,2.6991,-2.18756,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{-0.818026,-2.26664,0,0.47843,1.93244,2.66053,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{2.05933,0,1.04002,0,0.0900037,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-0.880898,0},
{0,0,0.190849,0.928411,0,-0.718132,0,0,0,0,0,0,0,0,0,-2.19245,0,0,0,-3.11975,2.54704,0,0,2.8385,0,0,1.87325,0},
{0,1.15751,2.11893,0,-2.65972,0,0.436445,-0.410101,0,0,0,-1.02947,0,0,0,-1.68985,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0.650845,0,0,0,1.67485,0,2.66657,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,-2.45169,2.52498,0,1.08499,0,0,-1.04183,-0.0073309,0,0,-1.53211,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,2.7234,0,0,-1.46549,0,-2.52439,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,1.6112,0,0,0,0,0,2.5385,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,-1.32709,2.8528,0,0,-0.0562384,0,0,0,1.49047,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0.708933,0,-0.403424,0,0,0,0,-1.85961,0,-3.02125,1.78653,0,0,2.6385,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,1.43108,0.414016,0,-0.394646,2.0788,0,-2.0561,-3.07259,0,-0.999757,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,-2.49769,0,-1.24865,0,2.51014,-0.816241,0,0,0,0,0,0,0,0.239006,0,0},
{0,0,0,0,0,0,0,0,0,0,0,-2.28284,-3.131,2.27294,0,-1.70319,0,0.483478,-0.868649,0,0,0,0,0,0,1.27559,0,0},
{0,0,0,0,1.94595,1.24856,0,0.309486,0,0,0,-0.151874,0,0,-1.2416,0,0,0,-1.8535,3.0531,2.64821,0,0,-3.11624,-2.49408,0,0,0},
{0,0,0,0,0,0,0,0,0,-1.69991,-0.851126,0,0.13865,0.948542,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0.225352,1.14189,0,0,0,2.22273,0,0,0,0,0,0,-0.915682,0,0},
{0,0,0,0,0,0,0,0,0,0,0,2.20009,0,0,1.09294,2.78491,0,0.384318,0,-2.75728,0,0,0,0,-1.85125,0,0,0},
{0,0,0,0,-0.481342,0,0,0,0,0,0,0,0,0,0,-1.58531,0,0,-2.61568,0,0.489404,0,0,1.81935,2.90523,0,0.593031,0},
{0,0,0,0,-2.79136,0,0,0,0,0,0,0,0,0,0,2.5898,0,0,0,1.931,0,-0.55179,-0.0701263,0.960251,1.46092,0,-1.03197,-0.671694},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-2.1902,0,2.49727,-2.73585,0,0,-1.62016,-0.999907},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-2.60853,-1.54432,0,3.13105,0,0,-2.03246,-1.61164},
{0,0,0,0,2.00009,0,0,0,0,0,0,0,0,0,0,1.32535,0,0,0,1.48095,2.31866,-2.87744,-2.39055,0,0.0805254,0,2.91201,-2.98324},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2.94751,0,0,2.09034,-2.71636,-2.46067,0,0,-2.06107,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,-2.62259,-1.96601,0,0,-1.67727,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0.0575097,-1.16516,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-1.94538,-1.87037,2.31825,2.80595,-2.4264,0,0,0,2.1531},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,-2.2101,2.2385,2.52996,-2.74165,0,0,-1.68531,0}
};
float weight[28][28]={
{0,37.8799,33.9442,31.5038,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{28.2443,0,27.0228,0,0,34.8704,27.5862,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{22.453,29.2853,0,17.9995,29.5284,29.875,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{31.8384,0,21.2173,0,23.0504,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24.4526,0},
{0,0,19.5495,27.8543,0,16.4258,0,0,0,0,0,0,0,0,0,28.3736,0,0,0,33.6868,27.6443,0,0,40.0139,0,0,30.4975,0},
{0,26.0375,26.7718,0,27.5506,0,24.8613,21.755,0,0,0,27.2586,0,0,0,28.7628,0,0,0,0,0,0,0,0,0,0,0,0},
{0,18.7812,0,0,0,31.9571,0,32.6443,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,33.4528,31.833,0,26.7182,0,0,18.5318,20.7331,0,0,31.7596,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,36.1059,0,0,24.6469,0,35.8606,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,21.7318,0,0,0,0,0,30.795,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,23.8539,28.8458,0,0,19.8479,0,0,0,21.8276,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,25.422,0,14.8739,0,0,0,0,28.5523,0,38.8169,23.524,0,0,38.8679,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,28.8909,23.7687,0,21.7868,29.8082,0,29.4586,39.4354,0,29.0802,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,31.9888,0,26.7201,0,35.6325,28.6886,0,0,0,0,0,0,0,20.4908,0,0},
{0,0,0,0,0,0,0,0,0,0,0,34.586,39.7701,32.589,0,33.9003,0,13.078,18.9525,0,0,0,0,0,0,30.7942,0,0},
{0,0,0,0,26.9612,26.2343,0,24.7543,0,0,0,14.1578,0,0,31.2556,0,0,0,28.6478,31.6356,35.3679,0,0,41.867,38.0733,0,0,0},
{0,0,0,0,0,0,0,0,0,25.9901,18.1644,0,24.1463,26.6849,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,25.303,16.8505,0,0,0,28.1973,0,0,0,0,0,0,23.9966,0,0},
{0,0,0,0,0,0,0,0,0,0,0,36.356,0,0,20.2376,33.9846,0,17.6637,0,36.414,0,0,0,0,24.8594,0,0,0},
{0,0,0,0,18.5693,0,0,0,0,0,0,0,0,0,0,23.2255,0,0,35.6027,0,11.9043,0,0,20.5022,32.9442,0,24.9763,0},
{0,0,0,0,29.0442,0,0,0,0,0,0,0,0,0,0,35.0333,0,0,0,20.1643,0,23.356,23.4507,17.3605,32.252,0,18.4753,23.2539},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32.7437,0,24.9887,38.4861,0,0,20.036,8.22921},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,37.9951,19.5286,0,37.7044,0,0,30.5614,22.2847},
{0,0,0,0,35.21,0,0,0,0,0,0,0,0,0,0,31.6057,0,0,0,18.5633,25.1439,39.2974,33.4615,0,15.0923,0,37.1866,40.4451},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,40.6714,0,0,26.2294,31.8621,37.9803,0,0,26.4403,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0,0,34.1482,34.7501,0,0,28.3603,0,0,0,0,0,0,0,0,0,0},
{0,0,0,19.7348,26.4403,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32.7249,23.2791,24.0359,34.9933,34.4042,0,0,0,21.1756},
{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,32.0686,15.326,27.5464,39.0608,0,0,18.4952,0}
};
#define max_translation_velocity 0.08 // m/s
#define max_rotational_velocity 10 // rad/s
int main(int argc, char *argv[])
{
ofstream outdata;
outdata.open("/home/hossein/Desktop/weight.txt");
for(int i=0;i<28;i++){
for(int j=0;j<28;j++){
weight[i][j]=fabs(theta_error[i][j]*180/3.1415)/max_rotational_velocity+distances[i][j]/max_translation_velocity/100;
}
}
for(int i=0;i<28;i++){
outdata<<"\n";
for(int j=0;j<28;j++)
outdata<<weight[i][j]<<",";
}
return 0;
}
// //mohasebeye delta_error
// ofstream outdata;
// outdata.open("/home/hossein/Desktop/theta_error.txt");
// for(int i=0;i<28;i++){
// for(int j=0;j<28;j++){
// if(edges[i][j]==1){
// theta_error[i][j]=atan2(points[i][1]-points[j][1],points[i][0]-points[j][0])-points[i][2]-3.1415;
// if(theta_error[i][j]>3.1415)
// theta_error[i][j]=-1*(3.1415*2-theta_error[i][j]);
// if(theta_error[i][j]<-3.1415)
// theta_error[i][j]=3.14*2+theta_error[i][j];
// }
// else{
// theta_error[i][j]=0;
// }
// }
// }
// outdata<<"\n";
// for(int i=0;i<28;i++){
// outdata<<"\n";
// for(int j=0;j<28;j++)
// outdata<<theta_error[i][j]<<",";
// }
| [
"hosh0425@gmail.com"
] | hosh0425@gmail.com |
047db9eaf74a68b5a2ee36ff769d80091e8a8713 | e764f21e8dbefd01c8ba1faf3d8ea2f04c8a0752 | /debug.h | 47ad8258037def906a4f69c37f9a67befc22fb60 | [
"MIT"
] | permissive | MahiruInami/gomoku | e378a7669130c241f4ee842b379032023b3ff5b9 | 0324beb999dffc95ffce3e5a0fa5fe8d16e4276e | refs/heads/master | 2022-12-26T05:44:24.907645 | 2020-09-21T19:59:08 | 2020-09-21T19:59:08 | 295,533,075 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,624 | h | #pragma once
#include <array>
#include <QtGlobal>
#include <QElapsedTimer>
enum class DebugTrackLevel : unsigned {
DEBUG = 0,
INFO,
PRODUCTION
};
enum class DebugTimeTracks : unsigned {
GAME_UPDATE = 0,
AI_UPDATE,
INCREMENTAL_UPDATE,
MAKE_MOVE,
UPDATE_PRIORITY,
NODE_SELECTION,
TRAVERSE_AND_EXPAND,
ERASE_AVAILABLE_MOVES,
CLEAR_TEMPLATES,
ADD_NEW_MOVES,
UPDATE_TEMPLATES,
CREATE_TEMPLATE,
TOTAL_TRACKS
};
enum class DebugCallTracks : unsigned {
GAME_UPDATE = 0,
MAKE_MOVE,
UPDATE_PRIORITY,
CREATE_TEMPLATE,
UPDATE_TEMPLATES,
UPDATE_TEMPLATES_INLINE,
TOTAL_TRACKS
};
class Debug {
public:
static Debug& getInstance() {
static Debug instance;
return instance;
}
Debug();
virtual ~Debug() {
if (_timer) {
delete _timer;
_timer = nullptr;
}
}
void registerTimeTrackName(DebugTimeTracks track, std::string trackName) { _timeTrackNames[static_cast<unsigned>(track)] = trackName; }
void registerCallTrackName(DebugCallTracks track, std::string trackName) { _callTrackNames[static_cast<unsigned>(track)] = trackName; }
void setTimeTrackDebugLevel(DebugTimeTracks track, DebugTrackLevel level) { _timeTracksDebugLevel[static_cast<unsigned>(track)] = static_cast<unsigned>(level); }
void setCallTrackDebugLevel(DebugCallTracks track, DebugTrackLevel level) { _callTracksDebugLevel[static_cast<unsigned>(track)] = static_cast<unsigned>(level); }
void startTrack(DebugTimeTracks track);
void stopTrack(DebugTimeTracks track);
void trackCall(DebugCallTracks track);
void resetStats();
void printStats(DebugTrackLevel);
qint64 getTrackStats(DebugTimeTracks track) const { return _tracksTime[static_cast<unsigned>(track)]; }
qint64 getCallStats(DebugCallTracks track) const { return _callTracks[static_cast<unsigned>(track)]; }
private:
static constexpr unsigned TRACKS_COUNT = 32;
std::array<qint64, TRACKS_COUNT> _tracksStart;
std::array<qint64, TRACKS_COUNT> _tracksEnd;
std::array<qint64, TRACKS_COUNT> _tracksTime;
std::array<qint64, TRACKS_COUNT> _callTracks;
std::array<bool, TRACKS_COUNT> _trackedTimeTracks;
std::array<bool, TRACKS_COUNT> _trackedCallTracks;
std::array<std::string, TRACKS_COUNT> _timeTrackNames;
std::array<std::string, TRACKS_COUNT> _callTrackNames;
std::array<unsigned, TRACKS_COUNT> _timeTracksDebugLevel;
std::array<unsigned, TRACKS_COUNT> _callTracksDebugLevel;
QElapsedTimer* _timer = nullptr;
bool _isEnabled = false;
};
| [
"mahiruinamichan@gmail.com"
] | mahiruinamichan@gmail.com |
f90a67474598b4e3107d1a37c9e6c215850a1d9b | 5218777f96dad9adb655c738ac171369c4ae243a | /ExamPrep2/BinaryTree/Header.h | 246c89dd138f20e08ff9e5b26d792ad4a30629bb | [] | no_license | Pavel-Romanov99/Data-Structures-and-Programming | ddb234ac2146f903abf1b1a837ab79a50198d6d8 | 8d0ac679e717ff5f0cecf14f69b6a5b9f0a7f2c5 | refs/heads/master | 2022-04-02T06:28:39.155165 | 2020-01-17T09:54:48 | 2020-01-17T09:54:48 | 212,769,727 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,485 | h | #pragma once
#pragma once
#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;
template <typename T>
struct node
{
T data;
node* left;
node* right;
bool visited = 0;
int distance = 1;
};
template <typename T>
node<T>* getNewNode(T data) {
node<T>* temp = new node<T>();
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
template <typename T>
class BinaryTree
{
public:
node<T>* root = NULL;
BinaryTree();
BinaryTree(T data);
node<T>* insertNode(node<T>* root, T data);
void inOrder(node<T>* root);
void preOrder(node<T>* root);
void postOrder(node<T>* root);
void BFS(node<T>* node);
void refreshVisited(node<T>* root);
int height(node<T>* node);
int minElement(node<T>* node);
int maxElement(node<T>* node);
int sumElements(node<T>* node);
//===================================
// new functions
void swapTree(node<T>* tree1, node<T>* tree2);
node<T>* swapInsert(node<T>* root,T data);
void addToNodes(node<T>* root, T data);
void map1(node<T>* root, T(*f) (T));
int accumulate(node<T>* root, T(*f) (T, T, T), int value);
bool sameTrees(node<T>* tree1, node<T>* tree2);
bool findElement(node<T>* root, T data);
node<T>* deleteElement(node<T>* root, T data);
node<T>* findMin(node<T>* root);
void numbers(BinaryTree<T> a);
bool checkFull(node<T>* root);
bool checkBalanced(node<T>* root);
bool sameStructure(node<T>* tree1, node<T>* tree2);
void createByPreorder(vector<int> preorder);
int numberElements(node<T>* root);
void leaves(node<T>* root);
};
template<typename T>
int BinaryTree<T>::sumElements(node<T>* root) {
if (root == NULL) return 0;
return (root->data + sumElements(root->left) + sumElements(root->right));
}
template<typename T>
int BinaryTree<T>::minElement(node<T>* root) {
if (root == nullptr) return -1;
node<T>* current = root;
while (current->left != nullptr) {
current = current->left;
}
return current->data;
}
template<typename T>
int BinaryTree<T>::maxElement(node<T>* root) {
if (root == nullptr) return -1;
node<T>* current = root;
while (current->right != nullptr) {
current = current->right;
}
return current->data;
}
template <typename T>
BinaryTree<T>::BinaryTree() {
this->root = NULL;
}
template <typename T>
BinaryTree<T>::BinaryTree<T>(T data) {
root = getNewNode(data);
}
template<typename T>
node<T>* BinaryTree<T>::insertNode(node<T>* root, T data) {
if (root == NULL) {
root = getNewNode(data);
}
else if (data <= root->data) {
root->left = insertNode(root->left, data);
}
else if (data > root->data) {
root->right = insertNode(root->right, data);
}
return root;
}
template<typename T>
void BinaryTree<T>::inOrder(node<T>* root) {
if (root == NULL)return;
inOrder(root->left);
cout << root->data << " ";
inOrder(root->right);
}
template<typename T>
void BinaryTree<T>::preOrder(node<T>* root) {
if (root == NULL) return;
preOrder(root->left);
preOrder(root->right);
cout << root->data << " ";
}
template<typename T>
void BinaryTree<T>::postOrder(node<T>* root) {
if (root == NULL) return;
postOrder(root->right);
cout << root->data << " ";
postOrder(root->left);
}
template<typename T>
void BinaryTree<T>::BFS(node<T>* root) {
if (root == NULL) {
cout << "Empty tree" << endl;
}
queue<node<T>*> queue;
queue.push(root);
root->visited = 1;
while (!queue.empty()) {
node<T>* current = queue.front();
cout << current->data << " ";
queue.pop();
if (current->left != NULL) {
current->left->visited = 1;
current->left->distance = current->distance + 1;
queue.push(current->left);
}
if (current->right != NULL) {
current->right->visited = 1;
current->right->distance = current->distance + 1;
queue.push(current->right);
}
}
cout << endl;
}
template <typename T>
void BinaryTree<T>::refreshVisited(node<T>* root) {
if (root == NULL) return;
root->visited = 0;
refreshVisited(root->left);
refreshVisited(root->right);
}
template<typename T>
int BinaryTree<T>::height(node<T>* root) {
if (root == NULL) {
return -1;
}
int distance = root->distance;
queue<node<T>*> queue;
queue.push(root);
root->visited = 1;
while (!queue.empty()) {
node<T>* current = queue.front();
queue.pop();
if (current->left != NULL) {
current->left->visited = 1;
current->left->distance = current->distance + 1;
queue.push(current->left);
}
if (current->right != NULL) {
current->right->visited = 1;
current->right->distance = current->distance + 1;
queue.push(current->right);
}
distance = current->distance;
}
return distance;
}
//===================================
//Swap trees
template<typename T>
node<T>* BinaryTree<T>::swapInsert(node<T>* root, T data) {
if (root == NULL) {
root = getNewNode(data);
}
else if (data >= root->data) {
root->left = swapInsert(root->left, data);
}
else if (data < root->data) {
root->right = swapInsert(root->right, data);
}
return root;
}
template<typename T>
void BinaryTree<T>::swapTree(node<T>* tree1, node<T>* tree2) {
if (tree1 == NULL)return;
swapTree(tree1->left, tree2);
tree2 = swapInsert(tree2, tree1->data);
swapTree(tree1->right, tree2);
}
//add a number to all nodes
template<typename T>
void BinaryTree<T>::addToNodes(node<T>* root, T data) {
if (root == NULL) {
return;
}
root->data += data;
addToNodes(root->left, data);
addToNodes(root->right, data);
}
//map function to all nodes
int addFive(int x) {
return x + 5;
}
template<typename T>
void BinaryTree<T>::map1(node<T>* root, T(*f)(T)) {
if (root == NULL) {
return;
}
root->data = f(root->data);
map1(root->left, f);
map1(root->right, f);
}
//Accumulate function
int addition(int x, int y, int z) { return x + y + z; }
int product(int x, int y, int z) { return x * y * z; }
template <typename T>
int BinaryTree<T>::accumulate(node<T>* root, T(*op)(T, T, T), int value) {
if (root == nullptr) return value;
return (op(root->data, accumulate(root->right, op, value),
accumulate(root->left, op, value)));
}
//Check whether two trees are the same
template<typename T>
bool BinaryTree<T>::sameTrees(node<T>* tree1, node<T>* tree2) {
if (tree1 == nullptr && tree2 == nullptr) return true; //if both are empty
if (tree1 != NULL && tree2 != NULL) {
return tree1->data == tree2->data && sameTrees(tree1->left, tree2->left) &&
sameTrees(tree1->right, tree2->right);
}
return 0; //if one is empty the other is not
}
//check if an element is in the tree
template<typename T>
bool BinaryTree<T>::findElement(node<T>* root, T data) {
if (root == NULL) return false;
return data == root->data || findElement(root->left, data)
|| findElement(root->right, data);
}
//delete an element from the tree
template <typename T>
node<T>* BinaryTree<T>::findMin(node<T>* root) {
node<T>* current = root;
while (current->left != NULL) {
current = current->left;
}
return current;
}
template <typename T>
node<T>* BinaryTree<T>::deleteElement(node<T>* root, T data) {
if (root == NULL) return root; // if tree is empty
//these two lines fix the tree
else if (data < root->data) root->left = deleteElement(root->left, data);
else if (data > root->data) root->right = deleteElement(root->right, data);
else {
//we have found the element
if (root->left == NULL && root->right == NULL) //case 1: no children
{
delete root;
root = NULL;
}
//case 2: Only one child
else if (root->left == NULL) {
node<T>* temp = root;
root = root->right;
delete temp;
}
else if (root->right == NULL) {
node<T>* temp = root;
root = root->left;
delete temp;
}
//case 3: There are two children
else {
node<T>* temp = findMin(root->right);
root->data = temp->data;
root->right = deleteElement(root->right, temp->data);
}
}
return root;
}
//exercise on binary tree
template<typename T>
void BinaryTree<T>::numbers(BinaryTree<T> a) {
int n;
cout << "How many numbers do you want to insert? ";
cin >> n;
for (int i = 0; i < n; i++)
{
int num;
cin >> num;
a.insertNode(a.root, num);
}
a.inOrder(a.root);
int c;
cout << "How many numbers do you want to delete? ";
cin >> c;
for (int i = 0; i < c; i++)
{
int num;
cin >> num;
a.deleteElement(a.root, num);
}
a.inOrder(a.root);
}
//check if a tree is full
template <typename T>
bool BinaryTree<T>::checkFull(node<T>* root) {
if (root == NULL) return true;
else if (root->left == NULL && root->right == NULL) return true;
return root->left != NULL && root->right != NULL &&
checkFull(root->left) && checkFull(root->right);
}
//check if a tree is balanced
template<typename T>
bool BinaryTree<T>::checkBalanced(node<T>* root) {
if (root == NULL) return false;
if (root->left != nullptr && root->right != nullptr) {
if (height(root->left) == height(root->right) ||
height(root->left) + 1 == height(root->right) ||
height(root->left) == height(root->right) + 1)
return true;
}
return false;
}
//check if two trees have the same structure
template<typename T>
bool BinaryTree<T>::sameStructure(node<T>* tree1, node<T>* tree2) {
if (tree1 == NULL && tree2 == NULL) return true;
return (tree1 != NULL && tree2 != NULL) && sameStructure(tree1->left, tree2->left)
&& sameStructure(tree1->right, tree2->right);
}
//build a tree via a string in a preorder format
template<typename T>
void BinaryTree<T>::createByPreorder(vector<int> preorder) {
int rootData = preorder[preorder.size() - 1];
BinaryTree a(rootData);
for (int i = 0; i < preorder.size() - 1; i++)
{
a.insertNode(a.root, preorder[i]);
}
a.inOrder(a.root);
}
//get number of elements in a tree
template<typename T>
int BinaryTree<T>::numberElements(node<T>* root) {
if (root == NULL) return 0;
return (root != NULL) + numberElements(root->left) +
numberElements(root->right);
}
//prints the leaves in a tree
template<typename T>
void BinaryTree<T>::leaves(node<T>* root) {
if (root == NULL) return;
if (root->left == NULL && root->right == NULL) {
cout << root->data << " ";
}
leaves(root->left);
leaves(root->right);
}
| [
"noreply@github.com"
] | noreply@github.com |
14de19c724987c47e9a941b8b42a880734f8b316 | b16027325ccfbbcef34109776ec4879a8deab108 | /ios/app/Pods/FirebaseFirestore/Firestore/core/src/firebase/firestore/immutable/sorted_map_base.cc | 954bdb9cd73df149425b64e2031f42fd53b8b94f | [
"LicenseRef-scancode-proprietary-license",
"Apache-2.0"
] | permissive | RubyLichtenstein/Kotlin-Multiplatform-Firebase | dc385e683d5116a4abb56ddcecaa35b318c24212 | a6654b5c81a122735e9339dd7897e4fbe4b1f4f2 | refs/heads/master | 2021-06-07T09:52:40.752288 | 2021-05-24T08:03:12 | 2021-05-24T08:03:12 | 154,049,137 | 127 | 19 | Apache-2.0 | 2019-04-25T20:38:53 | 2018-10-21T20:26:29 | C | UTF-8 | C++ | false | false | 1,012 | cc | /*
* Copyright 2018 Google
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Firestore/core/src/firebase/firestore/immutable/sorted_map_base.h"
namespace firebase {
namespace firestore {
namespace immutable {
namespace impl {
// Define external storage for constants:
constexpr SortedMapBase::size_type SortedMapBase::kFixedSize;
constexpr SortedMapBase::size_type SortedMapBase::npos;
} // namespace impl
} // namespace immutable
} // namespace firestore
} // namespace firebase
| [
"oronbz@gmail.com"
] | oronbz@gmail.com |
fdce76c3a88cace60ccf783bc1f1edc4a2e59bbd | bfd1aeb4fe4d4e9781a68364f043dda797a3924e | /test/unit/test_dla_interface.cpp | 32571d261975da2b23a18879349ab049460fa3e8 | [
"BSD-3-Clause"
] | permissive | msimberg/DLA-interface | 82f5dc6bc5127cc978756517b8ce3a7e5e18d70a | c17506eafec31f055b23be51f12abf57de635445 | refs/heads/master | 2020-03-13T19:51:47.222214 | 2018-04-20T12:12:35 | 2018-04-20T12:12:35 | 131,262,257 | 0 | 0 | null | 2018-04-27T07:33:47 | 2018-04-27T07:33:47 | null | UTF-8 | C++ | false | false | 8,721 | cpp | #include "dla_interface.h"
#include <cmath>
#include <iostream>
#include <stdexcept>
#include "gtest/gtest.h"
#include "util_complex.h"
#include "util_distributed_matrix.h"
#include "communicator_grid.h"
#include "communicator_manager.h"
using namespace dla_interface;
using namespace testing;
constexpr auto dists = {scalapack_dist, tile_dist};
constexpr auto solvers = {ScaLAPACK, ELPA, DPlasma, Chameleon};
std::vector<comm::Communicator2DGrid*> comms;
template <typename T>
class DLATypedTest : public ::testing::Test {
public:
BaseType<T> epsilon() {
return std::numeric_limits<BaseType<T>>::epsilon();
}
T value(BaseType<T> r, int arg) {
return testing::value<T>(r, arg);
}
};
typedef ::testing::Types<float, double, std::complex<float>, std::complex<double>> MyTypes;
TYPED_TEST_CASE(DLATypedTest, MyTypes);
bool choleskyFactorizationTestThrows(SolverType solver) {
#ifdef DLA_HAVE_SCALAPACK
if (solver == ScaLAPACK)
return false;
#endif
#ifdef DLA_HAVE_DPLASMA
if (solver == DPlasma)
return false;
#endif
return true;
}
TYPED_TEST(DLATypedTest, CholeskyFactorization) {
using ElType = TypeParam;
int n = 59;
int nb = 3;
auto el_val = [this](int i, int j) {
return this->value(std::exp2(-(i + j) + 2 * (std::min(i, j) + 1)) / 3 - std::exp2(-(i + j)) / 3,
-i + j);
};
auto el_val_expected_lower = [this, &el_val](int i, int j) {
return i < j ? el_val(i, j) : this->value(std::exp2(-std::abs(i - j)), -i + j);
};
auto el_val_expected_upper = [this, &el_val](int i, int j) {
return i > j ? el_val(i, j) : this->value(std::exp2(-std::abs(i - j)), -i + j);
};
for (auto comm_ptr : comms) {
for (auto dist : dists) {
for (auto solver : solvers) {
for (auto uplo : {Lower, Upper}) {
auto A1 = std::make_shared<DistributedMatrix<ElType>>(n, n, nb, nb, *comm_ptr, dist);
auto A2 =
DistributedMatrix<ElType>(n + nb, n + nb, nb, nb, *comm_ptr, dist).subMatrix(n, n, nb, nb);
for (auto A_ptr : {A1, A2}) {
auto& A = *A_ptr;
fillDistributedMatrix(A, el_val);
if (choleskyFactorizationTestThrows(solver)) {
EXPECT_THROW(choleskyFactorization(uplo, A, solver), std::invalid_argument);
}
else {
choleskyFactorization(uplo, A, solver);
if (uplo == Lower)
EXPECT_TRUE(
checkNearDistributedMatrix(A, el_val_expected_lower, 10 * this->epsilon()));
if (uplo == Upper)
EXPECT_TRUE(
checkNearDistributedMatrix(A, el_val_expected_upper, 10 * this->epsilon()));
}
}
}
}
}
}
}
bool LUFactorizationTestThrows(SolverType solver) {
#ifdef DLA_HAVE_SCALAPACK
if (solver == ScaLAPACK)
return false;
#endif
#ifdef DLA_HAVE_DPLASMA
if (solver == DPlasma)
return false;
#endif
return true;
}
TYPED_TEST(DLATypedTest, LUFactorization) {
using ElType = TypeParam;
int n = 59;
int nb = 3;
auto el_val = [this](int i, int j) {
return this->value(
std::exp2(-(i + 2 * j) + 3 * (std::min(i, j) + 1)) / 7 - std::exp2(-(i + 2 * j)) / 7, -i + j);
};
auto el_val_expected = [this, &el_val](int i, int j) {
return i < j ? this->value(std::exp2(-2 * std::abs(i - j)), -i + j)
: this->value(std::exp2(-std::abs(i - j)), -i + j);
};
for (int m : {47, 59, 79}) {
for (auto comm_ptr : comms) {
for (auto dist : dists) {
for (auto solver : solvers) {
// DPlasma supports only 1D communicators for LU.
if (solver == DPlasma && comm_ptr->size2D().first != 1)
continue;
auto A1 = std::make_shared<DistributedMatrix<ElType>>(m, n, nb, nb, *comm_ptr, dist);
auto A2 = DistributedMatrix<ElType>(m + nb, n + 2 * nb, nb, nb, *comm_ptr, dist)
.subMatrix(m, n, nb, 2 * nb);
for (auto A_ptr : {A1, A2}) {
auto& A = *A_ptr;
fillDistributedMatrix(A, el_val);
std::vector<int> ipiv;
if (LUFactorizationTestThrows(solver)) {
EXPECT_THROW(LUFactorization(A, ipiv, solver), std::invalid_argument);
}
else {
LUFactorization(A, ipiv, solver);
EXPECT_TRUE(checkNearDistributedMatrix(A, el_val_expected, 10 * this->epsilon()));
for (int i = 0; i < A.localSize().first; ++i) {
int global_row_index = A.getGlobal2DIndex(Local2DIndex(i, 0)).row;
if (global_row_index < A.size().second) {
int expected = global_row_index + A.baseIndex().row + 1;
EXPECT_EQ(expected, ipiv[A.localBaseIndex().row + i]);
}
}
}
}
}
}
}
}
}
bool matrixMultiplicationTestThrows(SolverType solver) {
#ifdef DLA_HAVE_SCALAPACK
if (solver == ScaLAPACK)
return false;
#endif
#ifdef DLA_HAVE_DPLASMA
if (solver == DPlasma)
return false;
#endif
return true;
}
TYPED_TEST(DLATypedTest, Gemm) {
using ElType = TypeParam;
int m = 49;
int n = 59;
int k = 37;
int nb = 3;
ElType alpha(2);
ElType beta(-1);
auto el_val_c = [this](int i, int j) {
return this->value(static_cast<BaseType<ElType>>(i + 1) / (j + 1), -i + j);
};
auto el_val_c_expected = [this, k, alpha, beta](int i, int j) {
return this->value(static_cast<BaseType<ElType>>(i + 1) / (j + 1), -i + j) *
(alpha * static_cast<BaseType<ElType>>(k) + beta);
};
for (auto trans_a : {NoTrans, Trans, ConjTrans}) {
int a_m = trans_a == NoTrans ? m : k;
int a_n = trans_a == NoTrans ? k : m;
bool swap_index_a = trans_a == NoTrans ? false : true;
int exp_complex_a = trans_a == ConjTrans ? -1 : 1;
auto el_val_a = [this, swap_index_a, exp_complex_a](int i, int j) {
if (swap_index_a)
std::swap(i, j);
return this->value(static_cast<BaseType<ElType>>(i + 1) / (j + 1), exp_complex_a * (-i + j));
};
for (auto trans_b : {NoTrans, Trans, ConjTrans}) {
int b_m = trans_b == NoTrans ? k : n;
int b_n = trans_b == NoTrans ? n : k;
bool swap_index_b = trans_b == NoTrans ? false : true;
int exp_complex_b = trans_b == ConjTrans ? -1 : 1;
auto el_val_b = [this, swap_index_b, exp_complex_b](int i, int j) {
if (swap_index_b)
std::swap(i, j);
return this->value(static_cast<BaseType<ElType>>(i + 1) / (j + 1), exp_complex_b * (-i + j));
};
for (auto comm_ptr : comms) {
for (auto dist : dists) {
for (auto solver : solvers) {
auto a_ptr = DistributedMatrix<ElType>(a_m + nb, a_n + nb, nb, nb, *comm_ptr, dist)
.subMatrix(a_m, a_n, nb, nb);
auto b_ptr = DistributedMatrix<ElType>(b_m + 2 * nb, b_n, nb, nb, *comm_ptr, dist)
.subMatrix(b_m, b_n, 2 * nb, 0);
auto c_ptr =
DistributedMatrix<ElType>(m, n + nb, nb, nb, *comm_ptr, dist).subMatrix(m, n, 0, nb);
auto& a = *a_ptr;
auto& b = *b_ptr;
auto& c = *c_ptr;
fillDistributedMatrix(a, el_val_a);
fillDistributedMatrix(b, el_val_b);
fillDistributedMatrix(c, el_val_c);
if (matrixMultiplicationTestThrows(solver)) {
EXPECT_THROW(matrixMultiplication(trans_a, trans_b, alpha, a, b, beta, c, solver),
std::invalid_argument);
}
else {
matrixMultiplication(trans_a, trans_b, alpha, a, b, beta, c, solver);
EXPECT_TRUE(checkNearDistributedMatrix(c, el_val_c_expected, k * this->epsilon()));
}
}
}
}
}
}
}
int main(int argc, char** argv) {
comm::CommunicatorManager::initialize(2, &argc, &argv, true);
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
if (size != 6) {
std::cout << "This test need 6 MPI ranks (" << size << " provided)!" << std::endl;
return 1;
}
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
// Create communicators used in the tests.
for (auto order : {RowMajor, ColMajor}) {
comms.push_back(&comm::CommunicatorManager::createCommunicator2DGrid(MPI_COMM_WORLD, 2, 3, order));
comms.push_back(&comm::CommunicatorManager::createCommunicator2DGrid(MPI_COMM_WORLD, 3, 2, order));
comms.push_back(&comm::CommunicatorManager::createCommunicator2DGrid(MPI_COMM_WORLD, 1, 6, order));
}
::testing::InitGoogleTest(&argc, argv);
auto ret = RUN_ALL_TESTS();
comm::CommunicatorManager::finalize();
return ret;
}
| [
"rasolca@cscs.ch"
] | rasolca@cscs.ch |
01ff06e23915fddece97bc8465c6a35d876ebac6 | 39621ae5808d68b2192c955f79101182a257f363 | /tank/timer.h | a3d3e3dba5e783dc7ce50f217c716ffc5795886b | [] | no_license | churley862/tank | dfcc11501e2fbe646f6040d9d773bebb30713d1c | b508c370358556a15765c6de731e758cc7321890 | refs/heads/master | 2021-01-22T12:12:21.708511 | 2015-01-03T23:24:24 | 2015-01-03T23:24:24 | 28,572,582 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 607 | h | //
// timer.h
// tank
//
// Created by Kitchen on 12/27/14.
// Copyright (c) 2014 Collin. All rights reserved.
//
#ifndef __tank__timer__
#define __tank__timer__
#include <stdio.h>
#include "sdl.h"
class Timer
{
public:
Timer()
{
reset();
}
void reset()
{
startTime = SDL_GetTicks();
}
int getTime ()
{
return SDL_GetTicks()- startTime;
}
void waitFor (int ms)
{
int delay=(ms-getTime());
if (delay > 0)
SDL_Delay(delay);
}
private :
Uint32 startTime;
};
#endif /* defined(__tank__timer__) */
| [
"phurley@gmail.com"
] | phurley@gmail.com |
e5a1aff37132e9b14fe1b313c8cd2be8fcb8eb82 | 64e4fabf9b43b6b02b14b9df7e1751732b30ad38 | /src/chromium/gen/gen_combined/third_party/blink/renderer/bindings/modules/v8/v8_payment_item.cc | 0d4255a35bc11de9e24dbb9c95c0534f62f8d456 | [
"BSD-3-Clause"
] | permissive | ivan-kits/skia-opengl-emscripten | 8a5ee0eab0214c84df3cd7eef37c8ba54acb045e | 79573e1ee794061bdcfd88cacdb75243eff5f6f0 | refs/heads/master | 2023-02-03T16:39:20.556706 | 2020-12-25T14:00:49 | 2020-12-25T14:00:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,729 | 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/dictionary_v8.cc.tmpl
// by the script code_generator_v8.py.
// DO NOT MODIFY!
// clang-format off
#include "third_party/blink/renderer/bindings/modules/v8/v8_payment_item.h"
#include "base/stl_util.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/modules/v8/v8_payment_currency_amount.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
namespace blink {
static const v8::Eternal<v8::Name>* eternalV8PaymentItemKeys(v8::Isolate* isolate) {
static const char* const kKeys[] = {
"amount",
"label",
"pending",
};
return V8PerIsolateData::From(isolate)->FindOrCreateEternalNameCache(
kKeys, kKeys, base::size(kKeys));
}
void V8PaymentItem::ToImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8_value, PaymentItem* impl, ExceptionState& exception_state) {
if (IsUndefinedOrNull(v8_value)) {
exception_state.ThrowTypeError("Missing required member(s): amount, label.");
return;
}
if (!v8_value->IsObject()) {
exception_state.ThrowTypeError("cannot convert to dictionary.");
return;
}
v8::Local<v8::Object> v8Object = v8_value.As<v8::Object>();
ALLOW_UNUSED_LOCAL(v8Object);
const v8::Eternal<v8::Name>* keys = eternalV8PaymentItemKeys(isolate);
v8::TryCatch block(isolate);
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::Local<v8::Value> amount_value;
if (!v8Object->Get(context, keys[0].Get(isolate)).ToLocal(&amount_value)) {
exception_state.RethrowV8Exception(block.Exception());
return;
}
if (amount_value.IsEmpty() || amount_value->IsUndefined()) {
exception_state.ThrowTypeError("required member amount is undefined.");
return;
} else {
PaymentCurrencyAmount* amount_cpp_value = NativeValueTraits<PaymentCurrencyAmount>::NativeValue(isolate, amount_value, exception_state);
if (exception_state.HadException())
return;
impl->setAmount(amount_cpp_value);
}
v8::Local<v8::Value> label_value;
if (!v8Object->Get(context, keys[1].Get(isolate)).ToLocal(&label_value)) {
exception_state.RethrowV8Exception(block.Exception());
return;
}
if (label_value.IsEmpty() || label_value->IsUndefined()) {
exception_state.ThrowTypeError("required member label is undefined.");
return;
} else {
V8StringResource<> label_cpp_value = label_value;
if (!label_cpp_value.Prepare(exception_state))
return;
impl->setLabel(label_cpp_value);
}
v8::Local<v8::Value> pending_value;
if (!v8Object->Get(context, keys[2].Get(isolate)).ToLocal(&pending_value)) {
exception_state.RethrowV8Exception(block.Exception());
return;
}
if (pending_value.IsEmpty() || pending_value->IsUndefined()) {
// Do nothing.
} else {
bool pending_cpp_value = NativeValueTraits<IDLBoolean>::NativeValue(isolate, pending_value, exception_state);
if (exception_state.HadException())
return;
impl->setPending(pending_cpp_value);
}
}
v8::Local<v8::Value> PaymentItem::ToV8Impl(v8::Local<v8::Object> creationContext, v8::Isolate* isolate) const {
v8::Local<v8::Object> v8Object = v8::Object::New(isolate);
if (!toV8PaymentItem(this, v8Object, creationContext, isolate))
return v8::Undefined(isolate);
return v8Object;
}
bool toV8PaymentItem(const PaymentItem* impl, v8::Local<v8::Object> dictionary, v8::Local<v8::Object> creationContext, v8::Isolate* isolate) {
const v8::Eternal<v8::Name>* keys = eternalV8PaymentItemKeys(isolate);
v8::Local<v8::Context> context = isolate->GetCurrentContext();
auto create_property = [dictionary, context, keys, isolate](
size_t key_index, v8::Local<v8::Value> value) {
bool added_property;
v8::Local<v8::Name> key = keys[key_index].Get(isolate);
if (!dictionary->CreateDataProperty(context, key, value)
.To(&added_property)) {
return false;
}
return added_property;
};
v8::Local<v8::Value> amount_value;
bool amount_has_value_or_default = false;
if (impl->hasAmount()) {
amount_value = ToV8(impl->amount(), creationContext, isolate);
amount_has_value_or_default = true;
} else {
NOTREACHED();
}
if (amount_has_value_or_default &&
!create_property(0, amount_value)) {
return false;
}
v8::Local<v8::Value> label_value;
bool label_has_value_or_default = false;
if (impl->hasLabel()) {
label_value = V8String(isolate, impl->label());
label_has_value_or_default = true;
} else {
NOTREACHED();
}
if (label_has_value_or_default &&
!create_property(1, label_value)) {
return false;
}
v8::Local<v8::Value> pending_value;
bool pending_has_value_or_default = false;
if (impl->hasPending()) {
pending_value = v8::Boolean::New(isolate, impl->pending());
pending_has_value_or_default = true;
} else {
pending_value = v8::Boolean::New(isolate, false);
pending_has_value_or_default = true;
}
if (pending_has_value_or_default &&
!create_property(2, pending_value)) {
return false;
}
return true;
}
PaymentItem* NativeValueTraits<PaymentItem>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exception_state) {
PaymentItem* impl = PaymentItem::Create();
V8PaymentItem::ToImpl(isolate, value, impl, exception_state);
return impl;
}
} // namespace blink
| [
"trofimov_d_a@magnit.ru"
] | trofimov_d_a@magnit.ru |
8ad72f59bd872334b3ce6b3570c20fe6c03ceb5e | 530851a2ee9193f0e47af35a65eac8982ac52a63 | /src/block.cpp | 2dd201127b48da03e7c8d0407fadc38c10a17cb2 | [] | no_license | smmzhang/EasyBlocks | 56be3e6c1d5bfba8aa3b99f8656a0b9ec88ee1e0 | 3ee26c74345ca6a1a7e2763983834906b4d934a0 | refs/heads/master | 2021-12-08T06:03:09.401833 | 2015-08-27T22:33:30 | 2015-08-27T22:33:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,164 | cpp | #include "block.h"
#include "executionthread.h"
bool Block::isValidParam(Block::ParamType given, Block::ParamType target)
{
//if equal -> match
if(given == target)
return true;
//if given is a Variable and target is an Expression -> match
if(given == BOOLEAN_VAR && target == BOOLEAN_EXPRESSION)
return true;
if(given == NUMBER_VAR && target == NUMBER_EXPRESSION)
return true;
if(given == STRING_VAR && target == STRING_EXPRESSION)
return true;
//if none of the above -> no match
return false;
}
bool Block::isExpressionParam(Block::ParamType paramType)
{
return (paramType == BOOLEAN_EXPRESSION
|| paramType == NUMBER_EXPRESSION
|| paramType == STRING_EXPRESSION);
}
bool Block::isVariableParam(Block::ParamType paramType)
{
return (paramType == BOOLEAN_VAR
|| paramType == NUMBER_VAR
|| paramType == STRING_VAR);
}
bool Block::isListParam(Block::ParamType paramType)
{
return (paramType == BOOLEAN_LIST
|| paramType == NUMBER_LIST
|| paramType == STRING_LIST);
}
| [
"brentchesny@Brents-MacBook-Pro.local"
] | brentchesny@Brents-MacBook-Pro.local |
cf7ab9216dd2932ed4f28032eab4f53981414f64 | cd17244bdea3cf5ea9ce9d32ca00b98dbaec9d7a | /递归/revBolish.cpp | 93fe88fdfc7bf175ccc1af153bb06ebab9db486c | [] | no_license | shzcsgithub2018/code | 9fab4cf569e71425a637a70b892f63558334d73f | c2d643bfa2ae814243e6b3c0eeb2083a8459e4a6 | refs/heads/master | 2020-04-21T16:08:40.301576 | 2019-06-27T13:59:36 | 2019-06-27T13:59:36 | 169,690,865 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 666 | cpp | /*
**Source:http://pkuic.openjudge.cn/dg1/2/
**Auther:Shz
**Data : February 8, 2019
*/
#include<iostream>
#include<cstring>
#include<cmath>
using namespace std;
#define TOKEN_LEN 10
double revBolish() {
char token[TOKEN_LEN];
scanf("%s",token);
if (strlen(token) == 1) {
switch (token[0]) {
case '+': return revBolish() + revBolish();
case '-': return revBolish() - revBolish();
case '*': return revBolish() * revBolish();
case '/': return revBolish() / revBolish();
}
}
else
return atof(token);
}
int main() {
printf("%f\n",revBolish());
return 0;
} | [
"1919062854@qq.com"
] | 1919062854@qq.com |
1e69c838cafbd566e4e1da6c8b7c05f93dad75dc | b34cd2fb7a9e361fe1deb0170e3df323ec33259f | /Nexus/Include/Nexus/BinarySequenceProtocol/BinarySequenceProtocolClient.hpp | 1aa3fb70927486b71bf48d6e47e0e06c220bef8d | [] | no_license | lineCode/nexus | c4479879dba1fbd11573c129f15b7b3c2156463e | aea7e2cbcf96a113f58eed947138b76e09b8fccb | refs/heads/master | 2022-04-19T01:10:22.139995 | 2020-04-16T23:07:23 | 2020-04-16T23:07:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,966 | hpp | #ifndef NEXUS_BINARYSEQUENCEPROTOCOLCLIENT_HPP
#define NEXUS_BINARYSEQUENCEPROTOCOLCLIENT_HPP
#include <cstdint>
#include <Beam/IO/NotConnectedException.hpp>
#include <Beam/IO/OpenState.hpp>
#include <Beam/Pointers/Dereference.hpp>
#include <Beam/Pointers/LocalPtr.hpp>
#include <Beam/Pointers/Out.hpp>
#include <boost/noncopyable.hpp>
#include <boost/throw_exception.hpp>
#include "Nexus/BinarySequenceProtocol/BinarySequenceProtocol.hpp"
#include "Nexus/BinarySequenceProtocol/BinarySequenceProtocolMessage.hpp"
#include "Nexus/BinarySequenceProtocol/BinarySequenceProtocolPacket.hpp"
namespace Nexus {
namespace BinarySequenceProtocol {
/*! \class BinarySequenceProtocolClient
\brief Implements a client using the BinarySequenceProtocol.
\tparam ChannelType The type of Channel connected to the server.
\tparam SequenceType The type used to represent sequence numbers.
*/
template<typename ChannelType, typename SequenceType>
class BinarySequenceProtocolClient : private boost::noncopyable {
public:
//! The type of Channel connected to the server.
using Channel = Beam::GetTryDereferenceType<ChannelType>;
//! The type used to represent sequence numbers.
using Sequence = SequenceType;
//! Constructs a BinarySequenceProtocolClient.
/*!
\param channel The Channel to connect to the server
*/
template<typename ChannelForward>
BinarySequenceProtocolClient(ChannelForward&& channel);
~BinarySequenceProtocolClient();
//! Reads the next message from the feed.
BinarySequenceProtocolMessage Read();
//! Reads the next message from the feed.
/*!
\param sequenceNumber The message's sequence number.
*/
BinarySequenceProtocolMessage Read(Beam::Out<Sequence> sequenceNumber);
void Open();
void Close();
private:
using Buffer = typename Channel::Reader::Buffer;
Beam::GetOptionalLocalPtr<ChannelType> m_channel;
Buffer m_buffer;
BinarySequenceProtocolPacket<Sequence> m_packet;
const char* m_source;
std::size_t m_remainingSize;
Sequence m_sequenceNumber;
Beam::IO::OpenState m_openState;
void Shutdown();
};
template<typename ChannelType, typename SequenceType>
template<typename ChannelForward>
BinarySequenceProtocolClient<ChannelType, SequenceType>::
BinarySequenceProtocolClient(ChannelForward&& channel)
: m_channel(std::forward<ChannelType>(channel)) {}
template<typename ChannelType, typename SequenceType>
BinarySequenceProtocolClient<ChannelType, SequenceType>::
~BinarySequenceProtocolClient() {
Close();
}
template<typename ChannelType, typename SequenceType>
BinarySequenceProtocolMessage
BinarySequenceProtocolClient<ChannelType, SequenceType>::Read() {
Sequence sequenceNumber;
return Read(Beam::Store(sequenceNumber));
}
template<typename ChannelType, typename SequenceType>
BinarySequenceProtocolMessage
BinarySequenceProtocolClient<ChannelType, SequenceType>::Read(
Beam::Out<Sequence> sequenceNumber) {
if(!m_openState.IsOpen()) {
BOOST_THROW_EXCEPTION(Beam::IO::NotConnectedException());
}
if(m_sequenceNumber == -1 ||
m_sequenceNumber == m_packet.m_sequenceNumber + m_packet.m_count) {
while(true) {
m_buffer.Reset();
m_channel->GetReader().Read(Beam::Store(m_buffer));
m_packet = BinarySequenceProtocolPacket<Sequence>::Parse(
m_buffer.GetData(), m_buffer.GetSize());
if(m_packet.m_count != 0) {
m_sequenceNumber = m_packet.m_sequenceNumber;
m_source = m_packet.m_payload;
m_remainingSize = m_buffer.GetSize() -
BinarySequenceProtocolPacket<Sequence>::PACKET_LENGTH;
break;
}
}
}
auto message = BinarySequenceProtocolMessage::Parse(m_source,
m_remainingSize);
auto messageSize = message.m_length + sizeof(message.m_length);
m_remainingSize -= messageSize;
m_source += messageSize;
*sequenceNumber = m_sequenceNumber;
++m_sequenceNumber;
return message;
}
template<typename ChannelType, typename SequenceType>
void BinarySequenceProtocolClient<ChannelType, SequenceType>::Open() {
if(m_openState.SetOpening()) {
return;
}
try {
m_channel->GetConnection().Open();
m_sequenceNumber = -1;
} catch(std::exception&) {
m_openState.SetOpenFailure();
Shutdown();
}
m_openState.SetOpen();
}
template<typename ChannelType, typename SequenceType>
void BinarySequenceProtocolClient<ChannelType, SequenceType>::Close() {
if(m_openState.SetClosing()) {
return;
}
Shutdown();
}
template<typename ChannelType, typename SequenceType>
void BinarySequenceProtocolClient<ChannelType, SequenceType>::Shutdown() {
m_channel->GetConnection().Close();
m_openState.SetClosed();
}
}
}
#endif
| [
"kamal@eidolonsystems.com"
] | kamal@eidolonsystems.com |
982954f3e93ae486ff313bb461092f4a862f0750 | a881762a7d07e7f76575bc08e2d64270e8b5d430 | /CallCenter/SLWorkSet.cpp | 40104136235918c35c24bbc9ba55a4ac615e6a66 | [] | no_license | f108/arch | 0d0f3baae1899e17af9ed6ff72d4bfbbea19c620 | 0ad9f394ac58d18ec133f59b4dff4d60d9409611 | refs/heads/master | 2020-03-13T17:07:19.647165 | 2018-05-04T07:34:36 | 2018-05-04T07:34:36 | 131,211,864 | 1 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 10,969 | cpp | // SLWorkSet.cpp: implementation of the CSLWorkSet class.
//
//////////////////////////////////////////////////////////////////////
#include "stdafx.h"
#include "SLWorkSet.h"
#include <stdio.h>
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CSLine::CSLine()
{
InitializeCriticalSection(&CS);
SLServiceGroup = SL_UNATTACHED;
RTState = CCS_BLOCKED;
MustBeBlocked = false;
AlarmBlocking = false;
}
CSLine::~CSLine()
{
DeleteCriticalSection(&CS);
}
//####################################################################
void HCharBuffer::CheckBuffer(void)
{
len += CBR; CBR=0;
if (len==0) return;
int HMI=0;
int HEQ=0;
for (unsigned k=0; k<len;)
{
if (buf[k]=='-') HMI++;
if (buf[k]=='=') HEQ++;
if ((k!=0 && buf[k]=='-' && (HMI==0 || (HMI==1 && HEQ==0) || (HMI==1 && HEQ>0))) ||
(k!=0 && HMI==0 && HEQ!=0))
{
memcpy(&buf[0], &buf[k], len-k);
len-=k; k=0;
HEQ=0; HMI=0;
continue;
};
k++;
};
if (HMI==0) len=0;
return;
};
TZSuperShortString HCharBuffer::GetCommand(void)
{
if (len==0 || buf[0]!='-') return TZSuperShortString();
unsigned int k;
for (k=1; k<len; k++)
{
if (buf[k]=='=')
{
TZSuperShortString ret;
ret = TZSuperShortString(&buf[0], k+1);
memcpy(&buf[0], &buf[k+1], len-k);
len-= k+1;
return ret;
};
};
return TZSuperShortString();
};
//####################################################################
CSLWorkSet::CSLWorkSet(bool CreateSuspend) : CThread(CreateSuspend)
{
hPort=INVALID_HANDLE_VALUE;
PortName = "\\\\.\\COM28";
}
CSLWorkSet::~CSLWorkSet()
{
}
void CSLWorkSet::SaveTo(TBinaryData *TBD)
{
for (int i=0; i<SLCount; i++)
(*TBD) << SLList[i].SLServiceGroup << SLList[i].SLComment;
}
void CSLWorkSet::LoadFrom(TBinaryData *TBD)
{
for (int i=0; i<SLCount; i++)
(*TBD) >> SLList[i].SLServiceGroup >> SLList[i].SLComment;
}
void CSLWorkSet::SaveTo(TSNPData *TND)
{
for (int i=0; i<SLCount; i++)
(*TND) << SLList[i].SLServiceGroup << SLList[i].SLComment;
}
void CSLWorkSet::LoadFrom(TSNPData *TND)
{
unsigned __int32 k;
(*TND) >> k;
if (k<0 || k>=SLCount) return;
(*TND) >> SLList[k].SLServiceGroup >> SLList[k].SLComment;
PostSysMessage(SCMD_SAVEPROFILE);
}
//====================================================================================================
unsigned CSLWorkSet::GetSLSG(unsigned index)
{
if (index>=SLCount) return 0;
unsigned ret;
EnterCriticalSection(&SLList[index].CS);
ret = SLList[index].SLServiceGroup;
LeaveCriticalSection(&SLList[index].CS);
return ret;
}
unsigned CSLWorkSet::GetSLState(unsigned index)
{
if (index>=SLCount) return 0;
unsigned ret;
EnterCriticalSection(&SLList[index].CS);
ret = SLList[index].RTState;
LeaveCriticalSection(&SLList[index].CS);
return ret;
}
void CSLWorkSet::SetSLState(unsigned index, unsigned State)
{
if (index>=SLCount) return;
char buf[30];
sprintf(buf, "-KK%X%X%X%X=", index, index, State, State);
OutboundQueue.Push(new TZSuperShortString(buf));
}
unsigned CSLWorkSet::GetRMState(unsigned index)
{
return 0;
}
void CSLWorkSet::SetRMState(unsigned index, unsigned State)
{
if (index>=SLCount) return;
char buf[30];
sprintf(buf, "-RR%X%X%X%X=", index, index, State, State);
OutboundQueue.Push(new TZSuperShortString(buf));
}
//====================================================================================================
void CSLWorkSet::RequestSLsState(void)
{
OutboundQueue.Push(new TZSuperShortString("-SS22="));
OutboundQueue.Push(new TZSuperShortString("-SS33="));
}
void CSLWorkSet::RequestRMsState(void)
{
OutboundQueue.Push(new TZSuperShortString("-SS11="));
// RequestSLsState();
}
//====================================================================================================
void CSLWorkSet::OnAlarm(unsigned SLNumber)
{
if (SLList[SLNumber].MustBeBlocked==false)
{
int i;
for (i=SLNumber+1; i<SLCount; i++)
{
if (SLList[i].SLServiceGroup==SLList[SLNumber].SLServiceGroup &&
SLList[i].MustBeBlocked==true && SLList[i].AlarmBlocking==false)
{
SLList[i].MustBeBlocked = false;
if (SLList[i].RTState==CCS_BLOCKED)
SetSLState(i, CCS_SLSETTODEFAULT);
return;
};
};
for (i=0; i<SLNumber; i++)
{
if (SLList[i].SLServiceGroup==SLList[SLNumber].SLServiceGroup &&
SLList[i].MustBeBlocked==true && SLList[i].AlarmBlocking==false)
{
SLList[i].MustBeBlocked = false;
if (SLList[i].RTState==CCS_BLOCKED)
SetSLState(i, CCS_SLSETTODEFAULT);
return;
};
};
};
}
void CSLWorkSet::OnDefault(unsigned SLNumber)
{
PostSysMessage(SCMD_CHECKSLCOUNT, 0, SLNumber, SLList[SLNumber].SLServiceGroup);
}
void CSLWorkSet::CheckSLCount(unsigned SGUID, unsigned ActSLCount, unsigned FirstSL)
{
__int32 TAC=0, i;
for (i=0; i<SLCount; i++)
if (SLList[i].SLServiceGroup==SGUID && SLList[i].RTState!=CCS_BLOCKED &&
SLList[i].RTState!=CCS_ALARM2 && SLList[i].MustBeBlocked!=true) TAC++;
FLOG << time << "CHECK SL: " << SGUID << " " << ActSLCount << " " << TAC << endl;
if (TAC>=ActSLCount) // блокируем лишние линии
{
for (i=SLCount-1; i>=0; i--)
{
if (TAC<=ActSLCount) return;
if (SLList[i].SLServiceGroup==SGUID && SLList[i].RTState!=CCS_BLOCKED &&
SLList[i].RTState!=CCS_ALARM2 && SLList[i].MustBeBlocked!=true)
{
SLList[i].MustBeBlocked = true;
TAC--;
};
if (SLList[i].SLServiceGroup==SGUID && ActSLCount==0 && SLList[i].RTState!=CCS_ALARM2)
{
SLList[i].MustBeBlocked = true;
SetSLState(i, CCS_SLBLOCK);
};
};
return;
}
else
{
for (i=0; i<SLCount; i++) // разблокируем заблокированные рабочие линии
{
if (TAC>=ActSLCount) return;
if (SLList[i].SLServiceGroup==SGUID &&
(SLList[i].RTState==CCS_BLOCKED || SLList[i].RTState==CCS_DEFAULT) &&
SLList[i].MustBeBlocked==true)
{
SLList[i].MustBeBlocked=false;
SetSLState(i, CCS_SLSETTODEFAULT);
TAC++;
};
};
};
}
void CSLWorkSet::LockAllSL(void)
{
unsigned k=SL_UNATTACHED;
for (int i=0; i<12; i++)
{
SetSLState(i, CCS_SLSETTODEFAULT);
SLList[i].MustBeBlocked = true;
};
}
//=======================================================================
void CSLWorkSet::Execute(void)
{
FLOG << time << "Start CSLWorkSet" << endl;
COMSTAT CS;
TZSuperShortString str;
TZSuperShortString *outstr;
DWORD cbw;
InitPort();
LockAllSL();
for (int i=0; i<15; i++) SetSLState(i, 0xf);
RequestSLsState();
RequestRMsState();
CS.cbInQue = 0;
HCB.GetMaxSize(CS.cbInQue);
for (;!Terminated;)
{
// cout << "aa" << HCB.GetMaxSize(CS.cbInQue) << endl;
try
{
ReadFile(hPort, HCB.GetBufPtr(), HCB.GetMaxSize(100), HCB.GetLPCBR(), NULL);
for (;;)
{
HCB.CheckBuffer();
str = HCB.GetCommand();
if (str.length()!=0)
{
ProcessComCommand(str);
} else break;
};
if (!OutboundQueue.IsEmpty())
{
outstr = OutboundQueue.Pop();
// FLOG << "PortOut: " << outstr->c_str() << endl;
WriteFile(hPort, outstr->c_str(), outstr->length(), &cbw, NULL);
delete outstr;
};
}
catch (...)
{
FLOG << time << "Exception in SLWorkSet" << endl;
};
};
}
void CSLWorkSet::ProcessComCommand(TZSuperShortString &str)
{
unsigned PTNum, PTState;
// FLOG << "PortIn : " << str.c_str() << endl;
if (str[1]=='T' && str[2]=='L')
{
PTNum = (str[4]>='0'&&str[4]<='9')?str[4]-0x30:((str[4]>='a'&&str[4]<='f')?(unsigned char)str[4]-97+10:0);
PTState = (str[6]>='0'&&str[6]<='9')?str[6]-0x30:((str[6]>='a'&&str[6]<='f')?(unsigned char)str[6]-97+10:0);
if (PTNum>=SLCount) return;
if (PTState!=CCS_ALARM2)
SLList[PTNum].AlarmBlocking = false;
switch (PTState)
{
case CCS_RING:
FLOG << time << "RING on line " << PTNum << " " << PTState<< endl;
// if (SLList[PTNum].RTState!=CCS_RING)
PostSysMessage(SCMD_ADDRINGINQUEUE, 0, PTNum, SLList[PTNum].SLServiceGroup);
SLList[PTNum].RTState = CCS_RING;
break;
case CCS_CALLINPROGRESS:
case CCS_COMBUSY:
break;
case CCS_BLOCKED:
SLList[PTNum].MustBeBlocked = false;
case CCS_ALARM:
break;
case CCS_ALARM2:
// SLList[PTNum].AlarmBlocking = true;
PostSysMessage(SCMD_CHECKSLCOUNT, 0, PTNum, SLList[PTNum].SLServiceGroup);
// SetSLState(PTNum, CCS_SLBLOCK);
break;
case CCS_DEFAULT:
if (SLList[PTNum].RTState==CCS_ALARM2) PostSysMessage(SCMD_CHECKSLCOUNT, 0, PTNum, SLList[PTNum].SLServiceGroup);
if (SLList[PTNum].MustBeBlocked==true) SetSLState(PTNum, CCS_SLBLOCK);
case CCS_HOLD:
PostSysMessage(SCMD_DELETERINGINQUEUE, 0, PTNum);
break;
};
SLList[PTNum].RTState = PTState;
} else if (str[1]=='R' && str[2]=='M')
{
PTNum = (str[4]>='0'&&str[4]<='9')?str[4]-0x30:((str[4]>='a'&&str[4]<='f')?(unsigned char)str[4]-97+10:0);
PTState = (str[6]>='0'&&str[6]<='9')?str[6]-0x30:((str[6]>='a'&&str[6]<='f')?(unsigned char)str[6]-97+10:0);
switch (PTState)
{
case CCS_RMALARM:
PostSysMessage(SCMD_RMOALARM, 0, PTNum);
break;
case CCS_RMINUSE:
PostSysMessage(SCMD_SETRMOINSERV, 0, PTNum);
break;
};
} else if (str[1]=='S' && str[2]=='R')
{
for (int i=0; i<SLCount; i++)
if (str[i+4]=='0') PostSysMessage(SCMD_RMOALARM, 0, i);
} else if (str[1]=='S' && str[2]=='T')
{
// FLOG << "SLState::" << str.c_str() << endl;
FLOG << time << "SLST-AMSC [";
for (int i=0; i<SLCount; i++)
{
FLOG << SLList[i].AlarmBlocking << SLList[i].MustBeBlocked << str[i+4] << "x";
if (i!=SLCount-1) FLOG << ".";
SLList[i].RTState = (str[i+4]>='0'&&str[i+4]<='9')?str[i+4]-0x30:((str[i+4]>='a'&&str[i+4]<='f')?(unsigned char)str[i+4]-97+10:0);
if (SLList[i].RTState==CCS_DEFAULT && SLList[i].MustBeBlocked)
SetSLState(i, CCS_SLBLOCK);
};
FLOG << "]" << endl;
};
}
DWORD CSLWorkSet::InitPort(void)
{
if (hPort!=INVALID_HANDLE_VALUE) CloseHandle(hPort);
hPort = CreateFile(PortName.c_str(), GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hPort==INVALID_HANDLE_VALUE) return GetLastError();
DCB dcb;
memset(&dcb,0,sizeof(DCB));
dcb.DCBlength = sizeof(DCB);
GetCommState(hPort, &dcb);
dcb.BaudRate = CBR_9600;
dcb.ByteSize = 8;
dcb.Parity = EVENPARITY;
dcb.StopBits = ONESTOPBIT;
dcb.fOutxDsrFlow = FALSE;
dcb.fOutxCtsFlow = FALSE;
dcb.fDsrSensitivity = FALSE;
dcb.fInX = dcb.fOutX = FALSE;
dcb.fAbortOnError =FALSE;
dcb.fDtrControl = DTR_CONTROL_DISABLE;
dcb.fRtsControl = DTR_CONTROL_DISABLE;
dcb.fBinary = TRUE;
dcb.fParity = TRUE;
if (!SetCommState(hPort,&dcb)) return GetLastError();
COMMTIMEOUTS com_t_out;
com_t_out.ReadIntervalTimeout = 1;
com_t_out.ReadTotalTimeoutMultiplier = 3;
com_t_out.ReadTotalTimeoutConstant = 1;
com_t_out.WriteTotalTimeoutMultiplier = 10;
com_t_out.WriteTotalTimeoutConstant = 200;
if (!SetCommTimeouts(hPort, &com_t_out)) return GetLastError();
if (!SetupComm(hPort, 512, 512)) return GetLastError();
return ERROR_SUCCESS;
}
| [
"smith@SMTHSB"
] | smith@SMTHSB |
e982b1f7c84c573f42148ebe14a65ea9bfe244c1 | 5e7b8bfa89225e03bc8cdc0723e8756b81b9e008 | /cycledetectundirectdfs.cpp | cfc3ec3d0d9489fbe50941c2bcf35d18eba1fae3 | [] | no_license | shashankch/DataStructures-Algorithms | 3e0137065f878c962a815d17cb7916487ebdeb0b | b6b447ebf4e1a18ec23b94172e844ce0d53f7a14 | refs/heads/master | 2020-09-11T13:55:21.068954 | 2020-05-06T07:24:07 | 2020-05-06T07:24:07 | 222,088,726 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,054 | cpp | #include <iostream>
#include <map>
#include <list>
#include <queue>
using namespace std;
template <typename T>
class Graph
{
map<T, list<T>> adjList;
public:
Graph()
{
}
void addEdge(T u, T v, bool bidir = true)
{
adjList[u].push_back(v);
if (bidir)
{
adjList[v].push_back(u);
}
}
void print()
{
//iterate over the map
for (auto i : adjList)
{
cout << i.first << "-->";
// i.second is LL
for (T entry : i.second)
{
cout << entry << ",";
}
cout << endl;
}
}
bool iscyclichelper(T node, map<T, bool> &visited, T parent)
{
visited[node] = true;
for (T neighbour : adjList[node])
{
if (!visited[neighbour])
{
bool cycledetected = iscyclichelper(neighbour, visited, node);
if (cycledetected)
{
return true;
}
}
// in this neighbour is already visited..
else if (neighbour != parent)
{
return true;
}
}
return false;
}
// CHECK FOR UNDIRECTED GRAPH USING DFS (RECURSIVE)
bool iscyclicdfs()
{
map<T, bool> visited;
// you can find cycle in dfs tree..
for (auto i : adjList)
{
T node = i.first;
if (!visited[node])
{
bool ans = iscyclichelper(node, visited, node);
if (ans == true)
{
return true;
}
}
}
return false;
}
};
int main(int argc, char const *argv[])
{
Graph<int> g;
g.addEdge(1, 2);
g.addEdge(1, 4);
g.addEdge(2, 3);
g.addEdge(4, 3);
if (g.iscyclicdfs())
{
cout << "cycle present !";
}
else
{
cout << "cycle not present";
}
return 0;
}
| [
"shashakchandel@gmail.com"
] | shashakchandel@gmail.com |
1d6043f153a999a1cff26d337aecd7c2bb6e02f5 | 33bd7c6d8df57039ec636cbf62f02265e7b861fb | /include/h3api/H3DialogControls/H3DlgPcx16.cpp | 7002e6ff3cc0bf3818180a68bd902e1c1491147b | [
"MIT"
] | permissive | RoseKavalier/H3API | 26f5bd1e2d63d1a61f762bba16a009ba33bf021f | 49c65f1e30fe82a2156918aa7e45349f91a8524d | refs/heads/master | 2023-08-18T14:07:00.214661 | 2022-11-14T02:27:17 | 2022-11-14T02:27:17 | 367,050,838 | 21 | 8 | MIT | 2023-08-06T16:55:05 | 2021-05-13T13:04:01 | C++ | UTF-8 | C++ | false | false | 2,120 | cpp | //////////////////////////////////////////////////////////////////////
// //
// Created by RoseKavalier: //
// rosekavalierhc@gmail.com //
// Created or last updated on: 2021-02-03 //
// ***You may use or distribute these files freely //
// so long as this notice remains present.*** //
// //
//////////////////////////////////////////////////////////////////////
#include "h3api/H3DialogControls/H3DlgPcx16.hpp"
#include "h3api/H3Assets/H3LoadedPcx16.hpp"
namespace h3
{
_H3API_ H3DlgPcx16* H3DlgPcx16::Create(INT32 x, INT32 y, INT32 width, INT32 height, INT32 id, LPCSTR pcxName)
{
H3DlgPcx16* p = H3ObjectAllocator<H3DlgPcx16>().allocate(1);
if (p)
THISCALL_8(H3DlgPcx16*, 0x450340, p, x, y, width, height, id, pcxName, 0x800);
return p;
}
_H3API_ H3DlgPcx16* H3DlgPcx16::Create(INT32 x, INT32 y, INT32 id, LPCSTR pcxName)
{
H3DlgPcx16* p = Create(x, y, 0, 0, id, pcxName);
if (p && p->loadedPcx16)
{
p->widthItem = p->loadedPcx16->width;
p->heightItem = p->loadedPcx16->height;
}
return p;
}
_H3API_ H3DlgPcx16* H3DlgPcx16::Create(INT32 x, INT32 y, LPCSTR pcxName)
{
return Create(x, y, 0, 0, 0, pcxName);
}
_H3API_ VOID H3DlgPcx16::SetPcx(H3LoadedPcx16* pcx16)
{
loadedPcx16 = pcx16;
}
_H3API_ H3LoadedPcx16* H3DlgPcx16::GetPcx()
{
return loadedPcx16;
}
_H3API_ VOID H3DlgPcx16::SinkArea(INT32 x, INT32 y, INT32 w, INT32 h)
{
loadedPcx16->SinkArea(x, y, w, h);
}
_H3API_ VOID H3DlgPcx16::BevelArea(INT32 x, INT32 y, INT32 w, INT32 h)
{
loadedPcx16->BevelArea(x, y, w, h);
}
_H3API_ VOID H3DlgPcx16::SinkArea(H3DlgItem* it)
{
SinkArea(it->GetX() - 1, it->GetY() - 1, it->GetWidth() + 2, it->GetHeight() + 2);
}
_H3API_ VOID H3DlgPcx16::BevelArea(H3DlgItem* it)
{
BevelArea(it->GetX() - 1, it->GetY() - 1, it->GetWidth() + 2, it->GetHeight() + 2);
}
} /* namespace h3 */
| [
"rosekavalierhc@gmail.com"
] | rosekavalierhc@gmail.com |
d038f9b33baee68c2e9aab2396fade65e7e56713 | 78612309dd1dbb4b54779a52a8ee62ad114e767a | /array reversal.cpp | 8b8cdfd05a98001d44b2564468c80c61d1ea6ffb | [] | no_license | supriya701/c-programming-part--7 | 0f794616f792cdf0a39655804681c2edff8e1009 | 3967b4bba13b56ddb59e295852d1f2b4c1613385 | refs/heads/master | 2022-11-06T10:44:19.730022 | 2020-06-21T15:25:51 | 2020-06-21T15:25:51 | 273,931,064 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 524 | cpp | #include <stdio.h>
#include <stdlib.h>
int main()
{
int num, *arr, i,temp;
scanf("%d", &num);
arr = (int*) malloc(num * sizeof(int));
for(i = 0; i < num; i++) {
scanf("%d", arr + i);
}
for (i = 0; i < num / 2; i++) {
temp = (int) *(arr + num - i - 1);
*(arr + num - i - 1) = *(arr + i);
*(arr + i) = temp;
}
/* Write the logic to reverse the array. */
for(i = 0; i < num; i++)
printf("%d ", *(arr + i));
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
1fb2ade021ac7b067aba7b8e23a3f0e08e49921b | 10915905c29357dbc38227a03511e964d1271fa0 | /src/privatesend-util.h | ed8308a4d779ccbc0109cd4a86afb12cacce9243 | [
"MIT"
] | permissive | cryptocoineroffiziell/GermancommunityCoin3.0 | 97eb074eff0c6b55b9e3b643c000d9d8dd0c93f5 | 1e9e79b7c15ea6c3fbf93cf9d860c935f9efa3ae | refs/heads/master | 2020-03-23T22:11:24.320420 | 2018-07-24T13:20:27 | 2018-07-24T13:20:27 | 142,159,182 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 838 | h | // Copyright (c) 2014-2017 The GermanCC Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef PRIVATESENDUTIL_H
#define PRIVATESENDUTIL_H
#include "wallet/wallet.h"
class CKeyHolder
{
private:
CReserveKey reserveKey;
CPubKey pubKey;
public:
CKeyHolder(CWallet* pwalletIn);
CKeyHolder(CKeyHolder&&) = default;
CKeyHolder& operator=(CKeyHolder&&) = default;
void KeepKey();
void ReturnKey();
CScript GetScriptForDestination() const;
};
class CKeyHolderStorage
{
private:
std::vector<std::unique_ptr<CKeyHolder> > storage;
mutable CCriticalSection cs_storage;
public:
CScript AddKey(CWallet* pwalletIn);
void KeepAll();
void ReturnAll();
};
#endif //PRIVATESENDUTIL_H
| [
"38588994+cryptocoineroffiziell@users.noreply.github.com"
] | 38588994+cryptocoineroffiziell@users.noreply.github.com |
f4168b6af7b78f104907550d6458e2f4c1d3bae2 | 2aeb2e79bf5fcb5a344a20c2e7b481fa177d3acb | /src/sampling.cxx | 3c932fd5e2aefba791f2651cdb9ea2c6e4e54645 | [
"Apache-2.0"
] | permissive | takaho/10xrnaseq | 63655984301af62028361f802974f6cfa6cccde9 | eefc82de763b711fdf2c5c9d9a760f8f71607dff | refs/heads/master | 2020-03-22T09:21:34.477389 | 2018-07-06T09:30:02 | 2018-07-06T09:30:02 | 139,831,682 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 571 | cxx | #include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <stdexcept>
#include <list>
#include <set>
#include <fstream>
#include <boost/program_options.hpp>
#include <boost/iostreams/device/file.hpp>
#include <boost/iostreams/filtering_stream.hpp>
#include <boost/iostreams/filter/gzip.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
typedef unsigned long long ullong;
int main(int argc, char** argv) {
try {
return 0;
} catch (exception& e) {
cerr << e.what() << endl;
return -1;
}
}
| [
"takaho.endo@riken.jp"
] | takaho.endo@riken.jp |
4d93307b99b0b70eb14b0d32c936a7833c5e64bc | feea534063d5b224c947f7604510bd62b8017e23 | /Quadruped Bot/Arduino_Code/FOWSGJ6IEFIAEWY.ino | 2071070f2ace4ff0c10984be7b54b3c106a6d010 | [] | no_license | CSEC-NITH/Hack4-0 | 57454da14797abbce6e2fffb5a7e329105206f00 | 4f40cdee257b5b30cec22cc502c923387512cf28 | refs/heads/master | 2022-12-25T00:07:03.139438 | 2021-03-30T12:50:35 | 2021-03-30T12:50:35 | 240,886,568 | 1 | 38 | null | 2022-12-22T14:19:58 | 2020-02-16T12:21:22 | C# | UTF-8 | C++ | false | false | 20,794 | ino | /* Includes ------------------------------------------------------------------*/
#include <Servo.h> //to define and control servos
#include <FlexiTimer2.h>//to set a timer to manage all servos
/* Servos --------------------------------------------------------------------*/
//define 12 servos for 4 legs
Servo servo[4][3];
//define servos' ports
const int servo_pin[4][3] = { {2, 3, 4}, {5, 6, 7}, {8, 9, 10}, {11, 12, 13} };
/* Size of the robot ---------------------------------------------------------*/
const float length_a = 55;
const float length_b = 77.5;
const float length_c = 27.5;
const float length_side = 71;
const float z_absolute = -28;
/* Constants for movement ----------------------------------------------------*/
const float z_default = -50, z_up = -30, z_boot = z_absolute;
const float x_default = 62, x_offset = 0;
const float y_start = 0, y_step = 40;
/* variables for movement ----------------------------------------------------*/
volatile float site_now[4][3]; //real-time coordinates of the end of each leg
volatile float site_expect[4][3]; //expected coordinates of the end of each leg
float temp_speed[4][3]; //each axis' speed, needs to be recalculated before each movement
float move_speed; //movement speed
float speed_multiple = 1; //movement speed multiple
const float spot_turn_speed = 4;
const float leg_move_speed = 8;
const float body_move_speed = 3;
const float stand_seat_speed = 1;
volatile int rest_counter; //+1/0.02s, for automatic rest
//functions' parameter
const float KEEP = 255;
//define PI for calculation
const float pi = 3.1415926;
/* Constants for turn --------------------------------------------------------*/
//temp length
const float temp_a = sqrt(pow(2 * x_default + length_side, 2) + pow(y_step, 2));
const float temp_b = 2 * (y_start + y_step) + length_side;
const float temp_c = sqrt(pow(2 * x_default + length_side, 2) + pow(2 * y_start + y_step + length_side, 2));
const float temp_alpha = acos((pow(temp_a, 2) + pow(temp_b, 2) - pow(temp_c, 2)) / 2 / temp_a / temp_b);
//site for turn
const float turn_x1 = (temp_a - length_side) / 2;
const float turn_y1 = y_start + y_step / 2;
const float turn_x0 = turn_x1 - temp_b * cos(temp_alpha);
const float turn_y0 = temp_b * sin(temp_alpha) - turn_y1 - length_side;
/* ---------------------------------------------------------------------------*/
/*
- setup function
---------------------------------------------------------------------------*/
void setup()
{
//start serial for debug
Serial.begin(115200);
Serial.println("Robot starts initialization");
//initialize default parameter
set_site(0, x_default - x_offset, y_start + y_step, z_boot);
set_site(1, x_default - x_offset, y_start + y_step, z_boot);
set_site(2, x_default + x_offset, y_start, z_boot);
set_site(3, x_default + x_offset, y_start, z_boot);
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
site_now[i][j] = site_expect[i][j];
}
}
//start servo service
FlexiTimer2::set(20, servo_service);
FlexiTimer2::start();
Serial.println("Servo service started");
//initialize servos
servo_attach();
Serial.println("Servos initialized");
Serial.println("Robot initialization Complete");
}
void servo_attach(void)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
servo[i][j].attach(servo_pin[i][j]);
delay(100);
}
}
}
void servo_detach(void)
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
servo[i][j].detach();
delay(100);
}
}
}
/*
- loop function
---------------------------------------------------------------------------*/
void loop()
{
Serial.println("Stand");
stand();
delay(2000);
Serial.println("Step forward");
step_forward(5);
delay(20000);
Serial.println("Step back");
//step_back(5);
//delay(2000);
Serial.println("Turn left");
//turn_left(5);
//delay(2000);
Serial.println("Turn right");
//turn_right(5);
//delay(2000);
Serial.println("Hand wave");
//hand_wave(3);
//delay(2000);
Serial.println("Hand wave");
//hand_shake(3);
//delay(2000);
Serial.println("Sit");
sit();
delay(2000);
}
/*
- sit
- blocking function
---------------------------------------------------------------------------*/
void sit(void)
{
move_speed = stand_seat_speed;
for (int leg = 0; leg < 4; leg++)
{
set_site(leg, KEEP, KEEP, z_boot);
}
wait_all_reach();
}
/*
- stand
- blocking function
---------------------------------------------------------------------------*/
void stand(void)
{
move_speed = stand_seat_speed;
for (int leg = 0; leg < 4; leg++)
{
set_site(leg, KEEP, KEEP, z_default);
}
wait_all_reach();
}
/*
- spot turn to left
- blocking function
- parameter step steps wanted to turn
---------------------------------------------------------------------------*/
void turn_left(unsigned int step)
{
move_speed = spot_turn_speed;
while (step-- > 0)
{
if (site_now[3][1] == y_start)
{
//leg 3&1 move
set_site(3, x_default + x_offset, y_start, z_up);
wait_all_reach();
set_site(0, turn_x1 - x_offset, turn_y1, z_default);
set_site(1, turn_x0 - x_offset, turn_y0, z_default);
set_site(2, turn_x1 + x_offset, turn_y1, z_default);
set_site(3, turn_x0 + x_offset, turn_y0, z_up);
wait_all_reach();
set_site(3, turn_x0 + x_offset, turn_y0, z_default);
wait_all_reach();
set_site(0, turn_x1 + x_offset, turn_y1, z_default);
set_site(1, turn_x0 + x_offset, turn_y0, z_default);
set_site(2, turn_x1 - x_offset, turn_y1, z_default);
set_site(3, turn_x0 - x_offset, turn_y0, z_default);
wait_all_reach();
set_site(1, turn_x0 + x_offset, turn_y0, z_up);
wait_all_reach();
set_site(0, x_default + x_offset, y_start, z_default);
set_site(1, x_default + x_offset, y_start, z_up);
set_site(2, x_default - x_offset, y_start + y_step, z_default);
set_site(3, x_default - x_offset, y_start + y_step, z_default);
wait_all_reach();
set_site(1, x_default + x_offset, y_start, z_default);
wait_all_reach();
}
else
{
//leg 0&2 move
set_site(0, x_default + x_offset, y_start, z_up);
wait_all_reach();
set_site(0, turn_x0 + x_offset, turn_y0, z_up);
set_site(1, turn_x1 + x_offset, turn_y1, z_default);
set_site(2, turn_x0 - x_offset, turn_y0, z_default);
set_site(3, turn_x1 - x_offset, turn_y1, z_default);
wait_all_reach();
set_site(0, turn_x0 + x_offset, turn_y0, z_default);
wait_all_reach();
set_site(0, turn_x0 - x_offset, turn_y0, z_default);
set_site(1, turn_x1 - x_offset, turn_y1, z_default);
set_site(2, turn_x0 + x_offset, turn_y0, z_default);
set_site(3, turn_x1 + x_offset, turn_y1, z_default);
wait_all_reach();
set_site(2, turn_x0 + x_offset, turn_y0, z_up);
wait_all_reach();
set_site(0, x_default - x_offset, y_start + y_step, z_default);
set_site(1, x_default - x_offset, y_start + y_step, z_default);
set_site(2, x_default + x_offset, y_start, z_up);
set_site(3, x_default + x_offset, y_start, z_default);
wait_all_reach();
set_site(2, x_default + x_offset, y_start, z_default);
wait_all_reach();
}
}
}
/*
- spot turn to right
- blocking function
- parameter step steps wanted to turn
---------------------------------------------------------------------------*/
void turn_right(unsigned int step)
{
move_speed = spot_turn_speed;
while (step-- > 0)
{
if (site_now[2][1] == y_start)
{
//leg 2&0 move
set_site(2, x_default + x_offset, y_start, z_up);
wait_all_reach();
set_site(0, turn_x0 - x_offset, turn_y0, z_default);
set_site(1, turn_x1 - x_offset, turn_y1, z_default);
set_site(2, turn_x0 + x_offset, turn_y0, z_up);
set_site(3, turn_x1 + x_offset, turn_y1, z_default);
wait_all_reach();
set_site(2, turn_x0 + x_offset, turn_y0, z_default);
wait_all_reach();
set_site(0, turn_x0 + x_offset, turn_y0, z_default);
set_site(1, turn_x1 + x_offset, turn_y1, z_default);
set_site(2, turn_x0 - x_offset, turn_y0, z_default);
set_site(3, turn_x1 - x_offset, turn_y1, z_default);
wait_all_reach();
set_site(0, turn_x0 + x_offset, turn_y0, z_up);
wait_all_reach();
set_site(0, x_default + x_offset, y_start, z_up);
set_site(1, x_default + x_offset, y_start, z_default);
set_site(2, x_default - x_offset, y_start + y_step, z_default);
set_site(3, x_default - x_offset, y_start + y_step, z_default);
wait_all_reach();
set_site(0, x_default + x_offset, y_start, z_default);
wait_all_reach();
}
else
{
//leg 1&3 move
set_site(1, x_default + x_offset, y_start, z_up);
wait_all_reach();
set_site(0, turn_x1 + x_offset, turn_y1, z_default);
set_site(1, turn_x0 + x_offset, turn_y0, z_up);
set_site(2, turn_x1 - x_offset, turn_y1, z_default);
set_site(3, turn_x0 - x_offset, turn_y0, z_default);
wait_all_reach();
set_site(1, turn_x0 + x_offset, turn_y0, z_default);
wait_all_reach();
set_site(0, turn_x1 - x_offset, turn_y1, z_default);
set_site(1, turn_x0 - x_offset, turn_y0, z_default);
set_site(2, turn_x1 + x_offset, turn_y1, z_default);
set_site(3, turn_x0 + x_offset, turn_y0, z_default);
wait_all_reach();
set_site(3, turn_x0 + x_offset, turn_y0, z_up);
wait_all_reach();
set_site(0, x_default - x_offset, y_start + y_step, z_default);
set_site(1, x_default - x_offset, y_start + y_step, z_default);
set_site(2, x_default + x_offset, y_start, z_default);
set_site(3, x_default + x_offset, y_start, z_up);
wait_all_reach();
set_site(3, x_default + x_offset, y_start, z_default);
wait_all_reach();
}
}
}
/*
- go forward
- blocking function
- parameter step steps wanted to go
---------------------------------------------------------------------------*/
void step_forward(unsigned int step)
{
move_speed = leg_move_speed;
while (step-- > 0)
{
if (site_now[2][1] == y_start)
{
//leg 2&1 move
set_site(2, x_default + x_offset, y_start, z_up);
wait_all_reach();
set_site(2, x_default + x_offset, y_start + 2 * y_step, z_up);
wait_all_reach();
set_site(2, x_default + x_offset, y_start + 2 * y_step, z_default);
wait_all_reach();
move_speed = body_move_speed;
set_site(0, x_default + x_offset, y_start, z_default);
set_site(1, x_default + x_offset, y_start + 2 * y_step, z_default);
set_site(2, x_default - x_offset, y_start + y_step, z_default);
set_site(3, x_default - x_offset, y_start + y_step, z_default);
wait_all_reach();
move_speed = leg_move_speed;
set_site(1, x_default + x_offset, y_start + 2 * y_step, z_up);
wait_all_reach();
set_site(1, x_default + x_offset, y_start, z_up);
wait_all_reach();
set_site(1, x_default + x_offset, y_start, z_default);
wait_all_reach();
}
else
{
//leg 0&3 move
set_site(0, x_default + x_offset, y_start, z_up);
wait_all_reach();
set_site(0, x_default + x_offset, y_start + 2 * y_step, z_up);
wait_all_reach();
set_site(0, x_default + x_offset, y_start + 2 * y_step, z_default);
wait_all_reach();
move_speed = body_move_speed;
set_site(0, x_default - x_offset, y_start + y_step, z_default);
set_site(1, x_default - x_offset, y_start + y_step, z_default);
set_site(2, x_default + x_offset, y_start, z_default);
set_site(3, x_default + x_offset, y_start + 2 * y_step, z_default);
wait_all_reach();
move_speed = leg_move_speed;
set_site(3, x_default + x_offset, y_start + 2 * y_step, z_up);
wait_all_reach();
set_site(3, x_default + x_offset, y_start, z_up);
wait_all_reach();
set_site(3, x_default + x_offset, y_start, z_default);
wait_all_reach();
}
}
}
/*
- go back
- blocking function
- parameter step steps wanted to go
---------------------------------------------------------------------------*/
void step_back(unsigned int step)
{
move_speed = leg_move_speed;
while (step-- > 0)
{
if (site_now[3][1] == y_start)
{
//leg 3&0 move
set_site(3, x_default + x_offset, y_start, z_up);
wait_all_reach();
set_site(3, x_default + x_offset, y_start + 2 * y_step, z_up);
wait_all_reach();
set_site(3, x_default + x_offset, y_start + 2 * y_step, z_default);
wait_all_reach();
move_speed = body_move_speed;
set_site(0, x_default + x_offset, y_start + 2 * y_step, z_default);
set_site(1, x_default + x_offset, y_start, z_default);
set_site(2, x_default - x_offset, y_start + y_step, z_default);
set_site(3, x_default - x_offset, y_start + y_step, z_default);
wait_all_reach();
move_speed = leg_move_speed;
set_site(0, x_default + x_offset, y_start + 2 * y_step, z_up);
wait_all_reach();
set_site(0, x_default + x_offset, y_start, z_up);
wait_all_reach();
set_site(0, x_default + x_offset, y_start, z_default);
wait_all_reach();
}
else
{
//leg 1&2 move
set_site(1, x_default + x_offset, y_start, z_up);
wait_all_reach();
set_site(1, x_default + x_offset, y_start + 2 * y_step, z_up);
wait_all_reach();
set_site(1, x_default + x_offset, y_start + 2 * y_step, z_default);
wait_all_reach();
move_speed = body_move_speed;
set_site(0, x_default - x_offset, y_start + y_step, z_default);
set_site(1, x_default - x_offset, y_start + y_step, z_default);
set_site(2, x_default + x_offset, y_start + 2 * y_step, z_default);
set_site(3, x_default + x_offset, y_start, z_default);
wait_all_reach();
move_speed = leg_move_speed;
set_site(2, x_default + x_offset, y_start + 2 * y_step, z_up);
wait_all_reach();
set_site(2, x_default + x_offset, y_start, z_up);
wait_all_reach();
set_site(2, x_default + x_offset, y_start, z_default);
wait_all_reach();
}
}
}
// add by RegisHsu
void body_left(int i)
{
set_site(0, site_now[0][0] + i, KEEP, KEEP);
set_site(1, site_now[1][0] + i, KEEP, KEEP);
set_site(2, site_now[2][0] - i, KEEP, KEEP);
set_site(3, site_now[3][0] - i, KEEP, KEEP);
wait_all_reach();
}
void body_right(int i)
{
set_site(0, site_now[0][0] - i, KEEP, KEEP);
set_site(1, site_now[1][0] - i, KEEP, KEEP);
set_site(2, site_now[2][0] + i, KEEP, KEEP);
set_site(3, site_now[3][0] + i, KEEP, KEEP);
wait_all_reach();
}
void hand_wave(int i)
{
float x_tmp;
float y_tmp;
float z_tmp;
move_speed = 1;
if (site_now[3][1] == y_start)
{
body_right(15);
x_tmp = site_now[2][0];
y_tmp = site_now[2][1];
z_tmp = site_now[2][2];
move_speed = body_move_speed;
for (int j = 0; j < i; j++)
{
set_site(2, turn_x1, turn_y1, 50);
wait_all_reach();
set_site(2, turn_x0, turn_y0, 50);
wait_all_reach();
}
set_site(2, x_tmp, y_tmp, z_tmp);
wait_all_reach();
move_speed = 1;
body_left(15);
}
else
{
body_left(15);
x_tmp = site_now[0][0];
y_tmp = site_now[0][1];
z_tmp = site_now[0][2];
move_speed = body_move_speed;
for (int j = 0; j < i; j++)
{
set_site(0, turn_x1, turn_y1, 50);
wait_all_reach();
set_site(0, turn_x0, turn_y0, 50);
wait_all_reach();
}
set_site(0, x_tmp, y_tmp, z_tmp);
wait_all_reach();
move_speed = 1;
body_right(15);
}
}
void hand_shake(int i)
{
float x_tmp;
float y_tmp;
float z_tmp;
move_speed = 1;
if (site_now[3][1] == y_start)
{
body_right(15);
x_tmp = site_now[2][0];
y_tmp = site_now[2][1];
z_tmp = site_now[2][2];
move_speed = body_move_speed;
for (int j = 0; j < i; j++)
{
set_site(2, x_default - 30, y_start + 2 * y_step, 55);
wait_all_reach();
set_site(2, x_default - 30, y_start + 2 * y_step, 10);
wait_all_reach();
}
set_site(2, x_tmp, y_tmp, z_tmp);
wait_all_reach();
move_speed = 1;
body_left(15);
}
else
{
body_left(15);
x_tmp = site_now[0][0];
y_tmp = site_now[0][1];
z_tmp = site_now[0][2];
move_speed = body_move_speed;
for (int j = 0; j < i; j++)
{
set_site(0, x_default - 30, y_start + 2 * y_step, 55);
wait_all_reach();
set_site(0, x_default - 30, y_start + 2 * y_step, 10);
wait_all_reach();
}
set_site(0, x_tmp, y_tmp, z_tmp);
wait_all_reach();
move_speed = 1;
body_right(15);
}
}
/*
- microservos service /timer interrupt function/50Hz
- when set site expected,this function move the end point to it in a straight line
- temp_speed[4][3] should be set before set expect site,it make sure the end point
move in a straight line,and decide move speed.
---------------------------------------------------------------------------*/
void servo_service(void)
{
sei();
static float alpha, beta, gamma;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 3; j++)
{
if (abs(site_now[i][j] - site_expect[i][j]) >= abs(temp_speed[i][j]))
site_now[i][j] += temp_speed[i][j];
else
site_now[i][j] = site_expect[i][j];
}
cartesian_to_polar(alpha, beta, gamma, site_now[i][0], site_now[i][1], site_now[i][2]);
polar_to_servo(i, alpha, beta, gamma);
}
rest_counter++;
}
/*
- set one of end points' expect site
- this founction will set temp_speed[4][3] at same time
- non - blocking function
---------------------------------------------------------------------------*/
void set_site(int leg, float x, float y, float z)
{
float length_x = 0, length_y = 0, length_z = 0;
if (x != KEEP)
length_x = x - site_now[leg][0];
if (y != KEEP)
length_y = y - site_now[leg][1];
if (z != KEEP)
length_z = z - site_now[leg][2];
float length = sqrt(pow(length_x, 2) + pow(length_y, 2) + pow(length_z, 2));
temp_speed[leg][0] = length_x / length * move_speed * speed_multiple;
temp_speed[leg][1] = length_y / length * move_speed * speed_multiple;
temp_speed[leg][2] = length_z / length * move_speed * speed_multiple;
if (x != KEEP)
site_expect[leg][0] = x;
if (y != KEEP)
site_expect[leg][1] = y;
if (z != KEEP)
site_expect[leg][2] = z;
}
/*
- wait one of end points move to expect site
- blocking function
---------------------------------------------------------------------------*/
void wait_reach(int leg)
{
while (1)
if (site_now[leg][0] == site_expect[leg][0])
if (site_now[leg][1] == site_expect[leg][1])
if (site_now[leg][2] == site_expect[leg][2])
break;
}
/*
- wait all of end points move to expect site
- blocking function
---------------------------------------------------------------------------*/
void wait_all_reach(void)
{
for (int i = 0; i < 4; i++)
wait_reach(i);
}
/*
- trans site from cartesian to polar
- mathematical model 2/2
---------------------------------------------------------------------------*/
void cartesian_to_polar(volatile float &alpha, volatile float &beta, volatile float &gamma, volatile float x, volatile float y, volatile float z)
{
//calculate w-z degree
float v, w;
w = (x >= 0 ? 1 : -1) * (sqrt(pow(x, 2) + pow(y, 2)));
v = w - length_c;
alpha = atan2(z, v) + acos((pow(length_a, 2) - pow(length_b, 2) + pow(v, 2) + pow(z, 2)) / 2 / length_a / sqrt(pow(v, 2) + pow(z, 2)));
beta = acos((pow(length_a, 2) + pow(length_b, 2) - pow(v, 2) - pow(z, 2)) / 2 / length_a / length_b);
//calculate x-y-z degree
gamma = (w >= 0) ? atan2(y, x) : atan2(-y, -x);
//trans degree pi->180
alpha = alpha / pi * 180;
beta = beta / pi * 180;
gamma = gamma / pi * 180;
}
/*
- trans site from polar to microservos
- mathematical model map to fact
- the errors saved in eeprom will be add
---------------------------------------------------------------------------*/
void polar_to_servo(int leg, float alpha, float beta, float gamma)
{
if (leg == 0)
{
alpha = 90 - alpha;
beta = beta;
gamma += 90;
}
else if (leg == 1)
{
alpha += 90;
beta = 180 - beta;
gamma = 90 - gamma;
}
else if (leg == 2)
{
alpha += 90;
beta = 180 - beta;
gamma = 90 - gamma;
}
else if (leg == 3)
{
alpha = 90 - alpha;
beta = beta;
gamma += 90;
}
servo[leg][0].write(alpha);
servo[leg][1].write(beta);
servo[leg][2].write(gamma);
}
| [
"stdhruv2104@gmail.com"
] | stdhruv2104@gmail.com |
bd9e7750d772ff92120c48bd4630ebcd17d57741 | d90e029661a7f0589f6f16758caba9f48c0f5db0 | /om_bot/src/fake_laserscan.cpp | 91bfaa626bf5c8bd56c5f123e32a4c9b1d4afcdc | [] | no_license | jdios89/ombot | a9a03123ec5c568e4e124c1f1047d88763981991 | 2663a80db99ff61b35dc947aebfdfb2895499285 | refs/heads/master | 2021-06-29T14:52:46.169689 | 2020-11-27T12:14:00 | 2020-11-27T12:14:00 | 143,436,629 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,177 | cpp | #include <ros/ros.h>
#include <sensor_msgs/LaserScan.h>
#include <math.h>
#include <cmath>
int main(int argc, char** argv){
ros::init(argc, argv, "laser_scan_publisher");
ros::NodeHandle n;
ros::Publisher scan_pub = n.advertise<sensor_msgs::LaserScan>("scan_obstacle", 50);
double laser_frequency = 40;
bool last_bool = false;
int count = 100.0;
ros::Rate r(10.0);
while(n.ok()){
int num_readings = 100;
ros::Time scan_time = ros::Time::now();
//Just testing
double x ;
double y ;
bool enabled;
ros::param::param<bool>("/move_base/global_costmap/simple_layer_sub/enabled", enabled, false);
if( enabled != last_bool)
{
last_bool = enabled;
if(enabled) ROS_INFO("Fake scan enabled");
else ROS_INFO("Fake scan disabled");
}
//ROS_INFO("Enabled ");
else
//ROS_INFO("Not enabled");
ros::param::param<double>("/move_base/global_costmap/simple_layer_sub/object_x", x, 0.0);
//ROS_INFO(" GOT x %f", x);
ros::param::param<double>("/move_base/global_costmap/simple_layer_sub/object_y", y, 0.0);
//ROS_INFO(" GOT y %f", y);
//Converting to polar coordinates
double p = sqrt(pow(x,2)+pow(y,2));
double angle = atan2(y,x);
int p_int = abs(p);
if ( p_int > 0) num_readings = num_readings * p_int;
double ranges[num_readings];
double intensities[num_readings];
//generate some fake data for our laser scan
for(unsigned int i = 0; i < num_readings; ++i){
ranges[i] = 99.0;
intensities[i] = 100 + count;
}
//ROS_INFO("Angle: %f", angle);
//ROS_INFO("radius: %f", p);
//Assining the two closest points
int point_1 = 0, point_2 = 0;
double closest_match = 0.0;
double last_closest = 0.0;
for(int i=0; i< num_readings; i++){
double angle_test = -3.14 + i*(6.28/num_readings);
//ROS_INFO("ANgle test %f",std::abs(angle_test - angle));
if( std::abs(angle_test - angle) < std::abs(angle - closest_match)){
last_closest = closest_match;
point_2 = point_1;
closest_match = angle_test;
point_1 = i;
//ROS_INFO("Got to this point");
}
else if( std::abs(angle_test - angle) < std::abs(angle - last_closest)) {
last_closest = angle_test;
point_2 = i; }
}
//populate the LaserScan message
sensor_msgs::LaserScan scan;
scan.header.stamp = scan_time;
scan.header.frame_id = "map";
scan.angle_min = -3.14;
scan.angle_max = 3.14;
scan.angle_increment = 6.28 / num_readings;
scan.time_increment = (1 / laser_frequency) / (num_readings);
scan.range_min = 0.0;
scan.range_max = 100.0;
//ROS_INFO("Point 1 %i", point_1);
//ROS_INFO("Point 2 %i", point_2);
scan.ranges.resize(num_readings);
//scan.intensities.resize(num_readings);
for(unsigned int i = 0; i < num_readings; ++i){
scan.ranges[i] = ranges[i];
if( i == point_1 && enabled) scan.ranges[i] = p;
else if( i==point_2 && enabled) scan.ranges[i] = p;
//scan.intensities[i] = intensities[i];
}
scan_pub.publish(scan);
//++count;
r.sleep();
}
}
| [
"jdios@jdios-Toshiba.(none)"
] | jdios@jdios-Toshiba.(none) |
e2b7b521f04df269f1522d1651ccb225f02f94b5 | aef5b7ad15eef1df8996cb85f9566336b0862390 | /3rdparty/virtual-treeview/Design/VirtualTreesReg.hpp | 9af63716ef6dcb16d112a0554c3e76ec1b01187c | [] | no_license | wyrover/delphi-examples | f14f9d3123de52c0aa196d905edfe9b3dbabca55 | 9cc6dadd11f5f5c2703275ef0f7ca14789b35f7a | refs/heads/master | 2021-05-13T15:54:17.908535 | 2018-01-12T10:04:03 | 2018-01-12T10:04:03 | 116,781,863 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,137 | hpp | // CodeGear C++Builder
// Copyright (c) 1995, 2014 by Embarcadero Technologies, Inc.
// All rights reserved
// (DO NOT EDIT: machine generated header) 'VirtualTreesReg.pas' rev: 27.00 (Windows)
#ifndef VirtualtreesregHPP
#define VirtualtreesregHPP
#pragma delphiheader begin
#pragma option push
#pragma option -w- // All warnings off
#pragma option -Vx // Zero-length empty class member
#pragma pack(push,8)
#include <System.hpp> // Pascal unit
#include <SysInit.hpp> // Pascal unit
#include <Winapi.Windows.hpp> // Pascal unit
#include <System.Classes.hpp> // Pascal unit
#include <DesignIntf.hpp> // Pascal unit
#include <DesignEditors.hpp> // Pascal unit
#include <VCLEditors.hpp> // Pascal unit
#include <PropertyCategories.hpp> // Pascal unit
#include <ColnEdit.hpp> // Pascal unit
#include <VirtualTrees.hpp> // Pascal unit
#include <VTHeaderPopup.hpp> // Pascal unit
//-- user supplied -----------------------------------------------------------
namespace Virtualtreesreg
{
//-- type declarations -------------------------------------------------------
class DELPHICLASS TVirtualTreeEditor;
#pragma pack(push,4)
class PASCALIMPLEMENTATION TVirtualTreeEditor : public Designeditors::TDefaultEditor
{
typedef Designeditors::TDefaultEditor inherited;
public:
virtual void __fastcall Edit(void);
public:
/* TComponentEditor.Create */ inline __fastcall virtual TVirtualTreeEditor(System::Classes::TComponent* AComponent, Designintf::_di_IDesigner ADesigner) : Designeditors::TDefaultEditor(AComponent, ADesigner) { }
public:
/* TObject.Destroy */ inline __fastcall virtual ~TVirtualTreeEditor(void) { }
};
#pragma pack(pop)
//-- var, const, procedure ---------------------------------------------------
extern DELPHI_PACKAGE void __fastcall Register(void);
} /* namespace Virtualtreesreg */
#if !defined(DELPHIHEADER_NO_IMPLICIT_NAMESPACE_USE) && !defined(NO_USING_NAMESPACE_VIRTUALTREESREG)
using namespace Virtualtreesreg;
#endif
#pragma pack(pop)
#pragma option pop
#pragma delphiheader end.
//-- end unit ----------------------------------------------------------------
#endif // VirtualtreesregHPP
| [
"wyrover@gmail.com"
] | wyrover@gmail.com |
5c9f8a51a401c259b0ad64cc3d0b4e329ca89ddd | 6446d4ddc81572c3237e048fe933181e9a468e34 | /Data Structrue/1/1_iteration.cpp | dad5b81f212b63c4c54764e1c7afa745066703d7 | [
"MIT"
] | permissive | YeWenting/BUPT-Homework | afd9cad4af02d6adcf692a7a1626b2a8b94fdfb9 | 624e3931aaa12055f90df8054e89450df4e2128f | refs/heads/master | 2020-07-05T11:29:51.613594 | 2016-11-26T13:41:27 | 2016-11-26T13:41:27 | 74,121,439 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 455 | cpp | //迭代算法求解斐波那契数列中a[10]的值
#include <iostream>
#include <ctime>
#include <iomanip>
#define MaxN 1000
using namespace std;
int main(int argc, char const *argv[])
{
int f[MaxN]={0,1},n=10;
clock_t start=clock();
for (int i=2;i<=n;i++)
f[i]=f[i-1]+f[i-2];
clock_t end=clock();
cout.setf(ios::fixed);
cout<<"f[10]="<<f[n]<<", consuming time is "<<setprecision(6)<<(double)(end-start)/CLOCKS_PER_SEC<<'.'<<endl;
return 0;
} | [
"Wenting_Ye@Outlook.com"
] | Wenting_Ye@Outlook.com |
fe2817e524eb9069a6dd730dd948fa127df31d96 | d4e96aa48ddff651558a3fe2212ebb3a3afe5ac3 | /Modules/Registration/Common/test/itkKullbackLeiblerCompareHistogramImageToImageMetricTest.cxx | c9ffb9e96f7bc943d7db69a147ade0b7bc46e636 | [
"SMLNJ",
"BSD-3-Clause",
"LicenseRef-scancode-free-unknown",
"LicenseRef-scancode-mit-old-style",
"LicenseRef-scancode-other-permissive",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"NTP",
"IJG",
"GPL-1.0-or-later",
"libtiff",
"BSD-4.3TAHOE",
"... | permissive | nalinimsingh/ITK_4D | 18e8929672df64df58a6446f047e6ec04d3c2616 | 95a2eacaeaffe572889832ef0894239f89e3f303 | refs/heads/master | 2020-03-17T18:58:50.953317 | 2018-10-01T20:46:43 | 2018-10-01T21:21:01 | 133,841,430 | 0 | 0 | Apache-2.0 | 2018-05-17T16:34:54 | 2018-05-17T16:34:53 | null | UTF-8 | C++ | false | false | 11,799 | cxx | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
#include "itkKullbackLeiblerCompareHistogramImageToImageMetric.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkTimeProbesCollectorBase.h"
#include "vnl/vnl_sample.h"
#include <iostream>
/**
* This test uses two 2D-Gaussians (standard deviation RegionSize/2)
* One is shifted by 5 pixels from the other.
*
* This test computes the KullbackLeibler information value and derivatives
* for various shift values in (-10,10).
*
*/
int itkKullbackLeiblerCompareHistogramImageToImageMetricTest(int, char* [] )
{
//------------------------------------------------------------
// Create four simple images
//------------------------------------------------------------
//Allocate Images
typedef itk::Image<unsigned char,2> MovingImageType;
typedef itk::Image<unsigned char,2> FixedImageType;
typedef itk::Image<unsigned char,2> TrainingMovingImageType;
typedef itk::Image<unsigned char,2> TrainingFixedImageType;
enum { ImageDimension = MovingImageType::ImageDimension };
MovingImageType::SizeType size = {{100,100}};
MovingImageType::IndexType index = {{0,0}};
MovingImageType::RegionType region;
region.SetSize( size );
region.SetIndex( index );
MovingImageType::Pointer imgMoving = MovingImageType::New();
imgMoving->SetLargestPossibleRegion( region );
imgMoving->SetBufferedRegion( region );
imgMoving->SetRequestedRegion( region );
imgMoving->Allocate();
FixedImageType::Pointer imgFixed = FixedImageType::New();
imgFixed->SetLargestPossibleRegion( region );
imgFixed->SetBufferedRegion( region );
imgFixed->SetRequestedRegion( region );
imgFixed->Allocate();
MovingImageType::Pointer imgTrainingMoving = MovingImageType::New();
imgTrainingMoving->SetLargestPossibleRegion( region );
imgTrainingMoving->SetBufferedRegion( region );
imgTrainingMoving->SetRequestedRegion( region );
imgTrainingMoving->Allocate();
FixedImageType::Pointer imgTrainingFixed = FixedImageType::New();
imgTrainingFixed->SetLargestPossibleRegion( region );
imgTrainingFixed->SetBufferedRegion( region );
imgTrainingFixed->SetRequestedRegion( region );
imgTrainingFixed->Allocate();
// Fill images with a 2D gaussian
typedef itk::ImageRegionIterator<MovingImageType>
ReferenceIteratorType;
typedef itk::ImageRegionIterator<FixedImageType>
TargetIteratorType;
typedef itk::ImageRegionIterator<TrainingMovingImageType>
TrainingReferenceIteratorType;
typedef itk::ImageRegionIterator<TrainingFixedImageType>
TrainingTargetIteratorType;
itk::Point<double,2> center;
center[0] = (double)region.GetSize()[0]/2.0;
center[1] = (double)region.GetSize()[1]/2.0;
const double s = (double)region.GetSize()[0]/2.0;
const double mag = (double)200.0;
const double noisemag = (double)0.0; // ended up yielding best results
itk::Point<double,2> p;
itk::Vector<double,2> d;
// Set the displacement
itk::Vector<double,2> displacement;
displacement[0] = 5;
displacement[1] = 0;
ReferenceIteratorType ri(imgMoving,region);
TargetIteratorType ti(imgFixed,region);
TrainingReferenceIteratorType gri(imgTrainingMoving,region);
TrainingTargetIteratorType gti(imgTrainingFixed,region);
ri.GoToBegin();
while(!ri.IsAtEnd())
{
p[0] = ri.GetIndex()[0];
p[1] = ri.GetIndex()[1];
d = p-center;
d += displacement;
const double x = d[0];
const double y = d[1];
ri.Set( (unsigned char) ( mag * std::exp( - ( x*x + y*y )/(s*s) ) ) );
++ri;
}
ti.GoToBegin();
while(!ti.IsAtEnd())
{
p[0] = ti.GetIndex()[0];
p[1] = ti.GetIndex()[1];
d = p-center;
const double x = d[0];
const double y = d[1];
ti.Set( (unsigned char) ( mag * std::exp( - ( x*x + y*y )/(s*s) ) ) );
++ti;
}
vnl_sample_reseed(2334237);
gri.GoToBegin();
while(!gri.IsAtEnd())
{
p[0] = gri.GetIndex()[0];
p[1] = gri.GetIndex()[1];
d = p-center;
// d += displacement;
const double x = d[0];
const double y = d[1];
gri.Set( (unsigned char) (( mag * std::exp( - ( x*x + y*y )/(s*s) ) ) +
vnl_sample_normal(0.0, noisemag)));
++gri;
}
gti.GoToBegin();
while(!gti.IsAtEnd())
{
p[0] = gti.GetIndex()[0];
p[1] = gti.GetIndex()[1];
d = p-center;
const double x = d[0];
const double y = d[1];
gti.Set( (unsigned char) (( mag * std::exp( - ( x*x + y*y )/(s*s) ) ) +
vnl_sample_normal(0.0, noisemag)));
++gti;
}
//-----------------------------------------------------------
// Set up a transformer
//-----------------------------------------------------------
typedef itk::AffineTransform< double, ImageDimension > TransformType;
typedef TransformType::ParametersType ParametersType;
TransformType::Pointer transformer = TransformType::New();
TransformType::Pointer TrainingTransform = TransformType::New();
transformer->SetIdentity();
TrainingTransform->SetIdentity();
//------------------------------------------------------------
// Set up a interpolator
//------------------------------------------------------------
typedef itk::LinearInterpolateImageFunction< MovingImageType, double >
InterpolatorType;
InterpolatorType::Pointer interpolator = InterpolatorType::New();
InterpolatorType::Pointer TrainingInterpolator = InterpolatorType::New();
//------------------------------------------------------------
// Set up the metric
//------------------------------------------------------------
typedef itk::KullbackLeiblerCompareHistogramImageToImageMetric<
FixedImageType, MovingImageType > MetricType;
MetricType::Pointer metric = MetricType::New();
// connect the interpolator
metric->SetInterpolator( interpolator );
// connect the transform
metric->SetTransform( transformer );
// connect the images to the metric
metric->SetFixedImage( imgFixed );
metric->SetMovingImage( imgMoving );
// set the standard deviations
//metric->SetFixedImageStandardDeviation( 5.0 );
//metric->SetMovingImageStandardDeviation( 5.0 );
// set the number of samples to use
// metric->SetNumberOfSpatialSamples( 100 );
unsigned int nBins = 64;
MetricType::HistogramType::SizeType histSize;
histSize.SetSize(2);
histSize[0] = nBins;
histSize[1] = nBins;
metric->SetHistogramSize(histSize);
// Set scales for derivative calculation.
typedef MetricType::ScalesType ScalesType;
ScalesType scales(transformer->GetNumberOfParameters());
for (unsigned int k = 0; k < transformer ->GetNumberOfParameters(); k++)
scales[k] = 1;
metric->SetDerivativeStepLengthScales(scales);
// set the region over which to compute metric
metric->SetFixedImageRegion( imgFixed->GetBufferedRegion() );
//------------------------------------------------------------
// Set up the metric
//------------------------------------------------------------
metric->SetTrainingInterpolator( TrainingInterpolator );
metric->SetTrainingFixedImage( imgTrainingFixed );
metric->SetTrainingMovingImage( imgTrainingMoving );
metric->SetTrainingFixedImageRegion( imgTrainingFixed->GetBufferedRegion() );
metric->SetTrainingTransform( TrainingTransform );
// initialize the metric before use
metric->Initialize();
//------------------------------------------------------------
// Set up a affine transform parameters
//------------------------------------------------------------
unsigned int numberOfParameters = transformer->GetNumberOfParameters();
ParametersType parameters( numberOfParameters );
// set the parameters to the identity
unsigned long count = 0;
// initialize the linear/matrix part
for( unsigned int row = 0; row < ImageDimension; row++ )
{
for( unsigned int col = 0; col < ImageDimension; col++ )
{
parameters[count] = 0;
if( row == col )
{
parameters[count] = 1;
}
++count;
}
}
// initialize the offset/vector part
for( unsigned int k = 0; k < ImageDimension; k++ )
{
parameters[count] = 0;
++count;
}
//---------------------------------------------------------
// Print out KullbackLeibler values
// for parameters[4] = {-10,10}
//---------------------------------------------------------
MetricType::MeasureType measure;
MetricType::DerivativeType derivative( numberOfParameters );
itk::TimeProbesCollectorBase collector;
collector.Start("Loop");
std::cout << "param[4]\tKullbackLeibler\tdKullbackLeibler/dparam[4]" << std::endl;
for( double trans = -10; trans <= 4; trans += 0.5 )
{
parameters[4] = trans;
metric->GetValueAndDerivative( parameters, measure, derivative );
std::cout << trans << "\t" << measure << "\t" << derivative[4] <<std::endl;
// exercise the other functions
metric->GetValue( parameters );
metric->GetDerivative( parameters, derivative );
}
collector.Stop("Loop");
collector.Report();
//-------------------------------------------------------
// exercise misc member functions
//-------------------------------------------------------
std::cout << "Name of class: " <<
metric->GetNameOfClass() << std::endl;
// std::cout << "No. of samples used = " <<
// metric->GetNumberOfSpatialSamples() << std::endl;
// std::cout << "Fixed image std dev = " <<
// metric->GetFixedImageStandardDeviation() << std::endl;
// std::cout << "Moving image std dev = " <<
// metric->GetMovingImageStandardDeviation() << std::endl;
metric->Print( std::cout );
// itk::KernelFunctionBase::Pointer theKernel = metric->GetKernelFunction();
// metric->SetKernelFunction( theKernel );
// theKernel->Print( std::cout );
// std::cout << "Try causing a exception by making std dev too small";
// std::cout << std::endl;
// metric->SetFixedImageStandardDeviation( 0.001 );
// try
// {
// metric->Initialize();
// std::cout << "Value = " << metric->GetValue( parameters );
// std::cout << std::endl;
// }
// catch(itk::ExceptionObject &err)
// {
// std::cout << "Caught the exception." << std::endl;
// std::cout << err << std::endl;
// }
//
// // reset standard deviation
// metric->SetFixedImageStandardDeviation( 5.0 );
std::cout << "Try causing a exception by making fixed image ITK_NULLPTR";
std::cout << std::endl;
metric->SetFixedImage( ITK_NULLPTR );
try
{
metric->Initialize();
std::cout << "Value = " << metric->GetValue( parameters );
std::cout << std::endl;
}
catch( itk::ExceptionObject &err)
{
std::cout << "Caught the exception." << std::endl;
std::cout << err << std::endl;
}
return EXIT_SUCCESS;
}
| [
"ruizhi@csail.mit.edu"
] | ruizhi@csail.mit.edu |
b88b0437d52146f3c7da826e1af393b249464dfc | 8a45c2bdc405443e3732b08d803541f4773af38c | /Qt5.9C++开发指南/QT5.12Samp2019/chap11Database/samp11_2QueryReadonly/mainwindow.cpp | 1eda6e1ce20f24480766da59c942aebdf26e0550 | [] | no_license | LONGZR007/StudyQt5 | aeae394eb39fab21dc41fa620cdf33cb322ac306 | cc21c29a286e735c47a506b22fe5cf5f526df32e | refs/heads/master | 2020-07-26T23:13:09.351341 | 2019-09-24T13:15:46 | 2019-09-24T13:16:15 | 208,793,451 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,133 | cpp | #include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QFileDialog>
#include <QMessageBox>
void MainWindow::openTable()
{//打开数据表
qryModel=new QSqlQueryModel(this);
qryModel->setQuery("SELECT empNo, Name, Gender, Height, Birthday, Mobile, Province, City, Department, "
" Education, Salary FROM employee ORDER BY empNo");
if (qryModel->lastError().isValid())
{
QMessageBox::critical(this, "错误", "数据表查询错误,错误信息\n"+qryModel->lastError().text(),
QMessageBox::Ok,QMessageBox::NoButton);
return;
}
LabInfo->setText(QString::asprintf("记录条数:%d",qryModel->rowCount()));
qryModel->setHeaderData(0,Qt::Horizontal,"工号");
qryModel->setHeaderData(1,Qt::Horizontal,"姓名");
qryModel->setHeaderData(2,Qt::Horizontal,"性别");
qryModel->setHeaderData(3,Qt::Horizontal,"身高");
qryModel->setHeaderData(4,Qt::Horizontal,"出生日期");
qryModel->setHeaderData(5,Qt::Horizontal,"手机");
qryModel->setHeaderData(6,Qt::Horizontal,"省份");
qryModel->setHeaderData(7,Qt::Horizontal,"城市");
qryModel->setHeaderData(8,Qt::Horizontal,"部门");
qryModel->setHeaderData(9,Qt::Horizontal,"学历");
qryModel->setHeaderData(10,Qt::Horizontal,"工资");
theSelection=new QItemSelectionModel(qryModel);
//选择行变化时
connect(theSelection,SIGNAL(currentRowChanged(QModelIndex,QModelIndex)),
this,SLOT(on_currentRowChanged(QModelIndex,QModelIndex)));
ui->tableView->setModel(qryModel);
ui->tableView->setSelectionModel(theSelection);
// ui->tableView->resizeColumnsToContents();
// ui->tableView->horizontalHeader()->setStretchLastSection(true);
//创建数据映射
dataMapper= new QDataWidgetMapper();
dataMapper->setSubmitPolicy(QDataWidgetMapper::AutoSubmit);
dataMapper->setModel(qryModel);
dataMapper->addMapping(ui->dbSpinEmpNo,0);//"empNo";
dataMapper->addMapping(ui->dbEditName,1);//"Name";
dataMapper->addMapping(ui->dbComboSex,2);//"Gender";
dataMapper->addMapping(ui->dbSpinHeight,3);//"Height";
dataMapper->addMapping(ui->dbEditBirth,4);//"Birthday";
dataMapper->addMapping(ui->dbEditMobile,5);//"Mobile";
dataMapper->addMapping(ui->dbComboProvince,6);//"Province";
dataMapper->addMapping(ui->dbEditCity,7);//"City";
dataMapper->addMapping(ui->dbComboDep,8);//"Department";
dataMapper->addMapping(ui->dbComboEdu,9);//"Education";
dataMapper->addMapping(ui->dbSpinSalary,10);//"Salary";
dataMapper->toFirst();
ui->actOpenDB->setEnabled(false);
}
void MainWindow::refreshTableView()
{//刷新tableView的当前选择行
int index=dataMapper->currentIndex();
QModelIndex curIndex=qryModel->index(index,1);//
theSelection->clearSelection();//清空选择项
theSelection->setCurrentIndex(curIndex,QItemSelectionModel::Select);//设置刚插入的行为当前选择行
}
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
LabInfo=new QLabel("记录条数",this);
LabInfo->setMinimumWidth(200);
ui->statusBar->addWidget(LabInfo);
this->setCentralWidget(ui->splitter);
ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
ui->tableView->setSelectionMode(QAbstractItemView::SingleSelection);
ui->tableView->setAlternatingRowColors(true);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_currentRowChanged(const QModelIndex ¤t, const QModelIndex &previous)
{
Q_UNUSED(previous);
if (!current.isValid())
{
ui->dbLabPhoto->clear();
return;
}
dataMapper->setCurrentModelIndex(current);
bool first=(current.row()==0); //是否首记录
bool last=(current.row()==qryModel->rowCount()-1);//是否尾记录
ui->actRecFirst->setEnabled(!first); //更新使能状态
ui->actRecPrevious->setEnabled(!first);
ui->actRecNext->setEnabled(!last);
ui->actRecLast->setEnabled(!last);
int curRecNo=theSelection->currentIndex().row();
QSqlRecord curRec=qryModel->record(curRecNo); //获取当前记录
int empNo=curRec.value("EmpNo").toInt();
QSqlQuery query; //查询当前empNo的Memo和Photo字段的数据
query.prepare("select EmpNo, Memo, Photo from employee where EmpNo = :ID");
query.bindValue(":ID",empNo);
query.exec();
query.first();
QVariant va=query.value("Photo");//
if (!va.isValid()) //图片字段内容为空
ui->dbLabPhoto->clear();
else
{//显示照片
QByteArray data=va.toByteArray();
QPixmap pic;
pic.loadFromData(data);
ui->dbLabPhoto->setPixmap(pic.scaledToWidth(ui->dbLabPhoto->size().width()));
}
QVariant va2=query.value("Memo");//显示备注
ui->dbEditMemo->setPlainText(va2.toString());
}
void MainWindow::on_actOpenDB_triggered()
{//打开数据库
QString aFile=QFileDialog::getOpenFileName(this,"选择数据库文件","",
"SQL Lite数据库(*.db *.db3)");
if (aFile.isEmpty())
return;
//打开数据库
DB=QSqlDatabase::addDatabase("QSQLITE"); //添加 SQL LITE数据库驱动
DB.setDatabaseName(aFile); //设置数据库名称
// DB.setHostName();
// DB.setUserName();
// DB.setPassword();
if (!DB.open()) //打开数据库
{
QMessageBox::warning(this, "错误", "打开数据库失败",
QMessageBox::Ok,QMessageBox::NoButton);
return;
}
//打开数据表
openTable();
}
void MainWindow::on_actRecFirst_triggered()
{ //首记录
dataMapper->toFirst();
refreshTableView();
}
void MainWindow::on_actRecPrevious_triggered()
{ //前一条记录
dataMapper->toPrevious();
refreshTableView();
}
void MainWindow::on_actRecNext_triggered()
{//后一条记录
dataMapper->toNext();
refreshTableView();
}
void MainWindow::on_actRecLast_triggered()
{//最后一条记录
dataMapper->toLast();
refreshTableView();
}
| [
"1558193230@qq.com"
] | 1558193230@qq.com |
e67cb5a3a841f7bb46f458ad51f63c808926e769 | 0c40e97b69dcd00f0b0b05f249d0fce448320fd8 | /src/txmempool.h | 41bd1000a66507c51e5b7433e356f21a06a59f3e | [
"MIT"
] | permissive | Arhipovladimir/Earthcoin | 9908912df9b10b97512c545b855c3670767039d9 | bc5b5ee538c76e7232e93434aedd8688bae70792 | refs/heads/main | 2023-07-16T05:50:52.755250 | 2021-08-25T09:19:40 | 2021-08-25T09:19:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,111 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2018 The Earthcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef EARTHCOIN_TXMEMPOOL_H
#define EARTHCOIN_TXMEMPOOL_H
#include <memory>
#include <set>
#include <map>
#include <vector>
#include <utility>
#include <string>
#include <amount.h>
#include <coins.h>
#include <indirectmap.h>
#include <policy/feerate.h>
#include <primitives/transaction.h>
#include <sync.h>
#include <random.h>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/sequenced_index.hpp>
#include <boost/signals2/signal.hpp>
class CBlockIndex;
/** Fake height value used in Coin to signify they are only in the memory pool (since 0.8) */
static const uint32_t MEMPOOL_HEIGHT = 0x7FFFFFFF;
struct LockPoints
{
// Will be set to the blockchain height and median time past
// values that would be necessary to satisfy all relative locktime
// constraints (BIP68) of this tx given our view of block chain history
int height;
int64_t time;
// As long as the current chain descends from the highest height block
// containing one of the inputs used in the calculation, then the cached
// values are still valid even after a reorg.
CBlockIndex* maxInputBlock;
LockPoints() : height(0), time(0), maxInputBlock(nullptr) { }
};
class CTxMemPool;
/** \class CTxMemPoolEntry
*
* CTxMemPoolEntry stores data about the corresponding transaction, as well
* as data about all in-mempool transactions that depend on the transaction
* ("descendant" transactions).
*
* When a new entry is added to the mempool, we update the descendant state
* (nCountWithDescendants, nSizeWithDescendants, and nModFeesWithDescendants) for
* all ancestors of the newly added transaction.
*
*/
class CTxMemPoolEntry
{
private:
CTransactionRef tx;
CAmount nFee; //!< Cached to avoid expensive parent-transaction lookups
size_t nTxWeight; //!< ... and avoid recomputing tx weight (also used for GetTxSize())
size_t nUsageSize; //!< ... and total memory usage
int64_t nTime; //!< Local time when entering the mempool
unsigned int entryHeight; //!< Chain height when entering the mempool
bool spendsCoinbase; //!< keep track of transactions that spend a coinbase
int64_t sigOpCost; //!< Total sigop cost
int64_t feeDelta; //!< Used for determining the priority of the transaction for mining in a block
LockPoints lockPoints; //!< Track the height and time at which tx was final
// Information about descendants of this transaction that are in the
// mempool; if we remove this transaction we must remove all of these
// descendants as well.
uint64_t nCountWithDescendants; //!< number of descendant transactions
uint64_t nSizeWithDescendants; //!< ... and size
CAmount nModFeesWithDescendants; //!< ... and total fees (all including us)
// Analogous statistics for ancestor transactions
uint64_t nCountWithAncestors;
uint64_t nSizeWithAncestors;
CAmount nModFeesWithAncestors;
int64_t nSigOpCostWithAncestors;
public:
CTxMemPoolEntry(const CTransactionRef& _tx, const CAmount& _nFee,
int64_t _nTime, unsigned int _entryHeight,
bool spendsCoinbase,
int64_t nSigOpsCost, LockPoints lp);
const CTransaction& GetTx() const { return *this->tx; }
CTransactionRef GetSharedTx() const { return this->tx; }
const CAmount& GetFee() const { return nFee; }
size_t GetTxSize() const;
size_t GetTxWeight() const { return nTxWeight; }
int64_t GetTime() const { return nTime; }
unsigned int GetHeight() const { return entryHeight; }
int64_t GetSigOpCost() const { return sigOpCost; }
int64_t GetModifiedFee() const { return nFee + feeDelta; }
size_t DynamicMemoryUsage() const { return nUsageSize; }
const LockPoints& GetLockPoints() const { return lockPoints; }
// Adjusts the descendant state.
void UpdateDescendantState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount);
// Adjusts the ancestor state
void UpdateAncestorState(int64_t modifySize, CAmount modifyFee, int64_t modifyCount, int64_t modifySigOps);
// Updates the fee delta used for mining priority score, and the
// modified fees with descendants.
void UpdateFeeDelta(int64_t feeDelta);
// Update the LockPoints after a reorg
void UpdateLockPoints(const LockPoints& lp);
uint64_t GetCountWithDescendants() const { return nCountWithDescendants; }
uint64_t GetSizeWithDescendants() const { return nSizeWithDescendants; }
CAmount GetModFeesWithDescendants() const { return nModFeesWithDescendants; }
bool GetSpendsCoinbase() const { return spendsCoinbase; }
uint64_t GetCountWithAncestors() const { return nCountWithAncestors; }
uint64_t GetSizeWithAncestors() const { return nSizeWithAncestors; }
CAmount GetModFeesWithAncestors() const { return nModFeesWithAncestors; }
int64_t GetSigOpCostWithAncestors() const { return nSigOpCostWithAncestors; }
mutable size_t vTxHashesIdx; //!< Index in mempool's vTxHashes
};
// Helpers for modifying CTxMemPool::mapTx, which is a boost multi_index.
struct update_descendant_state
{
update_descendant_state(int64_t _modifySize, CAmount _modifyFee, int64_t _modifyCount) :
modifySize(_modifySize), modifyFee(_modifyFee), modifyCount(_modifyCount)
{}
void operator() (CTxMemPoolEntry &e)
{ e.UpdateDescendantState(modifySize, modifyFee, modifyCount); }
private:
int64_t modifySize;
CAmount modifyFee;
int64_t modifyCount;
};
struct update_ancestor_state
{
update_ancestor_state(int64_t _modifySize, CAmount _modifyFee, int64_t _modifyCount, int64_t _modifySigOpsCost) :
modifySize(_modifySize), modifyFee(_modifyFee), modifyCount(_modifyCount), modifySigOpsCost(_modifySigOpsCost)
{}
void operator() (CTxMemPoolEntry &e)
{ e.UpdateAncestorState(modifySize, modifyFee, modifyCount, modifySigOpsCost); }
private:
int64_t modifySize;
CAmount modifyFee;
int64_t modifyCount;
int64_t modifySigOpsCost;
};
struct update_fee_delta
{
explicit update_fee_delta(int64_t _feeDelta) : feeDelta(_feeDelta) { }
void operator() (CTxMemPoolEntry &e) { e.UpdateFeeDelta(feeDelta); }
private:
int64_t feeDelta;
};
struct update_lock_points
{
explicit update_lock_points(const LockPoints& _lp) : lp(_lp) { }
void operator() (CTxMemPoolEntry &e) { e.UpdateLockPoints(lp); }
private:
const LockPoints& lp;
};
// extracts a transaction hash from CTxMempoolEntry or CTransactionRef
struct mempoolentry_txid
{
typedef uint256 result_type;
result_type operator() (const CTxMemPoolEntry &entry) const
{
return entry.GetTx().GetHash();
}
result_type operator() (const CTransactionRef& tx) const
{
return tx->GetHash();
}
};
/** \class CompareTxMemPoolEntryByDescendantScore
*
* Sort an entry by max(score/size of entry's tx, score/size with all descendants).
*/
class CompareTxMemPoolEntryByDescendantScore
{
public:
bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
{
double a_mod_fee, a_size, b_mod_fee, b_size;
GetModFeeAndSize(a, a_mod_fee, a_size);
GetModFeeAndSize(b, b_mod_fee, b_size);
// Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
double f1 = a_mod_fee * b_size;
double f2 = a_size * b_mod_fee;
if (f1 == f2) {
return a.GetTime() >= b.GetTime();
}
return f1 < f2;
}
// Return the fee/size we're using for sorting this entry.
void GetModFeeAndSize(const CTxMemPoolEntry &a, double &mod_fee, double &size) const
{
// Compare feerate with descendants to feerate of the transaction, and
// return the fee/size for the max.
double f1 = (double)a.GetModifiedFee() * a.GetSizeWithDescendants();
double f2 = (double)a.GetModFeesWithDescendants() * a.GetTxSize();
if (f2 > f1) {
mod_fee = a.GetModFeesWithDescendants();
size = a.GetSizeWithDescendants();
} else {
mod_fee = a.GetModifiedFee();
size = a.GetTxSize();
}
}
};
/** \class CompareTxMemPoolEntryByScore
*
* Sort by feerate of entry (fee/size) in descending order
* This is only used for transaction relay, so we use GetFee()
* instead of GetModifiedFee() to avoid leaking prioritization
* information via the sort order.
*/
class CompareTxMemPoolEntryByScore
{
public:
bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
{
double f1 = (double)a.GetFee() * b.GetTxSize();
double f2 = (double)b.GetFee() * a.GetTxSize();
if (f1 == f2) {
return b.GetTx().GetHash() < a.GetTx().GetHash();
}
return f1 > f2;
}
};
class CompareTxMemPoolEntryByEntryTime
{
public:
bool operator()(const CTxMemPoolEntry& a, const CTxMemPoolEntry& b) const
{
return a.GetTime() < b.GetTime();
}
};
/** \class CompareTxMemPoolEntryByAncestorScore
*
* Sort an entry by min(score/size of entry's tx, score/size with all ancestors).
*/
class CompareTxMemPoolEntryByAncestorFee
{
public:
template<typename T>
bool operator()(const T& a, const T& b) const
{
double a_mod_fee, a_size, b_mod_fee, b_size;
GetModFeeAndSize(a, a_mod_fee, a_size);
GetModFeeAndSize(b, b_mod_fee, b_size);
// Avoid division by rewriting (a/b > c/d) as (a*d > c*b).
double f1 = a_mod_fee * b_size;
double f2 = a_size * b_mod_fee;
if (f1 == f2) {
return a.GetTx().GetHash() < b.GetTx().GetHash();
}
return f1 > f2;
}
// Return the fee/size we're using for sorting this entry.
template <typename T>
void GetModFeeAndSize(const T &a, double &mod_fee, double &size) const
{
// Compare feerate with ancestors to feerate of the transaction, and
// return the fee/size for the min.
double f1 = (double)a.GetModifiedFee() * a.GetSizeWithAncestors();
double f2 = (double)a.GetModFeesWithAncestors() * a.GetTxSize();
if (f1 > f2) {
mod_fee = a.GetModFeesWithAncestors();
size = a.GetSizeWithAncestors();
} else {
mod_fee = a.GetModifiedFee();
size = a.GetTxSize();
}
}
};
// Multi_index tag names
struct descendant_score {};
struct entry_time {};
struct ancestor_score {};
class CBlockPolicyEstimator;
/**
* Information about a mempool transaction.
*/
struct TxMempoolInfo
{
/** The transaction itself */
CTransactionRef tx;
/** Time the transaction entered the mempool. */
int64_t nTime;
/** Feerate of the transaction. */
CFeeRate feeRate;
/** The fee delta. */
int64_t nFeeDelta;
};
/** Reason why a transaction was removed from the mempool,
* this is passed to the notification signal.
*/
enum class MemPoolRemovalReason {
UNKNOWN = 0, //! Manually removed or unknown reason
EXPIRY, //! Expired from mempool
SIZELIMIT, //! Removed in size limiting
REORG, //! Removed for reorganization
BLOCK, //! Removed for block
CONFLICT, //! Removed for conflict with in-block transaction
REPLACED //! Removed for replacement
};
class SaltedTxidHasher
{
private:
/** Salt */
const uint64_t k0, k1;
public:
SaltedTxidHasher();
size_t operator()(const uint256& txid) const {
return SipHashUint256(k0, k1, txid);
}
};
/**
* CTxMemPool stores valid-according-to-the-current-best-chain transactions
* that may be included in the next block.
*
* Transactions are added when they are seen on the network (or created by the
* local node), but not all transactions seen are added to the pool. For
* example, the following new transactions will not be added to the mempool:
* - a transaction which doesn't meet the minimum fee requirements.
* - a new transaction that double-spends an input of a transaction already in
* the pool where the new transaction does not meet the Replace-By-Fee
* requirements as defined in BIP 125.
* - a non-standard transaction.
*
* CTxMemPool::mapTx, and CTxMemPoolEntry bookkeeping:
*
* mapTx is a boost::multi_index that sorts the mempool on 4 criteria:
* - transaction hash
* - descendant feerate [we use max(feerate of tx, feerate of tx with all descendants)]
* - time in mempool
* - ancestor feerate [we use min(feerate of tx, feerate of tx with all unconfirmed ancestors)]
*
* Note: the term "descendant" refers to in-mempool transactions that depend on
* this one, while "ancestor" refers to in-mempool transactions that a given
* transaction depends on.
*
* In order for the feerate sort to remain correct, we must update transactions
* in the mempool when new descendants arrive. To facilitate this, we track
* the set of in-mempool direct parents and direct children in mapLinks. Within
* each CTxMemPoolEntry, we track the size and fees of all descendants.
*
* Usually when a new transaction is added to the mempool, it has no in-mempool
* children (because any such children would be an orphan). So in
* addUnchecked(), we:
* - update a new entry's setMemPoolParents to include all in-mempool parents
* - update the new entry's direct parents to include the new tx as a child
* - update all ancestors of the transaction to include the new tx's size/fee
*
* When a transaction is removed from the mempool, we must:
* - update all in-mempool parents to not track the tx in setMemPoolChildren
* - update all ancestors to not include the tx's size/fees in descendant state
* - update all in-mempool children to not include it as a parent
*
* These happen in UpdateForRemoveFromMempool(). (Note that when removing a
* transaction along with its descendants, we must calculate that set of
* transactions to be removed before doing the removal, or else the mempool can
* be in an inconsistent state where it's impossible to walk the ancestors of
* a transaction.)
*
* In the event of a reorg, the assumption that a newly added tx has no
* in-mempool children is false. In particular, the mempool is in an
* inconsistent state while new transactions are being added, because there may
* be descendant transactions of a tx coming from a disconnected block that are
* unreachable from just looking at transactions in the mempool (the linking
* transactions may also be in the disconnected block, waiting to be added).
* Because of this, there's not much benefit in trying to search for in-mempool
* children in addUnchecked(). Instead, in the special case of transactions
* being added from a disconnected block, we require the caller to clean up the
* state, to account for in-mempool, out-of-block descendants for all the
* in-block transactions by calling UpdateTransactionsFromBlock(). Note that
* until this is called, the mempool state is not consistent, and in particular
* mapLinks may not be correct (and therefore functions like
* CalculateMemPoolAncestors() and CalculateDescendants() that rely
* on them to walk the mempool are not generally safe to use).
*
* Computational limits:
*
* Updating all in-mempool ancestors of a newly added transaction can be slow,
* if no bound exists on how many in-mempool ancestors there may be.
* CalculateMemPoolAncestors() takes configurable limits that are designed to
* prevent these calculations from being too CPU intensive.
*
*/
class CTxMemPool
{
private:
uint32_t nCheckFrequency GUARDED_BY(cs); //!< Value n means that n times in 2^32 we check.
unsigned int nTransactionsUpdated; //!< Used by getblocktemplate to trigger CreateNewBlock() invocation
CBlockPolicyEstimator* minerPolicyEstimator;
uint64_t totalTxSize; //!< sum of all mempool tx's virtual sizes. Differs from serialized tx size since witness data is discounted. Defined in BIP 141.
uint64_t cachedInnerUsage; //!< sum of dynamic memory usage of all the map elements (NOT the maps themselves)
mutable int64_t lastRollingFeeUpdate;
mutable bool blockSinceLastRollingFeeBump;
mutable double rollingMinimumFeeRate; //!< minimum fee to get into the pool, decreases exponentially
void trackPackageRemoved(const CFeeRate& rate) EXCLUSIVE_LOCKS_REQUIRED(cs);
public:
static const int ROLLING_FEE_HALFLIFE = 60 * 60 * 12; // public only for testing
typedef boost::multi_index_container<
CTxMemPoolEntry,
boost::multi_index::indexed_by<
// sorted by txid
boost::multi_index::hashed_unique<mempoolentry_txid, SaltedTxidHasher>,
// sorted by fee rate
boost::multi_index::ordered_non_unique<
boost::multi_index::tag<descendant_score>,
boost::multi_index::identity<CTxMemPoolEntry>,
CompareTxMemPoolEntryByDescendantScore
>,
// sorted by entry time
boost::multi_index::ordered_non_unique<
boost::multi_index::tag<entry_time>,
boost::multi_index::identity<CTxMemPoolEntry>,
CompareTxMemPoolEntryByEntryTime
>,
// sorted by fee rate with ancestors
boost::multi_index::ordered_non_unique<
boost::multi_index::tag<ancestor_score>,
boost::multi_index::identity<CTxMemPoolEntry>,
CompareTxMemPoolEntryByAncestorFee
>
>
> indexed_transaction_set;
mutable CCriticalSection cs;
indexed_transaction_set mapTx GUARDED_BY(cs);
using txiter = indexed_transaction_set::nth_index<0>::type::const_iterator;
std::vector<std::pair<uint256, txiter> > vTxHashes; //!< All tx witness hashes/entries in mapTx, in random order
struct CompareIteratorByHash {
bool operator()(const txiter &a, const txiter &b) const {
return a->GetTx().GetHash() < b->GetTx().GetHash();
}
};
typedef std::set<txiter, CompareIteratorByHash> setEntries;
const setEntries & GetMemPoolParents(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs);
const setEntries & GetMemPoolChildren(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs);
uint64_t CalculateDescendantMaximum(txiter entry) const EXCLUSIVE_LOCKS_REQUIRED(cs);
private:
typedef std::map<txiter, setEntries, CompareIteratorByHash> cacheMap;
struct TxLinks {
setEntries parents;
setEntries children;
};
typedef std::map<txiter, TxLinks, CompareIteratorByHash> txlinksMap;
txlinksMap mapLinks;
void UpdateParent(txiter entry, txiter parent, bool add);
void UpdateChild(txiter entry, txiter child, bool add);
std::vector<indexed_transaction_set::const_iterator> GetSortedDepthAndScore() const EXCLUSIVE_LOCKS_REQUIRED(cs);
public:
indirectmap<COutPoint, const CTransaction*> mapNextTx GUARDED_BY(cs);
std::map<uint256, CAmount> mapDeltas;
/** Create a new CTxMemPool.
*/
explicit CTxMemPool(CBlockPolicyEstimator* estimator = nullptr);
/**
* If sanity-checking is turned on, check makes sure the pool is
* consistent (does not contain two transactions that spend the same inputs,
* all inputs are in the mapNextTx array). If sanity-checking is turned off,
* check does nothing.
*/
void check(const CCoinsViewCache *pcoins) const;
void setSanityCheck(double dFrequency = 1.0) { LOCK(cs); nCheckFrequency = static_cast<uint32_t>(dFrequency * 4294967295.0); }
// addUnchecked must updated state for all ancestors of a given transaction,
// to track size/count of descendant transactions. First version of
// addUnchecked can be used to have it call CalculateMemPoolAncestors(), and
// then invoke the second version.
// Note that addUnchecked is ONLY called from ATMP outside of tests
// and any other callers may break wallet's in-mempool tracking (due to
// lack of CValidationInterface::TransactionAddedToMempool callbacks).
void addUnchecked(const uint256& hash, const CTxMemPoolEntry& entry, bool validFeeEstimate = true) EXCLUSIVE_LOCKS_REQUIRED(cs);
void addUnchecked(const uint256& hash, const CTxMemPoolEntry& entry, setEntries& setAncestors, bool validFeeEstimate = true) EXCLUSIVE_LOCKS_REQUIRED(cs);
void removeRecursive(const CTransaction &tx, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN);
void removeForReorg(const CCoinsViewCache *pcoins, unsigned int nMemPoolHeight, int flags);
void removeConflicts(const CTransaction &tx) EXCLUSIVE_LOCKS_REQUIRED(cs);
void removeForBlock(const std::vector<CTransactionRef>& vtx, unsigned int nBlockHeight);
void clear();
void _clear() EXCLUSIVE_LOCKS_REQUIRED(cs); //lock free
bool CompareDepthAndScore(const uint256& hasha, const uint256& hashb);
void queryHashes(std::vector<uint256>& vtxid);
bool isSpent(const COutPoint& outpoint) const;
unsigned int GetTransactionsUpdated() const;
void AddTransactionsUpdated(unsigned int n);
/**
* Check that none of this transactions inputs are in the mempool, and thus
* the tx is not dependent on other mempool transactions to be included in a block.
*/
bool HasNoInputsOf(const CTransaction& tx) const;
/** Affect CreateNewBlock prioritisation of transactions */
void PrioritiseTransaction(const uint256& hash, const CAmount& nFeeDelta);
void ApplyDelta(const uint256 hash, CAmount &nFeeDelta) const;
void ClearPrioritisation(const uint256 hash);
public:
/** Remove a set of transactions from the mempool.
* If a transaction is in this set, then all in-mempool descendants must
* also be in the set, unless this transaction is being removed for being
* in a block.
* Set updateDescendants to true when removing a tx that was in a block, so
* that any in-mempool descendants have their ancestor state updated.
*/
void RemoveStaged(setEntries &stage, bool updateDescendants, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN) EXCLUSIVE_LOCKS_REQUIRED(cs);
/** When adding transactions from a disconnected block back to the mempool,
* new mempool entries may have children in the mempool (which is generally
* not the case when otherwise adding transactions).
* UpdateTransactionsFromBlock() will find child transactions and update the
* descendant state for each transaction in vHashesToUpdate (excluding any
* child transactions present in vHashesToUpdate, which are already accounted
* for). Note: vHashesToUpdate should be the set of transactions from the
* disconnected block that have been accepted back into the mempool.
*/
void UpdateTransactionsFromBlock(const std::vector<uint256> &vHashesToUpdate);
/** Try to calculate all in-mempool ancestors of entry.
* (these are all calculated including the tx itself)
* limitAncestorCount = max number of ancestors
* limitAncestorSize = max size of ancestors
* limitDescendantCount = max number of descendants any ancestor can have
* limitDescendantSize = max size of descendants any ancestor can have
* errString = populated with error reason if any limits are hit
* fSearchForParents = whether to search a tx's vin for in-mempool parents, or
* look up parents from mapLinks. Must be true for entries not in the mempool
*/
bool CalculateMemPoolAncestors(const CTxMemPoolEntry& entry, setEntries& setAncestors, uint64_t limitAncestorCount, uint64_t limitAncestorSize, uint64_t limitDescendantCount, uint64_t limitDescendantSize, std::string& errString, bool fSearchForParents = true) const EXCLUSIVE_LOCKS_REQUIRED(cs);
/** Populate setDescendants with all in-mempool descendants of hash.
* Assumes that setDescendants includes all in-mempool descendants of anything
* already in it. */
void CalculateDescendants(txiter it, setEntries& setDescendants) const EXCLUSIVE_LOCKS_REQUIRED(cs);
/** The minimum fee to get into the mempool, which may itself not be enough
* for larger-sized transactions.
* The incrementalRelayFee policy variable is used to bound the time it
* takes the fee rate to go back down all the way to 0. When the feerate
* would otherwise be half of this, it is set to 0 instead.
*/
CFeeRate GetMinFee(size_t sizelimit) const;
/** Remove transactions from the mempool until its dynamic size is <= sizelimit.
* pvNoSpendsRemaining, if set, will be populated with the list of outpoints
* which are not in mempool which no longer have any spends in this mempool.
*/
void TrimToSize(size_t sizelimit, std::vector<COutPoint>* pvNoSpendsRemaining=nullptr);
/** Expire all transaction (and their dependencies) in the mempool older than time. Return the number of removed transactions. */
int Expire(int64_t time);
/**
* Calculate the ancestor and descendant count for the given transaction.
* The counts include the transaction itself.
*/
void GetTransactionAncestry(const uint256& txid, size_t& ancestors, size_t& descendants) const;
unsigned long size()
{
LOCK(cs);
return mapTx.size();
}
uint64_t GetTotalTxSize() const
{
LOCK(cs);
return totalTxSize;
}
bool exists(uint256 hash) const
{
LOCK(cs);
return (mapTx.count(hash) != 0);
}
CTransactionRef get(const uint256& hash) const;
TxMempoolInfo info(const uint256& hash) const;
std::vector<TxMempoolInfo> infoAll() const;
size_t DynamicMemoryUsage() const;
boost::signals2::signal<void (CTransactionRef)> NotifyEntryAdded;
boost::signals2::signal<void (CTransactionRef, MemPoolRemovalReason)> NotifyEntryRemoved;
private:
/** UpdateForDescendants is used by UpdateTransactionsFromBlock to update
* the descendants for a single transaction that has been added to the
* mempool but may have child transactions in the mempool, eg during a
* chain reorg. setExclude is the set of descendant transactions in the
* mempool that must not be accounted for (because any descendants in
* setExclude were added to the mempool after the transaction being
* updated and hence their state is already reflected in the parent
* state).
*
* cachedDescendants will be updated with the descendants of the transaction
* being updated, so that future invocations don't need to walk the
* same transaction again, if encountered in another transaction chain.
*/
void UpdateForDescendants(txiter updateIt,
cacheMap &cachedDescendants,
const std::set<uint256> &setExclude) EXCLUSIVE_LOCKS_REQUIRED(cs);
/** Update ancestors of hash to add/remove it as a descendant transaction. */
void UpdateAncestorsOf(bool add, txiter hash, setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs);
/** Set ancestor state for an entry */
void UpdateEntryForAncestors(txiter it, const setEntries &setAncestors) EXCLUSIVE_LOCKS_REQUIRED(cs);
/** For each transaction being removed, update ancestors and any direct children.
* If updateDescendants is true, then also update in-mempool descendants'
* ancestor state. */
void UpdateForRemoveFromMempool(const setEntries &entriesToRemove, bool updateDescendants) EXCLUSIVE_LOCKS_REQUIRED(cs);
/** Sever link between specified transaction and direct children. */
void UpdateChildrenForRemoval(txiter entry) EXCLUSIVE_LOCKS_REQUIRED(cs);
/** Before calling removeUnchecked for a given transaction,
* UpdateForRemoveFromMempool must be called on the entire (dependent) set
* of transactions being removed at the same time. We use each
* CTxMemPoolEntry's setMemPoolParents in order to walk ancestors of a
* given transaction that is removed, so we can't remove intermediate
* transactions in a chain before we've updated all the state for the
* removal.
*/
void removeUnchecked(txiter entry, MemPoolRemovalReason reason = MemPoolRemovalReason::UNKNOWN) EXCLUSIVE_LOCKS_REQUIRED(cs);
};
/**
* CCoinsView that brings transactions from a mempool into view.
* It does not check for spendings by memory pool transactions.
* Instead, it provides access to all Coins which are either unspent in the
* base CCoinsView, or are outputs from any mempool transaction!
* This allows transaction replacement to work as expected, as you want to
* have all inputs "available" to check signatures, and any cycles in the
* dependency graph are checked directly in AcceptToMemoryPool.
* It also allows you to sign a double-spend directly in signrawtransaction,
* as long as the conflicting transaction is not yet confirmed.
*/
class CCoinsViewMemPool : public CCoinsViewBacked
{
protected:
const CTxMemPool& mempool;
public:
CCoinsViewMemPool(CCoinsView* baseIn, const CTxMemPool& mempoolIn);
bool GetCoin(const COutPoint &outpoint, Coin &coin) const override;
};
/**
* DisconnectedBlockTransactions
* During the reorg, it's desirable to re-add previously confirmed transactions
* to the mempool, so that anything not re-confirmed in the new chain is
* available to be mined. However, it's more efficient to wait until the reorg
* is complete and process all still-unconfirmed transactions at that time,
* since we expect most confirmed transactions to (typically) still be
* confirmed in the new chain, and re-accepting to the memory pool is expensive
* (and therefore better to not do in the middle of reorg-processing).
* Instead, store the disconnected transactions (in order!) as we go, remove any
* that are included in blocks in the new chain, and then process the remaining
* still-unconfirmed transactions at the end.
*/
// multi_index tag names
struct txid_index {};
struct insertion_order {};
struct DisconnectedBlockTransactions {
typedef boost::multi_index_container<
CTransactionRef,
boost::multi_index::indexed_by<
// sorted by txid
boost::multi_index::hashed_unique<
boost::multi_index::tag<txid_index>,
mempoolentry_txid,
SaltedTxidHasher
>,
// sorted by order in the blockchain
boost::multi_index::sequenced<
boost::multi_index::tag<insertion_order>
>
>
> indexed_disconnected_transactions;
// It's almost certainly a logic bug if we don't clear out queuedTx before
// destruction, as we add to it while disconnecting blocks, and then we
// need to re-process remaining transactions to ensure mempool consistency.
// For now, assert() that we've emptied out this object on destruction.
// This assert() can always be removed if the reorg-processing code were
// to be refactored such that this assumption is no longer true (for
// instance if there was some other way we cleaned up the mempool after a
// reorg, besides draining this object).
~DisconnectedBlockTransactions() { assert(queuedTx.empty()); }
indexed_disconnected_transactions queuedTx;
uint64_t cachedInnerUsage = 0;
// Estimate the overhead of queuedTx to be 6 pointers + an allocation, as
// no exact formula for boost::multi_index_contained is implemented.
size_t DynamicMemoryUsage() const {
return memusage::MallocUsage(sizeof(CTransactionRef) + 6 * sizeof(void*)) * queuedTx.size() + cachedInnerUsage;
}
void addTransaction(const CTransactionRef& tx)
{
queuedTx.insert(tx);
cachedInnerUsage += RecursiveDynamicUsage(tx);
}
// Remove entries based on txid_index, and update memory usage.
void removeForBlock(const std::vector<CTransactionRef>& vtx)
{
// Short-circuit in the common case of a block being added to the tip
if (queuedTx.empty()) {
return;
}
for (auto const &tx : vtx) {
auto it = queuedTx.find(tx->GetHash());
if (it != queuedTx.end()) {
cachedInnerUsage -= RecursiveDynamicUsage(*it);
queuedTx.erase(it);
}
}
}
// Remove an entry by insertion_order index, and update memory usage.
void removeEntry(indexed_disconnected_transactions::index<insertion_order>::type::iterator entry)
{
cachedInnerUsage -= RecursiveDynamicUsage(*entry);
queuedTx.get<insertion_order>().erase(entry);
}
void clear()
{
cachedInnerUsage = 0;
queuedTx.clear();
}
};
#endif // EARTHCOIN_TXMEMPOOL_H
| [
"mail@deveac.com"
] | mail@deveac.com |
2c52667989c63260830c7a8db0a3404d1a5dc55f | 0526f69979d25a4094f8f5c09f8e5d40d2b47152 | /280715/operator_io.cc | 1db4e478c69f61fc9b154c4899cd3fc92c64da46 | [] | no_license | FightingJohn/c-learning | b46807f7b862a304493d2f66c445251ecce3d578 | 309c2a9ae5048db3b4eb7c4d4526fe24151dc35e | refs/heads/master | 2021-01-16T21:23:29.232125 | 2015-08-18T11:51:06 | 2015-08-18T11:51:06 | 40,962,546 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 484 | cc | #include<iostream>
using namespace std;
class Complex
{
friend ostream & operator <<(ostream &os, const Complex &rhs);
public:
Complex(double dreal = 0.0, double dimag = 0.0):
dreal_(dreal),dimag_(dimag){}
void disp()
{
cout<<dreal_<<"+"<<"*i"<<dimag_<<endl;
}
double dreal_;
double dimag_;
};
ostream & operator <<(ostream &os, const Complex &rhs)
{
cout<<rhs.dreal_<<"+"<<rhs.dimag_<<"*i"<<endl;
return os;
}
int main(void)
{
Complex c1(2,3);
cout<< c1 ;
}
| [
"1017283166@qq.com"
] | 1017283166@qq.com |
5a89342de3933dadc23656a7f1270f872f4cf026 | bd1fea86d862456a2ec9f56d57f8948456d55ee6 | /000/097/625/CWE36_Absolute_Path_Traversal__wchar_t_file_open_34.cpp | 73dfca009a90feb84a5ebc7bee3384ada1d2e988 | [] | no_license | CU-0xff/juliet-cpp | d62b8485104d8a9160f29213368324c946f38274 | d8586a217bc94cbcfeeec5d39b12d02e9c6045a2 | refs/heads/master | 2021-03-07T15:44:19.446957 | 2020-03-10T12:45:40 | 2020-03-10T12:45:40 | 246,275,244 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,944 | cpp | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE36_Absolute_Path_Traversal__wchar_t_file_open_34.cpp
Label Definition File: CWE36_Absolute_Path_Traversal.label.xml
Template File: sources-sink-34.tmpl.cpp
*/
/*
* @description
* CWE: 36 Absolute Path Traversal
* BadSource: file Read input from a file
* GoodSource: Full path and file name
* Sinks: open
* BadSink : Open the file named in data using open()
* Flow Variant: 34 Data flow: use of a union containing two methods of accessing the same data (within the same function)
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#ifdef _WIN32
#define FILENAME "C:\\temp\\file.txt"
#else
#define FILENAME "/tmp/file.txt"
#endif
#ifdef _WIN32
#define OPEN _wopen
#define CLOSE _close
#else
#include <unistd.h>
#define OPEN open
#define CLOSE close
#endif
namespace CWE36_Absolute_Path_Traversal__wchar_t_file_open_34
{
typedef union
{
wchar_t * unionFirst;
wchar_t * unionSecond;
} unionType;
#ifndef OMITBAD
void bad()
{
wchar_t * data;
unionType myUnion;
wchar_t dataBuffer[FILENAME_MAX] = L"";
data = dataBuffer;
{
/* Read input from a file */
size_t dataLen = wcslen(data);
FILE * pFile;
/* if there is room in data, attempt to read the input from a file */
if (FILENAME_MAX-dataLen > 1)
{
pFile = fopen(FILENAME, "r");
if (pFile != NULL)
{
/* POTENTIAL FLAW: Read data from a file */
if (fgetws(data+dataLen, (int)(FILENAME_MAX-dataLen), pFile) == NULL)
{
printLine("fgetws() failed");
/* Restore NUL terminator if fgetws fails */
data[dataLen] = L'\0';
}
fclose(pFile);
}
}
}
myUnion.unionFirst = data;
{
wchar_t * data = myUnion.unionSecond;
{
int fileDesc;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
if (fileDesc != -1)
{
CLOSE(fileDesc);
}
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2B()
{
wchar_t * data;
unionType myUnion;
wchar_t dataBuffer[FILENAME_MAX] = L"";
data = dataBuffer;
#ifdef _WIN32
/* FIX: Use a fixed, full path and file name */
wcscat(data, L"c:\\temp\\file.txt");
#else
/* FIX: Use a fixed, full path and file name */
wcscat(data, L"/tmp/file.txt");
#endif
myUnion.unionFirst = data;
{
wchar_t * data = myUnion.unionSecond;
{
int fileDesc;
/* POTENTIAL FLAW: Possibly opening a file without validating the file name or path */
fileDesc = OPEN(data, O_RDWR|O_CREAT, S_IREAD|S_IWRITE);
if (fileDesc != -1)
{
CLOSE(fileDesc);
}
}
}
}
void good()
{
goodG2B();
}
#endif /* OMITGOOD */
} /* close namespace */
/* Below is the main(). It is only used when building this testcase on
its own for testing or for building a binary to use in testing binary
analysis tools. It is not used when compiling all the testcases as one
application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN
using namespace CWE36_Absolute_Path_Traversal__wchar_t_file_open_34; /* 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
| [
"frank@fischer.com.mt"
] | frank@fischer.com.mt |
1eaeea3726688f05dd4c9bee600573c1d135bc00 | c21c8cba94f4f73aa23de98e555ef77bcab494f0 | /GeeksforGeeks/Random-problems/given an array rotate the array by some fixed rotation with no extra space.cpp | d9c8804b5f607467840233f2f44dcc7d73674df6 | [] | no_license | hoatd/Ds-Algos- | fc3ed0c8c1b285fb558f53eeeaea2632e0ed03ae | 1e74995433685f32ce75a036cd82460605024c49 | refs/heads/master | 2023-03-19T05:48:42.595330 | 2019-04-29T06:20:43 | 2019-04-29T06:20:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,326 | cpp | // AUTHOR: SHIV ANAND
// LANGUAGE: CPP
// TIME COMPLEXITY : O(n)
// SPACE COMPLEXITY : O(1)
/** juggling algorithm for array rotation without extra space **/
#include<bits/stdc++.h>
#define si(x) scanf("%d",&x)
#define slli(x) scanf("%lld",&x)
using namespace std;
int ar[102];
int n;
template<typename T>
void read_(T &x)
{
char r;
int start=0,neg=0;
x=0;
while(1)
{
r=getchar();
if((r-'0'<0 || r-'0'>9) && r!='-' && !start)
{continue;}
if((r-'0'<0 || r-'0'>9) && r!='-' && start)
{break;}
if(start)
x*=10;
start=1;
if(r=='-')
neg=1;
else x += r-'0';
}
if(neg)
x*=-1;
}
int gcd(int a,int b)
{
if(b == 0)
{
return a;
}
return gcd(b, a%b);
}
void jugguling(int d)
{
int i,j,k,tmp;
for(int i=0; i<gcd(d,n); i++)
{
tmp = ar[i];
j = i;
while(1)
{
k = j+d;
if(k >= n)
{
k -= n;
}
if(k == i)
{
break;
}
ar[j] = ar[k];
j = k;
}
ar[j] = tmp;
}
}
int main()
{
read_(n);
for(int i=0; i<n; i++)
{
read_(ar[i]);
}
int d;
read_(d);
jugguling(d);
for(int i=0; i<n; i++)
{
cout<<ar[i]<<" ";
}
return 0;
}
| [
"shivakp2111@gmail.com"
] | shivakp2111@gmail.com |
922f060665e0d7a8d5d9af3cdff74c33a4539fee | a332dc677d03d832c7eba640478f95afce40fb4f | /src/DS/Sort/Insert/DirectInsertSort/DirectInsertSort.cpp | fb0e0fe9c0eebf8e32458c013259884620471276 | [] | no_license | fenglunli1997/DataStructures | e8f91903290869a26503b1e9e212733737949233 | c6440ad406d5d60794e7ab637734fd4994dbca3c | refs/heads/master | 2022-11-15T14:09:43.248520 | 2020-07-03T06:50:42 | 2020-07-03T06:50:42 | 268,034,427 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 754 | cpp | //
// Created by fll on 2020/7/2.
//
#include "DirectInsertSort.h"
void DirectInsertSort::sort(int *array) {
int l = getLength();
for (int i = 1; i < l; ++i) {//未排序序列,依次插入到前面,array[i]是当前比较的数
int temp = array[i];
for (int j = i; j > 0; --j) {//有序序列,依次被插入
//排序
array[j] = array[j-1];//后移一位
if (temp > array[j]) {
array[j] = temp;
break;
}
if (j == 1) {
array[0] = temp;
break;
}
}
}
setResult(array);
}
DirectInsertSort::DirectInsertSort(int *array, int length) : Sort(array, length) {
sort(array);
}
| [
"fenglunli1997@gmail.com"
] | fenglunli1997@gmail.com |
8a75ba0124751dc7697f2f3370ef0a386ce3d70c | 76ce016fb54e0947885304ecee05eaa6d2f95356 | /ProjectScript/ProjectScript/FloatVar.h | 68224360f031b8d60bb508467aa9177d07347584 | [] | no_license | raysloks/ProjectRPG | d8cdfd7e40744597cc14efa83f40e4f4add78e76 | 035f700889ce4e60978d072a7eb395fad2fd2359 | refs/heads/master | 2021-03-22T02:15:12.456332 | 2019-07-08T12:48:20 | 2019-07-08T12:48:20 | 69,451,090 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 349 | h | #include "Variable.h"
#ifndef FLOAT_VAR_H
#define FLOAT_VAR_H
class FloatVar :
public Variable
{
public:
FloatVar(float f = 0.0f);
FloatVar(const FloatVar& f);
~FloatVar(void);
Variable * clone(void) const;
std::shared_ptr<Variable> operate(const std::string& op, std::shared_ptr<Variable> rhs, bool allocate = true);
float f;
};
#endif | [
"raysloks@gmail.com"
] | raysloks@gmail.com |
0c374866046ddca34cc81e6ad04a84b597cb50b1 | 6efbe48bcd65c58b8a76bfccfa73f4965f1dda10 | /window.cpp | 8b33e9e5f6f939e1676f137d3b80ead954d27dd0 | [] | no_license | Serhiyko/Translator | 4ce37b5974c26ba315668950a1721f10261c6d95 | b2320af539ff1131aa65f0a0264be8760c53f979 | refs/heads/master | 2021-01-23T16:31:13.175098 | 2017-06-06T18:41:25 | 2017-06-06T18:41:25 | 93,301,914 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,338 | cpp | #include "window.h"
#include <QRegExp>
#include <QMessageBox>
Window::Window(QWidget *parent) : QDialog(parent)
{
_label = new QLabel;
_line = new QLineEdit;
_buttonOk = new QPushButton("Ok");
_buttonUpdate = new QPushButton("Update");
QHBoxLayout* layout = new QHBoxLayout;
layout->addWidget(_label);
layout->addWidget(_line);
QHBoxLayout* layout1 = new QHBoxLayout;
layout1->addWidget(_buttonOk);
layout1->addWidget(_buttonUpdate);
QVBoxLayout *vlayout = new QVBoxLayout;
vlayout->addLayout(layout);
vlayout->addLayout(layout1);
connect(_buttonUpdate, SIGNAL(clicked()), this, SLOT(setVariable()));
connect(_buttonOk, SIGNAL(clicked(bool)), this, SLOT(close()));
setLayout(vlayout);
}
void Window::setLabelName(const QString& name)
{
_label->setText(name);
}
QString Window::getVariable()
{
_line->clear();
return _varData;
}
void Window::setVariable()
{
QRegExp tmp("\\d*\\.?\\d+$");
if(_line->text() != "")
{
if(tmp.exactMatch(_line->text()))
{
_varData = _line->text();
}
else
{
QMessageBox msg;
msg.setText("Invalid input variable, reenter variable please!");
msg.exec();
}
}
}
| [
"noreply@github.com"
] | noreply@github.com |
339b123319c2f795d9be28553127796715b59d26 | abbd7d47e42607cb4946ffbe356bed213cae0496 | /BombermanGame/IntroState.cpp | d912fa3770cb8e698cdf95370d9df69c31ccaaff | [] | no_license | aagyo/Enhanced-DynaBlaster-Bomberman | af0f802b3fcc13e0fcc4d695299bc546c0f25529 | 78c0e27eb32c779a7cafd8e2d8a3756cb38062d3 | refs/heads/master | 2022-08-03T08:26:12.254772 | 2020-05-28T19:58:48 | 2020-05-28T19:58:48 | 264,981,412 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,730 | cpp | #include "IntroState.h"
#include "LevelState.h"
#include "StateMachine.h"
#include <memory>
#include <SFML/Window/Keyboard.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Graphics/View.hpp>
#include "Logger.h"
IntroState::IntroState(StateMachine& machine, sf::RenderWindow& window, bool replace)
: State(machine, window, replace)
{
window.setKeyRepeatEnabled(false);
m_bgTexture.loadFromFile("../_external/states/introstate.png");
m_bg.setTexture(m_bgTexture, true);
m_soundBuffer = new sf::SoundBuffer;
m_soundBuffer->loadFromFile("../_external/audio/intro.flac");
globalLogger.LogData("Intro State", LogSeverity::info);
m_sound = new sf::Sound;
m_sound->setBuffer(*m_soundBuffer);
m_sound->play();
}
void IntroState::Update()
{
sf::Event event;
bool pressed = false;
while (m_window.pollEvent(event))
{
if (event.type == sf::Event::Resized)
{
const auto windowWidth = static_cast<float>(event.size.width);
const auto windowHeight = static_cast<float>(event.size.height);
const float newWidth = windowHeight;
const float newHeight = windowWidth;
const float offset_width = (windowWidth - newWidth) / 2.0f;
const float offset_height = (windowHeight - newHeight) / 2.0f;
sf::View view = m_window.getDefaultView();
if (windowWidth < m_windowSize || windowHeight < m_windowSize)
{
view.setViewport(sf::FloatRect(0.f, 0.f, m_windowSize, m_windowSize));
m_window.setSize(sf::Vector2u(static_cast<uint16_t>(m_windowSize), static_cast<uint16_t>(m_windowSize)));
m_window.setPosition(sf::Vector2i(400, 200));
}
else
{
if (windowWidth >= windowHeight)
{
view.setViewport(sf::FloatRect(offset_width / windowWidth, 0.0, newWidth / windowWidth, 1.0));
}
else
{
view.setViewport(sf::FloatRect(0.0, offset_height / windowHeight, 1.0, newHeight / windowHeight));
}
}
m_window.setView(view);
}
switch (event.type)
{
case sf::Event::Closed:
m_machine.Quit();
break;
case sf::Event::KeyPressed:
{
switch (event.key.code)
{
case sf::Keyboard::Enter:
if (pressed == false)
{
pressed = true;
DeleteMusicBuffer();
m_next = StateMachine::Build<LevelState>(m_machine, m_window, true);
}
break;
case sf::Keyboard::Escape:
globalLogger.LogData("**************GAME CLOSED****************");
m_machine.Quit();
break;
default:
break;
}
break;
}
default:
break;
}
}
}
void IntroState::Pause()
{
// empty
}
void IntroState::Resume()
{
// empty
}
void IntroState::DeleteMusicBuffer()
{
m_sound->~Sound();
m_soundBuffer->~SoundBuffer();
}
void IntroState::Draw()
{
m_window.clear();
m_window.draw(m_bg);
m_window.display();
} | [
"oyga.icl@gmail.com"
] | oyga.icl@gmail.com |
4ba18450e73f20547cee0e5e34710c632b71c6ba | b77843b33ce84ccfc6bc0e5be6e07f3ea2bc7812 | /common/display/physicaldisplaymanager.h | 08528f552b1ed7e14eed7898d51e211c8aff6070 | [] | no_license | kalyankondapally/temp | 0ed41354d37479601be978de97334368c146bc84 | 8e680d49d246ed8e5a02f6b5573484536efbebc0 | refs/heads/master | 2021-01-21T18:05:14.124442 | 2017-05-26T03:39:14 | 2017-05-26T03:39:14 | 92,009,032 | 0 | 3 | null | 2017-05-26T03:24:17 | 2017-05-22T03:49:19 | C++ | UTF-8 | C++ | false | false | 9,999 | h | /*
// Copyright (c) 2017 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#ifndef INTEL_UFO_HWC_PHYSICAL_DISPLAY_MANAGER_H
#define INTEL_UFO_HWC_PHYSICAL_DISPLAY_MANAGER_H
#include "abstractdisplaymanager.h"
#include "abstractphysicaldisplay.h"
#include "PlaneComposition.h"
#include "Timer.h"
#include "option.h"
namespace hwcomposer {
class Content;
class DisplayCaps;
class CompositionManager;
class InputAnalyzer;
class PhysicalDisplayManager : public AbstractDisplayManager
{
public:
PhysicalDisplayManager( Hwc& hwc, CompositionManager& compositionManager );
virtual ~PhysicalDisplayManager();
// Register a display.
// Returns an index or INVALID_DISPLAY_ID if no space.
uint32_t registerDisplay(AbstractPhysicalDisplay* pDisplay);
// Unregister a display.
void unregisterDisplay( AbstractPhysicalDisplay* pDisplay );
// Get count of physical displays.
uint32_t getNumPhysicalDisplays( void ) { return mPhysicalDisplays; }
// Get physical display.
AbstractPhysicalDisplay* getPhysicalDisplay( uint32_t phyIndex );
// Called each frame onPrepare().
int onPrepare(const Content& ref);
// Called each frame onSet().
int onSet(const Content& ref);
// Set a remapping.
// An upstream logical display manager can use this to remap its indices into physical
// indices for display content that is just passthrough.
void setRemap( uint32_t displayIndex, uint32_t physicalIndex );
// Reset remapping (no remapping).
void resetRemap( void );
// Get remapped display index
uint32_t remap( uint32_t displayIndex );
// Set display contents in SF display order.
void setSFDisplayOrder( bool bSFOrder ) { mbSFDisplayOrder = bSFOrder; }
// Are display contents in SF display order.
bool getSFDisplayOrder( void ) const { return mbSFDisplayOrder; }
// Enable or disable vsyncs for a physical display.
void vSyncEnable( uint32_t phyIndex, bool bEnableVSync );
// Modify the banking state for a physical display.
// Returns OK (0) if the requested blanking state is applied on return, negative on error.
// This will block for change to complete before returning for BLANK_SURFACEFLINGER source.
int blank( uint32_t phyIndex, bool bEnableBlank, BlankSource source );
// *************************************************************************
// This class implements the AbstractDisplayManager API.
// *************************************************************************
void open( void );
void onVSyncEnable( uint32_t sfIndex, bool bEnableVSync );
int onBlank( uint32_t sfIndex, bool bEnableBlank, BlankSource source );
void flush( uint32_t frameIndex = 0, nsecs_t timeoutNs = AbstractDisplay::mTimeoutForFlush );
void endOfFrame( void );
String8 dump( void );
String8 dumpDetail( void );
// Physical displays should call notifyPhysical*** to notify physical display changes.
// Notifications will be forwarded to the set receiver (Hwc or logical display manager).
void setNotificationReceiver( PhysicalDisplayNotificationReceiver* pNotificationReceiver );
void notifyPhysicalAvailable( AbstractPhysicalDisplay* pPhysical);
void notifyPhysicalUnavailable( AbstractPhysicalDisplay* pPhysical );
void notifyPhysicalChangeSize( AbstractPhysicalDisplay* pPhysical );
void notifyPhysicalVSync( AbstractPhysicalDisplay* pPhysical, nsecs_t timeStampNs );
// Notify plug change has completed, so that make sure plug event can be
// fully serialized and synchronized.
void notifyPlugChangeCompleted( void );
private:
Hwc& mHwc;
CompositionManager& mCompositionManager;
PhysicalDisplayNotificationReceiver* mpDisplayNotificationReceiver;
bool mbSFDisplayOrder:1;
// This class describes the current state of a physical display
class DisplayState
{
public:
DisplayState();
~DisplayState();
void setIndex( uint32_t index )
{
INTEL_UFO_HWC_ASSERT_MUTEX_NOT_HELD( mLock );
Mutex::Autolock _l( mLock );
mIndex= index;
}
bool isAttached(void) const
{
INTEL_UFO_HWC_ASSERT_MUTEX_NOT_HELD( mLock );
Mutex::Autolock _l( mLock );
return mpHwDisplay != NULL;
}
uint32_t getBlank( void ) const
{
INTEL_UFO_HWC_ASSERT_MUTEX_NOT_HELD( mLock );
Mutex::Autolock _l( mLock );
return mBlankMask;
}
bool isBlanked( void ) const
{
INTEL_UFO_HWC_ASSERT_MUTEX_NOT_HELD( mLock );
Mutex::Autolock _l( mLock );
return ( mBlankMask != 0 );
}
Content::Display& getContent( void )
{
INTEL_UFO_HWC_ASSERT_MUTEX_NOT_HELD( mLock );
Mutex::Autolock _l( mLock );
return mContent;
}
AbstractPhysicalDisplay* getHwDisplay( void ) const
{
INTEL_UFO_HWC_ASSERT_MUTEX_NOT_HELD( mLock );
Mutex::Autolock _l( mLock );
return mpHwDisplay;
}
PlaneComposition& getPlaneComposition( void )
{
INTEL_UFO_HWC_ASSERT_MUTEX_NOT_HELD( mLock );
Mutex::Autolock _l( mLock );
return mPlaneComposition;
}
void setHwDisplay( AbstractPhysicalDisplay* pDisp );
void onVSyncEnable( bool bEnableVSync );
int onBlank(bool bEnableBlank, BlankSource source, bool& bChange);
void setFrameIndex( uint32_t frameIndex )
{
INTEL_UFO_HWC_ASSERT_MUTEX_NOT_HELD( mLock );
Mutex::Autolock _l( mLock );
mFrameIndex = frameIndex;
mbValid = true;
}
void setFrameReceivedTime( nsecs_t rxTime )
{
INTEL_UFO_HWC_ASSERT_MUTEX_NOT_HELD( mLock );
Mutex::Autolock _l( mLock );
mFrameReceivedTime = rxTime;
}
bool validateFrame( uint32_t frameIndex )
{
INTEL_UFO_HWC_ASSERT_MUTEX_NOT_HELD( mLock );
Mutex::Autolock _l( mLock );
return mbValid && ( mFrameIndex = frameIndex);
}
private:
// Lock on DisplayState.
mutable Mutex mLock;
// Index for this state.
uint32_t mIndex;
// Pointer to the physical display that this state is going to be applied to
AbstractPhysicalDisplay* mpHwDisplay;
// This structure holds the layer state for this hardware display
Content::Display mContent;
// Composition thats currently in use
PlaneComposition mPlaneComposition;
// Indication of which external components have blanked the display
uint32_t mBlankMask;
// Frame index (set through setFrameIndex in prepare).
uint32_t mFrameIndex;
// Frame received time (set through setFrameReceivedTime in prepare).
nsecs_t mFrameReceivedTime;
// Has prepare (and frame index) been set yet?
bool mbValid:1;
// Are VSyncs currently enabled for this display hardware.
bool mbVSyncEnabled:1;
};
DisplayState mDisplayState[ cMaxSupportedPhysicalDisplays ]; //< Display state.
AbstractPhysicalDisplay* mpPhysicalDisplay[ cMaxSupportedPhysicalDisplays ]; //< Pool of physical displays.
uint32_t mPhysicalDisplays; //< Count of physical displays.
uint32_t mPhyIndexRemap[ cMaxSupportedLogicalDisplays ]; //< Used to remap indices into physical index.
bool mbRemapIndices:1; //< Use remap?
class IdleTimeout {
public:
IdleTimeout(Hwc& hwc);
bool shouldReAnalyse();
void setCanOptimize(unsigned display, bool can);
bool frameIsIdle() const { return mOptionIdleTimeout && ( mFramesToExitIdle > 1 ); }
void nextFrame() { resetIdleTimer(); }
private:
void idleTimeoutHandler();
void resetIdleTimer();
// The value '1' denotes that the current frame is transitioning to active.
bool frameComingOutOfIdle() const { return mFramesToExitIdle == 1; }
Hwc& mHwc; // Needed to request a re-draw.
// Milliseconds before switching to idle mode. 0 disables idle entirely.
Option mOptionIdleTimeout;
// Milliseconds for the display to remain idle in order to maintain idle mode.
Option mOptionIdleTimein;
TimerMFn<IdleTimeout, &IdleTimeout::idleTimeoutHandler> mIdleTimer;
uint32_t mFramesToExitIdle;
BitSet32 mDisplaysCanOptimise;
bool mbForceReAnalyse;
};
IdleTimeout mIdleTimeout;
Option mEnablePlaneAllocator;
};
}; // namespace hwc
}; // namespace ufo
}; // namespace intel
#endif // INTEL_UFO_HWC_PHYSICAL_DISPLAY_MANAGER_H
| [
"kalyan.kondapally@intel.com"
] | kalyan.kondapally@intel.com |
2dda1d616b898a1f65a13a4ee9a805640417261a | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/fb/a12552ba380235/main.cpp | c9f1e8285b9d3829eb80191d1ed26bf6d16ec668 | [] | 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 | 4,820 | cpp | #include <type_traits>
#include <initializer_list>
#include <tuple>
constexpr auto all(std::initializer_list<bool> v)
{
for (auto b : v) { if (!b) { return false; } }
return true;
}
namespace detail
{
template<typename T, typename U, typename = void>
struct erases_parameter : std::false_type { };
template<typename T, typename U>
struct erases_parameter<T, U, decltype(U{std::declval<T>()}, void())>
: std::true_type
{ };
//======================================================================
// A FEW TESTS...
static_assert(erases_parameter<int&, int>{}, "!");
static_assert(erases_parameter<int&, int const>{}, "!");
static_assert(erases_parameter<int&, int const&>{}, "!");
static_assert(!erases_parameter<int&, int&&>{}, "!");
static_assert(erases_parameter<int&&, int>{}, "!");
static_assert(erases_parameter<int&&, int const>{}, "!");
static_assert(erases_parameter<int&&, int const&>{}, "!");
static_assert(!erases_parameter<int&&, int&>{}, "!");
//======================================================================
template<typename... Ts>
struct erases_all_parameters;
template<typename... Ts, typename... Us>
struct erases_all_parameters<std::tuple<Ts...>, std::tuple<Us...>>
: std::integral_constant<bool, all({erases_parameter<Ts, Us>{}...})>
{ };
//======================================================================
// A FEW TESTS...
static_assert(erases_all_parameters<std::tuple<int&&, int&>,
std::tuple<int, int const&>>{}, "!");
//======================================================================
template<typename T, typename U>
using erases_return_type =
std::integral_constant<bool,
std::is_same<T, void>{} ||
erases_parameter<U, T>{}>;
//======================================================================
// A FEW TESTS...
static_assert(erases_return_type<int&&, int>{}, "!");
//======================================================================
}
template<typename S1, typename S2>
struct erases_signature;
template<typename R1, typename R2, typename... Params1, typename... Params2>
struct erases_signature<R1(Params1...), R2(Params2...)>
: std::integral_constant<
bool,
detail::erases_all_parameters<std::tuple<Params1...>,
std::tuple<Params2...>>{} &&
detail::erases_return_type<R1, R2>{}>
{ };
//======================================================================
// A FEW TESTS...
static_assert(erases_signature<void(int&), int*(const int)>{}, "!");
static_assert(erases_signature<void(int&&), int*(int const&)>{}, "!");
static_assert(erases_signature<int&&(int&), int(int const)>{}, "!");
static_assert(!erases_signature<int&(int&), int(int)>{}, "!");
//======================================================================
template<typename Sig>
struct member_function_globalizer;
template<typename T, typename R, typename... Params>
struct member_function_globalizer<R(T::*)(Params...)>
{
template<R(T::*F)(Params...)>
struct lambda
{
static R invoke(T* self, Params... args)
{
return (self->*F)(std::forward<Params>(args)...);
}
};
};
#define GLOBALIZE(T, fxn) \
member_function_globalizer<decltype(&T::fxn)>:: \
template lambda<&T::fxn>::invoke;
namespace detail
{
template<typename ThunkSig, typename TargetSig>
struct make_forwarding_thunk;
template<typename ThunkR,
typename TargetR,
typename... ThunkParams,
typename... TargetParams>
struct make_forwarding_thunk<ThunkR(ThunkParams...),
TargetR(*)(TargetParams...)>
{
template<TargetR(*F)(TargetParams...)>
struct lambda
{
static ThunkR invoke(ThunkParams... args)
{
return F(std::forward<ThunkParams>(args)...);
}
};
};
}
#define FORWARDING_THUNK(S, fxn) \
detail::make_forwarding_thunk<S, decltype(fxn)> \
::template lambda<fxn>::invoke
#include <iostream>
void foo(int& x, bool y)
{
std::cout << x << " " << y << std::endl;
}
struct X
{
X(int val) : _val{val}
{ }
void bar(int x, double y)
{ std::cout << x << " " << y << " " << _val << std::endl; }
int _val;
};
int main()
{
using SIG = void(int&, bool&&);
auto thunk1 = FORWARDING_THUNK(SIG, &foo);
int x = 42;
thunk1(x, true);
auto thunk2 = GLOBALIZE(X, bar);
X obj{1337};
thunk2(&obj, 1729, 3.14);
}
| [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
78dfc0d62086ec652664ebedf09fe6f27f51e2cd | e41f5b945c3420c0d24c40457e5970ecd8ea2834 | /src/init.cpp | 54504234a537d89065f3f4ccd0839cbbed24a305 | [
"Zlib"
] | permissive | ds84182/dart-sfml | f13c70c6373f12752a840a929a664c6f56062f0e | 501f17737c4779201fff475b7f7e5918dc5e8f0b | refs/heads/master | 2021-01-20T19:29:46.187585 | 2016-08-01T00:13:38 | 2016-08-01T00:13:38 | 63,967,930 | 2 | 1 | null | 2016-07-31T02:59:27 | 2016-07-22T16:30:49 | C++ | UTF-8 | C++ | false | false | 1,390 | cpp | #include "init.hpp"
#include "graphics.hpp"
#include "window.hpp"
#include <array>
const std::array<const FunctionMap*, 2> maps = {
&Graphics::functions,
&Window::functions,
};
void GCHandle(Dart_Handle handle, size_t size, std::function<void()> func) {
Dart_NewWeakPersistentHandle(handle, reinterpret_cast<void*>(new std::function<void()>(func)), size, [](void *, Dart_WeakPersistentHandle handle, void *func_v) {
std::function<void()> *funcptr = reinterpret_cast<std::function<void()>*>(func_v);
(*funcptr)();
delete funcptr;
});
}
static Dart_NativeFunction ResolveName(Dart_Handle name, int argc, bool* auto_setup_scope);
thread_local Dart_PersistentHandle library;
DART_EXPORT Dart_Handle sfml_Init(Dart_Handle parent_library) {
if (Dart_IsError(parent_library)) return parent_library;
library = Dart_NewPersistentHandle(parent_library);
Dart_Handle result_code = Dart_SetNativeResolver(parent_library, ResolveName, nullptr);
if (Dart_IsError(result_code)) return result_code;
return Dart_Null();
}
Dart_NativeFunction ResolveName(Dart_Handle name, int argc, bool* auto_setup_scope) {
// If we fail, we return nullptr, and Dart throws an exception.
if (!Dart_IsString(name)) return nullptr;
const char* cname;
$(Dart_StringToCString(name, &cname));
for (auto map : maps) {
if (map->count(cname)) {
return map->at(cname);
}
}
return nullptr;
}
| [
"ds84182@gmail.com"
] | ds84182@gmail.com |
102e61865a1d47a30b102a52c557f6f6d473a0c2 | e5c0cd8ca20c6a1fa26a39e75b3de99a487707a7 | /HEW/Sound.cpp | 52fd005b7517b2a38d3561b82996e3a37f194a2e | [] | no_license | Hohman-Y/HEW | 632fe20633022d7dba35f714a7a545df029d71b4 | 2c299de5bc75a300d7b8d341c7c29919ab68269a | refs/heads/master | 2020-09-13T14:48:40.898492 | 2020-01-17T07:33:41 | 2020-01-17T07:33:41 | 222,821,112 | 0 | 0 | null | 2019-12-18T08:10:50 | 2019-11-20T01:06:27 | C++ | SHIFT_JIS | C++ | false | false | 9,863 | cpp | /*==================================================
[Sound.cpp]
Author : 出合翔太
==================================================*/
#include "main.h"
#include "Sound.h"
// パラメータ構造体定義
struct Sounddata
{
char *pFilename; // ファイル名
int nCntLoop; // ループカウント
};
// プロトタイプ宣言
HRESULT CheckChunk(HANDLE hFile, DWORD format, DWORD *pChunkSize, DWORD *pChunkDataPosition);
HRESULT ReadChunkData(HANDLE hFile, void *pBuffer, DWORD dwBuffersize, DWORD dwBufferoffset);
// スタティック変数
IXAudio2 *Sound::m_pXAudio2 = NULL; // XAudio2オブジェクトへのインターフェイス
IXAudio2MasteringVoice *Sound::m_pMasteringVoice = NULL; // マスターボイス
IXAudio2SourceVoice *Sound::m_apSourceVoice[SOUND_LABEL_MAX] = {}; // ソースボイス
BYTE *Sound::m_apDataAudio[SOUND_LABEL_MAX] = {}; // オーディオデータ
DWORD Sound::m_aSizeAudio[SOUND_LABEL_MAX] = {}; // オーディオデータサイズ
// 各音素材のパラメータSounddata
Sounddata g_aParam[SOUND_LABEL_MAX] =
{
{(char*) "asset/SE/move.wav",0},
{(char*) "asset/SE/count.,wav",0},
{(char*) "asset/SE/start.wav",0},
{(char*) "asset/SE/bad.wav",0},
{(char*) "asset/SE/excellent.wav",0},
{(char*) "asset/SE/good.wav",0},
{(char*) "asset/SE/hazure.wav",0},
{(char*) "asset/SE/kettei",0},
{(char*) "asset/SE/seikai",0},
{(char*) "asset/SE/speed.,wav",0},
{(char*) "aseet/SE/fly.wav",0},
{(char*) "asset/SE/mondai.wav",0},
};
// 初期化処理
bool Sound::Init(HWND hWnd)
{
HRESULT hr;
// COMライブラリの初期化
CoInitializeEx(NULL, COINIT_MULTITHREADED);
// XAudio2オブジェクトの作成
hr = XAudio2Create(&m_pXAudio2, 0);
if (FAILED(hr))
{
MessageBox(hWnd, "XAudio2オブジェクトの作成に失敗!", "警告!", MB_ICONWARNING);
// COMライブラリの終了処理
CoUninitialize();
return false;
}
// マスターボイスの生成
hr = m_pXAudio2->CreateMasteringVoice(&m_pMasteringVoice);
if (FAILED(hr))
{
MessageBox(hWnd, "マスターボイスの生成に失敗!", "警告!", MB_ICONWARNING);
if (m_pXAudio2)
{
// XAudio2オブジェクトの開放
m_pXAudio2->Release();
m_pXAudio2 = NULL;
}
// COMライブラリの終了処理
CoUninitialize();
return false;
}
// サウンドデータの初期化
for (int nCntSound = 0; nCntSound < SOUND_LABEL_MAX; nCntSound++)
{
HANDLE hFile;
DWORD dwChunkSize = 0;
DWORD dwChunkPosition = 0;
DWORD dwFiletype;
WAVEFORMATEXTENSIBLE wfx;
XAUDIO2_BUFFER buffer;
// バッファのクリア
memset(&wfx, 0, sizeof(WAVEFORMATEXTENSIBLE));
memset(&buffer, 0, sizeof(XAUDIO2_BUFFER));
// サウンドデータファイルの生成
hFile = CreateFile(g_aParam[nCntSound].pFilename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (hFile = INVALID_HANDLE_VALUE)
{
MessageBox(hWnd, "サウンドデータファイルの生成に失敗!(1)", "警告!", MB_ICONWARNING);
return false;
}
if (SetFilePointer(hFile, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
{// ファイルポインタを先頭に移動
MessageBox(hWnd, "サウンドデータファイルの生成に失敗!(2)", "警告!", MB_ICONWARNING);
return false;
}
// WAVEファイルのチェック
hr = CheckChunk(hFile, 'FFIR', &dwChunkSize, &dwChunkPosition);
if (FAILED(hr))
{
MessageBox(hWnd, "WAVEファイルのチェックに失敗!(1)", "警告!", MB_ICONWARNING);
return false;
}
hr = ReadChunkData(hFile, &dwFiletype, sizeof(DWORD), dwChunkPosition);
if (FAILED(hr))
{
MessageBox(hWnd, "WAVEファイルのチェックに失敗!(2)", "警告!", MB_ICONWARNING);
return false;
}
if (dwFiletype != 'EVAW')
{
MessageBox(hWnd, "WAVEファイルのチェックに失敗!(3)", "警告!", MB_ICONWARNING);
return false;
}
// フォーマットチェック
hr = CheckChunk(hFile, ' tmf', &dwChunkSize, &dwChunkPosition);
if (FAILED(hr))
{
MessageBox(hWnd, "フォーマットチェックに失敗!(1)", "警告!", MB_ICONWARNING);
return false;
}
hr = ReadChunkData(hFile, &wfx, dwChunkSize, dwChunkPosition);
if (FAILED(hr))
{
MessageBox(hWnd, "フォーマットチェックに失敗!(2)", "警告!", MB_ICONWARNING);
return false;
}
// オーディオデータ読み込み
hr = CheckChunk(hFile, 'atad', &m_aSizeAudio[nCntSound], &dwChunkPosition);
if (FAILED(hr))
{
MessageBox(hWnd, "オーディオデータ読み込みに失敗!(1)", "警告!", MB_ICONWARNING);
return false;
}
m_apDataAudio[nCntSound] = (BYTE*)malloc(m_aSizeAudio[nCntSound]);
hr = ReadChunkData(hFile, m_apDataAudio[nCntSound], m_aSizeAudio[nCntSound], dwChunkPosition);
if (FAILED(hr))
{
MessageBox(hWnd, "オーディオデータ読み込みに失敗!(2)", "警告!", MB_ICONWARNING);
return false;
}
// ソースボイスの生成
hr = m_pXAudio2->CreateSourceVoice(&m_apSourceVoice[nCntSound], &(wfx.Format));
if (FAILED(hr))
{
MessageBox(hWnd, "ソースボイスの生成に失敗!", "警告!", MB_ICONWARNING);
return false;
}
// バッファの値設定
memset(&buffer, 0, sizeof(XAUDIO2_BUFFER));
buffer.AudioBytes = m_aSizeAudio[nCntSound];
buffer.pAudioData = m_apDataAudio[nCntSound];
buffer.Flags = XAUDIO2_END_OF_STREAM;
buffer.LoopCount = g_aParam[nCntSound].nCntLoop;
// オーディオバッファの登録
m_apSourceVoice[nCntSound]->SubmitSourceBuffer(&buffer);
}
return true;
}
// 終了処理
void Sound::Uninit(void)
{
// 一時停止
for (int nCntSound = 0; nCntSound < SOUND_LABEL_MAX; nCntSound++)
{
if (m_apSourceVoice[nCntSound])
{
// 一時停止
m_apSourceVoice[nCntSound]->Stop(0);
// ソースボイスの破棄
m_apSourceVoice[nCntSound]->DestroyVoice();
m_apSourceVoice[nCntSound] = NULL;
// オーディオデータの開放
free(m_apDataAudio[nCntSound]);
m_apDataAudio[nCntSound] = NULL;
}
}
// マスターボイスの破棄
m_pMasteringVoice->DestroyVoice();
m_pMasteringVoice = NULL;
if (m_pXAudio2)
{
// XAudio2オブジェクトの開放
m_pXAudio2->Release();
m_pXAudio2 = NULL;
}
// COMライブラリの終了処理
CoUninitialize();
}
// セグメント再生(再生中なら停止)
void Sound::Play(SOUND_LABEL label)
{
XAUDIO2_VOICE_STATE xa2state;
XAUDIO2_BUFFER buffer;
// バッファの値設定
memset(&buffer, 0, sizeof(XAUDIO2_BUFFER));
buffer.AudioBytes = m_aSizeAudio[label];
buffer.pAudioData = m_apDataAudio[label];
buffer.Flags = XAUDIO2_END_OF_STREAM;
buffer.LoopCount = g_aParam[label].nCntLoop;
// 状態取得
m_apSourceVoice[label]->GetState(&xa2state);
if (xa2state.BuffersQueued != 0)
{// 再生中
// 一時停止
m_apSourceVoice[label]->Stop(0);
// オーディオバッファの削除
m_apSourceVoice[label]->FlushSourceBuffers();
}
// オーディオバッファの登録
m_apSourceVoice[label]->SubmitSourceBuffer(&buffer);
// 再生
m_apSourceVoice[label]->Start(0);
}
// セグメント停止(ラベル指定)
void Sound::Stop(SOUND_LABEL label)
{
XAUDIO2_VOICE_STATE xa2state;
// 状態取得
m_apSourceVoice[label]->GetState(&xa2state);
if (xa2state.BuffersQueued != 0)
{// 再生中
// 一時停止
m_apSourceVoice[label]->Stop(0);
// オーディオバッファの削除
m_apSourceVoice[label]->FlushSourceBuffers();
}
}
// セグメント停止(全て)
void Sound::Stop(void)
{
// 一時停止
for (int nCntSound = 0; nCntSound < SOUND_LABEL_MAX; nCntSound++)
{
if (m_apSourceVoice[nCntSound])
{
// 一時停止
m_apSourceVoice[nCntSound]->Stop(0);
}
}
}
// チャンクのチェック
HRESULT CheckChunk(HANDLE hFile, DWORD format, DWORD *pChunkSize, DWORD *pChunkDataPosition)
{
HRESULT hr = S_OK;
DWORD dwRead;
DWORD dwChunkType;
DWORD dwChunkDataSize;
DWORD dwRIFFDataSize = 0;
DWORD dwFileType;
DWORD dwBytesRead = 0;
DWORD dwOffset = 0;
if (SetFilePointer(hFile, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
{// ファイルポインタを先頭に移動
return HRESULT_FROM_WIN32(GetLastError());
}
while (hr == S_OK)
{
if (ReadFile(hFile, &dwChunkType, sizeof(DWORD), &dwRead, NULL) == 0)
{// チャンクの読み込み
hr = HRESULT_FROM_WIN32(GetLastError());
}
if (ReadFile(hFile, &dwChunkDataSize, sizeof(DWORD), &dwRead, NULL) == 0)
{// チャンクデータの読み込み
hr = HRESULT_FROM_WIN32(GetLastError());
}
switch (dwChunkType)
{
case 'FFIR':
dwRIFFDataSize = dwChunkDataSize;
dwChunkDataSize = 4;
if (ReadFile(hFile, &dwFileType, sizeof(DWORD), &dwRead, NULL) == 0)
{// ファイルタイプの読み込み
hr = HRESULT_FROM_WIN32(GetLastError());
}
break;
default:
if (SetFilePointer(hFile, dwChunkDataSize, NULL, FILE_CURRENT) == INVALID_SET_FILE_POINTER)
{// ファイルポインタをチャンクデータ分移動
return HRESULT_FROM_WIN32(GetLastError());
}
}
dwOffset += sizeof(DWORD) * 2;
if (dwChunkType == format)
{
*pChunkSize = dwChunkDataSize;
*pChunkDataPosition = dwOffset;
return S_OK;
}
dwOffset += dwChunkDataSize;
if (dwBytesRead >= dwRIFFDataSize)
{
return S_FALSE;
}
}
return S_OK;
}
// チャンクデータの読み込み
HRESULT ReadChunkData(HANDLE hFile, void *pBuffer, DWORD dwBuffersize, DWORD dwBufferoffset)
{
DWORD dwRead;
if (SetFilePointer(hFile, dwBufferoffset, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER)
{// ファイルポインタを指定位置まで移動
return HRESULT_FROM_WIN32(GetLastError());
}
if (ReadFile(hFile, pBuffer, dwBuffersize, &dwRead, NULL) == 0)
{// データの読み込み
return HRESULT_FROM_WIN32(GetLastError());
}
return S_OK;
}
| [
"52692512+chinpanGX@users.noreply.github.com"
] | 52692512+chinpanGX@users.noreply.github.com |
b684b75fdff4fb28fae83a89c7b1511f29ae7173 | fbfb766101dde752846fa78e6a19f1163f4779da | /grid.cpp | a48093adda42bf9f3625d29dc415b8447c41b141 | [] | no_license | DineshPolakala/Data-Structures-and-Algorithms | 01abcf474d8e858261814f6e7022f555b0b1e04c | 69c7f4d3e3326365086c667d43fe1f6a46da1170 | refs/heads/main | 2023-06-24T10:50:30.937804 | 2021-07-18T05:58:31 | 2021-07-18T05:58:31 | 371,748,393 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 646 | cpp | #include<bits/stdc++.h>
using namespace std;
int helper(vector<vector<int>>grid, int i, int j, vector<vector<bool>>& visited ) {
if (grid[i][j] == 0)return 0;
if (grid[i][j] == 9)return 1;
visited[i][j] = true;
int a = helper(grid, i + 1, j, visited);
int b = helper(grid, i - 1, j, visited);
int c = helper(grid, i, j + 1, visited), d = helper(grid, i, j - 1, visited);
}
int getmin(vector<vector<int>>grid) {
vector<vector<bool>>visited(grid.size(), vector<bool>(grid[0].size(), false));
return helper(grid, 0, 0, visited, 0);
}
int main()
{
vector<vector<int>>grid {{1, 0, 0}, {1, 0, 1}, {1, 9, 0}};
cout << getmin(grid) << endl;
} | [
"polakala.dinesh@btech.christuniversity.in"
] | polakala.dinesh@btech.christuniversity.in |
54d7dd978bdbd5a76804b924f4fe6acc0cfeb826 | 59f9b66c6d0bfdb026087faa3b36916e02128d73 | /Plugins/ClimbingPawnMovementComponent/Source/ClimbingPawnMovementComponentRuntime/ClimbingPawnMovementComponent.cpp | 46e22bf33e4887021fc413870d4dcb371de55a5f | [
"MIT"
] | permissive | richmondmk/Climbing-Movement-Component | d587eea6ab99544042a53fac0a4ab6b889b8cc73 | 70c2c42a84920c7a350ace66ede788bc5d57fc62 | refs/heads/master | 2020-03-25T08:00:27.886285 | 2018-06-09T14:12:57 | 2018-06-09T14:12:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,870 | cpp | // Copyright 2016 - 2018 Dmitriy Pavlov
#include "ClimbingPawnMovementComponent.h"
#include "ClimbingCharacter.h"
#include "OverlapObject.h"
#include "Components/SplineComponent.h"
#include "LogCategory.h"
#include "ClimbingPawnMode.h"
#include <vector>
UClimbingPawnMovementComponent::UClimbingPawnMovementComponent(const class FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer),
ModeStorage(std::unique_ptr<TClimbingModeStorage> (new TClimbingModeStorage(*this)))
{
MaxWalkSpeed = 500;
JumpZVelocity = 400;
NavAgentProps.bCanCrouch = true;
bOrientRotationToMovement = true;
RunVelocytyCurve.GetRichCurve()->AddKey(0, MaxWalkSpeed);
RunVelocytyCurve.GetRichCurve()->AddKey(1.3, 1.6 * MaxWalkSpeed);
RunVelocytyCurve.GetRichCurve()->AddKey(3, 1.8 * MaxWalkSpeed);
float MaxRunVelocyty;
float MinRunVelocyty;
RunVelocytyCurve.GetRichCurve()->GetValueRange(MinRunVelocyty, MaxRunVelocyty);
SlideVelocytyCurve.GetRichCurve()->AddKey(0, MaxRunVelocyty);
SlideVelocytyCurve.GetRichCurve()->AddKey(0.8, 0.625 * MaxRunVelocyty);
SlideVelocytyCurve.GetRichCurve()->AddKey(1.2, 0);
CurrentClimbingMode = EClimbingPawnModeType::Run;
}
void UClimbingPawnMovementComponent::BeginPlay()
{
Super::BeginPlay();
float MinRunTime;
RunVelocytyCurve.GetRichCurve()->GetTimeRange(MinRunTime, MaxRunTime);
}
void UClimbingPawnMovementComponent::TickComponent(float DeltaTime, enum ELevelTick TickType, FActorComponentTickFunction *ThisTickFunction)
{
if (!PawnOwner || !UpdatedComponent || ShouldSkipUpdate(DeltaTime))
{
return;
}
if (ModeStorage->Get(CurrentClimbingMode).Tick(DeltaTime))
{
Super::TickComponent(DeltaTime, TickType, ThisTickFunction);
}
};
void UClimbingPawnMovementComponent::SetClimbMode(EClimbingPawnModeType ClimbingMode)
{
if (CurrentClimbingMode == ClimbingMode) return;
ModeStorage->Get(CurrentClimbingMode).UnSetMode();
CurrentClimbingMode = ClimbingMode;
ModeStorage->Get(ClimbingMode).SetMode();
}
bool UClimbingPawnMovementComponent::DoJump(bool bReplayingMoves)
{
bool ReturnValue;
if (ModeStorage->Get(CurrentClimbingMode).DoJump(bReplayingMoves, ReturnValue))
{
return Super::DoJump(bReplayingMoves);
}
else
{
return ReturnValue;
}
}
float UClimbingPawnMovementComponent::GetMaxSpeed() const
{
float MaxSpeed;
float CurrentRunTime = MaxRunTime * RunSpeedValue;
if (MovementMode == EMovementMode::MOVE_Walking || MovementMode == EMovementMode::MOVE_NavWalking || MovementMode == EMovementMode::MOVE_Falling)
{
MaxSpeed = RunVelocytyCurve.GetRichCurveConst()->Eval(CurrentRunTime);
}
else
{
MaxSpeed = Super::GetMaxSpeed();
}
return MaxSpeed;
}
void UClimbingPawnMovementComponent::MoveTo(const FVector Delta, const FRotator NewRotation, bool CheckCollision)
{
if (CheckCollision)
{
FHitResult Hit;
SafeMoveUpdatedComponent(Delta, NewRotation, true, Hit);
if (Hit.IsValidBlockingHit())
{
SlideAlongSurface(Delta, 1.f - Hit.Time, Hit.Normal, Hit, false);
}
}
else
{
GetPawnOwner()->AddActorWorldOffset(Delta);
GetPawnOwner()->SetActorRotation(NewRotation);
}
}
void UClimbingPawnMovementComponent::RollCameraSet(int NewRoll)
{
FRotator ControlRot = GetWorld()->GetFirstPlayerController()->GetControlRotation();
ControlRot.Roll = NewRoll;
GetWorld()->GetFirstPlayerController()->SetControlRotation(ControlRot);
}
void UClimbingPawnMovementComponent::YawCameraSet(int NewYaw)
{
FRotator ControlRot = GetWorld()->GetFirstPlayerController()->GetControlRotation();
ControlRot.Yaw = NewYaw;
GetWorld()->GetFirstPlayerController()->SetControlRotation(ControlRot);
}
void UClimbingPawnMovementComponent::AddYawCamera(int DeltaYaw)
{
FRotator ControlRot = GetWorld()->GetFirstPlayerController()->GetControlRotation();
ControlRot.Yaw += DeltaYaw;
GetWorld()->GetFirstPlayerController()->SetControlRotation(ControlRot);
} | [
"deema_35@mail.ru"
] | deema_35@mail.ru |
1f3b9f4f9f60a6bb3c289b5021e9bfc0c9379003 | d07e70da464584342f05c71ac7410e3e214666bb | /romans.cpp | f33f01a3e566b6a430f5cc30207f60f5a1e6631d | [] | no_license | Wai-Yan-Htoo/Kattis-Solutions | 554b86ac733146d0e4a99c9de9c80d70c0a84ae8 | 4e61b3967ca50fc50de32c6297f3adec503ec85e | refs/heads/master | 2022-03-20T20:29:26.506184 | 2019-12-06T08:37:49 | 2019-12-06T08:37:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 174 | cpp | #include <iostream>
int main() {
double miles;
std::cin >> miles;
int paces = (int)(miles * 1000 * 5280 / 4854 + 0.5);
std::cout << paces << std::endl;
return 0;
} | [
"nazhou.na9@gmail.com"
] | nazhou.na9@gmail.com |
f565702719fd7282f2589f05f0f083bb85cce13d | de0524250a32e3734b3d972618b663738dbdaa45 | /Algorytmy_i_Struktury_Danych/Spojnosc_extra.cpp | e63d2db70f1789dd5b765ddef4f50a426c07f934 | [] | no_license | Kitee666/UMK | 9702b8e83520194aae586aa48e27f5cb8e502d25 | 62ce69ba0e4ac323b6b702e80ef5f6c83f009c74 | refs/heads/main | 2023-05-28T09:40:27.913257 | 2021-06-07T10:32:45 | 2021-06-07T10:32:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 659 | cpp | #include <iostream>
#include <vector>
using namespace std;
void dfs(vector <int> *w, bool *o, int n){
int i;
o[n]=1;
for(i=0;i<w[n].size();i++){
if(o[w[n][i]]==0){
dfs(w,o,w[n][i]);
}
}
return;
}
bool spr(bool *o,int n){
int i;
for(i=0;i<n;i++){
if(o[i]==0){
return 0;
}
}
return 1;
}
int main() {
int n,i,j,k,a,b,c=0;
cin>>n;
vector <int> w[n];
bool o[n];
for(i=0;i<n;i++){
o[i]=0;
}
cin>>k;
for(i=0;i<k;i++){
cin>>a>>b;
w[a].push_back(b);
w[b].push_back(a);
}
for(i=0;i<n;i++){
if(o[i]==0){
dfs(w,o,0);
c++;
}
}
cout<<"Liczba skladowych: "<<c;
return 0;
} | [
"dawidsikorski272@gmail.com"
] | dawidsikorski272@gmail.com |
97cd2c6c3afd9c4c825941909d2e2a9cf06a998d | 51e8ee2b409440bcca1c7c6eefc08dcb2f71c875 | /WordNode.h | 3440af6af200faa5974ee3d19f6e667e1758322e | [] | no_license | TheTipTapTyper/Dictionary | 70e22c247c7d600bb20de0f5734a8889e56dc3fb | 4f7b38e57a6be39edd224a67f175ab41aaa9f947 | refs/heads/master | 2020-04-02T20:21:57.937113 | 2018-10-26T03:17:57 | 2018-10-26T03:17:57 | 154,766,565 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 308 | h | #ifndef _WORDNODE_H_
#define _WORDNODE_H_
class WordNode{
private:
string word;
public:
WordNode(string word_input); //constructor with word input
~WordNode(); //destructor
WordNode* left;
WordNode* right;
//getters
string getWord();
//setters
void changeWord();
};
#endif _WORDNODE_H_ | [
"jmmartin397@protonmail.com"
] | jmmartin397@protonmail.com |
7b178394d340058622aeaf018c966bcffabca14a | 22cf65e8491512a50745ec1697168af6ffa84079 | /lksh_sch/day2/F.cpp | 460d6b346aae8d0b1183fecbe2ba39317c35bbf1 | [] | no_license | GitProger/lksh | b140d5334e480a35c7dcaa78a9d945c2420be171 | b45c59077c1073c40a5df70621dec5cab1c037d4 | refs/heads/master | 2023-07-04T17:17:22.900522 | 2021-08-18T17:01:56 | 2021-08-18T17:01:56 | 395,274,077 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,534 | cpp | #include <bits/stdc++.h>
using namespace std;
#define int ll
typedef long long ll;
typedef long double ld;
typedef long long var;
typedef pair<int, int>prii;
typedef pair<ll, ll>prll;
typedef vector<int>veci;
typedef vector<ll>vecl;
typedef vector<veci> graph;
typedef map<int, int> mapii;
typedef set<int> seti;
typedef bitset<64> bits;
typedef string str;
#define vec vector
#define fir first
#define sec second
#define $ '\n'
#define $$ endl
#define MAX LONG_LONG_MAX
#define INF LONG_LONG_MAX
#define MIN LONG_LONG_MIN
#define len(o) ((int)o.size())
template <typename T> istream& operator >> (istream &in, vector<T> &v) {
for (T &t : v) in >> t;
return in;
}
template <typename T> ostream& operator << (ostream &out, const vector<T> &v) {
for (const T &t : v) out << t << ' ';
return out;
}
mt19937 rnd(1234);
inline void solve();
signed main() {
solve();
cout.flush();
return 0;
}
inline void stress() {
}
////////////////////////////////////////////////////////////////////////////////
template<class T> void fromPair(T &a, T &b, const pair<T, T> &c) {
a = c.first;
b = c.second;
}
struct Node {
int index, y, sz = 1;
int val = 0, sum = 0;
Node *left = nullptr, *right = nullptr;
Node(int i, int m = 0):
index(i), y(rnd()), val(m), sum(m)
{}
};
typedef Node *pNode;
int size(Node *r) { return r != nullptr ? r->sz : 0; }
int sum(Node *r) { return r != nullptr ? r->sum : 0; }
void upd(Node *r) {
if (r == nullptr) return;
r->sz = size(r->left) + 1 + size(r->right);
r->sum = r->val + sum(r->left) + sum(r->right);
}
void push(Node *r) {
}
pair<pNode, pNode> split(pNode root, int x) {
if (root == nullptr) return make_pair(nullptr, nullptr);
push(root);
if (x < 1 + size(root->left)) {
auto buf = split(root->left, x);
Node *r1 = buf.first, *r2 = buf.second;
root->left = r2;
upd(root);
return make_pair(r1, root);
} else {
auto buf = split(root->right, x - 1 - size(root->left));
Node *r1 = buf.first, *r2 = buf.second;
root->right = r1;
upd(root);
return make_pair(root, r2);
}
}
Node *merge(Node *r1, Node *r2) {
if (r1 == nullptr) return r2;
if (r2 == nullptr) return r1;
if (r1->y <= r2->y) {
push(r1);
r1->right = merge(r1->right, r2);
upd(r1);
return r1;
} else {
push(r2);
r2->left = merge(r1, r2->left);
upd(r2);
return r2;
}
}
void insert(pNode &root, int i, int v = 0) {
auto buf = split(root, i);
root = merge(merge(buf.first, new Node(i, v)), buf.second);
}
///////////////////////////////////////////////////////////////////////////////
int get_sum(pNode &root1, pNode &root2, int l, int r) {
if (l > r) return 0;
int l1 = (l + 1) / 2, r1 = r / 2;
int l2 = l / 2, r2 = (r + 1) / 2 - 1;
pNode a1, b1, c1, a2, b2, c2;
// root_i => [a_i, b_i, c_i] => root_i
fromPair(a1, b1, split(root1, l1));
fromPair(b1, c1, split(b1, r1 - l1 + 1));
fromPair(a2, b2, split(root2, l2));
fromPair(b2, c2, split(b2, r2 - l2 + 1));
int res = sum(b1) + sum(b2);
root1 = merge(merge(a1, b1), c1);
root2 = merge(merge(a2, b2), c2);
return res;
}
void swap(pNode &root1, pNode &root2, int l, int r) {
int l1 = (l + 1) / 2, r1 = r / 2;
int l2 = l / 2, r2 = (r + 1) / 2 - 1;
pNode a1, b1, c1, a2, b2, c2;
// root_i => [a_i, b_i, c_i] => root_i
fromPair(a1, b1, split(root1, l1));
fromPair(b1, c1, split(b1, r1 - l1 + 1));
fromPair(a2, b2, split(root2, l2));
fromPair(b2, c2, split(b2, r2 - l2 + 1));
root1 = merge(merge(a1, b2), c1);
root2 = merge(merge(a2, b1), c2);
}
inline void solve() {
// 1 - четные 0, 2, 4, ...
// 2 - нечетные
for (int test = 1;; test++) {
int n, m; cin >> n >> m;
if (n == 0 && m == 0) return;
pNode tree1 = nullptr, tree2 = nullptr;
for (int i = 0; i < n; i++) {
int x; cin >> x;
insert(i % 2 == 0 ? tree1 : tree2, i, x);
}
cout << "Swapper " << test << ":\n";
while (m--) {
int t, l, r; cin >> t >> l >> r; --l; --r;
if (t == 1) {
swap(tree1, tree2, l, r);
} else if (t == 2) {
cout << get_sum(tree1, tree2, l, r) << endl;
}
}
cout << $;
}
}
/*
5 5
1 2 3 4 5
1 2 5
2 2 4
1 1 4
2 1 3
2 4 4
0 0
*/
| [
"alex0surname@gmail.com"
] | alex0surname@gmail.com |
f30db07a5c98950b5a57a51f5ed2b30df34b9405 | 0557c926589e1628e02255d93909599815a5e994 | /Source/WQ/Golems/WQAIGolem.cpp | 244617a63fc3482b304e92f76959037ff702d95e | [] | no_license | timdhoffmann/WQ | e13b6df81335cfd02909c603fcee5ad1ef237227 | 721e7ce5af82a3200464192ad136fc250d00d763 | refs/heads/master | 2020-09-17T08:35:57.758419 | 2019-11-28T23:14:11 | 2019-11-28T23:14:11 | 224,052,196 | 0 | 0 | null | 2019-11-25T22:18:50 | 2019-11-25T22:18:50 | null | UTF-8 | C++ | false | false | 105 | cpp | // Fill out your copyright notice in the Description page of Project Settings.
#include "WQAIGolem.h"
| [
"sebastien.p.violier@gmail.com"
] | sebastien.p.violier@gmail.com |
861ab61658f8beef8e22aa63cb244c35946f77fd | f6c4fcca82d6ade6004534def8333c33c6e94b0d | /Grafos/Grafo/TestesDigrafo.cpp | 8d53bc4a5b5b92b98a2bdc4e2c1a61928a25f4a1 | [] | no_license | pedropaulovc/UFSC | a0d75e136db3ac930ad1c3ac159184b7fdb4dc86 | 8cf964e1fdc5c58379679c38c68a74154811e571 | refs/heads/master | 2019-01-02T03:12:19.975742 | 2011-01-03T01:13:33 | 2011-01-03T01:13:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,715 | cpp | /*
* TestesDigrafo.cpp
*
* INE5413 - Grafos
* Alunos: Pedro Paulo Vezzá Campos e Tarcisio Eduardo Moreira Crocomo
*
* Sobre a classe: Contém os testes unitários da classe Digrafo.
*/
#include <gtest/gtest.h>
#include "Digrafo.h"
#include <cstdlib>
#include <string>
#include <list>
#include <iostream>
using namespace std;
class TestesDigrafo: public ::testing::Test {
protected:
Digrafo<string> *digrafo;
TestesDigrafo() {
}
~TestesDigrafo() {
}
void SetUp() {
digrafo = new Digrafo<string> ();
}
void TearDown() {
delete digrafo;
}
};
TEST_F(TestesDigrafo, testaDigrafoVazio)
{
vector<string> vertices = digrafo->obterVertices();
ASSERT_EQ(0, digrafo->obterOrdem());
ASSERT_EQ(0, vertices.size());
}
TEST_F(TestesDigrafo, testaInsercaoVertice)
{
digrafo->adicionaVertice("A");
digrafo->adicionaVertice("B");
digrafo->adicionaVertice("C");
vector<string> v = digrafo->obterVertices();
ASSERT_EQ(3, v.size());
ASSERT_EQ("A", v[0]);
ASSERT_EQ("B", v[1]);
ASSERT_EQ("C", v[2]);
ASSERT_EQ(0, digrafo->obterGrauEmissao("A"));
ASSERT_EQ(0, digrafo->obterGrauEmissao("B"));
ASSERT_EQ(0, digrafo->obterGrauEmissao("C"));
ASSERT_EQ(0, digrafo->obterGrauRecepcao("A"));
ASSERT_EQ(0, digrafo->obterGrauRecepcao("B"));
ASSERT_EQ(0, digrafo->obterGrauRecepcao("C"));
ASSERT_EQ(0, digrafo->obterAntecessores("A").size());
ASSERT_EQ(0, digrafo->obterAntecessores("B").size());
ASSERT_EQ(0, digrafo->obterAntecessores("C").size());
ASSERT_EQ(0, digrafo->obterAntecessores("D").size());
ASSERT_EQ(0, digrafo->obterSucessores("A").size());
ASSERT_EQ(0, digrafo->obterSucessores("B").size());
ASSERT_EQ(0, digrafo->obterSucessores("C").size());
ASSERT_EQ(0, digrafo->obterSucessores("D").size());
}
TEST_F(TestesDigrafo, testaRemocaoVertice)
{
digrafo->adicionaVertice("A");
digrafo->adicionaVertice("B");
digrafo->adicionaVertice("C");
ASSERT_EQ(3, digrafo->obterVertices().size());
digrafo->removeVertice("A");
ASSERT_EQ(2, digrafo->obterVertices().size());
digrafo->removeVertice("A");
ASSERT_EQ(2, digrafo->obterVertices().size());
digrafo->removeVertice("B");
ASSERT_EQ(1, digrafo->obterVertices().size());
digrafo->removeVertice("C");
ASSERT_EQ(0, digrafo->obterVertices().size());
}
TEST_F(TestesDigrafo, testaSucessores)
{
digrafo->adicionaVertice("A");
digrafo->adicionaVertice("B");
digrafo->adicionaVertice("C");
digrafo->adicionaVertice("D");
digrafo->conecta("A", "B");
digrafo->conecta("B", "C");
digrafo->conecta("A", "D");
ASSERT_EQ(2, digrafo->obterGrauEmissao("A"));
ASSERT_EQ("B", digrafo->obterSucessores("A")[0]);
ASSERT_EQ("D", digrafo->obterSucessores("A")[1]);
ASSERT_EQ(1, digrafo->obterGrauEmissao("B"));
ASSERT_EQ("C", digrafo->obterSucessores("B")[0]);
ASSERT_EQ(0, digrafo->obterGrauEmissao("C"));
ASSERT_EQ(0, digrafo->obterSucessores("C").size());
ASSERT_EQ(0, digrafo->obterGrauEmissao("D"));
ASSERT_EQ(0, digrafo->obterSucessores("D").size());
}
TEST_F(TestesDigrafo, testaAntecessores)
{
digrafo->adicionaVertice("A");
digrafo->adicionaVertice("B");
digrafo->adicionaVertice("C");
digrafo->adicionaVertice("D");
digrafo->conecta("A", "B");
digrafo->conecta("B", "C");
digrafo->conecta("A", "D");
digrafo->conecta("B", "D");
ASSERT_EQ(0, digrafo->obterGrauRecepcao("A"));
ASSERT_EQ(0, digrafo->obterAntecessores("A").size());
ASSERT_EQ(1, digrafo->obterGrauRecepcao("B"));
ASSERT_EQ(1, digrafo->obterAntecessores("B").size());
ASSERT_EQ("A", digrafo->obterAntecessores("B")[0]);
ASSERT_EQ(1, digrafo->obterGrauRecepcao("C"));
ASSERT_EQ(1, digrafo->obterAntecessores("C").size());
ASSERT_EQ("B", digrafo->obterAntecessores("C")[0]);
ASSERT_EQ(2, digrafo->obterGrauRecepcao("D"));
ASSERT_EQ(2, digrafo->obterAntecessores("D").size());
ASSERT_EQ("A", digrafo->obterAntecessores("D")[0]);
ASSERT_EQ("B", digrafo->obterAntecessores("D")[1]);
}
TEST_F(TestesDigrafo, testaDesconectar)
{
digrafo->adicionaVertice("A");
digrafo->adicionaVertice("B");
digrafo->adicionaVertice("C");
digrafo->adicionaVertice("D");
digrafo->conecta("A", "B");
digrafo->conecta("A", "D");
digrafo->conecta("D", "A");
digrafo->desconecta("A", "D");
ASSERT_EQ(1, digrafo->obterSucessores("A").size());
ASSERT_EQ("B", digrafo->obterSucessores("A")[0]);
ASSERT_EQ(1, digrafo->obterGrauEmissao("A"));
ASSERT_EQ(1, digrafo->obterAntecessores("A").size());
ASSERT_EQ("D", digrafo->obterAntecessores("A")[0]);
ASSERT_EQ(1, digrafo->obterGrauRecepcao("A"));
ASSERT_EQ(0, digrafo->obterSucessores("B").size());
ASSERT_EQ(0, digrafo->obterGrauEmissao("B"));
ASSERT_EQ(1, digrafo->obterAntecessores("B").size());
ASSERT_EQ("A", digrafo->obterAntecessores("B")[0]);
ASSERT_EQ(1, digrafo->obterGrauRecepcao("B"));
ASSERT_EQ(0, digrafo->obterSucessores("C").size());
ASSERT_EQ(0, digrafo->obterGrauEmissao("C"));
ASSERT_EQ(0, digrafo->obterAntecessores("C").size());
ASSERT_EQ(0, digrafo->obterGrauRecepcao("C"));
ASSERT_EQ(1, digrafo->obterSucessores("D").size());
ASSERT_EQ("A", digrafo->obterSucessores("D")[0]);
ASSERT_EQ(1, digrafo->obterGrauEmissao("D"));
ASSERT_EQ(0, digrafo->obterAntecessores("D").size());
ASSERT_EQ(0, digrafo->obterGrauRecepcao("D"));
}
TEST_F(TestesDigrafo, testaVerticeAleatorio)
{
digrafo->adicionaVertice("A");
digrafo->adicionaVertice("B");
digrafo->adicionaVertice("C");
digrafo->adicionaVertice("D");
digrafo->adicionaVertice("E");
digrafo->adicionaVertice("F");
digrafo->adicionaVertice("G");
digrafo->adicionaVertice("H");
digrafo->adicionaVertice("I");
digrafo->adicionaVertice("J");
digrafo->adicionaVertice("K");
digrafo->adicionaVertice("L");
ASSERT_NE(digrafo->obterVerticeAleatorio(), digrafo->obterVerticeAleatorio());
}
| [
"pedropaulovc@gmail.com"
] | pedropaulovc@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.