hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7b6bf81fb3469f8133a3e0ad57675fd2d2cd3243 | 829 | cpp | C++ | utility/rep.cpp | Cyanmond/Library | e77bb2e46ebc8630983025045570bd094aca7aa7 | [
"CC0-1.0"
] | 1 | 2021-11-04T05:41:45.000Z | 2021-11-04T05:41:45.000Z | utility/rep.cpp | Cyanmond/Library | e77bb2e46ebc8630983025045570bd094aca7aa7 | [
"CC0-1.0"
] | null | null | null | utility/rep.cpp | Cyanmond/Library | e77bb2e46ebc8630983025045570bd094aca7aa7 | [
"CC0-1.0"
] | null | null | null | #pragma once
#include "../utility/int_alias.cpp"
#include <algorithm>
class rep {
struct rep_iterator {
usize itr;
constexpr rep_iterator(const usize pos) noexcept : itr(pos) {}
constexpr void operator++() noexcept {
++itr;
}
constexpr bool operator!=(const usize &other) const noexcept {
return itr != other;
}
constexpr usize operator*() const noexcept {
return itr;
}
};
const rep_iterator first;
const usize last;
public:
constexpr rep(const usize first_, const usize last_) noexcept
: first(first_), last(std::max(first_, last_)) {}
constexpr rep_iterator begin() const noexcept {
return first;
}
constexpr usize end() const noexcept {
return last;
}
};
| 24.382353 | 70 | 0.588661 | Cyanmond |
7b6c1b160aacc80b48f7f16bd1a74d3faf807215 | 1,847 | cc | C++ | cpp/tools/parquet/parquet-dump-schema.cc | paulkernfeld/arrow | 501cde9fbf4cf3752d8df1d9e6b27367893045cb | [
"Apache-2.0"
] | 1 | 2021-01-28T17:30:06.000Z | 2021-01-28T17:30:06.000Z | cpp/tools/parquet/parquet-dump-schema.cc | azkh93/arrow | f08e109ff009e911bb772e5b0490c7cacf02140e | [
"Apache-2.0"
] | 1 | 2019-01-04T21:42:29.000Z | 2019-01-04T21:42:29.000Z | cpp/tools/parquet/parquet-dump-schema.cc | azkh93/arrow | f08e109ff009e911bb772e5b0490c7cacf02140e | [
"Apache-2.0"
] | 2 | 2019-11-18T06:31:46.000Z | 2020-11-19T13:36:36.000Z | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 <getopt.h>
#include <iostream>
#include "parquet/api/reader.h"
#include "parquet/api/schema.h"
int main(int argc, char** argv) {
static struct option options[] = {
{"help", no_argument, nullptr, 'h'}
};
bool help_flag = false;
int opt_index;
do {
opt_index = getopt_long(argc, argv, "h", options, nullptr);
switch (opt_index) {
case '?':
case 'h':
help_flag = true;
opt_index = -1;
break;
}
} while (opt_index != -1);
argc -= optind;
argv += optind;
if (argc != 1 || help_flag) {
std::cerr << "Usage: parquet-dump-schema [-h] [--help]"
<< " <filename>" << std::endl;
return -1;
}
std::string filename = argv[0];
try {
std::unique_ptr<parquet::ParquetFileReader> reader =
parquet::ParquetFileReader::OpenFile(filename);
PrintSchema(reader->metadata()->schema()->schema_root().get(), std::cout);
} catch (const std::exception& e) {
std::cerr << "Parquet error: " << e.what() << std::endl;
return -1;
}
return 0;
}
| 29.790323 | 78 | 0.658365 | paulkernfeld |
7b6df611b5cfd460401bdb79ade1fe1ddbdc13ae | 1,313 | cc | C++ | RangeSim/src/StackingAction.cc | murffer/DetectorSim | 1ba114c405eff42c0a52b6dc394cbecfc2d2bab0 | [
"Apache-2.0"
] | 5 | 2018-01-13T22:42:24.000Z | 2021-03-19T07:38:47.000Z | RangeSim/src/StackingAction.cc | murffer/DetectorSim | 1ba114c405eff42c0a52b6dc394cbecfc2d2bab0 | [
"Apache-2.0"
] | 1 | 2017-05-03T19:01:12.000Z | 2017-05-03T19:01:12.000Z | RangeSim/src/StackingAction.cc | murffer/DetectorSim | 1ba114c405eff42c0a52b6dc394cbecfc2d2bab0 | [
"Apache-2.0"
] | 3 | 2015-10-10T15:12:22.000Z | 2021-10-18T00:53:35.000Z | #include "StackingAction.hh"
#include "HistoManager.hh"
#include "G4Track.hh"
#include "G4VProcess.hh"
/**
* Default Constructor - nothing to be done
*/
StackingAction::StackingAction(){ }
/**
* Deconstructor
*/
StackingAction::~StackingAction(){ }
/**
* Classifies a new track, and fills the energy of the charged and neutral
* particles of the secondaries.
*/
G4ClassificationOfNewTrack
StackingAction::ClassifyNewTrack(const G4Track* track)
{
//keep primary particle
if (track->GetParentID() == 0) return fUrgent;
//
//energy spectrum of secondaries
G4double energy = track->GetKineticEnergy();
G4double charge = track->GetDefinition()->GetPDGCharge();
G4AnalysisManager* analysisManager = G4AnalysisManager::Instance();
if (charge != 0.){
analysisManager->FillH1(5,energy);
/*
G4ParticleDefinition* p = track->GetDefinition();
// Only filling for electrons
if (p->GetPDGEncoding() == 11){
G4String procName = track->GetCreatorProcess()->GetProcessName();
if(procName == "hIoni")
analysisManager->FillH1(7,energy);
if(procName == "compt")
analysisManager->FillH1(8,energy);
//analysisManager->FillH1(5,energy);
}
*/
}
else analysisManager->FillH1(6,energy);
// return fKill;
return fUrgent;
}
| 25.745098 | 74 | 0.678599 | murffer |
7b75e8006e2687d18e5b2b5875ce4226d7fdd846 | 14,345 | cpp | C++ | NOLF/ObjectDLL/Editable.cpp | rastrup/no-one-lives-forever | dfbe22fb4cc01bf7e5f54a79174fa8f108dd2f54 | [
"Unlicense"
] | 65 | 2015-02-28T03:35:14.000Z | 2021-09-23T05:43:33.000Z | NOLF/ObjectDLL/Editable.cpp | rastrup/no-one-lives-forever | dfbe22fb4cc01bf7e5f54a79174fa8f108dd2f54 | [
"Unlicense"
] | null | null | null | NOLF/ObjectDLL/Editable.cpp | rastrup/no-one-lives-forever | dfbe22fb4cc01bf7e5f54a79174fa8f108dd2f54 | [
"Unlicense"
] | 27 | 2015-02-28T07:42:01.000Z | 2022-02-11T01:35:20.000Z | //----------------------------------------------------------
//
// MODULE : Editable.cpp
//
// PURPOSE : Editable aggreate
//
// CREATED : 3/10/99
//
//----------------------------------------------------------
#include "stdafx.h"
#include "Editable.h"
#include "iltserver.h"
#include "ObjectMsgs.h"
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::CEditable()
//
// PURPOSE: Constructor
//
// ----------------------------------------------------------------------- //
CEditable::CEditable() : IAggregate()
{
m_propList.Init(LTTRUE);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::~CEditable()
//
// PURPOSE: Destructor
//
// ----------------------------------------------------------------------- //
CEditable::~CEditable()
{
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::EngineMessageFn()
//
// PURPOSE: Handle engine messages
//
// ----------------------------------------------------------------------- //
uint32 CEditable::ObjectMessageFn(LPBASECLASS pObject, HOBJECT hSender, uint32 messageID, HMESSAGEREAD hRead)
{
switch(messageID)
{
case MID_TRIGGER:
{
const char* szMsg = (const char*)g_pLTServer->ReadFromMessageDWord(hRead);
TriggerMsg(pObject, hSender, szMsg);
}
break;
default : break;
}
return IAggregate::ObjectMessageFn(pObject, hSender, messageID, hRead);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::AddFloatProp
//
// PURPOSE: Add a float prop to our list
//
// ----------------------------------------------------------------------- //
void CEditable::AddFloatProp(char* pPropName, LTFLOAT* pPropAddress)
{
if (!pPropName || !pPropAddress) return;
CPropDef* pProp = debug_new(CPropDef);
if (!pProp) return;
pProp->Init(pPropName, CPropDef::PT_FLOAT_TYPE, (void*)pPropAddress);
m_propList.Add(pProp);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::AddDWordProp
//
// PURPOSE: Add a dword prop to our list
//
// ----------------------------------------------------------------------- //
void CEditable::AddDWordProp(char* pPropName, uint32* pPropAddress)
{
if (!pPropName || !pPropAddress) return;
CPropDef* pProp = debug_new(CPropDef);
if (!pProp) return;
pProp->Init(pPropName, CPropDef::PT_DWORD_TYPE, (void*)pPropAddress);
m_propList.Add(pProp);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::AddByteProp
//
// PURPOSE: Add a byte prop to our list
//
// ----------------------------------------------------------------------- //
void CEditable::AddByteProp(char* pPropName, uint8* pPropAddress)
{
if (!pPropName || !pPropAddress) return;
CPropDef* pProp = debug_new(CPropDef);
if (!pProp) return;
pProp->Init(pPropName, CPropDef::PT_BYTE_TYPE, (void*)pPropAddress);
m_propList.Add(pProp);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::AddBoolProp
//
// PURPOSE: Add a bool prop to our list
//
// ----------------------------------------------------------------------- //
void CEditable::AddBoolProp(char* pPropName, LTBOOL* pPropAddress)
{
if (!pPropName || !pPropAddress) return;
CPropDef* pProp = debug_new(CPropDef);
if (!pProp) return;
pProp->Init(pPropName, CPropDef::PT_BOOL_TYPE, (void*)pPropAddress);
m_propList.Add(pProp);
}
// ----------------------------------------------------------------------- //
//
// ROUTINE: CEditable::AddVectorProp
//
// PURPOSE: Add a vector prop to our list
//
// ----------------------------------------------------------------------- //
void CEditable::AddVectorProp(char* pPropName, LTVector* pPropAddress)
{
if (!pPropName || !pPropAddress) return;
CPropDef* pProp = debug_new(CPropDef);
if (!pProp) return;
pProp->Init(pPropName, CPropDef::PT_VECTOR_TYPE, (void*)pPropAddress);
m_propList.Add(pProp);
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CEditable::TriggerMsg()
//
// PURPOSE: Process trigger messages
//
// --------------------------------------------------------------------------- //
void CEditable::TriggerMsg(LPBASECLASS pObject, HOBJECT hSender, const char* szMsg)
{
if (!szMsg) return;
ILTCommon* pCommon = g_pLTServer->Common();
if (!pCommon) return;
// ConParse does not destroy szMsg, so this is safe
ConParse parse;
parse.Init((char*)szMsg);
while (pCommon->Parse(&parse) == LT_OK)
{
if (parse.m_nArgs > 0 && parse.m_Args[0])
{
if (_stricmp(parse.m_Args[0], "DISPLAYPROPERTIES") == 0)
{
ListProperties(pObject);
}
else if (_stricmp(parse.m_Args[0], "EDIT") == 0)
{
if (parse.m_nArgs > 2)
{
EditProperty(pObject, parse.m_Args[1], parse.m_Args[2]);
}
}
}
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CEditable::EditProperty()
//
// PURPOSE: Edit the specified property
//
// --------------------------------------------------------------------------- //
void CEditable::EditProperty(LPBASECLASS pObject, char* pPropName, char* pPropValue)
{
if (!pObject || !pPropName || !pPropValue) return;
// Edit the appropriate property...
CPropDef** pCur = m_propList.GetItem(TLIT_FIRST);
CPropDef* pPropDef = LTNULL;
while (pCur)
{
pPropDef = *pCur;
if (pPropDef)
{
char* pName = pPropDef->GetPropName();
if (pName && _strnicmp(pName, pPropName, strlen(pName)) == 0)
{
if (pPropDef->SetValue(pPropName, pPropValue))
{
ListProperties(pObject);
}
else
{
g_pLTServer->CPrint("Couldn't set '%s' to '%s'!", pName, pPropValue);
}
return;
}
}
pCur = m_propList.GetItem(TLIT_NEXT);
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CEditable::ListProperties()
//
// PURPOSE: List our properties/values
//
// --------------------------------------------------------------------------- //
void CEditable::ListProperties(LPBASECLASS pObject)
{
if (!pObject) return;
g_pLTServer->CPrint("Object Properties------------------------");
g_pLTServer->CPrint("'Name' = '%s'", g_pLTServer->GetObjectName(pObject->m_hObject));
CPropDef** pCur = m_propList.GetItem(TLIT_FIRST);
CPropDef* pPropDef = LTNULL;
while (pCur)
{
pPropDef = *pCur;
if (pPropDef)
{
char* pPropName = pPropDef->GetPropName();
CString str;
pPropDef->GetStringValue(str);
g_pLTServer->CPrint("'%s' = %s", pPropName ? pPropName : "(Invalid name)",
str.GetLength() > 1 ? str.GetBuffer(1) : "(Invalid value)");
}
pCur = m_propList.GetItem(TLIT_NEXT);
}
g_pLTServer->CPrint("-----------------------------------------");
}
// --------------------------------------------------------------------------- //
// --------------------------------------------------------------------------- //
//
// CPropDef class methods
//
// --------------------------------------------------------------------------- //
// --------------------------------------------------------------------------- //
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::CPropDef()
//
// PURPOSE: Constructor
//
// --------------------------------------------------------------------------- //
CPropDef::CPropDef()
{
m_strPropName = LTNULL;
m_eType = PT_UNKNOWN_TYPE;
m_pAddress = LTNULL;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::~CPropDef()
//
// PURPOSE: Destructor
//
// --------------------------------------------------------------------------- //
CPropDef::~CPropDef()
{
if (m_strPropName)
{
g_pLTServer->FreeString(m_strPropName);
}
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::Init()
//
// PURPOSE: Set up our data members
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::Init(char* pName, PropType eType, void* pAddress)
{
if (m_strPropName || !pName) return LTFALSE;
m_strPropName = g_pLTServer->CreateString(pName);
m_eType = eType;
m_pAddress = pAddress;
return LTTRUE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetFloatValue()
//
// PURPOSE: Get the value of the property as a float
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::GetFloatValue(LTFLOAT & fRet)
{
if (m_eType == PT_FLOAT_TYPE && m_pAddress)
{
fRet = *((LTFLOAT*)m_pAddress);
return LTTRUE;
}
return LTFALSE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetDWordValue()
//
// PURPOSE: Get the value of the property as a dword
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::GetDWordValue(uint32 & dwRet)
{
if (m_eType == PT_DWORD_TYPE && m_pAddress)
{
dwRet = *((uint32*)m_pAddress);
return LTTRUE;
}
return LTFALSE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetByteValue()
//
// PURPOSE: Get the value of the property as a byte
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::GetByteValue(uint8 & nRet)
{
if (m_eType == PT_BYTE_TYPE && m_pAddress)
{
nRet = *((uint8*)m_pAddress);
return LTTRUE;
}
return LTFALSE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetBoolValue()
//
// PURPOSE: Get the value of the property as a bool
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::GetBoolValue(LTBOOL & bRet)
{
if (m_eType == PT_BOOL_TYPE && m_pAddress)
{
bRet = *((LTBOOL*)m_pAddress);
return LTTRUE;
}
return LTFALSE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetVectorValue()
//
// PURPOSE: Get the value of the property as a vector
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::GetVectorValue(LTVector & vRet)
{
if (m_eType == PT_VECTOR_TYPE && m_pAddress)
{
vRet = *((LTVector*)m_pAddress);
return LTTRUE;
}
return LTFALSE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetPropName()
//
// PURPOSE: Get the name of the property
//
// --------------------------------------------------------------------------- //
char* CPropDef::GetPropName()
{
if (!m_strPropName) return LTNULL;
return g_pLTServer->GetStringData(m_strPropName);
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::GetStringValue()
//
// PURPOSE: Get the value of the property as a string
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::GetStringValue(CString & str)
{
switch (m_eType)
{
case PT_BYTE_TYPE:
{
uint8 nVal;
if (GetByteValue(nVal))
{
str.Format("%d", nVal);
return LTTRUE;
}
}
break;
case PT_BOOL_TYPE:
{
LTBOOL bVal;
if (GetBoolValue(bVal))
{
str.Format("%s", bVal ? "True" : "False");
return LTTRUE;
}
}
break;
case PT_FLOAT_TYPE:
{
LTFLOAT fVal;
if (GetFloatValue(fVal))
{
str.Format("%.2f", fVal);
return LTTRUE;
}
}
break;
case PT_VECTOR_TYPE:
{
LTVector vVal;
if (GetVectorValue(vVal))
{
str.Format("(%.2f, %.2f, %.2f)", vVal.x, vVal.y, vVal.z);
return LTTRUE;
}
}
break;
case PT_DWORD_TYPE:
{
uint32 dwVal;
if (GetDWordValue(dwVal))
{
str.Format("%d", dwVal);
return LTTRUE;
}
}
break;
default : break;
}
return LTFALSE;
}
// --------------------------------------------------------------------------- //
//
// ROUTINE: CPropDef::SetValue()
//
// PURPOSE: Set this property to the value specified...
//
// --------------------------------------------------------------------------- //
LTBOOL CPropDef::SetValue(char* pPropName, char* pValue)
{
if (!pPropName || !pValue) return LTFALSE;
switch (m_eType)
{
case PT_BYTE_TYPE:
{
uint8 nVal = (uint8) atol(pValue);
*((uint8*)m_pAddress) = nVal;
}
break;
case PT_BOOL_TYPE:
{
LTBOOL bVal = (LTBOOL) atol(pValue);
*((LTBOOL*)m_pAddress) = bVal;
}
break;
case PT_FLOAT_TYPE:
{
LTFLOAT fVal = (LTFLOAT) atof(pValue);
*((LTFLOAT*)m_pAddress) = fVal;
}
break;
case PT_VECTOR_TYPE:
{
LTFLOAT fVal = (LTFLOAT) atof(pValue);
if (strstr(pPropName, ".x") || strstr(pPropName, ".r"))
{
((LTVector*)m_pAddress)->x = fVal;
}
else if (strstr(pPropName, ".y") || strstr(pPropName, ".g"))
{
((LTVector*)m_pAddress)->y = fVal;
}
else if (strstr(pPropName, ".z") || strstr(pPropName, ".b"))
{
((LTVector*)m_pAddress)->z = fVal;
}
}
break;
case PT_DWORD_TYPE:
{
uint32 dwVal = (uint32) atol(pValue);
*((uint32*)m_pAddress) = dwVal;
}
break;
default : break;
}
return LTTRUE;
} | 24.190556 | 110 | 0.425793 | rastrup |
7b75fcd7ee901aa2bcc22a96bd5cdacaeb41602e | 25,316 | cc | C++ | external/src/blosc/shuffle-sse2.cc | upj977155/TileDB | 1c96c6a0c030e058930ff9d47409865fbfe2178f | [
"MIT"
] | 1,478 | 2017-06-15T13:58:50.000Z | 2022-03-30T13:46:00.000Z | external/src/blosc/shuffle-sse2.cc | upj977155/TileDB | 1c96c6a0c030e058930ff9d47409865fbfe2178f | [
"MIT"
] | 1,435 | 2017-05-25T01:16:18.000Z | 2022-03-31T21:57:06.000Z | external/src/blosc/shuffle-sse2.cc | upj977155/TileDB | 1c96c6a0c030e058930ff9d47409865fbfe2178f | [
"MIT"
] | 169 | 2017-06-09T18:35:45.000Z | 2022-03-13T01:11:18.000Z | /*********************************************************************
Blosc - Blocked Shuffling and Compression Library
Author: Francesc Alted <francesc@blosc.org>
See LICENSES/BLOSC.txt for details about copyright and rights to use.
Modifications for TileDB by Tyler Denniston <tyler@tiledb.io>
**********************************************************************/
#include "shuffle-generic.h"
#include "shuffle-sse2.h"
#ifdef __SSE2__
#include <emmintrin.h>
/* The next is useful for debugging purposes */
#if 0
#include <stdio.h>
#include <string.h>
static void printxmm(__m128i xmm0)
{
uint8_t buf[16];
((__m128i *)buf)[0] = xmm0;
printf("%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x,%x\n",
buf[0], buf[1], buf[2], buf[3],
buf[4], buf[5], buf[6], buf[7],
buf[8], buf[9], buf[10], buf[11],
buf[12], buf[13], buf[14], buf[15]);
}
#endif
namespace blosc {
/* Routine optimized for shuffling a buffer for a type size of 2 bytes. */
static void
shuffle2_sse2(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements)
{
static const size_t bytesoftype = 2;
size_t j;
int k;
uint8_t* dest_for_jth_element;
__m128i xmm0[2], xmm1[2];
for (j = 0; j < vectorizable_elements; j += sizeof(__m128i)) {
/* Fetch 16 elements (32 bytes) then transpose bytes, words and double words. */
for (k = 0; k < 2; k++) {
xmm0[k] = _mm_loadu_si128((__m128i*)(src + (j * bytesoftype) + (k * sizeof(__m128i))));
xmm0[k] = _mm_shufflelo_epi16(xmm0[k], 0xd8);
xmm0[k] = _mm_shufflehi_epi16(xmm0[k], 0xd8);
xmm0[k] = _mm_shuffle_epi32(xmm0[k], 0xd8);
xmm1[k] = _mm_shuffle_epi32(xmm0[k], 0x4e);
xmm0[k] = _mm_unpacklo_epi8(xmm0[k], xmm1[k]);
xmm0[k] = _mm_shuffle_epi32(xmm0[k], 0xd8);
xmm1[k] = _mm_shuffle_epi32(xmm0[k], 0x4e);
xmm0[k] = _mm_unpacklo_epi16(xmm0[k], xmm1[k]);
xmm0[k] = _mm_shuffle_epi32(xmm0[k], 0xd8);
}
/* Transpose quad words */
for (k = 0; k < 1; k++) {
xmm1[k*2] = _mm_unpacklo_epi64(xmm0[k], xmm0[k+1]);
xmm1[k*2+1] = _mm_unpackhi_epi64(xmm0[k], xmm0[k+1]);
}
/* Store the result vectors */
dest_for_jth_element = dest + j;
for (k = 0; k < 2; k++) {
_mm_storeu_si128((__m128i*)(dest_for_jth_element + (k * total_elements)), xmm1[k]);
}
}
}
/* Routine optimized for shuffling a buffer for a type size of 4 bytes. */
static void
shuffle4_sse2(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements)
{
static const size_t bytesoftype = 4;
size_t i;
int j;
uint8_t* dest_for_ith_element;
__m128i xmm0[4], xmm1[4];
for (i = 0; i < vectorizable_elements; i += sizeof(__m128i)) {
/* Fetch 16 elements (64 bytes) then transpose bytes and words. */
for (j = 0; j < 4; j++) {
xmm0[j] = _mm_loadu_si128((__m128i*)(src + (i * bytesoftype) + (j * sizeof(__m128i))));
xmm1[j] = _mm_shuffle_epi32(xmm0[j], 0xd8);
xmm0[j] = _mm_shuffle_epi32(xmm0[j], 0x8d);
xmm0[j] = _mm_unpacklo_epi8(xmm1[j], xmm0[j]);
xmm1[j] = _mm_shuffle_epi32(xmm0[j], 0x04e);
xmm0[j] = _mm_unpacklo_epi16(xmm0[j], xmm1[j]);
}
/* Transpose double words */
for (j = 0; j < 2; j++) {
xmm1[j*2] = _mm_unpacklo_epi32(xmm0[j*2], xmm0[j*2+1]);
xmm1[j*2+1] = _mm_unpackhi_epi32(xmm0[j*2], xmm0[j*2+1]);
}
/* Transpose quad words */
for (j = 0; j < 2; j++) {
xmm0[j*2] = _mm_unpacklo_epi64(xmm1[j], xmm1[j+2]);
xmm0[j*2+1] = _mm_unpackhi_epi64(xmm1[j], xmm1[j+2]);
}
/* Store the result vectors */
dest_for_ith_element = dest + i;
for (j = 0; j < 4; j++) {
_mm_storeu_si128((__m128i*)(dest_for_ith_element + (j * total_elements)), xmm0[j]);
}
}
}
/* Routine optimized for shuffling a buffer for a type size of 8 bytes. */
static void
shuffle8_sse2(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements)
{
static const size_t bytesoftype = 8;
size_t j;
int k, l;
uint8_t* dest_for_jth_element;
__m128i xmm0[8], xmm1[8];
for (j = 0; j < vectorizable_elements; j += sizeof(__m128i)) {
/* Fetch 16 elements (128 bytes) then transpose bytes. */
for (k = 0; k < 8; k++) {
xmm0[k] = _mm_loadu_si128((__m128i*)(src + (j * bytesoftype) + (k * sizeof(__m128i))));
xmm1[k] = _mm_shuffle_epi32(xmm0[k], 0x4e);
xmm1[k] = _mm_unpacklo_epi8(xmm0[k], xmm1[k]);
}
/* Transpose words */
for (k = 0, l = 0; k < 4; k++, l +=2) {
xmm0[k*2] = _mm_unpacklo_epi16(xmm1[l], xmm1[l+1]);
xmm0[k*2+1] = _mm_unpackhi_epi16(xmm1[l], xmm1[l+1]);
}
/* Transpose double words */
for (k = 0, l = 0; k < 4; k++, l++) {
if (k == 2) l += 2;
xmm1[k*2] = _mm_unpacklo_epi32(xmm0[l], xmm0[l+2]);
xmm1[k*2+1] = _mm_unpackhi_epi32(xmm0[l], xmm0[l+2]);
}
/* Transpose quad words */
for (k = 0; k < 4; k++) {
xmm0[k*2] = _mm_unpacklo_epi64(xmm1[k], xmm1[k+4]);
xmm0[k*2+1] = _mm_unpackhi_epi64(xmm1[k], xmm1[k+4]);
}
/* Store the result vectors */
dest_for_jth_element = dest + j;
for (k = 0; k < 8; k++) {
_mm_storeu_si128((__m128i*)(dest_for_jth_element + (k * total_elements)), xmm0[k]);
}
}
}
/* Routine optimized for shuffling a buffer for a type size of 16 bytes. */
static void
shuffle16_sse2(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements)
{
static const size_t bytesoftype = 16;
size_t j;
int k, l;
uint8_t* dest_for_jth_element;
__m128i xmm0[16], xmm1[16];
for (j = 0; j < vectorizable_elements; j += sizeof(__m128i)) {
/* Fetch 16 elements (256 bytes). */
for (k = 0; k < 16; k++) {
xmm0[k] = _mm_loadu_si128((__m128i*)(src + (j * bytesoftype) + (k * sizeof(__m128i))));
}
/* Transpose bytes */
for (k = 0, l = 0; k < 8; k++, l +=2) {
xmm1[k*2] = _mm_unpacklo_epi8(xmm0[l], xmm0[l+1]);
xmm1[k*2+1] = _mm_unpackhi_epi8(xmm0[l], xmm0[l+1]);
}
/* Transpose words */
for (k = 0, l = -2; k < 8; k++, l++) {
if ((k%2) == 0) l += 2;
xmm0[k*2] = _mm_unpacklo_epi16(xmm1[l], xmm1[l+2]);
xmm0[k*2+1] = _mm_unpackhi_epi16(xmm1[l], xmm1[l+2]);
}
/* Transpose double words */
for (k = 0, l = -4; k < 8; k++, l++) {
if ((k%4) == 0) l += 4;
xmm1[k*2] = _mm_unpacklo_epi32(xmm0[l], xmm0[l+4]);
xmm1[k*2+1] = _mm_unpackhi_epi32(xmm0[l], xmm0[l+4]);
}
/* Transpose quad words */
for (k = 0; k < 8; k++) {
xmm0[k*2] = _mm_unpacklo_epi64(xmm1[k], xmm1[k+8]);
xmm0[k*2+1] = _mm_unpackhi_epi64(xmm1[k], xmm1[k+8]);
}
/* Store the result vectors */
dest_for_jth_element = dest + j;
for (k = 0; k < 16; k++) {
_mm_storeu_si128((__m128i*)(dest_for_jth_element + (k * total_elements)), xmm0[k]);
}
}
}
/* Routine optimized for shuffling a buffer for a type size larger than 16 bytes. */
static void
shuffle16_tiled_sse2(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements, const size_t bytesoftype)
{
size_t j;
const size_t vecs_per_el_rem = bytesoftype % sizeof(__m128i);
int k, l;
uint8_t* dest_for_jth_element;
__m128i xmm0[16], xmm1[16];
for (j = 0; j < vectorizable_elements; j += sizeof(__m128i)) {
/* Advance the offset into the type by the vector size (in bytes), unless this is
the initial iteration and the type size is not a multiple of the vector size.
In that case, only advance by the number of bytes necessary so that the number
of remaining bytes in the type will be a multiple of the vector size. */
size_t offset_into_type;
for (offset_into_type = 0; offset_into_type < bytesoftype;
offset_into_type += (offset_into_type == 0 && vecs_per_el_rem > 0 ? vecs_per_el_rem : sizeof(__m128i))) {
/* Fetch elements in groups of 256 bytes */
const uint8_t* const src_with_offset = src + offset_into_type;
for (k = 0; k < 16; k++) {
xmm0[k] = _mm_loadu_si128((__m128i*)(src_with_offset + (j + k) * bytesoftype));
}
/* Transpose bytes */
for (k = 0, l = 0; k < 8; k++, l +=2) {
xmm1[k*2] = _mm_unpacklo_epi8(xmm0[l], xmm0[l+1]);
xmm1[k*2+1] = _mm_unpackhi_epi8(xmm0[l], xmm0[l+1]);
}
/* Transpose words */
for (k = 0, l = -2; k < 8; k++, l++) {
if ((k%2) == 0) l += 2;
xmm0[k*2] = _mm_unpacklo_epi16(xmm1[l], xmm1[l+2]);
xmm0[k*2+1] = _mm_unpackhi_epi16(xmm1[l], xmm1[l+2]);
}
/* Transpose double words */
for (k = 0, l = -4; k < 8; k++, l++) {
if ((k%4) == 0) l += 4;
xmm1[k*2] = _mm_unpacklo_epi32(xmm0[l], xmm0[l+4]);
xmm1[k*2+1] = _mm_unpackhi_epi32(xmm0[l], xmm0[l+4]);
}
/* Transpose quad words */
for (k = 0; k < 8; k++) {
xmm0[k*2] = _mm_unpacklo_epi64(xmm1[k], xmm1[k+8]);
xmm0[k*2+1] = _mm_unpackhi_epi64(xmm1[k], xmm1[k+8]);
}
/* Store the result vectors */
dest_for_jth_element = dest + j;
for (k = 0; k < 16; k++) {
_mm_storeu_si128((__m128i*)(dest_for_jth_element + (total_elements * (offset_into_type + k))), xmm0[k]);
}
}
}
}
/* Routine optimized for unshuffling a buffer for a type size of 2 bytes. */
static void
unshuffle2_sse2(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements)
{
static const size_t bytesoftype = 2;
size_t i;
int j;
__m128i xmm0[2], xmm1[2];
for (i = 0; i < vectorizable_elements; i += sizeof(__m128i)) {
/* Load 16 elements (32 bytes) into 2 XMM registers. */
const uint8_t* const src_for_ith_element = src + i;
for (j = 0; j < 2; j++) {
xmm0[j] = _mm_loadu_si128((__m128i*)(src_for_ith_element + (j * total_elements)));
}
/* Shuffle bytes */
/* Compute the low 32 bytes */
xmm1[0] = _mm_unpacklo_epi8(xmm0[0], xmm0[1]);
/* Compute the hi 32 bytes */
xmm1[1] = _mm_unpackhi_epi8(xmm0[0], xmm0[1]);
/* Store the result vectors in proper order */
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (0 * sizeof(__m128i))), xmm1[0]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (1 * sizeof(__m128i))), xmm1[1]);
}
}
/* Routine optimized for unshuffling a buffer for a type size of 4 bytes. */
static void
unshuffle4_sse2(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements)
{
static const size_t bytesoftype = 4;
size_t i;
int j;
__m128i xmm0[4], xmm1[4];
for (i = 0; i < vectorizable_elements; i += sizeof(__m128i)) {
/* Load 16 elements (64 bytes) into 4 XMM registers. */
const uint8_t* const src_for_ith_element = src + i;
for (j = 0; j < 4; j++) {
xmm0[j] = _mm_loadu_si128((__m128i*)(src_for_ith_element + (j * total_elements)));
}
/* Shuffle bytes */
for (j = 0; j < 2; j++) {
/* Compute the low 32 bytes */
xmm1[j] = _mm_unpacklo_epi8(xmm0[j*2], xmm0[j*2+1]);
/* Compute the hi 32 bytes */
xmm1[2+j] = _mm_unpackhi_epi8(xmm0[j*2], xmm0[j*2+1]);
}
/* Shuffle 2-byte words */
for (j = 0; j < 2; j++) {
/* Compute the low 32 bytes */
xmm0[j] = _mm_unpacklo_epi16(xmm1[j*2], xmm1[j*2+1]);
/* Compute the hi 32 bytes */
xmm0[2+j] = _mm_unpackhi_epi16(xmm1[j*2], xmm1[j*2+1]);
}
/* Store the result vectors in proper order */
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (0 * sizeof(__m128i))), xmm0[0]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (1 * sizeof(__m128i))), xmm0[2]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (2 * sizeof(__m128i))), xmm0[1]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (3 * sizeof(__m128i))), xmm0[3]);
}
}
/* Routine optimized for unshuffling a buffer for a type size of 8 bytes. */
static void
unshuffle8_sse2(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements)
{
static const size_t bytesoftype = 8;
size_t i;
int j;
__m128i xmm0[8], xmm1[8];
for (i = 0; i < vectorizable_elements; i += sizeof(__m128i)) {
/* Load 16 elements (128 bytes) into 8 XMM registers. */
const uint8_t* const src_for_ith_element = src + i;
for (j = 0; j < 8; j++) {
xmm0[j] = _mm_loadu_si128((__m128i*)(src_for_ith_element + (j * total_elements)));
}
/* Shuffle bytes */
for (j = 0; j < 4; j++) {
/* Compute the low 32 bytes */
xmm1[j] = _mm_unpacklo_epi8(xmm0[j*2], xmm0[j*2+1]);
/* Compute the hi 32 bytes */
xmm1[4+j] = _mm_unpackhi_epi8(xmm0[j*2], xmm0[j*2+1]);
}
/* Shuffle 2-byte words */
for (j = 0; j < 4; j++) {
/* Compute the low 32 bytes */
xmm0[j] = _mm_unpacklo_epi16(xmm1[j*2], xmm1[j*2+1]);
/* Compute the hi 32 bytes */
xmm0[4+j] = _mm_unpackhi_epi16(xmm1[j*2], xmm1[j*2+1]);
}
/* Shuffle 4-byte dwords */
for (j = 0; j < 4; j++) {
/* Compute the low 32 bytes */
xmm1[j] = _mm_unpacklo_epi32(xmm0[j*2], xmm0[j*2+1]);
/* Compute the hi 32 bytes */
xmm1[4+j] = _mm_unpackhi_epi32(xmm0[j*2], xmm0[j*2+1]);
}
/* Store the result vectors in proper order */
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (0 * sizeof(__m128i))), xmm1[0]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (1 * sizeof(__m128i))), xmm1[4]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (2 * sizeof(__m128i))), xmm1[2]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (3 * sizeof(__m128i))), xmm1[6]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (4 * sizeof(__m128i))), xmm1[1]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (5 * sizeof(__m128i))), xmm1[5]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (6 * sizeof(__m128i))), xmm1[3]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (7 * sizeof(__m128i))), xmm1[7]);
}
}
/* Routine optimized for unshuffling a buffer for a type size of 16 bytes. */
static void
unshuffle16_sse2(uint8_t* const dest, const uint8_t* const src,
const size_t vectorizable_elements, const size_t total_elements)
{
static const size_t bytesoftype = 16;
size_t i;
int j;
__m128i xmm1[16], xmm2[16];
for (i = 0; i < vectorizable_elements; i += sizeof(__m128i)) {
/* Load 16 elements (256 bytes) into 16 XMM registers. */
const uint8_t* const src_for_ith_element = src + i;
for (j = 0; j < 16; j++) {
xmm1[j] = _mm_loadu_si128((__m128i*)(src_for_ith_element + (j * total_elements)));
}
/* Shuffle bytes */
for (j = 0; j < 8; j++) {
/* Compute the low 32 bytes */
xmm2[j] = _mm_unpacklo_epi8(xmm1[j*2], xmm1[j*2+1]);
/* Compute the hi 32 bytes */
xmm2[8+j] = _mm_unpackhi_epi8(xmm1[j*2], xmm1[j*2+1]);
}
/* Shuffle 2-byte words */
for (j = 0; j < 8; j++) {
/* Compute the low 32 bytes */
xmm1[j] = _mm_unpacklo_epi16(xmm2[j*2], xmm2[j*2+1]);
/* Compute the hi 32 bytes */
xmm1[8+j] = _mm_unpackhi_epi16(xmm2[j*2], xmm2[j*2+1]);
}
/* Shuffle 4-byte dwords */
for (j = 0; j < 8; j++) {
/* Compute the low 32 bytes */
xmm2[j] = _mm_unpacklo_epi32(xmm1[j*2], xmm1[j*2+1]);
/* Compute the hi 32 bytes */
xmm2[8+j] = _mm_unpackhi_epi32(xmm1[j*2], xmm1[j*2+1]);
}
/* Shuffle 8-byte qwords */
for (j = 0; j < 8; j++) {
/* Compute the low 32 bytes */
xmm1[j] = _mm_unpacklo_epi64(xmm2[j*2], xmm2[j*2+1]);
/* Compute the hi 32 bytes */
xmm1[8+j] = _mm_unpackhi_epi64(xmm2[j*2], xmm2[j*2+1]);
}
/* Store the result vectors in proper order */
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (0 * sizeof(__m128i))), xmm1[0]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (1 * sizeof(__m128i))), xmm1[8]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (2 * sizeof(__m128i))), xmm1[4]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (3 * sizeof(__m128i))), xmm1[12]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (4 * sizeof(__m128i))), xmm1[2]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (5 * sizeof(__m128i))), xmm1[10]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (6 * sizeof(__m128i))), xmm1[6]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (7 * sizeof(__m128i))), xmm1[14]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (8 * sizeof(__m128i))), xmm1[1]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (9 * sizeof(__m128i))), xmm1[9]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (10 * sizeof(__m128i))), xmm1[5]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (11 * sizeof(__m128i))), xmm1[13]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (12 * sizeof(__m128i))), xmm1[3]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (13 * sizeof(__m128i))), xmm1[11]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (14 * sizeof(__m128i))), xmm1[7]);
_mm_storeu_si128((__m128i*)(dest + (i * bytesoftype) + (15 * sizeof(__m128i))), xmm1[15]);
}
}
/* Routine optimized for unshuffling a buffer for a type size larger than 16 bytes. */
static void
unshuffle16_tiled_sse2(uint8_t* const dest, const uint8_t* const orig,
const size_t vectorizable_elements, const size_t total_elements, const size_t bytesoftype)
{
size_t i;
const size_t vecs_per_el_rem = bytesoftype % sizeof(__m128i);
int j;
uint8_t* dest_with_offset;
__m128i xmm1[16], xmm2[16];
/* The unshuffle loops are inverted (compared to shuffle_tiled16_sse2)
to optimize cache utilization. */
size_t offset_into_type;
for (offset_into_type = 0; offset_into_type < bytesoftype;
offset_into_type += (offset_into_type == 0 && vecs_per_el_rem > 0 ? vecs_per_el_rem : sizeof(__m128i))) {
for (i = 0; i < vectorizable_elements; i += sizeof(__m128i)) {
/* Load the first 128 bytes in 16 XMM registers */
const uint8_t* const src_for_ith_element = orig + i;
for (j = 0; j < 16; j++) {
xmm1[j] = _mm_loadu_si128((__m128i*)(src_for_ith_element + (total_elements * (offset_into_type + j))));
}
/* Shuffle bytes */
for (j = 0; j < 8; j++) {
/* Compute the low 32 bytes */
xmm2[j] = _mm_unpacklo_epi8(xmm1[j*2], xmm1[j*2+1]);
/* Compute the hi 32 bytes */
xmm2[8+j] = _mm_unpackhi_epi8(xmm1[j*2], xmm1[j*2+1]);
}
/* Shuffle 2-byte words */
for (j = 0; j < 8; j++) {
/* Compute the low 32 bytes */
xmm1[j] = _mm_unpacklo_epi16(xmm2[j*2], xmm2[j*2+1]);
/* Compute the hi 32 bytes */
xmm1[8+j] = _mm_unpackhi_epi16(xmm2[j*2], xmm2[j*2+1]);
}
/* Shuffle 4-byte dwords */
for (j = 0; j < 8; j++) {
/* Compute the low 32 bytes */
xmm2[j] = _mm_unpacklo_epi32(xmm1[j*2], xmm1[j*2+1]);
/* Compute the hi 32 bytes */
xmm2[8+j] = _mm_unpackhi_epi32(xmm1[j*2], xmm1[j*2+1]);
}
/* Shuffle 8-byte qwords */
for (j = 0; j < 8; j++) {
/* Compute the low 32 bytes */
xmm1[j] = _mm_unpacklo_epi64(xmm2[j*2], xmm2[j*2+1]);
/* Compute the hi 32 bytes */
xmm1[8+j] = _mm_unpackhi_epi64(xmm2[j*2], xmm2[j*2+1]);
}
/* Store the result vectors in proper order */
dest_with_offset = dest + offset_into_type;
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 0) * bytesoftype), xmm1[0]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 1) * bytesoftype), xmm1[8]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 2) * bytesoftype), xmm1[4]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 3) * bytesoftype), xmm1[12]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 4) * bytesoftype), xmm1[2]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 5) * bytesoftype), xmm1[10]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 6) * bytesoftype), xmm1[6]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 7) * bytesoftype), xmm1[14]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 8) * bytesoftype), xmm1[1]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 9) * bytesoftype), xmm1[9]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 10) * bytesoftype), xmm1[5]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 11) * bytesoftype), xmm1[13]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 12) * bytesoftype), xmm1[3]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 13) * bytesoftype), xmm1[11]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 14) * bytesoftype), xmm1[7]);
_mm_storeu_si128((__m128i*)(dest_with_offset + (i + 15) * bytesoftype), xmm1[15]);
}
}
}
/* Shuffle a block. This can never fail. */
void
shuffle_sse2(const size_t bytesoftype, const size_t blocksize,
const uint8_t* const _src, uint8_t* const _dest) {
const size_t vectorized_chunk_size = bytesoftype * sizeof(__m128i);
/* If the blocksize is not a multiple of both the typesize and
the vector size, round the blocksize down to the next value
which is a multiple of both. The vectorized shuffle can be
used for that portion of the data, and the naive implementation
can be used for the remaining portion. */
const size_t vectorizable_bytes = blocksize - (blocksize % vectorized_chunk_size);
const size_t vectorizable_elements = vectorizable_bytes / bytesoftype;
const size_t total_elements = blocksize / bytesoftype;
/* If the block size is too small to be vectorized,
use the generic implementation. */
if (blocksize < vectorized_chunk_size) {
shuffle_generic(bytesoftype, blocksize, _src, _dest);
return;
}
/* Optimized shuffle implementations */
switch (bytesoftype)
{
case 2:
shuffle2_sse2(_dest, _src, vectorizable_elements, total_elements);
break;
case 4:
shuffle4_sse2(_dest, _src, vectorizable_elements, total_elements);
break;
case 8:
shuffle8_sse2(_dest, _src, vectorizable_elements, total_elements);
break;
case 16:
shuffle16_sse2(_dest, _src, vectorizable_elements, total_elements);
break;
default:
if (bytesoftype > sizeof(__m128i)) {
shuffle16_tiled_sse2(_dest, _src, vectorizable_elements, total_elements, bytesoftype);
}
else {
/* Non-optimized shuffle */
shuffle_generic(bytesoftype, blocksize, _src, _dest);
/* The non-optimized function covers the whole buffer,
so we're done processing here. */
return;
}
}
/* If the buffer had any bytes at the end which couldn't be handled
by the vectorized implementations, use the non-optimized version
to finish them up. */
if (vectorizable_bytes < blocksize) {
shuffle_generic_inline(bytesoftype, vectorizable_bytes, blocksize, _src, _dest);
}
}
/* Unshuffle a block. This can never fail. */
void
unshuffle_sse2(const size_t bytesoftype, const size_t blocksize,
const uint8_t* const _src, uint8_t* const _dest) {
const size_t vectorized_chunk_size = bytesoftype * sizeof(__m128i);
/* If the blocksize is not a multiple of both the typesize and
the vector size, round the blocksize down to the next value
which is a multiple of both. The vectorized unshuffle can be
used for that portion of the data, and the naive implementation
can be used for the remaining portion. */
const size_t vectorizable_bytes = blocksize - (blocksize % vectorized_chunk_size);
const size_t vectorizable_elements = vectorizable_bytes / bytesoftype;
const size_t total_elements = blocksize / bytesoftype;
/* If the block size is too small to be vectorized,
use the generic implementation. */
if (blocksize < vectorized_chunk_size) {
unshuffle_generic(bytesoftype, blocksize, _src, _dest);
return;
}
/* Optimized unshuffle implementations */
switch (bytesoftype)
{
case 2:
unshuffle2_sse2(_dest, _src, vectorizable_elements, total_elements);
break;
case 4:
unshuffle4_sse2(_dest, _src, vectorizable_elements, total_elements);
break;
case 8:
unshuffle8_sse2(_dest, _src, vectorizable_elements, total_elements);
break;
case 16:
unshuffle16_sse2(_dest, _src, vectorizable_elements, total_elements);
break;
default:
if (bytesoftype > sizeof(__m128i)) {
unshuffle16_tiled_sse2(_dest, _src, vectorizable_elements, total_elements, bytesoftype);
}
else {
/* Non-optimized unshuffle */
unshuffle_generic(bytesoftype, blocksize, _src, _dest);
/* The non-optimized function covers the whole buffer,
so we're done processing here. */
return;
}
}
/* If the buffer had any bytes at the end which couldn't be handled
by the vectorized implementations, use the non-optimized version
to finish them up. */
if (vectorizable_bytes < blocksize) {
unshuffle_generic_inline(bytesoftype, vectorizable_bytes, blocksize, _src, _dest);
}
}
}
#endif | 40.184127 | 112 | 0.622808 | upj977155 |
7b77bac2a43768468ac9619b6160875f737cbb8f | 628 | cpp | C++ | W1/Project 1/Source.cpp | katookei/Code202 | 0b046e9f8812de00405c14e512da50c8c6ece378 | [
"MIT"
] | null | null | null | W1/Project 1/Source.cpp | katookei/Code202 | 0b046e9f8812de00405c14e512da50c8c6ece378 | [
"MIT"
] | null | null | null | W1/Project 1/Source.cpp | katookei/Code202 | 0b046e9f8812de00405c14e512da50c8c6ece378 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include "Header.h"
using namespace std;
void fraction::readfile(fraction &b)
{
ifstream fou;
int data[10];
fou.open("a.txt");
for (int i = 0; i < 4; i++)
{
fou >> data[i];
}
fou.close();
nu = data[0]; de = data[1];
b.nu = data[2]; b.de = data[3];
cout << "Fraction 1: " << nu << "/" << de << endl;
cout << "Fraction 2: " << b.nu << "/" << b.de << endl;
}
void fraction::compare(fraction b)
{
if (nu*b.de - de* b.nu > 0)
cout << "f1>f2";
else if (nu*b.de - de * b.nu < 0)
cout << "f1<f2";
else
cout << "f1=f2";
} | 19.625 | 56 | 0.509554 | katookei |
7b798a71b278bd50752db3b6da6a429f32ea77d7 | 4,550 | cpp | C++ | butano/src/bn_hdma_manager.cpp | laqieer/butano | 986ec1d235922fbe7acafa7564a911085d3a9c6e | [
"Zlib"
] | 1 | 2022-02-06T10:02:14.000Z | 2022-02-06T10:02:14.000Z | butano/src/bn_hdma_manager.cpp | laqieer/butano | 986ec1d235922fbe7acafa7564a911085d3a9c6e | [
"Zlib"
] | null | null | null | butano/src/bn_hdma_manager.cpp | laqieer/butano | 986ec1d235922fbe7acafa7564a911085d3a9c6e | [
"Zlib"
] | null | null | null | /*
* Copyright (c) 2020-2022 Gustavo Valiente gustavo.valiente@protonmail.com
* zlib License, see LICENSE file.
*/
#include "bn_hdma_manager.h"
#include "bn_display.h"
#include "../hw/include/bn_hw_hdma.h"
#include "../hw/include/bn_hw_memory.h"
#include "bn_hdma.cpp.h"
namespace bn::hdma_manager
{
namespace
{
class state
{
public:
const uint16_t* source_ptr = nullptr;
uint16_t* destination_ptr = nullptr;
int elements = 0;
};
class entry
{
public:
explicit entry(int channel) :
_channel(int8_t(channel))
{
}
[[nodiscard]] bool running() const
{
return _next_state().elements;
}
void disable()
{
hw::hdma::stop(_channel);
}
void start(const uint16_t& source_ref, int elements, uint16_t& destination_ref)
{
state& next_state = _next_state();
next_state.source_ptr = &source_ref;
next_state.destination_ptr = &destination_ref;
next_state.elements = elements;
_updated = true;
}
void stop()
{
state& next_state = _next_state();
next_state.elements = 0;
_updated = true;
}
void force_stop()
{
_states[0].elements = 0;
_states[1].elements = 0;
_updated = false;
disable();
}
void update()
{
if(_updated)
{
_updated = false;
if(_current_state_index)
{
_current_state_index = 0;
_states[1] = _states[0];
}
else
{
_current_state_index = 1;
_states[0] = _states[1];
}
}
}
void commit()
{
const state& current_state = _current_state();
if(int elements = current_state.elements)
{
const uint16_t* source_ptr = current_state.source_ptr;
uint16_t* destination_ptr = current_state.destination_ptr;
hw::memory::copy_half_words(source_ptr + ((display::height() - 1) * elements),
elements, destination_ptr);
hw::hdma::start(_channel, source_ptr, elements, destination_ptr);
}
else
{
hw::hdma::stop(_channel);
}
}
private:
state _states[2];
int8_t _channel = 0;
int8_t _current_state_index = 0;
bool _updated = false;
[[nodiscard]] const state& _current_state() const
{
return _states[_current_state_index];
}
[[nodiscard]] state& _current_state()
{
return _states[_current_state_index];
}
[[nodiscard]] const state& _next_state() const
{
return _states[(_current_state_index + 1) % 2];
}
[[nodiscard]] state& _next_state()
{
return _states[(_current_state_index + 1) % 2];
}
};
class static_data
{
public:
entry low_priority_entry = entry(hw::hdma::low_priority_channel());
entry high_priority_entry = entry(hw::hdma::high_priority_channel());
};
BN_DATA_EWRAM static_data data;
}
void enable()
{
commit();
}
void disable()
{
data.low_priority_entry.disable();
data.high_priority_entry.disable();
}
void force_stop()
{
data.low_priority_entry.force_stop();
data.high_priority_entry.force_stop();
}
bool low_priority_running()
{
return data.low_priority_entry.running();
}
void low_priority_start(const uint16_t& source_ref, int elements, uint16_t& destination_ref)
{
data.low_priority_entry.start(source_ref, elements, destination_ref);
}
void low_priority_stop()
{
data.low_priority_entry.stop();
}
bool high_priority_running()
{
return data.high_priority_entry.running();
}
void high_priority_start(const uint16_t& source_ref, int elements, uint16_t& destination_ref)
{
data.high_priority_entry.start(source_ref, elements, destination_ref);
}
void high_priority_stop()
{
data.high_priority_entry.stop();
}
void update()
{
data.low_priority_entry.update();
data.high_priority_entry.update();
}
void commit()
{
data.low_priority_entry.commit();
data.high_priority_entry.commit();
}
}
| 22.087379 | 94 | 0.560879 | laqieer |
7b7bbf24f4684cf7cc5e4a503a3f84acb9ec4e7a | 1,173 | cc | C++ | src/ufo/predictors/Constant.cc | JCSDA/ufo | 69a6475f478306dd4d4f6728705fe0cd205752c7 | [
"Apache-2.0"
] | 4 | 2020-12-04T08:26:06.000Z | 2021-11-20T01:18:47.000Z | src/ufo/predictors/Constant.cc | JCSDA/ufo | 69a6475f478306dd4d4f6728705fe0cd205752c7 | [
"Apache-2.0"
] | 21 | 2020-10-30T08:57:16.000Z | 2021-05-17T15:11:20.000Z | src/ufo/predictors/Constant.cc | JCSDA/ufo | 69a6475f478306dd4d4f6728705fe0cd205752c7 | [
"Apache-2.0"
] | 8 | 2020-11-04T00:10:11.000Z | 2021-11-14T09:18:14.000Z | /*
* (C) Copyright 2020 UCAR
*
* This software is licensed under the terms of the Apache Licence Version 2.0
* which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
*/
#include <string>
#include "ufo/predictors/Constant.h"
#include "ioda/ObsSpace.h"
namespace ufo {
static PredictorMaker<Constant> makerFuncConstant_("constant");
// -----------------------------------------------------------------------------
Constant::Constant(const Parameters_ & parameters, const oops::Variables & vars)
: PredictorBase(parameters, vars) {
}
// -----------------------------------------------------------------------------
void Constant::compute(const ioda::ObsSpace & odb,
const GeoVaLs &,
const ObsDiagnostics &,
ioda::ObsVector & out) const {
const std::size_t nlocs = out.nlocs();
const std::size_t nvars = out.nvars();
for (std::size_t jloc = 0; jloc < nlocs; ++jloc) {
for (std::size_t jvar = 0; jvar < nvars; ++jvar) {
out[jloc*nvars+jvar] = 1.0;
}
}
}
// -----------------------------------------------------------------------------
} // namespace ufo
| 27.928571 | 80 | 0.500426 | JCSDA |
7b80fc0bde60c3e98bcde8a0d787d1c3cac08978 | 2,706 | cpp | C++ | apps/hls_examples/hls_support/syn_target.cpp | akifoezkan/Halide-HLS | 1eee3f38f32722f3e725c29a5b7a084275062a7f | [
"MIT"
] | 71 | 2016-11-17T19:22:21.000Z | 2022-01-10T10:03:58.000Z | apps/hls_examples/hls_support/syn_target.cpp | akifoezkan/Halide-HLS | 1eee3f38f32722f3e725c29a5b7a084275062a7f | [
"MIT"
] | 30 | 2017-02-02T21:03:33.000Z | 2018-06-27T20:49:31.000Z | apps/hls_examples/hls_support/syn_target.cpp | akifoezkan/Halide-HLS | 1eee3f38f32722f3e725c29a5b7a084275062a7f | [
"MIT"
] | 22 | 2017-04-16T11:44:34.000Z | 2022-03-26T13:27:10.000Z | #include "Linebuffer.h"
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
void syn_target(hls::stream<PackedStencil<uint8_t, 2, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 2, 3> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<20, 12>(input_stream, output_stream);
}
void syn_target_3D2D1D(hls::stream<PackedStencil<uint8_t, 1, 1, 1, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 3, 3, 3, 1> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<32, 32, 32, 1>(input_stream, output_stream);
}
void syn_target_3D2D(hls::stream<PackedStencil<uint8_t, 1, 1, 1, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 1, 3, 3, 1> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<32, 32, 32, 1>(input_stream, output_stream);
}
void syn_target_3D1D(hls::stream<PackedStencil<uint8_t, 1, 1, 1, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 3, 1, 3, 1> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<32, 32, 32, 1>(input_stream, output_stream);
}
void syn_target_3D(hls::stream<PackedStencil<uint8_t, 1, 1, 1, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 1, 1, 3, 1> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<32, 32, 32, 1>(input_stream, output_stream);
}
void syn_target_2D1D(hls::stream<PackedStencil<uint8_t, 1, 1, 1, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 3, 3, 1, 1> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<32, 32, 1, 1>(input_stream, output_stream);
}
void syn_target_2D(hls::stream<PackedStencil<uint8_t, 1, 1, 1, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 1, 3, 1, 1> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<32, 32, 1, 1>(input_stream, output_stream);
}
void syn_target_1D(hls::stream<PackedStencil<uint8_t, 1, 1, 1, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 3, 1, 1, 1> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<32, 1, 1, 1>(input_stream, output_stream);
}
//2D and 3D linebuffer has latency bug when IMG_EXTENT_0=IN_EXTENT_0=OUT_EXTENT_0
void syn_target_3D2D_bug(hls::stream<PackedStencil<uint8_t, 1, 1, 1, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 1, 3, 3, 1> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<1, 32, 32, 1>(input_stream, output_stream);
}
void syn_target_2D_bug(hls::stream<PackedStencil<uint8_t, 1, 1, 1, 1> > &input_stream,
hls::stream<PackedStencil<uint8_t, 1, 3, 1, 1> > &output_stream) {
#pragma HLS DATAFLOW
linebuffer<1, 32, 1, 1>(input_stream, output_stream);
}
| 39.217391 | 91 | 0.665558 | akifoezkan |
7b83dab5444b86b4a95aaa0adc8f908e1bcef221 | 1,883 | cpp | C++ | mainwindow.cpp | Kronephon/Rasp4Home | 162bd2a5ee2b718037862bffe9a117b188eff710 | [
"MIT"
] | null | null | null | mainwindow.cpp | Kronephon/Rasp4Home | 162bd2a5ee2b718037862bffe9a117b188eff710 | [
"MIT"
] | 11 | 2020-12-28T21:56:55.000Z | 2021-09-25T23:46:30.000Z | mainwindow.cpp | Kronephon/Rasp4Home | 162bd2a5ee2b718037862bffe9a117b188eff710 | [
"MIT"
] | null | null | null | #include <QApplication>
#include <QColor>
#include <QPalette>
#include <QFont>
#include <QBoxLayout>
#include "mainwindow.h"
namespace
{
const float Orange = 0xE95420;
const float WarmGrey = 0xAEA79F;
const float CoolGrey = 0x333333;
const float Aubergine = 0x772953;
const QFont sansFont("Helvetica [Cronyx]", 12);
}
rasp4home::ui::MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent), mDisplay(this)
{
setCentralWidget(&mDisplay);
}
rasp4home::ui::MainWindow::~MainWindow()
{
}
rasp4home::ui::MainScreen* rasp4home::ui::MainWindow::getUI()
{
return &mDisplay;
}
/////
rasp4home::ui::MainScreen::MainScreen(QWidget *parent) : QWidget(parent)
{
paletteSetup();
setLayout(new QBoxLayout(QBoxLayout::TopToBottom));
auto tmpfont = sansFont;
tmpfont.setPointSize(30);
mTime.mHours.setFont(tmpfont);
mTime.mSeparator.setFont(tmpfont);
mTime.mMinutes.setFont(tmpfont);
tmpfont.setPointSize(10);
mTime.mSeconds.setFont(tmpfont);
mTime.layout()->setAlignment(Qt::AlignBottom);
layout()->addWidget(&mTime);
layout()->addWidget(&mWeather);
layout()->addWidget(&mQuote);
}
void rasp4home::ui::MainScreen::paletteSetup()
{
setAutoFillBackground(true);
auto palette = QApplication::palette();
palette.setColor(QPalette::All, QPalette::Background, QColor(Aubergine));
palette.setColor(QPalette::All, QPalette::WindowText, QColor(Orange));
setPalette(palette);
}
void rasp4home::ui::MainScreen::setTime(int h, int m, int s)
{
mTime.mHours.setText(QStringLiteral("%1").arg(h, 2, 10, QLatin1Char('0')));
mTime.mMinutes.setText(QStringLiteral("%1").arg(m, 2, 10, QLatin1Char('0')));
mTime.mSeconds.setText(QStringLiteral("%1").arg(s, 2, 10, QLatin1Char('0')));
if(s%2 == 0){
mTime.mSeparator.setText(" ");
} else{
mTime.mSeparator.setText(":");
}
}
| 23.246914 | 81 | 0.686139 | Kronephon |
7b83f9b2e9ed820773769516250107094068a8fc | 2,797 | cpp | C++ | DarkSpace/StructureSolar.cpp | SnipeDragon/darkspace | b6a1fa0a29d3559b158156e7b96935bd0a832ee3 | [
"MIT"
] | 1 | 2016-05-22T21:28:29.000Z | 2016-05-22T21:28:29.000Z | DarkSpace/StructureSolar.cpp | SnipeDragon/darkspace | b6a1fa0a29d3559b158156e7b96935bd0a832ee3 | [
"MIT"
] | null | null | null | DarkSpace/StructureSolar.cpp | SnipeDragon/darkspace | b6a1fa0a29d3559b158156e7b96935bd0a832ee3 | [
"MIT"
] | null | null | null | /*
StructureSolar.cpp
(c)2000 Palestar Inc, Richard Lyle
*/
#include "Debug/Assert.h"
#include "NounStar.h"
#include "GameContext.h"
#include "StructureSolar.h"
//----------------------------------------------------------------------------
const float MAX_STAR_RANGE = 300000.0f;
const float MAX_POWER = 100.0f;
//----------------------------------------------------------------------------
IMPLEMENT_FACTORY( StructureSolar, StructurePower );
REGISTER_FACTORY_KEY( StructureSolar, 4358662172126761340LL );
BEGIN_PROPERTY_LIST( StructureSolar, StructurePower )
ADD_PROPERTY( m_Power );
END_PROPERTY_LIST();
StructureSolar::StructureSolar() : m_nUpdateTick( 0 )
{
m_Power = 0;
}
//----------------------------------------------------------------------------
void StructureSolar::simulate( dword nTick )
{
if ( nTick >= m_nUpdateTick )
{
m_nUpdateTick = nTick + (TICKS_PER_SECOND * 60);
NounPlanet * pPlanet = planet();
ASSERT( pPlanet );
// determine the power output
m_Power = 0;
// get my current world position
Vector3 myPosition( worldPosition() );
// get all nouns within the specified range
Array< GameContext::NounCollision > nouns;
context()->proximityCheck( myPosition, MAX_STAR_RANGE, nouns, CLASS_KEY(NounStar) );
// enumerate all the stars close to this solar generator
for(int i=0;i<nouns.size();i++)
{
NounStar * pStar = WidgetCast<NounStar>( nouns[i].pNoun );
if ( pStar != NULL && nouns[i].fDistance < MAX_STAR_RANGE )
{
// invert the range, so it's higher the closer the planet
float fRange = MAX_STAR_RANGE - nouns[i].fDistance;
Vector3 lightDirection( pStar->worldPosition() - myPosition );
lightDirection.normalize();
Vector3 surfaceDirection( myPosition - pPlanet->worldPosition() );
surfaceDirection.normalize();
float dot = surfaceDirection | lightDirection;
if ( dot > 0 )
m_Power += ((fRange * MAX_POWER) / MAX_STAR_RANGE) * dot;
}
}
}
NounStructure::simulate( nTick );
}
//----------------------------------------------------------------------------
int StructureSolar::sortId() const
{
return 1;
}
int StructureSolar::groupId() const
{
return 4;
}
int StructureSolar::maxDamage() const
{
return 52920;
}
int StructureSolar::buildTechnology() const
{
return 10;
}
int StructureSolar::buildTime() const
{
return 50;
}
int StructureSolar::buildCost() const
{
return 200;
}
int StructureSolar::repairRate() const
{
return 200;
}
Color StructureSolar::color() const
{
return BLUE;
}
int StructureSolar::workers() const
{
return 1;
}
int StructureSolar::power() const
{
return m_Power * getTechPercentage();
}
int StructureSolar::technology() const
{
return 0;
}
//----------------------------------------------------------------------------
//EOF
| 20.718519 | 86 | 0.607079 | SnipeDragon |
7b8735dfcf5702cf6bd4302b7796ab83c70ddbc7 | 318 | cpp | C++ | src/2000/2193.cpp14.cpp | upple/BOJ | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | [
"MIT"
] | 8 | 2018-04-12T15:54:09.000Z | 2020-06-05T07:41:15.000Z | src/2000/2193.cpp14.cpp | upple/BOJ | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | [
"MIT"
] | null | null | null | src/2000/2193.cpp14.cpp | upple/BOJ | e6dbf9fd17fa2b458c6a781d803123b14c18e6f1 | [
"MIT"
] | null | null | null | #include <cstdio>
using namespace std;
int main()
{
int n;
long long ans = 0, dp[91][2] = {};
scanf("%d", &n);
dp[1][0] = 0;
dp[1][1] = 1;
for (int i = 2; i <= n; i++)
{
dp[i][0] = dp[i - 1][0] + dp[i - 1][1];
dp[i][1] = dp[i - 1][0];
}
ans = dp[n][0] + dp[n][1];
printf("%lld\n", ans);
return 0;
} | 13.826087 | 41 | 0.440252 | upple |
7b8c9ad4a14e5a9f5b240f54706943637926380c | 742 | cpp | C++ | src/racket.cpp | CS126SP20/Crazy-Pong | b26d348535f8cc884b49dc9b5541c8dd552c2e9f | [
"MIT"
] | 1 | 2020-07-29T03:49:11.000Z | 2020-07-29T03:49:11.000Z | src/racket.cpp | CS126SP20/Crazy-Pong | b26d348535f8cc884b49dc9b5541c8dd552c2e9f | [
"MIT"
] | null | null | null | src/racket.cpp | CS126SP20/Crazy-Pong | b26d348535f8cc884b49dc9b5541c8dd552c2e9f | [
"MIT"
] | null | null | null | //
// Created by Riya Gupta on 4/27/20.
//
#include "mylibrary/racket.h";
using namespace mylibrary;
Racket::Racket() { x = 0.0f; y = 0.0f; score = 0; }
float Racket::getX() const { return x; }
float Racket::getY() const { return y; }
void Racket::Init( float a, float b) { x = a; y = b; }
int Racket::getScore() const { return score; }
void Racket::setScore(int score) { Racket::score = score; }
void Racket::Draw() {
cinder::gl::color(Color(0, 1, 0));
cinder::gl::drawSolidRect(Rectf(x,
y,
x + kRacket_width,
y + kRacket_height));
}
void Racket::MoveUp() {
y -= kRacket_speed;
}
void Racket::MoveDown() {
y += kRacket_speed;
} | 26.5 | 59 | 0.552561 | CS126SP20 |
7b90342ee9f4e6fca9ff2bfc0e5d68458ab25bc0 | 411 | cpp | C++ | samples/snippets/cpp/VS_Snippets_CLR_System/system.Char.CompareTo/CPP/compareto.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 421 | 2018-04-01T01:57:50.000Z | 2022-03-28T15:24:42.000Z | samples/snippets/cpp/VS_Snippets_CLR_System/system.Char.CompareTo/CPP/compareto.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 5,797 | 2018-04-02T21:12:23.000Z | 2022-03-31T23:54:38.000Z | samples/snippets/cpp/VS_Snippets_CLR_System/system.Char.CompareTo/CPP/compareto.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 1,482 | 2018-03-31T11:26:20.000Z | 2022-03-30T22:36:45.000Z |
// <snippet19>
using namespace System;
int main()
{
char chA = 'A';
char chB = 'B';
Console::WriteLine( chA.CompareTo( 'A' ) ); // Output: "0" (meaning they're equal)
Console::WriteLine( 'b'.CompareTo( chB ) ); // Output: "32" (meaning 'b' is greater than 'B' by 32)
Console::WriteLine( chA.CompareTo( chB ) ); // Output: "-1" (meaning 'A' is less than 'B' by 1)
}
// </snippet19>
| 29.357143 | 103 | 0.579075 | hamarb123 |
7b90c2c2b7f432370fdadd01accd3f25d094c45f | 2,495 | cpp | C++ | Traveling Salesman Problem/driver.cpp | Tony-Taehoon-Kwon/Algorithm-Analysis | a40fc99c1627672433122b671d5cab65e9ba9e32 | [
"MIT"
] | null | null | null | Traveling Salesman Problem/driver.cpp | Tony-Taehoon-Kwon/Algorithm-Analysis | a40fc99c1627672433122b671d5cab65e9ba9e32 | [
"MIT"
] | null | null | null | Traveling Salesman Problem/driver.cpp | Tony-Taehoon-Kwon/Algorithm-Analysis | a40fc99c1627672433122b671d5cab65e9ba9e32 | [
"MIT"
] | null | null | null | #include "tsp.h"
#include <iostream>
#include <vector>
#include <limits> // numeric_limits
#include <numeric> // accumulate
#include <fstream> // ifstream
void read( char const* filename, MAP& map, int& TotalCity )
{
map.clear();
std::ifstream in( filename, std::ifstream::in );
if( !in.is_open() ) {
std::cout << "problem reading " << filename << std::endl;
return;
}
in >> TotalCity;
for( int i = 0; i < TotalCity; ++i ) {
std::vector<int> row;
for( int j = 0; j < TotalCity; ++j ) {
row.push_back( std::numeric_limits<int>::max() );
}
map.push_back( row );
}
for( int i = 0; i < TotalCity; ++i ) {
for( int j = i + 1; j < TotalCity; ++j ) {
if( !in.good() ) {
std::cout << "problem reading " << filename << std::endl;
return;
}
in >> map[i][j];
map[j][i] = map[i][j];
}
}
}
bool check_legal( std::vector<int> const& sol, int const& num_cities )
{
std::vector<int> visits( num_cities, 0 );
for ( int const& i : sol ) {
++visits[i];
}
return sol.front() == 0
&& sol.back() == 0
&& visits[0] == 2
&& std::accumulate( visits.begin()+1, visits.end(), 1, std::multiplies<int>() ) == 1;
}
void run( char const * filename ) {
std::vector<int> sol = SolveTSP( filename );
MAP map;
int num_cities;
// load & check
read( filename, map, num_cities );
int prev = 0;
int total = 0;
for( int i=1; i<num_cities+1; ++i ) {
total += map[prev][sol[i]];
prev=sol[i];
}
if ( check_legal( sol, num_cities ) ) {
std::cout << total << '\n';
} else {
std::cout << "Path is illegal\n";
}
}
void test0() { run( "map0" ); }
void test1() { run( "map1" ); }
void test2() { run( "map2" ); }
void test3() { run( "map3" ); }
void test4() { run( "map4" ); }
void test5() { run( "map5" ); }
void test6() { run( "map6" ); }
void test7() { run( "map7" ); }
void test8() { run( "map8" ); }
void test9() { run( "map9" ); }
void test10() { run( "map10" ); }
void test11() { run( "map11" ); }
void (*pTests[])() = {
test0,test1,test2,test3,test4,test5,
test6,test7,test8,test9,test10,test11
};
#include <cstdio> // sscanf
int main(int argc, char ** argv) {
if ( argc == 2 ) {
int test = 0;
std::sscanf(argv[1],"%i",&test);
pTests[test]();
}
return 0;
}
| 25.20202 | 93 | 0.501403 | Tony-Taehoon-Kwon |
7b92b2674214aeea2c32f3eb186fa8d9b8177513 | 5,235 | hpp | C++ | src/centurion/initialization.hpp | Creeperface01/centurion | e3b674c11849367a18c2d976ce94071108e1590d | [
"MIT"
] | 14 | 2020-05-17T21:38:03.000Z | 2020-11-21T00:16:25.000Z | src/centurion/initialization.hpp | Creeperface01/centurion | e3b674c11849367a18c2d976ce94071108e1590d | [
"MIT"
] | 70 | 2020-04-26T17:08:52.000Z | 2020-11-21T17:34:03.000Z | src/centurion/initialization.hpp | Creeperface01/centurion | e3b674c11849367a18c2d976ce94071108e1590d | [
"MIT"
] | null | null | null | /*
* MIT License
*
* Copyright (c) 2019-2022 Albin Johansson
*
* 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 CENTURION_INITIALIZATION_HPP_
#define CENTURION_INITIALIZATION_HPP_
#include <SDL.h>
#include <cassert> // assert
#include <optional> // optional
#include "common.hpp"
#include "features.hpp"
#ifndef CENTURION_NO_SDL_IMAGE
#include <SDL_image.h>
#endif // CENTURION_NO_SDL_IMAGE
#ifndef CENTURION_NO_SDL_MIXER
#include <SDL_mixer.h>
#endif // CENTURION_NO_SDL_MIXER
#ifndef CENTURION_NO_SDL_TTF
#include <SDL_ttf.h>
#endif // CENTURION_NO_SDL_TTF
namespace cen {
/**
* \ingroup common
* \defgroup initialization Initialization
*
* \brief Contains components related to SDL initialization.
*/
/// \addtogroup initialization
/// \{
/**
* \brief Used to specify how the core SDL library is initialized.
*/
struct sdl_cfg final
{
/// \brief Controls which SDL subsystems are initialized, see `SDL_INIT_` macros.
uint32 flags{SDL_INIT_EVERYTHING};
};
/**
* \brief Used to load and subsequently unload the core SDL library.
*
* \see `img`
* \see `mix`
* \see `ttf`
*/
class sdl final
{
public:
/**
* \brief Loads the core SDL library.
*
* \param cfg the configuration that will be used.
*
* \throws sdl_error if the SDL library cannot be initialized.
*/
CENTURION_NODISCARD_CTOR explicit sdl(const sdl_cfg& cfg = {})
{
if (SDL_Init(cfg.flags) < 0) {
throw sdl_error{};
}
}
~sdl() noexcept { SDL_Quit(); }
};
#ifndef CENTURION_NO_SDL_IMAGE
/**
* \brief Used to specify how the SDL_image library is initialized.
*/
struct img_cfg final
{
/// \brief Controls which image formats to support, see `IMG_INIT_` macros.
int flags{IMG_INIT_PNG | IMG_INIT_JPG | IMG_INIT_TIF | IMG_INIT_WEBP};
};
/**
* \brief Used to load and subsequently unload the SDL_image library.
*/
class img final
{
public:
/**
* \brief Loads the SDL_image library.
*
* \param cfg the configuration that will be used.
*
* \throws img_error if the SDL_image library cannot be initialized.
*/
CENTURION_NODISCARD_CTOR explicit img(const img_cfg& cfg = {})
{
if (!IMG_Init(cfg.flags)) {
throw img_error{};
}
}
~img() noexcept { IMG_Quit(); }
};
#endif // CENTURION_NO_SDL_IMAGE
#ifndef CENTURION_NO_SDL_MIXER
/**
* \brief Used to specify how the SDL_mixer library is initialized.
*/
struct mix_cfg final
{
/// \brief Controls which file formats to be supported, see `MIX_INIT_` macros.
int flags{MIX_INIT_MP3 | MIX_INIT_OGG | MIX_INIT_FLAC | MIX_INIT_MID | MIX_INIT_MOD |
MIX_INIT_OPUS};
/// \brief The mixer frequency.
int frequency{MIX_DEFAULT_FREQUENCY};
/// \brief The mixer format.
uint16 format{MIX_DEFAULT_FORMAT};
/// \brief The amount of mixer channels.
int channels{MIX_DEFAULT_CHANNELS};
/// \brief The mixer chunk size, in bytes.
int chunk_size{4096};
};
/**
* \brief Used to load and subsequently unload the SDL_mixer library.
*/
class mix final
{
public:
/**
* \brief Loads the SDL_mixer library.
*
* \param cfg the configuration that will be used.
*
* \throws mix_error if the SDL_mixer library cannot be initialized or if the audio device
* couldn't be opened.
*/
CENTURION_NODISCARD_CTOR explicit mix(const mix_cfg& cfg = {})
{
if (!Mix_Init(cfg.flags)) {
throw mix_error{};
}
if (Mix_OpenAudio(cfg.frequency, cfg.format, cfg.channels, cfg.chunk_size) == -1) {
throw mix_error{};
}
}
~mix() noexcept
{
Mix_CloseAudio();
Mix_Quit();
}
};
#endif // CENTURION_NO_SDL_MIXER
#ifndef CENTURION_NO_SDL_TTF
/**
* \brief Used to load and subsequently unload the SDL_ttf library.
*/
class ttf final
{
public:
/**
* \brief Loads the SDL_ttf library.
*
* \param cfg the configuration that will be used.
*
* \throws ttf_error if the SDL_ttf library cannot be initialized.
*/
CENTURION_NODISCARD_CTOR ttf()
{
if (TTF_Init() == -1) {
throw ttf_error{};
}
}
~ttf() noexcept { TTF_Quit(); }
};
#endif // CENTURION_NO_SDL_TTF
/// \} End of group initialization
} // namespace cen
#endif // CENTURION_INITIALIZATION_HPP_
| 23.581081 | 92 | 0.697994 | Creeperface01 |
7b99d3ce05a090fef59aa439f23f343830e0db07 | 180 | cpp | C++ | recipes/poly2tri/all/test_package/test_package.cpp | rockandsalt/conan-center-index | d739adcec3e4dd4c250eff559ceb738e420673dd | [
"MIT"
] | 562 | 2019-09-04T12:23:43.000Z | 2022-03-29T16:41:43.000Z | recipes/poly2tri/all/test_package/test_package.cpp | rockandsalt/conan-center-index | d739adcec3e4dd4c250eff559ceb738e420673dd | [
"MIT"
] | 9,799 | 2019-09-04T12:02:11.000Z | 2022-03-31T23:55:45.000Z | recipes/poly2tri/all/test_package/test_package.cpp | rockandsalt/conan-center-index | d739adcec3e4dd4c250eff559ceb738e420673dd | [
"MIT"
] | 1,126 | 2019-09-04T11:57:46.000Z | 2022-03-31T16:43:38.000Z | #include <poly2tri/poly2tri.h>
int main() {
p2t::Point p1(0.0, 0.0);
p2t::Point p2(1.0, 0.0);
p2t::Point p3(0.0, 1.0);
p2t::Triangle triangle(p1, p2, p3);
return 0;
}
| 15 | 37 | 0.583333 | rockandsalt |
7ba5c8510ca867c972b3377b1e628d4e31576afa | 291 | hpp | C++ | SQL/FactoryRedis.hpp | useryoung-2019/MyHttpServer | ce23c1bf161edba08a82d54de6693167a8917d18 | [
"MIT"
] | null | null | null | SQL/FactoryRedis.hpp | useryoung-2019/MyHttpServer | ce23c1bf161edba08a82d54de6693167a8917d18 | [
"MIT"
] | null | null | null | SQL/FactoryRedis.hpp | useryoung-2019/MyHttpServer | ce23c1bf161edba08a82d54de6693167a8917d18 | [
"MIT"
] | null | null | null | #ifndef FACTORYREDIS_H
#define FACTORYREDIS_H
#include"AbstractFactory.hpp"
#include"ProductRedis.hpp"
class FactoryRedis:public AbstractFactory
{
public:
shared_ptr<AbstractProductSQL> createSQL()
{
return shared_ptr<AbstractProductSQL>(new ProductRedis);
}
};
#endif | 18.1875 | 64 | 0.762887 | useryoung-2019 |
7ba6461d2878e207b78317483922383b7d936371 | 1,872 | cpp | C++ | tests/cpp/restoreIPAddresses/restoreIPAddresses.cpp | zlc18/LocalJudge | e8b141d2e80087d447a45cce36bac27b4ddb9cd1 | [
"MIT"
] | null | null | null | tests/cpp/restoreIPAddresses/restoreIPAddresses.cpp | zlc18/LocalJudge | e8b141d2e80087d447a45cce36bac27b4ddb9cd1 | [
"MIT"
] | null | null | null | tests/cpp/restoreIPAddresses/restoreIPAddresses.cpp | zlc18/LocalJudge | e8b141d2e80087d447a45cce36bac27b4ddb9cd1 | [
"MIT"
] | null | null | null | // Source : https://oj.leetcode.com/problems/restore-ip-addresses/
// Author : Hao Chen
// Date : 2014-08-26
/**********************************************************************************
*
* Given a string containing only digits, restore it by returning all possible valid IP address combinations.
*
* For example:
* Given "25525511135",
*
* return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)
*
*
**********************************************************************************/
#include <stdlib.h>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void restoreIpAddressesHelper(string& s, int start, int partNum, string ip, vector<string>& result);
vector<string> restoreIpAddresses(string s) {
vector<string> result;
string ip;
restoreIpAddressesHelper(s, 0, 0, ip, result);
return result;
}
void restoreIpAddressesHelper(string& s, int start, int partNum, string ip, vector<string>& result) {
int len = s.size();
if ( len - start < 4-partNum || len - start > (4-partNum)*3 ) {
return;
}
if (partNum == 4 && start == len){
ip.erase(ip.end()-1, ip.end());
result.push_back(ip);
return;
}
int num = 0;
for (int i=start; i<start+3; i++){
num = num*10 + s[i]-'0';
if (num<256){
ip+=s[i];
restoreIpAddressesHelper(s, i+1, partNum+1, ip+'.', result);
}
//0.0.0.0 valid, but 0.1.010.01 is not
if (num == 0) {
break;
}
}
}
int main(int argc, char**argv)
{
string s = "25525511135";
if (argc>1){
s = argv[1];
}
vector<string> result = restoreIpAddresses(s);
cout << s << endl;
for(int i=0; i<result.size(); i++){
cout << '\t' << result[i] << endl;
}
return 0;
}
| 24.631579 | 108 | 0.511218 | zlc18 |
7ba6f89a0bb3ce7cb8ffe9410a66ae4e91723a37 | 7,736 | cpp | C++ | PointCloudGenerator/cpp/src/messaging.cpp | first95/ImageProcessorStub | 7b95b8b80ad708115e10104aaa1515f626b94c7d | [
"MIT"
] | 1 | 2021-07-05T07:39:27.000Z | 2021-07-05T07:39:27.000Z | PointCloudGenerator/cpp/src/messaging.cpp | first95/ImageProcessorStub | 7b95b8b80ad708115e10104aaa1515f626b94c7d | [
"MIT"
] | null | null | null | PointCloudGenerator/cpp/src/messaging.cpp | first95/ImageProcessorStub | 7b95b8b80ad708115e10104aaa1515f626b94c7d | [
"MIT"
] | null | null | null | /*
messaging.h
Declarations for PCG messaging
2016-12-23 JDW Created.
*/
#include <messaging.h>
using namespace std;
void Messaging::test() {
Messaging module;
module.initSend();
module.initListen();
cout << "Testing receive. Waiting for packet." << endl;
Msg* msg_in = NULL;
while(1) {
while (msg_in == NULL) {
msg_in = module.checkForMessage();
usleep(1000);
}
cout << "Got a message of type 0x" << hex << setw(4) << msg_in->getMsgId() <<
", size 0x" << msg_in->getLenB() << " bytes." << endl;
switch(msg_in->getMsgId()) {
case POINT_CLOUD_METADATA:
{
cout << "Received point cloud metadata." << dec << endl;
PointCloudMetadataMessage * parsed_msg = (PointCloudMetadataMessage *)msg_in;
cout << "PointCloudSeqNum = " << parsed_msg->getPointCloudSeqNum () << endl;
cout << "NumPktsThisPointCloud = " << parsed_msg->getNumPktsThisPointCloud () << endl;
cout << "NumPointsThisPointCloud = " << parsed_msg->getNumPointsThisPointCloud () << endl;
cout << "OpticalDataCaptureTimeS = " << parsed_msg->getOpticalDataCaptureTimeS () << endl;
cout << "OpticalDataCaptureTimeMs = " << parsed_msg->getOpticalDataCaptureTimeMs () << endl;
cout << "TimeSpentProcessingMs = " << parsed_msg->getTimeSpentProcessingMs () << endl;
}
break;
case POINT_CLOUD_DATA:
{
cout << "Received point cloud data." << dec << endl;
PointCloudDataMessage * parsed_msg = (PointCloudDataMessage *)msg_in;
cout << "PointCloudSeqNum = " << parsed_msg->getPointCloudSeqNum () << endl;
cout << "PktNumThisPointCloud = " << parsed_msg->getPktNumThisPointCloud () << endl;
cout << "NumPointsThisMsg = " << parsed_msg->getNumPointsThisMsg () << endl;
CloudPoint * cloud = parsed_msg->getPointCloud();
cout << "cloud[4] PointX() = " << cloud[4].getPointX() << endl;
cout << "cloud[4] PointY() = " << cloud[4].getPointY() << endl;
cout << "cloud[4] PointZ() = " << cloud[4].getPointZ() << endl;
}
break;
case EN_POINT_CLOUD_GEN:
cout << "Commanded to enable point cloud generation." << endl;
break;
case DIS_POINT_CLOUD_GEN:
cout << "Commanded to disable point cloud generation." << endl;
break;
case SHUTDOWN_PCG:
cout << "Commanded to shutdown." << endl;
break;
default:
cout << "Unrecognized MID 0x" << hex << setw(4) << msg_in->getMsgId() << endl;
break;
}
delete[] msg_in;
msg_in = NULL;
}
}
void Messaging::init(json options, Logger * lgr) {
logger = lgr;
// Load configuration options
string cur_key = "";
try {
cur_key = "flightPlannerIpAddr"; flightPlannerIpAddr = options[cur_key];
cur_key = "localListenPort"; localListenPort = options[cur_key];
cur_key = "remoteDestPort"; remoteDestPort = options[cur_key];
cur_key = "dataSourcePort"; dataSourcePort = options[cur_key];
cur_key = "cmdRespSourcePort"; cmdRespSourcePort = options[cur_key];
} catch (domain_error e) {
cerr << "JSON field missing or corrupted. Please see example file in config directory."
<< endl << "While reading key \"" << cur_key << "\" in acquisition section: "
<< e.what() << endl;
throw(e);
return;
}
initSend();
initListen();
}
void Messaging::setBlockingListen(bool block) {
int ret_val = -1;
// If setting any flags other than O_NONBLOCK, change that 0, you can do a F_GETFL
ret_val = fcntl(sockInbound, F_SETFL, block? 0 : O_NONBLOCK);
if(ret_val < 0) {
throw runtime_error("fcntl(): Failed to set socket blocking behavior.");
}
}
void Messaging::initListen() {
int ret_val = -1;
sockInbound = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(sockInbound >= 0) {
struct sockaddr_in local_sock;
memset(&local_sock, 0, sizeof(local_sock));
local_sock.sin_family = AF_INET;
local_sock.sin_addr.s_addr = htonl(INADDR_ANY);
local_sock.sin_port = htons(localListenPort);
ret_val = bind(sockInbound, (struct sockaddr *) &local_sock, sizeof(local_sock));
if(ret_val >= 0) {
listening = true;
} else {
throw runtime_error("bind(): Failed to bind incoming data socket.");
}
} else {
throw runtime_error("socket(): Failed to open incoming data socket.");
}
}
void Messaging::initSend() {
int ret_val = -1;
sockOutboundData = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if(sockOutboundData >= 0) {
struct sockaddr_in src_sock;
memset(&src_sock, 0, sizeof(src_sock));
src_sock.sin_family = AF_INET;
src_sock.sin_addr.s_addr = htonl(INADDR_ANY);
src_sock.sin_port = htons(dataSourcePort);
ret_val = bind(sockOutboundData, (struct sockaddr *) &src_sock, sizeof(src_sock));
if(ret_val >= 0) {
int broadcastEnable=1;
ret_val = setsockopt(sockOutboundData, SOL_SOCKET, SO_BROADCAST, &broadcastEnable, sizeof(broadcastEnable));
if(ret_val == 0) {
memset((void*)(&flightPlannerAddress), 0, sizeof(flightPlannerAddress));
flightPlannerAddress.sin_family = AF_INET;
flightPlannerAddress.sin_port = htons(remoteDestPort);
ret_val = inet_aton(flightPlannerIpAddr.c_str(), &(flightPlannerAddress.sin_addr));
if(ret_val == 1) {
readyToSend = true;
} else {
throw runtime_error("inet_aton(): Failed to translate destination IP address.");
}
} else {
throw runtime_error("setsockopt(): Failed to gain broadcast privileges.");
}
} else {
throw runtime_error("bind(): Failed to bind outbound data socket.");
}
} else {
throw runtime_error("socket(): Failed to open outbound data socket.");
}
}
void Messaging::sendMessage(const Msg * msg) {
if(readyToSend) {
int ret_val = sendto(sockOutboundData, (void*)msg, msg->getLenB(), 0 , (sockaddr*)(&flightPlannerAddress), sizeof(flightPlannerAddress));
if(ret_val != msg->getLenB()) {
throw runtime_error("sendto(): Failed to send entire message.");
}
}
}
Msg * Messaging::checkForMessage() {
if(!listening) { return NULL; }
// Copy any new data into the buffer
Msg * ret_msg = NULL;
struct sockaddr_in sender_address;
unsigned int sender_addr_len = sizeof(sender_address);
int bytes_rxd = recvfrom(sockInbound, incomingMsgStart, MSGING_RECV_BUFFER_SIZE_B - incomingMsgBytesReceived, 0,
(struct sockaddr*)&sender_address, &sender_addr_len);
if(bytes_rxd == -1) {
// This is probably due to a lack of message waiting for us
if(errno == EAGAIN || errno == EWOULDBLOCK) {
// No new data
bytes_rxd = 0;
} else {
throw runtime_error("recvfrom(): Error checking for new packet.");
}
} else {
// We have new data
}
// Return the next message, if any, in our buffer
incomingMsgBytesReceived += bytes_rxd;
if(incomingMsgBytesReceived >= sizeof(Msg)) {
// We have enough to start trying to make sense of the message
size_t msg_len = ((Msg*)incomingMsgStart)->getLenB() ;
if(msg_len >= incomingMsgBytesReceived) {
// We have this entire message
ret_msg = (Msg*)new char[msg_len];
memcpy((void*)ret_msg, incomingMsgStart, msg_len);
incomingMsgStart += msg_len;
incomingMsgBytesReceived -= msg_len;
// If the buffer was left empty by that, jump back to the beginning
if(incomingMsgBytesReceived == 0) {
incomingMsgStart = recvBuffer;
} else {
// The buffer has at least the start of another message
}
} else {
// We only have a chunk of this message
}
} else {
// Have received either nothing or just part of the header
}
// Check if we've filled the buffer
if((incomingMsgStart - recvBuffer) + incomingMsgBytesReceived >= MSGING_RECV_BUFFER_SIZE_B) {
// Buffer is full. Discard contents.
logger->logWarning("Filled message receive buffer; discarding.");
incomingMsgStart = recvBuffer;
incomingMsgBytesReceived = 0;
}
return ret_msg;
} | 34.690583 | 139 | 0.677482 | first95 |
7bb11b832ba20d98c9d7c8a8d06658affa55c560 | 3,919 | cpp | C++ | src/cipher.cpp | chrisballinger/OLMKit | daab2a58af947cddd67fe9f30dd3a9fc327650c0 | [
"Apache-2.0"
] | 2 | 2016-04-14T13:48:33.000Z | 2021-01-11T03:48:19.000Z | src/cipher.cpp | chrisballinger/OLMKit | daab2a58af947cddd67fe9f30dd3a9fc327650c0 | [
"Apache-2.0"
] | 1 | 2019-01-25T16:20:41.000Z | 2020-10-28T13:54:39.000Z | src/cipher.cpp | chrisballinger/OLMKit | daab2a58af947cddd67fe9f30dd3a9fc327650c0 | [
"Apache-2.0"
] | 1 | 2017-01-11T18:13:00.000Z | 2017-01-11T18:13:00.000Z | /* Copyright 2015 OpenMarket Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "olm/cipher.hh"
#include "olm/crypto.hh"
#include "olm/memory.hh"
#include <cstring>
olm::Cipher::~Cipher() {
}
namespace {
struct DerivedKeys {
olm::Aes256Key aes_key;
std::uint8_t mac_key[olm::KEY_LENGTH];
olm::Aes256Iv aes_iv;
};
static void derive_keys(
std::uint8_t const * kdf_info, std::size_t kdf_info_length,
std::uint8_t const * key, std::size_t key_length,
DerivedKeys & keys
) {
std::uint8_t derived_secrets[2 * olm::KEY_LENGTH + olm::IV_LENGTH];
olm::hkdf_sha256(
key, key_length,
nullptr, 0,
kdf_info, kdf_info_length,
derived_secrets, sizeof(derived_secrets)
);
std::uint8_t const * pos = derived_secrets;
pos = olm::load_array(keys.aes_key.key, pos);
pos = olm::load_array(keys.mac_key, pos);
pos = olm::load_array(keys.aes_iv.iv, pos);
olm::unset(derived_secrets);
}
static const std::size_t MAC_LENGTH = 8;
} // namespace
olm::CipherAesSha256::CipherAesSha256(
std::uint8_t const * kdf_info, std::size_t kdf_info_length
) : kdf_info(kdf_info), kdf_info_length(kdf_info_length) {
}
std::size_t olm::CipherAesSha256::mac_length() const {
return MAC_LENGTH;
}
std::size_t olm::CipherAesSha256::encrypt_ciphertext_length(
std::size_t plaintext_length
) const {
return olm::aes_encrypt_cbc_length(plaintext_length);
}
std::size_t olm::CipherAesSha256::encrypt(
std::uint8_t const * key, std::size_t key_length,
std::uint8_t const * plaintext, std::size_t plaintext_length,
std::uint8_t * ciphertext, std::size_t ciphertext_length,
std::uint8_t * output, std::size_t output_length
) const {
if (encrypt_ciphertext_length(plaintext_length) < ciphertext_length) {
return std::size_t(-1);
}
struct DerivedKeys keys;
std::uint8_t mac[olm::SHA256_OUTPUT_LENGTH];
derive_keys(kdf_info, kdf_info_length, key, key_length, keys);
olm::aes_encrypt_cbc(
keys.aes_key, keys.aes_iv, plaintext, plaintext_length, ciphertext
);
olm::hmac_sha256(
keys.mac_key, olm::KEY_LENGTH, output, output_length - MAC_LENGTH, mac
);
std::memcpy(output + output_length - MAC_LENGTH, mac, MAC_LENGTH);
olm::unset(keys);
return output_length;
}
std::size_t olm::CipherAesSha256::decrypt_max_plaintext_length(
std::size_t ciphertext_length
) const {
return ciphertext_length;
}
std::size_t olm::CipherAesSha256::decrypt(
std::uint8_t const * key, std::size_t key_length,
std::uint8_t const * input, std::size_t input_length,
std::uint8_t const * ciphertext, std::size_t ciphertext_length,
std::uint8_t * plaintext, std::size_t max_plaintext_length
) const {
DerivedKeys keys;
std::uint8_t mac[olm::SHA256_OUTPUT_LENGTH];
derive_keys(kdf_info, kdf_info_length, key, key_length, keys);
olm::hmac_sha256(
keys.mac_key, olm::KEY_LENGTH, input, input_length - MAC_LENGTH, mac
);
std::uint8_t const * input_mac = input + input_length - MAC_LENGTH;
if (!olm::is_equal(input_mac, mac, MAC_LENGTH)) {
olm::unset(keys);
return std::size_t(-1);
}
std::size_t plaintext_length = olm::aes_decrypt_cbc(
keys.aes_key, keys.aes_iv, ciphertext, ciphertext_length, plaintext
);
olm::unset(keys);
return plaintext_length;
}
| 28.194245 | 78 | 0.700944 | chrisballinger |
7bb208e8ba6f8a0ce70f31250587a31f0cf1ed7b | 4,387 | hpp | C++ | mod/wrd/src/ast/node.hpp | kniz/worldlang | 78701ab003c158211d42d129f91259d17febbb22 | [
"MIT"
] | 7 | 2019-03-12T03:04:32.000Z | 2021-12-26T04:33:44.000Z | mod/wrd/src/ast/node.hpp | kniz/worldlang | 78701ab003c158211d42d129f91259d17febbb22 | [
"MIT"
] | 7 | 2019-02-13T14:01:43.000Z | 2020-11-20T11:09:06.000Z | mod/wrd/src/ast/node.hpp | kniz/worldlang | 78701ab003c158211d42d129f91259d17febbb22 | [
"MIT"
] | null | null | null | #pragma once
#include "clonable.hpp"
#include "../builtin/container/native/tnarr.hpp"
#include "validable.hpp"
namespace wrd {
class ases;
/// node provides common API to manipulate its sub nodes.
class node : public instance, public clonable {
WRD(INTERFACE(node, instance))
public:
node& operator[](const std::string& name) const { return sub(name); }
public:
wbool isSub(const type& it) const { return getType().isSub(it); }
wbool isSuper(const type& it) const { return getType().isSuper(it); }
template <typename T>
wbool isSub() const { return getType().isSub<T>(); }
template <typename T>
wbool isSuper() const { return getType().isSuper<T>(); }
virtual ncontainer& subs() = 0;
const ncontainer& subs() const WRD_UNCONST_FUNC(subs())
template <typename T>
T& sub(std::function<wbool(const T&)> l) const {
return subs().get<T>(l);
}
template <typename T = me>
T& sub(const std::string& name) const;
template <typename T = me>
T& sub(const std::string& name, const ncontainer& args);
template <typename T = me>
T& sub(const std::string& name, const wtypes& types);
template <typename T = me>
T& sub(const std::string& name, const ncontainer& args) const;
template <typename T = me>
T& sub(const std::string& name, const wtypes& types) const;
template <typename T>
tnarr<T> subAll(std::function<wbool(const T&)> l) const {
return subs().getAll<T>(l);
}
template <typename T = me>
tnarr<T> subAll(const std::string& name) const;
template <typename T = me>
tnarr<T> subAll(const std::string& name, const ncontainer& args);
template <typename T = me>
tnarr<T> subAll(const std::string& name, const wtypes& types);
template <typename T = me>
tnarr<T> subAll(const std::string& name, const ncontainer& args) const;
template <typename T = me>
tnarr<T> subAll(const std::string& name, const wtypes& types) const;
virtual wbool canRun(const wtypes& typs) const = 0;
wbool canRun(const containable& args) const {
return canRun(createTypesFromArgs(args));
}
virtual str run(const containable& args) = 0;
str run();
/// release all holding resources and ready to be terminated.
/// @remark some class won't be able to reinitialize after rel() got called.
virtual void rel() {}
virtual const std::string& getName() const {
static std::string dummy = "";
return dummy;
}
template <typename T>
wbool is() const {
return is(ttype<T>::get());
}
wbool is(const type& to) const {
return getType().is(to);
}
template <typename T>
tstr<T> as() const {
return as(ttype<T>::get());
}
str as(const type& to) const {
return getType().as(*this, to);
}
template <typename T>
wbool isImpli() const {
return isImpli(ttype<T>::get());
}
wbool isImpli(const type& to) const {
return getType().isImpli(to);
}
template <typename T>
tstr<T> asImpli() const {
return asImpli(ttype<T>::get());
}
str asImpli(const type& to) const {
return getType().asImpli(*this, to);
}
/// getType() returns what it is. opposite to it, this returns what this class will
/// represents after evaluation.
///
/// for example, the 'expr' class has derived from this node class. and if an user call the
/// funcs to get type of it, class 'wtype' of 'expr' will be returned.
/// but if that user call the 'getEvalType()' then the 'expr' object evaluate its terms and
/// returns type of the output. it could be integer if it was 'addExpr' and all terms are
/// constructed with integers.
virtual const wtype& getEvalType() const {
return getType();
}
static wtypes createTypesFromArgs(const containable& args) {
wtypes ret;
for(iter e=args.begin(); e ;e++)
ret.push_back((wtype*) &e->getEvalType());
return ret;
}
};
}
| 34.543307 | 99 | 0.578527 | kniz |
7bb29975b2420b277accdb5621008b6c37ad4fbd | 1,776 | hpp | C++ | Example/src/MYENG_DB/ModuleBase.hpp | heesok2/MFC | 1ff13a425609addbf458d00f9853d16ada2b29ec | [
"MIT"
] | null | null | null | Example/src/MYENG_DB/ModuleBase.hpp | heesok2/MFC | 1ff13a425609addbf458d00f9853d16ada2b29ec | [
"MIT"
] | null | null | null | Example/src/MYENG_DB/ModuleBase.hpp | heesok2/MFC | 1ff13a425609addbf458d00f9853d16ada2b29ec | [
"MIT"
] | null | null | null | #pragma once
#ifndef MODULEDATA_DEF
#define MODULEDATA_DEF
#include "Module.h"
#include "EntityDictionary.hpp"
namespace mydb
{
template <class ENTITY_DATA>
class CModuleData : public mydb::CModule
{
public:
CModuleData(CPackage * pPackage)
: CModule(pPackage)
{}
virtual ~CModuleData() {}
public: // Data
virtual void Clear()
{
m_Dictionary.Clear();
}
virtual BOOL Empty()
{
return m_Dictionary.IsEmpty();
}
virtual BOOL Exist(MYKEY key)
{
auto itr = m_Dictionary.Find(key);
return ITR_IS_VALID(itr);
}
virtual MYITR Find(MYKEY key)
{
return m_Dictionary.Find(key);
}
virtual BOOL Lookup(MYKEY key, ENTITY_DATA& data)
{
auto itr = m_Dictionary.Find(key);
if (!ITR_IS_VALID(itr))
return FALSE;
data = m_Dictionary.GetAtNU(itr);
return TRUE;
}
virtual MYITR InsertNU(const ENTITY_DATA& data)
{
return m_Dictionary.InsertNU(data);
}
virtual BOOL SetAtNU(MYITR itr, const ENTITY_DATA& data)
{
return m_Dictionary.SetAtNU(itr, data);
}
virtual BOOL Remove(MYITR itr)
{
return m_Dictionary.Remove(itr);
}
virtual const ENTITY_DATA& GetAtNU(MYITR itr) const
{
return m_Dictionary.GetAtNU(itr);
}
virtual long GetItrList(std::vector<MYITR>& aItr)
{
return m_Dictionary.GetList(aItr);
}
virtual long GetDataList(std::vector<ENTITY_DATA>& aData)
{
return m_Dictionary.GetListData(aData);
}
virtual MYKEY GetNewKey()
{
return m_Dictionary.GetNewKey();
}
public:
virtual MYITR GetDefaultData()
{
ASSERT(g_warning);
return (MYITR)nullptr;
}
virtual void SetDefaultData()
{
ASSERT(g_warning);
}
protected:
MYTYPE m_myType;
CEntityDictionary<ENTITY_DATA> m_Dictionary;
};
}
#endif // !MODULEDATA_DEF
| 16.444444 | 59 | 0.684122 | heesok2 |
7bb2ef35750e081f80ff1393e876834f6050f347 | 388 | cpp | C++ | ParallelProgramming/lab1/readfiletest.cpp | maysincerity/GradLab | b9f067a1ba33e43f240261b092056a18494b3c22 | [
"MIT"
] | null | null | null | ParallelProgramming/lab1/readfiletest.cpp | maysincerity/GradLab | b9f067a1ba33e43f240261b092056a18494b3c22 | [
"MIT"
] | null | null | null | ParallelProgramming/lab1/readfiletest.cpp | maysincerity/GradLab | b9f067a1ba33e43f240261b092056a18494b3c22 | [
"MIT"
] | null | null | null | #include <fstream>
#include <iostream>
using namespace std;
int main(){
int data;
int count = 0;
ifstream infile;
infile.open("data.txt");
while(!infile.eof()){
cout<<"reading file ";
infile>>data;
if(infile.fail()){
break;
}
cout << data << " "<<endl;
count++;
}
infile.close();
cout<<count;
}
| 17.636364 | 34 | 0.497423 | maysincerity |
7bb36148ad788f1fa9884d648231660a92519887 | 10,501 | cpp | C++ | test/jhash_test.cpp | MrVoi/ric-plt-xapp-frame-cpp | dad910695faf755da932bdbd07430f58718fd910 | [
"Apache-2.0",
"CC-BY-4.0"
] | 1 | 2021-07-19T21:29:30.000Z | 2021-07-19T21:29:30.000Z | test/jhash_test.cpp | MrVoi/ric-plt-xapp-frame-cpp | dad910695faf755da932bdbd07430f58718fd910 | [
"Apache-2.0",
"CC-BY-4.0"
] | null | null | null | test/jhash_test.cpp | MrVoi/ric-plt-xapp-frame-cpp | dad910695faf755da932bdbd07430f58718fd910 | [
"Apache-2.0",
"CC-BY-4.0"
] | 1 | 2022-03-11T02:36:36.000Z | 2022-03-11T02:36:36.000Z | // vim: ts=4 sw=4 noet :
/*
==================================================================================
Copyright (c) 2020 Nokia
Copyright (c) 2020 AT&T Intellectual Property.
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.
==================================================================================
*/
/*
Mnemonic: json_test.cpp
Abstract: Unit test for the json module. This expects that a static json
file exist in the current directory with a known set of fields,
arrays and objects that can be sussed out after parsing. The
expected file is test.json.
Date: 26 June 2020
Author: E. Scott Daniels
*/
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <string>
#include <memory>
/*
Very simple file reader. Reads up to 8k into a single buffer and
returns the buffer as char*. Easier to put json test things in
a file than strings.
*/
static char* read_jstring( char* fname ) {
char* rbuf;
int fd;
int len;
rbuf = (char *) malloc( sizeof( char ) * 8192 );
fd = open( fname, O_RDONLY, 0 );
if( fd < 0 ) {
fprintf( stderr, "<ABORT> can't open test file: %s: %s\n", fname, strerror( errno ) );
exit( 1 );
}
len = read( fd, rbuf, 8190 );
if( len < 0 ) {
close( fd );
fprintf( stderr, "<ABORT> read from file failed: %s: %s\n", fname, strerror( errno ) );
exit( 1 );
}
rbuf[len] = 0;
close( fd );
return rbuf;
}
// this also tests jwrapper.c but that is built as a special object to link in
// rather than including here.
//
#include "../src/json/jhash.hpp"
#include "../src/json/jhash.cpp"
#include "ut_support.cpp"
int main( int argc, char** argv ) {
int errors = 0;
xapp::Jhash* jh;
char* jstr;
std::string sval;
double val;
bool state;
int i;
int len;
int true_count = 0;
set_test_name( "jhash_test" );
jstr = read_jstring( (char *) "test.json" ); // read and parse the json
fprintf( stderr, "read: (%s)\n", jstr );
jh = new xapp::Jhash( jstr );
free( jstr );
if( jh == NULL ) {
fprintf( stderr, "<FAIL> could not parse json string from: test.json\n" );
exit( 1 );
}
sval = jh->String( (char *) "meeting_day" );
fprintf( stderr, "<INFO> sval=(%s)\n", sval.c_str() );
errors += fail_if( sval.compare( "" ) == 0, "did not get meeting day string" );
errors += fail_if( sval.compare( "Tuesday" ) != 0, "meeting day was not expected string" );
sval = jh->String( (char *) "meeting_place" );
fprintf( stderr, "<INFO> sval=(%s)\n", sval.c_str() );
errors += fail_if( sval.compare( "" ) == 0, "did not get meeting place" );
errors += fail_if( sval.compare( "16801 East Green Drive" ) != 0, "meeting place stirng was not correct" );
state = jh->Exists( (char *) "meeting_place" );
errors += fail_if( !state, "test for meeting place exists did not return true" );
state = jh->Exists( (char *) "no-name" );
errors += fail_if( state, "test for non-existant thing returned true" );
state = jh->Is_missing( (char *) "no-name" );
errors += fail_if( !state, "missing test for non-existant thing returned false" );
state = jh->Is_missing( (char *) "meeting_place" );
errors += fail_if( state, "missing test for existing thing returned true" );
val = jh->Value( (char *) "lodge_number" );
errors += fail_if( val != 41.0, "lodge number value was not correct" );
val = jh->Value( (char *) "monthly_dues" );
fprintf( stderr, "<INFO> got dues: %.2f\n", val );
errors += fail_if( val != (double) 43.5, "lodge dues value was not correct" );
len = jh->Array_len( (char *) "members" );
fprintf( stderr, "<INFO> got %d members\n", len );
errors += fail_if( len != 4, "array length was not correct" );
if( len > 0 ) {
for( i = 0; i < len; i++ ) {
if( ! jh->Set_blob_ele( (char *) "members", i ) ) {
errors++;
fprintf( stderr, (char *) "couldn't set blob for element %d\n", i );
} else {
fprintf( stderr, (char *) "<INFO> testing element %d of %d\n", i, len );
state = jh->Is_value( (char *) "age" );
errors += fail_if( !state, "is value test for age returned false" );
state = jh->Is_value( (char *) "married" );
errors += fail_if( state, "is value test for married returned true" );
state = jh->Is_string( (char *) "occupation" );
errors += fail_if( !state, "is string test for spouse returned false" );
state = jh->Is_string( (char *) "married" );
errors += fail_if( state, "is string test for married returned true" );
state = jh->Is_bool( (char *) "married" );
errors += fail_if( !state, "is bool test for married returned false" );
state = jh->Is_bool( (char *) "occupation" );
errors += fail_if( state, "is bool test for spouse returned true" );
val = jh->Value( (char *) "age" );
fprintf( stderr, "<INFO> got age: %.2f\n", (double) val );
errors += fail_if( val < 0, "age value wasn't positive" );
sval = jh->String( (char *) "name" );
fprintf( stderr, "<INFO> sval=(%s)\n", sval.c_str() );
errors += fail_if( sval.compare( "" ) == 0, "no name found in element" );
if( jh->Bool( (char *) "married" ) ) {
true_count++;
}
}
jh->Unset_blob(); // must return to root
}
fprintf( stderr, "<INFO> true count = %d\n", true_count );
errors += fail_if( true_count != 3, "married == true count was not right" );
}
state = jh->Set_blob( (char *) "no-such-thing" );
errors += fail_if( state, "setting blob to non-existant blob returned true" );
state = jh->Set_blob( (char *) "grand_poobah" );
errors += fail_if( !state, "setting blob to existing blob failed" );
if( state ) {
sval = jh->String( (char *) "elected" );
fprintf( stderr, "<INFO> sval=(%s)\n", sval.c_str() );
errors += fail_if( sval != "February 2019", "blob 'elected' didn't return the expected string" );
state = jh->Exists( (char *) "monthly_dues" );
errors += fail_if( state, "blob that shouldn't have a field reports it does" );
jh->Unset_blob( ); // ensure that this is found once we unset to root
state = jh->Exists( (char *) "monthly_dues" );
errors += fail_if( !state, "after rest, root blob, that should have a field, reports it does not" );
}
// ---- test array element value type checks -------------------------------------------------
state = jh->Is_string_ele( (char *) "sponser", 1 );
errors += fail_if( !state, "string element check on sponser failed" );
state = jh->Is_string_ele( (char *) "current_on_dues", 1 );
errors += fail_if( state, "string element check on non-stirng element returned true" );
state = jh->Is_value_ele( (char *) "dues_assistance", 1 );
errors += fail_if( !state, "value element type check on value element reported false" );
state = jh->Is_value_ele( (char *) "current_on_dues", 1 );
errors += fail_if( state, "value element type check on non-value element returned true" );
state = jh->Is_bool_ele( (char *) "current_on_dues", 1 );
errors += fail_if( !state, "string element check on sponser failed" );
state = jh->Is_bool_ele( (char *) "sponser", 1 );
errors += fail_if( state, "string element check on non-stirng element returned true" );
state = jh->Is_null( (char *) "nvt" );
errors += fail_if( !state, "test for nil value returned false" );
state = jh->Is_null( (char *) "lodge_number" );
errors += fail_if( state, "nil test for non-nil value returned true" );
state = jh->Is_null_ele( (char *) "nvat", 0 );
errors += fail_if( !state, "test for nil array element value returned false" );
// ---- test sussing of elements from arrays -------------------------------------------------
sval = jh->String_ele( (char *) "sponser", 1 );
errors += fail_if( sval.compare( "" ) == 0, "get string element failed for sponser (empty string)" );
errors += fail_if( sval.compare( "slate" ) != 0, "get string element failed for sponser (wrong value for[1])" );
sval = jh->String_ele( (char *) "sponser", 0 );
errors += fail_if( sval.compare( "slate" ) != 0, "get string element failed for sponser (wrong value for [0])" );
sval = jh->String_ele( (char *) "sponser", 3 );
errors += fail_if( sval.compare( "brick" ) != 0, "get string element failed for sponser (wrong value for [3])" );
val = jh->Value_ele( (char *) "dues_assistance", 1 );
errors += fail_if( val == 0.0, "get value element for dues_assistance was zero" );
state = jh->Bool_ele( (char *) "current_on_dues", 1 );
errors += fail_if( state, "bool ele test returned true for a false value" );
state = jh->Bool_ele( (char *) "current_on_dues", 0 );
errors += fail_if( !state, "bool ele test returned false for a true value" );
val = jh->Value( (char *) "timestamp" );
fprintf( stderr, "<INFO> timestamp: %.10f\n", val );
jh->Dump(); // for coverage of debug things
// ----- jhashes can be moved, drive that logic for coverage
xapp::Jhash j2( "{}" );
xapp::Jhash j1 = std::move( *jh ); // drives move constructor function
j2 = std::move( j1 ); // drives move operator function
delete jh;
fprintf( stderr, "<INFO> testing for failures; jwrapper error and warning messages expected\n" );
// ---- these shouild all fail to parse, generate warnings to stderr, and drive error handling coverage ----
jh = new xapp::Jhash( (char *) "{ \"bad\": [ [ 1, 2, 3 ], [ 3, 4, 5]] }" ); // drive the exception process for bad json
delete jh;
jh = new xapp::Jhash( (char *) " \"bad\": 5 }" ); // no opening brace
state = jh->Parse_errors();
errors += fail_if( !state, "parse errors check returned false when known errors exist" );
delete jh;
jh = new xapp::Jhash( (char *) "{ \"bad\": fred }" ); // no quotes
delete jh;
jh = new xapp::Jhash( (char *) "{ \"bad: 456, \"good\": 100 }" ); // missing quote; impossible to detect error
jh->Dump(); // but dump should provide details
fprintf( stderr, "<INFO> good value=%d\n", (int) val );
delete jh;
// ---------------------------- end housekeeping ---------------------------
announce_results( errors );
return !!errors;
}
| 36.975352 | 124 | 0.614799 | MrVoi |
7bb4eac23f8ec73f6d3b79e9a42265c3740afa8e | 20,282 | cpp | C++ | src/binance/wallet.cpp | Hsin-Hung/binance_api_cpp | 1c7662cf0cd682122644dc5819dfe9b88e06b8a6 | [
"Apache-2.0"
] | 1 | 2022-02-06T17:40:55.000Z | 2022-02-06T17:40:55.000Z | src/binance/wallet.cpp | Hsin-Hung/binance_api_cpp | 1c7662cf0cd682122644dc5819dfe9b88e06b8a6 | [
"Apache-2.0"
] | null | null | null | src/binance/wallet.cpp | Hsin-Hung/binance_api_cpp | 1c7662cf0cd682122644dc5819dfe9b88e06b8a6 | [
"Apache-2.0"
] | 1 | 2022-03-31T07:54:23.000Z | 2022-03-31T07:54:23.000Z | /*
Binance API Wrapper for C++
Copyright (c) 2022 Hsin-Hung <https://github.com/Hsin-Hung>
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 "wallet.h"
#include <ctime>
using namespace Binance;
void Wallet::SystemStatus(json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
std::string url = endpoint + "/sapi/v1/system/status";
SetUpCurlOpt(curl, url, "", std::vector<Header>(), Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::AllCoins(WalletAllCoinsParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/capital/config/getall?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::DailyAccountSnapshot(WalletAccountSnapParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("type", params.type);
query_params.add_new_query("startTime", params.startTime);
query_params.add_new_query("endTime", params.endTime);
query_params.add_new_query("limit", params.limit);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/accountSnapshot?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::DisableFastWithdrawSwitch(WalletFastWithdrawSwitchParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/account/disableFastWithdrawSwitch?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::POST, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::EnableFastWithdrawSwitch(WalletFastWithdrawSwitchParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/account/enableFastWithdrawSwitch?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::POST, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::Withdraw(WalletWithdrawParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("coin", params.coin);
query_params.add_new_query("withdrawOrderId", params.withdrawOrderId);
query_params.add_new_query("network", params.network);
query_params.add_new_query("address", params.address);
query_params.add_new_query("addressTag", params.addressTag);
query_params.add_new_query("amount", params.amount);
query_params.add_new_query("transactionFeeFlag", params.transactionFeeFlag);
query_params.add_new_query("name", params.name);
query_params.add_new_query("walletType", params.walletType);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/capital/withdraw/apply?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::POST, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::DepositHistory(WalletDepositHistoryParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("coin", params.coin);
query_params.add_new_query("status", params.status);
query_params.add_new_query("startTime", params.startTime);
query_params.add_new_query("endTime", params.endTime);
query_params.add_new_query("offset", params.offset);
query_params.add_new_query("limit", params.limit);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/capital/deposit/hisrec?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::WithdrawHistory(WalletWithdrawHistoryParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("coin", params.coin);
query_params.add_new_query("withdrawOrderId", params.withdrawOrderId);
query_params.add_new_query("status", params.status);
query_params.add_new_query("offset", params.offset);
query_params.add_new_query("limit", params.limit);
query_params.add_new_query("startTime", params.startTime);
query_params.add_new_query("endTime", params.endTime);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/capital/withdraw/history?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::DepositAddress(WalletDepositAddressParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("coin", params.coin);
query_params.add_new_query("network", params.network);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/capital/deposit/address?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::AccountStatus(WalletAccountStatusParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/account/status?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::AccountAPITradeStatus(WalletAccountAPITradeStatusParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/account/apiTradingStatus?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::DustLog(WalletDustLogParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("startTime", params.startTime);
query_params.add_new_query("endTime", params.endTime);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/asset/dribblet?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::DustTransfer(WalletDustTransferParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("asset", params.asset);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/asset/dust?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::POST, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::AssetDividendRecord(WalletAssetDividendRecordParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("asset", params.asset);
query_params.add_new_query("startTime", params.startTime);
query_params.add_new_query("endTime", params.endTime);
query_params.add_new_query("limit", params.limit);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/asset/assetDividend?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::AssetDetail(WalletAssetDetailParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("asset", params.asset);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/asset/assetDetail?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::TradeFee(WalletTradeFeeParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("symbol", params.symbol);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/asset/tradeFee?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::UniversalTransfer(WalletUniversalTransferParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("type", get_OrderType(params.type));
query_params.add_new_query("asset", params.asset);
query_params.add_new_query("amount", params.amount);
query_params.add_new_query("fromSymbol", params.fromSymbol);
query_params.add_new_query("toSymbol", params.toSymbol);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/asset/transfer?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::POST, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::QueryUniversalTransfer(WalletQueryUniversalTransferParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("type", get_OrderType(params.type));
query_params.add_new_query("startTime", params.startTime);
query_params.add_new_query("endTime", params.endTime);
query_params.add_new_query("current", params.current);
query_params.add_new_query("size", params.size);
query_params.add_new_query("fromSymbol", params.fromSymbol);
query_params.add_new_query("toSymbol", params.toSymbol);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/asset/transfer?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::Funding(WalletFundingParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("asset", params.asset);
query_params.add_new_query("needBtcValuation", params.needBtcValuation);
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/asset/get-funding-asset?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::POST, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
}
void Wallet::GetAPIKeyPermission(WalletGetAPIKeyPermissionParams params, json &result)
{
struct memory chunk;
CURL *curl;
curl = curl_easy_init();
if (curl)
{
BinanceAPI::QueryParams query_params;
query_params.add_new_query("recvWindow", params.recvWindow);
query_params.add_new_query("timestamp", params.timestamp);
std::string sig;
generate_HMAC_SHA256_sig(secret_key, query_params.to_str(), sig);
query_params.add_signature(sig);
std::string url = endpoint + "/sapi/v1/account/apiRestrictions?" + query_params.to_str();
std::vector<Header> headers;
headers.push_back(Header{api_key_header, api_key});
SetUpCurlOpt(curl, url, "", headers, Action::GET, chunk);
StartCurl(curl);
ParseToJson(chunk.response, result);
}
} | 33.57947 | 107 | 0.671383 | Hsin-Hung |
7bb5307d403a7aeb7338108d2dd8b342c703c01a | 9,797 | cpp | C++ | Othello/othello.cpp | MBadriNarayanan/C-Project | a0a117252d0ded90d0fa7b5a813ef205d80e20e5 | [
"MIT"
] | 1 | 2020-05-02T17:16:15.000Z | 2020-05-02T17:16:15.000Z | Othello/othello.cpp | MBadriNarayanan/C-Project | a0a117252d0ded90d0fa7b5a813ef205d80e20e5 | [
"MIT"
] | null | null | null | Othello/othello.cpp | MBadriNarayanan/C-Project | a0a117252d0ded90d0fa7b5a813ef205d80e20e5 | [
"MIT"
] | 1 | 2021-09-28T09:19:52.000Z | 2021-09-28T09:19:52.000Z | class square
{ int c_x,c_y;
int col;
public: void fill();
void plot();
void play(int game=3);
void draw_circle(int ,int , int );
int check_YELLOW();
int check(int, int, int, int);
int check_chance(int ,int );
int load_game(char *);
void load_fill();
void save_game(int);
void write_score(int , int );
void save_option(char * st);
void print_rules();
char * get_input(int , int , int , int ,int = 30,int=80);
void Menu();
} ob[8][8];
mouse m;
int player[2]={2,2};
int pos_i, pos_j,player_check;
void square ::fill()// Filling the array ob with center x,y coodinates and YELLOW colour
{ int x=125,color;
int y=100;
for(int i=0;i<8;i++)
{ x=125;
for(int j=0;j<8;j++,x = x+50)
{ ob[i][j].c_x=x;
ob[i][j].c_y=y;
ob[i][j].col = YELLOW;
}
y+=40;
}
// Filling the the center 4 boxes with BLUE and RED colour
ob[3][3].col= BLUE; ob[3][4].col= RED;
ob[4][3].col= BLUE; ob[4][4].col= RED;
for (i = 3; i<=4; i++)
{ for (int j = 3; j<=4; j++)
{
setcolor(WHITE);
setfillstyle(1,ob[i][j].col);
circle(ob[i][j].c_x, ob[i][j].c_y,15);
floodfill(ob[i][j].c_x, ob[i][j].c_y,WHITE);
}
}
}
void square ::load_fill()
{ int x=125,color;
int y=100;
for(int i=0;i<8;i++)
{ x=125;
for(int j=0;j<8;j++,x = x+50)
{ ob[i][j].c_x=x;
ob[i][j].c_y=y;
ob[i][j].col = getpixel(x,y);
}
y+=40;
}
}
void square::draw_circle(int i, int j, int d_c)
{
int x,y;
m.hide_mouse();
x = 100+j*50; y = 80+i*40;
setfillstyle(1,YELLOW);
bar(x+2,y+2,x+48,y+38);
setcolor(WHITE);
circle(x+25, y+20,15);
setfillstyle(1,d_c);
floodfill(x+25,y+20,WHITE);
m.show_mouse();
}
int square::check(int x,int y, int c, int oc)
{
int flag,s,p,i,j;
i = pos_i; j = pos_j;
flag = 0; s= 0;
do
{
i= i+x; j = j+y;
if ((i<0 || i>7)|| ( j <0 || j >7)) flag= 1;
else
{
p = ob[i][j].col;
if (p==c || p==YELLOW) flag=1;
else if(p==oc) s++;
}
} while (flag==0);
if (s !=0 && p==c)
{
i = pos_i; j = pos_j; player_check=1;
draw_circle(i,j,c);
ob[i][j].col=c;
for (int k = 1; k <= s; k++)
{
i = i+x; j = j+y;
ob[i][j].col=c;
draw_circle(i,j,c);
}
return s;
}
else return 0;
}
int square::check_chance(int color,int op_c)
{
int flag=0;
for (int i=0; i<8&&flag==0;i++)
{
for (int j=0; j<8&&flag==0;j++)
{
if (ob[i][j].col==YELLOW)
{
for (int k = -1,m=1; m<=9&&flag==0; m++)
{ if (m%3==0) k++;
if (ob[i+k][j+k].col==op_c)flag=1;
}
}
}
}
return flag;
}
int square::check_YELLOW()
{
int s = 0;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
if (ob[i][j].col==YELLOW) s++;
}
return s;
}
// load already saved game back
int square::load_game(char fname[])
{
int player_no;
ifstream f(fname);
f>>player[0]>>player[1]>>player_no;
for(int i=0;i<getmaxx();i++)
{ for(int j=0;j<getmaxy();j++)
{ int p;
f>>p;
putpixel(i,j,p);
}
}
f.close();
return player_no;
}
// write the score n of the player in the position x,210
void square::write_score(int x, int n)
{
char st[10];
setfillstyle(1,0);
bar(x-10,200,x+30,250);
settextstyle(3,0,3);
setcolor(WHITE);
itoa(n, st,10);
outtextxy(x,210,st);
}
// displaying the options save
void square::save_option(char * st)
{
setfillstyle(1,BLUE);
bar(10,420,100,450);
setcolor(WHITE);
outtextxy(20,430,st);
}
// Get input from user in x,y coordinate
char * square::get_input(int x, int y, int bc, int col,int inc,int barcord)
{
char string[100]="\0",ch;
int i =0;
ch = getch();
while(ch!='\r')
{
if (ch!='\b') string[i]= ch;
else i=i-2;
string[i+1]= '\0';
setfillstyle(1,bc);
bar(x,y,x+barcord,y+inc);
setcolor(col);
outtextxy(x,y+10,string);
i++;
ch = getch();
}
return string;
}
// Write the game pixel by pixel in the hard disk
void file_write(char f_name[],int player_no)
{
ofstream f(f_name);
f <<player[0]<<" " << player[1]<< " "
<<player_no<<" ";
for(int i=0;i<getmaxx();i++)
{ for(int j=0;j<getmaxy();j++)
{ int p=getpixel(i,j);
f<<p<<" ";
}
}
f.close();
}
// Printing the Rules
void square::print_rules()
{
char st[100];
int y=10;
ifstream f("rules.txt");
settextstyle(3,0,2);
while(f.getline(st,100,'\n'))
{ outtextxy(10,y,st);
y=y+40;
if(y>=440)
{ getch();
cleardevice();
y=10;
}
}
}
// displaying the option Main Menu
void return_option()
{
setfillstyle(1,BLUE);
bar(300,420,380,450);
setcolor(WHITE);
outtextxy(303,430,"MAIN MENU");
}
// displaying the option Quit
void quit_option()
{
setfillstyle(1,BLUE);
bar(580,420,640,450);
setcolor(WHITE);
outtextxy(590,430,"QUIT");
}
// displaying the Save
void square::save_game(int player_no)
{
char f_name[20];
setfillstyle(1,BLUE);
bar(10,420,200,450);
setcolor(WHITE);
settextstyle(0,0,1);
outtextxy(10,430,"File Name : ");
strcpy(f_name,get_input(100,420,BLUE,WHITE));
settextstyle(0,0,1);
setfillstyle(1,BLUE);
bar(10,420,200,450);
save_option("SAVING GAME...");
delay(1000);
setfillstyle(1,BLACK);
bar(10,420,200,450);
save_option("SAVE GAME");
file_write(f_name,player_no);
}
// Play the Game
void square::play(int game)
{
int color,opp_col,points,pl_chance,pl,k;
char st[10];
char name[2][50];
if(game==3)
{
settextstyle(3,0,3);
outtextxy(10,100,"Enter Player Name 1 : ");
strcpy(name[0],get_input(270,90,0,WHITE,60,400));
outtextxy(10,200,"Enter Player Name 2 : ");
strcpy(name[1],get_input(270,190,0,WHITE,60,400));
cleardevice();
setcolor(LIGHTCYAN);
settextstyle(3,0,4);
outtextxy(200,20,"O T H E L L O");
setfillstyle(1,YELLOW);
setcolor(GREEN);
setfillstyle(1,YELLOW);
setcolor(YELLOW);
bar(100,80,8*50+100,80+8*40);
setcolor(GREEN);
for(int x=100;x<=500;x+=50)
line(x,80,x,400);
for( int y=80;y<=400;y+=40)
line(100,y,500,y);
setcolor(4);
settextstyle(0,0,1);
fill();
save_option("SAVE GAME");
return_option();
quit_option();
settextstyle(1,0,2);
setcolor(LIGHTBLUE);
outtextxy(10,100,name[0]);
setcolor(LIGHTRED);
outtextxy(575,100,name[1]);
write_score(10,player[0]);
write_score(550,player[1]);
game = 0;
}
m.show_mouse();
int flag = 1,pos;
for (k = game; flag!=0; k++)
{ flag = check_YELLOW();
if (flag==0) continue;
switch(k%2)
{
case 0 : color = BLUE;
opp_col= RED;pos = 5;
pl=1;break;
case 1 : color = RED;
opp_col= BLUE;pos = 550;
pl=0;
break;
}
pl_chance= check_chance(color,opp_col);
if (pl_chance==0)
{
cout<<"no chance"; flag=0;
player[pl]+= (64-k+1);
continue;
}
settextstyle(1,0,2);
setcolor(color);
outtextxy(pos,250,"Your");
outtextxy(pos,280,"chance");
m.get_status(); delay(500);
pos_j = (cx-100)/50;
pos_i = (cy-80)/40;
if ((cx >= 580 && cx <=640) && (cy >= 420 && cy <= 450) ) exit(0);
if ((cx >= 10 && cx <=200) && (cy >= 420 && cy <= 450) )
{
m.hide_mouse();
save_game(k%2);
m.show_mouse();k--;
setfillstyle(1,0);
bar(pos,250,pos+90,300);
continue;
}
if ((cx >= 300 && cx <=380) && (cy >= 420 && cy <= 450) )
{
flag=0;
continue;
}
if (ob[pos_i][pos_j].col==YELLOW)
{
int sum = 0,kk; kk = 0;
player_check = 0;
for (int pos =1; pos <=8; pos++)
{
switch (pos)
{
case 1 : points= check(0,1,color,opp_col); break;
case 2 : points= check(-1,1,color,opp_col); break;
case 3 : points= check(-1,0,color,opp_col); break;
case 4 : points= check(-1,-1,color,opp_col);break;
case 5 : points= check(0,-1,color,opp_col); break;
case 6 : points= check(1,-1,color,opp_col); break;
case 7 : points= check(1,0,color,opp_col); break;
case 8 : points= check(1,1,color,opp_col); break;
}
if (points >0) kk++;
sum = sum+points;
}
if (kk>0) kk=1; else kk = 0;
if (kk==1)
{
switch(k%2&& sum!=0)
{
case 0 : player[0] += sum+kk; player[1]-= sum;break;
case 1 : player[1] += sum+kk; player[0]-= sum;break;
}
write_score(10,player[0]);
write_score(560,player[1]);
}
else k--;
}
delay(100);
setfillstyle(1,0);
bar(pos,250,pos+90,300);
}
//setcolor();
write_score(10,player[0]);
write_score(600,player[1]);
if(player[0] >player[1])
{
outtextxy(420,400,"Winner ");
outtextxy(400,250,name[0]);
}
else
if(player[1] >player[0])
{
outtextxy(420,400,"Winner ");
outtextxy(400,250,name[1]);
}
else outtextxy(400,400,"TIE ");
}
void square::Menu()
{
char st[][20] = {"1.New Game", "2.Load Game", "3.Help",
"4.Back to Main"};
char f_name[20];
int a,b,k;
char ch[5]="\0";
do
{
a = 9; b = 2;
initgraph(&a,&b,"f:\\TC\\bgi");
setfillstyle(1,BLUE);
bar(0,0,getmaxx(),getmaxy());
setcolor(WHITE);
settextstyle(4,0,3);
b = 100;
for (int i = 0; i <=3;i++)
{
outtextxy(250,b,st[i]);
b = b+50;
}
outtextxy(200,b,"Enter Option : ");
ch[0] = getche();
//getch();
ch[1] = '\0';
outtextxy(360,b,ch);
//delay(1000);
getch();
cleardevice();
switch(ch[0])
{
case '1' :play(); break;
case '2' :outtextxy(10,100,"Enter File Name : ");
strcpy(f_name,get_input(270,90,0,WHITE));
k = load_game(f_name);load_fill();
play(k);break;
case '3' :print_rules();break;
case '4' :;//exit(0);
}
//getch();
closegraph();
}while(ch[0]!='4');
}
void othello()
{
square x;
x.Menu();
}
| 21.819599 | 88 | 0.54384 | MBadriNarayanan |
7bb9222e4be394a7c69581b489375ab5b69c9a15 | 8,253 | cpp | C++ | Sourcecode/mxtest/core/MusicDataGroupTest.cpp | diskzero/MusicXML-Class-Library | bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db | [
"MIT"
] | null | null | null | Sourcecode/mxtest/core/MusicDataGroupTest.cpp | diskzero/MusicXML-Class-Library | bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db | [
"MIT"
] | null | null | null | Sourcecode/mxtest/core/MusicDataGroupTest.cpp | diskzero/MusicXML-Class-Library | bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db | [
"MIT"
] | null | null | null | // MusicXML Class Library
// Copyright (c) by Matthew James Briggs
// Distributed under the MIT License
#include "mxtest/control/CompileControl.h"
#ifdef MX_COMPILE_CORE_TESTS
#include "cpul/cpulTestHarness.h"
#include "mxtest/core/HelperFunctions.h"
#include "mxtest/core/MusicDataGroupTest.h"
#include "mxtest/core/MusicDataChoiceTest.h"
#include "mxtest/core/NoteTest.h"
#include "mxtest/core/BackupTest.h"
#include "mxtest/core/ForwardTest.h"
#include "mxtest/core/DirectionTest.h"
#include "mxtest/core/PropertiesTest.h"
#include "mxtest/core/HarmonyTest.h"
#include "mxtest/core/FiguredBassTest.h"
#include "mxtest/core/PrintTest.h"
#include "mxtest/core/SoundTest.h"
#include "mxtest/core/BarlineTest.h"
#include "mxtest/core/GroupingTest.h"
using namespace mx::core;
using namespace std;
using namespace mxtest;
TEST( Test01, MusicDataGroup )
{
variant v = variant::one;
MusicDataGroupPtr object = tgenMusicDataGroup( v );
stringstream expected;
tgenMusicDataGroupExpected( expected, 1, v );
stringstream actual;
bool isOneLineOnly;
object->streamContents( actual, 1, isOneLineOnly );
CHECK_EQUAL( expected.str(), actual.str() )
CHECK( ! object->hasAttributes() )
CHECK( ! object->hasContents() )
}
TEST( Test02, MusicDataGroup )
{
variant v = variant::two;
MusicDataGroupPtr object = tgenMusicDataGroup( v );
stringstream expected;
tgenMusicDataGroupExpected( expected, 1, v );
stringstream actual;
bool isOneLineOnly;
object->streamContents( actual, 1, isOneLineOnly );
CHECK_EQUAL( expected.str(), actual.str() )
CHECK( ! object->hasAttributes() )
CHECK( object->hasContents() )
}
TEST( Test03, MusicDataGroup )
{
variant v = variant::three;
MusicDataGroupPtr object = tgenMusicDataGroup( v );
stringstream expected;
tgenMusicDataGroupExpected( expected, 1, v );
stringstream actual;
bool isOneLineOnly;
object->streamContents( actual, 1, isOneLineOnly );
CHECK_EQUAL( expected.str(), actual.str() )
CHECK( ! object->hasAttributes() )
CHECK( object->hasContents() )
}
namespace mxtest
{
MusicDataGroupPtr tgenMusicDataGroup( variant v )
{
MusicDataGroupPtr o = makeMusicDataGroup();
switch ( v )
{
case variant::one:
{
}
break;
case variant::two:
{
/* <xs:element name="note" type="note"/>
<xs:element name="backup" type="backup"/>
<xs:element name="forward" type="forward"/>
<xs:element name="direction" type="direction"/>
<xs:element name="attributes" type="attributes"/>
<xs:element name="harmony" type="harmony"/>
<xs:element name="figured-bass" type="figured-bass"/>
<xs:element name="print" type="print"/>
<xs:element name="sound" type="sound"/>
<xs:element name="barline" type="barline"/>
<xs:element name="grouping" type="grouping"/>
<xs:element name="link" type="link"/>
<xs:element name="bookmark" type="bookmark"/> */
auto x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::note );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::forward );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::properties );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::figuredBass );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::sound );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::grouping );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::bookmark );
o->addMusicDataChoice( x );
x.reset();
}
break;
case variant::three:
{
/* <xs:element name="note" type="note"/>
<xs:element name="backup" type="backup"/>
<xs:element name="forward" type="forward"/>
<xs:element name="direction" type="direction"/>
<xs:element name="attributes" type="attributes"/>
<xs:element name="harmony" type="harmony"/>
<xs:element name="figured-bass" type="figured-bass"/>
<xs:element name="print" type="print"/>
<xs:element name="sound" type="sound"/>
<xs:element name="barline" type="barline"/>
<xs:element name="grouping" type="grouping"/>
<xs:element name="link" type="link"/>
<xs:element name="bookmark" type="bookmark"/> */
auto x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::backup );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::direction );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::harmony );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::print );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::barline );
o->addMusicDataChoice( x );
x.reset();
x = tgenMusicDataChoiceAll( v );
x->setChoice( MusicDataChoice::Choice::link );
o->addMusicDataChoice( x );
x.reset();
}
break;
default:
break;
}
return o;
}
void tgenMusicDataGroupExpected( std::ostream& os, int i, variant v )
{
switch ( v )
{
case variant::one:
{
}
break;
case variant::two:
{
tgenNoteExpected( os, i, v );
os << std::endl;
tgenForwardExpected( os, i, v );
os << std::endl;
tgenPropertiesExpected( os, i, v );
os << std::endl;
tgenFiguredBassExpected( os, i, v );
os << std::endl;
tgenSoundExpected( os, i, v );
os << std::endl;
tgenGroupingExpected( os, i, v );
os << std::endl;
streamLine( os, i, R"(<bookmark id="ID" name="bookmarkStringTwo"/>)", false );
}
break;
case variant::three:
{
tgenBackupExpected( os, i, v );
os << std::endl;
tgenDirectionExpected( os, i, v );
os << std::endl;
tgenHarmonyExpected( os, i, v );
os << std::endl;
tgenPrintExpected( os, i, v );
os << std::endl;
tgenBarlineExpected( os, i, v );
os << std::endl;
streamLine( os, i, R"(<link xlink:href="linkStringThree"/>)", false );
}
break;
default:
break;
}
}
}
#endif
| 35.573276 | 94 | 0.515691 | diskzero |
7bb9d944f93d87f4a9c032404c24759ef5e140b6 | 5,320 | cpp | C++ | tools/unittests/Runtime/ArgmaxTest.cpp | jdh8/onnc | 018ff007e20734585579aac87ca9a573aa012909 | [
"BSD-3-Clause"
] | 1 | 2021-02-25T13:36:26.000Z | 2021-02-25T13:36:26.000Z | tools/unittests/Runtime/ArgmaxTest.cpp | jdh8/onnc | 018ff007e20734585579aac87ca9a573aa012909 | [
"BSD-3-Clause"
] | null | null | null | tools/unittests/Runtime/ArgmaxTest.cpp | jdh8/onnc | 018ff007e20734585579aac87ca9a573aa012909 | [
"BSD-3-Clause"
] | null | null | null | #if defined(__GNUC__) || defined(_MSC_VER)
# define restrict __restrict
#else
# define restrict
#endif
extern "C" {
#include <onnc/Runtime/onnc-runtime.h>
}
#undef restrict
#include "norm.hpp"
#include <skypat/skypat.h>
SKYPAT_F(Operator_ArgMax, test_argmax_no_keepdims_example)
{
const float input_0[] = {2.0, 1.0, 3.0, 10.0};
const int32_t input_0_ndim = 2;
const int32_t input_0_dims[] = {2, 2};
float output_0[2];
const int32_t output_0_ndim = 1;
const int32_t output_0_dims[] = {2};
const float answer_0[] = {0, 1};
const int32_t axis = 1;
const int32_t keepdims = 0;
using dragonite::norm;
ONNC_RUNTIME_argmax_float(nullptr, input_0, input_0_ndim, input_0_dims, output_0, output_0_ndim, output_0_dims, axis,
keepdims);
ASSERT_TRUE(norm(answer_0, output_0, 2) <= 1e-5 * norm(answer_0, 2));
}
SKYPAT_F(Operator_ArgMax, test_argmax_no_keepdims_random)
{
const float input_0[] = {7.916196, -5.050213, -6.5481505, -2.372179, 3.4055011, -5.259473, -5.876902, 9.181546,
3.8622417, 3.1683996, -4.334476, -7.461097, 8.506922, 5.0490994, 7.3549848, 0.19403115,
9.845381, 4.322886, 8.492865, -3.9024255, -3.6774218, -7.866902, 9.484194, 4.339801};
const int32_t input_0_ndim = 3;
const int32_t input_0_dims[] = {2, 3, 4};
float output_0[8];
const int32_t output_0_ndim = 2;
const int32_t output_0_dims[] = {2, 4};
const float answer_0[] = {0, 2, 2, 1, 1, 0, 2, 2};
const int32_t axis = 1;
const int32_t keepdims = 0;
using dragonite::norm;
ONNC_RUNTIME_argmax_float(nullptr, input_0, input_0_ndim, input_0_dims, output_0, output_0_ndim, output_0_dims, axis,
keepdims);
ASSERT_TRUE(norm(answer_0, output_0, 8) <= 1e-5 * norm(answer_0, 8));
}
SKYPAT_F(Operator_ArgMax, test_argmax_keepdims_example)
{
const float input_0[] = {2.0, 1.0, 3.0, 10.0};
const int32_t input_0_ndim = 2;
const int32_t input_0_dims[] = {2, 2};
float output_0[2];
const int32_t output_0_ndim = 2;
const int32_t output_0_dims[] = {2, 1};
const float answer_0[] = {0, 1};
const int32_t axis = 1;
const int32_t keepdims = 1;
using dragonite::norm;
ONNC_RUNTIME_argmax_float(nullptr, input_0, input_0_ndim, input_0_dims, output_0, output_0_ndim, output_0_dims, axis,
keepdims);
ASSERT_TRUE(norm(answer_0, output_0, 2) <= 1e-5 * norm(answer_0, 2));
}
SKYPAT_F(Operator_ArgMax, test_argmax_keepdims_random)
{
const float input_0[] = {-2.8666658, -9.930011, 8.533137, 9.542501, 2.6286595, 6.1863194, 0.39168122, 3.0457706,
-8.771415, 9.400704, 1.3585372, -1.9816046, -0.8143469, -2.7263594, -8.583799, -5.656237,
7.053225, 7.5800247, -9.178458, 2.4859655, 0.41899338, 5.0151973, -4.177078, -8.727053};
const int32_t input_0_ndim = 3;
const int32_t input_0_dims[] = {2, 3, 4};
float output_0[8];
const int32_t output_0_ndim = 3;
const int32_t output_0_dims[] = {2, 1, 4};
const float answer_0[] = {1, 2, 0, 0, 1, 1, 2, 1};
const int32_t axis = 1;
const int32_t keepdims = 1;
using dragonite::norm;
ONNC_RUNTIME_argmax_float(nullptr, input_0, input_0_ndim, input_0_dims, output_0, output_0_ndim, output_0_dims, axis,
keepdims);
ASSERT_TRUE(norm(answer_0, output_0, 8) <= 1e-5 * norm(answer_0, 8));
}
SKYPAT_F(Operator_ArgMax, test_argmax_default_axis_example)
{
const float input_0[] = {2.0, 1.0, 3.0, 10.0};
const int32_t input_0_ndim = 2;
const int32_t input_0_dims[] = {2, 2};
float output_0[2];
const int32_t output_0_ndim = 2;
const int32_t output_0_dims[] = {1, 2};
const float answer_0[] = {1, 1};
const int32_t keepdims = 1;
const int32_t axis = 0;
using dragonite::norm;
ONNC_RUNTIME_argmax_float(nullptr, input_0, input_0_ndim, input_0_dims, output_0, output_0_ndim, output_0_dims, axis,
keepdims);
ASSERT_TRUE(norm(answer_0, output_0, 2) <= 1e-5 * norm(answer_0, 2));
}
SKYPAT_F(Operator_ArgMax, test_argmax_default_axis_random)
{
const float input_0[] = {-9.826185, -7.196741, 7.7552886, -7.4781475, -1.815236, -5.1710205,
3.1197412, -5.936099, 9.407172, 1.4273096, -1.4433477, -7.499204,
0.024073577, -6.7123213, 8.195043, -6.8797135, -7.130009, -9.179616,
-2.3986602, 9.803744, 5.5405087, -0.44200945, -1.0355306, -2.874489};
const int32_t input_0_ndim = 3;
const int32_t input_0_dims[] = {2, 3, 4};
float output_0[12];
const int32_t output_0_ndim = 3;
const int32_t output_0_dims[] = {1, 3, 4};
const float answer_0[] = {1, 1, 1, 1, 0, 0, 0, 1, 0, 0, 1, 1};
const int32_t keepdims = 1;
const int32_t axis = 0;
using dragonite::norm;
ONNC_RUNTIME_argmax_float(nullptr, input_0, input_0_ndim, input_0_dims, output_0, output_0_ndim, output_0_dims, axis,
keepdims);
ASSERT_TRUE(norm(answer_0, output_0, 12) <= 1e-5 * norm(answer_0, 12));
}
| 41.24031 | 120 | 0.618233 | jdh8 |
7bba4af1cef957d08f16b1d9a35229cdbbf47e4a | 1,755 | cc | C++ | servlib/bundling/ForwardingInfo.cc | delay-tolerant-networking/DTN2 | 1c12a9dea32c5cbae8c46db105012a2031f4161e | [
"Apache-2.0"
] | 14 | 2016-06-27T19:28:23.000Z | 2021-06-28T20:41:17.000Z | servlib/bundling/ForwardingInfo.cc | delay-tolerant-networking/DTN2 | 1c12a9dea32c5cbae8c46db105012a2031f4161e | [
"Apache-2.0"
] | 3 | 2020-09-18T13:48:53.000Z | 2021-05-27T18:28:14.000Z | servlib/bundling/ForwardingInfo.cc | lauramazzuca21/DTNME | c97b598b09a8c8e97c2e4136879d9f0e157c8df7 | [
"Apache-2.0"
] | 10 | 2020-09-26T05:08:40.000Z | 2022-01-25T12:57:55.000Z | /*
* Copyright 2006-2007 The MITRE 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.
*
* The US Government will not be charged any license fee and/or royalties
* related to this software. Neither name of The MITRE Corporation; nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*/
#ifdef HAVE_CONFIG_H
# include <dtn-config.h>
#endif
#include "ForwardingInfo.h"
#include "bundling/BundleDaemon.h"
#include "contacts/ContactManager.h"
namespace dtn {
void
ForwardingInfo::serialize(oasys::SerializeAction *a)
{
a->process("state", &state_);
a->process("action", &action_);
a->process("link_name", &link_name_);
a->process("regid", ®id_);
a->process("remote_eid", &remote_eid_);
a->process("timestamp_sec", ×tamp_.sec_);
a->process("timestamp_usec", ×tamp_.usec_);
if(a->action_code() == oasys::Serialize::UNMARSHAL) {
if(state_ == QUEUED && !BundleDaemon::instance()->contactmgr()->has_link(link_name_.c_str())) {
state_ = TRANSMIT_FAILED;
timestamp_.get_time();
}
}
}
} // namespace dtn
| 34.411765 | 103 | 0.688319 | delay-tolerant-networking |
7bbc2d3f991fedd2498b0bab564e00a59c5e82d6 | 3,303 | cpp | C++ | test/PAGFontTest.cpp | henryzt/libpag | 9d3bb92a5a90240615884ff7f8afc3ea6c34d7a1 | [
"BSL-1.0",
"CC0-1.0",
"MIT"
] | 1 | 2022-02-15T03:04:01.000Z | 2022-02-15T03:04:01.000Z | test/PAGFontTest.cpp | henryzt/libpag | 9d3bb92a5a90240615884ff7f8afc3ea6c34d7a1 | [
"BSL-1.0",
"CC0-1.0",
"MIT"
] | null | null | null | test/PAGFontTest.cpp | henryzt/libpag | 9d3bb92a5a90240615884ff7f8afc3ea6c34d7a1 | [
"BSL-1.0",
"CC0-1.0",
"MIT"
] | null | null | null | /////////////////////////////////////////////////////////////////////////////////////////////////
//
// Tencent is pleased to support the open source community by making libpag available.
//
// Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// unless required by applicable law or agreed to in writing, software distributed under the
// license is distributed on an "as is" basis, without warranties or conditions of any kind,
// either express or implied. see the license for the specific language governing permissions
// and limitations under the license.
//
/////////////////////////////////////////////////////////////////////////////////////////////////
#include <fstream>
#include <vector>
#include "base/utils/TimeUtil.h"
#include "framework/pag_test.h"
#include "framework/utils/PAGTestUtils.h"
#include "nlohmann/json.hpp"
namespace pag {
using nlohmann::json;
/**
* 用例描述: 字体相关功能测试
*/
PAG_TEST(PAGFontTest, TestFont) {
json dumpJson;
json compareJson;
std::ifstream inputFile("../test/res/compare_font_md5.json");
bool needCompare = false;
if (inputFile) {
needCompare = true;
inputFile >> compareJson;
}
std::vector<std::string> compareVector;
std::string fileName = "test_font";
if (needCompare && compareJson.contains(fileName) && compareJson[fileName].is_array()) {
compareVector = compareJson[fileName].get<std::vector<std::string>>();
}
PAGFont::RegisterFont("../resources/font/NotoSerifSC-Regular.otf", 0, "TTTGBMedium", "Regular");
auto TestPAGFile = PAGFile::Load("../resources/apitest/test_font.pag");
ASSERT_NE(TestPAGFile, nullptr);
auto pagSurface = PAGSurface::MakeOffscreen(TestPAGFile->width(), TestPAGFile->height());
ASSERT_NE(pagSurface, nullptr);
auto pagPlayer = std::make_shared<PAGPlayer>();
pagPlayer->setSurface(pagSurface);
pagPlayer->setComposition(TestPAGFile);
Frame totalFrames = TimeToFrame(TestPAGFile->duration(), TestPAGFile->frameRate());
Frame currentFrame = 0;
std::vector<std::string> md5Vector;
std::string errorMsg;
bool status = true;
while (currentFrame < totalFrames) {
//添加0.1帧目的是保证progress不会由于精度问题帧数计算错误,frame应该使用totalFrames作为总体帧数。因为对于file来说总时长为[0,totalFrames],对应于[0,1],因此归一化时,分母应该为totalFrames
pagPlayer->setProgress((currentFrame + 0.1) * 1.0 / totalFrames);
pagPlayer->flush();
auto skImage = MakeSnapshot(pagSurface);
std::string md5 = DumpMD5(skImage);
md5Vector.push_back(md5);
if (needCompare && compareVector[currentFrame] != md5) {
errorMsg += (std::to_string(currentFrame) + ";");
if (status) {
std::string imagePath =
"../test/out/" + fileName + "_" + std::to_string(currentFrame) + ".png";
Trace(skImage, imagePath);
status = false;
}
}
currentFrame++;
}
EXPECT_EQ(errorMsg, "") << fileName << " frame fail";
dumpJson[fileName] = md5Vector;
std::ofstream outFile("../test/out/compare_font_md5.json");
outFile << std::setw(4) << dumpJson << std::endl;
outFile.close();
}
} // namespace pag
| 35.902174 | 129 | 0.659098 | henryzt |
7bbebd4206ef6ff96f71336e287356d3c17ce424 | 3,929 | cpp | C++ | src/motioncore/crypto/output_message_handler.cpp | Udbhavbisarya23/MOTION2NX | eb26f639d8c1729cebfa85dd3bf41b770cebe92b | [
"MIT"
] | 6 | 2021-11-05T00:39:47.000Z | 2022-02-26T16:42:55.000Z | src/motioncore/crypto/output_message_handler.cpp | Udbhavbisarya23/MOTION2NX | eb26f639d8c1729cebfa85dd3bf41b770cebe92b | [
"MIT"
] | 7 | 2021-11-07T06:53:00.000Z | 2022-03-23T11:46:40.000Z | src/motioncore/crypto/output_message_handler.cpp | Udbhavbisarya23/MOTION2NX | eb26f639d8c1729cebfa85dd3bf41b770cebe92b | [
"MIT"
] | 7 | 2021-11-04T12:01:07.000Z | 2022-03-29T12:15:23.000Z | // MIT License
//
// Copyright (c) 2020 Lennart Braun
//
// 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 "output_message_handler.h"
#include <fmt/format.h>
#include "communication/fbs_headers/message_generated.h"
#include "communication/fbs_headers/output_message_generated.h"
#include "utility/constants.h"
#include "utility/logger.h"
namespace MOTION::Crypto {
OutputMessageHandler::OutputMessageHandler(std::size_t party_id, std::shared_ptr<Logger> logger)
: party_id_(party_id), logger_(std::move(logger)) {}
ENCRYPTO::ReusableFiberFuture<std::vector<std::uint8_t>>
OutputMessageHandler::register_for_output_message(std::size_t gate_id) {
ENCRYPTO::ReusableFiberPromise<std::vector<std::uint8_t>> promise;
auto future = promise.get_future();
std::unique_lock<std::mutex> lock(output_message_promises_mutex_);
auto [_, success] = output_message_promises_.insert({gate_id, std::move(promise)});
lock.unlock();
if (!success) {
if (logger_) {
logger_->LogError(
fmt::format("Tried to register twice for OutputMessage with gate#{}", gate_id));
}
throw std::logic_error(
fmt::format("Tried to register twice for OutputMessage with gate#{}", gate_id));
}
if constexpr (MOTION_VERBOSE_DEBUG) {
if (logger_) {
logger_->LogDebug(fmt::format("Registered for OutputMessage from Party#{} for gate#{}",
gate_id, party_id_));
}
}
return future;
}
void OutputMessageHandler::received_message(std::size_t,
std::vector<std::uint8_t> &&output_message) {
assert(!output_message.empty());
auto message = Communication::GetMessage(reinterpret_cast<std::uint8_t *>(output_message.data()));
auto output_message_ptr = Communication::GetOutputMessage(message->payload()->data());
auto gate_id = output_message_ptr->gate_id();
// find promise
auto it = output_message_promises_.find(gate_id);
if (it == output_message_promises_.end()) {
// no promise found -> drop message
if (logger_) {
logger_->LogError(
fmt::format("Received unexpected OutputMessage from Party#{} for gate#{}, dropping",
party_id_, gate_id));
}
return;
}
auto &promise = it->second;
// put the received message into the promise
try {
promise.set_value(std::move(output_message));
} catch (std::future_error &e) {
// there might be already a value in the promise
if (logger_) {
logger_->LogError(fmt::format(
"Error while processing OutputMessage from Party#{} for gate#{}, dropping: {}", party_id_,
gate_id, e.what()));
}
return;
}
if constexpr (MOTION_VERBOSE_DEBUG) {
if (logger_) {
logger_->LogDebug(
fmt::format("Received an OutputMessage from Party#{} for gate#{}", party_id_, gate_id));
}
}
}
} // namespace MOTION::Crypto
| 38.519608 | 100 | 0.697633 | Udbhavbisarya23 |
7bc37a0f5eb3e44bb6b106c6c4b22bd0469ffc6e | 764 | cpp | C++ | pc-qa-matchbox/DPQAlib/XMLUtils.cpp | openpreserve/scape | 8b08bbad43feaa7a5070412079d476e31bb8194b | [
"Apache-2.0"
] | 6 | 2015-05-19T09:48:16.000Z | 2020-01-13T02:29:57.000Z | pc-qa-matchbox/DPQAlib/XMLUtils.cpp | openpreserve/scape | 8b08bbad43feaa7a5070412079d476e31bb8194b | [
"Apache-2.0"
] | 2 | 2021-06-03T23:48:14.000Z | 2021-09-02T15:27:13.000Z | pc-qa-matchbox/DPQAlib/XMLUtils.cpp | openpreserve/scape | 8b08bbad43feaa7a5070412079d476e31bb8194b | [
"Apache-2.0"
] | 4 | 2015-05-19T09:48:25.000Z | 2021-08-18T08:53:10.000Z | #include "XMLUtils.h"
XMLUtils::XMLUtils(void)
{
}
XMLUtils::~XMLUtils(void)
{
}
//string XMLUtils::getElementValue(DOMElement *rootelem, const string *name)
//{
// XMLCh* elemName = XMLString::transcode(name->c_str());
//
// DOMNodeList* nodes = rootelem->getElementsByTagName(elemName);
// DOMElement* elem = dynamic_cast< DOMElement* >( nodes->item(0) );
//
// const XMLCh* xmlstr = elem->getTextContent();
//
// return XMLString::transcode(xmlstr);
//}
//
//string XMLUtils::getElementValue(DOMElement *rootelem)
//{
// const XMLCh* xmlstr = rootelem->getTextContent();
// return XMLString::transcode(xmlstr);
//}
//
//string XMLUtils::xmlChToString(const XMLCh* toTranscode)
//{
// char* test = XMLString::transcode(toTranscode);
//
// return test;
//} | 22.470588 | 76 | 0.693717 | openpreserve |
7bc678974e45c20f132531188608fd8281d719b1 | 6,182 | hpp | C++ | Source/Terrain/TerrainConstructionData.hpp | storm20200/UniversitySecondYearTerrain | 4455f9804e165202839fdd05f660f6a9bbc999eb | [
"MIT"
] | 2 | 2016-06-05T04:52:35.000Z | 2016-07-10T04:18:04.000Z | Source/Terrain/TerrainConstructionData.hpp | storm20200/University3DGraphicsTerrain | 4455f9804e165202839fdd05f660f6a9bbc999eb | [
"MIT"
] | null | null | null | Source/Terrain/TerrainConstructionData.hpp | storm20200/University3DGraphicsTerrain | 4455f9804e165202839fdd05f660f6a9bbc999eb | [
"MIT"
] | null | null | null | #ifndef TERRAIN_CONSTRUCTION_DATA_3GP_HPP
#define TERRAIN_CONSTRUCTION_DATA_3GP_HPP
// Personal headers.
#include <Terrain/Terrain.hpp>
/// <summary>
/// A structure containing all the information required to generate terrain elements and vertices.
/// </summary>
class Terrain::ConstructionData final
{
public:
/////////////////////////////////
// Constructors and destructor //
/////////////////////////////////
/// <summary> Constructs a Terrain::ConstructionData object with the given dimensions. </summary>
/// <parma name="width"> How many vertices wide should the terrain be? </param>
/// <param name="depth"> How many vertices deep should the terrain be? </param>
/// <param name="divisor"> What will the terrain dimensions be subdivided by? </param>
/// <param name="worldWidth"> How many world units wide is the terrain? </param>
/// <param name="worldDepth"> How many world units deep is the terrain? </param>
ConstructionData (const unsigned int width, const unsigned int depth, const unsigned int divisor,
const float worldWidth, const float worldDepth);
ConstructionData (ConstructionData&& move);
ConstructionData& operator= (ConstructionData&& move);
ConstructionData() = default;
ConstructionData (const ConstructionData& copy) = default;
ConstructionData& operator= (const ConstructionData& copy) = default;
~ConstructionData() = default;
//////////////////////
// Public interface //
//////////////////////
/// <summary> Causes all stored values to be recalculated from different values. </summary>
/// <parma name="width"> How many vertices wide should the terrain be? </param>
/// <param name="depth"> How many vertices deep should the terrain be? </param>
/// <param name="divisor"> What will the terrain dimensions be subdivided by? </param>
/// <param name="worldWidth"> How many world units wide is the terrain? </param>
/// <param name="worldDepth"> How many world units deep is the terrain? </param>
void recalculate (const unsigned int width, const unsigned int depth, const unsigned int divisor,
const float worldWidth, const float worldDepth);
/// <summary> Gets the width of the terrain. </summary>
/// <returns> How many vertices wide the terrain should be. </returns>
unsigned int getWidth() const { return m_width; }
/// <summary> Gets the depth of the terrain. </summary>
/// <returns> How many vertices deep the terrain should be. </returns>
unsigned int getDepth() const { return m_depth; }
/// <summary> Gets the total number of vertices for the terrain. </summary>
/// <returns> How many total vertices the terrain should be. </returns>
unsigned int getVertexCount() const { return m_vertexCount; }
/// <summary> Gets the divisor of the terrain. </summary>
/// <returns> How many vertices wide and deep terrain patches should be. </returns>
unsigned int getDivisor() const { return m_divisor; }
/// <summary> Gets the number of vertices per segment. </summary>
/// <returns> The amount of vertices that make up a segment of terrain. </returns>
unsigned int getMeshVertices() const { return m_meshVertices; }
/// <summary> Gets the mesh width of the terrain </summary>
/// <returns> How many meshes wide the terrain should be. </returns>
unsigned int getMeshCountX() const { return m_meshCountX; }
/// <summary> Gets the mesh depth of the terrain. </summary>
/// <returns> How many meshes deep the terrain should be. </returns>
unsigned int getMeshCountZ() const { return m_meshCountZ; }
/// <summary> Gets the total number of meshes of the terrain. </summary>
/// <returns> How many total meshes there should be. </returns>
unsigned int getMeshTotal() const { return m_meshTotal; }
/// <summary> Gets the width of the terrain in world units. </summary>
/// <returns> The width of the terrain in world units. </returns>
float getWorldWidth() const { return m_worldWidth; }
/// <summary> Gets the depth of the terrain in world units. </summary>
/// <returns> The depth of the terrain in world units. </returns>
float getWorldDepth() const { return m_worldDepth; }
/// <summary> Gets the area of the terrain in world units. </summary>
/// <returns> The width of the terrain in world units. </returns>
float getWorldArea() const { return m_worldArea; }
private:
///////////////////
// Internal data //
///////////////////
unsigned int m_width { 0 }; //!< How many vertices wide should the terrain be?
unsigned int m_depth { 0 }; //!< How many vertices deep should the terrain be?
unsigned int m_vertexCount { 0 }; //!< The total number of vertices that make up the terrain.
unsigned int m_divisor { 0 }; //!< The width and depth of each terrain partition.
unsigned int m_meshVertices { 0 }; //!< How many vertices make up a segment of terrain.
unsigned int m_meshCountX { 0 }; //!< How many meshes wide the terrain is.
unsigned int m_meshCountZ { 0 }; //!< How many meshes deep the terrain is.
unsigned int m_meshTotal { 0 }; //!< How many total meshes will there be when the terrain is completed.
float m_worldWidth { 0.f }; //!< How many world units wide is the terrain?
float m_worldDepth { 0.f }; //!< How many world units deep is the terrain?
float m_worldArea { 0.f }; //!< The total area of the terrain in world units.
};
#endif // TERRAIN_CONSTRUCTION_DATA_3GP_HPP | 52.837607 | 119 | 0.602232 | storm20200 |
dcf24a695c136a6aae5c03d46bc526c17eac0baa | 2,217 | hpp | C++ | GPUImage-x/proj.iOS/GPUImage-x/GPUImage-x/GLProgram.hpp | antowang/GPUImage-x | 8c9237fd0bde008a69ccab5dc267871c4959f97d | [
"Apache-2.0"
] | 197 | 2017-04-04T16:49:42.000Z | 2022-02-15T10:47:24.000Z | GPUImage-x/proj.iOS/GPUImage-x/GPUImage-x/GLProgram.hpp | antowang/GPUImage-x | 8c9237fd0bde008a69ccab5dc267871c4959f97d | [
"Apache-2.0"
] | 6 | 2017-10-04T13:23:11.000Z | 2018-09-26T06:18:11.000Z | GPUImage-x/proj.iOS/GPUImage-x/GPUImage-x/GLProgram.hpp | antowang/GPUImage-x | 8c9237fd0bde008a69ccab5dc267871c4959f97d | [
"Apache-2.0"
] | 53 | 2017-08-07T14:55:30.000Z | 2022-02-25T09:55:25.000Z | /*
* GPUImage-x
*
* Copyright (C) 2017 Yijin Wang, Yiqian Wang
*
* 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 Shader_hpp
#define Shader_hpp
#include "macros.h"
#include "string"
#if PLATFORM == PLATFORM_ANDROID
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#elif PLATFORM == PLATFORM_IOS
#import <OpenGLES/ES2/gl.h>
#import <OpenGLES/ES2/glext.h>
#endif
#include <vector>
#include "math.hpp"
NS_GI_BEGIN
class GLProgram{
public:
GLProgram();
~GLProgram();
static GLProgram* createByShaderString(const std::string& vertexShaderSource, const std::string& fragmentShaderSource);
void use();
GLuint getID() const { return _program; }
GLuint getAttribLocation(const std::string& attribute);
GLuint getUniformLocation(const std::string& uniformName);
void setUniformValue(const std::string& uniformName, int value);
void setUniformValue(const std::string& uniformName, float value);
void setUniformValue(const std::string& uniformName, Vector2 value);
void setUniformValue(const std::string& uniformName, Matrix3 value);
void setUniformValue(const std::string& uniformName, Matrix4 value);
void setUniformValue(int uniformLocation, int value);
void setUniformValue(int uniformLocation, float value);
void setUniformValue(int uniformLocation, Vector2 value);
void setUniformValue(int uniformLocation, Matrix3 value);
void setUniformValue(int uniformLocation, Matrix4 value);
private:
static std::vector<GLProgram*> _programs;
GLuint _program;
bool _initWithShaderString(const std::string& vertexShaderSource, const std::string& fragmentShaderSource);
};
NS_GI_END
#endif /* GLProgram_hpp */
| 31.671429 | 123 | 0.741543 | antowang |
dcf875f106d6fc1b9e6c23f766fd45c079b7833a | 919 | cpp | C++ | algorithm/tests/PrimaryQueueTests.cpp | AirChen/AlgorithmCpp | a1af7ee437278682d9d0319bab76d85473c3baa0 | [
"MIT"
] | null | null | null | algorithm/tests/PrimaryQueueTests.cpp | AirChen/AlgorithmCpp | a1af7ee437278682d9d0319bab76d85473c3baa0 | [
"MIT"
] | null | null | null | algorithm/tests/PrimaryQueueTests.cpp | AirChen/AlgorithmCpp | a1af7ee437278682d9d0319bab76d85473c3baa0 | [
"MIT"
] | null | null | null | //
// PrimaryQueueTests.cpp
// tests
//
// Created by tuRen on 2021/5/17.
//
#include "PrimaryQueueTests.hpp"
#include "gtest/gtest.h"
#include "PrimaryQueue.hpp"
using std::vector;
class PrimaryQueueTest: public ::testing::Test {
public:
vector<int> _vn = {6, 5, 2, 7, 3, 9, 8, 4, 10, 1 };
};
TEST_F(PrimaryQueueTest, test_max_queue) {
PrimaryQueue<int>* pq = new PrimaryQueue<int>(3);
for (auto v : _vn) {
pq->insert(v);
}
int last = 10010;
do {
ASSERT_TRUE(last >= pq->top());
last = pq->top();
} while (pq->delTop());
delete pq;
}
TEST_F(PrimaryQueueTest, test_min_queue) {
PrimaryQueue<int>* pq = new PrimaryQueue<int>(3, PrimaryQueueType_MIN);
for (auto v : _vn) {
pq->insert(v);
}
int last = -10010;
do {
ASSERT_TRUE(last <= pq->top());
last = pq->top();
} while (pq->delTop());
delete pq;
}
| 19.145833 | 75 | 0.574538 | AirChen |
0d00a7b0316dc482655c9c851accaecb555a66bd | 12,255 | hpp | C++ | DT3Windows8/DeviceGraphicsDX11Material.hpp | 9heart/DT3 | 4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e | [
"MIT"
] | 3 | 2016-01-27T13:17:18.000Z | 2019-03-19T09:18:25.000Z | DT3Windows8/DeviceGraphicsDX11Material.hpp | pakoito/DT3 | 4ba8fd2af3aebb5c0d77036ac3941e83cd4d1c7e | [
"MIT"
] | 1 | 2016-01-28T14:39:49.000Z | 2016-01-28T22:12:07.000Z | DT3Windows8/DeviceGraphicsDX11Material.hpp | adderly/DT3 | e2605be091ec903d3582e182313837cbaf790857 | [
"MIT"
] | 3 | 2016-01-25T16:44:51.000Z | 2021-01-29T19:59:45.000Z | #ifndef DT2_DEVICEGRAPHICSDX11MATERIAL
#define DT2_DEVICEGRAPHICSDX11MATERIAL
//==============================================================================
///
/// File: DeviceGraphicsDX11Material.hpp
///
/// Copyright (C) 2000-2013 by Smells Like Donkey, Inc. All rights reserved.
///
/// This file is subject to the terms and conditions defined in
/// file 'LICENSE.txt', which is part of this source code package.
///
//==============================================================================
#include "pch.h"
#include "BaseClass.hpp"
#include "TextureResource.hpp"
#include "Color.hpp"
#include "Vector.hpp"
#include "Matrix.hpp"
//==============================================================================
/// Namespace
//==============================================================================
namespace DT2 {
//==============================================================================
/// Forward declarations
//==============================================================================
class MaterialResource;
class ShaderResource;
//==============================================================================
/// Class
//==============================================================================
class DeviceGraphicsDX11MaterialTexture {
public:
DEFINE_TYPE_SIMPLE_BASE(DeviceGraphicsDX11MaterialTexture)
DeviceGraphicsDX11MaterialTexture (void);
~DeviceGraphicsDX11MaterialTexture (void);
public:
TextureResource* _texture;
DTuint _wrap_mode_s;
DTuint _wrap_mode_t;
DTuint _wrap_mode_r;
DTuint _filter_mode;
Vector3 _scroll;
DTfloat _rotation;
Vector3 _scale;
Vector3 _pre_translate;
Vector3 _post_translate;
Matrix4 _texture_matrix;
ID3D11SamplerState *_sampler_state;
};
//==============================================================================
/// Class
//==============================================================================
class DeviceGraphicsDX11MaterialState {
public:
DEFINE_TYPE_SIMPLE_BASE(DeviceGraphicsDX11MaterialState)
DeviceGraphicsDX11MaterialState (void);
~DeviceGraphicsDX11MaterialState (void);
public:
DTboolean _blending_enabled;
DTuint _blending_src;
DTuint _blending_dst;
DTuint _blending_alpha_src;
DTuint _blending_alpha_dst;
DTboolean _color_mask_r;
DTboolean _color_mask_g;
DTboolean _color_mask_b;
DTboolean _color_mask_a;
DTboolean _depth_test_enabled;
DTint _depth_func;
DTboolean _depth_mask;
DTboolean _culling_enabled;
DTint _cull_face;
DTboolean _stencil_test_enabled;
DTuint _stencil_mask;
DTint _stencil_func;
DTuint _stencil_bit_mask;
DTint _stencil_front_sfail;
DTint _stencil_front_dpfail;
DTint _stencil_front_dppass;
DTint _stencil_back_sfail;
DTint _stencil_back_dpfail;
DTint _stencil_back_dppass;
Color _color;
ShaderResource *_shader;
ID3D11DepthStencilState *_depth_stencil_state;
ID3D11BlendState *_blend_state;
ID3D11RasterizerState *_rasterizer_state;
DeviceGraphicsDX11MaterialTexture _textures[8];
ID3D11ShaderResourceView *_textures_state[D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT];
ID3D11SamplerState *_samplers_state[D3D11_COMMONSHADER_SAMPLER_SLOT_COUNT];
};
//==============================================================================
/// Class
//==============================================================================
class DeviceGraphicsDX11Material: public BaseClass {
public:
DEFINE_TYPE(DeviceGraphicsDX11Material,BaseClass)
DEFINE_CREATE
DeviceGraphicsDX11Material (void);
private:
DeviceGraphicsDX11Material (const DeviceGraphicsDX11Material &rhs);
DeviceGraphicsDX11Material & operator = (const DeviceGraphicsDX11Material &rhs);
public:
virtual ~DeviceGraphicsDX11Material (void);
public:
/// Description
/// \param param description
/// \return description
void syncToResource (MaterialResource *material);
/// Description
/// \param param description
/// \return description
void activateMaterial (void);
// Blending
DEFINE_ACCESSORS(getBlending, setBlending, DTboolean, _current_state._blending_enabled)
DEFINE_ACCESSORS(getBlendFuncSrc, setBlendFuncSrc, DTint, _current_state._blending_src)
DEFINE_ACCESSORS(getBlendFuncDst, setBlendFuncDst, DTint, _current_state._blending_dst)
DEFINE_ACCESSORS(getAlphaBlendFuncSrc, setAlphaBlendFuncSrc, DTint, _current_state._blending_alpha_src)
DEFINE_ACCESSORS(getAlphaBlendFuncDst, setAlphaBlendFuncDst, DTint, _current_state._blending_alpha_dst)
DEFINE_ACCESSORS(getColorMaskR, setColorMaskR, DTboolean, _current_state._color_mask_r)
DEFINE_ACCESSORS(getColorMaskG, setColorMaskG, DTboolean, _current_state._color_mask_g)
DEFINE_ACCESSORS(getColorMaskB, setColorMaskB, DTboolean, _current_state._color_mask_b)
DEFINE_ACCESSORS(getColorMaskA, setColorMaskA, DTboolean, _current_state._color_mask_a)
// Depth
DEFINE_ACCESSORS(getDepthMask, setDepthMask, DTboolean, _current_state._depth_mask)
DEFINE_ACCESSORS(getDepthTest, setDepthTest, DTboolean, _current_state._depth_test_enabled)
DEFINE_ACCESSORS(getDepthFunc, setDepthFunc, DTint, _current_state._depth_func)
// Culling
DEFINE_ACCESSORS(getCulling, setCulling, DTboolean, _current_state._culling_enabled)
DEFINE_ACCESSORS(getCullFace, setCullFace, DTint, _current_state._cull_face)
// Stenciling
DEFINE_ACCESSORS(getStencilTest, setStencilTest, DTboolean, _current_state._stencil_test_enabled)
DEFINE_ACCESSORS(getStencilMask, setStencilMask, DTuint, _current_state._stencil_mask)
DEFINE_ACCESSORS(getStencilFunc, setStencilFunc, DTint, _current_state._stencil_func)
DEFINE_ACCESSORS(getStencilBitMask, setStencilBitMask, DTuint, _current_state._stencil_bit_mask)
DEFINE_ACCESSORS(getStencilFrontsFail, setStencilFrontsFail, DTint, _current_state._stencil_front_sfail)
DEFINE_ACCESSORS(getStencilFrontdpFail, setStencilFrontdpFail, DTint, _current_state._stencil_front_dpfail)
DEFINE_ACCESSORS(getStencilFrontdpPass, setStencilFrontdpPass, DTint, _current_state._stencil_front_dppass)
DEFINE_ACCESSORS(getStencilBacksFail, setStencilBacksFail, DTint, _current_state._stencil_back_sfail)
DEFINE_ACCESSORS(getStencilBackdpFail, setStencilBackdpFail, DTint, _current_state._stencil_back_dpfail)
DEFINE_ACCESSORS(getStencilBackdpPass, setStencilBackdpPass, DTint, _current_state._stencil_back_dppass)
// Color
DEFINE_ACCESSORS(getColor, setColor, Color, _current_state._color)
/// Description
/// \param param description
/// \return description
void setShader (ShaderResource *p);
/// Description
/// \param param description
/// \return description
ShaderResource*& getShader (void) { return _current_state._shader; }
/// Description
/// \param param description
/// \return description
void setTex (TextureResource *tex);
/// Description
/// \param param description
/// \return description
TextureResource* getTex (void) const;
/// Description
/// \param param description
/// \return description
void setScroll (const Vector3 &scroll) { _current_state._textures[_unit]._scroll = scroll; }
/// Description
/// \param param description
/// \return description
Vector3 getScroll (void) const { return _current_state._textures[_unit]._scroll; }
/// Description
/// \param param description
/// \return description
void setPreTranslate (const Vector3 &translate) { _current_state._textures[_unit]._pre_translate = translate; }
/// Description
/// \param param description
/// \return description
Vector3 getPreTranslate (void) const { return _current_state._textures[_unit]._pre_translate; }
/// Description
/// \param param description
/// \return description
void setPostTranslate (const Vector3 &translate) { _current_state._textures[_unit]._post_translate = translate; }
/// Description
/// \param param description
/// \return description
Vector3 getPostTranslate (void) const { return _current_state._textures[_unit]._post_translate; }
/// Description
/// \param param description
/// \return description
void setRotation (const DTfloat rotation) { _current_state._textures[_unit]._rotation = rotation; }
/// Description
/// \param param description
/// \return description
DTfloat getRotation (void) const { return _current_state._textures[_unit]._rotation; }
/// Description
/// \param param description
/// \return description
void setScale (const Vector3 &scale) { _current_state._textures[_unit]._scale = scale; }
/// Description
/// \param param description
/// \return description
Vector3 getScale (void) const { return _current_state._textures[_unit]._scale; }
/// Description
/// \param param description
/// \return description
const Matrix4& getTextureMatrix (void) const { return _current_state._textures[_unit]._texture_matrix; }
/// Description
/// \param param description
/// \return description
void setWrapS (DTuint wrap_mode_s) { _current_state._textures[_unit]._wrap_mode_s = wrap_mode_s; }
/// Description
/// \param param description
/// \return description
DTuint getWrapS (void) const { return _current_state._textures[_unit]._wrap_mode_s; }
/// Description
/// \param param description
/// \return description
void setWrapT (DTuint wrap_mode_t) { _current_state._textures[_unit]._wrap_mode_t = wrap_mode_t; }
/// Description
/// \param param description
/// \return description
DTuint getWrapT (void) const { return _current_state._textures[_unit]._wrap_mode_t; }
/// Description
/// \param param description
/// \return description
void setWrapR (DTuint wrap_mode_r) { _current_state._textures[_unit]._wrap_mode_r = wrap_mode_r; }
/// Description
/// \param param description
/// \return description
DTuint getWrapR (void) const { return _current_state._textures[_unit]._wrap_mode_r; }
/// Description
/// \param param description
/// \return description
void setFilter (DTuint filter_mode) { _current_state._textures[_unit]._filter_mode = filter_mode; }
/// Description
/// \param param description
/// \return description
DTuint getFilter (void) const { return _current_state._textures[_unit]._filter_mode; }
/// Description
/// \param param description
/// \return description
void setMode (DTint mode) {}
/// Description
/// \param param description
/// \return description
DTint getMode (void) const { return 0; }
/// Description
/// \param param description
/// \return description
void setCurrentUnit (const DTuint unit) { _unit = unit; }
private:
DTuint _unit;
DeviceGraphicsDX11MaterialState _current_state;
void syncTexture (DTuint unit);
};
//==============================================================================
//==============================================================================
} // DT2
#endif
| 35.938416 | 125 | 0.616157 | 9heart |
0d030c0917640d62afef953096945e7e1dedf137 | 1,432 | cpp | C++ | Codechef_Long_Chalenge_2021/shortestPath.cpp | AkashKumarSingh11032001/Coding-Challenge-Solutions | c46b5d466b1403b8e58b6ac9081298d617ad8611 | [
"MIT"
] | null | null | null | Codechef_Long_Chalenge_2021/shortestPath.cpp | AkashKumarSingh11032001/Coding-Challenge-Solutions | c46b5d466b1403b8e58b6ac9081298d617ad8611 | [
"MIT"
] | null | null | null | Codechef_Long_Chalenge_2021/shortestPath.cpp | AkashKumarSingh11032001/Coding-Challenge-Solutions | c46b5d466b1403b8e58b6ac9081298d617ad8611 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define maxn 3E5 + 5
void solve()
{
int n, m;
cin >> n >> m;
int a[n];
int b[m];
int i, j;
for (i = 0; i < n; i++)
{
cin >> a[i];
}
for (i = 0; i < m; i++)
{
cin >> b[i];
}
int max_i = maxn;
int rough[n];
int low = -1, high = -1;
for (i = 0; i < n; i++)
{
if (i == 0)
{
rough[i] = 0;
}
else if (a[i] != 0)
{
rough[i] = 0;
}
else
{
rough[i] = max_i;
}
}
for (i = 0; i < n; i++)
{
if (a[i] == 1)
{
high = i;
}
if (high != -1)
{
if (a[i] == 0)
{
rough[i] = min(rough[i], i - high);
}
}
}
for (i = n - 1; i >= 0; i--)
{
if (a[i] == 2)
{
low = i;
}
if (low != -1)
{
if (a[i] == 0)
{
rough[i] = min(rough[i], low - i);
}
}
}
for (i = 0; i < m; i++)
{
j = b[i] - 1;
if (rough[j] != max_i)
{
cout << rough[j] << " ";
}
else
{
cout << -1 << " ";
}
}
cout << endl;
}
int main()
{
int test;
cin >> test;
while (test--)
{
solve();
}
} | 16.45977 | 51 | 0.261872 | AkashKumarSingh11032001 |
0d040c97e20584697571dd9a08d3888e732af4b9 | 444 | cpp | C++ | CompetitiveProgramming/Exercise2.2.1/5-LongestContiguousSubArray.cpp | omarcespedes/algorithms-cpp | 5c66e41d0f4080ccd2c384ff9658ceb721545b19 | [
"MIT"
] | null | null | null | CompetitiveProgramming/Exercise2.2.1/5-LongestContiguousSubArray.cpp | omarcespedes/algorithms-cpp | 5c66e41d0f4080ccd2c384ff9658ceb721545b19 | [
"MIT"
] | null | null | null | CompetitiveProgramming/Exercise2.2.1/5-LongestContiguousSubArray.cpp | omarcespedes/algorithms-cpp | 5c66e41d0f4080ccd2c384ff9658ceb721545b19 | [
"MIT"
] | null | null | null | //increasing
#include <iostream>
using namespace std;
#define N 12
int arr[N] = {12, 13, 14, 15, 4, 7, 8, 1, 10, 11,25,26};
int main(){
int max = 1, len = 1;
for(int i = 1 ; i < N ; i++) {
if(arr[i] > arr[i-1]) {
len++;
} else {
if(len > max) {
max = len;
}
len = 1;
}
}
if(len > max) max = len;
cout << max << endl;
return 0;
} | 17.76 | 56 | 0.394144 | omarcespedes |
0d0438ec54dbbc75f365e7d3a351ed9b2661df27 | 4,453 | cpp | C++ | test/integration_tests/src/config.cpp | Paycasso/cpp-driver | 9e6efd4842afc226d999baf890a55275e7e94cf8 | [
"Apache-2.0"
] | null | null | null | test/integration_tests/src/config.cpp | Paycasso/cpp-driver | 9e6efd4842afc226d999baf890a55275e7e94cf8 | [
"Apache-2.0"
] | null | null | null | test/integration_tests/src/config.cpp | Paycasso/cpp-driver | 9e6efd4842afc226d999baf890a55275e7e94cf8 | [
"Apache-2.0"
] | null | null | null | #define BOOST_TEST_DYN_LINK
#ifdef STAND_ALONE
# define BOOST_TEST_MODULE cassandra
#endif
#include <boost/test/unit_test.hpp>
#include "cassandra.h"
#include "test_utils.hpp"
struct ConfigTests {
ConfigTests() { }
};
BOOST_FIXTURE_TEST_SUITE(config, ConfigTests)
BOOST_AUTO_TEST_CASE(test_options)
{
test_utils::CassClusterPtr cluster(cass_cluster_new());
{
cass_size_t data_length;
cass_size_t connect_timeout = 9999;
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONNECT_TIMEOUT, &connect_timeout, sizeof(connect_timeout));
cass_size_t connect_timeout_out = 0;
data_length = sizeof(connect_timeout_out);
cass_cluster_getopt(cluster.get(), CASS_OPTION_CONNECT_TIMEOUT, &connect_timeout_out, &data_length);
BOOST_REQUIRE(connect_timeout == connect_timeout_out && data_length == sizeof(connect_timeout_out));
}
{
cass_size_t data_length;
cass_int32_t port = 7000;
cass_cluster_setopt(cluster.get(), CASS_OPTION_PORT, &port, sizeof(port));
cass_int32_t port_out = 0;
data_length = sizeof(port_out);
cass_cluster_getopt(cluster.get(), CASS_OPTION_PORT, &port_out, &data_length);
BOOST_REQUIRE(port == port_out && data_length == sizeof(port_out));
}
}
BOOST_AUTO_TEST_CASE(test_invalid)
{
test_utils::CassClusterPtr cluster(cass_cluster_new());
cass_size_t temp = 0;
BOOST_REQUIRE(cass_cluster_setopt(cluster.get(), CASS_OPTION_CONNECT_TIMEOUT, &temp, sizeof(temp) - 1) == CASS_ERROR_LIB_INVALID_OPTION_SIZE);
cass_size_t temp_out = 0;
cass_size_t temp_out_size = sizeof(temp_out) - 1;
BOOST_REQUIRE(cass_cluster_getopt(cluster.get(), CASS_OPTION_CONNECT_TIMEOUT, &temp_out, &temp_out_size) == CASS_ERROR_LIB_INVALID_OPTION_SIZE);
}
BOOST_AUTO_TEST_CASE(test_contact_points)
{
char buffer[1024];
cass_size_t buffer_size;
test_utils::CassClusterPtr cluster(cass_cluster_new());
// Simple
const char* contact_points1 = "127.0.0.1,127.0.0.2,127.0.0.3";
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, contact_points1, strlen(contact_points1));
buffer_size = sizeof(buffer);
cass_cluster_getopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, buffer, &buffer_size);
BOOST_REQUIRE(strcmp(contact_points1, buffer) == 0);
// Clear
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, "", 0);
buffer_size = sizeof(buffer);
cass_cluster_getopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, buffer, &buffer_size);
BOOST_REQUIRE(buffer_size == 0);
// Extra commas
const char* contact_points1_commas = ",,,,127.0.0.1,,,,127.0.0.2,127.0.0.3,,,,";
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, contact_points1_commas, strlen(contact_points1_commas));
buffer_size = sizeof(buffer);
cass_cluster_getopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, buffer, &buffer_size);
BOOST_REQUIRE(strcmp(contact_points1, buffer) == 0);
// Clear
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, "", 0);
buffer_size = sizeof(buffer);
cass_cluster_getopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, buffer, &buffer_size);
BOOST_REQUIRE(buffer_size == 0);
// Extra whitespace
const char* contact_points1_ws = " ,\r\n, , , 127.0.0.1 ,,, ,\t127.0.0.2,127.0.0.3, \t\n, ,, ";
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, contact_points1_ws, strlen(contact_points1_ws));
buffer_size = sizeof(buffer);
cass_cluster_getopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, buffer, &buffer_size);
BOOST_REQUIRE(strcmp(contact_points1, buffer) == 0);
// Clear
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, "", 0);
buffer_size = sizeof(buffer);
cass_cluster_getopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, buffer, &buffer_size);
BOOST_REQUIRE(buffer_size == 0);
// Append
const char* contact_point1 = "127.0.0.1";
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, contact_point1, strlen(contact_point1));
const char* contact_point2 = "127.0.0.2";
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, contact_point2, strlen(contact_point2));
const char* contact_point3 = "127.0.0.3";
cass_cluster_setopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, contact_point3, strlen(contact_point3));
buffer_size = sizeof(buffer);
cass_cluster_getopt(cluster.get(), CASS_OPTION_CONTACT_POINTS, buffer, &buffer_size);
BOOST_REQUIRE(strcmp(contact_points1, buffer) == 0);
}
BOOST_AUTO_TEST_SUITE_END()
| 37.108333 | 146 | 0.760835 | Paycasso |
0d0446ac2835a18565812064ad6568f2fc69d033 | 6,268 | cpp | C++ | src/Auxiliary/Aux_Check_Conservation.cpp | zhulianhua/Daino | db88f5738aba76fa8a28d7672450e0c5c832b3de | [
"MIT"
] | 3 | 2019-04-13T02:08:01.000Z | 2020-11-17T12:45:37.000Z | src/Auxiliary/Aux_Check_Conservation.cpp | zhulianhua/Daino | db88f5738aba76fa8a28d7672450e0c5c832b3de | [
"MIT"
] | null | null | null | src/Auxiliary/Aux_Check_Conservation.cpp | zhulianhua/Daino | db88f5738aba76fa8a28d7672450e0c5c832b3de | [
"MIT"
] | 2 | 2019-11-12T02:00:20.000Z | 2019-12-09T14:52:31.000Z |
#include "DAINO.h"
#if ( MODEL == MHD )
#warning : WAIT MHD !!!
#endif
//-------------------------------------------------------------------------------------------------------
// Function : Aux_Check_Conservation
// Description : Verify the conservation laws
// --> HYDRO : check mass, momenum, and energy
// MHD : check mass, momenum, and energy
// ELBDM : check mass only
//
// Note : 1. This check only works with the models HYDRO, MHD, and ELBDM
// 2. The values measured during the first time this function is invoked will be taken as the
// reference values to estimate errors
// 3. The following gnuplot command can be used to plot "error vs. time", assuming
// "TVar = [0 ... NVar-1]"
//
// plot 'Record__Conservation' u 1:7 every NCOMP+1::(2+TVar) w lp ps 4
//
// Parameter : Output2File : true --> Output results to file instead of showing on the screen
// comment : You can put the location where this function is invoked in this string
//-------------------------------------------------------------------------------------------------------
void Aux_Check_Conservation( const bool Output2File, const char *comment )
{
static bool FirstTime = true;
const char *FileName = "Record__Conservation";
// check
# if ( MODEL != HYDRO && MODEL != MHD && MODEL != ELBDM )
Aux_Message( stderr, "Warning : function \"%s\" is supported only in the models HYDRO, MHD, and ELBDM !!\n",
__FUNCTION__ );
OPT__CK_CONSERVATION = false;
return;
# endif
if ( FirstTime && MPI_Rank == 0 && Output2File )
{
FILE *File_Check = fopen( FileName, "r" );
if ( File_Check != NULL )
{
Aux_Message( stderr, "WARNING : the file \"%s\" already exists !!\n", FileName );
fclose( File_Check );
}
}
# if ( MODEL == HYDRO )
const int NVar = NCOMP;
# elif ( MODEL == MHD )
# warning : WAIT MHD !!!
# elif ( MODEL == ELBDM )
const int NVar = 1;
# else
# error : ERROR : unsupported MODEL !!
# endif
double dV, Total_local[NVar], Total_sum[NVar], Total_lv[NVar]; // dV : cell volume at each level
int Sg;
FILE *File = NULL;
// output message if Output2File is off
if ( MPI_Rank == 0 && !Output2File )
{
if ( FirstTime )
Aux_Message( stdout, "\"%s\" : <%s> referencing at Time = %13.7e, Step = %7ld\n",
comment, __FUNCTION__, Time[0], Step );
else
Aux_Message( stdout, "\"%s\" : <%s> checking at Time = %13.7e, Step = %7ld\n",
comment, __FUNCTION__, Time[0], Step );
}
// measure the total amount of the targeted variables
for (int v=0; v<NVar; v++)
{
Total_local[v] = 0.0;
Total_sum [v] = 0.0;
}
for (int lv=0; lv<NLEVEL; lv++)
{
for (int v=0; v<NVar; v++) Total_lv[v] = 0.0;
dV = patch->dh[lv] * patch->dh[lv] * patch->dh[lv];
Sg = patch->FluSg[lv];
for (int PID=0; PID<patch->NPatchComma[lv][1]; PID++)
{
if ( patch->ptr[0][lv][PID]->son == -1 )
{
# if ( MODEL == HYDRO )
for (int v=0; v<NVar; v++)
for (int k=0; k<PATCH_SIZE; k++)
for (int j=0; j<PATCH_SIZE; j++)
for (int i=0; i<PATCH_SIZE; i++)
Total_lv[v] += (double)patch->ptr[Sg][lv][PID]->fluid[v][k][j][i];
# elif ( MODEL == MHD )
# warning : WAIT MHD !!!
# elif ( MODEL == ELBDM )
for (int k=0; k<PATCH_SIZE; k++)
for (int j=0; j<PATCH_SIZE; j++)
for (int i=0; i<PATCH_SIZE; i++)
Total_lv[0] += (double)patch->ptr[Sg][lv][PID]->fluid[DENS][k][j][i];
# endif // MODEL
}
} // for (int PID=0; PID<patch->NPatchComma[lv][1]; PID++)
// sum over NLEVEL levels
for (int v=0; v<NVar; v++)
{
Total_lv [v] *= dV;
Total_local[v] += Total_lv[v];
}
} // for (int lv=0; lv<NLEVEL; lv++)
// sum over all ranks
MPI_Reduce( Total_local, Total_sum, NVar, MPI_DOUBLE, MPI_SUM, 0, MPI_COMM_WORLD );
// output
if ( MPI_Rank == 0 )
{
static double RefTotal[NVar];
double AbsErr[NVar], RelErr[NVar];
// record the reference values
if ( FirstTime )
{
for (int v=0; v<NVar; v++) RefTotal[v] = Total_sum[v];
if ( Output2File )
{
File = fopen( FileName, "a" );
Aux_Message( File, "%16s%10s%13s%18s%18s%18s%18s\n",
"Time", "Step", "Attribute", "Evaluate", "Reference", "Absolute Error", "Error" );
Aux_Message( File, "-----------------------------------------------------------------------------" );
Aux_Message( File, "----------------------------------\n" );
fclose( File );
}
}
// calculate errors
else
{
for (int v=0; v<NVar; v++)
{
AbsErr[v] = Total_sum[v] - RefTotal[v];
RelErr[v] = AbsErr[v] / RefTotal[v];
}
if ( Output2File )
{
File = fopen( FileName, "a" );
for (int v=0; v<NVar; v++)
Aux_Message( File, "%16.7e%10ld%13d%18.7e%18.7e%18.7e%18.7e\n",
Time[0], Step, v, Total_sum[v], RefTotal[v], AbsErr[v], RelErr[v] );
Aux_Message( File, "-----------------------------------------------------------------------------" );
Aux_Message( File, "----------------------------------\n" );
fclose( File );
}
else
{
Aux_Message( stdout, "%13s%20s%20s%20s%20s\n",
"Attribute", "Evaluate", "Reference", "Absolute Error", "Error" );
for (int v=0; v<NVar; v++)
Aux_Message( stdout, "%13d%20.7e%20.7e%20.7e%20.7e\n",
v, Total_sum[v], RefTotal[v], AbsErr[v], RelErr[v] );
}
} // if ( FirstTime ) ... else ...
} // if ( MPI_Rank == 0 )
if ( FirstTime ) FirstTime = false;
} // FUNCTION : Aux_Check_Conservation
| 31.979592 | 113 | 0.469368 | zhulianhua |
0d0d6309cc3d18e9b97b348f1e2afd22e039ddea | 1,897 | cpp | C++ | crazyrc/rc_parser.cpp | mojmir-svoboda/BlackBoxTT | 0c87b989827107695538e1bf1266c08b083dda44 | [
"MIT"
] | 11 | 2017-06-19T14:21:15.000Z | 2020-03-04T06:43:16.000Z | crazyrc/rc_parser.cpp | mojmir-svoboda/BlackBoxTT | 0c87b989827107695538e1bf1266c08b083dda44 | [
"MIT"
] | null | null | null | crazyrc/rc_parser.cpp | mojmir-svoboda/BlackBoxTT | 0c87b989827107695538e1bf1266c08b083dda44 | [
"MIT"
] | 3 | 2017-07-23T18:08:55.000Z | 2019-09-16T16:28:18.000Z | #include <boost/spirit/include/qi.hpp>
#include <boost/foreach.hpp>
#include <boost/assert.hpp>
#include <boost/variant/variant.hpp>
#include <iostream>
#include <string>
#include <cstdlib>
#include <map>
#include "rc_grammar.h"
#include "rc_dump.h"
#include "unicode.h"
#include "utils_file.h"
#include "rc_cache.h"
using namespace boost::spirit::standard_wide;
#include <fstream>
#include <string>
#include <cerrno>
#include <tchar.h>
#include <string>
#include <vector>
#include <windef.h>
#include "rgb_txt_parser.h"
namespace rc {
namespace qi = boost::spirit::qi;
ColorSymbols::ColorSymbols()
{
for (auto const & item : rgb_txt::getColorTable())
this->add(item.second, item.first);
}
bool parseFile (tstring const & fname, tstring & err)
{
tstring content;
if (readFileContent(fname, content))
{
static rc::Grammar<tstring::iterator> const g;
tstring::iterator begin = content.begin();
tstring::iterator end = content.end();
ParsedFileRecord rec;
try
{
bool const r = qi::phrase_parse(begin, end, g, qi::blank, rec.m_parsedFile);
if (r && begin == end)
{
getParsedFileCache().Add(fname, rec);
getParsedFileCache().MakeIndex();
//std::cout << m;
return true;
}
else
{
tstringstream ss;
ss << "+---- parser stopped here\n";
ss << "V\n";
if (std::distance(begin, end) > 128)
{
tstring rest(begin, begin + 128);
ss << rest << "\n";
}
else
{
tstring rest(begin, end);
ss << rest << "\n";
}
err = ss.str();
return false;
}
}
catch (...)
{
tstringstream ss;
ss << "Exception caught while parsing!" << std::endl;
err = ss.str();
return false;
}
return true;
}
return false;
}
bool parseFile (tstring const & fname)
{
tstring err;
bool const parsed = parseFile(fname, err);
if (!parsed)
{
//LogError(fname, err);
}
return parsed;
}
}
| 18.066667 | 79 | 0.633632 | mojmir-svoboda |
0d0df500dc9c7cc3755a92e5f113f6e931144607 | 2,552 | cpp | C++ | LibraryDX12/Resource/D2DWrappedResource.cpp | DziubanMaciej/DirectX-Deconfused | a8a4177beeb40436f6e0734e6d28d60aa1867d40 | [
"MIT"
] | null | null | null | LibraryDX12/Resource/D2DWrappedResource.cpp | DziubanMaciej/DirectX-Deconfused | a8a4177beeb40436f6e0734e6d28d60aa1867d40 | [
"MIT"
] | null | null | null | LibraryDX12/Resource/D2DWrappedResource.cpp | DziubanMaciej/DirectX-Deconfused | a8a4177beeb40436f6e0734e6d28d60aa1867d40 | [
"MIT"
] | null | null | null | #include "D2DWrappedResource.h"
#include "Application/ApplicationImpl.h"
#include "Resource/Resource.h"
#include "Utility/ThrowIfFailed.h"
#include <cassert>
void D2DWrappedResource::wrap(float dpi) {
auto &d2dContext = ApplicationImpl::getInstance().getD2DContext();
// Create DX11 Resource
const D3D11_RESOURCE_FLAGS d3d11Flags = {D3D11_BIND_RENDER_TARGET};
throwIfFailed(d2dContext.getD3D11On12Device()->CreateWrappedResource(
d12Resource.getResource().Get(), &d3d11Flags,
inState, outState,
IID_PPV_ARGS(&d3d11Resource)));
// Convert to DXGI surface
IDXGISurfacePtr surface = {};
throwIfFailed(d3d11Resource.As(&surface));
// Create D2D Resource
const auto bitmapProperties = D2D1::BitmapProperties1(
D2D1_BITMAP_OPTIONS_TARGET | D2D1_BITMAP_OPTIONS_CANNOT_DRAW,
D2D1::PixelFormat(DXGI_FORMAT_UNKNOWN, D2D1_ALPHA_MODE_PREMULTIPLIED),
dpi, dpi);
throwIfFailed(d2dContext.getD2DDeviceContext()->CreateBitmapFromDxgiSurface(
surface.Get(),
&bitmapProperties,
&d2dResource));
}
void D2DWrappedResource::reset() {
d3d11Resource.Reset();
d2dResource.Reset();
}
AcquiredD2DWrappedResource D2DWrappedResource::acquire() {
assert(!this->acquired);
return AcquiredD2DWrappedResource{*this};
}
inline AcquiredD2DWrappedResource::AcquiredD2DWrappedResource(D2DWrappedResource &parent) : parent(&parent) {
assert(!parent.acquired);
auto &device = ApplicationImpl::getInstance().getD2DContext().getD3D11On12Device();
device->AcquireWrappedResources(parent.d3d11Resource.GetAddressOf(), 1);
parent.acquired = true;
}
AcquiredD2DWrappedResource::AcquiredD2DWrappedResource(AcquiredD2DWrappedResource &&other) : parent(other.parent) {
other.parent = nullptr;
}
AcquiredD2DWrappedResource::~AcquiredD2DWrappedResource() {
if (parent == nullptr) {
return;
}
assert(parent->acquired);
// Release
parent->acquired = false;
auto &device = ApplicationImpl::getInstance().getD2DContext().getD3D11On12Device();
device->ReleaseWrappedResources(parent->d3d11Resource.GetAddressOf(), 1); // This call makes implicit state transition
// Manage state
assert(parent->d12Resource.getState().areAllSubresourcesInState(parent->inState));
parent->d12Resource.setState(Resource::ResourceState{parent->outState});
// Flush to submit the D2D command list to the shared command queue.
ApplicationImpl::getInstance().getD2DContext().getD3D11DeviceContext()->Flush();
}
| 34.486486 | 122 | 0.738245 | DziubanMaciej |
0d11f1dccbf81b4bfe3341997c844aed40fcb94a | 22,910 | hpp | C++ | 3rdparty/sospd/include/litiv/3rdparty/sospd/sospd.hpp | jpjodoin/litiv | 435556bea20d60816aff492f50587b1a2d748b21 | [
"BSD-3-Clause"
] | 97 | 2015-10-16T04:32:33.000Z | 2022-03-29T07:04:02.000Z | 3rdparty/sospd/include/litiv/3rdparty/sospd/sospd.hpp | jpjodoin/litiv | 435556bea20d60816aff492f50587b1a2d748b21 | [
"BSD-3-Clause"
] | 19 | 2016-07-01T16:37:02.000Z | 2020-09-10T06:09:39.000Z | 3rdparty/sospd/include/litiv/3rdparty/sospd/sospd.hpp | jpjodoin/litiv | 435556bea20d60816aff492f50587b1a2d748b21 | [
"BSD-3-Clause"
] | 41 | 2015-11-17T05:59:23.000Z | 2022-02-16T09:30:28.000Z | #pragma once
#include "litiv/3rdparty/sospd/multilabel-energy.hpp"
#include "litiv/3rdparty/sospd/submodular-ibfs.hpp"
namespace sospd {
/** Optimizer using Sum-of-submodular Primal Dual algorithm.
*
* Implements SoSPD algorithm from Fix, Wang, Zabih in CVPR 14.
*/
template<typename ValueType, typename IndexType, typename LabelType, typename Flow = SubmodularIBFS<ValueType,IndexType>>
class SoSPD {
public:
typedef MultilabelEnergy<ValueType,IndexType,LabelType> MLE;
typedef typename MLE::REAL REAL;
typedef typename MLE::VarId VarId;
typedef typename MLE::Label Label;
typedef sospd::Assgn Assgn;
/** Proposal callbacks take as input the iteration number and current
* labeling (as a vector of labels) and write the next proposal to the
* final parameter.
*/
typedef std::function<void(IndexType niter,const std::vector<Label>& current,std::vector<Label>& proposed)> ProposalCallback;
/** Set up SoSPD to optimize a particular energy function
*
* \param energy Energy function to optimize.
*/
explicit SoSPD(const MLE* energy);
explicit SoSPD(const MLE* energy, SubmodularIBFSParams& params);
/** Run SoSPD algorithm either to completion, or for a number of steps.
*
* Each iteration has a single proposal (determined by
* SetProposalCallback), and solves a corresponding Sum-of-Submodular
* flow problem.
*
* Resulting labeling can be queried from GetLabel.
*
* \param niters Number of iterations
*/
void Solve(IndexType niters = std::numeric_limits<IndexType>::max());
/** Return label of a node i, returns -1 if Solve has not been called.*/
LabelType GetLabel(VarId i) const;
/** Give hint that energy is expansion submodular. Enables optimizations
* because we don't need to find submodular upper/lower bounds for the
* function.
*/
void SetExpansionSubmodular(bool b) { m_expansion_submodular = b; }
/** Choose whether to use lower/upper bound in approximating function.
*/
void SetLowerBound(bool b) { m_lower_bound = b; }
/** Specify method for choosing proposals. */
void SetProposalCallback(const ProposalCallback& pc) { m_pc = pc; }
/** Set the proposal method to alpha-expansion
*
* Alpha-expansion proposals simply cycle through the labels, proposing
* a constant labeling (i.e., all "alpha") at each iteration.
*/
void SetAlphaExpansion() {
m_pc = [&](IndexType,const std::vector<Label>&,std::vector<Label>&) {
AlphaProposal();
};
}
/** Set the proposal method to best-height alpha-expansion
*
* Best-height alpha-expansion, instead of cycling through labels,
* chooses the single alpha with the biggest sum of differences in
* heights.
*/
void SetHeightAlphaExpansion() {
m_pc = [&](IndexType,const std::vector<Label>&,std::vector<Label>&) {
HeightAlphaProposal();
};
}
/** Return lower bound on optimum, determined by current dual */
double LowerBound();
REAL dualVariable(IndexType alpha, VarId i, Label l) const;
Flow* GetFlow() { return &m_ibfs; }
private:
typedef typename MLE::CliquePtr CliquePtr;
typedef std::vector<REAL> LambdaAlpha;
typedef std::vector<std::pair<IndexType,IndexType>> NodeNeighborList;
typedef std::vector<NodeNeighborList> NodeCliqueList;
REAL ComputeHeight(VarId, Label);
REAL ComputeHeightDiff(VarId i, Label l1, Label l2) const;
void SetupGraph(Flow& crf);
// TODO(afix): redo this
void SetupAlphaEnergy(Flow& crf);
void InitialLabeling();
void InitialDual();
void InitialNodeCliqueList();
bool InitialFusionLabeling();
void PreEditDual(Flow& crf);
bool UpdatePrimalDual(Flow& crf);
void PostEditDual();
void DualFit();
REAL& Height(VarId i, Label l) { return m_heights[i*m_num_labels+l]; }
REAL& dualVariable(IndexType alpha, VarId i, Label l);
REAL dualVariable(const LambdaAlpha& lambdaAlpha,
VarId i, Label l) const;
REAL& dualVariable(LambdaAlpha& lambdaAlpha,
VarId i, Label l);
LambdaAlpha& lambdaAlpha(IndexType alpha);
const LambdaAlpha& lambdaAlpha(IndexType alpha) const;
// Move Proposals
void HeightAlphaProposal();
void AlphaProposal();
const MLE* m_energy;
// Unique ptr so we can forward declare?
Flow m_ibfs;
const IndexType m_num_labels;
std::vector<Label> m_labels;
/// The proposed labeling in a given iteration
std::vector<Label> m_fusion_labels;
// Factor this list back into a node list?
NodeCliqueList m_node_clique_list;
// FIXME(afix) change way m_dual is stored. Put lambda_alpha as separate
// REAL* for each clique, indexed by i, l.
std::vector<LambdaAlpha> m_dual;
std::vector<REAL> m_heights;
bool m_expansion_submodular;
bool m_lower_bound;
IndexType m_iter;
ProposalCallback m_pc;
};
} // namespace sospd
template<typename V, typename I, typename L, typename F>
inline sospd::SoSPD<V,I,L,F>::SoSPD(const MLE* energy)
: m_energy(energy),
m_num_labels(energy->numLabels()),
m_labels(energy->numVars(), 0),
m_fusion_labels(energy->numVars(), 0),
m_expansion_submodular(false),
m_lower_bound(false),
m_iter(0),
m_pc([&](I,const std::vector<Label>&,std::vector<Label>&) {HeightAlphaProposal();})
{ }
template<typename V, typename I, typename L, typename F>
inline sospd::SoSPD<V,I,L,F>::SoSPD(const MLE* energy, SubmodularIBFSParams& params)
: m_energy(energy),
m_ibfs(params),
m_num_labels(energy->numLabels()),
m_labels(energy->numVars(), 0),
m_fusion_labels(energy->numVars(), 0),
m_expansion_submodular(false),
m_lower_bound(false),
m_iter(0),
m_pc([&](I,const std::vector<Label>&,std::vector<Label>&) {HeightAlphaProposal();})
{ }
template<typename V, typename I, typename L, typename F>
inline L sospd::SoSPD<V,I,L,F>::GetLabel(VarId i) const {
return L(m_labels[i]);
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::InitialLabeling() {
const VarId n = m_energy->numVars();
for (VarId i = 0; i < n; ++i) {
REAL best_cost = std::numeric_limits<REAL>::max();
for (I l = 0; l < m_num_labels; ++l) {
if (m_energy->unary(i, l) < best_cost) {
best_cost = m_energy->unary(i, l);
m_labels[i] = l;
}
}
}
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::InitialDual() {
// Initialize heights
m_heights = std::vector<REAL>(m_energy->numVars()*m_num_labels, 0);
for (VarId i = 0; i < m_energy->numVars(); ++i)
for (Label l = 0; l < m_num_labels; ++l)
Height(i, l) = m_energy->unary(i, l);
m_dual.clear();
Label labelBuf[32];
for (const CliquePtr& cp : m_energy->cliques()) {
const Clique<V,I,L>& c = *cp;
const VarId* nodes = c.nodes();
I k = I(c.size());
ASSERT(k < I(32));
for (I i = 0; i < k; ++i) {
labelBuf[i] = m_labels[nodes[i]];
}
REAL energy = c.energy(labelBuf);
m_dual.emplace_back(k*m_num_labels, 0);
LambdaAlpha& lambda_a = m_dual.back();
ASSERT(energy >= 0);
REAL avg = energy / k;
int remainder = int(energy) % k;
for (I i = 0; i < k; ++i) {
Label l = m_labels[nodes[i]];
REAL& lambda_ail = dualVariable(lambda_a, i, l);
lambda_ail = avg;
if(int(i) < remainder) // Have to distribute remainder to maintain average
lambda_ail += 1;
Height(nodes[i], l) += lambda_ail;
}
}
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::InitialNodeCliqueList() {
I n = I(m_labels.size());
m_node_clique_list.clear();
m_node_clique_list.resize(n);
I clique_index = 0;
for (const CliquePtr& cp : m_energy->cliques()) {
const Clique<V,I,L>& c = *cp;
const VarId* nodes = c.nodes();
const I k = I(c.size());
for (I i = 0; i < k; ++i) {
m_node_clique_list[nodes[i]].push_back(std::make_pair(clique_index, i));
}
++clique_index;
}
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::PreEditDual(F& crf) {
auto& fixedVars = crf.Params().fixedVars;
fixedVars.resize(m_labels.size());
for (I i = 0; i < I(m_labels.size()); ++i)
fixedVars[i] = (m_labels[i] == m_fusion_labels[i]);
// Allocate all the buffers we need in one place, resize as necessary
Label label_buf[32];
std::vector<Label> current_labels;
std::vector<Label> fusion_labels;
std::vector<REAL> psi;
std::vector<REAL> current_lambda;
std::vector<REAL> fusion_lambda;
auto& ibfs_cliques = crf.Graph().GetCliques();
ASSERT(ibfs_cliques.size() == m_energy->cliques().size());
I clique_index = 0;
for (const CliquePtr& cp : m_energy->cliques()) {
const Clique<V,I,L>& c = *cp;
const I k = I(c.size());
ASSERT(k < I(32));
auto& lambda_a = lambdaAlpha(clique_index);
auto& ibfs_c = ibfs_cliques[clique_index];
ASSERT(k == ibfs_c.Size());
std::vector<REAL>& energy_table = ibfs_c.EnergyTable();
sospd::Assgn max_assgn = 1u << k;
ASSERT(energy_table.size() == max_assgn);
psi.resize(k);
current_labels.resize(k);
fusion_labels.resize(k);
current_lambda.resize(k);
fusion_lambda.resize(k);
for (I i = 0; i < k; ++i) {
current_labels[i] = m_labels[c.nodes()[i]];
fusion_labels[i] = m_fusion_labels[c.nodes()[i]];
/*
*ASSERT(0 <= c.nodes()[i] && c.nodes()[i] < m_labels.size());
*ASSERT(0 <= current_labels[i] && current_labels[i] < m_num_labels);
*ASSERT(0 <= fusion_labels[i] && fusion_labels[i] < m_num_labels);
*/
current_lambda[i] = dualVariable(lambda_a, i, current_labels[i]);
fusion_lambda[i] = dualVariable(lambda_a, i, fusion_labels[i]);
}
// Compute costs of all fusion assignments
{
Assgn last_gray = 0;
for (I i_idx = 0; i_idx < k; ++i_idx)
label_buf[i_idx] = current_labels[i_idx];
energy_table[0] = c.energy(label_buf);
for (Assgn a = 1; a < max_assgn; ++a) {
Assgn gray = a ^ (a >> 1);
Assgn diff = gray ^ last_gray;
int changed_idx = __builtin_ctz(diff);
if (diff & gray)
label_buf[changed_idx] = fusion_labels[changed_idx];
else
label_buf[changed_idx] = current_labels[changed_idx];
last_gray = gray;
energy_table[gray] = c.energy(label_buf);
}
}
// Compute the residual function
// g(S) - lambda_fusion(S) - lambda_current(C\S)
sospd::SubtractLinear(k, energy_table, fusion_lambda, current_lambda);
ASSERT(energy_table[0] == 0); // Check tightness of current labeling
++clique_index;
}
}
template<typename V, typename I, typename L, typename F>
inline typename sospd::SoSPD<V,I,L,F>::REAL sospd::SoSPD<V,I,L,F>::ComputeHeight(VarId i, Label x) {
REAL ret = m_energy->unary(i, x);
for (const auto& p : m_node_clique_list[i]) {
ret += dualVariable(p.first, p.second, x);
}
return ret;
}
template<typename V, typename I, typename L, typename F>
inline typename sospd::SoSPD<V,I,L,F>::REAL sospd::SoSPD<V,I,L,F>::ComputeHeightDiff(VarId i, Label l1, Label l2) const {
REAL ret = m_energy->unary(i, l1) - m_energy->unary(i, l2);
for (const auto& p : m_node_clique_list[i]) {
ret += dualVariable(p.first, p.second, l1)
- dualVariable(p.first, p.second, l2);
}
return ret;
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::SetupGraph(F& crf) {
const I n = I(m_labels.size());
crf.AddNode(n);
for (const CliquePtr& cp : m_energy->cliques()) {
const Clique<V,I,L>& c = *cp;
const I k = I(c.size());
ASSERT(k < I(32));
const I max_assgn = 1u << k;
std::vector<typename F::NodeId> nodes(c.nodes(), c.nodes() + c.size());
crf.AddClique(nodes, std::vector<REAL>(max_assgn, 0));
}
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::SetupAlphaEnergy(F& crf) {
const I n = I(m_labels.size());
crf.ClearUnaries();
crf.AddConstantTerm(-crf.GetConstantTerm());
for (I i = 0; i < n; ++i) {
REAL height_diff = ComputeHeightDiff(i, m_labels[i], m_fusion_labels[i]);
if (height_diff > 0) {
crf.AddUnaryTerm(i, height_diff, 0);
}
else {
crf.AddUnaryTerm(i, 0, -height_diff);
}
}
}
template<typename V, typename I, typename L, typename F>
inline bool sospd::SoSPD<V,I,L,F>::UpdatePrimalDual(F& crf) {
bool ret = false;
SetupAlphaEnergy(crf);
crf.Solve();
VarId n = m_labels.size();
for (VarId i = 0; i < n; ++i) {
int crf_label = crf.GetLabel(i);
if (crf_label == 1) {
Label alpha = m_fusion_labels[i];
if (m_labels[i] != alpha) ret = true;
m_labels[i] = alpha;
}
}
const auto& clique = crf.Graph().GetCliques();
I i = 0;
for (const CliquePtr& cp : m_energy->cliques()) {
const Clique<V,I,L>& c = *cp;
auto& ibfs_c = clique[i];
const std::vector<REAL>& phiCi = ibfs_c.AlphaCi();
for (I j = 0; j < I(phiCi.size()); ++j) {
dualVariable(i, j, m_fusion_labels[c.nodes()[j]]) += phiCi[j];
Height(c.nodes()[j], m_fusion_labels[c.nodes()[j]]) += phiCi[j];
}
++i;
}
return ret;
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::PostEditDual() {
Label labelBuf[32];
I clique_index = 0;
for (const CliquePtr& cp : m_energy->cliques()) {
const Clique<V,I,L>& c = *cp;
const VarId* nodes = c.nodes();
I k = I(c.size());
ASSERT(k < I(32));
REAL lambdaSum = 0;
for (I i = 0; i < k; ++i) {
labelBuf[i] = m_labels[nodes[i]];
lambdaSum += dualVariable(clique_index, i, labelBuf[i]);
}
REAL energy = c.energy(labelBuf);
REAL correction = energy - lambdaSum;
if (correction > 0) {
std::cout << "Bad clique in PostEditDual!\t Id:" << clique_index << "\n";
std::cout << "Correction: " << correction << "\tenergy: " << energy << "\tlambdaSum " << lambdaSum << "\n";
const auto& c2 = m_ibfs.Graph().GetCliques()[clique_index];
std::cout << "EnergyTable: ";
for (const auto& e : c2.EnergyTable())
std::cout << e << ", ";
std::cout << "\n";
}
ASSERT(correction <= 0);
REAL avg = correction / k;
int remainder = int(correction) % k;
if (remainder < 0) {
avg -= 1;
remainder += k;
}
for (I i = 0; i < k; ++i) {
auto& lambda_ail = dualVariable(clique_index, i, labelBuf[i]);
Height(nodes[i], labelBuf[i]) -= lambda_ail;
lambda_ail += avg;
if (int(i) < remainder)
lambda_ail += 1;
Height(nodes[i], labelBuf[i]) += lambda_ail;
}
++clique_index;
}
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::DualFit() {
// FIXME: This is the only function that doesn't work with integer division.
// It's also not really used for anything at the moment
/*
for (I i = 0; i < I(m_dual.size()); ++i)
for (I j = 0; j < I(m_dual[i].size()); ++j)
for (I k = 0; k < I(m_dual[i][j].size()); ++k)
m_dual[i][j][k] /= (m_mu * m_rho);
*/
ASSERT(false /* unimplemented */);
}
template<typename V, typename I, typename L, typename F>
inline bool sospd::SoSPD<V,I,L,F>::InitialFusionLabeling() {
m_pc(m_iter, m_labels, m_fusion_labels);
bool allDiff = false;
for (I i = 0; i < I(m_labels.size()); ++i) {
if (m_fusion_labels[i] < 0) m_fusion_labels[i] = 0;
if (m_fusion_labels[i] >= m_num_labels) m_fusion_labels[i] = m_num_labels-1;
if (m_labels[i] != m_fusion_labels[i])
allDiff = true;
}
return allDiff;
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::HeightAlphaProposal() {
const I n = I(m_labels.size());
REAL max_s_capacity = 0;
Label alpha = 0;
for (Label l = 0; l < m_num_labels; ++l) {
REAL s_capacity = 0;
for (I i = 0; i < n; ++i) {
REAL diff = Height(i, m_labels[i]) - Height(i, l);
if (diff > V(0))
s_capacity += diff;
}
if (s_capacity > max_s_capacity) {
max_s_capacity = s_capacity;
alpha = l;
}
}
for (I i = 0; i < n; ++i)
m_fusion_labels[i] = alpha;
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::AlphaProposal() {
Label alpha = m_iter % m_num_labels;
const I n = I(m_labels.size());
for (I i = 0; i < n; ++i)
m_fusion_labels[i] = alpha;
}
template<typename V, typename I, typename L, typename F>
inline void sospd::SoSPD<V,I,L,F>::Solve(I niters) {
if (m_iter == I(0)) {
SetupGraph(m_ibfs);
InitialLabeling();
InitialDual();
InitialNodeCliqueList();
}
#ifdef PROGRESS_DISPLAY
REAL energy = m_energy->ComputeEnergy(m_labels);
std::cout << "Iteration " << m_iter << ": " << energy << std::endl;
#endif
bool labelChanged = true;
I this_iter = 0;
while (labelChanged && this_iter < niters){
labelChanged = InitialFusionLabeling();
if (!labelChanged) break;
PreEditDual(m_ibfs);
UpdatePrimalDual(m_ibfs);
PostEditDual();
this_iter++;
m_iter++;
#ifdef PROGRESS_DISPLAY
energy = m_energy->ComputeEnergy(m_labels);
std::cout << "Iteration " << m_iter << ": " << energy << std::endl;
#endif
}
//LowerBound();
}
template<typename V, typename I, typename L, typename F>
inline typename sospd::SoSPD<V,I,L,F>::REAL sospd::SoSPD<V,I,L,F>::dualVariable(I alpha, VarId i, Label l) const {
return m_dual[alpha][i*m_num_labels+l];
}
template<typename V, typename I, typename L, typename F>
inline typename sospd::SoSPD<V,I,L,F>::REAL& sospd::SoSPD<V,I,L,F>::dualVariable(I alpha, VarId i, Label l) {
return m_dual[alpha][i*m_num_labels+l];
}
template<typename V, typename I, typename L, typename F>
inline typename sospd::SoSPD<V,I,L,F>::REAL sospd::SoSPD<V,I,L,F>::dualVariable(const LambdaAlpha& lambdaAlpha, VarId i, Label l) const {
return lambdaAlpha[i*m_num_labels+l];
}
template<typename V, typename I, typename L, typename F>
inline typename sospd::SoSPD<V,I,L,F>::REAL& sospd::SoSPD<V,I,L,F>::dualVariable(LambdaAlpha& lambdaAlpha, VarId i, Label l) {
return lambdaAlpha[i*m_num_labels+l];
}
template<typename V, typename I, typename L, typename F>
inline typename sospd::SoSPD<V,I,L,F>::LambdaAlpha& sospd::SoSPD<V,I,L,F>::lambdaAlpha(I alpha) {
return m_dual[alpha];
}
template<typename V, typename I, typename L, typename F>
inline const typename sospd::SoSPD<V,I,L,F>::LambdaAlpha& sospd::SoSPD<V,I,L,F>::lambdaAlpha(I alpha) const {
return m_dual[alpha];
}
template<typename V, typename I, typename L, typename F>
inline double sospd::SoSPD<V,I,L,F>::LowerBound() {
std::cout << "Computing Lower Bound\n";
double max_ratio = 0;
I clique_index = 0;
for (const CliquePtr& cp : m_energy->cliques()) {
const Clique<V,I,L>& c = *cp;
const I k = I(c.size());
ASSERT(k == 3); // Lower bound doesn't work for larger numbers
Label buf[3];
for (buf[0] = 0; buf[0] < m_num_labels; ++buf[0]) {
for (buf[1] = 0; buf[1] < m_num_labels; ++buf[1]) {
for (buf[2] = 0; buf[2] < m_num_labels; ++buf[2]) {
REAL energy = c.energy(buf);
REAL dualSum = dualVariable(clique_index, 0, buf[0])
+ dualVariable(clique_index, 1, buf[1])
+ dualVariable(clique_index, 2, buf[2]);
if (energy == 0) {
for (I i = 0; i < I(3); ++i) {
if (buf[i] != m_labels[c.nodes()[i]]) {
dualVariable(clique_index, i, buf[i]) -= dualSum - energy;
Height(c.nodes()[i], buf[i]) -= dualSum - energy;
dualSum = energy;
break;
}
}
ASSERT(dualSum == energy);
} else {
max_ratio = std::max(max_ratio, double(dualSum)/double(energy));
}
}
}
}
clique_index++;
}
REAL dual_objective = 0;
for (VarId i = 0; i < m_energy->numVars(); ++i) {
REAL min_height = std::numeric_limits<REAL>::max();
for (Label l = 0; l < m_num_labels; ++l)
min_height = std::min(min_height, Height(i, l));
dual_objective += min_height;
}
std::cout << "Max Ratio: " << max_ratio << "\n";
std::cout << "Dual objective: " << dual_objective << "\n";
return dual_objective / max_ratio;
} | 38.056478 | 137 | 0.564426 | jpjodoin |
0d126d18997c5116c1ffe32a9d37b6e080a1a95c | 1,210 | cpp | C++ | Aid/Aid/Main.cpp | mbikovitsky/bearded-octo-wallhack | d4df51b7f3dfc7f79ca958fd331ec043a4a2b5bc | [
"MIT"
] | 6 | 2016-08-22T18:43:38.000Z | 2021-09-06T15:22:11.000Z | Aid/Aid/Main.cpp | mbikovitsky/bearded-octo-wallhack | d4df51b7f3dfc7f79ca958fd331ec043a4a2b5bc | [
"MIT"
] | null | null | null | Aid/Aid/Main.cpp | mbikovitsky/bearded-octo-wallhack | d4df51b7f3dfc7f79ca958fd331ec043a4a2b5bc | [
"MIT"
] | 3 | 2016-08-22T18:57:14.000Z | 2018-05-13T11:34:22.000Z | #include <deque>
#include <boost\lexical_cast.hpp>
#include <boost\filesystem.hpp>
#include "Common\Utils.hpp"
#include "Exercises\Exercises.hpp"
namespace Aid {
void DoStuff(const std::deque<std::wstring> & arguments)
{
if (1 == arguments.size())
{
boost::filesystem::path modulePath(Utils::WinApiHelpers::GetModuleFileName());
auto stateFileName = modulePath.parent_path() / L"aid.state";
Exercises::g_exercises.Load(stateFileName.wstring());
do
{
Exercises::g_exercises.Save(stateFileName.wstring());
} while (Exercises::g_exercises.ExecuteOne());
}
else
{
// Retrieve the function RVA
auto rva = boost::lexical_cast<intptr_t>(arguments.at(1));
// Obtain a pointer to the function
auto rawPointer = Utils::RvaToPointer(rva);
auto childFunction = reinterpret_cast<Utils::ChildFunction>(rawPointer);
childFunction();
}
}
}
int wmain(int argc, wchar_t **argv)
{
try
{
const std::deque<std::wstring> arguments(argv, argv + argc);
Aid::DoStuff(arguments);
}
catch (const std::exception &)
{
std::cerr << boost::current_exception_diagnostic_information(true) << std::endl;
}
return 0;
}
| 20.508475 | 86 | 0.668595 | mbikovitsky |
0d1855467673227af463320dd6c9e725b1a7c2e8 | 5,541 | cpp | C++ | Data Structrures Lab/StringOperations.cpp | IamVaibhavsar/Second_Year_Lab_Assignments | dec3a0d4e71bc30820948d40d4e073b1d3e1da98 | [
"MIT"
] | 34 | 2020-02-09T08:42:49.000Z | 2022-03-01T09:04:53.000Z | Data Structrures Lab/StringOperations.cpp | MXNXV/Second_Year_Lab_Assignments | dec3a0d4e71bc30820948d40d4e073b1d3e1da98 | [
"MIT"
] | 1 | 2020-10-16T15:41:43.000Z | 2020-10-16T16:03:50.000Z | Data Structrures Lab/StringOperations.cpp | MXNXV/Second_Year_Lab_Assignments | dec3a0d4e71bc30820948d40d4e073b1d3e1da98 | [
"MIT"
] | 34 | 2020-01-07T08:47:42.000Z | 2022-03-29T16:45:56.000Z | /*Write C++ program for string operations- copy, concatenate, check substring, equal, reverse and length*/
#include<iostream>
#include<string.h> //noted
using namespace std;
class str
{
char a[20],b[20]; //Bydefault Private
public:
void read1(char []);
void read2(char []);
void copy(char [],char []);
void concatenate(char [],char []);
void substring(char []);
void compare(char [],char []);
void reverse(char [],char []);
void length(char []);
void toUppercase(char []);
void toLowercase(char []);
void palindrome(char []);
};
void str :: read1(char [])
{
cout<<"\nEnter the first string :";
cin>>a;
cout<<"\nThe first string is= "<<a<<endl;
}
void str :: read2(char [])
{
cout<<"\nEnter the second string :";
cin>>b;
cout<<"\nThe second string is= "<<b<<endl;
}
void str :: copy(char [],char [])
{
int i;
for(i=0;a[i]!='\0';i++)
{
b[i]=a[i];
}
cout<<"\nAfter copying, The second string is = "<<b<<endl;
cout<<"\nHence first string is copied into second"<<endl;
}
void str :: concatenate(char [],char [])
{
int i,j;
for (i = 0; a[i]!='\0'; i++);
{
for (j = 0; b[j]!='\0'; j++,i++)
{
a[i]=b[j]; //noted
}
}
a[i] = '\0';
cout<<"\n String after the Concatenate = "<<a<<endl;
}
void str :: substring(char [])
{
char search[20];
int i,j,k;
i=0,j=0;
cout<<"\nEnter the Search Substring: "<<endl;
cin>>search;
while(a[i]!='\0')
{
while((a[i]!=search[0])&&(a[i]!='\0'))
i++;
if(a[i]=='\0')
{
cout<<"\nIt is not a substring";
break;
}
k=i;
while((a[i]==search[j])&&(a[i]!='\0')&&(search[j]!='\0'))
{
i++;
j++;
}
if(search[j]=='\0')
{
cout<<"\nIt is a substring and present at position number "<<k+1<<endl;
break;
}
if(a[i]=='\0')
{
cout<<"\nIt is not a substring";
break;
}
i=k+1;
j=0;
}
}
void str :: compare(char [],char [])
{
int i=0;
while((a[i]==b[i]) && (a[i]!='\0'))
{
i++;
}
if(a[i]>b[i])
cout<<a<<" is greater than "<<b<<endl;
else if(a[i]<b[i])
cout<<a<<" is smaller than "<<b<<endl;
else
cout<<a<<" is equal to "<<b<<endl;
}
void str :: reverse(char [], char [])
{
int i,j,len;
j = 0;
len = strlen(a);
for (i =len-1; i >= 0;i--)
{
b[j++] = a[i];
}
b[i] = '\0';
cout<<"\n String after Reversing = "<<b<<endl;
}
void str :: length(char [])
{
int i,cnt=0;
for(i=0;a[i]!='\0';i++)
{
cnt++;
}
cout<<"\nThe length of String is = "<<cnt<<endl;
}
void str :: toUppercase(char [])
{
int i;
for (i = 0; a[i]!='\0'; i++)
{
if(a[i] >= 'a' && a[i] <= 'z')
{
a[i] = a[i] -32;
}
}
cout<<"\n The Entered String in Upper Case = "<<a<<endl;
}
void str :: toLowercase(char [])
{
int i;
for (i = 0; a[i]!='\0'; i++)
{
if(a[i] >= 'A' && a[i] <= 'Z')
{
a[i] = a[i] +32;
}
}
cout<<"\n The Entered String in Lower Case = "<<a<<endl;
}
void str :: palindrome(char [])
{
int l = 0;
int h = strlen(a) - 1;
while (l<h)
{
if (a[l++] != a[h--])
{
cout<<"\n The String "<<a<<" is Not a Palindrome"<<endl;
return;
}
}
cout<<"\n The String "<<a<<" is a palindrome"<<endl;
}
int main()
{
str s1;
int ch=0;
char cont,ch1[20],ch2[20];
do
{
cout<<"\nThe available choices are as follows: ";
cout<<"\n1.To Copy a string into another.";
cout<<"\n2.To concatenate two strings.";
cout<<"\n3.To Chech the substring.";
cout<<"\n4.To Compare the strings";
cout<<"\n5.To reverse a string .";
cout<<"\n6.To find the length of a string.";
cout<<"\n7.To convert the string into upper case.";
cout<<"\n8.To convert the string into Lower case.";
cout<<"\n9.To check string is palindrome or not.";
cout<<"\nEnter Your Choice: ";
cin>>ch;
switch(ch)
{
case 1:
s1.read1(ch1);
s1.read2(ch2);
s1.copy(ch1,ch2);
cout<<"\n*********************************************************************";
break;
case 2:
s1.read1(ch1);
s1.read2(ch2);
s1.concatenate(ch1,ch2);
cout<<"\n*********************************************************************";
break;
case 3:
s1.read1(ch1);
s1.substring(ch1);
cout<<"\n********************************************************************";
break;
case 4:
s1.read1(ch1);
s1.read2(ch2);
s1.compare(ch1,ch2);
cout<<"\n********************************************************************";
break;
case 5:
s1.read1(ch1);
s1.reverse(ch1,ch2);
cout<<"\n********************************************************************";
break;
case 6:
s1.read1(ch1);
s1.length(ch1);
cout<<"\n********************************************************************";
break;
case 7:
s1.read1(ch1);
s1.toUppercase(ch1);
cout<<"\n********************************************************************";
break;
case 8:
s1.read1(ch1);
s1.toLowercase(ch1);
cout<<"\n********************************************************************";
break;
case 9:
s1.read1(ch1);
s1.palindrome(ch2);
cout<<"\n********************************************************************";
break;
default:
{
cout<<"\n SORRY! Please Enter a valid choice";
}
}
cout<<"\nDo you want to Continue?"<<endl;
cin>>cont;
}while(cont=='Y'||cont=='y');
return 0;
}
| 18.59396 | 106 | 0.439451 | IamVaibhavsar |
0d1c148b5ab0de3d48c69dc629e369d28b987032 | 5,090 | cpp | C++ | AGVCCON/fDurationTasks.cpp | jluzardo1971/ActiveGanttVC | 4748cb4d942551dc64c9017f279c90969cdcc634 | [
"MIT"
] | null | null | null | AGVCCON/fDurationTasks.cpp | jluzardo1971/ActiveGanttVC | 4748cb4d942551dc64c9017f279c90969cdcc634 | [
"MIT"
] | null | null | null | AGVCCON/fDurationTasks.cpp | jluzardo1971/ActiveGanttVC | 4748cb4d942551dc64c9017f279c90969cdcc634 | [
"MIT"
] | null | null | null | // ----------------------------------------------------------------------------------------
// COPYRIGHT NOTICE
// ----------------------------------------------------------------------------------------
//
// The Source Code Store LLC
// ACTIVEGANTT SCHEDULER COMPONENT FOR C++ - ActiveGanttVC
// ActiveX Control
// Copyright (c) 2002-2017 The Source Code Store LLC
//
// All Rights Reserved. No parts of this file may be reproduced, modified or transmitted
// in any form or by any means without the written permission of the author.
//
// ----------------------------------------------------------------------------------------
#include "stdafx.h"
#include "AGVCCON.h"
#include "fDurationTasks.h"
IMPLEMENT_DYNAMIC(fDurationTasks, CDialog)
fDurationTasks::fDurationTasks(CWnd* pParent /*=NULL*/)
: CDialog(fDurationTasks::IDD, pParent)
{
}
fDurationTasks::~fDurationTasks()
{
}
void fDurationTasks::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
DDX_Control(pDX, IDC_ACTIVEGANTTVCCTL1, ActiveGanttVCCtl1);
}
BEGIN_MESSAGE_MAP(fDurationTasks, CDialog)
ON_WM_SIZE()
END_MESSAGE_MAP()
BOOL fDurationTasks::OnInitDialog()
{
CDialog::OnInitDialog();
g_MaximizeWindowsDim(this);
CWnd::ShowWindow(SW_SHOWMAXIMIZED);
//If you open the form: Styles And Templates -> Available Templates in the main menu (fTemplates.vb)
//you can preview all available Templates.
//Or you can also build your own:
//fMSProject11.vb shows you how to build a Solid Template in the InitializeAG Method.
//fMSProject14.vb shows you how to build a Gradient Template in the InitializeAG Method.
ActiveGanttVCCtl1.ApplyTemplate(STC_CH_VGRAD_ANAKIWA_BLUE, STO_DEFAULT);
ActiveGanttVCCtl1.SetAddMode(AT_DURATION_BOTH);
ActiveGanttVCCtl1.SetAddDurationInterval(IL_HOUR);
CclsView oView;
oView = ActiveGanttVCCtl1.GetViews().Add(IL_MINUTE, 10, ST_MONTH, ST_NOT_VISIBLE, ST_DAYOFWEEK, _T("View1"));
oView.GetTimeLine().GetTickMarkArea().SetVisible(FALSE);
ActiveGanttVCCtl1.SetCurrentView(_T("View1"));
LONG i = 0;
for (i = 0; i <= 110; i++)
{
ActiveGanttVCCtl1.GetRows().Add(_T("K") + CStr(i), _T(""), FALSE, TRUE, _T(""));
}
CclsTimeBlock oTimeBlock;
//Note: non-working overlapping TimeBlock objects are combined for duration calculation purposes.
// TimeBlock starts at 6:00pm and ends on 7:00am next day (13 Hours)
// This TimeBlock is repeated every day.
oTimeBlock = ActiveGanttVCCtl1.GetTimeBlocks().Add(_T("TB_OutOfOfficeHours"));
oTimeBlock.SetNonWorking(TRUE);
oTimeBlock.SetBaseDate(GetDateTime(2000, 1, 1, 18, 0, 0));
oTimeBlock.SetDurationInterval(IL_HOUR);
oTimeBlock.SetDurationFactor(13);
oTimeBlock.SetTimeBlockType(TBT_RECURRING);
oTimeBlock.SetRecurringType(RCT_DAY);
// TimeBlock starts at 12:00pm (noon) and ends at 1:30pm (90 Minutes)
// This TimeBlock is repeated every day.
oTimeBlock = ActiveGanttVCCtl1.GetTimeBlocks().Add(_T("TB_LunchBreak"));
oTimeBlock.SetNonWorking(TRUE);
oTimeBlock.SetBaseDate(GetDateTime(2000, 1, 1, 12, 0, 0));
oTimeBlock.SetDurationInterval(IL_MINUTE);
oTimeBlock.SetDurationFactor(90);
oTimeBlock.SetTimeBlockType(TBT_RECURRING);
oTimeBlock.SetRecurringType(RCT_DAY);
// Timeblock starts at 12:00am Saturday and ends on 12:00am Monday (48 Hours)
// This TimeBlock is repeated every week.
oTimeBlock = ActiveGanttVCCtl1.GetTimeBlocks().Add(_T("TB_Weekend"));
oTimeBlock.SetNonWorking(TRUE);
oTimeBlock.SetBaseDate(GetDateTime(2000, 1, 1, 0, 0, 0));
oTimeBlock.SetDurationInterval(IL_HOUR);
oTimeBlock.SetDurationFactor(48);
oTimeBlock.SetTimeBlockType(TBT_RECURRING);
oTimeBlock.SetRecurringType(RCT_WEEK);
oTimeBlock.SetBaseWeekDay(WD_SATURDAY);
// Arbitrary holiday that starts at 12:00am January 8th and ends on 12:00am January 9th (24 hours)
// This TimeBlock is repeated every year.
oTimeBlock = ActiveGanttVCCtl1.GetTimeBlocks().Add(_T("TB_Jan8"));
oTimeBlock.SetNonWorking(TRUE);
oTimeBlock.SetBaseDate(GetDateTime(2000, 1, 8, 0, 0, 0));
oTimeBlock.SetDurationInterval(IL_HOUR);
oTimeBlock.SetDurationFactor(24);
oTimeBlock.SetTimeBlockType(TBT_RECURRING);
oTimeBlock.SetRecurringType(RCT_YEAR);
ActiveGanttVCCtl1.GetTimeBlocks().SetIntervalStart(GetDateTime(2012, 1, 1));
ActiveGanttVCCtl1.GetTimeBlocks().SetIntervalEnd(GetDateTime(2023, 6, 1));
ActiveGanttVCCtl1.GetTimeBlocks().SetIntervalType(TBIT_MANUAL);
ActiveGanttVCCtl1.GetTimeBlocks().CalculateInterval();
CclsTask oTask;
for (i = 0; i <= 100; i++)
{
oTask = ActiveGanttVCCtl1.GetTasks().DAdd(_T("K") + CStr(i), GetDateTime(2013, 1, 1, 0, 0, 0), IL_HOUR, i, CStr(i), _T(""), _T(""), _T(""));
}
ActiveGanttVCCtl1.GetCurrentViewObject().GetTimeLine().Position(GetDateTime(2013, 1, 1, 0, 0, 0));
ActiveGanttVCCtl1.Redraw();
return TRUE;
}
void fDurationTasks::OnSize(UINT nType, int cx, int cy)
{
CDialog::OnSize(nType, cx, cy);
g_Resize(this, &ActiveGanttVCCtl1);
} | 37.426471 | 148 | 0.68998 | jluzardo1971 |
0d1d42bb1a2bbac80182053dd249695c15c4e76e | 2,919 | cpp | C++ | PickerControls/WxColourPickerCtrl1/src/WxColourPickerCtrl1Frame.cpp | wxIshiko/wxWidgetsTutorials | 83efacbad925a78b3111e055c2f0646ab68b973f | [
"Unlicense"
] | 38 | 2018-05-10T08:01:05.000Z | 2022-03-28T23:14:45.000Z | PickerControls/WxColourPickerCtrl1/src/WxColourPickerCtrl1Frame.cpp | zhuhui09/wxWidgetsTutorials | 83efacbad925a78b3111e055c2f0646ab68b973f | [
"Unlicense"
] | null | null | null | PickerControls/WxColourPickerCtrl1/src/WxColourPickerCtrl1Frame.cpp | zhuhui09/wxWidgetsTutorials | 83efacbad925a78b3111e055c2f0646ab68b973f | [
"Unlicense"
] | 16 | 2018-01-14T09:53:12.000Z | 2022-03-20T00:34:56.000Z | /*
Copyright (c) 2015 Xavier Leclercq
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 "WxColourPickerCtrl1Frame.h"
#include "WindowIDs.h"
#include <wx/panel.h>
#include <wx/sizer.h>
WxColourPickerCtrl1Frame::WxColourPickerCtrl1Frame(const wxString& title)
: wxFrame(NULL, wxID_ANY, title), m_textCtrl(0)
{
// Create a top-level panel to hold all the contents of the frame
wxPanel* panel = new wxPanel(this, wxID_ANY);
// Create a wxTextCtrl to have some text we can select the color of
m_textCtrl = new wxTextCtrl(panel, wxID_ANY, "Some text of the selected color.",
wxDefaultPosition, wxSize(200, wxDefaultCoord));
// Create a wxColourPickerCtrl control
wxColourPickerCtrl* colourPickerCtrl = new wxColourPickerCtrl(panel, ColourPickerID);
// Set up the sizer for the panel
wxBoxSizer* panelSizer = new wxBoxSizer(wxHORIZONTAL);
panelSizer->Add(m_textCtrl, 0, wxEXPAND | wxALL, 15);
panelSizer->Add(colourPickerCtrl, 0, wxEXPAND | wxALL, 15);
panel->SetSizer(panelSizer);
// Set up the sizer for the frame and resize the frame
// according to its contents
wxBoxSizer* topSizer = new wxBoxSizer(wxHORIZONTAL);
topSizer->Add(panel, 1, wxEXPAND);
SetSizerAndFit(topSizer);
}
void WxColourPickerCtrl1Frame::OnColourChanged(wxColourPickerEvent& evt)
{
// Use the wxColourPickerEvent::GetColour() function to get the selected
// color and set the color of the text control accordingly.
m_textCtrl->SetForegroundColour(evt.GetColour());
m_textCtrl->Refresh();
}
// Add the event handler to the event table. As you can see we use the
// window ID to link the event handler to the wxColourPickerCtrl we created.
wxBEGIN_EVENT_TABLE(WxColourPickerCtrl1Frame, wxFrame)
EVT_COLOURPICKER_CHANGED(ColourPickerID, WxColourPickerCtrl1Frame::OnColourChanged)
wxEND_EVENT_TABLE()
| 43.567164 | 89 | 0.7506 | wxIshiko |
0d20612ce77898f7ac8dbf6c3b055826f72b798d | 3,010 | cpp | C++ | src/dialog/vinserttabledialog.cpp | linails/vnote | 97810731db97292f474951c3450aac150acef0bc | [
"MIT"
] | 1 | 2020-10-13T14:28:59.000Z | 2020-10-13T14:28:59.000Z | src/dialog/vinserttabledialog.cpp | linails/vnote | 97810731db97292f474951c3450aac150acef0bc | [
"MIT"
] | 1 | 2022-01-22T13:10:44.000Z | 2022-01-22T13:10:44.000Z | src/dialog/vinserttabledialog.cpp | linails/vnote | 97810731db97292f474951c3450aac150acef0bc | [
"MIT"
] | 1 | 2021-06-17T02:43:27.000Z | 2021-06-17T02:43:27.000Z | #include "vinserttabledialog.h"
#include <QSpinBox>
#include <QRadioButton>
#include <QGridLayout>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLabel>
#include <QDialogButtonBox>
#include <QPushButton>
#include <QButtonGroup>
VInsertTableDialog::VInsertTableDialog(QWidget *p_parent)
: QDialog(p_parent),
m_alignment(VTable::None)
{
setupUI();
}
void VInsertTableDialog::setupUI()
{
m_rowCount = new QSpinBox(this);
m_rowCount->setToolTip(tr("Number of rows of the table body"));
m_rowCount->setMaximum(1000);
m_rowCount->setMinimum(0);
m_colCount = new QSpinBox(this);
m_colCount->setToolTip(tr("Number of columns of the table"));
m_colCount->setMaximum(1000);
m_colCount->setMinimum(1);
QRadioButton *noneBtn = new QRadioButton(tr("None"), this);
QRadioButton *leftBtn = new QRadioButton(tr("Left"), this);
QRadioButton *centerBtn = new QRadioButton(tr("Center"), this);
QRadioButton *rightBtn = new QRadioButton(tr("Right"), this);
QHBoxLayout *alignLayout = new QHBoxLayout();
alignLayout->addWidget(noneBtn);
alignLayout->addWidget(leftBtn);
alignLayout->addWidget(centerBtn);
alignLayout->addWidget(rightBtn);
alignLayout->addStretch();
noneBtn->setChecked(true);
QButtonGroup *bg = new QButtonGroup(this);
bg->addButton(noneBtn, VTable::None);
bg->addButton(leftBtn, VTable::Left);
bg->addButton(centerBtn, VTable::Center);
bg->addButton(rightBtn, VTable::Right);
connect(bg, static_cast<void(QButtonGroup::*)(int, bool)>(&QButtonGroup::buttonToggled),
this, [this](int p_id, bool p_checked){
if (p_checked) {
m_alignment = static_cast<VTable::Alignment>(p_id);
}
});
QGridLayout *topLayout = new QGridLayout();
topLayout->addWidget(new QLabel(tr("Row:")), 0, 0, 1, 1);
topLayout->addWidget(m_rowCount, 0, 1, 1, 1);
topLayout->addWidget(new QLabel(tr("Column:")), 0, 2, 1, 1);
topLayout->addWidget(m_colCount, 0, 3, 1, 1);
topLayout->addWidget(new QLabel(tr("Alignment:")), 1, 0, 1, 1);
topLayout->addLayout(alignLayout, 1, 1, 1, 3);
// Ok is the default button.
m_btnBox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
connect(m_btnBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(m_btnBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
QPushButton *okBtn = m_btnBox->button(QDialogButtonBox::Ok);
okBtn->setProperty("SpecialBtn", true);
QVBoxLayout *mainLayout = new QVBoxLayout();
mainLayout->addLayout(topLayout);
mainLayout->addWidget(m_btnBox);
setLayout(mainLayout);
setWindowTitle(tr("Insert Table"));
}
int VInsertTableDialog::getRowCount() const
{
return m_rowCount->value();
}
int VInsertTableDialog::getColumnCount() const
{
return m_colCount->value();
}
VTable::Alignment VInsertTableDialog::getAlignment() const
{
return m_alignment;
}
| 31.354167 | 92 | 0.68505 | linails |
0d22b3c91dc6464f08e620187d9368e7af62be64 | 5,644 | hpp | C++ | pythran/pythonic/numpy/reduce.hpp | xmar/pythran | dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592 | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/numpy/reduce.hpp | xmar/pythran | dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592 | [
"BSD-3-Clause"
] | null | null | null | pythran/pythonic/numpy/reduce.hpp | xmar/pythran | dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592 | [
"BSD-3-Clause"
] | null | null | null | #ifndef PYTHONIC_NUMPY_REDUCE_HPP
#define PYTHONIC_NUMPY_REDUCE_HPP
#include "pythonic/include/numpy/reduce.hpp"
#include "pythonic/types/ndarray.hpp"
#include "pythonic/__builtin__/None.hpp"
#include "pythonic/__builtin__/ValueError.hpp"
#include "pythonic/utils/neutral.hpp"
#include <algorithm>
namespace pythonic
{
namespace numpy
{
template <class Op, size_t N, class vector_form>
struct _reduce {
template <class E, class F>
F operator()(E e, F acc)
{
for (auto const &value : e)
acc = _reduce<Op, N - 1, vector_form>{}(value, acc);
return acc;
}
};
template <class Op, class vector_form>
struct _reduce<Op, 1, vector_form> {
template <class E, class F>
F operator()(E e, F acc)
{
for (auto const &value : e)
Op{}(acc, value);
return acc;
}
};
#ifdef USE_BOOST_SIMD
template <class vectorizer, class Op, class E, class F>
F vreduce(E e, F acc)
{
using T = typename E::dtype;
using vT = boost::simd::pack<T>;
static const size_t vN = vT::static_size;
const long n = e.size();
auto viter = vectorizer::vbegin(e), vend = vectorizer::vend(e);
const long bound = std::distance(viter, vend);
if (bound > 0) {
auto vacc = *viter;
++viter;
for (long i = 1; i < bound; ++i, ++viter)
Op{}(vacc, *viter);
alignas(sizeof(vT)) T stored[vN];
boost::simd::store(vacc, &stored[0]);
for (size_t j = 0; j < vN; ++j)
Op{}(acc, stored[j]);
}
auto iter = e.begin() + bound * vN;
for (long i = bound * vN; i < n; ++i, ++iter) {
Op{}(acc, *iter);
}
return acc;
}
template <class Op>
struct _reduce<Op, 1, types::vectorizer> {
template <class E, class F>
F operator()(E e, F acc)
{
return vreduce<types::vectorizer, Op>(e, acc);
}
};
template <class Op>
struct _reduce<Op, 1, types::vectorizer_nobroadcast> {
template <class E, class F>
F operator()(E e, F acc)
{
return vreduce<types::vectorizer_nobroadcast, Op>(e, acc);
}
};
#endif
template <class Op, class E, bool vector_form>
struct reduce_helper;
template <class Op, class E>
struct reduce_helper<Op, E, false> {
reduce_result_type<E> operator()(E const &expr,
reduce_result_type<E> p) const
{
return _reduce<Op, E::value, types::novectorizer>{}(expr, p);
}
};
template <class Op, class E>
struct reduce_helper<Op, E, true> {
reduce_result_type<E> operator()(E const &expr,
reduce_result_type<E> p) const
{
if (utils::no_broadcast(expr))
return _reduce<Op, E::value, types::vectorizer_nobroadcast>{}(expr,
p);
else
return _reduce<Op, E::value, types::vectorizer>{}(expr, p);
}
};
template <class Op, class E>
typename std::enable_if<types::is_numexpr_arg<E>::value,
reduce_result_type<E>>::type
reduce(E const &expr, types::none_type)
{
bool constexpr is_vectorizable =
E::is_vectorizable and
not std::is_same<typename E::dtype, bool>::value;
reduce_result_type<E> p = utils::neutral<Op, typename E::dtype>::value;
return reduce_helper<Op, E, is_vectorizable>{}(expr, p);
}
template <class Op, class E>
typename std::enable_if<
std::is_scalar<E>::value or types::is_complex<E>::value, E>::type
reduce(E const &expr, types::none_type)
{
return expr;
}
template <class Op, class E>
auto reduce(E const &array, long axis) ->
typename std::enable_if<std::is_scalar<E>::value or
types::is_complex<E>::value,
decltype(reduce<Op>(array))>::type
{
if (axis != 0)
throw types::ValueError("axis out of bounds");
return reduce<Op>(array);
}
template <class Op, class E>
auto reduce(E const &array, long axis) ->
typename std::enable_if<E::value == 1,
decltype(reduce<Op>(array))>::type
{
if (axis != 0)
throw types::ValueError("axis out of bounds");
return reduce<Op>(array);
}
template <class Op, class E>
typename std::enable_if<E::value != 1, reduced_type<E>>::type
reduce(E const &array, long axis)
{
if (axis < 0)
axis += E::value;
if (axis < 0 || size_t(axis) >= E::value)
throw types::ValueError("axis out of bounds");
auto shape = array.shape();
if (axis == 0) {
types::array<long, E::value - 1> shp;
std::copy(shape.begin() + 1, shape.end(), shp.begin());
return _reduce<Op, 1, types::novectorizer /* not on scalars*/>{}(
array,
reduced_type<E>{shp, utils::neutral<Op, typename E::dtype>::value});
} else {
types::array<long, E::value - 1> shp;
auto next = std::copy(shape.begin(), shape.begin() + axis, shp.begin());
std::copy(shape.begin() + axis + 1, shape.end(), next);
reduced_type<E> sumy{shp, __builtin__::None};
std::transform(array.begin(), array.end(), sumy.begin(),
[axis](typename E::const_iterator::value_type other) {
return reduce<Op>(other, axis - 1);
});
return sumy;
}
}
}
}
#endif
| 31.18232 | 80 | 0.546244 | xmar |
0d23fc8040b4d8729801a99ee105e6519236bcc1 | 2,274 | cpp | C++ | exe/Python_launcher.cpp | dillionhacker/python222 | 205414c33fba8166167fd8a6a03eda1a68f16316 | [
"Apache-2.0"
] | 1 | 2022-03-17T13:55:02.000Z | 2022-03-17T13:55:02.000Z | exe/Python_launcher.cpp | tuankien2601/python222 | 205414c33fba8166167fd8a6a03eda1a68f16316 | [
"Apache-2.0"
] | null | null | null | exe/Python_launcher.cpp | tuankien2601/python222 | 205414c33fba8166167fd8a6a03eda1a68f16316 | [
"Apache-2.0"
] | null | null | null | /*
* ====================================================================
* Python_launcher.cpp
*
* Launchpad EXE for starting Python server scripts
*
* Copyright (c) 2005 Nokia 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.
* ====================================================================
*/
#include <e32std.h>
#include <utf.h>
#include "CSPyInterpreter.h"
static TInt AsyncRunCallbackL(TAny* aArg)
{
char *argv[1];
int argc;
TBuf8<KMaxFileName> namebuf;
CnvUtfConverter::ConvertFromUnicodeToUtf8(namebuf, *((TDesC*)aArg));
argv[0] = (char*)namebuf.PtrZ();
argc = 1;
CSPyInterpreter* interp = CSPyInterpreter::NewInterpreterL();
interp->RunScript(argc, argv);
delete interp;
CActiveScheduler::Stop();
return KErrNone;
}
static void RunServerL(const TDesC& aScriptName)
{
CActiveScheduler* as = new (ELeave) CActiveScheduler;
CleanupStack::PushL(as);
CActiveScheduler::Install(as);
TCallBack cb(&AsyncRunCallbackL, (TAny*)&aScriptName);
CAsyncCallBack* async_callback =
new (ELeave) CAsyncCallBack(cb, CActive::EPriorityHigh);
CleanupStack::PushL(async_callback);
async_callback->CallBack();
CActiveScheduler::Start();
CleanupStack::PopAndDestroy(2);
}
#if defined(__WINS__)
GLDEF_C TInt E32Dll(TDllReason)
{
return KErrNone;
}
EXPORT_C TInt WinsMain(TAny *aScriptName)
#else
GLDEF_C TInt E32Main()
#endif
{
TInt error;
TFileName script;
#if defined(__WINS__)
script.Copy(*((TDesC*)aScriptName));
delete (HBufC*)aScriptName;
#else
RProcess().CommandLine(script);
#endif
CTrapCleanup* cleanupStack = CTrapCleanup::New();
TRAP(error, RunServerL(script));
if (error != KErrNone)
User::Panic(_L("Python server script"), error);
delete cleanupStack;
return KErrNone;
}
| 25.266667 | 74 | 0.686456 | dillionhacker |
0d24f56177201d598d47147f622e6b09f149d58c | 6,792 | cpp | C++ | circular_buffer.cpp | travc/vt | 20ba6b7a313aebf2162eb877c38a5c818322bafe | [
"MIT"
] | 166 | 2015-01-14T23:14:05.000Z | 2022-03-31T14:15:56.000Z | circular_buffer.cpp | travc/vt | 20ba6b7a313aebf2162eb877c38a5c818322bafe | [
"MIT"
] | 108 | 2015-01-16T13:21:07.000Z | 2022-01-26T22:47:55.000Z | circular_buffer.cpp | travc/vt | 20ba6b7a313aebf2162eb877c38a5c818322bafe | [
"MIT"
] | 48 | 2015-01-16T23:35:18.000Z | 2022-03-01T12:14:53.000Z | /* The MIT License
Copyright (c) 2015 Adrian Tan <atks@umich.edu>
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 "circular_buffer.h"
/**
* Constructor.
*
* @k - size of pileup is 2^k
*/
CircularBuffer::CircularBuffer(uint32_t k, uint32_t window_size)
{
//Buffer size is a power of 2^k.
buffer_size = 1 << k;
//this provides a cheaper way to do modulo operations for a circular array.
buffer_size_mask = (0xFFFFFFFF >> (32-k));
this->window_size = window_size;
P.resize(buffer_size);
tid = -1;
beg0 = end0 = 0;
gbeg1 = 0;
debug = 0;
};
/**
* Overloads subscript operator for accessing pileup positions.
*/
char& CircularBuffer::operator[] (const int32_t i)
{
return P[i];
}
/**
* Returns the maximum size of the pileup.
*/
uint32_t CircularBuffer::max_size()
{
return buffer_size - 1;
}
/**
* Returns the size of the pileup.
*/
uint32_t CircularBuffer::size()
{
return (end0>=beg0 ? end0-beg0 : buffer_size-(beg0-end0));
}
/**
* Checks if buffer is empty.
*/
bool CircularBuffer::is_empty()
{
return beg0==end0;
};
/**
* Set reference fasta file.
*/
void CircularBuffer::set_reference(std::string& ref_fasta_file)
{
if (ref_fasta_file!="")
{
fai = fai_load(ref_fasta_file.c_str());
if (fai==NULL)
{
fprintf(stderr, "[%s:%d %s] cannot load genome index: %s\n", __FILE__, __LINE__, __FUNCTION__, ref_fasta_file.c_str());
exit(1);
}
}
};
/**
* Set debug.
*/
void CircularBuffer::set_debug(int32_t debug)
{
this->debug = debug;
};
/**
* Sets tid.
*/
void CircularBuffer::set_tid(uint32_t tid)
{
this->tid = tid;
}
/**
* Gets tid.
*/
uint32_t CircularBuffer::get_tid()
{
return this->tid;
}
/**
* Sets chrom.
*/
void CircularBuffer::set_chrom(std::string& chrom)
{
this->chrom = chrom;
}
/**
* Gets chrom.
*/
std::string CircularBuffer::get_chrom()
{
return chrom;
}
/**
* Gets window_size.
*/
uint32_t CircularBuffer::get_window_size()
{
return window_size;
}
/**
* Converts gpos1 to index in P.
* If P is empty, initialize first position as gpos1.
*/
uint32_t CircularBuffer::g2i(uint32_t gpos1)
{
if (is_empty())
{
gbeg1 = gpos1;
return beg0;
}
else
{
if (gpos1<gbeg1)
{
fprintf(stderr, "[%s:%d %s] buffer out of extent: gpos1 %d < gbeg1 %d\n", __FILE__, __LINE__, __FUNCTION__, gpos1, gbeg1);
abort();
}
return (beg0 + (gpos1-gbeg1)) & buffer_size_mask;
}
}
/**
* Increments i by 1 circularly.
*/
uint32_t CircularBuffer::inc(uint32_t i)
{
return (i+1) & buffer_size_mask;
};
/**
* Sets gbeg1.
*/
void CircularBuffer::set_gbeg1(uint32_t gbeg1)
{
this->gbeg1 = gbeg1;
}
/**
* Gets gbeg1.
*/
uint32_t CircularBuffer::get_gbeg1()
{
return gbeg1;
}
/**
* Gets gend1.
*/
uint32_t CircularBuffer::get_gend1()
{
if (is_empty())
{
return 0;
}
else
{
return gbeg1 + diff(end0, beg0) - 1;
}
}
/**
* Sets beg0.
*/
void CircularBuffer::set_beg0(uint32_t beg0)
{
this->beg0 = beg0;
}
/**
* Sets end0.
*/
void CircularBuffer::set_end0(uint32_t end0)
{
this->end0 = end0;
}
/**
* Gets the index of the first element.
*/
uint32_t CircularBuffer::begin()
{
return beg0;
}
/**
* Gets the index of the last element.
*/
uint32_t CircularBuffer::end()
{
return end0;
}
/**
* Returns the difference between 2 buffer positions
*/
uint32_t CircularBuffer::diff(uint32_t i, uint32_t j)
{
return (i>=j ? i-j : buffer_size-(j-i));
};
/**
* Increments beg0 by 1.
*/
void CircularBuffer::inc_beg0()
{
beg0 = (beg0+1) & buffer_size_mask;
};
/**
* Increments end0 by 1.
*/
void CircularBuffer::inc_end0()
{
end0 = (end0+1) & buffer_size_mask;
};
/**
* Increments index i by j cyclically.
*/
uint32_t CircularBuffer::inc(uint32_t i, uint32_t j)
{
return (i+j) & buffer_size_mask;
};
/**
* Get a base.
*/
char CircularBuffer::fetch_base(std::string& chrom, uint32_t& pos1)
{
int ref_len = 0;
char *refseq = faidx_fetch_uc_seq(fai, chrom.c_str(), pos1-1, pos1-1, &ref_len);
if (!refseq)
{
fprintf(stderr, "[%s:%d %s] failure to extrac base from fasta file: %s:%d: >\n", __FILE__, __LINE__, __FUNCTION__, chrom.c_str(), pos1-1);
exit(1);
}
char base = refseq[0];
free(refseq);
return base;
};
///**
// * Get a sequence. User have to free the char* returned.
// */
//char* CircularBuffer::get_sequence(std::string& chrom, uint32_t pos1, uint32_t len)
//{
// int ref_len = 0;
// char* seq = faidx_fetch_uc_seq(fai, chrom.c_str(), pos1-1, pos1+len-2, &ref_len);
// if (!seq || ref_len!=len)
// {
// fprintf(stderr, "[%s:%d %s] failure to extract sequence from fasta file: %s:%d: >\n", __FILE__, __LINE__, __FUNCTION__, chrom.c_str(), pos1-1);
// exit(1);
// }
//
// return seq;
//};
/**
* Print pileup state.
*/
void CircularBuffer::print_state()
{
std::cerr << "******************" << "\n";
std::cerr << "gindex : " << gbeg1 << "-" << get_gend1() << "\n";
std::cerr << "index : " << beg0 << "-" << end0 << " (" << size() << ")\n";
std::cerr << "******************" << "\n";
uint32_t k = 0;
for (uint32_t i=beg0; i!=end0; i=inc(i))
{
//P[i].print(gbeg1+k);
++k;
}
std::cerr << "******************" << "\n";
}
/**
* Print pileup state extent.
*/
void CircularBuffer::print_state_extent()
{
std::cerr << "******************" << "\n";
std::cerr << "gindex : " << gbeg1 << "-" << get_gend1() << "\n";
std::cerr << "index : " << beg0 << "-" << end0 << " (" << size() << ")\n";
std::cerr << "******************" << "\n";
} | 20.581818 | 153 | 0.602621 | travc |
0d2d08597e179e4c55fc483afeed40178a2fc5e5 | 1,804 | hpp | C++ | host/include/serial_can_dump.hpp | hephaisto/serial-can-dump | a3aa3e6e166327ad86b491ca8d89fbcc1090f597 | [
"MIT"
] | 1 | 2016-09-20T20:20:00.000Z | 2016-09-20T20:20:00.000Z | host/include/serial_can_dump.hpp | hephaisto/serial-can-dump | a3aa3e6e166327ad86b491ca8d89fbcc1090f597 | [
"MIT"
] | null | null | null | host/include/serial_can_dump.hpp | hephaisto/serial-can-dump | a3aa3e6e166327ad86b491ca8d89fbcc1090f597 | [
"MIT"
] | null | null | null | #include <memory>
#include <string>
#include <boost/signals2.hpp>
#include <boost/asio.hpp>
namespace bs2 = boost::signals2;
class ExtendedCanFrame
{
public:
ExtendedCanFrame(const uint32_t id, const uint8_t data_len, const uint8_t *data, const bool rtr=false);
ExtendedCanFrame(const uint32_t id, const bool rtr=false);
ExtendedCanFrame(const uint32_t id, const uint8_t data, const bool rtr=false);
ExtendedCanFrame(const uint32_t id, const int8_t data, const bool rtr=false);
ExtendedCanFrame(const uint32_t id, const uint16_t data, const bool rtr=false);
ExtendedCanFrame(const uint32_t id, const int16_t data, const bool rtr=false);
~ExtendedCanFrame();
uint32_t id;
uint8_t data_len;
uint8_t *data;
bool rtr;
uint8_t getData_uint8() const;
int8_t getData_int8() const;
uint16_t getData_uint16() const;
int16_t getData_int16() const;
};
typedef bs2::signal<void (std::shared_ptr<const ExtendedCanFrame>)> ReceiveSignal;
class SerialCanDumpPort
{
public:
SerialCanDumpPort(boost::asio::io_service &io, const std::string &device, unsigned int baud_rate);
~SerialCanDumpPort();
ReceiveSignal& onReceive();
void send(const ExtendedCanFrame& frame);
void startWaitingForPacket();
void threadWorker(boost::asio::io_service &io);
private:
static const size_t HEADER_LEN = 5;
static const size_t MAX_DATA_LEN = 16;
static const size_t DATA_LEN_FIELD = 4;
static const uint32_t EXT_MASK = (1 << (5+24) );
static const uint32_t RTR_MASK = (1 << (6+24) );
static const uint32_t ID_MASK = ~( RTR_MASK | EXT_MASK );
ReceiveSignal _onReceive;
boost::asio::serial_port serial;
uint8_t* getDataBuffer();
void handleHeader(const boost::system::error_code& error);
void handleData(const boost::system::error_code& error);
uint8_t serialBuffer[HEADER_LEN + MAX_DATA_LEN];
};
| 30.066667 | 104 | 0.764412 | hephaisto |
0d2f495a880d395a7ea3446c654f4a054c254bf0 | 1,059 | hpp | C++ | gpu/cpu/CpuRaw.hpp | osom8979/example | f3cbe2c345707596edc1ec2763f9318c4676a92f | [
"Zlib"
] | 1 | 2020-02-11T05:37:54.000Z | 2020-02-11T05:37:54.000Z | gpu/cpu/CpuRaw.hpp | osom8979/example | f3cbe2c345707596edc1ec2763f9318c4676a92f | [
"Zlib"
] | null | null | null | gpu/cpu/CpuRaw.hpp | osom8979/example | f3cbe2c345707596edc1ec2763f9318c4676a92f | [
"Zlib"
] | 1 | 2022-03-01T00:47:19.000Z | 2022-03-01T00:47:19.000Z | /**
* @file CpuRaw.hpp
* @brief CpuRaw class prototype.
* @author zer0
* @date 2018-01-10
*/
#ifndef __INCLUDE_LIBTBAG__LIBTBAG_GPU_CPU_CPURAW_HPP__
#define __INCLUDE_LIBTBAG__LIBTBAG_GPU_CPU_CPURAW_HPP__
// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#include <libtbag/config.h>
#include <libtbag/predef.hpp>
#include <string>
// -------------------
NAMESPACE_LIBTBAG_OPEN
// -------------------
namespace gpu {
namespace cpu {
TBAG_API bool runCpuAdd1i(int const * v1, int const * v2, int * r, int count);
TBAG_API bool runCpuAdd1u(unsigned const * v1, unsigned const * v2, unsigned * r, int count);
TBAG_API bool runCpuAdd1f(float const * v1, float const * v2, float * r, int count);
TBAG_API bool runCpuAdd1d(double const * v1, double const * v2, double * r, int count);
} // namespace cpu
} // namespace gpu
// --------------------
NAMESPACE_LIBTBAG_CLOSE
// --------------------
#endif // __INCLUDE_LIBTBAG__LIBTBAG_GPU_CPU_CPURAW_HPP__
| 25.214286 | 93 | 0.661001 | osom8979 |
0d2f8d0b7c16eab8cc09638155ac707c42c53665 | 4,256 | cpp | C++ | Sources/Modules/Renderer/Stub/RendererStub.cpp | benkaraban/anima-games-engine | 8aa7a5368933f1b82c90f24814f1447119346c3b | [
"BSD-3-Clause"
] | 2 | 2015-04-16T01:05:53.000Z | 2019-08-26T07:38:43.000Z | Sources/Modules/Renderer/Stub/RendererStub.cpp | benkaraban/anima-games-engine | 8aa7a5368933f1b82c90f24814f1447119346c3b | [
"BSD-3-Clause"
] | null | null | null | Sources/Modules/Renderer/Stub/RendererStub.cpp | benkaraban/anima-games-engine | 8aa7a5368933f1b82c90f24814f1447119346c3b | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2010, Anima Games, Benjamin Karaban, Laurent Schneider,
* Jérémie Comarmond, Didier Colin.
* 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 copyright holder 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.
*/
#include <Renderer/Stub/RendererStub.h>
#include <Renderer/Stub/RenderViewStub.h>
#include <Renderer/Stub/SceneStub.h>
#include <Renderer/Stub/MeshStub.h>
#include <Renderer/Stub/TextureStub.h>
namespace Renderer
{
//-----------------------------------------------------------------------------
RendererStub::RendererStub() :
_pDefaultView(new RenderViewStub(100, 100)),
_pDefaultTexture(new TextureMapStub(null))
{
}
//-----------------------------------------------------------------------------
bool RendererStub::initialise()
{
return true;
}
//-----------------------------------------------------------------------------
Ptr<IMesh> RendererStub::uploadMesh(const Ptr<Assets::ModelMesh> & pMesh, ITextureGrabber & texGrabber)
{
return Ptr<IMesh>(new MeshStub(pMesh));
}
//-----------------------------------------------------------------------------
Ptr<ISkinMesh> RendererStub::uploadSkinMesh(const Ptr<Assets::ModelMesh> & pMesh, ITextureGrabber & texGrabber)
{
return Ptr<ISkinMesh>(new SkinMeshStub(pMesh));
}
//-----------------------------------------------------------------------------
Ptr<ITextureMap> RendererStub::uploadTexture(const Ptr<Assets::Texture> & pTexture)
{
return Ptr<ITextureMap>(new TextureMapStub(pTexture));
}
//-----------------------------------------------------------------------------
Ptr<ICubeTextureMap> RendererStub::uploadTexture(const Ptr<Assets::CubeTexture> & pTexture)
{
return Ptr<ICubeTextureMap>(null);
}
//-----------------------------------------------------------------------------
Ptr<IScene> RendererStub::createScene()
{
return Ptr<IScene>(new SceneStub());
}
//-----------------------------------------------------------------------------
Ptr<ITextureMap> RendererStub::getDefaultTexture() const
{
return _pDefaultTexture;
}
//-----------------------------------------------------------------------------
void RendererStub::renderScene(const Ptr<IRenderView> & pView, const Ptr<IScene> & pScene, const Ptr<ICamera> & pCamera)
{
}
//-----------------------------------------------------------------------------
Ptr<IRenderView> RendererStub::getDefaultView() const
{
return _pDefaultView;
}
//-----------------------------------------------------------------------------
Ptr<IRenderView> RendererStub::createView(int32 width, int32 height, int32 bufferCount, void * pHandle)
{
return Ptr<IRenderView>(new RenderViewStub(width, height));
}
//-----------------------------------------------------------------------------
}
| 44.8 | 121 | 0.574718 | benkaraban |
0d2ff67406c27f944c704f1a3394a211baa512ca | 18,585 | cpp | C++ | source/fontpage.cpp | tomorrow-wakeup/Font-Creator-For-Unity3D | 6bcb740def77679f8f6f7d9c08e4c6afca6fe2ab | [
"BSD-3-Clause"
] | null | null | null | source/fontpage.cpp | tomorrow-wakeup/Font-Creator-For-Unity3D | 6bcb740def77679f8f6f7d9c08e4c6afca6fe2ab | [
"BSD-3-Clause"
] | null | null | null | source/fontpage.cpp | tomorrow-wakeup/Font-Creator-For-Unity3D | 6bcb740def77679f8f6f7d9c08e4c6afca6fe2ab | [
"BSD-3-Clause"
] | 1 | 2019-09-09T06:44:23.000Z | 2019-09-09T06:44:23.000Z | /*
AngelCode Bitmap Font Generator
Copyright (c) 2004-2014 Andreas Jonsson
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you
must not claim that you wrote the original software. If you use
this software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
Andreas Jonsson
andreas@angelcode.com
*/
#include <algorithm>
#include <fstream>
#include "fontpage.h"
#include "fontchar.h"
#include "fontgen.h"
using namespace std;
#define CLR_BORDER 0x007F00ul
#define CLR_UNUSED 0xFF0000ul
CFontPage::CFontPage(CFontGen *gen, int id, int width, int height, int spacingH, int spacingV)
{
this->gen = gen;
pageId = id;
// Allocate and clear the image with the unused color
pageImg = new (std::nothrow) cImage(width, height);
pageImg->Clear(CLR_UNUSED);
// Initialize the height array that shows free space
heights[0] = new (std::nothrow) int[width];
if( heights[0] )
memset(heights[0], 0, width*4);
heights[1] = 0;
heights[2] = 0;
heights[3] = 0;
currX = 0;
this->spacingH = spacingH;
this->spacingV = spacingV;
paddingRight = 0;
paddingLeft = 0;
paddingUp = 0;
paddingDown = 0;
}
bool CFontPage::IsOK()
{
if( pageImg == 0 || heights[0] == 0 ) return false;
if( pageImg->pixels == 0 ) return false;
return true;
}
CFontPage::~CFontPage()
{
if( pageImg )
delete pageImg;
for( int n = 0; n < 4; n++ )
if( heights[n] )
delete[] heights[n];
}
void CFontPage::SetIntendedFormat(int bitDepth, bool fourChnlPacked, int a, int r, int g, int b)
{
this->bitDepth = bitDepth;
this->fourChnlPacked = fourChnlPacked;
alphaChnl = a;
redChnl = r;
greenChnl = g;
blueChnl = b;
}
void CFontPage::AddChar(int cx, int cy, CFontChar *ch, int channel)
{
// Update the charInfo with the extra draw rect
ch->m_x = cx;
ch->m_y = cy;
ch->m_page = pageId;
ch->m_width += paddingLeft + paddingRight;
ch->m_height += paddingUp + paddingDown;
ch->m_xoffset -= paddingLeft;
ch->m_yoffset -= paddingUp;
if( bitDepth == 32 && fourChnlPacked )
ch->m_chnl = !ch->m_isChar ? 0xF : 1<<channel;
else
ch->m_chnl = 0xF;
// Update heights
cImage *img = ch->m_charImg;
for( int x = -spacingH; x < img->width + paddingLeft + paddingRight + spacingH; x++ )
{
int tempX = x + cx;
if( tempX < 0 ) tempX += pageImg->width;
if( cy + img->height + spacingV + paddingUp + paddingDown > heights[channel][tempX] )
heights[channel][tempX] = cy + img->height + spacingV + paddingUp + paddingDown;
}
chars.push_back(ch);
// Increment counter in CFontGen
gen->counter++;
}
int CFontPage::AddChar(CFontChar *ch, int channel)
{
int origX = currX;
cImage *img = ch->m_charImg;
// Iterate for each possible x position
int i = 0;
while( i++ < pageImg->width - img->width - paddingRight - paddingLeft - spacingH )
{
// Is the character narrow enough to fit?
if( img->width + currX + paddingRight + paddingLeft > pageImg->width - spacingH )
{
// Start from the left side again
currX = 0;
}
// Will the character fit in this place?
int cy = 0;
for( int n = 0; n < img->width + paddingLeft + paddingRight; n++ )
{
if( heights[channel][n+currX] > cy )
cy = heights[channel][n+currX];
}
if( cy + img->height + paddingUp + paddingDown <= pageImg->height - spacingV )
{
// Are we creating any holes?
for( int x = 0; x < img->width + paddingLeft + paddingRight; x++ )
{
int tempX = x + currX;
if( cy - spacingV > heights[channel][tempX] )
{
SHole hole;
hole.x = tempX;
hole.y = heights[channel][tempX];
hole.w = 1;
hole.h = cy - spacingV - hole.y;
hole.chnl = channel;
// Determine the width of the hole
for( x++; x < img->width + paddingLeft + paddingRight; x++ )
{
int tempX = x + currX;
if( hole.y == heights[channel][tempX] )
hole.w++;
else
break;
}
// TODO: Should need to search for more holes.
holes.push_back(hole);
break;
}
}
AddChar(currX, cy, ch, channel);
currX += img->width + spacingH + paddingLeft + paddingRight;
return 0;
}
else
{
currX++;
}
}
currX = origX;
return -1;
}
cImage *CFontPage::GetPageImage()
{
return pageImg;
}
void CFontPage::SetPadding(int left, int up, int right, int down)
{
paddingLeft = left;
paddingUp = up;
paddingRight = right;
paddingDown = down;
}
int CFontPage::GetNextIdealImageWidth()
{
return pageImg->width - currX - paddingRight - paddingLeft - spacingH;
}
void CFontPage::GeneratePreviewTexture(int channel)
{
pageImg->Clear(CLR_UNUSED);
// Copy the font char images to the texture
for( unsigned int n = 0; n < chars.size(); n++ )
{
if( chars[n]->m_chnl & (1<<channel) )
{
int cx = chars[n]->m_x + paddingLeft;
int cy = chars[n]->m_y + paddingUp;
cImage *img = chars[n]->m_charImg;
if( chars[n]->HasOutline() )
{
// Show the outline, by blending against blue background
for( int y = 0; y < img->height; y++ )
{
for( int x = 0; x < img->width; x++ )
{
DWORD p = img->pixels[y*img->width+x];
if( (p >> 24) < 0xFF )
p += 255 - (p>>24);
pageImg->pixels[(y+cy)*pageImg->width+(x+cx)] = p;
}
}
}
else
{
for( int y = 0; y < img->height; y++ )
{
for( int x = 0; x < img->width; x++ )
pageImg->pixels[(y+cy)*pageImg->width+(x+cx)] = img->pixels[y*img->width+x];
}
}
// Draw the spacing borders
if( spacingH > 0 )
{
int cx1 = chars[n]->m_x - 1;
if( cx1 < 0 ) cx1 += pageImg->width;
int cx2 = chars[n]->m_x + chars[n]->m_width;
if( cx2 >= pageImg->width ) cx2 -= pageImg->width;
int cy = chars[n]->m_y;
for( int y = 0; y < chars[n]->m_height; y++ )
{
pageImg->pixels[(cy+y)*pageImg->width+cx1] = CLR_BORDER;
pageImg->pixels[(cy+y)*pageImg->width+cx2] = CLR_BORDER;
}
}
if( spacingV > 0 )
{
int cy1 = chars[n]->m_y - 1;
if( cy1 < 0 ) cy1 += pageImg->height;
int cy2 = chars[n]->m_y + chars[n]->m_height;
if( cy2 >= pageImg->height ) cy2 -= pageImg->height;
int cx = chars[n]->m_x;
for( int x = 0; x < chars[n]->m_width; x++ )
{
pageImg->pixels[cy1*pageImg->width+x+cx] = CLR_BORDER;
pageImg->pixels[cy2*pageImg->width+x+cx] = CLR_BORDER;
}
}
}
}
}
void CFontPage::GenerateOutputTexture()
{
// Clear the image
DWORD color = 0;
if( alphaChnl == e_one && !gen->IsAlphaInverted() || gen->IsAlphaInverted() )
color = 0xFF << 24;
if( fourChnlPacked )
{
// Fill all channels with the same color
color |= (color >> 24) << 16;
color |= (color >> 24) << 8;
color |= (color >> 24);
}
else
{
if( redChnl == e_one && !gen->IsRedInverted() || gen->IsRedInverted() )
color |= 0xFF << 16;
if( greenChnl == e_one && !gen->IsGreenInverted() || gen->IsGreenInverted() )
color |= 0xFF << 8;
if( blueChnl == e_one && !gen->IsBlueInverted() || gen->IsBlueInverted() )
color |= 0xFF;
}
pageImg->Clear(color);
// Copy the font char images to the texture
for( unsigned int n = 0; n < chars.size(); n++ )
{
int cx = chars[n]->m_x + paddingLeft;
int cy = chars[n]->m_y + paddingUp;
cImage *img = chars[n]->m_charImg;
if( !chars[n]->m_isChar )
{
// Colored images are copied as is
for( int y = 0; y < img->height; y++ )
{
for( int x = 0; x < img->width; x++ )
pageImg->pixels[(y+cy)*pageImg->width+(x+cx)] = img->pixels[y*img->width+x];
}
}
else
{
if( bitDepth == 32 && fourChnlPacked )
{
// When packing multiple characters we
// use the alpha channel to determine the content
for( int y = 0; y < img->height; y++ )
{
for( int x = 0; x < img->width; x++ )
{
DWORD p = chars[n]->GetPixelValue(x, y, alphaChnl);
if( gen->IsAlphaInverted() ) p = 255 - p;
DWORD c = pageImg->pixels[(y+cy)*pageImg->width+(x+cx)];
if( chars[n]->m_chnl == 1 )
{
c &= 0xFFFFFF00;
c |= p;
}
else if( chars[n]->m_chnl == 2 )
{
c &= 0xFFFF00FF;
c |= p << 8;
}
else if( chars[n]->m_chnl == 4 )
{
c &= 0xFF00FFFF;
c |= p << 16;
}
else if( chars[n]->m_chnl == 8 )
{
c &= 0x00FFFFFF;
c |= p << 24;
}
pageImg->pixels[(y+cy)*pageImg->width+(x+cx)] = c;
}
}
}
else
{
for( int y = 0; y < img->height; y++ )
{
for( int x = 0; x < img->width; x++ )
{
DWORD p = 0;
DWORD t;
t = (BYTE)chars[n]->GetPixelValue(x, y, blueChnl); if( gen->IsBlueInverted() ) t = 255 - t; p |= t << 0;
t = (BYTE)chars[n]->GetPixelValue(x, y, greenChnl); if( gen->IsGreenInverted() ) t = 255 - t; p |= t << 8;
t = (BYTE)chars[n]->GetPixelValue(x, y, redChnl); if( gen->IsRedInverted() ) t = 255 - t; p |= t << 16;
t = (BYTE)chars[n]->GetPixelValue(x, y, alphaChnl); if( gen->IsAlphaInverted() ) t = 255 - t; p |= t << 24;
pageImg->pixels[(y+cy)*pageImg->width+(x+cx)] = p;
}
}
}
}
}
}
// This global pointer will be used by the sorting algorithm
CFontChar **g_chars = 0;
// Define a structure and comparison operator for the sorting algorithm
struct element { int index; };
bool operator<(const element &a, const element &b)
{
// We want to sort the characters from larger to smaller
if( g_chars[a.index]->m_height > g_chars[b.index]->m_height ||
(g_chars[a.index]->m_height == g_chars[b.index]->m_height &&
g_chars[a.index]->m_width > g_chars[b.index]->m_width) )
return true;
return false;
}
void CFontPage::SortList(CFontChar **chars, int *index, int numChars)
{
g_chars = chars;
std::sort((element*)index, (element*)(&index[numChars]));
}
#ifdef TRACE_GENERATE
extern ofstream trace;
#endif
void CFontPage::AddChars(CFontChar **chars, int maxChars)
{
#ifdef TRACE_GENERATE
trace << "Adding colored images\n";
trace.flush();
#endif
// Add the colored images first
AddCharsToPage(chars, maxChars, true, 0);
// Check if we should stop
if( gen->stopWorking ) return;
#ifdef TRACE_GENERATE
trace << "Duplicating the height array to all channels\n";
trace.flush();
#endif
// Duplicate the height array for the other channels
for( int n = 1; n < 4; n++ )
{
heights[n] = new (std::nothrow) int[pageImg->width];
if( heights[n] == 0 )
{
#ifdef TRACE_GENERATE
trace << "Out of memory while allocating height buffer\n";
trace.flush();
#endif
gen->stopWorking = true;
gen->outOfMemory = true;
return;
}
memcpy(heights[n], heights[0], pageImg->width*sizeof(int));
}
// Remove the current holes
holes.resize(0);
#ifdef TRACE_GENERATE
trace << "Adding monochrome images to channel 0\n";
trace.flush();
#endif
// Then the black & white images
AddCharsToPage(chars, maxChars, false, 0);
// Check if we should stop
if( gen->stopWorking ) return;
if( bitDepth == 32 && fourChnlPacked )
{
for( int n = 1; n < 4; n++ )
{
#ifdef TRACE_GENERATE
trace << "Adding monochrome images to channel " << n << "\n";
trace.flush();
#endif
AddCharsToPage(chars, maxChars, false, n);
// Check if we should stop
if( gen->stopWorking ) return;
}
}
}
void CFontPage::AddCharsToPage(CFontChar **chars, int maxChars, bool colored, int channel)
{
static int indexA[maxUnicodeChar+1], indexB[maxUnicodeChar+1];
int *index = indexA, *index2 = indexB;
int numChars = 0, numChars2 = 0;
// Add images to the list
for( int n = 0; n < maxChars; n++ )
{
if( chars[n] && chars[n]->m_isChar != colored )
index[numChars++] = n;
}
#ifdef TRACE_GENERATE
trace << "Sorting list of " << numChars << " candidates\n";
trace.flush();
#endif
// Sort the characters by height/width, largest first
SortList(chars, index, numChars);
// Add the images to the page
while( numChars > 0 )
{
#ifdef TRACE_GENERATE
trace << "There are " << numChars << " candidates left, and " << holes.size() << " holes to fill\n";
trace.flush();
#endif
// Fill holes
for( int h = 0; h < (signed)holes.size(); h++ )
{
int bestMatch;
bestMatch = -1;
// Find the best matching character to fill the hole
for( int n = 0; n < numChars; n++ )
{
if( (holes[h].w == chars[index[n]]->m_charImg->width + paddingLeft + paddingRight) &&
(holes[h].h == chars[index[n]]->m_charImg->height + paddingUp + paddingDown) )
{
bestMatch = n;
break;
}
else if( (holes[h].w >= chars[index[n]]->m_charImg->width + paddingLeft + paddingRight) &&
(holes[h].h >= chars[index[n]]->m_charImg->height + paddingUp + paddingDown) )
{
if( bestMatch != -1 )
{
if( (chars[index[n]]->m_charImg->width > chars[index[bestMatch]]->m_charImg->width) ||
(chars[index[n]]->m_charImg->height > chars[index[bestMatch]]->m_charImg->height) )
bestMatch = n;
}
else
bestMatch = n;
}
}
if( bestMatch != -1 )
{
int x = holes[h].x;
int y = holes[h].y;
// There may still be room for more
if( holes[h].w - spacingH > chars[index[bestMatch]]->m_charImg->width + paddingLeft + paddingRight )
{
// Create a new hole to the right of the newly inserted character, with the same height of the previous hole
SHole hole2;
hole2.x = holes[h].x + (chars[index[bestMatch]]->m_charImg->width + paddingLeft + paddingRight + spacingH);
hole2.y = holes[h].y;
hole2.w = holes[h].w - (chars[index[bestMatch]]->m_charImg->width + paddingLeft + paddingRight + spacingH);
hole2.h = holes[h].h;
hole2.chnl = holes[h].chnl;
holes.push_back(hole2);
}
if( holes[h].h - spacingV > chars[index[bestMatch]]->m_charImg->height + paddingUp + paddingDown )
{
// Create a new hole below the newly inserted character, with the width of the character
SHole hole2;
hole2.x = holes[h].x;
hole2.y = holes[h].y + (chars[index[bestMatch]]->m_charImg->height + paddingUp + paddingDown + spacingV);
hole2.w = (chars[index[bestMatch]]->m_charImg->width + paddingLeft + paddingRight);
hole2.h = holes[h].h - (chars[index[bestMatch]]->m_charImg->height + paddingUp + paddingDown + spacingV);
hole2.chnl = holes[h].chnl;
holes.push_back(hole2);
}
AddChar(x, y, chars[index[bestMatch]], channel);
chars[index[bestMatch]] = 0;
#ifdef TRACE_GENERATE
trace << "Character [" << index[bestMatch] << "] was used to fill hole\n";
trace.flush();
#endif
// Check if we should stop
if( gen->stopWorking ) return;
// Compact the list
numChars--;
for( int n = bestMatch; n < numChars; n++ )
index[n] = index[n+1];
}
// Remove the hole
if( h < (signed)holes.size() - 1 )
holes[h] = holes[holes.size()-1];
holes.pop_back();
h--;
}
#ifdef TRACE_GENERATE
trace << "All holes have been filled\n";
trace.flush();
#endif
numChars2 = 0;
bool allTooWide = true;
bool drawn = false;
// Determine if there is a large height difference anywhere, and if so start filling from that location
// This happens for example when importing images that are out of proportion to the rest of the glyphs
currX = DetermineStartX(chars, index, numChars, channel);
#ifdef TRACE_GENERATE
trace << "currX is " << currX << " and heights is " << heights[channel][currX] << "\n";
trace << "tallest char is " << chars[index[0]]->m_height << "x" << chars[index[0]]->m_width << " and shortest char is " << chars[index[numChars-1]]->m_height << "x" << chars[index[numChars-1]]->m_width << "\n";
trace << "GetNextIdealImageWidth() = " << GetNextIdealImageWidth() << "\n";
trace.flush();
#endif
// Sanity check. This could become negative if previous code failed to catch out of memory
if( GetNextIdealImageWidth() < 0 )
{
#ifdef TRACE_GENERATE
trace << "GetNextIdealImageWidth() < 0. Something is wrong\n";
trace.flush();
#endif
gen->stopWorking = true;
gen->outOfMemory = true;
return;
}
// Add one row of chars to texture
for( int n = 0; n < numChars; n++ )
{
bool ok = false;
if( chars[index[n]]->m_charImg->width <= GetNextIdealImageWidth() )
{
allTooWide = false;
int r = AddChar(chars[index[n]], channel);
if( r >= 0 )
{
#ifdef TRACE_GENERATE
trace << "Character [" << index[n] << "] was added\n";
trace.flush();
#endif
chars[index[n]] = 0;
ok = true;
drawn = true;
// Check if we should stop
if( gen->stopWorking ) return;
}
}
if( !ok )
{
#ifdef TRACE_GENERATE
// trace << "Character [" << index[n] << "] didn't fit on this row\n";
// trace.flush();
#endif
// Move it to the next index list
index2[numChars2++] = index[n];
}
}
if( index == indexA )
{
// Swap indices
index = indexB;
index2 = indexA;
}
else
{
index = indexA;
index2 = indexB;
}
numChars = numChars2;
numChars2 = 0;
#ifdef TRACE_GENERATE
trace << "allTooWide = " << allTooWide << ", drawn = " << drawn << "\n";
trace.flush();
#endif
if( !allTooWide && !drawn )
{
// Next page
break;
}
}
}
int CFontPage::DetermineStartX(CFontChar **chars, int *index, int numChars, int channel)
{
int startX = 0;
// Determine if there is a large height difference anywhere, and if so start filling from that location
// This happens for example when importing images that are out of proportion to the rest of the glyphs
int thinnestChar = pageImg->width;
for( int n = 0; n < numChars; n++ )
if( thinnestChar > (chars[index[n]]->m_width + paddingLeft + paddingRight + spacingH) )
thinnestChar = chars[index[n]]->m_width + paddingLeft + paddingRight + spacingH;
for( int n = 0; n < pageImg->width - 1 - thinnestChar; n++ )
{
// Compare against the largest glyph that we'll add (first in list)
if( heights[channel][n] - heights[channel][n+1] >= (chars[index[0]]->m_height + paddingUp + paddingDown + spacingV) )
{
startX = n+1;
break;
}
}
return startX;
} | 26.324363 | 212 | 0.612429 | tomorrow-wakeup |
0d319dd56d678092a074bd1a97fcbcfca5af379c | 1,710 | cpp | C++ | hermes/common/cuda_utils.cpp | filipecn/hermes | c0411cec4d5b216b0f5f7e095805101af2aa6fc0 | [
"MIT"
] | null | null | null | hermes/common/cuda_utils.cpp | filipecn/hermes | c0411cec4d5b216b0f5f7e095805101af2aa6fc0 | [
"MIT"
] | null | null | null | hermes/common/cuda_utils.cpp | filipecn/hermes | c0411cec4d5b216b0f5f7e095805101af2aa6fc0 | [
"MIT"
] | null | null | null | /// Copyright (c) 2021, FilipeCN.
///
/// The MIT License (MIT)
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to
/// deal in the Software without restriction, including without limitation the
/// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
/// sell copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
/// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
/// IN THE SOFTWARE.
///
///\file cuda_utils.cpp
///\author FilipeCN (filipedecn@gmail.com)
///\date 2021-08-07
///
///\brief
#include <hermes/common/cuda_utils.h>
namespace hermes::cuda_utils {
#ifdef HERMES_DEVICE_ENABLED
Lock::Lock() {
int state = 0;
cudaMalloc((void **) &mutex, sizeof(int));
cudaMemcpy(mutex, &state, sizeof(int), cudaMemcpyHostToDevice);
}
Lock::~Lock() {
cudaFree(mutex);
}
HERMES_DEVICE_FUNCTION void Lock::lock() {
while (atomicCAS(mutex, 0, 1) != 0);
}
HERMES_DEVICE_FUNCTION void Lock::unlock() {
atomicExch(mutex, 0);
}
#endif
} | 31.666667 | 80 | 0.725731 | filipecn |
0d339d3773f7bf9f3892264b1742b35a09dd50e6 | 7,130 | cxx | C++ | examples/Registration/RegistrationFrameworkBenchmark.cxx | mseng10/ITKPerformanceBenchmarking | 95698a3c9eb03b5e4ea74079bc0f68b2e7ccfdf6 | [
"Apache-2.0"
] | 1 | 2017-12-07T21:29:59.000Z | 2017-12-07T21:29:59.000Z | examples/Registration/RegistrationFrameworkBenchmark.cxx | mseng10/ITKPerformanceBenchmarking | 95698a3c9eb03b5e4ea74079bc0f68b2e7ccfdf6 | [
"Apache-2.0"
] | 33 | 2017-06-30T19:35:06.000Z | 2021-09-22T00:07:26.000Z | examples/Registration/RegistrationFrameworkBenchmark.cxx | mseng10/ITKPerformanceBenchmarking | 95698a3c9eb03b5e4ea74079bc0f68b2e7ccfdf6 | [
"Apache-2.0"
] | 6 | 2017-06-30T18:22:47.000Z | 2020-02-19T23:10:16.000Z | /*=========================================================================
*
* Copyright NumFOCUS
*
* 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 "itkImageFileReader.h"
#include "itkTransformFileWriter.h"
#include "itkImageRegistrationMethodv4.h"
#include "itkMeanSquaresImageToImageMetricv4.h"
#include "itkRegularStepGradientDescentOptimizerv4.h"
#include "itkHighPriorityRealTimeProbesCollector.h"
#include "PerformanceBenchmarkingUtilities.h"
class CommandIterationUpdate : public itk::Command
{
public:
using Self = CommandIterationUpdate;
using Superclass = itk::Command;
using Pointer = itk::SmartPointer<Self>;
itkNewMacro(Self);
protected:
CommandIterationUpdate() = default;
public:
using OptimizerType = itk::RegularStepGradientDescentOptimizerv4<double>;
using OptimizerPointer = const OptimizerType *;
void
Execute(itk::Object * caller, const itk::EventObject & event) override
{
Execute((const itk::Object *)caller, event);
}
void
Execute(const itk::Object * object, const itk::EventObject & event) override
{
auto optimizer = static_cast<OptimizerPointer>(object);
if (!itk::IterationEvent().CheckEvent(&event))
{
return;
}
std::cout << optimizer->GetCurrentIteration() << " = ";
std::cout << optimizer->GetValue() << " : ";
std::cout << optimizer->GetCurrentPosition() << std::endl;
}
};
int
main(int argc, char * argv[])
{
if (argc < 7)
{
std::cerr << "Usage: " << std::endl;
std::cerr << argv[0] << " timingsFile iterations threads fixedImageFile movingImageFile outputTransformFileName"
<< std::endl;
return EXIT_FAILURE;
}
const std::string timingsFileName = ReplaceOccurrence(argv[1], "__DATESTAMP__", PerfDateStamp());
const int iterations = std::stoi(argv[2]);
int threads = std::stoi(argv[3]);
const char * fixedImageFileName = argv[4];
const char * movingImageFileName = argv[5];
const char * outputTransformFileName = argv[6];
if (threads > 0)
{
MultiThreaderName::SetGlobalDefaultNumberOfThreads(threads);
}
constexpr unsigned int Dimension = 3;
using PixelType = float;
using ParametersValueType = double;
using ImageType = itk::Image<PixelType, 3>;
using ReaderType = itk::ImageFileReader<ImageType>;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(fixedImageFileName);
try
{
reader->UpdateLargestPossibleRegion();
}
catch (itk::ExceptionObject & error)
{
std::cerr << "Error: " << error << std::endl;
return EXIT_FAILURE;
}
ImageType::Pointer fixedImage = reader->GetOutput();
fixedImage->DisconnectPipeline();
reader->SetFileName(movingImageFileName);
try
{
reader->UpdateLargestPossibleRegion();
}
catch (itk::ExceptionObject & error)
{
std::cerr << "Error: " << error << std::endl;
return EXIT_FAILURE;
}
ImageType::Pointer movingImage = reader->GetOutput();
movingImage->DisconnectPipeline();
using OptimizerType = itk::RegularStepGradientDescentOptimizerv4<ParametersValueType>;
OptimizerType::Pointer optimizer = OptimizerType::New();
optimizer->SetLearningRate(4.0);
optimizer->SetMinimumStepLength(0.001);
optimizer->SetRelaxationFactor(0.5);
optimizer->SetNumberOfIterations(200);
// CommandIterationUpdate::Pointer observer = CommandIterationUpdate::New();
// optimizer->AddObserver( itk::IterationEvent(), observer );
using MetricType = itk::MeanSquaresImageToImageMetricv4<ImageType, ImageType>;
MetricType::Pointer metric = MetricType::New();
using TransformType = itk::TranslationTransform<ParametersValueType, Dimension>;
using RegistrationType = itk::ImageRegistrationMethodv4<ImageType, ImageType, TransformType>;
RegistrationType::Pointer registration = RegistrationType::New();
registration->SetMetric(metric);
registration->SetOptimizer(optimizer);
TransformType::Pointer movingInitialTransform = TransformType::New();
TransformType::ParametersType initialParameters(movingInitialTransform->GetNumberOfParameters());
initialParameters.Fill(0.0);
movingInitialTransform->SetParameters(initialParameters);
registration->SetMovingInitialTransform(movingInitialTransform);
TransformType::Pointer identityTransform = TransformType::New();
identityTransform->SetIdentity();
registration->SetFixedInitialTransform(identityTransform);
TransformType::Pointer optimizedTransform = TransformType::New();
optimizedTransform->SetParameters(initialParameters);
registration->SetInitialTransform(optimizedTransform);
constexpr unsigned int numberOfLevels = 1;
RegistrationType::ShrinkFactorsArrayType shrinkFactorsPerLevel;
shrinkFactorsPerLevel.SetSize(1);
shrinkFactorsPerLevel[0] = 1;
RegistrationType::SmoothingSigmasArrayType smoothingSigmasPerLevel;
smoothingSigmasPerLevel.SetSize(1);
smoothingSigmasPerLevel[0] = 0;
registration->SetNumberOfLevels(numberOfLevels);
registration->SetSmoothingSigmasPerLevel(smoothingSigmasPerLevel);
registration->SetShrinkFactorsPerLevel(shrinkFactorsPerLevel);
RegistrationType::MetricSamplingStrategyEnum samplingStrategy = RegistrationType::MetricSamplingStrategyEnum::RANDOM;
registration->SetMetricSamplingStrategy(samplingStrategy);
registration->SetMetricSamplingPercentage(0.03);
registration->SetFixedImage(fixedImage);
registration->SetMovingImage(movingImage);
using ScalesEstimatorType = itk::RegistrationParameterScalesFromPhysicalShift<MetricType>;
ScalesEstimatorType::Pointer scalesEstimator = ScalesEstimatorType::New();
scalesEstimator->SetMetric(metric);
scalesEstimator->SetTransformForward(true);
optimizer->SetScalesEstimator(scalesEstimator);
optimizer->SetDoEstimateLearningRateOnce(true);
itk::HighPriorityRealTimeProbesCollector collector;
for (int ii = 0; ii < iterations; ++ii)
{
collector.Start("RegistrationFramework");
optimizedTransform->SetParameters(initialParameters);
registration->SetInitialTransform(optimizedTransform);
registration->Update();
collector.Stop("RegistrationFramework");
}
WriteExpandedReport(timingsFileName, collector, true, true, false);
TransformType::ConstPointer transform = registration->GetTransform();
using WriterType = itk::TransformFileWriterTemplate<ParametersValueType>;
WriterType::Pointer writer = WriterType::New();
writer->SetFileName(outputTransformFileName);
writer->SetInput(transform);
writer->Update();
return EXIT_SUCCESS;
}
| 34.61165 | 119 | 0.736466 | mseng10 |
0d3a74e11d00f485465ebcb165fa432dc5095dc5 | 306 | hpp | C++ | vm/os-solaris-x86.64.hpp | seckar/factor | 9683b081e3d93a996d00c91a139b533139dfb945 | [
"BSD-2-Clause"
] | 1 | 2016-05-08T19:43:03.000Z | 2016-05-08T19:43:03.000Z | vm/os-solaris-x86.64.hpp | seckar/factor | 9683b081e3d93a996d00c91a139b533139dfb945 | [
"BSD-2-Clause"
] | null | null | null | vm/os-solaris-x86.64.hpp | seckar/factor | 9683b081e3d93a996d00c91a139b533139dfb945 | [
"BSD-2-Clause"
] | null | null | null | #include <ucontext.h>
namespace factor
{
inline static void *ucontext_stack_pointer(void *uap)
{
ucontext_t *ucontext = (ucontext_t *)uap;
return (void *)ucontext->uc_mcontext.gregs[RSP];
}
#define UAP_PROGRAM_COUNTER(ucontext) \
(((ucontext_t *)(ucontext))->uc_mcontext.gregs[RIP])
}
| 19.125 | 56 | 0.699346 | seckar |
0d3bba656186d2d469e71c41c3b328baff71fbfa | 5,468 | cpp | C++ | src/devices/bus/spectrum/intf1.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 26 | 2015-03-31T06:25:51.000Z | 2021-12-14T09:29:04.000Z | src/devices/bus/spectrum/intf1.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | null | null | null | src/devices/bus/spectrum/intf1.cpp | Robbbert/messui | 49b756e2140d8831bc81335298ee8c5471045e79 | [
"BSD-3-Clause"
] | 10 | 2015-03-27T05:45:51.000Z | 2022-02-04T06:57:36.000Z | // license:BSD-3-Clause
// copyright-holders:Nigel Barnes
/**********************************************************************
ZX Interface 1
The ZX Interface 1 combines the three functions of microdrive
controller, local area network and RS232 interface.
**********************************************************************/
#include "emu.h"
#include "intf1.h"
//**************************************************************************
// DEVICE DEFINITIONS
//**************************************************************************
DEFINE_DEVICE_TYPE(SPECTRUM_INTF1, spectrum_intf1_device, "spectrum_intf1", "ZX Interface 1")
//-------------------------------------------------
// MACHINE_DRIVER( intf1 )
//-------------------------------------------------
ROM_START( intf1 )
ROM_REGION( 0x2000, "rom", 0 )
ROM_DEFAULT_BIOS("v2")
ROM_SYSTEM_BIOS(0, "v1", "v1")
ROMX_LOAD("if1-1.rom", 0x0000, 0x2000, CRC(e72a12ae) SHA1(4ffd9ed9c00cdc6f92ce69fdd8b618ef1203f48e), ROM_BIOS(0))
ROM_SYSTEM_BIOS(1, "v2", "v2")
ROMX_LOAD("if1-2.rom", 0x0000, 0x2000, CRC(bb66dd1e) SHA1(5cfb6bca4177c45fefd571734576b55e3a127c08), ROM_BIOS(1))
ROM_END
//-------------------------------------------------
// device_add_mconfig - add device configuration
//-------------------------------------------------
void spectrum_intf1_device::device_add_mconfig(machine_config &config)
{
/* rs232 */
RS232_PORT(config, m_rs232, default_rs232_devices, nullptr);
/* microdrive */
MICRODRIVE(config, m_mdv1);
m_mdv1->comms_out_wr_callback().set(m_mdv2, FUNC(microdrive_image_device::comms_in_w));
MICRODRIVE(config, m_mdv2);
/* passthru */
SPECTRUM_EXPANSION_SLOT(config, m_exp, spectrum_expansion_devices, nullptr);
m_exp->irq_handler().set(DEVICE_SELF_OWNER, FUNC(spectrum_expansion_slot_device::irq_w));
m_exp->nmi_handler().set(DEVICE_SELF_OWNER, FUNC(spectrum_expansion_slot_device::nmi_w));
SOFTWARE_LIST(config, "microdrive_list").set_original("spectrum_microdrive");
}
const tiny_rom_entry *spectrum_intf1_device::device_rom_region() const
{
return ROM_NAME( intf1 );
}
//**************************************************************************
// LIVE DEVICE
//**************************************************************************
//-------------------------------------------------
// spectrum_intf1_device - constructor
//-------------------------------------------------
spectrum_intf1_device::spectrum_intf1_device(const machine_config &mconfig, const char *tag, device_t *owner, uint32_t clock)
: device_t(mconfig, SPECTRUM_INTF1, tag, owner, clock)
, device_spectrum_expansion_interface(mconfig, *this)
, m_exp(*this, "exp")
, m_rs232(*this, "rs232")
, m_mdv1(*this, "mdv1")
, m_mdv2(*this, "mdv2")
, m_rom(*this, "rom")
{
}
//-------------------------------------------------
// device_start - device-specific startup
//-------------------------------------------------
void spectrum_intf1_device::device_start()
{
save_item(NAME(m_romcs));
}
//-------------------------------------------------
// device_reset - device-specific reset
//-------------------------------------------------
void spectrum_intf1_device::device_reset()
{
m_romcs = 0;
}
//**************************************************************************
// IMPLEMENTATION
//**************************************************************************
READ_LINE_MEMBER(spectrum_intf1_device::romcs)
{
return m_romcs | m_exp->romcs();
}
// the Interface 1 looks for specific bus conditions to enable / disable the expansion overlay ROM
// the enable must occur BEFORE the opcode is fetched, as the opcode must be fetched from the expansion ROM
void spectrum_intf1_device::pre_opcode_fetch(offs_t offset)
{
m_exp->pre_opcode_fetch(offset);
if (!machine().side_effects_disabled())
{
switch (offset)
{
case 0x0008: case 0x1708:
m_romcs = 1;
break;
}
}
}
// the disable must occur AFTER the opcode fetch, or the incorrect opcode is fetched for 0x0700
void spectrum_intf1_device::post_opcode_fetch(offs_t offset)
{
m_exp->post_opcode_fetch(offset);
if (!machine().side_effects_disabled())
{
switch (offset)
{
case 0x0700:
m_romcs = 0;
break;
}
}
}
uint8_t spectrum_intf1_device::mreq_r(offs_t offset)
{
uint8_t data = 0xff;
if (m_romcs)
data &= m_rom->base()[offset & 0x1fff];
if (m_exp->romcs())
data &= m_exp->mreq_r(offset);
return data;
}
uint8_t spectrum_intf1_device::iorq_r(offs_t offset)
{
uint8_t data = 0xff;
if ((offset & 0x18) != 0x18)
{
switch (offset & 0x18)
{
case 0x00:
logerror("%s: iorq_r (microdrive) %04x\n", machine().describe_context(), offset);
break;
case 0x08:
logerror("%s: iorq_r (control) %04x\n", machine().describe_context(), offset);
break;
case 0x10:
logerror("%s: iorq_r (network) %04x\n", machine().describe_context(), offset);
break;
}
}
data &= m_exp->iorq_r(offset);
return data;
}
void spectrum_intf1_device::iorq_w(offs_t offset, uint8_t data)
{
if ((offset & 0x18) != 0x18)
{
switch (offset & 0x18)
{
case 0x00:
logerror("%s: iorq_w (microdrive) %04x: %02x\n", machine().describe_context(), offset, data);
break;
case 0x08:
logerror("%s: iorq_w (control) %04x: %02x\n", machine().describe_context(), offset, data);
break;
case 0x10:
logerror("%s: iorq_w (network) %04x: %02x\n", machine().describe_context(), offset, data);
break;
}
}
m_exp->iorq_w(offset, data);
}
| 26.935961 | 125 | 0.571507 | Robbbert |
0d3c0e729231216556dd90d9abf9febc31be5e36 | 1,409 | cpp | C++ | plugins/ChannelMute/Source/PluginEditor.cpp | COx2/slPlugins | 72f6e8e70b23e97d44d27001df02433585c7fb81 | [
"BSD-3-Clause"
] | 39 | 2020-04-24T10:36:31.000Z | 2022-02-15T17:09:03.000Z | plugins/ChannelMute/Source/PluginEditor.cpp | COx2/slPlugins | 72f6e8e70b23e97d44d27001df02433585c7fb81 | [
"BSD-3-Clause"
] | 3 | 2020-04-28T00:24:43.000Z | 2020-11-09T21:43:34.000Z | plugins/ChannelMute/Source/PluginEditor.cpp | COx2/slPlugins | 72f6e8e70b23e97d44d27001df02433585c7fb81 | [
"BSD-3-Clause"
] | 5 | 2020-06-15T08:42:12.000Z | 2021-06-10T06:49:57.000Z | /*
==============================================================================
This file was auto-generated by the Introjucer!
It contains the basic framework code for a JUCE plugin editor.
==============================================================================
*/
#include "PluginProcessor.h"
#include "PluginEditor.h"
using namespace gin;
//==============================================================================
ChannelMuteAudioProcessorEditor::ChannelMuteAudioProcessorEditor (ChannelMuteAudioProcessor& p)
: gin::ProcessorEditor (p), cmProcessor (p)
{
for (auto pp : p.getPluginParameters())
{
ParamComponent* pc;
if (pp->isOnOff())
pc = new Switch (pp);
else
pc = new Knob (pp);
addAndMakeVisible (pc);
controls.add (pc);
}
setGridSize (4, 1);
}
ChannelMuteAudioProcessorEditor::~ChannelMuteAudioProcessorEditor()
{
}
//==============================================================================
void ChannelMuteAudioProcessorEditor::resized()
{
gin::ProcessorEditor::resized();
componentForId (PARAM_MUTE_L)->setBounds (getGridArea (0, 0));
componentForId (PARAM_LEVEL_L)->setBounds (getGridArea (1, 0));
componentForId (PARAM_MUTE_R)->setBounds (getGridArea (2, 0));
componentForId (PARAM_LEVEL_R)->setBounds (getGridArea (3, 0));
}
| 28.18 | 95 | 0.51171 | COx2 |
0d40e47199a89b577d1743a70e3572f4f2b20088 | 1,723 | cpp | C++ | array/pair-with-sum-in-unsorted-array.cpp | HarshitKaushik/ds-algorithms-revision | 98fddca7b196179dd795dfde822a1d9bb1518b74 | [
"MIT"
] | 1 | 2018-08-28T17:44:45.000Z | 2018-08-28T17:44:45.000Z | array/pair-with-sum-in-unsorted-array.cpp | HarshitKaushik/ds-algorithms-revision | 98fddca7b196179dd795dfde822a1d9bb1518b74 | [
"MIT"
] | null | null | null | array/pair-with-sum-in-unsorted-array.cpp | HarshitKaushik/ds-algorithms-revision | 98fddca7b196179dd795dfde822a1d9bb1518b74 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
// Given an array A[] and a number x, check for pair in A[] with sum as x
// https://www.geeksforgeeks.org/write-a-c-program-that-given-a-set-a-of-n-numbers-and-another-number-x-determines-whether-or-not-there-exist-two-elements-in-s-whose-sum-is-exactly-x/
// Method to swap the integer values
void swapValues(int *i, int *j)
{
int temp = *i;
*i = *j;
*j = temp;
}
// Partition method to place last element in its right place in the array. All smaller and equal elements before it
// and all greater elements after it
int partition(int array[], int low, int high)
{
int pivot = array[high];
int i = low - 1;
for (int j = low; j < high; j++)
{
if (array[j] <= pivot)
{
i++;
swapValues(&array[i], &array[j]);
}
}
// Place pivot in its right place
swapValues(&array[i + 1], &array[high]);
return (i + 1);
}
// Recursive quick sort algorithm
void quickSort(int array[], int low, int high)
{
// low is lower index and high is upper index
// taking the last element as pivot
if (low < high)
{
int partitioningIndex = partition(array, low, high);
quickSort(array, low, partitioningIndex - 1);
quickSort(array, partitioningIndex + 1, high);
}
}
int main()
{
int arraySize = 10;
int testArray[] = { 8, 9 , 7, 4, 7, 2, 4, 1, 6, 9 };
int sumOfPair = 18;
quickSort(testArray, 0, arraySize - 1);
int i = 0;
int j = arraySize - 1;
while(i < j) {
if (testArray[i] + testArray[j] == sumOfPair) {
cout << testArray[i] << " " << testArray[j] << endl;
break;
} else if (testArray[i] + testArray[j] < sumOfPair) {
i++;
} else {
j++;
}
}
// Output
// 9 9
return 0;
}
| 24.971014 | 183 | 0.611143 | HarshitKaushik |
0d424cd08a4656c2bc957dabc6c46163c364a778 | 4,506 | cpp | C++ | source/App/EnmConsole.cpp | Borrk/Enzyme-labeled-instrument | a7c8f4459511c774f7e0c4fee1fe05baf1ae2a5f | [
"MIT"
] | null | null | null | source/App/EnmConsole.cpp | Borrk/Enzyme-labeled-instrument | a7c8f4459511c774f7e0c4fee1fe05baf1ae2a5f | [
"MIT"
] | null | null | null | source/App/EnmConsole.cpp | Borrk/Enzyme-labeled-instrument | a7c8f4459511c774f7e0c4fee1fe05baf1ae2a5f | [
"MIT"
] | null | null | null | #include "EnmConsole.h"
CEnmConsole::CEnmConsole()
{
Init();
}
CEnmConsole::~CEnmConsole()
{
}
#include "Mig_Page.hpp"
enConsoleCommand CEnmConsole::SetConsoleCmdLine( INT8U* pCmdLine, INT16U size )
{
INT8S aFrame[32];
mCurCmd = ENM_CONSOLE_NONE;
mParser.Push( (INT8U*)pCmdLine, size );
INT16U aLen = mParser.FindeFrame( (INT8U*)aFrame );
if ( aLen <= 0 )
return mCurCmd;
/// parse command
MCHAR ch1, ch = aFrame[0];
switch ( ch )
{
case 'R':
mCurCmd = (aLen == 1) ? ENM_CONSOLE_ENTER : ENM_CONSOLE_NONE;
break;
case 'Q':
mCurCmd = (aLen == 1) ? ENM_CONSOLE_QUIT : ENM_CONSOLE_NONE;
break;
case 'P':
ch = aFrame[1];
if ( aLen == 1 )
{
mScanOption.scanCount = 1;
mCurCmd = ENM_CONSOLE_SCAN;
}
else if (aLen == 2 && ch == 'M' )
{
mScanOption.scanCount = 1;
/// do nothing, now ignore PM command
}
else
{
if ( '0' <= ch && ch <= '9' )
{
ch1 = aFrame[2];
if ( aLen == 2 )
{
mScanOption.scanCount = ch - '0';
mCurCmd = ENM_CONSOLE_SCAN;
}
else if ( aLen == 3 && ('0' <= ch1 && ch1 <= '9') )
{
mScanOption.scanCount = (ch - '0') * 10 + (ch1 - '0');
mCurCmd = ENM_CONSOLE_SCAN;
}
}
}
break;
case 'M':
ch = aFrame[1];
ch1 = aFrame[2];
if ( aLen == 2 && ('1' <= ch && ch <= '9') )
{
mScanOption.startColumn = ch - '0' - 1;
mCurCmd = ENM_CONSOLE_SCAN;
}
else if ( aLen == 3 && ('0' <= ch1 && ch1 <= '9') )
{
mScanOption.startColumn = (ch - '0') * 10 + (ch1 - '0') - 1;
if ( mScanOption.startColumn < 12 )
{
mCurCmd = ENM_CONSOLE_SCAN;
}
else
{
mScanOption.startColumn = 0;
mCurCmd = ENM_CONSOLE_NONE;
}
}
break;
case 'F':
/// now ignore FMn command
if ( '1' <= aFrame[1] && aFrame[1] <= '8' )
{
mScanOption.wave = aFrame[1] - '0' - 1;
mCurCmd = ENM_CONSOLE_CFG;
}
break;
case 'E':
ch = aFrame[1];
if ( ch == '0' )
{
mScanOption.stepMode = ENM_FORWARD_ON;
mCurCmd = ENM_CONSOLE_CFG;
}
else if ( ch == '1' )
{
mScanOption.stepMode = ENM_FORWARD_STEP;
mCurCmd = ENM_CONSOLE_CFG;
}
break;
/// plate shake
case 'X':
if ( aLen == 2 )
{
ch = aFrame[1];
if ( ch == '1' )
{
mScanOption.shakeSpeed = ENM_LIBRATE_SPEED_FAST;
mCurCmd = ENM_CONSOLE_CFG;
}
else if ( ch == '2' )
{
mScanOption.shakeSpeed = ENM_LIBRATE_SPEED_MIDDLE;
mCurCmd = ENM_CONSOLE_CFG;
}
else if ( ch == '3' )
{
mScanOption.shakeSpeed = ENM_LIBRATE_SPEED_SLOW;
mCurCmd = ENM_CONSOLE_CFG;
}
}
break;
case 'Z':
ch = aFrame[1];
ch1 = aFrame[2];
if ( aLen == 2 && ('0' <= ch && ch <= '9') )
{
mScanOption.shakeTime = ch - '0';
mCurCmd = ENM_CONSOLE_SCAN;
}
else if ( aLen == 3 && ('0' <= ch1 && ch1 <= '9') )
{
mScanOption.shakeTime = (ch - '0') * 10 + (ch1 - '0');
if ( mScanOption.startColumn <= 60 )
mCurCmd = ENM_CONSOLE_CFG;
else
{
mScanOption.shakeTime = 0;
mCurCmd = ENM_CONSOLE_NONE;
}
}
break;
case 'A':
if (aLen == 1)
{
mScanOption.reagent = ENM_REAGENT_NO;
mScanOption.reagentCnt = 0;
mCurCmd = ENM_CONSOLE_CFG;
}
break;
case 'B':
if ( mScanOption.reagentCnt >= 12 )
break;
if (aLen == 2 )
{
if( '1' <= aFrame[1] && aFrame[1] <= '9' )
{
mScanOption.reagent = ENM_REAGENT_LN;
mScanOption.reagentArr[mScanOption.reagentCnt++] = aFrame[1] - '0' - 1;
mCurCmd = ENM_CONSOLE_CFG;
}
}
else if ( aLen == 3 )
{
ch = aFrame[1];
ch1 = aFrame[2];
if ( '1' <= aFrame[1] && aFrame[1] <= '9' && '1' <= aFrame[1] && aFrame[1] <= '9')
{
mScanOption.reagentArr[mScanOption.reagentCnt] = (ch - '0' - 1) * 10 + (ch1 - '0' - 1);
if ( mScanOption.reagentArr[mScanOption.reagentCnt] <= 12 )
{
mScanOption.reagent = ENM_REAGENT_LN;
mScanOption.reagentCnt++;
mCurCmd = ENM_CONSOLE_CFG;
}
}
}
break;
/// Quary commandsw
case 'T':
if (aLen == 1)
{
mCurCmd = ENM_CONSOLE_QUAEY_DATE;
}
break;
case 'N':
if (aLen == 1)
{
mCurCmd = ENM_CONSOLE_QUAEY_SN;
}
break;
case 'V':
if (aLen == 1)
{
mCurCmd = ENM_CONSOLE_QUAEY_VER;
}
break;
}
if ( mCurCmd == ENM_CONSOLE_SCAN )
mScanOption.columnCnt = 12 - mScanOption.startColumn;
/// temp for debug
if ( mCurCmd != ENM_CONSOLE_NONE )
{
PutStr( 10, 30, (MCHAR*)aFrame, 0 );
}
return mCurCmd;
}
void CEnmConsole::Init()
{
mParser.SetBufferLen( 128 );
mCurCmd = ENM_CONSOLE_NONE;
mScanOption.Reset();
}
| 18.697095 | 91 | 0.562583 | Borrk |
0d4443dbe65e09b81ed32908937afd93343a5e3d | 20,740 | cpp | C++ | core/src/control/dihu_context.cpp | maierbn/opendihu | 577650e2f6b36a7306766b0f4176f8124458cbf0 | [
"MIT"
] | 17 | 2018-11-25T19:29:34.000Z | 2021-09-20T04:46:22.000Z | core/src/control/dihu_context.cpp | maierbn/opendihu | 577650e2f6b36a7306766b0f4176f8124458cbf0 | [
"MIT"
] | 1 | 2020-11-12T15:15:58.000Z | 2020-12-29T15:29:24.000Z | core/src/control/dihu_context.cpp | maierbn/opendihu | 577650e2f6b36a7306766b0f4176f8124458cbf0 | [
"MIT"
] | 4 | 2018-10-17T12:18:10.000Z | 2021-05-28T13:24:20.000Z | #include "control/dihu_context.h"
#include <Python.h> // this has to be the first included header
#include <python_home.h> // defines PYTHON_HOME_DIRECTORY
#include <omp.h>
#include <fstream>
#include <iostream>
#include <iomanip>
#include <memory>
#include <thread>
#include <list>
#include <petscvec.h>
#include <sys/types.h> // getpid
#include <unistd.h> // getpid
#include <omp.h>
#include <csignal>
#include <cstdlib>
#include <cctype>
#include "utility/python_utility.h"
//#include "output_writer/paraview/paraview.h"
#include "output_writer/python_callback/python_callback.h"
#include "output_writer/python_file/python_file.h"
#include "output_writer/exfile/exfile.h"
#include "mesh/mesh_manager/mesh_manager.h"
#include "mesh/mapping_between_meshes/manager/04_manager.h"
#include "solver/solver_manager.h"
#include "partition/partition_manager.h"
#include "control/diagnostic_tool/stimulation_logging.h"
#include "control/diagnostic_tool/solver_structure_visualizer.h"
#include "slot_connection/global_connections_by_slot_name.h"
#include "easylogging++.h"
#include "control/python_config/settings_file_name.h"
#include "utility/mpi_utility.h"
#ifdef HAVE_PAT
#include <pat_api.h> // perftools, only available on hazel hen
#endif
#ifdef HAVE_EXTRAE
#include "extrae.h"
#endif
#ifdef HAVE_MEGAMOL
#include "Console.h"
#endif
#ifdef HAVE_CHASTE
#include "CommandLineArguments.hpp"
#include "ExecutableSupport.hpp"
#endif
bool GLOBAL_DEBUG = false; //< use this variable to hack in debugging output that should only be visible in certain conditions. Do not commit these hacks!
// global singleton objects
std::shared_ptr<MappingBetweenMeshes::Manager> DihuContext::mappingBetweenMeshesManager_ = nullptr;
std::shared_ptr<Mesh::Manager> DihuContext::meshManager_ = nullptr;
std::shared_ptr<Solver::Manager> DihuContext::solverManager_ = nullptr;
std::shared_ptr<Partition::Manager> DihuContext::partitionManager_ = nullptr;
std::shared_ptr<SolverStructureVisualizer> DihuContext::solverStructureVisualizer_ = nullptr;
std::shared_ptr<GlobalConnectionsBySlotName> DihuContext::globalConnectionsBySlotName_ = nullptr;
// other global variables that are needed in static methods
std::string DihuContext::solverStructureDiagramFile_ = ""; //< filename of the solver structure diagram file
std::string DihuContext::pythonScriptText_ = ""; //< the python settings text
DihuContext::logFormat_t DihuContext::logFormat_ = DihuContext::logFormat_t::logFormatCsv; //< format of lines in the log file
// megamol variables
std::shared_ptr<std::thread> DihuContext::megamolThread_ = nullptr;
std::vector<char *> DihuContext::megamolArgv_;
std::vector<std::string> DihuContext::megamolArguments_;
#ifdef HAVE_ADIOS
std::shared_ptr<adios2::ADIOS> DihuContext::adios_ = nullptr; //< adios context option
#endif
bool DihuContext::initialized_ = false;
int DihuContext::nObjects_ = 0; //< number of objects of DihuContext, if the last object gets destroyed, call MPI_Finalize
int DihuContext::nRanksCommWorld_ = 0; //< number of MPI ranks in MPI_COMM_WORLD
int DihuContext::ownRankNoCommWorld_ = 0; //< own MPI rank no in MPI_COMM_WORLD
void handleSignal(int signalNo)
{
std::string signalName = strsignal(signalNo);
Control::PerformanceMeasurement::setParameter("exit_signal",signalNo);
Control::PerformanceMeasurement::setParameter("exit",signalName);
Control::PerformanceMeasurement::writeLogFile();
Control::StimulationLogging::writeLogFile();
DihuContext::writeSolverStructureDiagram();
MappingBetweenMeshes::Manager::writeLogFile();
int rankNo = DihuContext::ownRankNoCommWorld();
LOG(INFO) << "Rank " << rankNo << " received signal " << sys_siglist[signalNo]
<< " (" << signalNo << "): " << signalName;
if (signalNo == SIGBUS)
{
LOG(ERROR) << "Available memory was exceeded.";
}
if (signalNo != SIGRTMIN)
{
MPI_Abort(MPI_COMM_WORLD,0);
}
if (signalNo == SIGSEGV)
{
#ifndef NDEBUG
#ifndef RELWITHDEBINFO
#ifdef __GNUC__
// source: https://stackoverflow.com/questions/77005/how-to-automatically-generate-a-stacktrace-when-my-program-crashes
void *array[100];
// get void*'s for all entries on the stack
size_t size = backtrace(array, 100);
// print stack trace
backtrace_symbols_fd(array, size, STDERR_FILENO);
#endif
#endif
#endif
}
// set back to normal in case program continues execution
Control::PerformanceMeasurement::setParameter("exit","normal");
}
// copy-constructor
DihuContext::DihuContext(const DihuContext &rhs) : pythonConfig_(rhs.pythonConfig_), rankSubset_(rhs.rankSubset_)
{
nObjects_++;
VLOG(1) << "DihuContext(a), nObjects = " << nObjects_;
doNotFinalizeMpi_ = rhs.doNotFinalizeMpi_;
}
DihuContext::DihuContext(int argc, char *argv[], bool doNotFinalizeMpi, PythonConfig pythonConfig, std::shared_ptr<Partition::RankSubset> rankSubset) :
pythonConfig_(pythonConfig), rankSubset_(rankSubset), doNotFinalizeMpi_(doNotFinalizeMpi)
{
nObjects_++;
VLOG(1) << "DihuContext(b), nObjects = " << nObjects_;
// if rank subset was not given
if (!rankSubset_)
{
rankSubset_ = std::make_shared<Partition::RankSubset>(); // create rankSubset with all ranks, i.e. MPI_COMM_WORLD
}
}
DihuContext::DihuContext(int argc, char *argv[], bool doNotFinalizeMpi, bool settingsFromFile) :
pythonConfig_(NULL), doNotFinalizeMpi_(doNotFinalizeMpi)
{
nObjects_++;
VLOG(1) << "DihuContext(c), nObjects = " << nObjects_;
if (!initialized_)
{
#ifdef HAVE_PAT
PAT_record(PAT_STATE_OFF);
#endif
// initialize MPI, this is necessary to be able to call PetscFinalize without MPI shutting down
MPI_Init(&argc, &argv);
// the following three lines output the MPI version during compilation, use for debugging
//#define XSTR(x) STR(x)
//#define STR(x) #x
//#pragma message "The value of MPI_VERSION: " XSTR(MPI_VERSION)
#if MPI_VERSION >= 3
MPI_Comm_set_errhandler(MPI_COMM_WORLD, MPI_ERRORS_RETURN); // MPI >= 4
#else
MPI_Errhandler_set(MPI_COMM_WORLD, MPI_ERRORS_RETURN);
#endif
// get current MPI version
char versionString[MPI_MAX_LIBRARY_VERSION_STRING];
int resultLength;
MPI_Get_library_version(versionString, &resultLength);
std::string mpiVersion(versionString, versionString+resultLength);
#ifdef HAVE_EXTRAE
// Disable Extrae tracing at startup
Extrae_shutdown();
#endif
// create rankSubset with all ranks, i.e. MPI_COMM_WORLD
rankSubset_ = std::make_shared<Partition::RankSubset>();
// initial global variables that will be returned by the static methods nRanksCommWorld() and ownRankNoCommWorld()
nRanksCommWorld_ = rankSubset_->size();
ownRankNoCommWorld_ = rankSubset_->ownRankNo();
// initialize the logging output formats of easylogging++
initializeLogging(argc, argv);
// configure PETSc to abort on error
PetscOptionsSetValue(NULL, "-on_error_abort", "");
// initialize PETSc
PetscInitialize(&argc, &argv, NULL, "This is an opendihu application.");
// print header text to console
LOG(INFO) << "This is " << versionText() << ", " << metaText();
LOG(INFO) << mpiVersion;
LOG(DEBUG) << "MPI version: \"" << mpiVersion << "\".";
// warn if OpenMPI 4 is used, remove this warning if you know if the bug has been fixed (try running fibers_emg with at least 64 ranks)
if (mpiVersion.find("Open MPI v4") != std::string::npos && metaText().find("ipvs-epyc") != std::string::npos)
{
LOG(WARNING) << "Using MPI 4 on ipvs-epyc, which might cause problems. \n"
<< "In 2020 we found there is a bug in at least OpenMPI 4.0.4. Everything works fine with OpenMPI 3 (e.g. version 3.1.6). \n"
<< "So, either use OpenMPI 3 or you might check if the issues have already be fixed in newer versions of OpenMPI 4 or higher. \n"
<< "If so, remove this warning message.";
}
// output process ID in debug
int pid = getpid();
LOG(DEBUG) << "PID " << pid;
// set number of OpenMP threads to use to 1
omp_set_num_threads(1);
LOG(DEBUG) << "set number of threads to 1";
// parallel debugging barrier
bool enableDebuggingBarrier = false;
PetscErrorCode ierr = PetscOptionsHasName(NULL, NULL, "-pause", (PetscBool *)&enableDebuggingBarrier); CHKERRV(ierr);
if (enableDebuggingBarrier)
{
MPIUtility::gdbParallelDebuggingBarrier();
}
// register signal handler functions on various signals. This enforces dumping of the log file even if the program crashes.
struct sigaction signalHandler;
signalHandler.sa_handler = handleSignal;
sigemptyset(&signalHandler.sa_mask);
signalHandler.sa_flags = 0;
sigaction(SIGINT, &signalHandler, NULL);
//sigaction(SIGKILL, &signalHandler, NULL);
sigaction(SIGTERM, &signalHandler, NULL);
//sigaction(SIGABRT, &signalHandler, NULL);
sigaction(SIGFPE, &signalHandler, NULL);
sigaction(SIGILL, &signalHandler, NULL);
sigaction(SIGSEGV, &signalHandler, NULL);
sigaction(SIGXCPU, &signalHandler, NULL);
sigaction(SIGRTMIN, &signalHandler, NULL);
Control::PerformanceMeasurement::setParameter("exit","normal");
Control::PerformanceMeasurement::setParameter("exit_signal","");
// determine settings filename
Control::settingsFileName = "settings.py";
// check if the first command line argument is *.py, only then it is treated as config file
bool explicitConfigFileGiven = false;
if (argc > 1 && settingsFromFile)
{
std::string firstArgument = argv[1];
if (firstArgument.rfind(".py") == firstArgument.size() - 3)
{
explicitConfigFileGiven = true;
Control::settingsFileName = argv[1];
}
else
{
LOG(ERROR) << "First command line argument does not have suffix *.py, not considering it as config file!";
}
}
initializePython(argc, argv, explicitConfigFileGiven);
// load python script
if (settingsFromFile)
{
if (!loadPythonScriptFromFile(Control::settingsFileName))
{
// if a settings file was given but could not be loaded
if (explicitConfigFileGiven)
{
LOG(FATAL) << "Could not load settings file \"" << Control::settingsFileName << "\".";
}
else
{
// look for any other settings.py files to output a message with a suggestion
std::stringstream commandSuggestions;
int ret = system("ls ../settings*.py > a");
if (ret == 0)
{
// parse contents of ls command
std::ifstream file("a", std::ios::in|std::ios::binary);
if (file.is_open())
{
while (!file.eof())
{
std::string line;
std::getline(file, line);
if (file.eof())
break;
commandSuggestions << " " << argv[0] << " " << line << std::endl;
}
}
// remove temporary file `a`
ret = system("rm a");
}
if (commandSuggestions.str().empty())
{
commandSuggestions << " " << argv[0] << " ../settings.py";
}
// if no settings file was given (default file "settings.py" was tried but not successful)
LOG(FATAL) << "No settings file was specified!" << std::endl
<< "Usually you run the executable from within a \"build_release\" or \"build_debug\" directory "
<< "and the settings file is located one directory higher. Try a command like the following:" << std::endl << std::endl
<< commandSuggestions.str();
}
}
}
// start megamol console
LOG(DEBUG) << "initializeMegaMol";
initializeMegaMol(argc, argv);
// initialize chaste, if available
#ifdef HAVE_CHASTE
int *argcChaste = new int;
char ***argvChaste = new (char**);
*argcChaste = argc;
*argvChaste = argv;
ExecutableSupport::StartupWithoutShowingCopyright(argcChaste, argvChaste);
LOG(DEBUG) << "initialize chaste";
#endif
initialized_ = true;
}
if (!rankSubset_)
rankSubset_ = std::make_shared<Partition::RankSubset>(); // create rankSubset with all ranks, i.e. MPI_COMM_WORLD
// if this is the first constructed DihuContext object, create global objects partition manager, mesh manager and solver manager
if (!partitionManager_)
{
VLOG(2) << "create partitionManager_";
partitionManager_ = std::make_shared<Partition::Manager>(pythonConfig_);
}
if (!meshManager_)
{
VLOG(2) << "create meshManager_";
meshManager_ = std::make_shared<Mesh::Manager>(pythonConfig_);
meshManager_->setPartitionManager(partitionManager_);
mappingBetweenMeshesManager_ = std::make_shared<MappingBetweenMeshes::Manager>(pythonConfig_);
}
if (!solverManager_)
{
solverManager_ = std::make_shared<Solver::Manager>(pythonConfig_);
}
if (!solverStructureVisualizer_)
{
solverStructureVisualizer_ = std::make_shared<SolverStructureVisualizer>();
}
if (!globalConnectionsBySlotName_)
{
globalConnectionsBySlotName_ = std::make_shared<GlobalConnectionsBySlotName>(pythonConfig_);
}
// initialize regularization parameters
if (pythonConfig_.hasKey("regularization"))
{
if (pythonConfig_.isEmpty("regularization"))
{
MathUtility::INVERSE_REGULARIZATION_TOLERANCE = 0;
MathUtility::INVERSE_REGULARIZATION_EPSILON = 0;
LOG(INFO) << "Note, disabling regularization.";
}
else
{
std::array<double,2> regularization = pythonConfig_.getOptionArray<double,2>("regularization", 0, PythonUtility::ValidityCriterion::NonNegative);
MathUtility::INVERSE_REGULARIZATION_TOLERANCE = regularization[0];
MathUtility::INVERSE_REGULARIZATION_EPSILON = regularization[1];
LOG(INFO) << "Note, setting regularization to [tol,eps] = [" << regularization[0] << "," << regularization[1] << "].";
}
}
else
{
LOG(INFO) << "Note, setting regularization to [tol,eps] = [1e-2,1e-1]. Add `\"regularization\": None` in the settings to disable.";
}
}
DihuContext::DihuContext(int argc, char *argv[], std::string pythonSettings, bool doNotFinalizeMpi) :
DihuContext(argc, argv, doNotFinalizeMpi, false)
{
nObjects_++;
VLOG(1) << "DihuContext(d), nObjects = " << nObjects_;
// This constructor is called when creating the context object from unit tests.
// load python config script as given by parameter
loadPythonScript(pythonSettings);
if (VLOG_IS_ON(1))
{
PythonUtility::printDict(pythonConfig_.pyObject());
}
// initialize global singletons
// they are first set to nullptr to allow break points on their destruction (happens in unit tests)
partitionManager_ = nullptr;
partitionManager_ = std::make_shared<Partition::Manager>(pythonConfig_);
VLOG(2) << "recreate meshManager";
meshManager_ = nullptr;
meshManager_ = std::make_shared<Mesh::Manager>(pythonConfig_);
meshManager_->setPartitionManager(partitionManager_);
mappingBetweenMeshesManager_ = nullptr;
mappingBetweenMeshesManager_ = std::make_shared<MappingBetweenMeshes::Manager>(pythonConfig_);
// create solver manager
solverManager_ = nullptr;
solverManager_ = std::make_shared<Solver::Manager>(pythonConfig_);
}
PythonConfig DihuContext::getPythonConfig() const
{
return pythonConfig_;
}
std::string DihuContext::pythonScriptText()
{
return pythonScriptText_;
}
std::string DihuContext::versionText()
{
std::stringstream versionTextStr;
versionTextStr << "opendihu 1.3, built " << __DATE__; // << " " << __TIME__; // do not add time otherwise it wants to recompile this file every time
#ifdef __cplusplus
versionTextStr << ", C++ " << __cplusplus;
#endif
#ifdef __INTEL_COMPILER
versionTextStr << ", Intel";
#elif defined _CRAYC
versionTextStr << ", Cray";
#elif defined __GNUC__
versionTextStr << ", GCC";
#elif defined __PGI
versionTextStr << ", PGI";
#endif
#ifdef __VERSION__
versionTextStr << " " << __VERSION__;
#elif defined __PGIC__
versionTextStr << " " << __PGIC__;
#endif
return versionTextStr.str();
}
std::string DihuContext::metaText()
{
std::stringstream metaTextStr;
// time stamp
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
// metaTextStr << "current time: " << std::put_time(&tm, "%Y/%m/%d %H:%M:%S") << ", hostname: ";
std::string tm_string = StringUtility::timeToString(&tm);
metaTextStr << "current time: " << tm_string << ", hostname: ";
// host name
char hostname[MAXHOSTNAMELEN+1];
gethostname(hostname, MAXHOSTNAMELEN+1);
metaTextStr << std::string(hostname) << ", n ranks: " << nRanksCommWorld_;
return metaTextStr.str();
}
int DihuContext::ownRankNoCommWorld()
{
return ownRankNoCommWorld_;
}
int DihuContext::ownRankNo()
{
return rankSubset_->ownRankNo();
}
int DihuContext::nRanksCommWorld()
{
return nRanksCommWorld_;
}
std::shared_ptr<Mesh::Manager> DihuContext::meshManager()
{
return meshManager_;
}
std::shared_ptr<MappingBetweenMeshes::Manager> DihuContext::mappingBetweenMeshesManager()
{
return mappingBetweenMeshesManager_;
}
std::shared_ptr<Partition::Manager> DihuContext::partitionManager()
{
return partitionManager_;
}
std::shared_ptr<Solver::Manager> DihuContext::solverManager() const
{
return solverManager_;
}
std::shared_ptr<SolverStructureVisualizer> DihuContext::solverStructureVisualizer()
{
return solverStructureVisualizer_;
}
std::shared_ptr<GlobalConnectionsBySlotName> DihuContext::globalConnectionsBySlotName()
{
return globalConnectionsBySlotName_;
}
void DihuContext::writeSolverStructureDiagram()
{
if (solverStructureVisualizer_ && solverStructureDiagramFile_ != "")
solverStructureVisualizer_->writeDiagramFile(solverStructureDiagramFile_);
}
#ifdef HAVE_ADIOS
std::shared_ptr<adios2::ADIOS> DihuContext::adios() const
{
return adios_;
}
#endif
#ifdef HAVE_MEGAMOL
std::shared_ptr<zmq::socket_t> DihuContext::zmqSocket() const
{
return zmqSocket_;
}
#endif
std::shared_ptr<Partition::RankSubset> DihuContext::rankSubset() const
{
return rankSubset_;
}
DihuContext::logFormat_t DihuContext::logFormat() {
return logFormat_;
}
void DihuContext::setLogFormat(DihuContext::logFormat_t format) {
logFormat_ = format;
}
DihuContext DihuContext::operator[](std::string keyString)
{
int argc = 0;
char **argv = NULL;
DihuContext dihuContext(argc, argv, doNotFinalizeMpi_, PythonConfig(pythonConfig_, keyString), rankSubset_);
return dihuContext;
}
//! create a context object, like with the operator[] but with given config
DihuContext DihuContext::createSubContext(PythonConfig config, std::shared_ptr<Partition::RankSubset> rankSubset)
{
int argc = 0;
char **argv = NULL;
DihuContext dihuContext(argc, argv, doNotFinalizeMpi_, config, rankSubset);
return dihuContext;
}
DihuContext::~DihuContext()
{
nObjects_--;
VLOG(1) << "~DihuContext, nObjects = " << nObjects_;
if (nObjects_ == 0)
{
// write log files
writeSolverStructureDiagram();
Control::StimulationLogging::writeLogFile();
Control::PerformanceMeasurement::writeLogFile();
MappingBetweenMeshes::Manager::writeLogFile();
// After a call to MPI_Finalize we cannot call MPI_Initialize() anymore.
// This is only a problem when the code is tested with the GoogleTest framework, because then we want to run multiple tests in one executable.
// In this case, do not finalize MPI, but call MPI_Barrier instead which also syncs the ranks.
if (!doNotFinalizeMpi_)
{
#ifdef HAVE_MEGAMOL
LOG(DEBUG) << "wait for MegaMol to finish";
// wait for megamol to finish
if (megamolThread_)
megamolThread_->join();
#endif
// global barrier
MPI_Barrier(MPI_COMM_WORLD);
// finalize Petsc and MPI
LOG(DEBUG) << "Petsc_Finalize";
PetscErrorCode ierr = PetscFinalize(); CHKERRV(ierr);
MPI_Finalize();
}
}
// do not clear pythonConfig_ here, because it crashes
//VLOG(4) << "PY_CLEAR(PYTHONCONFIG_)"; // note: calling VLOG in a destructor is critical and can segfault
//Py_CLEAR(pythonConfig_);
// do not finalize Python because otherwise tests keep crashing
//Py_Finalize();
#if PY_MAJOR_VERSION >= 3
//Py_Finalize();
#endif
// do not finalize Petsc because otherwise there can't be multiple DihuContext objects for testing
//PetscErrorCode ierr;
//ierr = PetscFinalize(); CHKERRV(ierr);
//MPI_Finalize();
}
| 32.816456 | 162 | 0.696866 | maierbn |
0d45caf5e5072c6dfb885f377dac04ce2cafe8e6 | 8,084 | cpp | C++ | examples/check-trx-approving/send-1xdr-wait-for-approving.cpp | mile-core/mile-csa-light | de15599ad38a2b6c672da1fba321cd9eb473ddef | [
"MIT"
] | null | null | null | examples/check-trx-approving/send-1xdr-wait-for-approving.cpp | mile-core/mile-csa-light | de15599ad38a2b6c672da1fba321cd9eb473ddef | [
"MIT"
] | null | null | null | examples/check-trx-approving/send-1xdr-wait-for-approving.cpp | mile-core/mile-csa-light | de15599ad38a2b6c672da1fba321cd9eb473ddef | [
"MIT"
] | null | null | null | //
// Created by lotus mile on 17/11/2018.
//
// Example shows how to prepare MILE transaction, then send to node use MILE JSON-RPC API
// and waiting for transaction approving by blockchain
//
// Alternate C++ wrappper for json-rpc API: https://github.com/mile-core/mile-csa-jsonrpc-client
//
#include <string>
#include <iostream>
#include <milecsa_light_api.hpp>
#include <time.h>
#include <unistd.h>
#include "json.hpp"
#ifdef WITH_CURL
#include <curl/curl.h>
#else
#error "curl library has not been configured"
#endif
#define __DEBUG_RPC__ 0
using milecsa::light::Pair;
using result = milecsa::light::result;
using namespace milecsa::transaction;
using namespace milecsa::keys;
using namespace std;
using namespace nlohmann;
///
/// MILE Testnet node with opened JSON-RPC API
///
string url = "https://lotus000.testnet.mile.global/v1/api";
/// Get current block id
uint64_t get_block_id();
/// Get block data serialized to json by block id
nlohmann::json get_block(uint64_t block_id);
/// Send prepared signed transaction
int send_transaction(const string &body);
int main(int argc, char *argv[]) {
if (argc != 3) {
cerr << "Usage to send 1 XDR from -> to" << endl;
cerr << argv[0] << " <from address as secret phrase> <to>" << endl;
return -1;
}
string from = argv[1];
string to = argv[2];
string errorMessage;
milecsa::light::Pair pair;
///
/// Restore wallet private and public keys pair from secret phrase
///
if (generate_with_secret(pair, from, errorMessage) != result::OK) {
cerr << " from secret phrase error: " << errorMessage << endl;
return -1;
}
///
/// Validate destination address
///
if (validate_public_key(to, errorMessage) != result::OK) {
cerr << " destination public key error: " << errorMessage << endl;
return -1;
}
uint64_t block_id = (uint64_t)-1;
///
/// Try getting block-id 3 times
///
int repeats = 0;
while (block_id == (uint64_t)-1) {
block_id = get_block_id();
if (repeats >= 3) {
cerr << "Node: " << url << " is not available..."<< endl;
exit(EXIT_FAILURE);
}
repeats ++;
}
///
/// trx id can be create for user reason or can be default
///
uint64_t trx_id = default_transaction_id;
///
/// Transaction container string
///
std::string transaction;
///
/// Transaction container uniq digest
///
std::string digest;
///
/// Asset code
///
milecsa::token token = milecsa::assets::XDR;
///
/// Prepare asset amount
///
float amount = 0.01f;
///
/// Build signed transfer transaction
///
if (milecsa::transaction::prepare_transfer(
pair.private_key, /// "from" private key
to, /// "to" public key
to_string(block_id), /// block id
trx_id, /// user defined transaction id or number
token, /// asset
amount, /// amount of transfer
0.0, /// fee is always 0
"0xtest:approving", /// description
transaction, /// returned signed transaction as json string
digest, /// uinq transaction digest string
errorMessage /// error message if something failed
)){
cerr << " prepare_transfer error: " << errorMessage << endl;
return -1;
}
bool is_appoved = false;
for (int repeats = 0; repeats < 10 && !is_appoved;) {
cout << endl << " Sending transaction: " << digest << " repeat: "<< repeats << endl;
///
/// Send transfer the first time or resend next 10 blocks
///
send_transaction(transaction);
///
/// Try the next 3 blocks
///
for (uint64_t i = 0; i < 3; ++i, ++repeats) {
///
/// Waiting the next block
///
cout << " Waiting for transaction: " << digest << endl;
sleep(20);
uint64_t next_block_id = block_id + repeats;
json transactions = get_block(next_block_id);
if (transactions.is_array()) {
cout << " Block: " << next_block_id << " transactions: " << endl;
for (json::iterator it = transactions.begin(); it != transactions.end(); ++it) {
cout << *it << '\n';
if (digest == it->at("digest").get<string>()) {
//
// approved
//
cout << " Transaction: " << digest << " has been approved in :" << next_block_id << " block"<< endl;
is_appoved = true;
}
}
}
if (is_appoved)
break;
else {
cout << " Transaction: " << digest << " has not been found in :" << next_block_id << " block"<< endl;
}
}
}
exit(EXIT_SUCCESS);
}
///
/// Common JSON-RPC request
///
/// \param method - json-rpc method
/// \param params - method params
/// \return json srialzed object
///
json request(string method, const json ¶ms);
json get_block(uint64_t block_id){
string id = to_string(block_id);
json response = request("get-block-by-id", {{"id",id}});
if (!response.empty() && response.count("block-data")) {
return response.at("block-data").at("transactions");
}
return {};
}
uint64_t get_block_id(){
uint64_t block_id = (uint64_t)-1;
json response = request("get-current-block-id", {});
if (!response.empty()) {
block_id = stoull(response["current-block-id"].get<string>());
}
return block_id;
}
int send_transaction(const string &body)
{
int ret = -1;
json params = json::parse(body);
json response = request("send-transaction", params);
if (!response.empty()) {
ret = 0;
}
return ret;
}
///
/// libCurl utilites
///
size_t writeFunction(void *ptr, size_t size, size_t nmemb, std::string* data) {
data->append((char*) ptr, size * nmemb);
return size * nmemb;
}
json request(string method, const json ¶ms) {
int ret = 0;
CURL *curl;
CURLcode res;
json request = {
{"jsonrpc","2.0"},
{"id","0"},
{"method",method},
{"params",params}
};
string request_string = request.dump();
#if __DEBUG_RPC__
cout << "Send: " << endl;
cout << " " << request << endl;
#endif
///
/// Create curl object
///
curl = curl_easy_init();
if(curl) {
#if __DEBUG_RPC__
cout << endl << "Response:" << endl;
#endif
///
/// Setup curl request
///
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request_string.c_str());
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, (long)request_string.length());
std::string response_string;
std::string header_string;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeFunction);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &header_string);
///
/// Perform the request, res will get the return code
///
res = curl_easy_perform(curl);
///
/// Check for errors
///
if(res != CURLE_OK){
ret = -1;
cerr << "curl_easy_perform() failed: " << curl_easy_strerror(res) << endl;
}
else {
#if __DEBUG_RPC__
cout << " : " << response_string << endl;
#endif
}
///
/// Always cleanup
///
curl_easy_cleanup(curl);
return json::parse(response_string).at("result");
}
return {};
}
| 24.203593 | 124 | 0.539955 | mile-core |
0d4686544a5e554f737ac86f116d4c7c3f948baa | 435 | cpp | C++ | LAB-1/CODE/Lab-1-Program-5-Write a program to receive marks of physics, chemistry & maths from user.cpp | CSIT-Knowledge-Hub-EBulk/PPS-C-Lang.-Lab-Based-Programs-AKTU--KCS-151P-KCS-251P- | 7e6fcf1658d7122cfeeb04ce97ecda0355f6c4e1 | [
"Apache-2.0"
] | 2 | 2022-02-24T14:28:03.000Z | 2022-03-03T06:18:10.000Z | LAB-1/CODE/Lab-1-Program-5-Write a program to receive marks of physics, chemistry & maths from user.cpp | CSIT-Knowledge-Hub-EBulk/PPS-C-Lang.-Lab-Based-Programs-AKTU--KCS-151P-KCS-251P- | 7e6fcf1658d7122cfeeb04ce97ecda0355f6c4e1 | [
"Apache-2.0"
] | null | null | null | LAB-1/CODE/Lab-1-Program-5-Write a program to receive marks of physics, chemistry & maths from user.cpp | CSIT-Knowledge-Hub-EBulk/PPS-C-Lang.-Lab-Based-Programs-AKTU--KCS-151P-KCS-251P- | 7e6fcf1658d7122cfeeb04ce97ecda0355f6c4e1 | [
"Apache-2.0"
] | null | null | null | #include<stdio.h>
#include<math.h>
int main()
{
int phy,che,math,total,PM;
printf("Enter the marks of the physics chemistry and math's\n");
scanf("%d%d%d",&phy,&che,&math);
total=(phy+che+math);
PM=phy+math;
if(phy>40 && che>50 && math>60 && (PM>150||total>200))
{
printf("You are eligible for the course\n");
}
else
printf("Not eligible\n");
return 0;
}
| 22.894737 | 69 | 0.542529 | CSIT-Knowledge-Hub-EBulk |
0d479d8cd3aab2ea0db1c5db3db6a934ea60bbd3 | 2,376 | cc | C++ | src/core/tests/ordered_fixed_list_test.cc | litlpoet/beliefbox | 6b303e49017f8054f43c6c840686fcc632205e4e | [
"OLDAP-2.3"
] | null | null | null | src/core/tests/ordered_fixed_list_test.cc | litlpoet/beliefbox | 6b303e49017f8054f43c6c840686fcc632205e4e | [
"OLDAP-2.3"
] | null | null | null | src/core/tests/ordered_fixed_list_test.cc | litlpoet/beliefbox | 6b303e49017f8054f43c6c840686fcc632205e4e | [
"OLDAP-2.3"
] | null | null | null | /* -*- Mode: c++ -*- */
// copyright (c) 2009 by Christos Dimitrakakis <christos.dimitrakakis@gmail.com>
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifdef MAKE_MAIN
#include "OrderedFixedList.h"
#include <iostream>
#include <list>
#include "Random.h"
#include "real.h"
using namespace std;
bool TestList(int N, int K);
int main(void) {
int n_tests = 1000;
int errors = 0;
cout << "\nRunning ordered fixed list test\n";
cout << "n_tests: " << n_tests << endl;
for (int test = 0; test < n_tests; ++test) {
bool res = TestList((int)ceil(urandom(0, 1000)), (int)ceil(urandom(0, 10)));
if (!res) {
errors++;
}
}
fflush(stdout);
fflush(stderr);
if (errors) {
std::cerr << "test failed with " << errors << "/" << n_tests
<< " failed tests\n";
} else {
std::cout << "test complete with no errors in " << n_tests << " tests\n";
}
return errors;
}
bool TestList(int N, int K) {
OrderedFixedList<int> L(K);
list<real> X;
vector<int> number(N);
for (int i = 0; i < N; ++i) {
real x = floor(10 * urandom());
number[i] = i;
X.push_back(x);
L.AddPerhaps(x, &number[i]);
}
X.sort();
list<real>::iterator it;
list<pair<real, int*> >::iterator oit;
it = X.begin();
oit = L.S.begin();
bool flag = true;
for (int i = 0; i < K; ++i, ++it, ++oit) {
if (it == X.end() || oit == L.S.end()) {
break;
}
if (*it != oit->first) {
flag = false;
break;
}
}
if (!flag) {
it = X.begin();
oit = L.S.begin();
for (int i = 0; i < K; ++i, ++it, ++oit) {
real x = *it;
real y = *it;
if (approx_eq(x, y)) {
cout << x << "=" << y << " ";
} else {
cout << x << "!" << y << " ";
}
}
cout << endl;
}
return flag;
}
#endif
| 25.826087 | 80 | 0.457912 | litlpoet |
0d4bf48003af45391df0befebd85e79a05dbde89 | 182 | cpp | C++ | server/main.cpp | kaiqiangren/webrtc | f898ba54714a58d387282b4a9bbd4ab2b9bc7659 | [
"MIT"
] | 1 | 2020-06-16T05:05:40.000Z | 2020-06-16T05:05:40.000Z | server/main.cpp | kaiqiangren/webrtc | f898ba54714a58d387282b4a9bbd4ab2b9bc7659 | [
"MIT"
] | null | null | null | server/main.cpp | kaiqiangren/webrtc | f898ba54714a58d387282b4a9bbd4ab2b9bc7659 | [
"MIT"
] | null | null | null | #include <iostream>
#include "server.h"
int main (int argc, char* argv[]){
avdance::Server* server = new avdance::Server();
if (server)
{
server->run();
}
return 0;
}; | 16.545455 | 50 | 0.604396 | kaiqiangren |
0d4c928dcd47f276b2461bb23895566cdd1185a0 | 5,813 | cxx | C++ | Modules/ThirdParty/VNL/src/vxl/core/vnl/algo/tests/test_symmetric_eigensystem.cxx | arobert01/ITK | 230d319fdeaa3877273fab5d409dd6c11f0a6874 | [
"Apache-2.0"
] | 945 | 2015-01-09T00:43:52.000Z | 2022-03-30T08:23:02.000Z | Modules/ThirdParty/VNL/src/vxl/core/vnl/algo/tests/test_symmetric_eigensystem.cxx | arobert01/ITK | 230d319fdeaa3877273fab5d409dd6c11f0a6874 | [
"Apache-2.0"
] | 2,354 | 2015-02-04T21:54:21.000Z | 2022-03-31T20:58:21.000Z | Modules/ThirdParty/VNL/src/vxl/core/vnl/algo/tests/test_symmetric_eigensystem.cxx | arobert01/ITK | 230d319fdeaa3877273fab5d409dd6c11f0a6874 | [
"Apache-2.0"
] | 566 | 2015-01-04T14:26:57.000Z | 2022-03-18T20:33:18.000Z | // This is core/vnl/algo/tests/test_symmetric_eigensystem.cxx
#include <iostream>
#include <chrono> // Needed for high resolution clock
#include <algorithm>
#include "testlib/testlib_test.h"
//:
// \file
// \brief test program for symmetric eigensystem routines.
// \author Andrew W. Fitzgibbon, Oxford RRG.
// \date 29 Aug 96
//-----------------------------------------------------------------------------
#include "vnl/vnl_double_3x3.h"
#include "vnl/vnl_double_3.h"
#include "vnl/vnl_random.h"
#include <vnl/algo/vnl_symmetric_eigensystem.h>
// extern "C"
void
test_symmetric_eigensystem()
{
double Sdata[36] = {
30.0000, -3.4273, 13.9254, 13.7049, -2.4446, 20.2380, -3.4273, 13.7049, -2.4446, 1.3659, 3.6702, -0.2282,
13.9254, -2.4446, 20.2380, 3.6702, -0.2282, 28.6779, 13.7049, 1.3659, 3.6702, 12.5273, -1.6045, 3.9419,
-2.4446, 3.6702, -0.2282, -1.6045, 3.9419, 2.5821, 20.2380, -0.2282, 28.6779, 3.9419, 2.5821, 44.0636,
};
vnl_matrix<double> S(Sdata, 6, 6);
{
vnl_symmetric_eigensystem<double> eig(S);
vnl_matrix<double> res = eig.recompose() - S;
std::cout << "V'*D*V - S = " << res << std::endl << "residual = " << res.fro_norm() << std::endl;
TEST_NEAR("recompose residual", res.fro_norm(), 0.0, 1e-12);
std::cout << "Eigenvalues: ";
for (int i = 0; i < 6; ++i)
std::cout << eig.get_eigenvalue(i) << ' ';
std::cout << std::endl;
}
double Cdata[36] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, -1, 0, 0, 0, 0, 2, 0, 0,
};
vnl_matrix<double> C(Cdata, 6, 6);
{
vnl_symmetric_eigensystem<double> eig(C);
vnl_matrix<double> res = eig.recompose() - C;
std::cout << "V'*D*V - C = " << res << std::endl << "residual = " << res.fro_norm() << std::endl;
TEST_NEAR("recompose residual", res.fro_norm(), 0.0, 1e-12);
std::cout << "Eigenvalues: ";
for (int i = 0; i < 6; ++i)
std::cout << eig.get_eigenvalue(i) << ' ';
std::cout << std::endl;
}
{
// Generate a random system
vnl_random rng;
int n = 6;
int s = 10;
vnl_matrix<double> D_rand(s, n);
for (int i = 0; i < s; ++i)
for (int j = 0; j < n; ++j)
D_rand(i, j) = 1.0 + 2.0 * rng.normal64();
vnl_matrix<double> S = D_rand.transpose() * D_rand;
vnl_matrix<double> evecs(n, n);
vnl_vector<double> evals(n);
vnl_symmetric_eigensystem_compute(S, evecs, evals);
std::cout << "Testing random system:\n"
<< "evals: " << evals << std::endl;
for (int i = 1; i < n; ++i)
{
TEST("Eigenvalue increases", evals(i) >= evals(i - 1), true);
}
}
{ // test I with specialised 3x3 version
double l1, l2, l3;
vnl_symmetric_eigensystem_compute_eigenvals(1.0, 0.0, 0.0, 1.0, 0.0, 1.0, l1, l2, l3);
std::cout << "Eigenvals: " << l1 << ' ' << l2 << ' ' << l3 << std::endl;
TEST("Correct eigenvalues for I", l1 == 1.0 && l2 == 1.0 && l3 == 1.0, true);
}
{ // compare speed and values of specialised 3x3 version with nxn version
constexpr unsigned n = 20000;
double fixed_data[n][3];
unsigned int fixed_time = 0;
{
double M11, M12, M13, M22, M23, M33;
// Generate a random system
vnl_random rng(5);
for (auto & c : fixed_data)
{
M11 = rng.drand64() * 10.0 - 5.0;
M12 = rng.drand64() * 10.0 - 5.0;
M13 = rng.drand64() * 10.0 - 5.0;
M22 = rng.drand64() * 10.0 - 5.0;
M23 = rng.drand64() * 10.0 - 5.0;
M33 = rng.drand64() * 10.0 - 5.0;
const auto timer_01 = std::chrono::high_resolution_clock::now();
vnl_symmetric_eigensystem_compute_eigenvals(M11, M12, M13, M22, M23, M33, c[0], c[1], c[2]);
const auto timer_02 = std::chrono::high_resolution_clock::now();
fixed_time += (timer_02 - timer_01).count();
}
}
double netlib_data[n][3];
unsigned int netlib_time = 0;
{
// Generate same random system
vnl_random rng(5);
vnl_double_3x3 M, evecs;
vnl_double_3 evals;
for (auto & c : netlib_data)
{
M(0, 0) = rng.drand64() * 10.0 - 5.0;
M(1, 0) = M(0, 1) = rng.drand64() * 10.0 - 5.0;
M(2, 0) = M(0, 2) = rng.drand64() * 10.0 - 5.0;
M(1, 1) = rng.drand64() * 10.0 - 5.0;
M(2, 1) = M(1, 2) = rng.drand64() * 10.0 - 5.0;
M(2, 2) = rng.drand64() * 10.0 - 5.0;
const auto timer_03 = std::chrono::high_resolution_clock::now();
vnl_symmetric_eigensystem_compute(M.as_ref(), evecs.as_ref().non_const(), evals.as_ref().non_const());
const auto timer_04 = std::chrono::high_resolution_clock::now();
netlib_time += (timer_04 - timer_03).count();
c[0] = evals[0];
c[1] = evals[1];
c[2] = evals[2];
}
}
std::cout << "Fixed Time: " << fixed_time << " netlib time: " << netlib_time << std::endl;
TEST("Specialised version is faster", fixed_time < netlib_time, true);
double sum_dsq = 0.0;
double max_dsq = 0.0;
for (unsigned c = 0; c < n; ++c)
{
const double dsq = vnl_c_vector<double>::euclid_dist_sq(netlib_data[c], fixed_data[c], 3);
max_dsq = std::max(dsq, max_dsq);
sum_dsq += dsq;
}
std::cout << "max_dsq: " << max_dsq << " mean_dsq: " << sum_dsq / static_cast<double>(n) << std::endl;
TEST("Specialised version gives similar results", max_dsq < 1e-8, true);
}
{
double v1, v2, v3;
vnl_symmetric_eigensystem_compute_eigenvals(4199.0, 0.0, 0.0, 4199.0, 0.0, 4801.0, v1, v2, v3);
TEST_NEAR("Numerically difficult values are ok v1", v1, 4199, 1e-3);
TEST_NEAR("Numerically difficult values are ok v2", v2, 4199, 1e-3);
TEST_NEAR("Numerically difficult values are ok v3", v3, 4801, 1e-7);
}
}
TESTMAIN(test_symmetric_eigensystem);
| 34.808383 | 112 | 0.565801 | arobert01 |
0d4f7ca83e76c6b2bc23448babd58a7f3c3019cf | 4,384 | cpp | C++ | system/BufferVector_tests.cpp | EvilMcJerkface/grappa | 69f2f3674d6f8e512e0bf55264bb75b972fd82de | [
"BSD-3-Clause"
] | 144 | 2015-01-16T01:53:24.000Z | 2022-02-27T21:59:09.000Z | system/BufferVector_tests.cpp | EvilMcJerkface/grappa | 69f2f3674d6f8e512e0bf55264bb75b972fd82de | [
"BSD-3-Clause"
] | 79 | 2015-01-01T00:32:30.000Z | 2021-07-06T12:26:08.000Z | system/BufferVector_tests.cpp | EvilMcJerkface/grappa | 69f2f3674d6f8e512e0bf55264bb75b972fd82de | [
"BSD-3-Clause"
] | 53 | 2015-02-02T17:55:46.000Z | 2022-03-08T09:35:16.000Z | ////////////////////////////////////////////////////////////////////////
// Copyright (c) 2010-2015, University of Washington and Battelle
// Memorial Institute. 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 Washington, Battelle
// Memorial Institute, or the names of their 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
// UNIVERSITY OF WASHINGTON OR BATTELLE MEMORIAL INSTITUTE 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.
////////////////////////////////////////////////////////////////////////
/// This file contains tests for the GlobalAddress<> class.
#include <boost/test/unit_test.hpp>
#include <Grappa.hpp>
#include "BufferVector.hpp"
#include "Delegate.hpp"
#define DOTEST(str) VLOG(1) << "TEST: " << (str);
BOOST_AUTO_TEST_SUITE( BufferVector_tests );
using namespace Grappa;
BOOST_AUTO_TEST_CASE( test1 ) {
Grappa::init( GRAPPA_TEST_ARGS );
Grappa::run([]{
DOTEST("basic insert") {
BufferVector<int64_t> b(10);
BOOST_CHECK_EQUAL( b.getLength(), 0 );
const int64_t v1 = 11;
b.insert( v1 );
BOOST_CHECK_EQUAL( b.getLength(), 1 );
b.setReadMode();
GlobalAddress<const int64_t> vs = b.getReadBuffer();
int64_t r = delegate::read( vs );
BOOST_CHECK_EQUAL( r, v1 );
}
DOTEST("one capacity growth") {
BufferVector<int64_t> b(4);
BOOST_CHECK_EQUAL( b.getLength(), 0 );
const int64_t v1 = 11;
b.insert( v1 );
BOOST_CHECK_EQUAL( b.getLength(), 1 );
const int64_t v2 = 22;
b.insert( v2 );
BOOST_CHECK_EQUAL( b.getLength(), 2 );
const int64_t v3 = 33;
b.insert( v3 );
BOOST_CHECK_EQUAL( b.getLength(), 3 );
const int64_t v4 = 44;
b.insert( v4 );
BOOST_CHECK_EQUAL( b.getLength(), 4 );
b.setReadMode();
GlobalAddress<const int64_t> vs = b.getReadBuffer();
{
int64_t r = delegate::read( vs+0 );
BOOST_CHECK_EQUAL( *(vs.pointer()), v1);
BOOST_CHECK_EQUAL( r, v1 );
}
{
int64_t r = delegate::read( vs+1 );
BOOST_CHECK_EQUAL( r, v2 );
}
{
int64_t r = delegate::read( vs+2 );
BOOST_CHECK_EQUAL( r, v3 );
}
{
int64_t r = delegate::read( vs+3 );
BOOST_CHECK_EQUAL( r, v4 );
}
}
DOTEST("more capacity growth") {
BufferVector<int64_t> b(2);
BOOST_CHECK_EQUAL( b.getLength(), 0 );
const uint64_t num = 222;
int64_t vals[num];
for (uint64_t i=0; i<num; i++) {
vals[i] = i*2;
b.insert(vals[i]);
BOOST_CHECK_EQUAL( b.getLength(), i+1 );
// BOOST_MESSAGE( "insert and now " << b );
}
b.setReadMode();
GlobalAddress<const int64_t> vs = b.getReadBuffer();
for (uint64_t i=0; i<num; i++) {
int64_t r = delegate::read( vs+i );
BOOST_CHECK_EQUAL( r, vals[i] );
BOOST_CHECK_EQUAL( b.getLength(), num );
}
}
});
Grappa::finalize();
}
BOOST_AUTO_TEST_SUITE_END();
| 32.474074 | 72 | 0.619526 | EvilMcJerkface |
0d502432df28a49db97ff275ca967b2453e10b19 | 765 | cpp | C++ | tools/WmarkEditor/src/viewmodel/commands/ReplaceCommand.cpp | meilj/CppTS | 00b077c264a7c32fcbd416f73c4bdc2e0027afd8 | [
"BSD-2-Clause"
] | null | null | null | tools/WmarkEditor/src/viewmodel/commands/ReplaceCommand.cpp | meilj/CppTS | 00b077c264a7c32fcbd416f73c4bdc2e0027afd8 | [
"BSD-2-Clause"
] | null | null | null | tools/WmarkEditor/src/viewmodel/commands/ReplaceCommand.cpp | meilj/CppTS | 00b077c264a7c32fcbd416f73c4bdc2e0027afd8 | [
"BSD-2-Clause"
] | null | null | null | /*
** Mei Lijuan, 2019
*/
////////////////////////////////////////////////////////////////////////////////
#include "precomp.h"
#include "../../model/TextModel.h"
#include "../TextViewModel.h"
////////////////////////////////////////////////////////////////////////////////
namespace CSL {
////////////////////////////////////////////////////////////////////////////////
// TextViewModel
CommandFunc TextViewModel::get_ReplaceCommand()
{
return [this](std::any&& param)->bool
{
return this->m_spModel->Replace(std::any_cast<ReplacePara>(param));
};
}
////////////////////////////////////////////////////////////////////////////////
}
////////////////////////////////////////////////////////////////////////////////
| 26.37931 | 82 | 0.282353 | meilj |
0d553ac226f783748c49c6bfb439bac18b562242 | 3,078 | cpp | C++ | demos/FileInstrument.cpp | michaelwillis/sfizz | 0461f6e5e288da71aeccf7b7dfd71302bf0ba175 | [
"BSD-2-Clause"
] | 281 | 2019-06-06T05:58:59.000Z | 2022-03-06T12:20:09.000Z | demos/FileInstrument.cpp | michaelwillis/sfizz | 0461f6e5e288da71aeccf7b7dfd71302bf0ba175 | [
"BSD-2-Clause"
] | 590 | 2019-09-22T00:26:10.000Z | 2022-03-31T19:21:58.000Z | demos/FileInstrument.cpp | michaelwillis/sfizz | 0461f6e5e288da71aeccf7b7dfd71302bf0ba175 | [
"BSD-2-Clause"
] | 44 | 2019-10-08T08:24:20.000Z | 2022-02-26T04:21:44.000Z | // SPDX-License-Identifier: BSD-2-Clause
// This code is part of the sfizz library and is licensed under a BSD 2-clause
// license. You should have receive a LICENSE.md file along with the code.
// If not, contact the sfizz maintainers at https://github.com/sfztools/sfizz
#include "sfizz/FileMetadata.h"
#include "absl/strings/string_view.h"
#include <sndfile.hh>
#include <cstdio>
static const char* modeString(int mode, const char* valueFallback = nullptr)
{
switch (mode) {
case sfz::LoopNone:
return "none";
case sfz::LoopForward:
return "forward";
case sfz::LoopBackward:
return "backward";
case sfz::LoopAlternating:
return "alternating";
default:
return valueFallback;
}
}
template <class Instrument>
static void printInstrument(const Instrument& ins)
{
printf("Gain: %d\n", ins.gain);
printf("Base note: %d\n", ins.basenote);
printf("Detune: %d\n", ins.detune);
printf("Velocity: %d:%d\n", ins.velocity_lo, ins.velocity_hi);
printf("Key: %d:%d\n", ins.key_lo, ins.key_hi);
printf("Loop count: %d\n", ins.loop_count);
for (unsigned i = 0, n = ins.loop_count; i < n; ++i) {
printf("\nLoop %d:\n", i + 1);
printf("\tMode: %s\n", modeString(ins.loops[i].mode, "(unknown)"));
printf("\tStart: %u\n", ins.loops[i].start);
printf("\tEnd: %u\n", ins.loops[i].end);
printf("\tCount: %u\n", ins.loops[i].count);
}
}
static void usage(const char* argv0)
{
fprintf(
stderr,
"Usage: %s [-s|-f] <sound-file>\n"
" -s: extract the instrument using libsndfile\n"
" -f: extract the instrument using RIFF metadata\n",
argv0);
}
enum FileMethod {
kMethodSndfile,
kMethodRiff,
};
int main(int argc, char *argv[])
{
fs::path path;
FileMethod method = kMethodSndfile;
if (argc == 2) {
path = argv[1];
}
else if (argc == 3) {
absl::string_view flag = argv[1];
if (flag == "-s")
method = kMethodSndfile;
else if (flag == "-f")
method = kMethodRiff;
else {
usage(argv[0]);
return 1;
}
path = argv[2];
}
else {
usage(argv[0]);
return 1;
}
if (method == kMethodRiff) {
sfz::FileMetadataReader reader;
if (!reader.open(path)) {
fprintf(stderr, "Cannot open file\n");
return 1;
}
sfz::InstrumentInfo ins {};
if (!reader.extractInstrument(ins)) {
fprintf(stderr, "Cannot get instrument\n");
return 1;
}
printInstrument(ins);
}
else {
SndfileHandle sndFile(path);
if (!sndFile) {
fprintf(stderr, "Cannot open file\n");
return 1;
}
SF_INSTRUMENT ins {};
if (sndFile.command(SFC_GET_INSTRUMENT, &ins, sizeof(ins)) != 1) {
fprintf(stderr, "Cannot get instrument\n");
return 1;
}
printInstrument(ins);
}
return 0;
}
| 26.534483 | 78 | 0.561079 | michaelwillis |
0d567711d2da622f3ada827358709f9e36ecc4f0 | 5,152 | cpp | C++ | dependencies/PyMesh/python/PyCGAL.cpp | aprieels/3D-watermarking-spectral-decomposition | dcab78857d0bb201563014e58900917545ed4673 | [
"MIT"
] | 5 | 2018-06-04T19:52:02.000Z | 2022-01-22T09:04:00.000Z | dependencies/PyMesh/python/PyCGAL.cpp | aprieels/3D-watermarking-spectral-decomposition | dcab78857d0bb201563014e58900917545ed4673 | [
"MIT"
] | null | null | null | dependencies/PyMesh/python/PyCGAL.cpp | aprieels/3D-watermarking-spectral-decomposition | dcab78857d0bb201563014e58900917545ed4673 | [
"MIT"
] | null | null | null | #include <memory>
#include <pybind11/pybind11.h>
#include <pybind11/eigen.h>
#include <pybind11/stl.h>
#include <pybind11/operators.h>
#include <Core/EigenTypedef.h>
#include <CGAL/SelfIntersection.h>
#include <CGAL/enum.h>
#include <CGAL/Gmpz.h>
#include <CGAL/Gmpq.h>
namespace py = pybind11;
using namespace PyMesh;
void init_CGAL(py::module &m) {
py::class_<SelfIntersection, std::shared_ptr<SelfIntersection> >(m, "SelfIntersection")
.def(py::init<const MatrixFr& , const MatrixIr&>())
.def("detect_self_intersection",
&SelfIntersection::detect_self_intersection)
.def("clear", &SelfIntersection::clear)
.def("get_self_intersecting_pairs",
&SelfIntersection::get_self_intersecting_pairs)
.def("handle_intersection_candidate",
&SelfIntersection::handle_intersection_candidate);
py::class_<CGAL::Gmpz>(m, "Gmpz")
.def(py::init<>())
.def(py::init<int>())
.def(py::init<Float>())
.def_property_readonly("sign", [](const CGAL::Gmpz& v){
switch (v.sign()) {
case CGAL::ZERO:
return 0;
case CGAL::POSITIVE:
return 1;
case CGAL::NEGATIVE:
return -1;
default:
throw RuntimeError("Unexpected sign type");
}
})
.def(py::self + py::self)
.def(py::self - py::self)
.def(py::self * py::self)
.def(py::self / py::self)
.def(py::self + int())
.def(int() + py::self)
.def(py::self - int())
.def(int() - py::self)
.def(py::self * int())
.def(int() * py::self)
.def(py::self / int())
.def(int() / py::self)
.def(py::self += py::self)
.def(py::self += int())
.def(py::self -= py::self)
.def(py::self -= int())
.def(py::self *= py::self)
.def(py::self *= int())
.def(py::self /= py::self)
.def(py::self /= int())
.def(py::self << int())
.def(py::self >> int())
.def(py::self <<= int())
.def(py::self >>= int())
.def(py::self & py::self)
.def(py::self &= py::self)
.def(py::self | py::self)
.def(py::self |= py::self)
.def(py::self ^ py::self)
.def(py::self ^= py::self)
.def_property_readonly("size", &CGAL::Gmpz::size)
.def_property_readonly("bit_size", &CGAL::Gmpz::bit_size)
.def_property_readonly("approximate_decimal_length", &CGAL::Gmpz::approximate_decimal_length)
.def("to_double", &CGAL::Gmpz::to_double)
.def("__repr__", [](const CGAL::Gmpz& v) {
std::stringstream sout;
sout << v;
return sout.str();
}) ;
py::class_<CGAL::Gmpq>(m, "Gmpq")
.def(py::init<>())
.def(py::init<int>())
.def(py::init<CGAL::Gmpz>())
.def(py::init<int, int>())
.def(py::init<CGAL::Gmpz, CGAL::Gmpz>())
.def(py::init<Float>())
.def(py::init<std::string>())
.def(py::init<std::string, int>())
.def(py::self + py::self)
.def(py::self - py::self)
.def(py::self * py::self)
.def(py::self / py::self)
.def(py::self + int())
.def(py::self + CGAL::Gmpz())
.def(py::self + Float())
.def(int() + py::self)
.def(CGAL::Gmpz() + py::self)
.def(Float() + py::self)
.def(py::self - int())
.def(py::self - CGAL::Gmpz())
.def(py::self - Float())
.def(int() - py::self)
.def(CGAL::Gmpz() - py::self)
.def(Float() - py::self)
.def(py::self * int())
.def(py::self * CGAL::Gmpz())
.def(py::self * Float())
.def(int() * py::self)
.def(CGAL::Gmpz() * py::self)
.def(Float() * py::self)
.def(py::self / int())
.def(py::self / CGAL::Gmpz())
.def(py::self / Float())
.def(int() / py::self)
.def(CGAL::Gmpz() / py::self)
.def(Float() / py::self)
.def(py::self += py::self)
.def(py::self += CGAL::Gmpz())
.def(py::self += int())
.def(py::self += Float())
.def(py::self -= py::self)
.def(py::self -= CGAL::Gmpz())
.def(py::self -= int())
.def(py::self -= Float())
.def(py::self *= py::self)
.def(py::self *= CGAL::Gmpz())
.def(py::self *= int())
.def(py::self *= Float())
.def(py::self /= py::self)
.def(py::self /= CGAL::Gmpz())
.def(py::self /= int())
.def(py::self /= Float())
.def_property_readonly("numerator", &CGAL::Gmpq::numerator)
.def_property_readonly("denominator", &CGAL::Gmpq::denominator)
.def("to_double", &CGAL::Gmpq::to_double)
.def("__repr__", [](const CGAL::Gmpq& v) {
std::stringstream sout;
sout << v;
return sout.str();
}) ;
}
| 32.815287 | 101 | 0.477484 | aprieels |
0d56fc306f89d4c03bb78b2ea29efa086c108fbf | 18,793 | cpp | C++ | gui/main_window/history_control/reactions/ReactionsPlate.cpp | SammyEnigma/im-desktop | d93c1c335c8290b21b69c578c399edf61cb899e8 | [
"Apache-2.0"
] | 2 | 2020-10-23T06:27:27.000Z | 2021-11-12T12:06:12.000Z | gui/main_window/history_control/reactions/ReactionsPlate.cpp | john-preston/im-desktop | 271e42db657bdaa8e261f318c627ca5414e0dd87 | [
"Apache-2.0"
] | null | null | null | gui/main_window/history_control/reactions/ReactionsPlate.cpp | john-preston/im-desktop | 271e42db657bdaa8e261f318c627ca5414e0dd87 | [
"Apache-2.0"
] | null | null | null | #include "stdafx.h"
#include "controls/TextUnit.h"
#include "controls/GeneralDialog.h"
#include "styles/ThemeParameters.h"
#include "main_window/MainWindow.h"
#include "main_window/contact_list/ContactListModel.h"
#include "../HistoryControlPageItem.h"
#include "utils/InterConnector.h"
#include "animation/animation.h"
#include "../MessageStyle.h"
#include "utils/DrawUtils.h"
#include "utils/utils.h"
#include "fonts.h"
#include "ReactionsPlate.h"
#include "ReactionsList.h"
namespace
{
constexpr std::chrono::milliseconds animationDuration = std::chrono::milliseconds(150);
constexpr std::chrono::milliseconds updateAnimationDuration = std::chrono::milliseconds(100);
int32_t plateOffsetY(Ui::ReactionsPlateType _type)
{
if (_type == Ui::ReactionsPlateType::Regular)
return Ui::MessageStyle::Reactions::plateYOffset();
else
return Ui::MessageStyle::Reactions::mediaPlateYOffset();
}
int32_t plateOffsetX()
{
return Utils::scale_value(4);
}
int32_t plateHeight()
{
return Ui::MessageStyle::Reactions::plateHeight();
}
int32_t plateHeightWithShadow(Ui::ReactionsPlateType _type)
{
auto height = plateHeight();
if (_type == Ui::ReactionsPlateType::Regular)
height += Ui::MessageStyle::Reactions::shadowHeight();
return height;
}
int32_t plateBorderRadius()
{
return Utils::scale_value(12);
}
const QColor& plateColor(Ui::ReactionsPlateType _type, bool _outgoing)
{
if (_type == Ui::ReactionsPlateType::Regular)
{
if (_outgoing)
{
static const auto color = Styling::getParameters().getColor(Styling::StyleVariable::PRIMARY_BRIGHT);
return color;
}
else
{
static const auto color = Styling::getParameters().getColor(Styling::StyleVariable::BASE_LIGHT);
return color;
}
}
else
{
static const auto color = Styling::getParameters().getColor(Styling::StyleVariable::GHOST_SECONDARY);
return color;
}
}
int32_t shadowOffset()
{
return Utils::scale_value(2);
}
int32_t plateEmojiSize()
{
return Utils::scale_value(19);
}
int32_t plateSideMargin()
{
return Utils::scale_value(4);
}
int32_t plateTopMargin()
{
return Utils::scale_value(3);
}
int32_t emojiRightMargin()
{
return Utils::scale_value(4);
}
int32_t textRightMargin()
{
return Utils::scale_value(6);
}
QFont countFont(bool _myReaction)
{
if (_myReaction)
return Fonts::adjustedAppFont(12, Fonts::FontWeight::Bold);
else
return Fonts::adjustedAppFont(12, Fonts::FontWeight::Normal);
}
const QColor& countTextColor(Ui::ReactionsPlateType _type, bool _outgoing)
{
if (_type == Ui::ReactionsPlateType::Regular)
{
if (_outgoing)
{
static const auto color = Styling::getParameters().getColor(Styling::StyleVariable::PRIMARY_PASTEL);
return color;
}
else
{
static const auto color = Styling::getParameters().getColor(Styling::StyleVariable::BASE_PRIMARY);
return color;
}
}
else
{
static const auto color = Styling::getParameters().getColor(Styling::StyleVariable::TEXT_SOLID_PERMANENT);
return color;
}
}
QColor shadowColor()
{
return QColor(0, 0, 0, 255);
}
double shadowColorAlpha()
{
return 0.12;
}
QString countText(int _count)
{
if (_count < 100)
return QString::number(_count);
else
return qsl("99+");
}
bool allowedToViewReactionsList(const QString& _chatId)
{
const auto role = Logic::getContactListModel()->getYourRole(_chatId);
const auto notAllowed = role == ql1s("notamember") || Logic::getContactListModel()->isChannel(_chatId);
return !notAllowed;
}
int shadowHeight()
{
return Utils::scale_value(1);
}
void drawSolidShadow(QPainter& _p, const QPainterPath& _path)
{
Utils::ShadowLayer layer;
layer.color_ = QColor(17, 32, 55, 255 * 0.05);
layer.yOffset_ = shadowHeight();
Utils::drawLayeredShadow(_p, _path, { layer });
}
}
namespace Ui
{
//////////////////////////////////////////////////////////////////////////
// ReactionsPlate_p
//////////////////////////////////////////////////////////////////////////
class ReactionsPlate_p
{
public:
ReactionsPlate_p(ReactionsPlate* _q) : q(_q) {}
struct ReactionItem
{
QRect rect_;
QRect emojiRect_;
QImage emoji_;
bool mouseOver_ = false;
QString reaction_;
double opacity_ = 1;
TextRendering::TextUnitPtr countUnit_;
anim::Animation opacityAnimation_;
anim::Animation geometryAnimation_;
};
ReactionItem createReactionItem(const Data::Reactions::Reaction& _reaction, const QString& _myReaction)
{
ReactionItem item;
item.reaction_ = _reaction.reaction_;
item.countUnit_ = TextRendering::MakeTextUnit(countText(_reaction.count_));
item.countUnit_->init(countFont(_reaction.reaction_ == _myReaction), countTextColor(item_->reactionsPlateType(), outgoingPosition_));
item.emoji_ = Emoji::GetEmoji(Emoji::EmojiCode::fromQString(_reaction.reaction_), Utils::scale_bitmap(plateEmojiSize()));
return item;
}
void updateReactionItem(ReactionItem& _item, const Data::Reactions::Reaction& _reaction, const QString& _myReaction)
{
_item.countUnit_->setText(countText(_reaction.count_));
_item.countUnit_->init(countFont(_reaction.reaction_ == _myReaction), countTextColor(item_->reactionsPlateType(), outgoingPosition_));
}
void updateItems(const Data::Reactions& _reactions)
{
for (auto& reaction : _reactions.reactions_)
{
if (reaction.count_ == 0)
continue;
auto it = std::find_if(items_.begin(), items_.end(), [reaction](const ReactionItem& _item) { return _item.reaction_ == reaction.reaction_; });
if (it != items_.end())
updateReactionItem(*it, reaction, _reactions.myReaction_);
else
items_.push_back(createReactionItem(reaction, _reactions.myReaction_));
}
}
int updateItemGeometry(ReactionItem& _item, int _xOffset)
{
auto startXOffset = _xOffset;
_item.emojiRect_ = QRect(_xOffset, plateTopMargin(), plateEmojiSize(), plateEmojiSize());
const auto countWidth = _item.countUnit_->desiredWidth();
_xOffset += _item.emojiRect_.width() + emojiRightMargin();
_item.countUnit_->getHeight(countWidth);
_item.countUnit_->setOffsets(_xOffset, plateHeight() / 2);
_item.rect_ = QRect(_item.emojiRect_.topLeft(), QSize(plateEmojiSize() + emojiRightMargin() + countWidth, plateHeight()));
_xOffset += textRightMargin() + countWidth;
return _xOffset - startXOffset;
}
std::vector<int> calcItemsOffsets(std::vector<ReactionItem>& _items, int& _xOffset)
{
std::vector<int> offsets_;
for (const auto& item : _items)
{
offsets_.push_back(_xOffset);
_xOffset += item.emojiRect_.width() + emojiRightMargin();
const auto countWidth = item.countUnit_->desiredWidth();
_xOffset += textRightMargin() + countWidth;
}
return offsets_;
}
int updateItemsGeometry(std::vector<ReactionItem>& _items, int _xOffset = 0)
{
auto startXOffset = _xOffset;
for (auto& item: _items)
_xOffset += updateItemGeometry(item, _xOffset);
return _xOffset - startXOffset;
}
QPoint calcPlatePosition(int _plateWidth)
{
const auto messageRect = item_->messageRect();
const auto top = messageRect.bottom() + plateOffsetY(item_->reactionsPlateType());
auto left = 0;
if (outgoingPosition_)
left = messageRect.right() - plateOffsetX() - _plateWidth;
else
left = messageRect.left() + plateOffsetX();
return QPoint(left, top);
}
QRect updateGeometryHelper()
{
const auto plateType = item_->reactionsPlateType();
shadow_->setEnabled(plateType == ReactionsPlateType::Regular);
auto xOffset = plateSideMargin();
xOffset += updateItemsGeometry(items_, xOffset);
const auto plateSize = QSize(xOffset, plateHeightWithShadow(plateType));
return QRect(calcPlatePosition(plateSize.width()), plateSize);
}
void setPlateGeometry(const QRect& _geometry)
{
q->setGeometry(_geometry);
Q_EMIT q->platePositionChanged();
}
void draw(QPainter& _p)
{
QPainterPath platePath;
const auto plateRect = QRect(0, 0, q->width(), plateHeight());
platePath.addRoundedRect(plateRect, plateBorderRadius(), plateBorderRadius());
drawSolidShadow(_p, platePath);
_p.setOpacity(opacity_);
_p.fillPath(platePath, plateColor(item_->reactionsPlateType(), outgoingPosition_));
for (auto& item : items_)
{
_p.setOpacity(item.opacity_ * opacity_);
_p.drawImage(item.emojiRect_, item.emoji_);
item.countUnit_->draw(_p, TextRendering::VerPosition::MIDDLE);
}
}
void startShowAnimation()
{
updateInProgress_ = true;
opacity_ = 0;
opacityAnimation_.finish();
opacityAnimation_.start([this]()
{
opacity_ = opacityAnimation_.current();
shadow_->setColor(shadowColorWithAlpha());
q->update();
},[this]()
{
updateInProgress_ = false;
startQueuedAnimation();
},0, 1, animationDuration.count(), anim::sineInOut);
q->show();
}
void startUpdateAnimation()
{
updateInProgress_ = true;
opacityAnimation_.finish();
opacityAnimation_.start([this]()
{
if (deletedReactions_.empty())
return;
for (auto& item : items_)
{
if (deletedReactions_.count(item.reaction_))
item.opacity_ = opacityAnimation_.current();
}
q->update();
},[this]()
{
startGeometryAnimation();
}, 1, 0, updateAnimationDuration.count(), anim::sineInOut);
}
void startGeometryAnimation()
{
auto currentWidth = q->size().width();
std::vector<int> currentOffsets;
for (auto& item : items_)
{
if (deletedReactions_.count(item.reaction_) == 0)
currentOffsets.push_back(item.emojiRect_.left());
}
for (auto& reaction : deletedReactions_)
{
auto it = std::find_if(items_.begin(), items_.end(), [reaction](const ReactionItem& _item) { return _item.reaction_ == reaction; });
if (it != items_.end())
items_.erase(it);
}
auto xOffset = plateSideMargin();
auto newOffsets = calcItemsOffsets(items_, xOffset);
auto sizeAfterDeletion = xOffset;
addedItems_.clear();
for (auto& reaction : addedReactions_)
addedItems_.push_back(createReactionItem(reaction, reactions_.myReaction_));
auto addedSize = updateItemsGeometry(addedItems_, sizeAfterDeletion);
auto newWidth = sizeAfterDeletion + addedSize;
geometryAnimation_.finish();
geometryAnimation_.start([this, currentOffsets, newOffsets, currentWidth, newWidth]()
{
for (auto i = 0u; i < items_.size(); i++)
{
auto itemNewX = currentOffsets[i] + (newOffsets[i] - currentOffsets[i]) * geometryAnimation_.current();
updateItemGeometry(items_[i], itemNewX);
}
auto width = currentWidth + (newWidth - currentWidth) * geometryAnimation_.current();
setPlateGeometry(QRect(calcPlatePosition(width), QSize(width, plateHeightWithShadow(item_->reactionsPlateType()))));
q->update();
}, [this]()
{
startAddedItemsAnimation();
}, 0, 1, updateAnimationDuration.count(), anim::sineInOut);
}
void startAddedItemsAnimation()
{
for (auto& item : addedItems_)
item.opacity_ = 0;
auto addedIndex = items_.size();
std::move(addedItems_.begin(), addedItems_.end(), std::back_inserter(items_));
addedItems_.resize(0);
opacityAnimation_.finish();
opacityAnimation_.start([this, addedIndex]()
{
for (auto i = addedIndex; i < items_.size(); i++)
items_[i].opacity_ = opacityAnimation_.current();
q->update();
}, [this]()
{
updateItems(reactions_);
setPlateGeometry(updateGeometryHelper());
updateInProgress_ = false;
startQueuedAnimation();
}, 0, 1, updateAnimationDuration.count(), anim::sineInOut);
}
void startQueuedAnimation()
{
if (queuedData_)
{
reactions_ = *queuedData_;
processUpdate(reactions_);
if (addedReactions_.empty() && deletedReactions_.empty())
{
updateItems(reactions_);
setPlateGeometry(updateGeometryHelper());
}
else
{
startUpdateAnimation();
}
queuedData_.reset();
}
}
void processUpdate(const Data::Reactions& _reactions)
{
deletedReactions_.clear();
addedReactions_.clear();
reactions_ = _reactions;
if (items_.empty())
return;
std::unordered_set<QString, Utils::QStringHasher> reactionsSet;
for (auto& reaction : _reactions.reactions_)
{
if (reaction.count_ == 0)
continue;
auto it = std::find_if(items_.begin(), items_.end(), [reaction](const ReactionItem& _item) { return _item.reaction_ == reaction.reaction_; });
if (it == items_.end())
addedReactions_.push_back(reaction);
reactionsSet.insert(reaction.reaction_);
}
for (const auto& item : items_)
{
if (reactionsSet.count(item.reaction_) == 0)
deletedReactions_.insert(item.reaction_);
}
}
QColor shadowColorWithAlpha()
{
auto color = shadowColor();
color.setAlphaF(shadowColorAlpha() * opacity_);
return color;
}
void initShadow()
{
shadow_ = new QGraphicsDropShadowEffect(q);
shadow_->setBlurRadius(8);
shadow_->setOffset(0, Utils::scale_value(1));
shadow_->setColor(shadowColorWithAlpha());
q->setGraphicsEffect(shadow_);
}
QPoint pressPos_;
Data::Reactions reactions_;
HistoryControlPageItem* item_;
std::vector<ReactionItem> items_;
std::vector<ReactionItem> addedItems_;
QGraphicsDropShadowEffect* shadow_;
std::unordered_set<QString, Utils::QStringHasher> deletedReactions_;
std::vector<Data::Reactions::Reaction> addedReactions_;
std::optional<Data::Reactions> queuedData_;
anim::Animation opacityAnimation_;
anim::Animation geometryAnimation_;
bool updateInProgress_ = false;
double opacity_ = 0;
bool outgoingPosition_;
ReactionsPlate* q;
};
//////////////////////////////////////////////////////////////////////////
// ReactionsPlate
//////////////////////////////////////////////////////////////////////////
ReactionsPlate:: ReactionsPlate(HistoryControlPageItem* _item)
: QWidget(_item),
d(std::make_unique<ReactionsPlate_p>(this))
{
d->item_ = _item;
setVisible(false);
setMouseTracking(true);
setCursor(allowedToViewReactionsList(_item->getContact()) ? Qt::PointingHandCursor : Qt::ArrowCursor);
connect(&Utils::InterConnector::instance(), &Utils::InterConnector::multiselectChanged, this, &ReactionsPlate::onMultiselectChanged);
d->initShadow();
}
ReactionsPlate::~ReactionsPlate()
{
}
void ReactionsPlate::setReactions(const Data::Reactions& _reactions)
{
if (!_reactions.isEmpty())
{
d->processUpdate(_reactions);
if (d->addedReactions_.empty() && d->deletedReactions_.empty() && !d->updateInProgress_)
{
d->updateItems(_reactions);
d->setPlateGeometry(d->updateGeometryHelper());
if (!isVisible() && !Utils::InterConnector::instance().isMultiselect())
d->startShowAnimation();
}
else
{
if (d->updateInProgress_)
d->queuedData_ = _reactions;
else
d->startUpdateAnimation();
}
}
else
{
d->items_.clear();
hide();
}
update();
}
void ReactionsPlate::setOutgoingPosition(bool _outgoingPosition)
{
d->outgoingPosition_ = _outgoingPosition;
}
void ReactionsPlate::onMessageSizeChanged()
{
d->setPlateGeometry(d->updateGeometryHelper());
}
void ReactionsPlate::paintEvent(QPaintEvent* _event)
{
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing);
d->draw(p);
QWidget::paintEvent(_event);
}
void ReactionsPlate::showEvent(QShowEvent* _event)
{
raise();
QWidget::showEvent(_event);
}
void ReactionsPlate::mouseMoveEvent(QMouseEvent* _event)
{
QWidget::mouseMoveEvent(_event);
}
void ReactionsPlate::mousePressEvent(QMouseEvent* _event)
{
if (_event->button() == Qt::LeftButton)
d->pressPos_ = _event->pos();
_event->accept();
}
void ReactionsPlate::mouseReleaseEvent(QMouseEvent* _event)
{
if (_event->button() == Qt::LeftButton && allowedToViewReactionsList(d->item_->getContact()))
{
for (auto& item : d->items_)
{
if (item.rect_.contains(_event->pos()) && item.rect_.contains(d->pressPos_))
{
Q_EMIT reactionClicked(item.reaction_);
break;
}
}
}
d->pressPos_ = QPoint();
_event->accept();
}
void ReactionsPlate::leaveEvent(QEvent* _event)
{
}
void ReactionsPlate::onMultiselectChanged()
{
if (Utils::InterConnector::instance().isMultiselect())
hide();
else if (d->items_.size() > 0)
show();
}
}
| 28.604262 | 154 | 0.59751 | SammyEnigma |
0d5724dfa5986996aea11106ca56d2d0be617aee | 2,054 | cpp | C++ | Codigos/16-3SumClosest.cpp | BrunoHarlis/Solucoes_LeetCode | cca9b1331cbfe7d8dc8d844a810ac651a92d8c97 | [
"MIT"
] | null | null | null | Codigos/16-3SumClosest.cpp | BrunoHarlis/Solucoes_LeetCode | cca9b1331cbfe7d8dc8d844a810ac651a92d8c97 | [
"MIT"
] | null | null | null | Codigos/16-3SumClosest.cpp | BrunoHarlis/Solucoes_LeetCode | cca9b1331cbfe7d8dc8d844a810ac651a92d8c97 | [
"MIT"
] | null | null | null | //Source: https://leetcode.com/problems/3sum-closest/
//Author: Bruno Harlis
//Date: 30/04/2020
/******************************************************************************************
* PROPOSED PROBLEM
* Given an array nums of n integers and an integer target, find three integers in nums such
* that the sum is closest to target. Return the sum of the three integers.
* You may assume that each input would have exactly one solution.
*
* Exemple 1
* Input: nums = [-1,2,1,-4], target = 1
* Output: 2
*
* EFFICIENCY TEST
* Runtime: 0 ms
* Memory Usage: 9.9 MB
*****************************************************************************************/
#include <iostream>
#include <vector>
#include <algorithm>
class Solution {
public:
int threeSumClosest(std::vector<int>& nums, int target)
{
int dif{INT_MAX};
int resp{ 0 };
int sum{ 0 };
std::sort(nums.begin(), nums.end());
for (auto a{ nums.begin() }; a < nums.end() - 2; ++a)
{
auto b{ a + 1 };
auto c{ nums.end() - 1 };
while (b < c)
{
sum = *a + *b + *c;
if (sum == target) return target;
int tempDif = (sum > target) ? sum - target : target - sum;
if (tempDif < dif)
{
dif = tempDif;
resp = sum;
}
if (sum > target)
{
--c;
while (c > b && *c == (*(c + 1)))
{
--c;
}
}
else
{
++b;
while (b < c && *b == (*(b - 1)))
{
++b;
}
}
}
}
return resp;
}
};
int main()
{
std::vector<int> x{ -1,2,1,-4 };
int target{ 1 };
Solution s;
std::cout << s.threeSumClosest(x, target);
} | 26 | 92 | 0.373905 | BrunoHarlis |
0d5d22d011900ffe9b83e68d7fcc64c80ca902cb | 259 | cpp | C++ | Benchine/BenchineCore/Core/BaseGame.cpp | DatTestBench/Benchine | 7f2034dc9d486f8eae39cb5bf917012d3b234955 | [
"MIT"
] | null | null | null | Benchine/BenchineCore/Core/BaseGame.cpp | DatTestBench/Benchine | 7f2034dc9d486f8eae39cb5bf917012d3b234955 | [
"MIT"
] | null | null | null | Benchine/BenchineCore/Core/BaseGame.cpp | DatTestBench/Benchine | 7f2034dc9d486f8eae39cb5bf917012d3b234955 | [
"MIT"
] | null | null | null | #include "BenchinePCH.h"
#include "Core/BaseGame.h"
void BaseGame::BaseInitialize()
{
// User Definined Initialize
Initialize();
}
void BaseGame::BaseUpdate(const float dT)
{
SceneManager::GetInstance()->Update(dT);
// User Defined Update
Update(dT);
} | 17.266667 | 41 | 0.725869 | DatTestBench |
0d5d8f71c15c0ac407463b55c1f1a842b07ffcfa | 1,687 | cpp | C++ | Stack/ImplementStackusingQueues_225.cpp | obviouskkk/leetcode | 5d25c3080fdc9f68ae79e0f4655a474a51ff01fc | [
"BSD-3-Clause"
] | null | null | null | Stack/ImplementStackusingQueues_225.cpp | obviouskkk/leetcode | 5d25c3080fdc9f68ae79e0f4655a474a51ff01fc | [
"BSD-3-Clause"
] | null | null | null | Stack/ImplementStackusingQueues_225.cpp | obviouskkk/leetcode | 5d25c3080fdc9f68ae79e0f4655a474a51ff01fc | [
"BSD-3-Clause"
] | null | null | null | /* ***********************************************************************
> File Name: ImplementStackusingQueues_225.cpp
> Author: zzy
> Mail: 942744575@qq.com
> Created Time: Mon 08 Jul 2019 05:14:47 PM CST
********************************************************************** */
#include <stdio.h>
#include <vector>
#include <string>
#include <stdio.h>
#include <climits>
#include <queue>
#include <gtest/gtest.h>
using std::vector;
using std::string;
/*
*
* 225. 用队列实现栈
*
* 使用队列实现栈的下列操作:
*
* push(x) -- 元素 x 入栈
* pop() -- 移除栈顶元素
* top() -- 获取栈顶元素
* empty() -- 返回栈是否为空
*
*/
/*
* 队列没有栈那种来回颠倒的能力。从一个队列移动到另一个队列还是一样的
* 因此每次插入都要往最前面插。所以就需要另一个队列来回倒腾:
* 每次放入空队列,把另一个队列的元素全部移到追加到这个空队列
* 结果:原来有数的队列变空,元素都移动到 原来的空队列,新插入的元素在队首
*
*/
class MyStack {
public:
/** Initialize your data structure here. */
MyStack() {
}
/** Push element x onto stack. */
void push(int x) {
auto & st_null = A.empty() ? A : B;
st_null.push(x);
auto & st_not_null = A.empty() ? A : B;
while (!st_not_null.empty()) {
int ele = st_not_null.front();
st_not_null.pop();
st_null.push(ele);
}
}
/** Removes the element on top of the stack and returns that element. */
int pop() {
auto & st = A.empty() ? B : A;
int ele = st.front();
st.pop();
return ele;
}
/** Get the top element. */
int top() {
auto & st = A.empty() ? B : A;
return st.front();
}
/** Returns whether the stack is empty. */
bool empty() {
return A.empty() && B.empty();
}
protected:
std::queue<int> A;
std::queue<int> B;
};
TEST(testCase,test0) {
}
int main(int argc, char* argv[]) {
testing::InitGoogleTest(&argc,argv);
return RUN_ALL_TESTS();
}
| 17.572917 | 74 | 0.559573 | obviouskkk |
0d6185bf85c772eee717b669d205d60c550916cf | 683 | cpp | C++ | Codeforces/1409/D.cpp | noobie7/Codes | 4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4 | [
"MIT"
] | 2 | 2021-09-14T15:57:24.000Z | 2022-03-18T14:11:04.000Z | Codeforces/1409/D.cpp | noobie7/Codes | 4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4 | [
"MIT"
] | null | null | null | Codeforces/1409/D.cpp | noobie7/Codes | 4d8265f4b7042bd7e8c0e0402d417c7e160ae6d4 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
int sum(ll n){
int res = 0;
while(n){
res+= n%10;
n/=10;
}
return res;
}
int main(){
int t; cin>>t;
while(t--){
ll n; cin>>n;
int s; cin>>s;
if(sum(n)<=s){
cout<<0<<endl;
continue;
}
ll ans = 0;
ll pw = 1;
for(int i = 0 ; i < 18; i++){
int dig = (n/pw)%10;
ll add = pw*((10 - dig)%10);
n+=add;
ans+=add;
if(sum(n)<=s){
break;
}
pw*=10;
}
cout<<ans<<endl;
}
return 0;
} | 18.972222 | 40 | 0.358712 | noobie7 |
0d6369dbb568aebf1daa3ff253108d961ef326de | 2,916 | hxx | C++ | main/dtrans/source/os2/clipb/Os2Transferable.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 679 | 2015-01-06T06:34:58.000Z | 2022-03-30T01:06:03.000Z | main/dtrans/source/os2/clipb/Os2Transferable.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 102 | 2017-11-07T08:51:31.000Z | 2022-03-17T12:13:49.000Z | main/dtrans/source/os2/clipb/Os2Transferable.hxx | Grosskopf/openoffice | 93df6e8a695d5e3eac16f3ad5e9ade1b963ab8d7 | [
"Apache-2.0"
] | 331 | 2015-01-06T11:40:55.000Z | 2022-03-14T04:07:51.000Z | /**************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 _DTRANS_OS2_TRANSFERABLE_HXX_
#define _DTRANS_OS2_TRANSFERABLE_HXX_
#include <com/sun/star/datatransfer/XTransferable.hpp>
#ifndef _COM_SUN_STAR_LANG_XEVENTLISTENER_HDL_
#include <com/sun/star/lang/XEventListener.hpp>
#endif
#include <cppuhelper/implbase1.hxx>
#include <osl/thread.h>
#include <errno.h>
#include <uclip.h>
#define CHAR_POINTER(THE_OUSTRING) ::rtl::OUStringToOString (THE_OUSTRING, RTL_TEXTENCODING_UTF8).pData->buffer
#if OSL_DEBUG_LEVEL>0
extern "C" int debug_printf(const char *f, ...);
#else
#define debug_printf( ...)
#endif
#define CPPUTYPE_SEQSALINT8 getCppuType( (const Sequence< sal_Int8 >*) 0 )
#define CPPUTYPE_DEFAULT CPPUTYPE_SEQSALINT8
using namespace com::sun::star::uno;
HBITMAP OOoBmpToOS2Handle( Any &aAnyB);
int OS2HandleToOOoBmp( HBITMAP hbm, Sequence< sal_Int8 >* winDIBStream);
namespace os2 {
class Os2Transferable : public ::cppu::WeakImplHelper1 <
::com::sun::star::datatransfer::XTransferable >
{
HAB hAB;
::rtl::OUString clipText;
::com::sun::star::datatransfer::DataFlavor aFlavor;
::osl::Mutex m_aMutex;
::com::sun::star::uno::Reference< XInterface > m_xCreator;
public:
Os2Transferable( const ::com::sun::star::uno::Reference< XInterface >& xCreator);
virtual ~Os2Transferable();
/*
* XTransferable
*/
virtual ::com::sun::star::uno::Any SAL_CALL getTransferData( const ::com::sun::star::datatransfer::DataFlavor& aFlavor )
throw(::com::sun::star::datatransfer::UnsupportedFlavorException,
::com::sun::star::io::IOException,
::com::sun::star::uno::RuntimeException
);
virtual ::com::sun::star::uno::Sequence< ::com::sun::star::datatransfer::DataFlavor > SAL_CALL getTransferDataFlavors( )
throw(::com::sun::star::uno::RuntimeException);
virtual sal_Bool SAL_CALL isDataFlavorSupported( const ::com::sun::star::datatransfer::DataFlavor& aFlavor )
throw(::com::sun::star::uno::RuntimeException);
};
} // namespace
#endif
| 32.4 | 124 | 0.698903 | Grosskopf |
0d66d7240298fc05d53ee3e0e879d17a5781870f | 1,202 | cpp | C++ | data_structures/disjoint_union.cpp | vedantiitkgp/CP-Algorithms | 81d1a64624f8b0e918b7d5b7f8dc1e2cdcbc88b4 | [
"MIT"
] | null | null | null | data_structures/disjoint_union.cpp | vedantiitkgp/CP-Algorithms | 81d1a64624f8b0e918b7d5b7f8dc1e2cdcbc88b4 | [
"MIT"
] | null | null | null | data_structures/disjoint_union.cpp | vedantiitkgp/CP-Algorithms | 81d1a64624f8b0e918b7d5b7f8dc1e2cdcbc88b4 | [
"MIT"
] | null | null | null | // https://cp-algorithms.com/data_structures/disjoint_set_union.html
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef pair<string, string> pss;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<pii> vii;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<bool> vb;
// Path compression optimization applied and Union by size (Similar union by rank)
void swap(vi &a, vi &b)
{
vi temp;
temp = a;
a = b;
b = temp;
}
void make_set(int v, vi &parent,vi &size)
{
parent[v] = v;
size[v] = 1;
}
void find_set(int v, vi &parent)
{
if(v==parent[v]) return v;
return parent[v] = find_set(parent[v]);
}
void union_sets(int a,int b,vi &parent,vi &size)
{
a = find_set(a);
b = find_set(b);
if(a!=b)
{
if(size[a]<size[b]) swap(a,b);
parent[b] = a;
size[a]+=size[b];
}
}
// Applications
// 1. Connected components - Completing a Minimum spanning tree
// 2. Search connected components in a image.
// 3. Arpa's trick for finding long range minimum queries
// 4. Offline LCA - O(alpha(n))
// 5. Online bridge finding algorithm help | 21.087719 | 82 | 0.647255 | vedantiitkgp |
0d6799d2d6c25ceb8e8ef8d5a47b2670e85d48c9 | 2,567 | cc | C++ | src/main_perft.cc | swgillespie/apollo3 | 2cd7b613cba08c21f65be722769dcb1e2540cd3c | [
"MIT"
] | null | null | null | src/main_perft.cc | swgillespie/apollo3 | 2cd7b613cba08c21f65be722769dcb1e2540cd3c | [
"MIT"
] | null | null | null | src/main_perft.cc | swgillespie/apollo3 | 2cd7b613cba08c21f65be722769dcb1e2540cd3c | [
"MIT"
] | null | null | null | #include <cstdlib>
#include <cstring>
#include <fstream>
#include <iomanip>
#include <iostream>
#include "json.hpp"
#include "position.h"
using apollo::Color;
using apollo::Move;
using apollo::Position;
using nlohmann::json;
const char* const kIntermediateFilename = "intermediates.json";
namespace {
bool save_intermediates = false;
const char* position_fen = nullptr;
int depth = 4;
void ParseOptions(int argc, const char* argv[]) {
int i = 2;
while (i < argc) {
if (strcmp(argv[i], "-h") == 0 || strcmp(argv[i], "--help") == 0) {
std::cout << "help!" << std::endl;
std::exit(EXIT_FAILURE);
}
if (strcmp(argv[i], "--save-intermediates") == 0) {
save_intermediates = true;
i++;
continue;
}
if (strcmp(argv[i], "--depth") == 0 || strcmp(argv[i], "-d") == 0) {
i++;
if (i >= argc) {
std::cout << "expected argument for depth" << std::endl;
std::exit(EXIT_FAILURE);
}
depth = atoi(argv[i++]);
continue;
}
if (!position_fen) {
position_fen = argv[i++];
} else {
std::cout << "unexpected positional argument: " << argv[i] << std::endl;
std::exit(EXIT_FAILURE);
}
}
}
} // anonymous namespace
int Perft(Position& pos, int depth, json& document) {
if (depth == 0) {
return 1;
}
json position;
if (save_intermediates) {
position["fen"] = pos.AsFen();
}
std::vector<std::string> moves;
Color to_move = pos.SideToMove();
int nodes = 0;
for (Move mov : pos.PseudolegalMoves()) {
pos.MakeMove(mov);
if (!pos.IsCheck(to_move)) {
if (save_intermediates) {
moves.push_back(mov.AsUci());
}
nodes += Perft(pos, depth - 1, document);
}
pos.UnmakeMove();
}
if (save_intermediates) {
position["moves"] = moves;
document.push_back(position);
}
return nodes;
}
[[noreturn]] void PerftCommand(int argc, const char* argv[]) {
ParseOptions(argc, argv);
if (!position_fen) {
std::cout << "no FEN position provided" << std::endl;
std::exit(EXIT_FAILURE);
}
if (save_intermediates) {
std::cout << "saving intermediates" << std::endl;
}
json doc;
Position p(position_fen);
p.Dump(std::cout);
std::cout << std::endl;
for (int i = 1; i <= depth; i++) {
int res = Perft(p, i, doc);
std::cout << "perft(" << i << ") = " << res << std::endl;
}
if (save_intermediates) {
std::ofstream fs;
fs.open(kIntermediateFilename);
fs << std::setw(4) << doc << std::endl;
fs.close();
}
std::exit(EXIT_SUCCESS);
}
| 22.716814 | 78 | 0.580834 | swgillespie |
0d6a1c5c4ca0b2f1b23eb3d286c935b6eadc9bde | 6,013 | cpp | C++ | ql/experimental/preexperimental/oneFactorGauss.cpp | universe1987/QuantLib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 4 | 2016-03-28T15:05:23.000Z | 2020-02-17T23:05:57.000Z | ql/experimental/preexperimental/oneFactorGauss.cpp | universe1987/QuantLib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 1 | 2015-02-02T20:32:43.000Z | 2015-02-02T20:32:43.000Z | ql/experimental/preexperimental/oneFactorGauss.cpp | pcaspers/quantlib | bbb0145aff285853755b9f6ed013f53a41163acb | [
"BSD-3-Clause"
] | 10 | 2015-01-26T14:50:24.000Z | 2015-10-23T07:41:30.000Z | #include <oneFactorGauss.hpp>
using namespace std;
namespace QuantLib {
OneFactorGauss::OneFactorGauss() {
nd_ = NormalDistribution();
cnd_ = CumulativeNormalDistribution();
icn_ = InverseCumulativeNormal();
gh_= new GaussHermiteIntegration(64);
}
boost::shared_ptr<KernelDensity> OneFactorGauss::empiricalPdDensity(long numberOfObligors, double pd, double correlation, int seed, long samples) {
MersenneTwisterUniformRng mt(seed);
vector<double> sam;
double spd;
for(int i=0;i<samples;i++) {
spd=((double)sampleNumberOfDefaults(numberOfObligors,pd,correlation,mt)) / ((double)numberOfObligors);
sam.push_back(spd);
}
//return estimator with default bandwidth, can be computed by user later
return boost::shared_ptr<KernelDensity>(new KernelDensity(sam,0.05,0.01));
}
boost::shared_ptr<KernelDensity> OneFactorGauss::empiricalGordyVarDensity(long numberOfObligors, double pd, double quantile, double correlation, int seed, long samples) {
MersenneTwisterUniformRng mt(seed);
vector<double> sam;
double spd,gvar;
for(int i=0;i<samples;i++) {
spd=((double)sampleNumberOfDefaults(numberOfObligors,pd,correlation,mt)) / ((double)numberOfObligors);
if(spd>0.0&&spd<1.0) {
gvar=spd>0.0?cnd_(pow(1.0-correlation*correlation,-0.5)*icn_(spd)+pow(correlation*correlation/(1.0-correlation*correlation),0.5)*icn_(quantile)) : 0.0;
}
else {
gvar=spd==0.0?0.0:1.0;
}
sam.push_back(gvar);
}
//return estimator with default bandwidth, can be computed by user later
return boost::shared_ptr<KernelDensity>(new KernelDensity(sam,0.3,0.1));
}
double OneFactorGauss::empiricalBootstrapVariance(long numberOfObligors, double pd, double correlation, int seed, long samples) {
Array roots = gh_->x();
Array weights = gh_->weights();
double i1=0.0,i2=0.0;
double icnPd=icn_(pd);
double condPd;
double u,df;
//FILE* out=fopen("ASFR.log","a");
for(int i=0;i<roots.size();i++) {
u=roots[i]*sqrt(2.0);
df=exp(-roots[i]*roots[i]);
condPd=cnd_((icnPd-correlation*u)/sqrt(1.0-correlation*correlation));
i1+=condPd*weights[i]*df;
i2+=condPd*condPd*weights[i]*df;
}
i1/=sqrt(M_PI);
i2/=sqrt(M_PI);
//fclose(out);
return (i1-i2)/((double)numberOfObligors)+i2-i1*i1;
/*MersenneTwisterUniformRng mt(seed);
IncrementalStatistics stat1;
double spd,globalFactor,condPd,condSpr,defTime,rn;
double icnPd=icn_(pd);
int nod;
for(int i=0;i<samples;i++) {
//spd=((double)sampleNumberOfDefaults(numberOfObligors,pd,correlation,mt)) / ((double)numberOfObligors);
// fast implementation
globalFactor=icn_(mt.next().value);
condPd=cnd_((icnPd-correlation*globalFactor)/sqrt(1.0-correlation*correlation));
//condSpr=condPd<1.0 ? -log(1-condPd) : 1000.0;
nod=0;
for(int i=0;i<numberOfObligors;i++) {
rn=mt.next().value;
//defTime=condSpr>0.0 && rn<1.0 ? -log(1.0-mt.next().value)/condSpr : 100000.0;
//if(defTime<1.0) nod++;
if(rn<condPd) nod++;
}
spd=nod/((double)numberOfObligors);
stat1.add(spd);
}
//return estimator with default bandwidth, can be computed by user later
//fprintf(out,"mean=%f,var=%f\n",stat1.mean(),stat1.variance());
//fclose(out);
return stat1.variance();*/
}
boost::shared_ptr<KernelDensity> OneFactorGauss::convexityAdjGordyVarDensity(long numberOfObligors, double pd, double quantile, double correlation, bool useCorr, int seed, long samples) {
MersenneTwisterUniformRng mt(seed);
vector<double> sam;
double spd,gvar,spd2,conv;
boost::shared_ptr<KernelDensity> eg;
double A=1.0/sqrt(1.0-correlation*correlation);
double B=sqrt(correlation*correlation/(1.0-correlation*correlation))*icn_(quantile);
double icnSpd,phi1,phi1p,phi2,phi2p,alpha,alphaP,alphaPP,der2;
double m2a,m2b,m2c,m2Corr,bv2der;
double h=1E-5; // for 2nd derivative computation
for(int i=0;i<samples;i++) {
spd=((double)sampleNumberOfDefaults(numberOfObligors,pd,correlation,mt)) / ((double)numberOfObligors);
if(spd>0.0&&spd<1.0) {
gvar=spd>0.0?cnd_(pow(1.0-correlation*correlation,-0.5)*icn_(spd)+pow(correlation*correlation/(1.0-correlation*correlation),0.5)*icn_(quantile)) : 0.0;
}
else {
gvar=spd==0.0?0.0:1.0;
}
// compute convexity adjustment
// estimate variance of pd estimator and 2nd derivative
if(spd>h && spd<1.0) {
m2a=empiricalBootstrapVariance(numberOfObligors,spd-h,correlation,0,0);
m2b=empiricalBootstrapVariance(numberOfObligors,spd,correlation,0,0);
m2c=empiricalBootstrapVariance(numberOfObligors,spd+h,correlation,0,0);
if(useCorr) bv2der=(m2c-2.0*m2b+m2a)/(h*h);
else bv2der=0.0;
m2Corr=m2b-0.5*bv2der*m2b; // convexity correction for m2
//fprintf(out,"%f;%f;%f\n",m2b,bv2der,m2Corr);
// compute conv adj
icnSpd=icn_(spd);
phi1=exp(-0.5*icnSpd*icnSpd)/sqrt(2.0*M_PI);
//if(phi1>0.0) {
phi1p=-phi1*icnSpd;
alpha=A*icnSpd+B;
alphaP=A/phi1;
alphaPP=-A*phi1p/(phi1*phi1*phi1);
phi2=exp(-0.5*alpha*alpha)/sqrt(2.0*M_PI);
phi2p=-phi2*alpha;
der2=phi2p*alphaP*alphaP+phi2*alphaPP;
conv=0.5*m2Corr*der2;
//}
//else {
// conv=0.0;
//}
}
else {
conv=0.0;
}
sam.push_back(gvar-conv);
}
//return estimator with default bandwidth, can be computed by user later
return boost::shared_ptr<KernelDensity>(new KernelDensity(sam,0.3,0.1));
}
long OneFactorGauss::sampleNumberOfDefaults(long numberOfObligors, double pd, double correlation, MersenneTwisterUniformRng& mt) {
double globalFactor, condPd, condSpr, defTime, rn;
long numberOfDefaults=0;
globalFactor=icn_(mt.next().value);
condPd=cnd_((icn_(pd)-correlation*globalFactor)/sqrt(1.0-correlation*correlation));
condSpr=condPd<1.0 ? -log(1-condPd) : 1000.0;
for(int i=0;i<numberOfObligors;i++) {
rn=mt.next().value;
defTime=condSpr>0.0 && rn<1.0 ? -log(1.0-mt.next().value)/condSpr : 100000.0;
if(defTime<1.0) numberOfDefaults++;
}
return numberOfDefaults;
}
}
| 32.502703 | 188 | 0.695493 | universe1987 |
0d6c36c9db140a3c320beb1ba93be709d81f3e76 | 2,020 | cpp | C++ | rali/rali/source/video_loader_module.cpp | rsudheerk001/MIVisionX | fc7574bd58446ff9072f7e5cf4c50d989dcb6cd8 | [
"MIT"
] | 153 | 2018-12-20T19:33:15.000Z | 2022-03-30T03:51:14.000Z | rali/rali/source/video_loader_module.cpp | rsudheerk001/MIVisionX | fc7574bd58446ff9072f7e5cf4c50d989dcb6cd8 | [
"MIT"
] | 484 | 2019-01-02T23:51:58.000Z | 2022-03-31T15:52:43.000Z | rali/rali/source/video_loader_module.cpp | rsudheerk001/MIVisionX | fc7574bd58446ff9072f7e5cf4c50d989dcb6cd8 | [
"MIT"
] | 105 | 2018-12-21T00:02:38.000Z | 2022-03-25T15:44:02.000Z | /*
Copyright (c) 2019 - 2020 Advanced Micro Devices, Inc. All rights reserved.
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 "video_loader_module.h"
#ifdef RALI_VIDEO
VideoLoaderModule::VideoLoaderModule(std::shared_ptr<VideoFileNode> video_node):_video_node(std::move(video_node))
{
}
LoaderModuleStatus
VideoLoaderModule::load_next()
{
// Do nothing since call to process graph suffices (done externally)
return LoaderModuleStatus::OK;
}
void
VideoLoaderModule::set_output_image (Image* output_image)
{
}
void
VideoLoaderModule::initialize(ReaderConfig reader_cfg, DecoderConfig decoder_cfg, RaliMemType mem_type, unsigned batch_size)
{
}
size_t VideoLoaderModule::count()
{
// TODO: use FFMPEG to find the total number of frames and keep counting
// how many times laod_next() is called successfully, subtract them and
// that would be the count of frames remained to be decoded
return 9999999;
}
void VideoLoaderModule::reset()
{
// Functionality not there yet in the OpenVX API
}
#endif | 34.237288 | 124 | 0.784158 | rsudheerk001 |
0d6f1615cafefe7c90f44f151a636a3b692d9ffc | 1,472 | cc | C++ | ash/sticky_keys/sticky_keys_overlay_unittest.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2015-08-13T21:04:58.000Z | 2015-08-13T21:04:58.000Z | ash/sticky_keys/sticky_keys_overlay_unittest.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2018-02-10T21:00:08.000Z | 2018-03-20T05:09:50.000Z | ash/sticky_keys/sticky_keys_overlay_unittest.cc | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T06:34:36.000Z | 2020-11-04T06:34:36.000Z | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/sticky_keys/sticky_keys_overlay.h"
#include "ash/shell.h"
#include "ash/sticky_keys/sticky_keys_controller.h"
#include "ash/test/ash_test_base.h"
#include "ui/events/event.h"
namespace ash {
class StickyKeysOverlayTest : public test::AshTestBase {
public:
StickyKeysOverlayTest() {}
virtual ~StickyKeysOverlayTest() {}
};
TEST_F(StickyKeysOverlayTest, OverlayVisibility) {
StickyKeysOverlay overlay;
EXPECT_FALSE(overlay.is_visible());
overlay.Show(true);
EXPECT_TRUE(overlay.is_visible());
}
TEST_F(StickyKeysOverlayTest, ModifierKeyState) {
StickyKeysOverlay overlay;
overlay.SetModifierKeyState(ui::EF_SHIFT_DOWN, STICKY_KEY_STATE_DISABLED);
overlay.SetModifierKeyState(ui::EF_ALT_DOWN, STICKY_KEY_STATE_LOCKED);
overlay.SetModifierKeyState(ui::EF_CONTROL_DOWN, STICKY_KEY_STATE_ENABLED);
EXPECT_EQ(STICKY_KEY_STATE_DISABLED,
overlay.GetModifierKeyState(ui::EF_SHIFT_DOWN));
EXPECT_EQ(STICKY_KEY_STATE_LOCKED,
overlay.GetModifierKeyState(ui::EF_ALT_DOWN));
EXPECT_EQ(STICKY_KEY_STATE_ENABLED,
overlay.GetModifierKeyState(ui::EF_CONTROL_DOWN));
}
// Additional sticky key overlay tests that depend on chromeos::EventRewriter
// are now in chrome/browser/chromeos/events/event_rewriter_unittest.cc .
} // namespace ash
| 32.711111 | 77 | 0.780571 | Fusion-Rom |
0d6f3493d31cf0a9e3d9ff78a25ae5a42e803ab0 | 8,813 | cpp | C++ | src/Map.cpp | xDUDSSx/bomberman | 693a6aae2dba44662ceb1599d1cbdb47f1a9240c | [
"MIT"
] | 1 | 2022-01-14T02:12:01.000Z | 2022-01-14T02:12:01.000Z | src/Map.cpp | xDUDSSx/bomberman | 693a6aae2dba44662ceb1599d1cbdb47f1a9240c | [
"MIT"
] | null | null | null | src/Map.cpp | xDUDSSx/bomberman | 693a6aae2dba44662ceb1599d1cbdb47f1a9240c | [
"MIT"
] | 1 | 2021-02-02T19:31:12.000Z | 2021-02-02T19:31:12.000Z | #include "Map.h"
#include "Tile.h"
#include "Constants.h"
#include "Game.h"
#include "MapData.h"
#include "EntityManager.h"
#include <iostream>
#include <sstream>
#include "Utils.h"
Map::Map() = default;
Map::Map(const Map &map) {
*this = map;
}
Map& Map::operator=(const Map& map) {
if (this != &map) {
this->mapWidth = map.mapWidth;
this->mapHeight = map.mapHeight;
this->tileSize = map.tileSize;
this->mapTileWidth = map.mapTileWidth;
this->mapTileHeight = map.mapTileHeight;
fillWithEmptyPointers();
for (int y = 0; y < mapTileHeight; y++) {
for (int x = 0; x < mapTileWidth; x++) {
tiles[x][y] = std::make_shared<Tile>(Tile(*map.tiles[x][y]));
}
}
}
return *this;
}
void Map::generate(int pMapWidth, int pMapHeight, Game* game) {
mapWidth = pMapWidth;
mapHeight = pMapHeight;
tileSize = Constants::TILE_SIZE;
mapTileWidth = mapWidth / tileSize;
mapTileHeight = mapHeight / tileSize;
fillWithEmptyPointers();
//Generating a default map
for (int y = 0; y < mapTileHeight; y++) {
for (int x = 0; x < mapTileWidth; x++) {
auto newTile = std::make_shared<Tile>(Tile(x * tileSize, y * tileSize));;
if (!((x < 3 && y < 3) || (x > mapTileWidth-4 && y > mapTileHeight-4))) {
if (Utils::getRandomIntNumberInRange(0, 100) <= 80) {
newTile->setWall(true);
}
}
if (x % 2 == 0 && y % 2 == 0) {
newTile->setWall(true);
newTile->setIndestructible(true);
}
if (x == 0 || y == 0 || x == mapTileWidth - 1 || y == mapTileHeight - 1) {
newTile->setWall(true);
newTile->setIndestructible(true);
newTile->setEdgeWall(true);
}
tiles[x][y] = newTile;
game->entityManager->addEntity(newTile);
}
}
//Default players
game->registerPlayer('A', getTileAtCoordinates(Constants::TILE_SIZE, Constants::TILE_SIZE));
game->registerPlayer('B', getTileAtCoordinates(mapWidth - Constants::TILE_SIZE * 2, mapHeight - Constants::TILE_SIZE * 2));
}
bool Map::generateFromMapData(MapData* mapData, Game* game) {
try {
mapTileWidth = mapData->tileWidth;
mapTileHeight = mapData->tileHeight;
mapWidth = mapData->pixelWidth;
mapHeight = mapData->pixelHeight;
tileSize = mapData->pixelWidth / mapData->tileWidth;
fillWithEmptyPointers();
//Parsing map data symbols
for (int y = 0; y < mapTileHeight; y++) {
//Making sure that the lines have the same width
std::string line = mapData->lines[y];
if (static_cast<int>(line.length()) != mapTileWidth) {
throw std::runtime_error("Map data map width is not consistent!");
}
//Parsing characters in a line
for (int x = 0; x < mapTileWidth; x++) {
const char c = line[x];
parseCharacterAndLoadTile(x, y, c, game);
}
}
} catch (std::runtime_error& error) {
std::cerr << "Failed to generate map from map data! " << error.what() << std::endl;
return false;
}
return true;
}
void Map::render(SDL_Renderer * renderer) {
for (int y = 0; y < mapTileHeight; y++) {
for (int x = 0; x < mapTileWidth; x++) {
tiles[x][y]->render(renderer);
}
}
}
Tile* Map::getTileAtCoordinates(const int x, const int y) const {
if (x < 0 || y < 0 || x >= mapWidth || y >= mapHeight) {
return nullptr;
}
Tile* tilePtr = tiles[x / tileSize][y / tileSize].get();
return tilePtr;
}
Tile* Map::getTileAtIndexes(int x, int y) const {
if (x < 0 || y < 0 || x >= mapTileWidth || y >= mapTileHeight) {
return nullptr;
}
Tile* tilePtr = tiles[x][y].get();
return tilePtr;
}
Tile* Map::getTileAbove(Tile * tile) const {
return getTileAtCoordinates(tile->getCenterX(), tile->getCenterY() - tileSize);
}
Tile* Map::getTileLeft(Tile * tile) const {
return getTileAtCoordinates(tile->getCenterX() - tileSize, tile->getCenterY());
}
Tile* Map::getTileRight(Tile * tile) const {
return getTileAtCoordinates(tile->getCenterX() + tileSize, tile->getCenterY());
}
Tile* Map::getTileBelow(Tile * tile) const {
return getTileAtCoordinates(tile->getCenterX(), tile->getCenterY() + tileSize);
}
Tile* Map::getTileTopLeftCorner(Tile* tile) const {
return getTileAtCoordinates(tile->getCenterX() - tileSize, tile->getCenterY() - tileSize);
}
Tile* Map::getTileBottomLeftCorner(Tile* tile) const {
return getTileAtCoordinates(tile->getCenterX() - tileSize, tile->getCenterY() + tileSize);
}
Tile* Map::getTileBottomRightCorner(Tile* tile) const {
return getTileAtCoordinates(tile->getCenterX() + tileSize, tile->getCenterY() + tileSize);
}
Tile* Map::getTileTopRightCorner(Tile* tile) const {
return getTileAtCoordinates(tile->getCenterX() + tileSize, tile->getCenterY() - tileSize);
}
std::vector<Tile*> Map::getNeighbourTiles(Tile* tile) const {
std::vector<Tile*> neighbours = std::vector<Tile*>(8, nullptr);
neighbours[0] = getTileAbove(tile);
neighbours[1] = getTileTopLeftCorner(tile);
neighbours[2] = getTileLeft(tile);
neighbours[3] = getTileBottomLeftCorner(tile);
neighbours[4] = getTileBelow(tile);
neighbours[5] = getTileBottomRightCorner(tile);
neighbours[6] = getTileRight(tile);
neighbours[7] = getTileTopRightCorner(tile);
return neighbours;
}
std::vector<Tile*> Map::getExistingNeighbourTiles(Tile* tile, bool ignoreCorners = false) const {
std::vector<Tile*> neighbours;
if (Tile* t = getTileAbove(tile)) neighbours.push_back(t);
if (Tile* t = getTileTopLeftCorner(tile)) {
if (!ignoreCorners) neighbours.push_back(t);
}
if (Tile* t = getTileLeft(tile)) neighbours.push_back(t);
if (Tile* t = getTileBottomLeftCorner(tile)) {
if (!ignoreCorners) neighbours.push_back(t);
}
if (Tile* t = getTileBelow(tile)) neighbours.push_back(t);
if (Tile* t = getTileBottomRightCorner(tile)) {
if (!ignoreCorners) neighbours.push_back(t);
}
if (Tile* t = getTileRight(tile)) neighbours.push_back(t);
if (Tile* t = getTileTopRightCorner(tile)) {
if (!ignoreCorners) neighbours.push_back(t);
}
return neighbours;
}
std::vector<Tile*> Map::getWalkableNeighbourTiles(Tile* tile, bool ignoreCorners = false) const {
std::vector<Tile*> neighbours;
for (int i = 0; i < 8; i++) {
Tile* t = nullptr;
switch (i) {
case 0: t = getTileAbove(tile); break;
case 1: if (!ignoreCorners) t = getTileTopLeftCorner(tile); break;
case 2: t = getTileLeft(tile); break;
case 3: if (!ignoreCorners) t = getTileBottomLeftCorner(tile); break;
case 4: t = getTileBelow(tile); break;
case 5: if (!ignoreCorners) t = getTileBottomRightCorner(tile); break;
case 6: t = getTileRight(tile); break;
case 7: if (!ignoreCorners) t = getTileTopRightCorner(tile); break;
}
if (t && t->isOverrideWalkable()) {
neighbours.push_back(t);
} else
if (t && !t->isWall() && !t->isDangerous() && !t->isBombermanPresent()) {
neighbours.push_back(t);
}
}
return neighbours;
}
const std::vector<std::vector<std::shared_ptr<Tile>>>& Map::getTiles() const {
return tiles;
}
void Map::parseCharacterAndLoadTile(const int x, const int y, const char c, Game* game) {
switch (c) {
case 'X':
{
auto newTile = std::make_shared<Tile>(Tile(x * tileSize, y * tileSize));;
newTile->setWall(true);
newTile->setIndestructible(true);
tiles[x][y] = newTile;
game->entityManager->addEntity(newTile);
break;
}
case 'O':
{
auto newTile = std::make_shared<Tile>(Tile(x * tileSize, y * tileSize));;
newTile->setWall(true);
newTile->setIndestructible(true);
newTile->setEdgeWall(true);
tiles[x][y] = newTile;
game->entityManager->addEntity(newTile);
break;
}
case 'o':
{
auto newTile = std::make_shared<Tile>(Tile(x * tileSize, y * tileSize));;
newTile->setWall(true);
tiles[x][y] = newTile;
game->entityManager->addEntity(newTile);
break;
}
case '-':
{
auto newTile = std::make_shared<Tile>(Tile(x * tileSize, y * tileSize));;
tiles[x][y] = newTile;
game->entityManager->addEntity(newTile);
break;
}
case 'c':
{
auto newTile = std::make_shared<Tile>(Tile(x * tileSize, y * tileSize));;
tiles[x][y] = newTile;
game->entityManager->addEntity(newTile);
game->registerComputer(newTile.get());
break;
}
case 'A':
{
auto newTile = std::make_shared<Tile>(Tile(x * tileSize, y * tileSize));;
tiles[x][y] = newTile;
game->entityManager->addEntity(newTile);
game->registerPlayer('A', newTile.get());
break;
}
case 'B':
{
auto newTile = std::make_shared<Tile>(Tile(x * tileSize, y * tileSize));;
tiles[x][y] = newTile;
game->entityManager->addEntity(newTile);
game->registerPlayer('B', newTile.get());
break;
}
default:
std::ostringstream oss;
oss << "Invalid map character ('" << c << "') at row:column " << x << ":" << y << std::endl;
throw std::runtime_error(oss.str());
}
}
void Map::fillWithEmptyPointers() {
for (int i = 0; i < mapTileWidth; i++) {
tiles.push_back(std::vector<std::shared_ptr<Tile>>(mapTileHeight, std::shared_ptr<Tile>()));
}
} | 29.773649 | 124 | 0.662998 | xDUDSSx |
0d729f3d3e2f57eec981b42bebd09c63a0404270 | 1,004 | cpp | C++ | chapter13/ex03_arrow.cpp | ClassAteam/stroustrup-ppp | ea9e85d4ea9890038eb5611c3bc82734c8706ce7 | [
"MIT"
] | 124 | 2018-06-23T10:16:56.000Z | 2022-03-19T15:16:12.000Z | chapter13/ex03_arrow.cpp | therootfolder/stroustrup-ppp | b1e936c9a67b9205fdc9712c42496b45200514e2 | [
"MIT"
] | 23 | 2018-02-08T20:57:46.000Z | 2021-10-08T13:58:29.000Z | chapter13/ex03_arrow.cpp | ClassAteam/stroustrup-ppp | ea9e85d4ea9890038eb5611c3bc82734c8706ce7 | [
"MIT"
] | 65 | 2019-05-27T03:05:56.000Z | 2022-03-26T03:43:05.000Z | #include "../GUI/Simple_window.h"
#include "../GUI/Graph.h"
#include "./Arrow.h"
#include <string>
#include <iostream>
using namespace Graph_lib;
int main()
try {
// Window
const Point tl {100, 100};
Simple_window win {tl, 600, 400, "Chapter 12 Ex 3"};
Arrow a1 {Point{100, 100}, Point{250, 200}};
win.attach(a1);
Arrow a2 {Point{500, 300}, Point{500, 100}};
a2.set_color(Color::dark_green);
win.attach(a2);
Arrow a3 {Point{525, 100}, Point{525, 300}};
a3.set_color(Color::blue);
win.attach(a3);
Arrow a4 {Point{300, 50}, Point{100, 300}};
a4.set_color(Color::red);
win.attach(a4);
win.wait_for_button();
}
catch(exception& e) {
cerr << "exception: " << e.what() << '\n';
return 1;
}
catch(...) {
cerr << "error\n";
return 2;
}
/* Compile command
g++ -w -Wall -std=c++11 ../GUI/Graph.cpp ../GUI/Window.cpp ../GUI/GUI.cpp ../GUI/Simple_window.cpp Arrow.cpp ex03_arrow.cpp `fltk-config --ldflags --use-images` -o a.out
*/
| 22.818182 | 169 | 0.605578 | ClassAteam |
0d730f69c1a1a9e1651ac8a1ba1a5cb1be303c01 | 597 | cpp | C++ | hackerrank.com/crush/main.cpp | bepec/challenge | cf2d4fcf11a9a1724b6f620fdda86afbb1ba9ddc | [
"MIT"
] | null | null | null | hackerrank.com/crush/main.cpp | bepec/challenge | cf2d4fcf11a9a1724b6f620fdda86afbb1ba9ddc | [
"MIT"
] | null | null | null | hackerrank.com/crush/main.cpp | bepec/challenge | cf2d4fcf11a9a1724b6f620fdda86afbb1ba9ddc | [
"MIT"
] | null | null | null | #include <cstdio>
using namespace std;
#define out if(1)cout
#define min(a,b) (((a)<(b))?(a):(b))
#define max(a,b) (((a)>(b))?(a):(b))
#define abs(a) (((a)<0)?(-(a)):(a))
static const int MAXN = 10000001;
typedef long long int i64;
static i64 ar[MAXN];
int main()
{
ios::sync_with_stdio(false);
int N, M;
scanf("%d %d", &N, &M);
for (int i = 0; i < M; i++) {
int a, b, k;
scanf("%d %d %d", &a, &b, &k);
ar[a] += k;
ar[b+1] -= k;
}
i64 cur = 0;
i64 max = 0;
for (int i = 1; i <= N; i++) {
cur += ar[i];
if (cur > max) max = cur;
}
printf("%lld\n", max);
return 0;
}
| 16.135135 | 37 | 0.499162 | bepec |
0d7dccb58719fb31c6c88506b2609791bf5806be | 7,872 | cpp | C++ | Engine/Source/Editor/PropertyEditor/Private/UserInterface/PropertyEditor/SPropertyEditorCombo.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | 1 | 2022-01-29T18:36:12.000Z | 2022-01-29T18:36:12.000Z | Engine/Source/Editor/PropertyEditor/Private/UserInterface/PropertyEditor/SPropertyEditorCombo.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | Engine/Source/Editor/PropertyEditor/Private/UserInterface/PropertyEditor/SPropertyEditorCombo.cpp | windystrife/UnrealEngine_NVIDIAGameWork | b50e6338a7c5b26374d66306ebc7807541ff815e | [
"MIT"
] | null | null | null | // Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#include "UserInterface/PropertyEditor/SPropertyEditorCombo.h"
#include "IDocumentation.h"
#include "PropertyEditorHelpers.h"
#include "UserInterface/PropertyEditor/SPropertyComboBox.h"
#define LOCTEXT_NAMESPACE "PropertyEditor"
static int32 FindEnumValueIndex(UEnum* Enum, FString const& ValueString)
{
int32 Index = INDEX_NONE;
for(int32 ValIndex = 0; ValIndex < Enum->NumEnums(); ++ValIndex)
{
FString const EnumName = Enum->GetNameStringByIndex(ValIndex);
FString const DisplayName = Enum->GetDisplayNameTextByIndex(ValIndex).ToString();
if (DisplayName.Len() > 0)
{
if (DisplayName == ValueString)
{
Index = ValIndex;
break;
}
}
if (EnumName == ValueString)
{
Index = ValIndex;
break;
}
}
return Index;
}
void SPropertyEditorCombo::GetDesiredWidth( float& OutMinDesiredWidth, float& OutMaxDesiredWidth )
{
OutMinDesiredWidth = 125.0f;
OutMaxDesiredWidth = 400.0f;
}
bool SPropertyEditorCombo::Supports( const TSharedRef< class FPropertyEditor >& InPropertyEditor )
{
const TSharedRef< FPropertyNode > PropertyNode = InPropertyEditor->GetPropertyNode();
const UProperty* Property = InPropertyEditor->GetProperty();
int32 ArrayIndex = PropertyNode->GetArrayIndex();
if( ((Property->IsA(UByteProperty::StaticClass()) && Cast<const UByteProperty>(Property)->Enum)
|| Property->IsA(UEnumProperty::StaticClass())
|| (Property->IsA(UStrProperty::StaticClass()) && Property->HasMetaData(TEXT("Enum")))
)
&& ( ( ArrayIndex == -1 && Property->ArrayDim == 1 ) || ( ArrayIndex > -1 && Property->ArrayDim > 0 ) ) )
{
return true;
}
return false;
}
void SPropertyEditorCombo::Construct( const FArguments& InArgs, const TSharedPtr< class FPropertyEditor >& InPropertyEditor )
{
PropertyEditor = InPropertyEditor;
PropertyHandle = InArgs._PropertyHandle;
TAttribute<FText> TooltipAttribute;
if (PropertyEditor.IsValid())
{
PropertyHandle = PropertyEditor->GetPropertyHandle();
TooltipAttribute = TAttribute<FText>::Create(TAttribute<FText>::FGetter::CreateSP(PropertyEditor.ToSharedRef(), &FPropertyEditor::GetValueAsText));
}
TArray<TSharedPtr<FString>> ComboItems;
TArray<bool> Restrictions;
TArray<TSharedPtr<SToolTip>> RichToolTips;
OnGetComboBoxStrings = InArgs._OnGetComboBoxStrings;
OnGetComboBoxValue = InArgs._OnGetComboBoxValue;
OnComboBoxValueSelected = InArgs._OnComboBoxValueSelected;
GenerateComboBoxStrings(ComboItems, RichToolTips, Restrictions);
SAssignNew(ComboBox, SPropertyComboBox)
.Font( InArgs._Font )
.RichToolTipList( RichToolTips )
.ComboItemList( ComboItems )
.RestrictedList( Restrictions )
.OnSelectionChanged( this, &SPropertyEditorCombo::OnComboSelectionChanged )
.OnComboBoxOpening( this, &SPropertyEditorCombo::OnComboOpening )
.VisibleText( this, &SPropertyEditorCombo::GetDisplayValueAsString )
.ToolTipText( TooltipAttribute );
ChildSlot
[
ComboBox.ToSharedRef()
];
SetEnabled( TAttribute<bool>( this, &SPropertyEditorCombo::CanEdit ) );
}
FString SPropertyEditorCombo::GetDisplayValueAsString() const
{
if (OnGetComboBoxValue.IsBound())
{
return OnGetComboBoxValue.Execute();
}
else if (PropertyEditor.IsValid())
{
return (bUsesAlternateDisplayValues) ? PropertyEditor->GetValueAsDisplayString() : PropertyEditor->GetValueAsString();
}
else
{
FString ValueString;
if (bUsesAlternateDisplayValues)
{
PropertyHandle->GetValueAsDisplayString(ValueString);
}
else
{
PropertyHandle->GetValueAsFormattedString(ValueString);
}
return ValueString;
}
}
void SPropertyEditorCombo::GenerateComboBoxStrings( TArray< TSharedPtr<FString> >& OutComboBoxStrings, TArray<TSharedPtr<SToolTip>>& RichToolTips, TArray<bool>& OutRestrictedItems )
{
if (OnGetComboBoxStrings.IsBound())
{
OnGetComboBoxStrings.Execute(OutComboBoxStrings, RichToolTips, OutRestrictedItems);
return;
}
TArray<FText> BasicTooltips;
bUsesAlternateDisplayValues = PropertyHandle->GeneratePossibleValues(OutComboBoxStrings, BasicTooltips, OutRestrictedItems);
// For enums, look for rich tooltip information
if(PropertyHandle.IsValid())
{
if(const UProperty* Property = PropertyHandle->GetProperty())
{
UEnum* Enum = nullptr;
if(const UByteProperty* ByteProperty = Cast<UByteProperty>(Property))
{
Enum = ByteProperty->Enum;
}
else if(const UEnumProperty* EnumProperty = Cast<UEnumProperty>(Property))
{
Enum = EnumProperty->GetEnum();
}
if(Enum)
{
TArray<FName> AllowedPropertyEnums = PropertyEditorHelpers::GetValidEnumsFromPropertyOverride(Property, Enum);
// Get enum doc link (not just GetDocumentationLink as that is the documentation for the struct we're in, not the enum documentation)
FString DocLink = PropertyEditorHelpers::GetEnumDocumentationLink(Property);
for(int32 EnumIdx = 0; EnumIdx < Enum->NumEnums() - 1; ++EnumIdx)
{
FString Excerpt = Enum->GetNameStringByIndex(EnumIdx);
bool bShouldBeHidden = Enum->HasMetaData(TEXT("Hidden"), EnumIdx) || Enum->HasMetaData(TEXT("Spacer"), EnumIdx);
if(!bShouldBeHidden && AllowedPropertyEnums.Num() != 0)
{
bShouldBeHidden = AllowedPropertyEnums.Find(Enum->GetNameByIndex(EnumIdx)) == INDEX_NONE;
}
if (!bShouldBeHidden)
{
bShouldBeHidden = PropertyHandle->IsHidden(Excerpt);
}
if(!bShouldBeHidden)
{
RichToolTips.Add(IDocumentation::Get()->CreateToolTip(MoveTemp(BasicTooltips[EnumIdx]), nullptr, DocLink, MoveTemp(Excerpt)));
}
}
}
}
}
}
void SPropertyEditorCombo::OnComboSelectionChanged( TSharedPtr<FString> NewValue, ESelectInfo::Type SelectInfo )
{
if ( NewValue.IsValid() )
{
SendToObjects( *NewValue );
}
}
void SPropertyEditorCombo::OnComboOpening()
{
TArray<TSharedPtr<FString>> ComboItems;
TArray<TSharedPtr<SToolTip>> RichToolTips;
TArray<bool> Restrictions;
GenerateComboBoxStrings(ComboItems, RichToolTips, Restrictions);
ComboBox->SetItemList(ComboItems, RichToolTips, Restrictions);
// try and re-sync the selection in the combo list in case it was changed since Construct was called
// this would fail if the displayed value doesn't match the equivalent value in the combo list
FString CurrentDisplayValue = GetDisplayValueAsString();
ComboBox->SetSelectedItem(CurrentDisplayValue);
}
void SPropertyEditorCombo::SendToObjects( const FString& NewValue )
{
FString Value = NewValue;
if (OnComboBoxValueSelected.IsBound())
{
OnComboBoxValueSelected.Execute(NewValue);
}
else if (PropertyHandle.IsValid())
{
UProperty* Property = PropertyHandle->GetProperty();
if (bUsesAlternateDisplayValues && !Property->IsA(UStrProperty::StaticClass()))
{
// currently only enum properties can use alternate display values; this
// might change, so assert here so that if support is expanded to other
// property types without updating this block of code, we'll catch it quickly
UEnum* Enum = nullptr;
if (UByteProperty* ByteProperty = Cast<UByteProperty>(Property))
{
Enum = ByteProperty->Enum;
}
else if (UEnumProperty* EnumProperty = Cast<UEnumProperty>(Property))
{
Enum = EnumProperty->GetEnum();
}
check(Enum != nullptr);
const int32 Index = FindEnumValueIndex(Enum, NewValue);
check(Index != INDEX_NONE);
Value = Enum->GetNameStringByIndex(Index);
FText ToolTipValue = Enum->GetToolTipTextByIndex(Index);
FText ToolTipText = Property->GetToolTipText();
if (!ToolTipValue.IsEmpty())
{
ToolTipText = FText::Format(FText::FromString(TEXT("{0}\n\n{1}")), ToolTipText, ToolTipValue);
}
SetToolTipText(ToolTipText);
}
PropertyHandle->SetValueFromFormattedString(Value);
}
}
bool SPropertyEditorCombo::CanEdit() const
{
return PropertyEditor.IsValid() ? !PropertyEditor->IsEditConst() : true;
}
#undef LOCTEXT_NAMESPACE
| 30.045802 | 181 | 0.744284 | windystrife |
0d7e5319b22f5592b0f6282cfc140da11673585c | 871 | cpp | C++ | _includes/code/max-area-of-island/solution.cpp | rajat19/interview-questions | cb1fa382a76f2f287f1c12dd3d1fca9bfb7fa311 | [
"MIT"
] | null | null | null | _includes/code/max-area-of-island/solution.cpp | rajat19/interview-questions | cb1fa382a76f2f287f1c12dd3d1fca9bfb7fa311 | [
"MIT"
] | 2 | 2022-03-01T06:30:35.000Z | 2022-03-13T07:05:50.000Z | _includes/code/max-area-of-island/solution.cpp | rajat19/interview-questions | cb1fa382a76f2f287f1c12dd3d1fca9bfb7fa311 | [
"MIT"
] | 1 | 2022-02-09T12:13:36.000Z | 2022-02-09T12:13:36.000Z | class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int n = grid.size(), m = grid[0].size();
int mx = 0;
int count[1] = {0};
for(int i=0; i<n; i++) {
for(int j = 0; j<m; j++) {
if (grid[i][j] == 1) {
count[0] = 0;
dfs(grid, n, m, i, j, count);
mx = max(count[0], mx);
}
}
}
return mx;
}
void dfs(vector<vector<int>> &grid, int n, int m, int x, int y, int* count) {
count[0]++;
grid[x][y] = 2;
int dir[5] = {-1,0,1,0,-1};
for(int i=0; i<4; i++) {
int nx = x+dir[i], ny = y+dir[i+1];
if(nx>=0 && ny>=0 && nx<n && ny <m && grid[nx][ny] == 1) {
dfs(grid,n,m,nx,ny,count);
}
}
}
}; | 29.033333 | 81 | 0.360505 | rajat19 |
0d7f4096f8519e8578083bcd259d40a0c43da262 | 3,900 | cpp | C++ | CodeXL/AMDTApplicationFramework/src/afGlobalVariableChangedEvent.cpp | jeongjoonyoo/CodeXL | ea6d623d0530aa3a862ef0bf60ad2923a2f8f8a5 | [
"MIT"
] | 1,025 | 2016-04-19T21:36:08.000Z | 2020-04-26T05:12:53.000Z | CodeXL/AMDTApplicationFramework/src/afGlobalVariableChangedEvent.cpp | jeongjoonyoo/CodeXL | ea6d623d0530aa3a862ef0bf60ad2923a2f8f8a5 | [
"MIT"
] | 244 | 2016-04-20T02:05:43.000Z | 2020-04-29T17:40:49.000Z | CodeXL/AMDTApplicationFramework/src/afGlobalVariableChangedEvent.cpp | jeongjoonyoo/CodeXL | ea6d623d0530aa3a862ef0bf60ad2923a2f8f8a5 | [
"MIT"
] | 161 | 2016-04-20T03:23:53.000Z | 2020-04-14T01:46:55.000Z | //==================================================================================
// Copyright (c) 2016 , Advanced Micro Devices, Inc. All rights reserved.
//
/// \author AMD Developer Tools Team
/// \file afGlobalVariableChangedEvent.cpp
///
//==================================================================================
// Infra:
#include <AMDTOSWrappers/Include/osOSDefinitions.h>
#include <AMDTOSWrappers/Include/osChannel.h>
#include <AMDTOSWrappers/Include/osChannelOperators.h>
// Local:
#include <AMDTApplicationFramework/Include/afGlobalVariableChangedEvent.h>
// ---------------------------------------------------------------------------
// Name: afGlobalVariableChangedEvent::afGlobalVariableChangedEvent
// Description: Constructor.
// Arguments: variableId - The id of the global variable that was changed.
// Author: Yaki Tebeka
// Date: 1/7/2004
// ---------------------------------------------------------------------------
afGlobalVariableChangedEvent::afGlobalVariableChangedEvent(GlobalVariableId variableId)
: _changedVariableId(variableId)
{
}
// ---------------------------------------------------------------------------
// Name: afGlobalVariableChangedEvent::type
// Description: Returns my transferable object type.
// Author: Uri Shomroni
// Date: 11/8/2009
// ---------------------------------------------------------------------------
osTransferableObjectType afGlobalVariableChangedEvent::type() const
{
return OS_TOBJ_ID_GLOBAL_VARIABLE_CHANGED_EVENT;
}
// ---------------------------------------------------------------------------
// Name: afGlobalVariableChangedEvent::writeSelfIntoChannel
// Description: Writes this class data into a communication channel
// Return Val: bool - Success / failure.
// Author: Uri Shomroni
// Date: 11/8/2009
// ---------------------------------------------------------------------------
bool afGlobalVariableChangedEvent::writeSelfIntoChannel(osChannel& ipcChannel) const
{
// Write the variable ID:
ipcChannel << (gtInt32)_changedVariableId;
// Call my parent class's version of this function:
bool retVal = apEvent::writeSelfIntoChannel(ipcChannel);
return retVal;
}
// ---------------------------------------------------------------------------
// Name: afGlobalVariableChangedEvent::readSelfFromChannel
// Description: Reads this class data from a communication channel
// Return Val: bool - Success / failure.
// Author: Uri Shomroni
// Date: 11/8/2009
// ---------------------------------------------------------------------------
bool afGlobalVariableChangedEvent::readSelfFromChannel(osChannel& ipcChannel)
{
// Read the variable ID:
gtInt32 changedVariableIdAsInt32 = CHOSEN_CONTEXT_ID;
ipcChannel >> changedVariableIdAsInt32;
_changedVariableId = (GlobalVariableId)changedVariableIdAsInt32;
// Call my parent class's version of this function:
bool retVal = apEvent::readSelfFromChannel(ipcChannel);
return retVal;
}
// ---------------------------------------------------------------------------
// Name: afGlobalVariableChangedEvent::type
// Description: Returns my event type.
// Author: Yaki Tebeka
// Date: 1/7/2004
// ---------------------------------------------------------------------------
apEvent::EventType afGlobalVariableChangedEvent::eventType() const
{
return apEvent::APP_GLOBAL_VARIABLE_CHANGED;
}
// ---------------------------------------------------------------------------
// Name: afGlobalVariableChangedEvent::clone
// Description: Returns a copy of self.
// Author: Yaki Tebeka
// Date: 1/7/2004
// ---------------------------------------------------------------------------
apEvent* afGlobalVariableChangedEvent::clone() const
{
return new afGlobalVariableChangedEvent(_changedVariableId);
}
| 38.613861 | 87 | 0.529231 | jeongjoonyoo |
0d80b0bae4b066968105b537e4245878c1aee91a | 3,156 | hpp | C++ | include/GTGE/Physics/CollisionShapeTypes.hpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 31 | 2015-03-19T08:44:48.000Z | 2021-12-15T20:52:31.000Z | include/GTGE/Physics/CollisionShapeTypes.hpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 19 | 2015-07-09T09:02:44.000Z | 2016-06-09T03:51:03.000Z | include/GTGE/Physics/CollisionShapeTypes.hpp | mackron/GTGameEngine | 380d1e01774fe6bc2940979e4e5983deef0bf082 | [
"BSD-3-Clause"
] | 3 | 2017-10-04T23:38:18.000Z | 2022-03-07T08:27:13.000Z | // Copyright (C) 2011 - 2014 David Reid. See included LICENCE.
#ifndef GT_CollisionShapeTypes
#define GT_CollisionShapeTypes
#include <BulletCollision/CollisionShapes/btCylinderShape.h>
#include <BulletCollision/CollisionShapes/btCapsuleShape.h>
namespace GT
{
enum CollisionShapeType
{
CollisionShapeType_None = 0,
CollisionShapeType_Box = 1,
CollisionShapeType_Sphere = 2,
CollisionShapeType_Ellipsoid = 3,
CollisionShapeType_CylinderX = 4,
CollisionShapeType_CylinderY = 5,
CollisionShapeType_CylinderZ = 6,
CollisionShapeType_CapsuleX = 7,
CollisionShapeType_CapsuleY = 8,
CollisionShapeType_CapsuleZ = 9,
CollisionShapeType_ConvexHull = 10,
CollisionShapeType_ModelConvexHulls = 11,
};
inline CollisionShapeType GetCollisionShapeType(const btCollisionShape* shape)
{
if (shape != nullptr)
{
switch (shape->getShapeType())
{
case BOX_SHAPE_PROXYTYPE:
{
return CollisionShapeType_Box;
}
case SPHERE_SHAPE_PROXYTYPE:
{
return CollisionShapeType_Sphere;
}
case CUSTOM_CONVEX_SHAPE_TYPE:
{
return CollisionShapeType_Ellipsoid;
}
case CYLINDER_SHAPE_PROXYTYPE:
{
int upAxis = static_cast<const btCylinderShape*>(shape)->getUpAxis();
if (upAxis == 0)
{
return CollisionShapeType_CylinderX;
}
else if (upAxis == 2)
{
return CollisionShapeType_CylinderZ;
}
return CollisionShapeType_CylinderY;
}
case CAPSULE_SHAPE_PROXYTYPE:
{
int upAxis = static_cast<const btCapsuleShape*>(shape)->getUpAxis();
if (upAxis == 0)
{
return CollisionShapeType_CapsuleX;
}
else if (upAxis == 2)
{
return CollisionShapeType_CapsuleZ;
}
return CollisionShapeType_CapsuleY;
}
case CONVEX_HULL_SHAPE_PROXYTYPE:
{
return CollisionShapeType_ConvexHull;
}
case COMPOUND_SHAPE_PROXYTYPE: // <-- Will be the model convex hulls.
{
return CollisionShapeType_ModelConvexHulls;
}
default:
{
break;
}
}
}
return CollisionShapeType_None;
}
inline CollisionShapeType GetCollisionShapeType(const btCollisionShape &shape)
{
return GetCollisionShapeType(&shape);
}
}
#endif | 29.495327 | 98 | 0.498733 | mackron |
0d82f71a6ee579f7c7271823129651b733a44cf2 | 203 | hpp | C++ | Paramedic.hpp | liorls/wargame-a | b4e2f65259defe5664dfc0f83294269beb18fea0 | [
"MIT"
] | null | null | null | Paramedic.hpp | liorls/wargame-a | b4e2f65259defe5664dfc0f83294269beb18fea0 | [
"MIT"
] | null | null | null | Paramedic.hpp | liorls/wargame-a | b4e2f65259defe5664dfc0f83294269beb18fea0 | [
"MIT"
] | null | null | null | #pragma once
#include "Soldier.hpp"
class Paramedic : public Soldier {
public:
Paramedic(int p): Soldier(p, 100, 0, 100) {}
void attack(vector<vector<Soldier*>> &b, pair<int,int> location);
}; | 20.3 | 69 | 0.669951 | liorls |
0d877b6c00c091ecbac688cf441eab948af5189c | 237 | hpp | C++ | src/lattice_boltzmann/LBUtils/Stencil.hpp | flowzario/mesoBasic | 0a86c98e784a7446a7b6f03b48eef4c9dbfe5940 | [
"MIT"
] | null | null | null | src/lattice_boltzmann/LBUtils/Stencil.hpp | flowzario/mesoBasic | 0a86c98e784a7446a7b6f03b48eef4c9dbfe5940 | [
"MIT"
] | null | null | null | src/lattice_boltzmann/LBUtils/Stencil.hpp | flowzario/mesoBasic | 0a86c98e784a7446a7b6f03b48eef4c9dbfe5940 | [
"MIT"
] | null | null | null | # ifndef STENCIL_H
# define STENCIL_H
# include <vector>
# include <string>
struct Stencil {
int nn;
std::vector<int> exi,eyi,ezi;
std::vector<double> ex,ey,ez,wa;
void setStencil(const std::string);
};
# endif // STENCIL_H
| 11.85 | 36 | 0.675105 | flowzario |
0d88a900ecb849ab151c7e1816019193d7201541 | 889 | cpp | C++ | core/HighPrecisionClock/SimpleClock.cpp | esayui/mworks | 0522e5afc1e30fdbf1e67cedd196ee50f7924499 | [
"MIT"
] | null | null | null | core/HighPrecisionClock/SimpleClock.cpp | esayui/mworks | 0522e5afc1e30fdbf1e67cedd196ee50f7924499 | [
"MIT"
] | null | null | null | core/HighPrecisionClock/SimpleClock.cpp | esayui/mworks | 0522e5afc1e30fdbf1e67cedd196ee50f7924499 | [
"MIT"
] | null | null | null | //
// SimpleClock.cpp
// MWorksCore
//
// Created by Christopher Stawarz on 8/17/16.
//
//
#include "SimpleClock.hpp"
BEGIN_NAMESPACE_MW
SimpleClock::SimpleClock() :
systemBaseTimeAbsolute(mach_absolute_time())
{ }
MWTime SimpleClock::getSystemBaseTimeNS() {
return timebase.absoluteToNanos(systemBaseTimeAbsolute);
}
MWTime SimpleClock::getSystemTimeNS() {
return timebase.absoluteToNanos(mach_absolute_time());
}
MWTime SimpleClock::getCurrentTimeNS() {
return timebase.absoluteToNanos(mach_absolute_time() - systemBaseTimeAbsolute);
}
void SimpleClock::sleepNS(MWTime time) {
logMachError("mach_wait_until", mach_wait_until(mach_absolute_time() +
timebase.nanosToAbsolute(std::max(MWTime(0), time))));
}
void SimpleClock::yield() {
sleepUS(500);
}
END_NAMESPACE_MW
| 12.347222 | 106 | 0.68054 | esayui |
0d891d182cebe76956d01f5c436f5b1cb77a5a8d | 11,123 | cpp | C++ | ModelGenerator/src/ModelGenerator.cpp | adam-lafontaine/AugmentedAI | a4736ce59963ee86313a5936aaf09f0f659e4184 | [
"MIT"
] | null | null | null | ModelGenerator/src/ModelGenerator.cpp | adam-lafontaine/AugmentedAI | a4736ce59963ee86313a5936aaf09f0f659e4184 | [
"MIT"
] | null | null | null | ModelGenerator/src/ModelGenerator.cpp | adam-lafontaine/AugmentedAI | a4736ce59963ee86313a5936aaf09f0f659e4184 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2021 Adam Lafontaine
*/
#include "ModelGenerator.hpp"
#include "pixel_conversion.hpp"
#include "cluster_distance.hpp"
#include "../../utils/cluster_config.hpp"
#include "../../utils/dirhelper.hpp"
#include "../../DataAdaptor/src/data_adaptor.hpp"
#include <algorithm>
#include <numeric>
#include <functional>
#include <iomanip>
#include <sstream>
#include <cassert>
#include <cmath>
#include <ctime>
#include <cstdlib>
#include <string>
namespace dir = dirhelper;
namespace img = libimage;
namespace data = data_adaptor;
namespace model_generator
{
using hist_value_t = unsigned; // represent a pixel as a single value for a histogram
constexpr hist_value_t MAX_COLOR_VALUE = 255;
using color_qty_t = unsigned;
constexpr color_qty_t MAX_RELATIVE_QTY = 255;
// provides a count for every shade that is found
using color_hist_t = std::array<color_qty_t, MAX_COLOR_VALUE>;
// provides shade counts for every column in the data image
using column_hists_t = std::vector<color_hist_t>;
// shade counts by column for each class
using class_column_hists_t = std::array<column_hists_t, mlclass::ML_CLASS_COUNT>;
using cluster_t = cluster::Cluster;
using centroid_list_t = cluster::value_row_list_t;
using data_list_t = std::vector<cluster::data_row_t>;
using class_cluster_data_t = std::array<data_list_t, mlclass::ML_CLASS_COUNT>;
using index_list_t = std::vector<size_t>;
using file_path_t = ModelGenerator::file_path_t;
//======= HELPERS ===================
static std::string make_model_file_name();
//======= CONVERSION =============
// converts a data pixel to a value between 0 and MAX_COLOR_VALUE
static hist_value_t to_hist_value(data_pixel_t const& pix);
//======= CLUSTERING =======================
// finds the indeces of the data that contribute to determining the class
static index_list_t find_relevant_positions(class_column_hists_t const& class_pos_hists);
//======= HISTOGRAM ============================
static void update_histograms(column_hists_t& pos_hists, img::view_t const& view);
static void append_data(data_list_t& data, img::view_t const& data_view);
// sets all values in the histograms to a value between 0 and MAX_RELATIVE_QTY
static void normalize_histograms(column_hists_t& pos);
static class_column_hists_t make_empty_histograms();
//======= CLASS METHODS ==================
// for cleaning up after reading data
void ModelGenerator::purge_class_data()
{
mlclass::for_each_class([&](auto c) { m_class_data[c].clear(); });
}
// check if data exists for every class
bool ModelGenerator::has_class_data()
{
auto const pred = [&](auto const& list) { return !list.empty(); };
return std::all_of(m_class_data.begin(), m_class_data.end(), pred);
}
// reads directory of raw data for a given class
void ModelGenerator::add_class_data(const char* src_dir, MLClass class_index)
{
// convert the class enum to an array index
auto const index = mlclass::to_class_index(class_index);
// data is organized in directories by class
m_class_data[index] = dir::get_files_of_type(src_dir, data::DATA_IMAGE_EXTENSION);
}
// saves properties based on all of the data read
void ModelGenerator::save_model(const char* save_dir)
{
if (!has_class_data())
return;
/* get all of the data */
class_cluster_data_t cluster_data;
auto hists = make_empty_histograms();
auto const get_data = [&](auto class_index)
{
for (auto const& data_file : m_class_data[class_index])
{
img::image_t data_image;
img::read_image_from_file(data_file, data_image);
auto data_view = img::make_view(data_image);
assert(static_cast<size_t>(data_view.width) == data::data_image_width());
append_data(cluster_data[class_index], data_view);
update_histograms(hists[class_index], data_view);
}
normalize_histograms(hists[class_index]);
};
mlclass::for_each_class(get_data);
/* cluster the data */
auto const data_indeces = find_relevant_positions(hists); // This needs to be right
cluster_t cluster;
centroid_list_t centroids;
auto const class_clusters = mlclass::make_class_clusters(cluster::CLUSTER_COUNT);
cluster.set_distance(build_cluster_distance(data_indeces));
auto const cluster_class_data = [&](auto c)
{
auto const cents = cluster.cluster_data(cluster_data[c], class_clusters[c]);
centroids.insert(centroids.end(), cents.begin(), cents.end());
};
mlclass::for_each_class(cluster_class_data);
/* create the model and save it */
auto const save_path = fs::path(save_dir) / make_model_file_name();
auto const width = static_cast<u32>(data::data_image_width());
auto const height = static_cast<u32>(centroids.size());
img::image_t image;
img::make_image(image, width, height);
auto view = img::make_view(image);
for(u32 y = 0; y < height; ++y)
{
auto const list = centroids[y];
auto ptr = view.row_begin(y);
for (u32 x = 0; x < width; ++x)
{
auto is_counted = std::find(data_indeces.begin(), data_indeces.end(), x) != data_indeces.end();
ptr[x] = model_value_to_model_pixel(list[x], is_counted);
}
}
img::write_view(view, save_path);
/*
This is a long function and it could be broken up into smaller ones.
However, this logic is only used here so there is no sense in creating more class members
*/
}
//======= CLUSTERING =======================
static index_list_t set_indeces_manually(class_column_hists_t const& class_pos_hists)
{
// here you can cheat by choosing indeces after inspecting the data images
//index_list_t list{ 0 }; // uses only the first index of the data image values
// just return all of the indeces
index_list_t list(class_pos_hists[0].size());
std::iota(list.begin(), list.end(), 0);
return list;
}
typedef struct
{
double min;
double max;
} minmax_t;
// returns the mean +/- one std dev
static minmax_t get_stat_range(color_hist_t const& hist)
{
auto const calc_mean = [](color_hist_t const& hist)
{
size_t qty_total = 0;
size_t val_total = 0;
for (size_t shade = 0; shade < hist.size(); ++shade)
{
auto qty = hist[shade];
if (!qty)
continue;
qty_total += qty;
val_total += qty * shade;
}
return qty_total == 0 ? 0 : val_total / qty_total;
};
auto const calc_sigma = [](color_hist_t const& hist, size_t mean)
{
double total = 0;
size_t qty_total = 0;
for (size_t shade = 0; shade < hist.size(); ++shade)
{
auto val = shade;
auto qty = hist[shade];
if (!qty)
continue;
qty_total += qty;
auto const diff = val - mean;
total += qty * diff * diff;
}
return qty_total == 0 ? 0 : std::sqrt(total / qty_total);
};
auto const m = calc_mean(hist);
auto const s = calc_sigma(hist, m);
return{ m - s, m + s }; // mean +/- one std dev
}
// determine if any of the ranges overlap each other
static bool has_overlap(std::array<minmax_t, mlclass::ML_CLASS_COUNT> const& ranges)
{
assert(ranges.size() >= 2);
auto const r_min = std::min_element(ranges.begin(), ranges.end(), [](auto const& a, auto const& b) { return a.min < b.min; });
auto const r_max = std::max_element(ranges.begin(), ranges.end(), [](auto const& a, auto const& b) { return a.max < b.max; });
return r_min->max >= r_max->min;
}
// An attempt at programatically finding data image indeces that contribute to classification
// finds the indeces of the data that contribute to determining the class
static index_list_t try_find_indeces(class_column_hists_t const& class_pos_hists)
{
const size_t num_pos = class_pos_hists[0].size();
std::array<minmax_t, mlclass::ML_CLASS_COUNT> class_ranges;
index_list_t list;
for (size_t pos = 0; pos < num_pos; ++pos)
{
class_ranges = { 0 };
auto const set_class_range = [&](auto class_index) { class_ranges[class_index] = get_stat_range(class_pos_hists[class_index][pos]); };
mlclass::for_each_class(set_class_range);
if (has_overlap(class_ranges))
continue;
list.push_back(pos);
}
return list;
}
static index_list_t find_relevant_positions(class_column_hists_t const& class_pos_hists)
{
auto const indeces = try_find_indeces(class_pos_hists);
if(indeces.empty())
return set_indeces_manually(class_pos_hists);
return indeces;
}
//======= HISTOGRAM ============================
// update the counts in the histograms with data from a data image
static void update_histograms(column_hists_t& pos_hists, img::view_t const& data_view)
{
u32 column = 0;
auto const update_pred = [&](auto const& p)
{
data_pixel_t dp{ p };
++pos_hists[column][to_hist_value(dp)];
};
for (; column < data_view.width; ++column)
{
auto column_view = img::column_view(data_view, column);
std::for_each(column_view.begin(), column_view.end(), update_pred);
}
}
// add converted data from a data image
static void append_data(data_list_t& data, img::view_t const& data_view)
{
auto const height = data_view.height;
for (u32 y = 0; y < height; ++y)
{
cluster::data_row_t data_row;
auto row_view = img::row_view(data_view, y);
std::transform(row_view.begin(), row_view.end(), std::back_inserter(data_row), data_pixel_to_model_value);
data.push_back(std::move(data_row));
}
}
// sets all values in the histograms to a value between 0 and MAX_RELATIVE_QTY
static void normalize_histograms(column_hists_t& pos)
{
std::vector<unsigned> hists;
hists.reserve(pos.size());
auto const max_val = [](auto const& list)
{
auto it = std::max_element(list.begin(), list.end());
return *it;
};
std::transform(pos.begin(), pos.end(), std::back_inserter(hists), max_val);
const double max = max_val(hists);
auto const norm = [&](unsigned count)
{
return static_cast<unsigned>(count / max * MAX_RELATIVE_QTY);
};
for (auto& list : pos)
{
for (auto& count : list)
{
count = norm(count);
}
}
}
static class_column_hists_t make_empty_histograms()
{
class_column_hists_t position_hists;
auto const width = data::data_image_width();
auto const set_column_zeros = [&](auto c)
{
position_hists[c] = column_hists_t(width, {0});
};
mlclass::for_each_class(set_column_zeros);
return position_hists;
}
//======= HELPERS =====================
static std::string make_model_file_name()
{
std::ostringstream oss;
std::time_t t = std::time(nullptr);
struct tm buf;
// TODO: C++20 chrono
#ifdef __linux
localtime_r(&t, &buf);
#else
localtime_s(&buf, &t);
#endif
oss << "model_" << std::put_time(&buf, "%F_%T");
auto date_file = oss.str() + MODEL_FILE_EXTENSION;
std::replace(date_file.begin(), date_file.end(), ':', '-');
return date_file;
}
//======= CONVERSION =============
// converts a data pixel to a value between 0 and MAX_COLOR_VALUE
static hist_value_t to_hist_value(data_pixel_t const& pix)
{
auto const val = static_cast<double>(pix.value);
auto const ratio = val / UINT32_MAX;
return static_cast<hist_value_t>(ratio * MAX_COLOR_VALUE);
}
}
| 24.286026 | 137 | 0.685427 | adam-lafontaine |
0d8a3cfa3854dfce410e87e120e2042b9ee5860e | 7,571 | cc | C++ | server/src/JsonNode.cc | shawndfl/http_server | f4a0e13146ca95cc9f7c4e1145fbc52bfd45a8a0 | [
"MIT"
] | null | null | null | server/src/JsonNode.cc | shawndfl/http_server | f4a0e13146ca95cc9f7c4e1145fbc52bfd45a8a0 | [
"MIT"
] | null | null | null | server/src/JsonNode.cc | shawndfl/http_server | f4a0e13146ca95cc9f7c4e1145fbc52bfd45a8a0 | [
"MIT"
] | null | null | null | /*
* JsonNode.cc
*
* Created on: Jun 1, 2020
* Author: sdady
*/
#include "JsonNode.h"
namespace ehs {
/*************************************************/
JsonNode::JsonNode() {
type_ = JsonNull;
valueNum_ = 0;
}
/*************************************************/
JsonNode::~JsonNode() {
}
/*************************************************/
JsonNode& JsonNode::setString(const std::string& value) {
type_= JsonString;
valueStr_ = value;
return *this;
}
/*************************************************/
JsonNode& JsonNode::setNumber(double value) {
type_= JsonNumber;
valueNum_ = value;
return *this;
}
/*************************************************/
JsonNode& JsonNode::setBool(bool value) {
type_= value? JsonTrue: JsonFalse;
return *this;
}
/*************************************************/
JsonNode& JsonNode::setNull() {
type_= JsonNull;
return *this;
}
/*************************************************/
JsonNode& JsonNode::setObject(const std::string& key, const JsonNode& value) {
type_= JsonObject;
valueObj_[key] = value;
return *this;
}
/*************************************************/
JsonNode& JsonNode::setArray(int index, const JsonNode &value) {
type_ = JsonArray;
JsonNode newNode;
for (int i = valueArray_.size(); i <= index; i++) {
valueArray_.push_back(JsonNode());
}
return valueArray_[index];
}
/*************************************************/
void JsonNode::clear() {
valueArray_.clear();
valueObj_.clear();
type_ = JsonNull;
valueNum_ = 0;
valueStr_ = "";
}
/*************************************************/
std::string JsonNode::toString(bool humanReadable) const {
std::string json;
// we can only start with objects or arrays
if (type_ == JsonObject || type_ == JsonArray) {
if(humanReadable){
toStringReadableImpl(json, 0);
} else {
toStringImpl(json);
}
} else {
json = "{}";
}
return json;
}
/*************************************************/
std::string JsonNode::getString(const std::string &key, const std::string &defaultValue) {
auto itt = valueObj_.find(key);
if(itt == valueObj_.end() || (*itt).second.type_ != JsonString) {
return defaultValue;
} else {
return (*itt).second.valueStr_;
}
}
/*************************************************/
double JsonNode::getNumber(const std::string &key, const double defaultValue) {
auto itt = valueObj_.find(key);
if (itt == valueObj_.end() || (*itt).second.type_ != JsonNumber) {
return defaultValue;
} else {
return (*itt).second.valueNum_;
}
}
/*************************************************/
bool JsonNode::getBool(const std::string &key, const bool defaultValue) {
auto itt = valueObj_.find(key);
if (itt == valueObj_.end() ||
((*itt).second.type_ != JsonFalse &&
(*itt).second.type_ != JsonTrue)) {
return defaultValue;
} else {
return (*itt).second.valueNum_ == 1;
}
}
/*************************************************/
JsonNode& JsonNode::append() {
type_= JsonArray;
valueArray_.push_back(JsonNode());
return valueArray_[valueArray_.size() - 1];
}
/*************************************************/
JsonNode& JsonNode::operator [](int index) {
type_ = JsonArray;
JsonNode newNode;
// add nodes until we get to this index
for (int i = valueArray_.size(); i <= index; i++) {
valueArray_.push_back(JsonNode());
}
return valueArray_[index];
}
/*************************************************/
JsonNode& JsonNode::operator [](const std::string& key) {
type_= JsonObject;
return valueObj_[key];
}
/*************************************************/
JsonNode& JsonNode::operator =(ulong value) {
return setNumber(value);
}
/*************************************************/
JsonNode& JsonNode::operator =(int value) {
type_= JsonNumber;
valueNum_ = value;
return *this;
}
/*************************************************/
JsonNode& JsonNode::operator =(uint value) {
type_= JsonNumber;
valueNum_ = value;
return *this;
}
/*************************************************/
JsonNode& JsonNode::operator =(long value) {
type_= JsonNumber;
valueNum_ = value;
return *this;
}
/*************************************************/
JsonNode& JsonNode::operator =(double value) {
type_= JsonNumber;
valueNum_ = value;
return *this;
}
/*************************************************/
JsonNode& JsonNode::operator =(const std::string& value) {
type_= JsonString;
valueStr_ = value;
return *this;
}
/*************************************************/
JsonNode& JsonNode::operator =(const char* value) {
type_= JsonString;
valueStr_ = value;
return *this;
}
/*************************************************/
void JsonNode::toStringReadableImpl(std::string& json, int tab) const {
std::string tabs;
for(int i =0; i < tab; i++) {
tabs +="\t";
}
switch (type_) {
case JsonNull:
json += "null";
break;
case JsonObject: {
size_t i = 0;
json += "{\n";
++tab;
for (auto& pair : valueObj_) {
json += tabs + "\t\"" + pair.first + "\": ";
pair.second.toStringReadableImpl(json, tab);
if (i < valueObj_.size() - 1) {
json += ",";
}
i++;
json += '\n';
}
json += tabs + "}";
break;
}
case JsonArray: {
size_t i = 0;
json += "[\n";
++tab;
for (auto& item : valueArray_) {
json += tabs + "\t";
item.toStringReadableImpl(json, tab);
if (i < valueArray_.size() - 1) {
json += ",";
}
i++;
json += '\n';
}
json += tabs + "]";
break;
}
break;
case JsonTrue:
json += "true";
break;
case JsonFalse:
json += "false";
break;
case JsonString:
json += "\"" + valueStr_ + "\"";
break;
case JsonNumber:
try {
json += std::to_string(valueNum_);
} catch(std::exception& ) {
json += "0";
}
break;
}
}
/*************************************************/
void JsonNode::toStringImpl(std::string& json) const {
switch (type_) {
case JsonNull:
json += "null";
break;
case JsonObject: {
size_t i = 0;
json += "{";
for (auto& pair : valueObj_) {
json += "\"" + pair.first + "\":";
pair.second.toStringImpl(json);
if (i < valueObj_.size() - 1) {
json += ",";
}
i++;
}
json += "}";
break;
}
case JsonArray: {
size_t i = 0;
json += "[";
for (auto& item : valueArray_) {
item.toStringImpl(json);
if (i < valueArray_.size() - 1) {
json += ",";
}
i++;
}
json += "]";
break;
}
break;
case JsonTrue:
json += "true";
break;
case JsonFalse:
json += "false";
break;
case JsonString:
json += "\"" + valueStr_ + "\"";
break;
case JsonNumber:
try {
json += std::to_string(valueNum_);
} catch(std::exception& ) {
json += "0";
}
break;
}
}
}
| 24.188498 | 90 | 0.439704 | shawndfl |
0d8cd40a38502f306fcf411fca8525436a599e58 | 5,382 | cpp | C++ | src/UDPSocket.cpp | MaoChen1980/wrighteaglebase | 12b29e5d6d9ada4dd98ec288f7cb6fb845596717 | [
"BSD-2-Clause"
] | 86 | 2016-06-16T05:10:57.000Z | 2022-03-01T08:02:43.000Z | src/UDPSocket.cpp | rc2dcc/wrighteaglebase | f6be453447b657fa4c7417b5b62b5ea2067409bc | [
"BSD-2-Clause"
] | 1 | 2020-03-04T16:59:58.000Z | 2020-03-04T16:59:58.000Z | src/UDPSocket.cpp | rc2dcc/wrighteaglebase | f6be453447b657fa4c7417b5b62b5ea2067409bc | [
"BSD-2-Clause"
] | 43 | 2016-07-08T03:19:19.000Z | 2022-01-12T12:28:44.000Z | /************************************************************************************
* WrightEagle (Soccer Simulation League 2D) *
* BASE SOURCE CODE RELEASE 2016 *
* Copyright (c) 1998-2016 WrightEagle 2D Soccer Simulation Team, *
* Multi-Agent Systems Lab., *
* School of Computer Science and Technology, *
* University of Science and Technology of China *
* 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 WrightEagle 2D Soccer Simulation Team 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 WrightEagle 2D Soccer Simulation Team BE LIABLE *
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL *
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR *
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER *
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, *
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF *
* THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *
************************************************************************************/
#include "UDPSocket.h"
//==============================================================================
UDPSocket::UDPSocket()
{
mIsInitialOK = false;
}
//==============================================================================
UDPSocket::~UDPSocket()
{
}
//==============================================================================
UDPSocket & UDPSocket::instance()
{
static UDPSocket udp_socket;
return udp_socket;
}
//==============================================================================
void UDPSocket::Initial(const char *host, int port)
{
struct hostent *host_ent ;
struct in_addr *addr_ptr ;
#ifdef WIN32
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD( 2, 2 );
if (WSAStartup(wVersionRequested, &wsaData) != 0)
{
PRINT_ERROR("WSAStartup failed");
}
if (LOBYTE( wsaData.wVersion) != 2 || HIBYTE(wsaData.wVersion) != 2)
{
WSACleanup();
PRINT_ERROR("WSASTartup version mismatch");
}
#endif
if ((host_ent = (struct hostent *)gethostbyname(host)) == 0)
{
if (inet_addr(host) == INADDR_NONE)
PRINT_ERROR("Invalid host name");
}
else
{
addr_ptr = (struct in_addr *) *host_ent->h_addr_list ;
host = inet_ntoa(*addr_ptr) ;
}
if( (mSockfd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
PRINT_ERROR("Can't create socket") ;
}
memset(&mAddress, 0, sizeof(mAddress)) ;
mAddress.sin_family = AF_INET ;
mAddress.sin_addr.s_addr = htonl(INADDR_ANY) ;
mAddress.sin_port = htons(0) ;
if(bind(mSockfd, (sockaddr *)&mAddress, sizeof(mAddress)) < 0)
{
#ifdef WIN32
closesocket(mSockfd);
#else
close(mSockfd);
#endif
PRINT_ERROR("Can't bind client to any port") ;
}
memset(&mAddress, 0, sizeof(mAddress)) ;
mAddress.sin_family = AF_INET ;
mAddress.sin_addr.s_addr = inet_addr( host ) ;
mAddress.sin_port = htons( port ) ;
mIsInitialOK = true;
}
//==============================================================================
int UDPSocket::Receive(char *msg)
{
#ifdef WIN32
int servlen;
#else
socklen_t servlen ;
#endif
sockaddr_in serv_addr;
servlen = sizeof(serv_addr);
int n = recvfrom(mSockfd, msg, MAX_MESSAGE, 0, (sockaddr *)&serv_addr, &servlen);
if (n > 0)
{
msg[n] = '\0' ; // rccparser will crash if msg has no end
mAddress.sin_port = serv_addr.sin_port ;
}
return n ;
}
//==============================================================================
int UDPSocket::Send(const char *msg)
{
if (mIsInitialOK == true)
{
int n = std::strlen(msg) ;
n = sendto(mSockfd, msg, n+1, 0, (sockaddr *)&mAddress, sizeof(mAddress));
return n;
}
std::cout << msg << std::endl;
return std::strlen(msg);
}
//end of UDPSocket.cpp
| 34.722581 | 86 | 0.533631 | MaoChen1980 |
0d8e59b76d9e6fc939bee9474ebe232cef51a86f | 1,088 | cpp | C++ | src/backlight_set.cpp | klokik/JemUtilities | 21dd11aae53557109e1b1613c2343c8a1eb5d165 | [
"MIT"
] | 1 | 2021-01-13T07:57:05.000Z | 2021-01-13T07:57:05.000Z | src/backlight_set.cpp | klokik/JemUtilities | 21dd11aae53557109e1b1613c2343c8a1eb5d165 | [
"MIT"
] | null | null | null | src/backlight_set.cpp | klokik/JemUtilities | 21dd11aae53557109e1b1613c2343c8a1eb5d165 | [
"MIT"
] | null | null | null | #include <cstring>
#include <iostream>
#include <fstream>
#include <string>
#include <sys/types.h>
#include <unistd.h>
int main(int argc, char **argv) {
if (argc != 2) {
std::cout << "Invalid parameters" << std::endl;
return 0;
}
int delta = atoi(argv[1]);
int max_level = 7;
int cur_level = 3;
if (setuid(0)) {
std::cout << "Failed to set uid 0, trying with curent id ..." << std::endl;
}
std::string path = "/sys/class/backlight/backlight";
try {
std::ifstream ifs_max(path + "/max_brightness");
ifs_max >> max_level;
ifs_max.close();
std::ifstream ifs_cur(path + "/actual_brightness");
ifs_cur >> cur_level;
ifs_cur.close();
int new_level = cur_level+delta;
if (new_level < 0)
new_level = 0;
if (new_level > max_level)
new_level = max_level;
char buf[15];
sprintf(&buf[0], "%d", new_level);
std::ofstream ofs_set(path + "/brightness");
ofs_set.write(&buf[0], strlen(buf));
ofs_set.close();
}
catch (...) {
std::cout << "An IO error occured, do you have enough permissions?" << std::endl;
return -1;
}
return 0;
}
| 18.758621 | 83 | 0.629596 | klokik |
0d8f9eaa121e233592aaf3d98c930b091a2cf348 | 924 | hpp | C++ | include/platform/internal/list/top_type.hpp | vladankor/types_library | 9f0f64946b621c447c5f72a6df34ced9438b1ff2 | [
"MIT"
] | null | null | null | include/platform/internal/list/top_type.hpp | vladankor/types_library | 9f0f64946b621c447c5f72a6df34ced9438b1ff2 | [
"MIT"
] | null | null | null | include/platform/internal/list/top_type.hpp | vladankor/types_library | 9f0f64946b621c447c5f72a6df34ced9438b1ff2 | [
"MIT"
] | null | null | null | // ----------------------------------------------------------------------------
// Copyright (C) 2019 Korobov Vladislav
// ----------------------------------------------------------------------------
#pragma once
//- platform ------------------------------------------------------------------
#include <platform/internal/list/list_type.hpp>
// ----------------------------------------------------------------------------
namespace platform::internal {
//-----------------------------------------------------------------------------
// struct top_type
//-----------------------------------------------------------------------------
template<class ...>
struct top_type;
template<class ...TArgs>
struct top_type<list_type<TArgs...>> {
using type = typename list_type<TArgs...>::head_type;
}; // top_type
template<class ...TArgs>
using top_t = typename top_type<TArgs...>::type;
} // namespace platform::internal
| 28.875 | 79 | 0.351732 | vladankor |
0d964f38068ef7aecaf433a374b4bd07436db0ab | 4,857 | cc | C++ | lib/pods-trie-builder.cc | rockeet/taiju | 90f152d5e66b1741d35b9d871f7a5db68699d48d | [
"BSD-3-Clause"
] | null | null | null | lib/pods-trie-builder.cc | rockeet/taiju | 90f152d5e66b1741d35b9d871f7a5db68699d48d | [
"BSD-3-Clause"
] | null | null | null | lib/pods-trie-builder.cc | rockeet/taiju | 90f152d5e66b1741d35b9d871f7a5db68699d48d | [
"BSD-3-Clause"
] | null | null | null | #include <taiju/pods-trie-builder.h>
#include <algorithm>
namespace taiju {
PodsTrieBuilder::PodsTrieBuilder() : node_order_(DEFAULT_NODE_ORDER),
num_keys_(0), child_diffs_(), has_siblings_(), labels_(),
is_terminals_(), inters_(), finished_(false) {}
UInt64 PodsTrieBuilder::size() const
{
return sizeof(TrieType) + sizeof(UInt64) + child_diffs_.size()
+ has_siblings_.size() + labels_.size() + is_terminals_.size();
}
void PodsTrieBuilder::open(NodeOrder node_order)
{
PodsTrieBuilder temp;
switch (node_order)
{
case ASCENDING_LABEL_ORDER:
case DESCENDING_LABEL_ORDER:
case TOTAL_WEIGHT_ORDER:
case MAX_WEIGHT_ORDER:
case RANDOM_ORDER:
temp.node_order_ = node_order;
break;
default:
TAIJU_THROW("failed to open PodsTrieBuilder: invalid NodeOrder");
}
temp.child_diffs_.open();
temp.has_siblings_.open();
temp.labels_.open();
temp.is_terminals_.open(ONLY_RANK_INDEX);
temp.append_inter(TrieNode());
swap(&temp);
}
void PodsTrieBuilder::close()
{
node_order_ = DEFAULT_NODE_ORDER;
num_keys_ = 0;
child_diffs_.clear();
has_siblings_.clear();
labels_.clear();
is_terminals_.clear();
inters_.clear();
finished_ = false;
}
void PodsTrieBuilder::append(const void *ptr, UInt64 size, double weight)
{
if (finished())
TAIJU_THROW("failed to append: the builder is finished");
append_key(static_cast<const UInt8 *>(ptr), size, weight);
}
void PodsTrieBuilder::finish()
{
finished_ = true;
flush(0);
if (!inters_.empty())
{
append_node(inters_[0]);
inters_.clear();
}
child_diffs_.finish();
has_siblings_.finish();
labels_.finish();
is_terminals_.finish();
}
void PodsTrieBuilder::swap(PodsTrieBuilder *target)
{
std::swap(node_order_, target->node_order_);
std::swap(num_keys_, target->num_keys_);
child_diffs_.swap(&target->child_diffs_);
has_siblings_.swap(&target->has_siblings_);
labels_.swap(&target->labels_);
is_terminals_.swap(&target->is_terminals_);
inters_.swap(&target->inters_);
std::swap(finished_, target->finished_);
}
void PodsTrieBuilder::write(Writer writer)
{
finish();
writer.write(type());
writer.write(num_keys_);
child_diffs_.write(writer);
has_siblings_.write(writer);
labels_.write(writer);
is_terminals_.write(writer);
}
void PodsTrieBuilder::append_key(const UInt8 *key, UInt64 length,
double weight)
{
UInt64 id = 0;
for ( ; length > 0; ++key, --length)
{
if (!inters_[id].has_child())
break;
UInt64 child_id = inters_[id].child();
UInt8 label = inters_[child_id].label();
if (*key < label)
TAIJU_THROW("failed to append: wrong key order");
else if (*key > label)
{
flush(child_id);
inters_[child_id].set_has_sibling(true);
break;
}
switch (node_order_)
{
case ASCENDING_LABEL_ORDER:
case DESCENDING_LABEL_ORDER:
break;
case TOTAL_WEIGHT_ORDER:
inters_[id].set_weight(inters_[id].weight() + weight);
break;
case MAX_WEIGHT_ORDER:
if (weight > inters_[id].weight())
inters_[id].set_weight(weight);
break;
case RANDOM_ORDER:
break;
}
id = child_id;
}
for ( ; length > 0; ++key, --length)
{
UInt64 child_id = inters_.num_objs();
inters_[id].set_has_child(true);
inters_[id].set_child(child_id);
TrieNode node;
node.set_label(*key);
node.set_weight(weight);
append_inter(node);
id = child_id;
}
inters_[id].set_is_terminal(true);
++num_keys_;
}
void PodsTrieBuilder::append_inter(const TrieNode &node)
{
if (!inters_.push(node))
TAIJU_THROW("failed to append: Vector::push() failed");
}
void PodsTrieBuilder::append_node(const TrieNode &node)
{
if (node.has_child())
child_diffs_.append(labels_.num_objs() - node.child());
else
child_diffs_.append(0);
has_siblings_.append(node.has_sibling());
labels_.append(node.label());
is_terminals_.append(node.is_terminal());
}
void PodsTrieBuilder::flush(UInt64 root)
{
while (root + 1 < inters_.num_objs())
{
std::size_t end_id = static_cast<std::size_t>(inters_.num_objs());
std::size_t begin_id = end_id - 1;
while (inters_[begin_id - 1].has_sibling())
--begin_id;
if (end_id - begin_id > 1)
{
inters_[end_id - 1].set_has_sibling(true);
switch (node_order_)
{
case ASCENDING_LABEL_ORDER:
break;
case DESCENDING_LABEL_ORDER:
std::reverse(inters_.begin() + begin_id,
inters_.begin() + end_id);
break;
case TOTAL_WEIGHT_ORDER:
case MAX_WEIGHT_ORDER:
std::stable_sort(inters_.begin() + begin_id,
inters_.begin() + end_id, TrieNode::WeightComparer());
break;
case RANDOM_ORDER:
std::random_shuffle(inters_.begin() + begin_id,
inters_.begin() + end_id);
break;
}
inters_[end_id - 1].set_has_sibling(false);
}
for (UInt64 id = end_id; id > begin_id; --id)
append_node(inters_[id - 1]);
inters_.resize(begin_id);
inters_[begin_id - 1].set_child(labels_.num_objs() - 1);
}
}
} // namespace taiju
| 21.977376 | 73 | 0.704756 | rockeet |