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
109
| 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
48.5k
⌀ | 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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
21ccb13453d5a3cbdb1cf3c52e4392b59befa2db
| 1,937
|
cpp
|
C++
|
objLoader/main.cpp
|
ComradeKeys/kc_lib
|
589f355f62b0e4660ec3109ea9c81cd6e60dbae1
|
[
"Zlib"
] | null | null | null |
objLoader/main.cpp
|
ComradeKeys/kc_lib
|
589f355f62b0e4660ec3109ea9c81cd6e60dbae1
|
[
"Zlib"
] | null | null | null |
objLoader/main.cpp
|
ComradeKeys/kc_lib
|
589f355f62b0e4660ec3109ea9c81cd6e60dbae1
|
[
"Zlib"
] | null | null | null |
//This example program is created by thecplusplusuy for demonstration purposes. It's a simple 3D model loader (wavefront (.obj)), which is capable to load materials and UV textures:
//http://www.youtube.com/user/thecplusplusguy
//Free source, modify if you want, LGPL licence (I guess), I would be happy, if you would not delete the link
//so other people can see the tutorial
//this file is third.cpp an example, how to use the class
#include "obj.h"
float angle=0.0;
obj object;//create an instance of the objloader
void init()
{
glClearColor(0.4,0.8,0.9,1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluPerspective(45,640.0/480.0,1.0,500.0);
glMatrixMode(GL_MODELVIEW);
glEnable(GL_DEPTH_TEST);
object.load("test.obj");//load it
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
float col[]={1.0,1.0,1.0,1.0};
glLightfv(GL_LIGHT0,GL_DIFFUSE,col);
}
void display()
{
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glLoadIdentity();
float pos[]={-1.0,1.0,-2.0,1.0};
glLightfv(GL_LIGHT0,GL_POSITION,pos);
/* How to move 3d elements independently off each other
glPushMatrix();
glTranslatef(-6.0,0, -15.0);
glRotatef(0.0,-1.0,1.0,-1.0);
secondObject.draw();
glPopMatrix(); */
glTranslatef(-1.0,-1, -30.0);
glRotatef(angle,-1.0,1.0,-1.0);
object.draw();
}
int main(int argc,char** argv)
{
angle = 0;
SDL_Init(SDL_INIT_EVERYTHING);
SDL_Surface* screen=SDL_SetVideoMode(640,480,32,SDL_SWSURFACE|SDL_OPENGL);
bool running=true;
Uint32 start;
SDL_Event event;
init();
while(running)
{
start=SDL_GetTicks();
while(SDL_PollEvent(&event))
{
switch(event.type)
{
case SDL_QUIT:
running=false;
break;
}
}
display();
SDL_GL_SwapBuffers();
angle+=0.5;
if(angle>360)
angle-=360;
if(1000/30>(SDL_GetTicks()-start))
SDL_Delay(1000/30-(SDL_GetTicks()-start));
}
SDL_Quit();
return 0;
}
| 25.155844
| 181
| 0.675787
|
ComradeKeys
|
21ceb61b912411afdcac867428878c2f65db44d5
| 4,047
|
cpp
|
C++
|
VecRegs.cpp
|
antoniocgj/SweRV-ISS-1
|
bc32016a0b92d6240b5963457c4403b498200403
|
[
"Apache-2.0"
] | 49
|
2020-05-27T10:14:02.000Z
|
2022-03-30T15:49:31.000Z
|
VecRegs.cpp
|
antoniocgj/SweRV-ISS-1
|
bc32016a0b92d6240b5963457c4403b498200403
|
[
"Apache-2.0"
] | 19
|
2020-06-30T08:26:02.000Z
|
2022-03-22T05:18:14.000Z
|
VecRegs.cpp
|
antoniocgj/SweRV-ISS-1
|
bc32016a0b92d6240b5963457c4403b498200403
|
[
"Apache-2.0"
] | 18
|
2020-08-30T02:55:25.000Z
|
2022-03-30T13:58:15.000Z
|
// Copyright 2020 Western Digital Corporation or its affiliates.
//
// 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 <iostream>
#include <cmath>
#include <string.h>
#include "VecRegs.hpp"
using namespace WdRiscv;
VecRegs::VecRegs()
{
// Intialize structure (vector of vectors) defining legal
// element-width/group-multiplier combinations to all false: No
// combination is supported. Configuration code will later change
// this.
legalConfigs_.resize(size_t(VecEnums::WidthLimit));
for (auto& groupFlags : legalConfigs_)
groupFlags.resize(size_t(VecEnums::GroupLimit));
// Temporary, for testing, make all combinations legal. FIX.
for (auto& groupFlags : legalConfigs_)
groupFlags.assign(groupFlags.size(), true);
// Temporary, for testing. FIX.
sew_ = ElementWidth::Word2;
sewInBits_ = 64;
// Temporary, for testing. FIX.
elems_ = 2;
}
VecRegs::~VecRegs()
{
regCount_ = 0;
bytesPerReg_ = 0;
bytesInRegFile_ = 0;
delete [] data_;
data_ = nullptr;
}
void
VecRegs::config(unsigned bytesPerReg, unsigned bytesPerElem)
{
if (bytesPerReg > 4096)
{
std::cerr << "VecRegs::configure: bytes-per-register too large (" << bytesPerReg
<< ") -- using 4096\n";
bytesPerReg = 4096;
}
if (bytesPerReg <= 4)
{
std::cerr << "VecRegs::configure: bytes-per-register too small (" << bytesPerReg
<< ") -- using 4\n";
bytesPerReg = 4;
}
unsigned l2BytesPerReg = std::log2(bytesPerReg);
unsigned p2BytesPerReg = uint32_t(1) << l2BytesPerReg;
if (p2BytesPerReg != bytesPerReg)
{
std::cerr << "VecRegs::configure: bytes-per-register (" << bytesPerReg
<< ") not a power of 2 -- using " << p2BytesPerReg << "\n";
bytesPerReg = p2BytesPerReg;
}
if (bytesPerElem < 1)
{
std:: cerr << "VecRegd::configure: zero max-bytes-per-element -- using 1\n";
bytesPerElem = 1;
}
unsigned l2BytesPerElem = std::log2(bytesPerElem);
unsigned p2BytesPerElem = uint32_t(1) << l2BytesPerElem;
if (p2BytesPerElem != bytesPerElem)
{
std::cerr << "VecRegs::configure: max-bytes-per-element (" << bytesPerElem
<< ") not a power of 2 -- using " << p2BytesPerElem << "\n";
bytesPerElem = p2BytesPerElem;
}
if (bytesPerElem > bytesPerReg)
{
std::cerr << "VecRegs::configure: max-bytes-per-element (" << bytesPerElem
<< ") is greater than the bytes-per-regidter (" << bytesPerReg
<< " -- using " << p2BytesPerReg << "\n";
bytesPerElem = bytesPerReg;
}
regCount_ = 32;
bytesPerReg_ = bytesPerReg;
bytesPerElem_ = bytesPerElem;
bytesInRegFile_ = regCount_ * bytesPerReg_;
delete [] data_;
data_ = new uint8_t[bytesInRegFile_];
memset(data_, 0, bytesInRegFile_);
}
uint64_t
VecRegs::checksum(unsigned regIx, unsigned elemIx0, unsigned elemIx1,
unsigned elemWidth) const
{
uint64_t sum = 0;
unsigned byteIx0 = (elemWidth*elemIx0) / 8;
unsigned byteIx1 = (elemWidth*elemIx1) / 8;
const uint8_t* regData = getVecData(regIx);
const uint8_t* end = data_ + bytesInRegFile_;
for (unsigned i = byteIx0; i <= byteIx1; ++i)
{
uint8_t byte = 0;
if (regData and regData + i < end)
byte = regData[i];
sum += byte; // FIX BOGUS replace my md5sum
}
return sum;
}
void
VecRegs::reset()
{
if (data_)
memset(data_, 0, bytesInRegFile_);
lastWrittenReg_ = -1;
lastElemIx_ = 0;
lastElemWidth_ = 0;
}
| 26.801325
| 86
| 0.650111
|
antoniocgj
|
21d0062dd7bae756e34740bc6b948c19724e6f74
| 874
|
cpp
|
C++
|
Utils/FileOperations.cpp
|
ebithril/Cerberus
|
8c5034bbb4fcdcc2cdb4495631176a2595c22dc7
|
[
"MIT"
] | 1
|
2017-08-13T20:41:57.000Z
|
2017-08-13T20:41:57.000Z
|
Utils/FileOperations.cpp
|
ebithril/Cerberus
|
8c5034bbb4fcdcc2cdb4495631176a2595c22dc7
|
[
"MIT"
] | null | null | null |
Utils/FileOperations.cpp
|
ebithril/Cerberus
|
8c5034bbb4fcdcc2cdb4495631176a2595c22dc7
|
[
"MIT"
] | null | null | null |
#include "FileOperations.h"
#include <stdio.h>
#include "UString.h"
typedef FILE FileHandle;
FileHandle* OpenFile(const String& FileName, const String& Mode)
{
return fopen(FileName.CString(), Mode.CString());
}
void CloseFile(FileHandle* Handle)
{
fclose(Handle);
}
int32 GetFileSize(FileHandle* Handle)
{
fseek(Handle, 0L, SEEK_END);
const int32 fileSize = ftell(Handle);
fseek(Handle, 0L, SEEK_SET);
return fileSize;
}
void ReadFromFile(void* dst, int32 size, int32 count, FileHandle* Handle)
{
fread(dst, size, count, Handle);
}
void ReadFileIntoArray(const String& FileName, Array<int8>& outArray)
{
FileHandle* file = OpenFile(FileName, "r");
const int32 fileSize = GetFileSize(file);
outArray.InitEmpty(fileSize);
ReadFromFile((void*)outArray.Data(), sizeof(int8), fileSize, file);
CloseFile(file);
}
| 20.325581
| 74
| 0.695652
|
ebithril
|
21d1d9951dc25cbedabf0e350329a100dffa0bde
| 305
|
hpp
|
C++
|
src/Key.hpp
|
PymZoR/gbcEmulator
|
4b7f7dd645a83aae792767a91b2d7def5d239c70
|
[
"MIT"
] | null | null | null |
src/Key.hpp
|
PymZoR/gbcEmulator
|
4b7f7dd645a83aae792767a91b2d7def5d239c70
|
[
"MIT"
] | null | null | null |
src/Key.hpp
|
PymZoR/gbcEmulator
|
4b7f7dd645a83aae792767a91b2d7def5d239c70
|
[
"MIT"
] | null | null | null |
#ifndef KEY_HPP
#define KEY_HPP
#include <SDL/SDL.h>
class Key
{
public:
Key();
~Key();
//Uint8 readByte(Uint16 addr); TODO: correct
Uint8 readByte();
//void writeByte(Uint16 addr, Uint16 value); TODO: correct
void writeByte(Uint16 addr);
};
#endif
| 16.052632
| 66
| 0.590164
|
PymZoR
|
21db548ede130611ed74743b91cc67ce0c549e70
| 2,646
|
cpp
|
C++
|
Ref/SignalGen/test/ut/Tester.cpp
|
AlperenCetin0/fprime
|
7e20febd34019c730da1358567e7a512592de4d8
|
[
"Apache-2.0"
] | 9,182
|
2017-07-06T15:51:35.000Z
|
2022-03-30T11:20:33.000Z
|
Ref/SignalGen/test/ut/Tester.cpp
|
AlperenCetin0/fprime
|
7e20febd34019c730da1358567e7a512592de4d8
|
[
"Apache-2.0"
] | 719
|
2017-07-14T17:56:01.000Z
|
2022-03-31T02:41:35.000Z
|
Ref/SignalGen/test/ut/Tester.cpp
|
AlperenCetin0/fprime
|
7e20febd34019c730da1358567e7a512592de4d8
|
[
"Apache-2.0"
] | 1,216
|
2017-07-12T15:41:08.000Z
|
2022-03-31T21:44:37.000Z
|
// ======================================================================
// \title SignalGen.hpp
// \author mstarch
// \brief cpp file for SignalGen test harness implementation class
//
// \copyright
// Copyright 2009-2015, by the California Institute of Technology.
// ALL RIGHTS RESERVED. United States Government Sponsorship
// acknowledged.
//
// ======================================================================
#include "Tester.hpp"
#define INSTANCE 0
#define MAX_HISTORY_SIZE 10
#define QUEUE_DEPTH 10
namespace Ref {
// ----------------------------------------------------------------------
// Construction and destruction
// ----------------------------------------------------------------------
Tester ::
Tester() :
SignalGenGTestBase("Tester", MAX_HISTORY_SIZE),
component("SignalGen")
{
this->initComponents();
this->connectPorts();
}
Tester ::
~Tester()
{
}
// ----------------------------------------------------------------------
// Tests
// ----------------------------------------------------------------------
void Tester ::
test_start()
{
ASSERT_TLM_Output_SIZE(0);
sendCmd_SignalGen_Toggle(0, 0);
component.doDispatch();
invoke_to_schedIn(0, 0);
component.doDispatch();
ASSERT_TLM_Output_SIZE(1);
}
// ----------------------------------------------------------------------
// Helper methods
// ----------------------------------------------------------------------
void Tester ::
connectPorts()
{
// cmdIn
this->connect_to_cmdIn(
0,
this->component.get_cmdIn_InputPort(0)
);
// schedIn
this->connect_to_schedIn(
0,
this->component.get_schedIn_InputPort(0)
);
// timeCaller
this->component.set_timeCaller_OutputPort(
0,
this->get_from_timeCaller(0)
);
// cmdRegOut
this->component.set_cmdRegOut_OutputPort(
0,
this->get_from_cmdRegOut(0)
);
// logTextOut
this->component.set_logTextOut_OutputPort(
0,
this->get_from_logTextOut(0)
);
// logOut
this->component.set_logOut_OutputPort(
0,
this->get_from_logOut(0)
);
// cmdResponseOut
this->component.set_cmdResponseOut_OutputPort(
0,
this->get_from_cmdResponseOut(0)
);
// tlmOut
this->component.set_tlmOut_OutputPort(
0,
this->get_from_tlmOut(0)
);
}
void Tester ::
initComponents()
{
this->init();
this->component.init(
QUEUE_DEPTH, INSTANCE
);
}
} // end namespace Ref
| 21
| 75
| 0.474301
|
AlperenCetin0
|
21db941990f5c12abc5e1a4ab9173023ce024a1c
| 1,309
|
cpp
|
C++
|
allocgc/src/details/compacting/forwarding.cpp
|
eucpp/allocgc
|
8d134d58515e0e2a7348fdd1fdbe8c2e8423cfef
|
[
"Apache-2.0"
] | null | null | null |
allocgc/src/details/compacting/forwarding.cpp
|
eucpp/allocgc
|
8d134d58515e0e2a7348fdd1fdbe8c2e8423cfef
|
[
"Apache-2.0"
] | 2
|
2017-01-17T16:24:59.000Z
|
2017-06-08T17:39:26.000Z
|
allocgc/src/details/compacting/forwarding.cpp
|
eucpp/allocgc
|
8d134d58515e0e2a7348fdd1fdbe8c2e8423cfef
|
[
"Apache-2.0"
] | null | null | null |
#include <liballocgc/details/compacting/forwarding.hpp>
#include <cassert>
#include <liballocgc/details/allocators/gc_box.hpp>
#include <liballocgc/details/logging.hpp>
#include <liballocgc/details/gc_cell.hpp>
#include <liballocgc/details/allocators/memory_index.hpp>
namespace allocgc { namespace details { namespace compacting {
void forwarding::create(byte* from, byte* to)
{
using namespace allocators;
logging::debug() << "create forwarding: from " << (void*) from << " to " << (void*) to;
gc_box::set_forward_pointer(from, to);
}
void forwarding::forward(gc_handle* handle) const
{
using namespace allocators;
byte* from = gc_handle_access::get<std::memory_order_relaxed>(*handle);
if (!from) {
return;
}
gc_cell from_cell = allocators::memory_index::get_gc_cell(from);
byte* from_cell_start = from_cell.cell_start();
byte* from_obj_start = gc_box::get_obj_start(from_cell_start);
if (!gc_box::is_forwarded(from_cell_start)) {
return;
}
byte* to_obj_start = gc_box::forward_pointer(from_cell_start);
byte* to = to_obj_start + (from - from_obj_start);
gc_handle_access::set<std::memory_order_relaxed>(*handle, to);
logging::debug() << "fix ptr: from " << (void*) from << " to " << (void*) to;
}
}}}
| 28.456522
| 91
| 0.689076
|
eucpp
|
21e26cf47313fe01fc5d803b860ecbe44ec5d0f3
| 31,727
|
hpp
|
C++
|
include/Matrix11.hpp
|
Chrinkus/advent-of-code-2020
|
15feedc68ddffe51ff2005e0cc8ab9f28fea97d8
|
[
"MIT"
] | 1
|
2021-12-04T20:55:02.000Z
|
2021-12-04T20:55:02.000Z
|
2020/cpp/include/Matrix11.hpp
|
Chrinkus/advent-of-code
|
b2ae137dc7a1d6fc9e20f29549e891404591c47f
|
[
"MIT"
] | null | null | null |
2020/cpp/include/Matrix11.hpp
|
Chrinkus/advent-of-code
|
b2ae137dc7a1d6fc9e20f29549e891404591c47f
|
[
"MIT"
] | 1
|
2020-12-17T20:00:37.000Z
|
2020-12-17T20:00:37.000Z
|
/*
warning: this small multidimensional matrix library uses a few features
not taught in ENGR112 and not explained in elementary textbooks
C++11 version
(c) Bjarne Stroustrup, Texas A&M University.
Use as you like as long as you acknowledge the source.
*/
#ifndef MATRIX_LIB
#define MATRIX_LIB
#include<string>
#include<algorithm>
//#include<iostream>
namespace Numeric_lib {
//-----------------------------------------------------------------------------
struct Matrix_error {
std::string name;
Matrix_error(const char* q) :name(q) { }
Matrix_error(std::string n) :name(n) { }
};
//-----------------------------------------------------------------------------
inline void error(const char* p)
{
throw Matrix_error(p);
}
//-----------------------------------------------------------------------------
//typedef long Index; // I still dislike unsigned
using Index = std::size_t;
//-----------------------------------------------------------------------------
// The general Matrix template is simply a prop for its specializations:
template<class T = double, int D = 1> class Matrix {
// multidimensional matrix class
// ( ) does multidimensional subscripting
// [ ] does C style "slicing": gives an N-1 dimensional matrix from an N dimensional one
// row() is equivalent to [ ]
// column() is not (yet) implemented because it requires strides.
// = has copy semantics
// ( ) and [ ] are range checked
// slice() to give sub-ranges
private:
Matrix(); // this should never be compiled
// template<class A> Matrix(A);
};
//-----------------------------------------------------------------------------
template<class T = double, int D = 1> class Row ; // forward declaration
//-----------------------------------------------------------------------------
// function objects for various apply() operations:
template<class T> struct Assign {
void operator()(T& a, const T& c) { a = c; }
};
template<class T> struct Add_assign {
void operator()(T& a, const T& c) { a += c; }
};
template<class T> struct Mul_assign {
void operator()(T& a, const T& c) { a *= c; }
};
template<class T> struct Minus_assign {
void operator()(T& a, const T& c) { a -= c; }
};
template<class T> struct Div_assign {
void operator()(T& a, const T& c) { a /= c; }
};
template<class T> struct Mod_assign {
void operator()(T& a, const T& c) { a %= c; }
};
template<class T> struct Or_assign {
void operator()(T& a, const T& c) { a |= c; }
};
template<class T> struct Xor_assign {
void operator()(T& a, const T& c) { a ^= c; }
};
template<class T> struct And_assign {
void operator()(T& a, const T& c) { a &= c; }
};
template<class T> struct Not_assign {
void operator()(T& a) { a = !a; }
};
template<class T> struct Not {
T operator()(T& a) { return !a; }
};
template<class T> struct Unary_minus {
T operator()(T& a) { return -a; }
};
template<class T> struct Complement {
T operator()(T& a) { return ~a; }
};
//-----------------------------------------------------------------------------
// Matrix_base represents the common part of the Matrix classes:
template<class T> class Matrix_base {
// matrixs store their memory (elements) in Matrix_base and have copy semantics
// Matrix_base does element-wise operations
protected:
T* elem; // vector? no: we couldn't easily provide a vector for a slice
const Index sz;
mutable bool owns;
mutable bool xfer;
public:
Matrix_base(Index n) :elem(new T[n]()), sz(n), owns(true), xfer(false)
// matrix of n elements (default initialized)
{
// std::cerr << "new[" << n << "]->" << elem << "\n";
}
Matrix_base(Index n, T* p) :elem(p), sz(n), owns(false), xfer(false)
// descriptor for matrix of n elements owned by someone else
{
}
~Matrix_base()
{
if (owns) {
// std::cerr << "delete[" << sz << "] " << elem << "\n";
delete[]elem;
}
}
// if necessay, we can get to the raw matrix:
T* data() { return elem; }
const T* data() const { return elem; }
Index size() const { return sz; }
void copy_elements(const Matrix_base& a)
{
if (sz!=a.sz) error("copy_elements()");
for (Index i=0; i<sz; ++i) elem[i] = a.elem[i];
}
void base_assign(const Matrix_base& a) { copy_elements(a); }
void base_copy(const Matrix_base& a)
{
if (a.xfer) { // a is just about to be deleted
// so we can transfer ownership rather than copy
// std::cerr << "xfer @" << a.elem << " [" << a.sz << "]\n";
elem = a.elem;
a.xfer = false; // note: modifies source
a.owns = false;
}
else {
elem = new T[a.sz];
// std::cerr << "base copy @" << a.elem << " [" << a.sz << "]\n";
copy_elements(a);
}
owns = true;
xfer = false;
}
// to get the elements of a local matrix out of a function without copying:
void base_xfer(Matrix_base& x)
{
if (owns==false) error("cannot xfer() non-owner");
owns = false; // now the elements are safe from deletion by original owner
x.xfer = true; // target asserts temporary ownership
x.owns = true;
}
template<class F> void base_apply(F f) { for (Index i = 0; i<size(); ++i) f(elem[i]); }
template<class F> void base_apply(F f, const T& c) { for (Index i = 0; i<size(); ++i) f(elem[i],c); }
private:
void operator=(const Matrix_base&); // no ordinary copy of bases
Matrix_base(const Matrix_base&);
};
//-----------------------------------------------------------------------------
template<class T> class Matrix<T,1> : public Matrix_base<T> {
const Index d1;
protected:
// for use by Row:
Matrix(Index n1, T* p) : Matrix_base<T>(n1,p), d1(n1)
{
// std::cerr << "construct 1D Matrix from data\n";
}
public:
Matrix(Index n1) : Matrix_base<T>(n1), d1(n1) { }
Matrix(Row<T,1>& a) : Matrix_base<T>(a.dim1(),a.p), d1(a.dim1())
{
// std::cerr << "construct 1D Matrix from Row\n";
}
// copy constructor: let the base do the copy:
Matrix(const Matrix& a) : Matrix_base<T>(a.size(),0), d1(a.d1)
{
// std::cerr << "copy ctor\n";
this->base_copy(a);
}
template<int n>
Matrix(const T (&a)[n]) : Matrix_base<T>(n), d1(n)
// deduce "n" (and "T"), Matrix_base allocates T[n]
{
// std::cerr << "matrix ctor\n";
for (Index i = 0; i<n; ++i) this->elem[i]=a[i];
}
Matrix(const T* p, Index n) : Matrix_base<T>(n), d1(n)
// Matrix_base allocates T[n]
{
// std::cerr << "matrix ctor\n";
for (Index i = 0; i<n; ++i) this->elem[i]=p[i];
}
template<class F> Matrix(const Matrix& a, F f) : Matrix_base<T>(a.size()), d1(a.d1)
// construct a new Matrix with element's that are functions of a's elements:
// does not modify a unless f has been specifically programmed to modify its argument
// T f(const T&) would be a typical type for f
{
for (Index i = 0; i<this->sz; ++i) this->elem[i] = f(a.elem[i]);
}
template<class F, class Arg> Matrix(const Matrix& a, F f, const Arg& t1) : Matrix_base<T>(a.size()), d1(a.d1)
// construct a new Matrix with element's that are functions of a's elements:
// does not modify a unless f has been specifically programmed to modify its argument
// T f(const T&, const Arg&) would be a typical type for f
{
for (Index i = 0; i<this->sz; ++i) this->elem[i] = f(a.elem[i],t1);
}
Matrix& operator=(const Matrix& a)
// copy assignment: let the base do the copy
{
// std::cerr << "copy assignment (" << this->size() << ',' << a.size()<< ")\n";
if (d1!=a.d1) error("length error in 1D=");
this->base_assign(a);
return *this;
}
~Matrix() { }
Index dim1() const { return d1; } // number of elements in a row
Matrix xfer() // make an Matrix to move elements out of a scope
{
Matrix x(dim1(),this->data()); // make a descriptor
this->base_xfer(x); // transfer (temporary) ownership to x
return x;
}
void range_check(Index n1) const
{
// std::cerr << "range check: (" << d1 << "): " << n1 << "\n";
if (n1<0 || d1<=n1) error("1D range error: dimension 1");
}
// subscripting:
T& operator()(Index n1) { range_check(n1); return this->elem[n1]; }
const T& operator()(Index n1) const { range_check(n1); return this->elem[n1]; }
// slicing (the same as subscripting for 1D matrixs):
T& operator[](Index n) { return row(n); }
const T& operator[](Index n) const { return row(n); }
T& row(Index n) { range_check(n); return this->elem[n]; }
const T& row(Index n) const { range_check(n); return this->elem[n]; }
Row<T,1> slice(Index n)
// the last elements from a[n] onwards
{
if (n<0) n=0;
else if(d1<n) n=d1;// one beyond the end
return Row<T,1>(d1-n,this->elem+n);
}
const Row<T,1> slice(Index n) const
// the last elements from a[n] onwards
{
if (n<0) n=0;
else if(d1<n) n=d1;// one beyond the end
return Row<T,1>(d1-n,this->elem+n);
}
Row<T,1> slice(Index n, Index m)
// m elements starting with a[n]
{
if (n<0) n=0;
else if(d1<n) n=d1; // one beyond the end
if (m<0) m = 0;
else if (d1<n+m) m=d1-n;
return Row<T,1>(m,this->elem+n);
}
const Row<T,1> slice(Index n, Index m) const
// m elements starting with a[n]
{
if (n<0) n=0;
else if(d1<n) n=d1; // one beyond the end
if (m<0) m = 0;
else if (d1<n+m) m=d1-n;
return Row<T,1>(m,this->elem+n);
}
// element-wise operations:
template<class F> Matrix& apply(F f) { this->base_apply(f); return *this; }
template<class F> Matrix& apply(F f,const T& c) { this->base_apply(f,c); return *this; }
Matrix& operator=(const T& c) { this->base_apply(Assign<T>(),c); return *this; }
Matrix& operator*=(const T& c) { this->base_apply(Mul_assign<T>(),c); return *this; }
Matrix& operator/=(const T& c) { this->base_apply(Div_assign<T>(),c); return *this; }
Matrix& operator%=(const T& c) { this->base_apply(Mod_assign<T>(),c); return *this; }
Matrix& operator+=(const T& c) { this->base_apply(Add_assign<T>(),c); return *this; }
Matrix& operator-=(const T& c) { this->base_apply(Minus_assign<T>(),c); return *this; }
Matrix& operator&=(const T& c) { this->base_apply(And_assign<T>(),c); return *this; }
Matrix& operator|=(const T& c) { this->base_apply(Or_assign<T>(),c); return *this; }
Matrix& operator^=(const T& c) { this->base_apply(Xor_assign<T>(),c); return *this; }
Matrix operator!() { return xfer(Matrix(*this,Not<T>())); }
Matrix operator-() { return xfer(Matrix(*this,Unary_minus<T>())); }
Matrix operator~() { return xfer(Matrix(*this,Complement<T>())); }
template<class F> Matrix apply_new(F f) { return xfer(Matrix(*this,f)); }
void swap_rows(Index i, Index j)
// swap_rows() uses a row's worth of memory for better run-time performance
// if you want pairwise swap, just write it yourself
{
if (i == j) return;
/*
Matrix<T,1> temp = (*this)[i];
(*this)[i] = (*this)[j];
(*this)[j] = temp;
*/
Index max = (*this)[i].size();
for (Index ii=0; ii<max; ++ii) std::swap((*this)(i,ii),(*this)(j,ii));
}
};
//-----------------------------------------------------------------------------
template<class T> class Matrix<T,2> : public Matrix_base<T> {
const Index d1;
const Index d2;
protected:
// for use by Row:
Matrix(Index n1, Index n2, T* p) : Matrix_base<T>(n1*n2,p), d1(n1), d2(n2)
{
// std::cerr << "construct 3D Matrix from data\n";
}
public:
Matrix(Index n1, Index n2) : Matrix_base<T>(n1*n2), d1(n1), d2(n2) { }
Matrix(Row<T,2>& a) : Matrix_base<T>(a.dim1()*a.dim2(),a.p), d1(a.dim1()), d2(a.dim2())
{
// std::cerr << "construct 2D Matrix from Row\n";
}
// copy constructor: let the base do the copy:
Matrix(const Matrix& a) : Matrix_base<T>(a.size(),0), d1(a.d1), d2(a.d2)
{
// std::cerr << "copy ctor\n";
this->base_copy(a);
}
template<int n1, int n2>
Matrix(const T (&a)[n1][n2]) : Matrix_base<T>(n1*n2), d1(n1), d2(n2)
// deduce "n1", "n2" (and "T"), Matrix_base allocates T[n1*n2]
{
// std::cerr << "matrix ctor (" << n1 << "," << n2 << ")\n";
for (Index i = 0; i<n1; ++i)
for (Index j = 0; j<n2; ++j) this->elem[i*n2+j]=a[i][j];
}
template<class F> Matrix(const Matrix& a, F f) : Matrix_base<T>(a.size()), d1(a.d1), d2(a.d2)
// construct a new Matrix with element's that are functions of a's elements:
// does not modify a unless f has been specifically programmed to modify its argument
// T f(const T&) would be a typical type for f
{
for (Index i = 0; i<this->sz; ++i) this->elem[i] = f(a.elem[i]);
}
template<class F, class Arg> Matrix(const Matrix& a, F f, const Arg& t1) : Matrix_base<T>(a.size()), d1(a.d1), d2(a.d2)
// construct a new Matrix with element's that are functions of a's elements:
// does not modify a unless f has been specifically programmed to modify its argument
// T f(const T&, const Arg&) would be a typical type for f
{
for (Index i = 0; i<this->sz; ++i) this->elem[i] = f(a.elem[i],t1);
}
Matrix& operator=(const Matrix& a)
// copy assignment: let the base do the copy
{
// std::cerr << "copy assignment (" << this->size() << ',' << a.size()<< ")\n";
if (d1!=a.d1 || d2!=a.d2) error("length error in 2D =");
this->base_assign(a);
return *this;
}
~Matrix() { }
Index dim1() const { return d1; } // number of elements in a row
Index dim2() const { return d2; } // number of elements in a column
Matrix xfer() // make an Matrix to move elements out of a scope
{
Matrix x(dim1(),dim2(),this->data()); // make a descriptor
this->base_xfer(x); // transfer (temporary) ownership to x
return x;
}
void range_check(Index n1, Index n2) const
{
// std::cerr << "range check: (" << d1 << "," << d2 << "): " << n1 << " " << n2 << "\n";
if (n1<0 || d1<=n1) error("2D range error: dimension 1");
if (n2<0 || d2<=n2) error("2D range error: dimension 2");
}
// subscripting:
T& operator()(Index n1, Index n2) { range_check(n1,n2); return this->elem[n1*d2+n2]; }
const T& operator()(Index n1, Index n2) const { range_check(n1,n2); return this->elem[n1*d2+n2]; }
// slicing (return a row):
Row<T,1> operator[](Index n) { return row(n); }
const Row<T,1> operator[](Index n) const { return row(n); }
Row<T,1> row(Index n) { range_check(n,0); return Row<T,1>(d2,&this->elem[n*d2]); }
const Row<T,1> row(Index n) const { range_check(n,0); return Row<T,1>(d2,&this->elem[n*d2]); }
Row<T,2> slice(Index n)
// rows [n:d1)
{
if (n<0) n=0;
else if(d1<n) n=d1; // one beyond the end
return Row<T,2>(d1-n,d2,this->elem+n*d2);
}
const Row<T,2> slice(Index n) const
// rows [n:d1)
{
if (n<0) n=0;
else if(d1<n) n=d1; // one beyond the end
return Row<T,2>(d1-n,d2,this->elem+n*d2);
}
Row<T,2> slice(Index n, Index m)
// the rows [n:m)
{
if (n<0) n=0;
if(d1<m) m=d1; // one beyond the end
return Row<T,2>(m-n,d2,this->elem+n*d2);
}
const Row<T,2> slice(Index n, Index m) const
// the rows [n:sz)
{
if (n<0) n=0;
if(d1<m) m=d1; // one beyond the end
return Row<T,2>(m-n,d2,this->elem+n*d2);
}
// Column<T,1> column(Index n); // not (yet) implemented: requies strides and operations on columns
// element-wise operations:
template<class F> Matrix& apply(F f) { this->base_apply(f); return *this; }
template<class F> Matrix& apply(F f,const T& c) { this->base_apply(f,c); return *this; }
Matrix& operator=(const T& c) { this->base_apply(Assign<T>(),c); return *this; }
Matrix& operator*=(const T& c) { this->base_apply(Mul_assign<T>(),c); return *this; }
Matrix& operator/=(const T& c) { this->base_apply(Div_assign<T>(),c); return *this; }
Matrix& operator%=(const T& c) { this->base_apply(Mod_assign<T>(),c); return *this; }
Matrix& operator+=(const T& c) { this->base_apply(Add_assign<T>(),c); return *this; }
Matrix& operator-=(const T& c) { this->base_apply(Minus_assign<T>(),c); return *this; }
Matrix& operator&=(const T& c) { this->base_apply(And_assign<T>(),c); return *this; }
Matrix& operator|=(const T& c) { this->base_apply(Or_assign<T>(),c); return *this; }
Matrix& operator^=(const T& c) { this->base_apply(Xor_assign<T>(),c); return *this; }
Matrix operator!() { return xfer(Matrix(*this,Not<T>())); }
Matrix operator-() { return xfer(Matrix(*this,Unary_minus<T>())); }
Matrix operator~() { return xfer(Matrix(*this,Complement<T>())); }
template<class F> Matrix apply_new(F f) { return xfer(Matrix(*this,f)); }
void swap_rows(Index i, Index j)
// swap_rows() uses a row's worth of memory for better run-time performance
// if you want pairwise swap, just write it yourself
{
if (i == j) return;
/*
Matrix<T,1> temp = (*this)[i];
(*this)[i] = (*this)[j];
(*this)[j] = temp;
*/
Index max = (*this)[i].size();
for (Index ii=0; ii<max; ++ii) std::swap((*this)(i,ii),(*this)(j,ii));
}
};
//-----------------------------------------------------------------------------
template<class T> class Matrix<T,3> : public Matrix_base<T> {
const Index d1;
const Index d2;
const Index d3;
protected:
// for use by Row:
Matrix(Index n1, Index n2, Index n3, T* p) : Matrix_base<T>(n1*n2*n3,p), d1(n1), d2(n2), d3(n3)
{
// std::cerr << "construct 3D Matrix from data\n";
}
public:
Matrix(Index n1, Index n2, Index n3) : Matrix_base<T>(n1*n2*n3), d1(n1), d2(n2), d3(n3) { }
Matrix(Row<T,3>& a) : Matrix_base<T>(a.dim1()*a.dim2()*a.dim3(),a.p), d1(a.dim1()), d2(a.dim2()), d3(a.dim3())
{
// std::cerr << "construct 3D Matrix from Row\n";
}
// copy constructor: let the base do the copy:
Matrix(const Matrix& a) : Matrix_base<T>(a.size(),0), d1(a.d1), d2(a.d2), d3(a.d3)
{
// std::cerr << "copy ctor\n";
this->base_copy(a);
}
template<int n1, int n2, int n3>
Matrix(const T (&a)[n1][n2][n3]) : Matrix_base<T>(n1*n2), d1(n1), d2(n2), d3(n3)
// deduce "n1", "n2", "n3" (and "T"), Matrix_base allocates T[n1*n2*n3]
{
// std::cerr << "matrix ctor\n";
for (Index i = 0; i<n1; ++i)
for (Index j = 0; j<n2; ++j)
for (Index k = 0; k<n3; ++k)
this->elem[i*n2*n3+j*n3+k]=a[i][j][k];
}
template<class F> Matrix(const Matrix& a, F f) : Matrix_base<T>(a.size()), d1(a.d1), d2(a.d2), d3(a.d3)
// construct a new Matrix with element's that are functions of a's elements:
// does not modify a unless f has been specifically programmed to modify its argument
// T f(const T&) would be a typical type for f
{
for (Index i = 0; i<this->sz; ++i) this->elem[i] = f(a.elem[i]);
}
template<class F, class Arg> Matrix(const Matrix& a, F f, const Arg& t1) : Matrix_base<T>(a.size()), d1(a.d1), d2(a.d2), d3(a.d3)
// construct a new Matrix with element's that are functions of a's elements:
// does not modify a unless f has been specifically programmed to modify its argument
// T f(const T&, const Arg&) would be a typical type for f
{
for (Index i = 0; i<this->sz; ++i) this->elem[i] = f(a.elem[i],t1);
}
Matrix& operator=(const Matrix& a)
// copy assignment: let the base do the copy
{
// std::cerr << "copy assignment (" << this->size() << ',' << a.size()<< ")\n";
if (d1!=a.d1 || d2!=a.d2 || d3!=a.d3) error("length error in 2D =");
this->base_assign(a);
return *this;
}
~Matrix() { }
Index dim1() const { return d1; } // number of elements in a row
Index dim2() const { return d2; } // number of elements in a column
Index dim3() const { return d3; } // number of elements in a depth
Matrix xfer() // make an Matrix to move elements out of a scope
{
Matrix x(dim1(),dim2(),dim3(),this->data()); // make a descriptor
this->base_xfer(x); // transfer (temporary) ownership to x
return x;
}
void range_check(Index n1, Index n2, Index n3) const
{
// std::cerr << "range check: (" << d1 << "," << d2 << "): " << n1 << " " << n2 << "\n";
if (n1<0 || d1<=n1) error("3D range error: dimension 1");
if (n2<0 || d2<=n2) error("3D range error: dimension 2");
if (n3<0 || d3<=n3) error("3D range error: dimension 3");
}
// subscripting:
T& operator()(Index n1, Index n2, Index n3) { range_check(n1,n2,n3); return this->elem[d2*d3*n1+d3*n2+n3]; };
const T& operator()(Index n1, Index n2, Index n3) const { range_check(n1,n2,n3); return this->elem[d2*d3*n1+d3*n2+n3]; };
// slicing (return a row):
Row<T,2> operator[](Index n) { return row(n); }
const Row<T,2> operator[](Index n) const { return row(n); }
Row<T,2> row(Index n) { range_check(n,0,0); return Row<T,2>(d2,d3,&this->elem[n*d2*d3]); }
const Row<T,2> row(Index n) const { range_check(n,0,0); return Row<T,2>(d2,d3,&this->elem[n*d2*d3]); }
Row<T,3> slice(Index n)
// rows [n:d1)
{
if (n<0) n=0;
else if(d1<n) n=d1; // one beyond the end
return Row<T,3>(d1-n,d2,d3,this->elem+n*d2*d3);
}
const Row<T,3> slice(Index n) const
// rows [n:d1)
{
if (n<0) n=0;
else if(d1<n) n=d1; // one beyond the end
return Row<T,3>(d1-n,d2,d3,this->elem+n*d2*d3);
}
Row<T,3> slice(Index n, Index m)
// the rows [n:m)
{
if (n<0) n=0;
if(d1<m) m=d1; // one beyond the end
return Row<T,3>(m-n,d2,d3,this->elem+n*d2*d3);
}
const Row<T,3> slice(Index n, Index m) const
// the rows [n:sz)
{
if (n<0) n=0;
if(d1<m) m=d1; // one beyond the end
return Row<T,3>(m-n,d2,d3,this->elem+n*d2*d3);
}
// Column<T,2> column(Index n); // not (yet) implemented: requies strides and operations on columns
// element-wise operations:
template<class F> Matrix& apply(F f) { this->base_apply(f); return *this; }
template<class F> Matrix& apply(F f,const T& c) { this->base_apply(f,c); return *this; }
Matrix& operator=(const T& c) { this->base_apply(Assign<T>(),c); return *this; }
Matrix& operator*=(const T& c) { this->base_apply(Mul_assign<T>(),c); return *this; }
Matrix& operator/=(const T& c) { this->base_apply(Div_assign<T>(),c); return *this; }
Matrix& operator%=(const T& c) { this->base_apply(Mod_assign<T>(),c); return *this; }
Matrix& operator+=(const T& c) { this->base_apply(Add_assign<T>(),c); return *this; }
Matrix& operator-=(const T& c) { this->base_apply(Minus_assign<T>(),c); return *this; }
Matrix& operator&=(const T& c) { this->base_apply(And_assign<T>(),c); return *this; }
Matrix& operator|=(const T& c) { this->base_apply(Or_assign<T>(),c); return *this; }
Matrix& operator^=(const T& c) { this->base_apply(Xor_assign<T>(),c); return *this; }
Matrix operator!() { return xfer(Matrix(*this,Not<T>())); }
Matrix operator-() { return xfer(Matrix(*this,Unary_minus<T>())); }
Matrix operator~() { return xfer(Matrix(*this,Complement<T>())); }
template<class F> Matrix apply_new(F f) { return xfer(Matrix(*this,f)); }
void swap_rows(Index i, Index j)
// swap_rows() uses a row's worth of memory for better run-time performance
// if you want pairwise swap, just write it yourself
{
if (i == j) return;
Matrix<T,2> temp = (*this)[i];
(*this)[i] = (*this)[j];
(*this)[j] = temp;
}
};
//-----------------------------------------------------------------------------
template<class T> Matrix<T> scale_and_add(const Matrix<T>& a, T c, const Matrix<T>& b)
// Fortran "saxpy()" ("fma" for "fused multiply-add").
// will the copy constructor be called twice and defeat the xfer optimization?
{
if (a.size() != b.size()) error("sizes wrong for scale_and_add()");
Matrix<T> res(a.size());
for (Index i = 0; i<a.size(); ++i) res[i] += a[i]*c+b[i];
return res.xfer();
}
//-----------------------------------------------------------------------------
template<class T> T dot_product(const Matrix<T>&a , const Matrix<T>& b)
{
if (a.size() != b.size()) error("sizes wrong for dot product");
T sum = 0;
for (Index i = 0; i<a.size(); ++i) sum += a[i]*b[i];
return sum;
}
//-----------------------------------------------------------------------------
template<class T, int N> Matrix<T,N> xfer(Matrix<T,N>& a)
{
return a.xfer();
}
//-----------------------------------------------------------------------------
template<class F, class A> A apply(F f, A x) { A res(x,f); return xfer(res); }
template<class F, class Arg, class A> A apply(F f, A x, Arg a) { A res(x,f,a); return xfer(res); }
//-----------------------------------------------------------------------------
// The default values for T and D have been declared before.
template<class T, int D> class Row {
// general version exists only to allow specializations
private:
Row();
};
//-----------------------------------------------------------------------------
template<class T> class Row<T,1> : public Matrix<T,1> {
public:
Row(Index n, T* p) : Matrix<T,1>(n,p)
{
}
Matrix<T,1>& operator=(const T& c) { this->base_apply(Assign<T>(),c); return *this; }
Matrix<T,1>& operator=(const Matrix<T,1>& a)
{
return *static_cast<Matrix<T,1>*>(this)=a;
}
};
//-----------------------------------------------------------------------------
template<class T> class Row<T,2> : public Matrix<T,2> {
public:
Row(Index n1, Index n2, T* p) : Matrix<T,2>(n1,n2,p)
{
}
Matrix<T,2>& operator=(const T& c) { this->base_apply(Assign<T>(),c); return *this; }
Matrix<T,2>& operator=(const Matrix<T,2>& a)
{
return *static_cast<Matrix<T,2>*>(this)=a;
}
};
//-----------------------------------------------------------------------------
template<class T> class Row<T,3> : public Matrix<T,3> {
public:
Row(Index n1, Index n2, Index n3, T* p) : Matrix<T,3>(n1,n2,n3,p)
{
}
Matrix<T,3>& operator=(const T& c) { this->base_apply(Assign<T>(),c); return *this; }
Matrix<T,3>& operator=(const Matrix<T,3>& a)
{
return *static_cast<Matrix<T,3>*>(this)=a;
}
};
//-----------------------------------------------------------------------------
template<class T, int N> Matrix<T,N-1> scale_and_add(const Matrix<T,N>& a, const Matrix<T,N-1> c, const Matrix<T,N-1>& b)
{
Matrix<T> res(a.size());
if (a.size() != b.size()) error("sizes wrong for scale_and_add");
for (Index i = 0; i<a.size(); ++i) res[i] += a[i]*c+b[i];
return res.xfer();
}
//-----------------------------------------------------------------------------
template<class T, int D> Matrix<T,D> operator*(const Matrix<T,D>& m, const T& c) { Matrix<T,D> r(m); return r*=c; }
template<class T, int D> Matrix<T,D> operator/(const Matrix<T,D>& m, const T& c) { Matrix<T,D> r(m); return r/=c; }
template<class T, int D> Matrix<T,D> operator%(const Matrix<T,D>& m, const T& c) { Matrix<T,D> r(m); return r%=c; }
template<class T, int D> Matrix<T,D> operator+(const Matrix<T,D>& m, const T& c) { Matrix<T,D> r(m); return r+=c; }
template<class T, int D> Matrix<T,D> operator-(const Matrix<T,D>& m, const T& c) { Matrix<T,D> r(m); return r-=c; }
template<class T, int D> Matrix<T,D> operator&(const Matrix<T,D>& m, const T& c) { Matrix<T,D> r(m); return r&=c; }
template<class T, int D> Matrix<T,D> operator|(const Matrix<T,D>& m, const T& c) { Matrix<T,D> r(m); return r|=c; }
template<class T, int D> Matrix<T,D> operator^(const Matrix<T,D>& m, const T& c) { Matrix<T,D> r(m); return r^=c; }
//-----------------------------------------------------------------------------
template<class T> class Matrix<T,4> : public Matrix_base<T> {
private:
const Index d1;
const Index d2;
const Index d3;
const Index d4;
protected:
// for use by Row:
Matrix(Index n1, Index n2, Index n3, Index n4, T* p)
: Matrix_base<T>{n1*n2*n3*n4,p},
d1{n1}, d2{n2}, d3{n3}, d4{n4}
{
// std::cerr << "construct 4D Matrix from data\n";
}
public:
Matrix(Index n1, Index n2, Index n3, Index n4)
: Matrix_base<T>{n1*n2*n3*n4}, d1{n1}, d2{n2}, d3{n3}, d4{n4} { }
Matrix(const Matrix& a)
: Matrix_base<T>{a.size(), 0}, d1{a.d1}, d2{a.d2}, d3{a.d3}, d4{a.d4}
{
this->base_copy(a);
}
Matrix& operator=(const Matrix& a)
{
if (d1!=a.d1 || d2!=a.d2 || d3!=a.d3 || d4!=a.d4)
error("length error in 3D =");
this->base_assign(a);
return *this;
}
~Matrix() { }
Index dim1() const { return d1; }
Index dim2() const { return d2; }
Index dim3() const { return d3; }
Index dim4() const { return d4; }
Matrix xfer()
{
Matrix x {dim1(), dim2(), dim3(), dim4(), this->data()};
this->base_xfer(x);
return x;
}
void range_check(Index n1, Index n2, Index n3, Index n4) const
{
if (n1 < 0 || d1 <= n1) error("4D range error: dimension 1");
if (n2 < 0 || d2 <= n2) error("4D range error: dimension 2");
if (n3 < 0 || d3 <= n3) error("4D range error: dimension 3");
if (n4 < 0 || d4 <= n4) error("4D range error: dimension 4");
}
// subscripting:
T& operator()(Index n1, Index n2, Index n3, Index n4)
{
range_check(n1,n2,n3,n4);
return this->elem[d2*d3*d4*n1+d3*d4*n2+d4*n3+n4];
}
const T& operator()(Index n1, Index n2, Index n3, Index n4) const
{
range_check(n1,n2,n3,n4);
return this->elem[d2*d3*d4*n1+d3*d4*n2+d4*n3+n4];
}
// slicing (return a row)
Row<T,3> operator[](Index n) { return row(n); }
const Row<T,3> operator[](Index n) const { return row(n); }
Row<T,3> row(Index n)
{
range_check(n,0,0,0);
return Row<T,3>(d2,d3,d4,&this->elem[n*d2*d3*d4]);
}
const Row<T,3> row(Index n) const
{
range_check(n,0,0,0);
return Row<T,3>(d2,d3,d4,&this->elem[n*d2*d3*d4]);
}
Matrix& operator=(const T& c)
{
this->base_apply(Assign<T>(),c);
return *this;
}
};
}
#endif
| 35.330735
| 133
| 0.527154
|
Chrinkus
|
21f0ead7b9852c9196611c01f55c43cb6f2fe46e
| 12,955
|
cpp
|
C++
|
tests/misc.cpp
|
JackWolfard/cash
|
a646c0b94d075fa424a93904b7499a0dee90ac89
|
[
"BSD-3-Clause"
] | 14
|
2018-08-08T19:02:21.000Z
|
2022-01-07T14:42:43.000Z
|
tests/misc.cpp
|
JackWolfard/cash
|
a646c0b94d075fa424a93904b7499a0dee90ac89
|
[
"BSD-3-Clause"
] | null | null | null |
tests/misc.cpp
|
JackWolfard/cash
|
a646c0b94d075fa424a93904b7499a0dee90ac89
|
[
"BSD-3-Clause"
] | 3
|
2020-04-20T20:58:34.000Z
|
2021-11-23T14:50:14.000Z
|
#include "common.h"
#include <htl/complex.h>
#include <htl/queue.h>
#include <htl/fixed.h>
using namespace ch::htl;
using namespace ch::extension;
namespace {
__enum (my_enum, 4, (
(idle, 0),
execute,
stats,
done
));
__struct (Person, (
(ch_int4) age,
(ch_int4) height
));
template <typename T>
auto sbind(const T& a, const T& b) {
return std::tuple(a + b, a - b);
}
template <typename T>
struct SubPrint {
__io (
__in (T) in,
__out (T) out
);
void describe() {
io.out = io.in;
__if (io.in[0]) {
ch_println("io.in={0}", io.in);
};
}
};
template <typename T>
struct Print {
__io (
__in (T) in,
__out (T) out
);
void describe() {
ch_module<SubPrint<T>> m;
m.io.in = io.in;
io.out = m.io.out;
ch_println("io.in={0}", io.in);
}
};
template <typename T>
struct Bypass2 {
__io (
__in (T) in,
__out (T) out
);
void describe() {
tap_ = (io.in << 1);
io.out = (tap_ >> 1);
}
T tap_;
};
template <typename T>
struct Bypass {
__io (
__in (T) in,
__out (T) out
);
void describe() {
bypass_.io.in = io.in;
io.out = bypass_.io.out;
}
ch_module<Bypass2<T>> bypass_;
};
}
TEST_CASE("misc", "[misc]") {
SECTION("sbind", "[sbind]") {
TEST([]()->ch_bool {
ch_int4 a(0_h), b(1_h);
auto q = sbind(a, b);
auto [x, y] = q;
return (x == 1 && y == -1);
});
TEST([]()->ch_bool {
ch_fixed<8, 4> a(00_h), b(10_h);
auto q = sbind(a, b);
auto [x, y] = q;
return (x == 10_h && y == -16);
});
TEST([]()->ch_bool {
ch_complex<ch_int4> a(0, 0), b(1, 1);
auto q = sbind(a, b);
auto [x, y] = q;
return (x == ch_complex<ch_int4>(1, 1)
&& y == ch_complex<ch_int4>(-1, -1));
});
}
SECTION("utils", "[utils]") {
TESTX([]()->bool {
char bigs[258];
memset(bigs, ' ', sizeof(bigs));
bigs[255] = '%';
bigs[256] = 'd';
bigs[257] = '\0';
std::string s = stringf(bigs, 7);
std::cout << s << " " << s.size() << std::endl;
return (s.size() == 256 && s[255] == '7');
});
TESTX([]()->bool {
std::string tmp(1028, 'X');
std::string s = stringf(tmp.c_str());
return true;
});
}
SECTION("assert", "[assert]") {
TEST([]()->ch_bool {
ch_bit4 a(1100_b);
auto c = ch_slice<2>(a, 1) ^ 01_b;
ch_assert(c == 11_b, "assertion failed!");
return (c == 11_b);
});
TEST([]()->ch_bool {
ch_bit4 a(1100_b), b(1);
auto c = ch_slice<2>(a, 1) ^ 01_b;
__if (b == 1) {
ch_assert(c == 11_b, "assertion failed!");
} __else {
ch_assert(c != 11_b, "assertion failed!");
};
return (c == 11_b);
});
}
SECTION("taps", "[tap]") {
TESTX([]()->bool {
auto_cflags_enable dump_enable(ch_flags::dump_cfg | ch_flags::debug_cfg);
ch_device<GenericModule2<ch_uint4, ch_uint4, ch_uint4>> device(
[](auto lhs, auto rhs) {
auto ret = (lhs + rhs) / 2;
__tap(ret);
return ret;
}
);
ch_toVerilog("taps.v", device);
device.io.lhs = 5;
device.io.rhs = 3;
ch_tracer trace(device);
trace.run(2);
RetCheck ret;
ret &= (device.io.out == 4);
trace.toText("taps.log");
trace.toVCD("taps.vcd");
trace.toVerilog("taps_tb.v", "taps.v");
ret &= (checkVerilog("taps_tb.v"));
return ret;
});
TESTX([]()->bool {
auto_cflags_enable dump_enable(ch_flags::dump_cfg | ch_flags::debug_cfg);
ch_device<GenericModule2<ch_uint4, ch_uint4, ch_uint4>> device(
[](auto lhs, auto rhs) {
auto f = [](auto in) {
auto ret = (in << 1) / 2;
__tap(ret);
return ret;
};
ch_vec<ch_module<GenericModule<ch_uint4, ch_uint4>>, 2> m{f, f};
m[0].io.in = lhs;
m[1].io.in = rhs;
auto ret = (m[0].io.out + m[1].io.out) / 2;
return ret;
}
);
ch_toVerilog("taps2.v", device);
device.io.lhs = 5;
device.io.rhs = 3;
ch_tracer trace(device);
trace.run(2);
RetCheck ret;
ret &= (device.io.out == 4);
trace.toText("taps2.log");
trace.toVCD("taps2.vcd");
trace.toVerilog("taps2_tb.v", "taps2.v");
ret &= (checkVerilog("taps2_tb.v"));
return ret;
});
}
SECTION("tick", "[tick]") {
TEST([]()->ch_bool {
return (0 == ch_now());
});
}
SECTION("print", "[print]") {
TEST([]()->ch_bool {
ch_println("hello world");
return ch_true;
});
TEST([]()->ch_bool {
ch_println("a=%d, b=%f", 1, 2.0f);
return ch_true;
});
TEST([]()->ch_bool {
ch_bit128 a(0x5555);
ch_println("a={0}", a);
return ch_true;
});
TEST([]()->ch_bool {
ch_bit128 a(0x5555);
ch_println("a=%d, b=%f", 1, 2.0f, a);
return ch_true;
});
TEST([]()->ch_bool {
ch_bit8 a(255), b(0);
ch_println("x=%f, y=%d, z=%f, a={}, b={}", a, 0.0f, b, 1, 2.0f);
return ch_true;
});
TEST([]()->ch_bool {
ch_bit8 a(255);
ch_println("a={0}", a);
return ch_true;
});
TESTX([]()->bool {
ch_device<Print<ch_bit128>> device;
device.io.in = 0x5555;
ch_simulator sim(device);
sim.run(2);
return (device.io.out == 0x5555);
});
TEST([]()->ch_bool {
ch_bit8 a(255), b(0);
ch_println("a={}, b={}", a, b);
ch_println("a={0}, b={}", a, b);
ch_println("a={}, b={1}", a, b);
ch_println("a={0}, b={1}", a, b);
return ch_true;
});
TEST1([](const ch_int8& pred)->ch_bool {
ch_int8 a(1), b(2);
__if (pred != 0) {
ch_println("a={}", a);
__if (pred > 0) {
ch_println("b={}", b);
}__else {
ch_println("b={}", -b);
};
};
return ch_true;
});
TEST([]()->ch_bool {
ch_int4 a(-1);
ch_println("a={0:i}", a);
return ch_true;
});
TEST([]()->ch_bool {
ch_int32 a(0x3e800000_h);
ch_println("a={0:f}", a);
return ch_true;
});
TEST([]()->ch_bool {
my_enum a(my_enum::done);
ch_println("a={0:e}", a);
return ch_true;
});
}
SECTION("streams", "[streams]") {
TEST([]()->ch_bool {
unsigned char a(1);
short b(1);
unsigned short c(1);
long double d(1);
ch_cout << true << ',' << a << "," << b << ", " << c << ", " << d << ", " << 1 << ", " << 1u << ", " << 1l << ", " << 1ul << ", " << 1ll << ", " << 1ull << ", " << 1.0f << ", " << 1.0;
return ch_true;
});
TEST([]()->ch_bool {
ch_int8 a(1), b(2);
ch_bool c(false);
ch_cout << "a={" << a << "}, b={" << b << "}, c={" << c << "}" << std::endl;
return ch_true;
});
TEST1([](const ch_int8& pred)->ch_bool {
ch_int8 a(1), b(2);
__if (pred != 0) {
ch_cout << "a=" << a;
__if (pred > 0) {
ch_cout << "b=" << b;
}__else {
ch_cout << "b=" << -b;
};
};
return ch_true;
});
TEST1([](const ch_int8& pred)->ch_bool {
Person person{2, 1};
ch_cout << "person=" << person << std::endl;
return ch_true;
});
TEST1([](const ch_int8& pred)->ch_bool {
ch_vec<ch_int4, 2> vi{2, 1};
ch_cout << "vi=" << vi << std::endl;
return ch_true;
});
TEST1([](const ch_int8& pred)->ch_bool {
ch_vec<my_enum, 2> ve{my_enum::done, my_enum::stats};
ch_cout << "ve=" << ve << std::endl;
return ch_true;
});
}
SECTION("bitvector", "[bitvector]") {
TESTX([]()->bool {
sdata_type x(12, 0x707);
auto y = static_cast<int32_t>(x);
return (0x707 == y);
});
TESTX([]()->bool {
sdata_type x(12, "707_h");
auto y = static_cast<int32_t>(x);
return (0x707 == y);
});
TESTX([]()->bool {
std::vector<uint16_t> tmp({0x707});
sdata_type x(12, tmp);
auto y = static_cast<int32_t>(x);
return (0x707 == y);
});
TESTX([]()->bool {
std::vector<uint8_t> tmp({0x7, 0x7});
sdata_type x(12, tmp);
auto y = static_cast<int32_t>(x);
return (0x707 == y);
});
TESTX([]()->bool {
std::array<uint16_t, 1> tmp{0x707};
sdata_type x(12, tmp);
auto q = x;
auto y = static_cast<int32_t>(q);
return (0x707 == y);
});
TESTX([]()->bool {
std::array<uint8_t, 2> tmp{0x7, 0x7};
sdata_type x(12, tmp);
auto q = x;
auto y = static_cast<int32_t>(q);
return (0x707 == y);
});
}
SECTION("sign_ext", "[sign_ext]") {
CHECK(sign_ext<uint32_t>(0x0555, 16) == 0x00000555);
CHECK(sign_ext<uint32_t>(0xf555, 16) == 0xfffff555);
CHECK(sign_ext<uint32_t>(0x05555555, 32) == 0x05555555);
CHECK(sign_ext<uint32_t>(0xf5555555, 32) == 0xf5555555);
}
SECTION("log2", "[log2]") {
CHECK(log2floor(1) == 0);
CHECK(log2floor(2) == 1);
CHECK(log2floor(3) == 1);
CHECK(log2floor(4) == 2);
CHECK(log2ceil(1) == 0);
CHECK(log2ceil(2) == 1);
CHECK(log2ceil(3) == 2);
CHECK(log2ceil(4) == 2);
CHECK(log2up(1) == 1);
CHECK(log2up(2) == 1);
CHECK(log2up(3) == 2);
CHECK(log2up(4) == 2);
CHECK(roundup(7, 3) == 9);
}
SECTION("unused", "unused") {
TESTX([]()->bool {
ch_device<GenericModule2<ch_int4, ch_int4, ch_int4>> device(
[](auto lhs, auto rhs) {
ch_module<ch_queue<ch_int4, 4>> queue;
ch_module<ch_queue<ch_int4, 4>> q1(queue);
auto q2 = q1;
q2.io.enq.data = lhs + rhs;
q2.io.enq.valid = true;
q2.io.deq.ready = true;
return lhs * rhs;
}
);
device.io.lhs = 2;
device.io.rhs = 3;
ch_simulator sim(device);
sim.run(2);
return (device.io.out == 6);
});
TESTX([]()->bool {
ch_device<GenericModule2<ch_int4, ch_int4, ch_int4>> device(
[](auto lhs, auto rhs) {
ch_module<ch_queue<ch_int4, 4>> queue;
queue.io.enq.data = lhs + rhs;
return lhs * rhs;
}
);
device.io.lhs = 2;
device.io.rhs = 3;
ch_simulator sim(device);
sim.run(2);
return (device.io.out == 6);
});
TESTX([]()->bool {
auto_cflags_disable cg_merge(ch_flags::codegen_merged);
ch_device<GenericModule2<ch_int4, ch_int4, ch_int4>> device(
[](auto lhs, auto rhs) {
ch_vec<ch_module<Bypass<ch_int4>>, 2> bypass;
bypass[0].io.in = lhs;
bypass[1].io.in = rhs;
return bypass[0].io.out * bypass[1].io.out;
}
);
ch_toVerilog("merged.v", device);
device.io.lhs = 2;
device.io.rhs = 3;
ch_tracer trace(device);
trace.run(2);
RetCheck ret;
ret &= (device.io.out == 6);
trace.toText("merged.log");
trace.toVCD("merged.vcd");
trace.toVerilog("merged_tb.v", "merged.v");
ret &= (checkVerilog("merged_tb.v"));
return ret;
});
TESTX([]()->bool {
auto_cflags_disable cg_merge(ch_flags::codegen_merged);
ch_device<GenericModule2<ch_int4, ch_int4, ch_int4>> device(
[](auto lhs, auto rhs) {
ch_vec<ch_module<Bypass<ch_int4>>, 2> bypass;
bypass[1].io.in = rhs;
return lhs * bypass[1].io.out;
}
);
ch_toVerilog("merged2.v", device);
device.io.lhs = 2;
device.io.rhs = 3;
ch_tracer trace(device);
trace.run(2);
RetCheck ret;
ret &= (device.io.out == 6);
trace.toText("merged2.log");
trace.toVCD("merged2.vcd");
trace.toVerilog("merged2_tb.v", "merged2.v");
ret &= (checkVerilog("merged2_tb.v"));
return ret;
});
TESTX([]()->bool {
auto_cflags_disable cfo_off(ch_flags::disable_cfo);
ch_device<GenericModule2<ch_int4, ch_int4, ch_int4>> device(
[](auto lhs, auto rhs) {
ch_vec<ch_module<Bypass<ch_int4>>, 2> bypass;
bypass[0].io.in = lhs;
bypass[1].io.in = rhs;
auto x = bypass[0].io.out + bypass[1].io.out;
auto y = bypass[1]->bypass_->tap_ - bypass[0]->bypass_->tap_;
//ch_print("y={0}", y);
return x * y;
}
);
ch_toVerilog("bypass.v", device);
device.io.lhs = 2;
device.io.rhs = 3;
ch_tracer trace(device);
trace.run(2);
RetCheck ret;
ret &= (device.io.out == 10);
trace.toText("bypass.log");
trace.toVCD("bypass.vcd");
trace.toVerilog("bypass_tb.v", "bypass.v");
ret &= (checkVerilog("bypass_tb.v"));
return ret;
});
}
}
| 24.818008
| 190
| 0.487302
|
JackWolfard
|
21f2e7464d3b4ea4c9a746f1c2094769de755994
| 3,667
|
cpp
|
C++
|
src/libcvpg/videoproc/stage_data_handler.cpp
|
franz-alt/cv-playground
|
d6c3bbdb500bf121c28299d117e459730b2b912d
|
[
"MIT"
] | null | null | null |
src/libcvpg/videoproc/stage_data_handler.cpp
|
franz-alt/cv-playground
|
d6c3bbdb500bf121c28299d117e459730b2b912d
|
[
"MIT"
] | null | null | null |
src/libcvpg/videoproc/stage_data_handler.cpp
|
franz-alt/cv-playground
|
d6c3bbdb500bf121c28299d117e459730b2b912d
|
[
"MIT"
] | null | null | null |
// Copyright (c) 2020-2021 Franz Alt
// This code is licensed under MIT license (see LICENSE.txt for details).
#include <libcvpg/videoproc/stage_data_handler.hpp>
#include <algorithm>
#include <iterator>
namespace cvpg::videoproc {
template<typename T> stage_data_handler<T>::stage_data_handler(std::string name,
std::size_t max_stored_entries,
std::function<void()> trigger_new_data_callback,
std::function<std::size_t()> get_deliver_amount_callback,
std::function<void(std::vector<T>, std::function<void()>)> deliver_data_callback)
: m_name(std::move(name))
, m_max_stored_entries(max_stored_entries)
, m_trigger_new_data_callback(std::move(trigger_new_data_callback))
, m_get_deliver_amount_callback(std::move(get_deliver_amount_callback))
, m_deliver_data_callback(std::move(deliver_data_callback))
, m_in_data()
, m_out_data()
, m_next(0)
{
// reserve space for output buffer for the same size as input buffer
m_out_data.reserve(max_stored_entries);
}
template<typename T> void stage_data_handler<T>::add(T && t)
{
m_in_data.push(std::move(t));
try_flush();
}
template<typename T> void stage_data_handler<T>::add(std::vector<T> && t)
{
for (auto & d : t)
{
m_in_data.push(std::move(d));
}
try_flush();
}
template<typename T> void stage_data_handler<T>::try_flush()
{
try_process_input();
const std::size_t max_deliver = std::min(m_max_stored_entries, m_get_deliver_amount_callback());
if (max_deliver >= m_out_data.size())
{
if (!m_out_data.empty())
{
// deliver output buffer completly
m_deliver_data_callback(std::move(m_out_data), m_trigger_new_data_callback);
m_out_data.clear();
}
else
{
m_trigger_new_data_callback();
}
}
else
{
if (max_deliver > 0)
{
// deliver only 'max_deliver' entries from the beginning of the output buffer
std::vector<T> moved;
moved.reserve(max_deliver);
// move 'maxdeliver' entries from output to 'moved' vector
std::move(m_out_data.begin(), m_out_data.begin() + max_deliver, std::back_inserter(moved));
m_out_data.erase(m_out_data.begin(), m_out_data.begin() + max_deliver);
m_deliver_data_callback(std::move(moved), m_trigger_new_data_callback);
}
}
}
template<typename T> void stage_data_handler<T>::try_process_input()
{
bool found = true;
while (found)
{
found = !m_in_data.empty() && m_in_data.top().number() == m_next;
if (found)
{
// move data from input to output buffer
m_out_data.push_back(m_in_data.top());
m_in_data.pop();
++m_next;
}
}
}
template<typename T> bool stage_data_handler<T>::empty() const
{
return m_in_data.empty();
}
template<typename T> bool stage_data_handler<T>::full() const
{
return free() == 0;
}
template<typename T> std::size_t stage_data_handler<T>::free() const
{
return std::min(m_max_stored_entries - m_in_data.size() + m_out_data.size(), m_max_stored_entries);
}
// manual instantiation of stage_data_handler<> for some types
template class stage_data_handler<videoproc::frame<image_gray_8bit> >;
template class stage_data_handler<videoproc::frame<image_rgb_8bit> >;
} // namespace cvpg::videoproc
| 30.305785
| 144
| 0.620944
|
franz-alt
|
21f3135df82752e03bd87bf652f63f8a95b83923
| 1,088
|
cpp
|
C++
|
block_statistics/rows-nnz-stdev.cpp
|
DanielLangr/abhsf
|
1f8083d474ac634d6301d0736b187acdd5b557cd
|
[
"MIT"
] | null | null | null |
block_statistics/rows-nnz-stdev.cpp
|
DanielLangr/abhsf
|
1f8083d474ac634d6301d0736b187acdd5b557cd
|
[
"MIT"
] | null | null | null |
block_statistics/rows-nnz-stdev.cpp
|
DanielLangr/abhsf
|
1f8083d474ac634d6301d0736b187acdd5b557cd
|
[
"MIT"
] | 1
|
2021-11-09T08:19:35.000Z
|
2021-11-09T08:19:35.000Z
|
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <abhsf/utils/colors.h>
double stdev(const std::string& filename, uintmax_t m)
{
std::vector<uintmax_t> rows_nnz(m);
std::ifstream f(filename);
for (uintmax_t k = 0; k < m; k++)
f>> rows_nnz[k];
f.close();
// average
uintmax_t nnz = std::accumulate(rows_nnz.cbegin(), rows_nnz.cend(), uintmax_t(0));
double avg = double(nnz) / double(m);
double stdev = 0.0;
for (uintmax_t k = 0; k < m; k++)
stdev += pow(double(rows_nnz[k]) - avg, 2.0);
stdev /= double(m);
stdev = sqrt(stdev);
return stdev;
}
int main()
{
std::ifstream f("props");
uintmax_t m, n;
f >> m >> n;
f.close();
double stdev_stored = stdev("rows_nnz_stored", m);
double stdev_all = stdev("rows_nnz_all", m);
std::cout << stdev_stored << " " << stdev_all << " "
<< stdev_stored / double(n) * 100.0 << " "
<< stdev_all / double(n) * 100.0 << std::endl;
}
| 23.652174
| 86
| 0.575368
|
DanielLangr
|
21f5bdeb6b8f2ea262bfdd5d6c89a3f228be7bac
| 59
|
hpp
|
C++
|
src/boost_units_systems_si_angular_acceleration.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 10
|
2018-03-17T00:58:42.000Z
|
2021-07-06T02:48:49.000Z
|
src/boost_units_systems_si_angular_acceleration.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 2
|
2021-03-26T15:17:35.000Z
|
2021-05-20T23:55:08.000Z
|
src/boost_units_systems_si_angular_acceleration.hpp
|
miathedev/BoostForArduino
|
919621dcd0c157094bed4df752b583ba6ea6409e
|
[
"BSL-1.0"
] | 4
|
2019-05-28T21:06:37.000Z
|
2021-07-06T03:06:52.000Z
|
#include <boost/units/systems/si/angular_acceleration.hpp>
| 29.5
| 58
| 0.830508
|
miathedev
|
21f5d568c76595344ed2d0d17fc4820791e15ac3
| 6,552
|
cpp
|
C++
|
src/drift_velocity.cpp
|
jdpetticrew/Simple-Monte-Carlo-Simulator
|
548d7cfe5f7a16e4095db7da27f61eca4dce6d98
|
[
"Apache-2.0"
] | 8
|
2018-07-12T11:07:02.000Z
|
2022-02-18T06:34:17.000Z
|
src/drift_velocity.cpp
|
jdpetticrew/Simple-Monte-Carlo-Simulator
|
548d7cfe5f7a16e4095db7da27f61eca4dce6d98
|
[
"Apache-2.0"
] | 2
|
2019-10-21T09:45:57.000Z
|
2022-01-18T09:48:51.000Z
|
src/drift_velocity.cpp
|
jdpetticrew/Simple-Monte-Carlo-Simulator
|
548d7cfe5f7a16e4095db7da27f61eca4dce6d98
|
[
"Apache-2.0"
] | 1
|
2019-05-24T07:59:16.000Z
|
2019-05-24T07:59:16.000Z
|
/* Copyright 2017 Advanced Detector Centre, Department of Electronic and
Electrical Engineering, University of Sheffield, UK.
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.*/
/*
drift_velocity.cpp contains drift_velocity() which calculates the drift velocity in a given material.
Takes user input for Minimum,Maximum for Electric Fields.
Takes material input from main.cpp
Prototyped in model.h
Uses the Classes SMC & tools.
Also uses functions.h which contains common functions used in all three modes.
Calculates the drift velocity for electrons and holes by tracking their movement through the material
until they have undergone 1000000 scattering events each.
There total movment is then divided by the time it took to travel that far to calculate the drift velocities.
The velocities are outputted to epdf and hpdf.
Jonathan Petticrew, University of Sheffield, 2017.
*/
#include "model.h"
#include "SMC.h"
#include "functions.h"
#include "tools.h"
#include <stdio.h>
#include <math.h>
void drift_velocity(int material){
SMC constants; //SMC parameter set
constants.mat(material); //Tells SMC parameter set which material
SMC *pointSMC = &constants; //Used to pass constants to other classes.
double minEfield, maxEfield;
printf(" Minimum Electric Field (kV/cm):\n");
scanf("%lf",&minEfield);
printf(" Maximum Electric Field (kV/cm):\n");
scanf("%lf",&maxEfield);
tools simulation(pointSMC);
simulation.scattering_probability();//this function returns 0 if no output can be generated and the user wants to quit
sgenrand(4358);//seeds the random number generator constant used to alow for comparison using different parameters.
double Esim,Eloop,z_pos,kf,kxy,kz,cos_theta,Energy;
int tn;
int scat_e=0;
FILE *epdf;
FILE *hpdf;
epdf=fopen("evelocity.txt","w");
hpdf=fopen("hvelocity.txt","w");
for(Esim=minEfield; Esim<=maxEfield; Esim+=1) {
Eloop=Esim*1e5;//change elecric field from kV/cm to V/m.
z_pos=0;
Energy=0;
kf=0; //Kf^2=Kx^2+Ky^2+Kz^2
kxy=0; // combined momentum tangential to travel direction.
kz=0; // z momentum (direction of travel)
cos_theta=0; //scattering angle
tn=0;
double drift_t=0;
double dE=0;
int counter=0;
double vtotal=0;
//electrons
for(counter=0; counter<1000000; counter++) { //loop for 1000000 scattering events
if(scat_e==0) {
double cos_theta;
kf=2*constants.Get_e_mass()*Energy/(constants.Get_hbar()*constants.Get_hbar());
if(kf>=0) {
cos_theta=2*genrand()-1;
kz=cos_theta*sqrt(kf);
kxy=kf*(1-cos_theta*cos_theta);
}
}
//electron drift process starts
double random1;
random1=genrand();
drift_t= -log(random1)/(simulation.Get_rtotal());
kz+=(constants.Get_q()*drift_t*Eloop)/(constants.Get_hbar());
dE=((constants.Get_hbar()*constants.Get_hbar())/(2*constants.Get_e_mass()))*(kxy+kz*kz)-Energy;
Energy=((constants.Get_hbar()*constants.Get_hbar())/(2*constants.Get_e_mass()))*(kxy+kz*kz);
z_pos+=dE/(constants.Get_q()*Eloop);
//electron drift process ends
double velocity = dE/(constants.Get_q()*Eloop*drift_t);
vtotal += (velocity);
// electron scattering process starts
double random2;
int Eint;
Eint=(int)floor(Energy*1000.0/constants.Get_q()+0.5);
if (Energy>constants.Get_Emax()) {
Eint= constants.Get_NUMPOINTS();
random2=simulation.Get_pb(2,constants.Get_NUMPOINTS());
}
else if (Energy == constants.Get_Emax()) random2=simulation.Get_pb(2,constants.Get_NUMPOINTS());
else random2=genrand();
if(random2<=simulation.Get_pb(0,Eint)) //phonon absorption
{ Energy+=constants.Get_hw();
scat_e=0;}
else if(random2<=simulation.Get_pb(1,Eint)) //phonon emission
{ Energy-=constants.Get_hw();
scat_e=0;}
else if(random2<=simulation.Get_pb(2,Eint)) //impact ionization
{ Energy=(Energy-constants.Get_e_Eth())/3.0;
tn++;
scat_e=0;
z_pos=0;}
else if(random2>simulation.Get_pb(2,Eint)) //selfscattering
{ scat_e=1;}
//electron scattering process ends
}
double vmean=vtotal/counter;
fprintf(epdf,"%g %g\n", Esim, vmean);
z_pos=0;
Energy=0;
kf=0;
kxy=0;
kz=0;
cos_theta=0;
tn=0;
drift_t=0;
dE=0;
double vtotalh=0;
//holes
for(counter=0; counter<1000000; counter++) {
if(scat_e==0) {
double cos_theta;
kf=2*constants.Get_h_mass()*Energy/(constants.Get_hbar()*constants.Get_hbar());
if(kf>=0) {
cos_theta=2*genrand()-1;
kz=cos_theta*sqrt(kf);
kxy=kf*(1-cos_theta*cos_theta);
}
}
//hole drift process starts
double random11;
random11=genrand();
drift_t= -log(random11)/simulation.Get_rtotal2();
kz-=((constants.Get_q()*drift_t*Eloop)/(constants.Get_hbar()));
dE=((constants.Get_hbar()*constants.Get_hbar())/(2*constants.Get_h_mass()))*(kxy+kz*kz)-Energy;
Energy=((constants.Get_hbar()*constants.Get_hbar())/(2*constants.Get_h_mass()))*(kxy+kz*kz);
z_pos-=dE/(Eloop*constants.Get_q());
//hole drift process ends
double velocity = dE/(Eloop*constants.Get_q()*drift_t);
vtotalh+= (velocity);
double random22;
int Eint2;
Eint2=(int)floor(Energy*1000.0/constants.Get_q()+0.5);
if (Energy>constants.Get_Emax()) {
Eint2= constants.Get_NUMPOINTS();
random22=simulation.Get_pb2(2,constants.Get_NUMPOINTS());
}
else if (Energy == constants.Get_Emax()) random22=simulation.Get_pb2(2,constants.Get_NUMPOINTS());
else random22=genrand();
if(random22<=simulation.Get_pb2(0,Eint2)) //phonon absorption
{ Energy+=constants.Get_hw();
scat_e=0;}
else if(random22<=simulation.Get_pb2(1,Eint2)) //phonon emission
{ Energy-=constants.Get_hw();
scat_e=0;}
else if(random22<=simulation.Get_pb2(2,Eint2)) //impact ionization
{ Energy=(Energy-constants.Get_h_Eth())/3.0;
tn++;
scat_e=0;
z_pos=0;}
else if(random22>simulation.Get_pb2(2,Eint2)) //selfscattering
{ scat_e=1;}
//electron scattering process ends
}
vmean=vtotalh/counter;
fprintf(hpdf,"%g %g\n", Esim, vmean);
}
fclose(epdf);
fclose(hpdf);
}
| 33.773196
| 119
| 0.699176
|
jdpetticrew
|
21f84c9bcecf8423f128899aedf9efd2873c1cea
| 7,408
|
hpp
|
C++
|
include/RunStatistics.hpp
|
pixie-net/pixie-net-api
|
743e473845fc6c6d674d454b3a419d55372d99d4
|
[
"Unlicense"
] | null | null | null |
include/RunStatistics.hpp
|
pixie-net/pixie-net-api
|
743e473845fc6c6d674d454b3a419d55372d99d4
|
[
"Unlicense"
] | 3
|
2019-04-07T17:18:47.000Z
|
2019-11-10T22:08:18.000Z
|
include/RunStatistics.hpp
|
spaulaus/pixie-net
|
743e473845fc6c6d674d454b3a419d55372d99d4
|
[
"Unlicense"
] | null | null | null |
/// @file RunStatistics.hpp
/// @brief
/// @author S. V. Paulauskas
/// @date March 01, 2020
#ifndef PIXIE_NET_RUNSTATISTICS_HPP
#define PIXIE_NET_RUNSTATISTICS_HPP
#include <map>
class RunStatistics {
public:
double getRunTime() const;
double getTotalTime() const;
double getEventRate() const;
unsigned int getPsCodeVersion() const;
void setPsCodeVersion(const unsigned int &psCodeVersion);
unsigned int getCsrout() const;
void setCsrout(const unsigned int &csrout);
unsigned int getSystime() const;
void setSystime(const unsigned int &systime);
unsigned int getRunTimeLow() const;
void setRunTimeLow(const unsigned int &RunTimeLow);
unsigned int getRunTimeHigh() const;
void setRunTimeHigh(const unsigned int &RunTimeHigh);
unsigned int getNumEventsLow() const;
void setNumEventsLow(const unsigned int &NumEventsLow);
unsigned int getNumEventsHigh() const;
void setNumEventsHigh(const unsigned int &NumEventsHigh);
unsigned int getBhlEhl() const;
void setBhlEhl(const unsigned int &bhlEhl);
unsigned int getChlFifilength() const;
void setChlFifilength(const unsigned int &chlFifilength);
unsigned int getRevision() const;
void setRevision(const unsigned int &revision);
unsigned int getSnum() const;
void setSnum(const unsigned int &snum);
double getTemperatureAdc() const;
void setTemperatureAdc(const double &temperatureAdc);
double getTemperatureZynq() const;
void setTemperatureZynq(const double &temperatureZynq);
double getCountTime(const unsigned int &channel) const;
double getNtrig(const unsigned int &channel) const;
double getInputCountRate(const unsigned int &channel) const;
double getOutputCountRate(const unsigned int &channel) const;
double getNumEvents() const;
double getNout(const unsigned int &channel) const;
double getFtdt(const unsigned int &channel) const;
double getSfdt(const unsigned int &channel) const;
double getNppi(const unsigned int &channel) const;
double getGcount(const unsigned int &channel) const;
double getGcountRate(const unsigned int &channel) const;
double getPassPileupRate(const unsigned int &channel) const;
double getGdt(const unsigned int &channel) const;
unsigned int getOor(const unsigned int &channel) const;
void getOor(const unsigned int &channel, const unsigned int &value);
unsigned int getIcr(const unsigned int &channel) const;
void setIcr(const unsigned int &channel, const unsigned int &value);
unsigned int getCountTimeLow(const unsigned int &channel) const;
void setCountTimeLow(const unsigned int &channel, const unsigned int &value);
unsigned int getCountTimeHigh(const unsigned int &channel) const;
void setCountTimeHigh(const unsigned int &channel, const unsigned int &value);
unsigned int getNtrigLow(const unsigned int &channel) const;
void setNtrigLow(const unsigned int &channel, const unsigned int &value);
unsigned int getNtrigHigh(const unsigned int &channel) const;
void setNtrigHigh(const unsigned int &channel, const unsigned int &value);
unsigned int getFtdtLow(const unsigned int &channel) const;
void setFtdtLow(const unsigned int &channel, const unsigned int &value);
unsigned int getFtdtHigh(const unsigned int &channel) const;
void setFtdtHigh(const unsigned int &channel, const unsigned int &value);
unsigned int getSfdtLow(const unsigned int &channel) const;
void setSfdtLow(const unsigned int &channel, const unsigned int &value);
unsigned int getSfdtHigh(const unsigned int &channel) const;
void setSfdtHigh(const unsigned int &channel, const unsigned int &value);
unsigned int getGcountLow(const unsigned int &channel) const;
void setGcountLow(const unsigned int &channel, const unsigned int &value);
unsigned int getGcountHigh(const unsigned int &channel) const;
void setGcountHigh(const unsigned int &channel, const unsigned int &value);
unsigned int getNoutLow(const unsigned int &channel) const;
void setNoutLow(const unsigned int &channel, const unsigned int &value);
unsigned int getNoutHigh(const unsigned int &channel) const;
void setNoutHigh(const unsigned int &channel, const unsigned int &value);
unsigned int getGdtLow(const unsigned int &channel) const;
void setGdtLow(const unsigned int &channel, const unsigned int &value);
unsigned int getGdtHigh(const unsigned int &channel) const;
void setGdtHigh(const unsigned int &channel, const unsigned int &value);
unsigned int getNppiLow(const unsigned int &channel) const;
void setNppiLow(const unsigned int &channel, const unsigned int &value);
unsigned int getNppiHigh(const unsigned int &channel) const;
void setNppiHigh(const unsigned int &channel, const unsigned int &value);
unsigned int getPsaLicensed() const;
void setPsaLicensed(const unsigned int &psaLicensed);
unsigned int getActive() const;
void setActive(const unsigned int &active);
unsigned int getPtpRequired() const;
void setPtpRequired(const unsigned int &ptpRequired);
unsigned int getHwVersion() const;
void setHwVersion(unsigned int hwVersion);
unsigned int getTotalTimeLow() const;
void setTotalTimeLow(unsigned int totalTimeLow);
unsigned int getTotalTimeHigh() const;
void setTotalTimeHigh(unsigned int totalTimeHigh);
private:
unsigned int total_time_low;
unsigned int total_time_high;
unsigned int ps_code_version;
unsigned int psa_licensed;
unsigned int csrout;
unsigned int systime;
unsigned int run_time_low;
unsigned int run_time_high;
unsigned int num_events_low;
unsigned int num_events_high;
unsigned int bhl_ehl;
unsigned int active;
unsigned int ptp_required;
unsigned int chl_fifilength;
unsigned int revision;
unsigned int snum;
double temperature_adc;
double temperature_zynq;
unsigned int hw_version;
std::map<unsigned int, unsigned int> oor;
std::map<unsigned int, unsigned int> icr;
std::map<unsigned int, unsigned int> count_time_low;
std::map<unsigned int, unsigned int> count_time_high;
std::map<unsigned int, unsigned int> ntrig_low;
std::map<unsigned int, unsigned int> ntrig_high;
std::map<unsigned int, unsigned int> ftdt_low;
std::map<unsigned int, unsigned int> ftdt_high;
std::map<unsigned int, unsigned int> sfdt_low;
std::map<unsigned int, unsigned int> sfdt_high;
std::map<unsigned int, unsigned int> gcount_low;
std::map<unsigned int, unsigned int> gcount_high;
std::map<unsigned int, unsigned int> nout_low;
std::map<unsigned int, unsigned int> nout_high;
std::map<unsigned int, unsigned int> gdt_low;
std::map<unsigned int, unsigned int> gdt_high;
std::map<unsigned int, unsigned int> nppi_low;
std::map<unsigned int, unsigned int> nppi_high;
};
#endif //PIXIE_NET_RUNSTATISTICS_HPP
| 31.257384
| 82
| 0.701674
|
pixie-net
|
21f982f74156cbc1137e8f05b33a013398d2ee66
| 11,172
|
cpp
|
C++
|
src/device.cpp
|
madl3x/miflora_rbs
|
ad893ea2aeaa15529ec6dde7823c2e833b82f884
|
[
"MIT"
] | null | null | null |
src/device.cpp
|
madl3x/miflora_rbs
|
ad893ea2aeaa15529ec6dde7823c2e833b82f884
|
[
"MIT"
] | null | null | null |
src/device.cpp
|
madl3x/miflora_rbs
|
ad893ea2aeaa15529ec6dde7823c2e833b82f884
|
[
"MIT"
] | null | null | null |
/*
* MIT License
*
* 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.
*
* Copyright (c) 2021 Alex Mircescu
*/
#include "device.h"
#include "mqtt.h"
#define LOG_TAG LOG_TAG_FLORA
#include "log.h"
MiFloraFleet fleet;
/*
* Device implementation for MiFlora
*/
MiFloraDevice::MiFloraDevice(const std::string & addr):
conductivity (this, ATTR_ID_MOISTURE , "Cond"),
temperature (this, ATTR_ID_TEMPERATURE , "Temp"),
moisture (this, ATTR_ID_MOISTURE , "Moist"),
illuminance (this, ATTR_ID_ILLUMINANCE , "Light"),
RSSI (this, ATTR_ID_RSSI , "RSSI"),
_last_updated(millis()),
_id(0),
_address (addr), _name("") {
// MQTT collaboration
if (config.flora_mqtt_collaborate) {
std::string topic;
// subscribe for getting attribute update from other stations
config.formatTopic(topic, ConfigMain::MQTT_TOPIC_FLORA, _address.c_str(), "temp");
mqtt.subscribeTo(topic.c_str(), s_onMQTTMessage, this);
config.formatTopic(topic, ConfigMain::MQTT_TOPIC_FLORA, _address.c_str(), "conductivity");
mqtt.subscribeTo(topic.c_str(), s_onMQTTMessage, this);
config.formatTopic(topic, ConfigMain::MQTT_TOPIC_FLORA, _address.c_str(), "light");
mqtt.subscribeTo(topic.c_str(), s_onMQTTMessage, this);
config.formatTopic(topic, ConfigMain::MQTT_TOPIC_FLORA, _address.c_str(), "moisture");
mqtt.subscribeTo(topic.c_str(), s_onMQTTMessage, this);
}
}
/* update device attributes from BLE scan result */
void MiFloraDevice::updateFromBLEScan(XiaomiParseResult & result) {
unsigned long now = millis();
char value[16];
std::string topic;
// TEMPERATURE
if (result.has_temperature) {
// publish to mqtt
if (temperature.isOlder(config.flora_publish_min_interval_sec, now)) {
sprintf(value, "%.2f", result.temperature);
config.formatTopic(topic, ConfigMain::MQTT_TOPIC_FLORA, _address.c_str(), "temp");
mqtt.publish(topic.c_str(), value, config.flora_mqtt_retain);
}
LOG_F("From BLE %s %s->%.2f",
_name.c_str(), temperature.getLabel(), result.temperature );
temperature.set(result.temperature, SOURCE_BLE);
}
// CONDUCTIVITY
if (result.has_conductivity) {
// publish to mqtt
if (conductivity.isOlder(config.flora_publish_min_interval_sec, now)) {
sprintf(value, "%u", (unsigned int) result.conductivity);
config.formatTopic(topic, ConfigMain::MQTT_TOPIC_FLORA, _address.c_str(), "conductivity");
mqtt.publish(topic.c_str(), value, config.flora_mqtt_retain);
}
LOG_F("From BLE %s %s->%d",
_name.c_str(), conductivity.getLabel(), (int) result.conductivity);
conductivity.set(result.conductivity, SOURCE_BLE);
}
// LIGHT
if (result.has_illuminance) {
// publish to mqtt
if (illuminance.isOlder(config.flora_publish_min_interval_sec, now)) {
sprintf(value, "%u", (unsigned int) result.illuminance);
config.formatTopic(topic, ConfigMain::MQTT_TOPIC_FLORA, _address.c_str(), "light");
mqtt.publish(topic.c_str(), value, config.flora_mqtt_retain);
}
LOG_F("From BLE %s %s->%d",
_name.c_str(), illuminance.getLabel(), (int) result.illuminance);
illuminance.set((int)result.illuminance, SOURCE_BLE);
}
// MOISTURE
if (result.has_moisture) {
// publish to mqtt
if (moisture.isOlder(config.flora_publish_min_interval_sec, now)) {
sprintf(value, "%u", (unsigned int) result.moisture);
config.formatTopic(topic, ConfigMain::MQTT_TOPIC_FLORA, _address.c_str(), "moisture");
mqtt.publish(topic.c_str(), value, config.flora_mqtt_retain);
}
LOG_F("From BLE %s %s->%d",
_name.c_str(), moisture.getLabel(), (int) result.moisture);
moisture.set((int)result.moisture, SOURCE_BLE);
}
}
inline void MiFloraDevice::updateRSSI(int rssi) {
unsigned long now = millis();
std::string topic;
char value[16];
// publish RSSI on MQTT
if (RSSI.isOlder(config.flora_publish_min_interval_sec, now)) {
sprintf(value, "%d", rssi);
config.formatTopic(topic, ConfigMain::MQTT_TOPIC_FLORA, _address.c_str(), "rssi");
mqtt.publish(topic.c_str(), value, config.flora_mqtt_retain);
}
// update attribute
RSSI.set(rssi, SOURCE_BLE);
}
/* update device attributes via MQTT message */
void MiFloraDevice::updateFromMQTT(const char * topic, uint8_t * _payload, unsigned int len) {
const char * attribute;
char payload [16];
// payload too large
if (len - 1 > sizeof(payload))
return;
// copy payload with null terminator
strncpy(payload, (const char *)_payload, len);
payload[len] = '\0';
// should not happen
attribute = strrchr(topic, '/');
if (attribute == NULL)
return;
auto now = millis();
LOG_F("From MQTT %s %s->%s", _name.c_str(), attribute, payload);
if (strcmp(attribute, "/temp") == 0) {
if ((now - temperature.lastUpdated()) < 10000 && temperature.getSource() == SOURCE_BLE) return;
temperature.set(strtof(payload, NULL), SOURCE_MQTT);
} else
if (strcmp(attribute, "/moisture") == 0) {
if ((now - moisture.lastUpdated()) < 10000 && moisture.getSource() == SOURCE_BLE) return;
moisture.set(strtol(payload, NULL, 10), SOURCE_MQTT);
} else
if (strcmp(attribute, "/conductivity") == 0) {
if ((now - conductivity.lastUpdated()) < 10000 && conductivity.getSource() == SOURCE_BLE) return;
conductivity.set(strtol(payload, NULL, 10), SOURCE_MQTT);
} else
if (strcmp(attribute, "/light") == 0) {
if ((now - illuminance.lastUpdated()) < 10000 && illuminance.getSource() == SOURCE_BLE) return;
illuminance.set(strtol(payload, NULL, 10), SOURCE_MQTT);
} else {
// should not happen
}
}
/*
* Fleet class for managing MiFlora devices
*/
#undef LOG_TAG
#define LOG_TAG LOG_TAG_FLEET
bool MiFloraFleet::begin(const char * filename) {
ConfigFile config;
LOG_F("Loading devices from: %s", filename);
// load filename
if (config.load(filename) == false) {
LOG_LN("Failed to load devices configuration!");
return false;
}
// load from configuration
loadFromConfig(config);
LOG_F("Loaded %d devices from '%s'", count(), filename);
// register to BLE to get new updates
ble.setMifloraHandler(s_BLE_MiFloraHandler);
return true;
}
void MiFloraFleet::loadFromConfig(ConfigFile & configDevices) {
// load devices
for (std::string address : configDevices.sections()) {
// create new flora device, section name is the address
auto id = configDevices.getInt(
(address + ":id").c_str(), _devices.size());
auto name = configDevices.get(
(address + ":name").c_str(), "unknown");
LOG_F("Device '%s' id:%d name:%s",
address.c_str(), id, name);
auto flora_device = new MiFloraDevice(address);
flora_device->setID(id);
flora_device->setName(name);
// install limits
const char * min_val;
const char * max_val;
// moisture
min_val = configDevices.get((address + ":min_moisture").c_str());
max_val = configDevices.get((address + ":max_moisture").c_str());
if (min_val) flora_device->moisture.setMin(atol(min_val));
if (max_val) flora_device->moisture.setMax(atol(max_val));
LOG_F(" - moisture limits [%s,%s]",
min_val ? min_val : "n/a", max_val ? max_val : "n/a");
// temperature
min_val = configDevices.get((address + ":min_temperature").c_str());
max_val = configDevices.get((address + ":max_temperature").c_str());
if (min_val) flora_device->temperature.setMin(atol(min_val));
if (max_val) flora_device->temperature.setMax(atol(max_val));
LOG_F(" - temperature limits [%s,%s]",
min_val ? min_val : "n/a", max_val ? max_val : "n/a");
// conductivity
min_val = configDevices.get((address + ":min_conductivity").c_str());
max_val = configDevices.get((address + ":max_conductivity").c_str());
if (min_val) flora_device->conductivity.setMin(atol(min_val));
if (max_val) flora_device->conductivity.setMax(atol(max_val));
LOG_F(" - conductivity limits [%s,%s]",
min_val ? min_val : "n/a", max_val ? max_val : "n/a");
// illuminance
min_val = configDevices.get((address + ":min_illuminance").c_str());
max_val = configDevices.get((address + ":max_illuminance").c_str());
if (min_val) flora_device->illuminance.setMin(atol(min_val));
if (max_val) flora_device->illuminance.setMax(atol(max_val));
LOG_F(" - illuminance limits [%s,%s]",
min_val ? min_val : "n/a", max_val ? max_val : "n/a");
// RSSI
min_val = configDevices.get((address + ":min_rssi").c_str());
if (min_val) flora_device->RSSI.setMin(atol(min_val));
LOG_F(" - RSSI limit %s",
min_val ? min_val : "n/a");
// add to devices
addDevice(flora_device);
}
}
/* notification from BLE to interpret new data scans */
void MiFloraFleet::s_BLE_MiFloraHandler(const BLE::MiFloraScanData_t & scanData) {
XiaomiParseResult result = {};
MiFloraDevice * flora_device = NULL;
// parse the scan data for Xiami devices into a result structure
parse_xiaomi_message(scanData.serviceData, result);
// find Flora device
flora_device = fleet.findByAddress(scanData.deviceAddress.c_str());
// create new flora device if not found
if (flora_device == NULL) {
// ignore new devices, if configured to do so
if (config.flora_discover_devices == false) {
LOG_F("New flora device: %s (ignored)",
scanData.deviceAddress.c_str());
return;
}
flora_device = new MiFloraDevice(scanData.deviceAddress);
flora_device->setID(fleet.count());
flora_device->setName("Unknown");
fleet.addDevice(flora_device);
LOG_F("New flora device: %s",flora_device->getAddress().c_str());
}
// update device attributes from BLE data
flora_device->updateFromBLEScan(result);
if (scanData.deviceRSSI != BLE_NO_RSSI) {
flora_device->updateRSSI(scanData.deviceRSSI);
}
LOG_F("BLE updated device #%d %s (%s): ",
flora_device->getID(),
flora_device->getName().c_str(),
flora_device->getAddress().c_str());
}
| 33.151335
| 101
| 0.676871
|
madl3x
|
21fbeb3529983db45ed0249a8854be985fe1afe3
| 536
|
hpp
|
C++
|
main/util/stdextend.hpp
|
michaelsimon101/Homepoint
|
c197bd8f5e84a4cb366cb6e1f2ce0ef5d77092bd
|
[
"MIT"
] | 506
|
2019-05-26T10:03:12.000Z
|
2022-03-30T16:01:14.000Z
|
main/util/stdextend.hpp
|
michaelsimon101/Homepoint
|
c197bd8f5e84a4cb366cb6e1f2ce0ef5d77092bd
|
[
"MIT"
] | 113
|
2019-05-26T11:33:06.000Z
|
2022-01-19T09:25:07.000Z
|
main/util/stdextend.hpp
|
michaelsimon101/Homepoint
|
c197bd8f5e84a4cb366cb6e1f2ce0ef5d77092bd
|
[
"MIT"
] | 74
|
2019-05-26T23:14:11.000Z
|
2022-03-24T22:07:11.000Z
|
#pragma once
#include <iterator>
#include <sstream>
#include <string>
namespace estd
{
// ESP32 STL is missing std::string::to_string
template <typename T>
std::string to_string(T value)
{
std::ostringstream os ;
os << value ;
return os.str() ;
}
} // namespace estd
namespace util
{
// Safely advance until end()
template <typename Iterator>
size_t safe_advance(Iterator& it, Iterator const& end, size_t n)
{
size_t i = 0;
for (; i != n && it != end; ++i, ++it);
return n - i;
}
}
| 17.866667
| 66
| 0.61194
|
michaelsimon101
|
1d0058b844d1dac98b3445a19a0cb93e3bd5b7ba
| 681
|
cpp
|
C++
|
LeetCode Problem-Set/24. Swap Nodes in Pairs (Medium)/Solution1.cpp
|
ankuralld5999/LeetCode-Problems
|
2f9a767a0effbb2a50672e102925fbbb65034083
|
[
"FSFAP"
] | 2
|
2021-01-06T20:43:59.000Z
|
2021-01-11T15:42:59.000Z
|
LeetCode Problem-Set/24. Swap Nodes in Pairs (Medium)/Solution1.cpp
|
ankuralld5999/LeetCode-Problems
|
2f9a767a0effbb2a50672e102925fbbb65034083
|
[
"FSFAP"
] | null | null | null |
LeetCode Problem-Set/24. Swap Nodes in Pairs (Medium)/Solution1.cpp
|
ankuralld5999/LeetCode-Problems
|
2f9a767a0effbb2a50672e102925fbbb65034083
|
[
"FSFAP"
] | null | null | null |
// Problem: https://leetcode.com/problems/swap-nodes-in-pairs/
// Author: github.com/ankuralld5999
// Time: O(N)
// Space: O(1)
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
if(head==NULL || head->next==NULL)
return head;
ListNode *p=NULL, *q=NULL, *r=head;
int n = 0;
while(r!=NULL){
n++;
r=r->next;
}
r=head;
for(int i=1; i<=n/2; i++){
p = q;
q = r;
r = r->next;
q->next = r->next;
r->next = q;
p==NULL ? head = r : p->next = r;
r = q->next;
}
return head;
}
};
| 23.482759
| 62
| 0.422907
|
ankuralld5999
|
1d0779a548ba928c3e951dd5082b7ca87c2163cf
| 958
|
hpp
|
C++
|
src/rooms/level.hpp
|
snailbaron/rooms
|
03496c3cd30e2020e1b0f1ad7d96bfba4e000eaa
|
[
"MIT"
] | null | null | null |
src/rooms/level.hpp
|
snailbaron/rooms
|
03496c3cd30e2020e1b0f1ad7d96bfba4e000eaa
|
[
"MIT"
] | null | null | null |
src/rooms/level.hpp
|
snailbaron/rooms
|
03496c3cd30e2020e1b0f1ad7d96bfba4e000eaa
|
[
"MIT"
] | null | null | null |
#pragma once
#include "cellar.hpp"
#include "geometry.hpp"
#include "types.hpp"
#include <filesystem>
#include <istream>
#include <iterator>
#include <string>
#include <vector>
enum class Cell : unsigned char {
Empty,
Full,
SmallColumn,
LargeColumn,
HalfHeight,
TallHeight,
};
class Level {
public:
struct Hit {
float distance;
Vector normal;
Cell cell;
};
void loadFromString(const std::string& string);
void loadFromFile(const std::filesystem::path& filePath);
std::vector<Hit> trace(
const Point& origin,
Vector lookDirection,
Vector rayDirection) const;
private:
static constexpr float _cellSize = 1.f;
static constexpr float _smallColumnRadius = 0.1f;
static constexpr float _largeColumnRadius = 0.3f;
Point normalizedCellPoint(const Point& levelPoint) const;
Point cellCenter(size_t x, size_t y) const;
Cellar<Cell> _cells;
};
| 19.958333
| 61
| 0.67119
|
snailbaron
|
1d0960f04530f276c37a982476e95a9005c38d33
| 1,776
|
cpp
|
C++
|
src/plugins/snails/accountlogger.cpp
|
Maledictus/leechcraft
|
79ec64824de11780b8e8bdfd5d8a2f3514158b12
|
[
"BSL-1.0"
] | 120
|
2015-01-22T14:10:39.000Z
|
2021-11-25T12:57:16.000Z
|
src/plugins/snails/accountlogger.cpp
|
Maledictus/leechcraft
|
79ec64824de11780b8e8bdfd5d8a2f3514158b12
|
[
"BSL-1.0"
] | 8
|
2015-02-07T19:38:19.000Z
|
2017-11-30T20:18:28.000Z
|
src/plugins/snails/accountlogger.cpp
|
Maledictus/leechcraft
|
79ec64824de11780b8e8bdfd5d8a2f3514158b12
|
[
"BSL-1.0"
] | 33
|
2015-02-07T16:59:55.000Z
|
2021-10-12T00:36:40.000Z
|
/**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
**********************************************************************/
#include "accountlogger.h"
#include <QFile>
#include <QDateTime>
#include <QtDebug>
#include <QDir>
#include <util/sys/paths.h>
#include "account.h"
namespace LC
{
namespace Snails
{
AccountLogger::AccountLogger (const QString& accName, QObject *parent)
: QObject { parent }
, AccName_ { accName }
{
}
void AccountLogger::SetEnabled (bool enabled)
{
Enabled_ = enabled;
}
void AccountLogger::Log (const QString& context, int connId, const QString& msg)
{
const auto& now = QDateTime::currentDateTime ();
const auto& str = QString { "[%1] [%2] [%3]: %4" }
.arg (now.toString ("dd.MM.yyyy HH:mm:ss.zzz"))
.arg (context)
.arg (connId)
.arg (msg);
QMetaObject::invokeMethod (this,
"writeLog",
Qt::QueuedConnection,
Q_ARG (QString, str));
emit gotLog (now, context, connId, msg);
}
void AccountLogger::writeLog (const QString& log)
{
if (!Enabled_)
return;
if (!File_)
{
const auto& path = Util::CreateIfNotExists ("snails/logs").filePath (AccName_ + ".log");
File_ = std::make_shared<QFile> (path);
if (!File_->open (QIODevice::WriteOnly))
{
qWarning () << Q_FUNC_INFO
<< "unable to open"
<< path
<< "for writing, error:"
<< File_->errorString ();
return;
}
}
if (File_->isOpen ())
{
File_->write (log.toUtf8 () + "\n");
File_->flush ();
}
}
}
}
| 23.064935
| 91
| 0.586712
|
Maledictus
|
1d0c6cc6acf6407d35237ac5f98c450d1ba7f7dd
| 478
|
cpp
|
C++
|
week5/MoneyChangeAgain.cpp
|
leohr/coursera-algorithmic-toolbox
|
53894f826f00b0776859174d45395eab48180dde
|
[
"MIT"
] | null | null | null |
week5/MoneyChangeAgain.cpp
|
leohr/coursera-algorithmic-toolbox
|
53894f826f00b0776859174d45395eab48180dde
|
[
"MIT"
] | null | null | null |
week5/MoneyChangeAgain.cpp
|
leohr/coursera-algorithmic-toolbox
|
53894f826f00b0776859174d45395eab48180dde
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main(){
int n; cin >> n;
vector<int> sols(n+1);
for (int x=1; x<n+1; ++x){
if (x == 1)
sols[x] = 1;
else if (x == 2)
sols[x] = 2;
else if (x == 3)
sols[x] = 1;
else if (x == 4)
sols[x] = 1;
else
sols[x] = 1 + min(sols[x-1], min(sols[x-3], sols[x-4]));
}
cout << sols[n] << endl;
return 0;
}
| 22.761905
| 70
| 0.378661
|
leohr
|
1d17ec08510aaa84286abb18c17663b136f5c8c3
| 1,255
|
cpp
|
C++
|
src/lesson_2/changing.cpp
|
tarcisioe/cpp-mdbook
|
61ddab9ba126328f618574d427ede7121146de15
|
[
"MIT"
] | 2
|
2020-03-16T04:14:15.000Z
|
2021-07-07T22:33:58.000Z
|
src/lesson_2/changing.cpp
|
tarcisioe/cpp-mdbook
|
61ddab9ba126328f618574d427ede7121146de15
|
[
"MIT"
] | null | null | null |
src/lesson_2/changing.cpp
|
tarcisioe/cpp-mdbook
|
61ddab9ba126328f618574d427ede7121146de15
|
[
"MIT"
] | null | null | null |
#include <vector>
#include <iostream>
int main()
{
auto v = std::vector<int>{1, 2, 3, 4};
auto w = std::vector<int>{4, 3, 2, 1};
std::cout << "Before: v[3] = " << v[3] << "\n";
v[3] = 42;
std::cout << "Now: v[3] = " << v[3] << "\n";
auto n = v.size();
std::cout << "n = v.size() = " << n << "\n";
std::cout << "Before: v[n-1] = " << v[n-1] << "\n";
v.push_back(777);
n = v.size(); // Atualiza tamanho do vetor
std::cout << "n = v.size() = " << n << "\n";
std::cout << "Now: v[n-1] = " << v[n-1] << "\n";
std::cout << "v[n-2] = " << v[n-2] << "\n";
v.pop_back();
n = v.size();
std::cout << "Popped vector's back\n";
std::cout << "n = v.size() = " << n << "\n";
std::cout << "Now: v[n-1] = " << v[n-1] << "\n";
std::cout << "v[n-2] = " << v[n-2] << "\n";
auto strings = std::vector<std::string>{ "Hello", "World", "!" };
std::cout << "strings = {\""
<< strings[0] << "\", \""
<< strings[1] << "\", \""
<< strings[2] << "\"}\n";
std::cout << "With strings' contents we can say... you had it coming:\n";
std::cout << strings[0] << ", " << strings[1] << strings[2] << "\n";
// strings.push_back(3);
}
| 23.679245
| 77
| 0.404781
|
tarcisioe
|
1d1ccc514214e4b497c0d8e43387381d414fb48d
| 1,203
|
cpp
|
C++
|
raytrace/HitList.cpp
|
lede701/raytrace
|
79b0082c6cd90fd1381263c3795ece6bdf3e6cfa
|
[
"Unlicense"
] | null | null | null |
raytrace/HitList.cpp
|
lede701/raytrace
|
79b0082c6cd90fd1381263c3795ece6bdf3e6cfa
|
[
"Unlicense"
] | null | null | null |
raytrace/HitList.cpp
|
lede701/raytrace
|
79b0082c6cd90fd1381263c3795ece6bdf3e6cfa
|
[
"Unlicense"
] | null | null | null |
#include "HitList.h"
HitList::HitList()
{
}
HitList::HitList(Hitable **l, int n)
{
hList = l;
hSize = n;
eSize = -1;
}
HitList::HitList(Entity **e, int n)
{
eList = e;
eSize = n;
hSize = -1;
}
HitList::~HitList()
{
}
bool HitList::hit(const Ray& r, float t_min, float t_max, HitRecord& hit) const
{
bool bRetVal = false;
if (eSize > 0)
{
bRetVal = eHit(r, t_min, t_max, hit);
}
else if (hSize > 0)
{
bRetVal = hHit(r, t_min, t_max, hit);
}
return bRetVal;
}
bool HitList::eHit(const Ray& r, float t_min, float t_max, HitRecord& hit) const
{
HitRecord temp_hit;
bool hitAnything = false;
float closestSoFar = t_max;
for (int i = 0; i < eSize; ++i)
{
if (eList[i]->hit(r, t_min, closestSoFar, temp_hit))
{
hitAnything = true;
closestSoFar = temp_hit.t;
hit = temp_hit;
}
}
return hitAnything;
}
bool HitList::hHit(const Ray& r, float t_min, float t_max, HitRecord& hit) const
{
HitRecord temp_hit;
bool hitAnything = false;
float closestSoFar = t_max;
for (int i = 0; i < hSize; ++i)
{
if (hList[i]->hit(r, t_min, closestSoFar, temp_hit))
{
hitAnything = true;
closestSoFar = temp_hit.t;
hit = temp_hit;
}
}
return hitAnything;
}
| 15.623377
| 80
| 0.632585
|
lede701
|
1d1d3cb324ec29b123e60314b0b0ea694ffac672
| 3,100
|
hh
|
C++
|
include/core/IAgent.hh
|
thingthing/smart-agent
|
f4c41432b1bab3283b00237b0208676acb0a00b1
|
[
"MIT"
] | null | null | null |
include/core/IAgent.hh
|
thingthing/smart-agent
|
f4c41432b1bab3283b00237b0208676acb0a00b1
|
[
"MIT"
] | null | null | null |
include/core/IAgent.hh
|
thingthing/smart-agent
|
f4c41432b1bab3283b00237b0208676acb0a00b1
|
[
"MIT"
] | null | null | null |
#ifndef _IAGENT_HH_
# define _IAGENT_HH_
#include <string>
#include <pcl/common/transforms.h>
#include <pcl/common/common.h>
#include <pcl/impl/point_types.hpp>
#include <pcl/common/projection_matrix.h>
#include "event/Dispatcher.h"
#include "ICapture.hh"
class IAgent : public Utils::Dispatcher
{
public:
//Defined in IAgent.cpp
static const double DEGREESPERSCAN; // meter
static const double CAMERAPROBLEM; // meter
enum e_mode {
DIRECT,
DELAYED
};
IAgent(double degreePerScan = DEGREESPERSCAN, double cameraProblem = CAMERAPROBLEM,
std::string const &name = "Default", int battery = 0, e_mode mode = DIRECT);
virtual ~IAgent();
pcl::PointXYZ const &getPos() const;
double getRoll() const;
ICapture *getCapture() const;
double getYaw() const;
double getPitch() const;
double getPrevYaw() const;
double getPrevPitch() const;
double getPrevRoll() const;
int getBattery() const;
pcl::PointXYZ getVelocity() const { return _velocity; }
pcl::PointXYZ getAcceleration() const { return _acceleration; }
inline e_mode getMode() const { return _mode; }
inline bool getSendData() { return _send_data; }
inline void setSendData(bool data) { _send_data = data; }
void setBattery(int new_battery_value);
void setRoll(double thrust);
void setYaw(double theta);
void setPitch(double deltaTheta);
void setPrevRoll(double deltaTheta);
void setPrevPitch(double deltaTheta);
void setPrevYaw(double deltaTheta);
void setPos(pcl::PointXYZ const &pos);
void setPos(double x, double y, double z);
inline void setVelocity(pcl::PointXYZ const &velo) { _velocity = velo; }
inline void setAcceleration(pcl::PointXYZ const &accel) { _acceleration = accel; }
std::string const &status(std::string const &status);
inline void setMode(e_mode mode) { _mode = mode; }
virtual pcl::PointCloud<pcl::PointXYZRGBA> const &takeData() = 0;
virtual void updateState(bool true_update = true) = 0;
virtual void goTowardsGoal() = 0;
inline std::string const &name() const { return (_name); }
inline std::string const &status() const {return (_status) ;}
double const degreePerScan;
double const cameraProblem;
protected:
pcl::PointXYZ _pos;
double _yaw;
std::string _name;
std::string _status;
double _roll;
double _pitch;
double _prev_roll;
double _prev_pitch;
double _prev_yaw;
ICapture *_capture;
int _battery;
bool _send_data;
pcl::PointXYZ _velocity;
pcl::PointXYZ _acceleration;
e_mode _mode;
public:
//Use to align class with pointCloud
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
#endif /* !_IAGENT_HH_ */
| 32.631579
| 90
| 0.610968
|
thingthing
|
1d21e0f999e9650fab0e94b8d429d225f203031a
| 1,807
|
cpp
|
C++
|
app/crawler/srcs/main.cpp
|
team-irc/twitch-chat-analyzer
|
4af175ec5dfd3dc43ad7b1e401f65d6cc4858bd7
|
[
"MIT"
] | 1
|
2022-01-13T07:12:47.000Z
|
2022-01-13T07:12:47.000Z
|
app/crawler/srcs/main.cpp
|
team-irc/twitch-chat-analyzer
|
4af175ec5dfd3dc43ad7b1e401f65d6cc4858bd7
|
[
"MIT"
] | 10
|
2021-12-18T12:33:45.000Z
|
2022-02-07T20:14:00.000Z
|
app/crawler/srcs/main.cpp
|
team-irc/twitch-chat-analyzer
|
4af175ec5dfd3dc43ad7b1e401f65d6cc4858bd7
|
[
"MIT"
] | null | null | null |
#include "IrcClient.hpp"
#include "IrcSocket.hpp"
#include "utils.hpp"
#define LOGGING_INTERVAL 60
IrcClient *g_client; // 입력용 thread와 공유할 변수
void announce()
{
std::cout << "채널 참여: join #twitch_id" << std::endl;
std::cout << "채널 나가기: part #twitch_id" << std::endl;
}
void input_thread()
{
std::string msg;
while (true)
{
getline(std::cin, msg);
if (msg == "")
continue;
if (msg == "quit" || msg == "exit")
exit(0);
if (msg == "help")
announce();
g_client->send_to_server(msg);
}
}
void log_current_time()
{
std::time_t t = std::time(0); // get time now
std::tm* now = std::localtime(&t);
std::cout << '[' << (now->tm_year + 1900) << '-'
<< (now->tm_mon + 1) << '-'
<< now->tm_mday << ' '
<< now->tm_hour << ':'
<< now->tm_min << ':'
<< now->tm_sec << ']';
}
void log_parse_chat_counter()
{
g_client->parse_chat("", true);
}
void logging_thread()
{
std::string log;
while (true)
{
log_current_time();
log_parse_chat_counter();
sleep(LOGGING_INTERVAL);
}
}
int main()
{
try
{
g_client = new IrcClient();
g_client->login_twitch();
g_client->join_streamer_channels();
// announce();
// std::thread thread(input_thread);
// std::thread thread2(logging_thread);
// thread.detach();
// thread2.detach();
while (true)
{
try
{
g_client->recv_from_server();
}
catch (SocketDisconnectError const &e)
{
std::cout << "socket connection closed. (recv return 0)" << std::endl;
std::cout << "try socket reconnect. after 30seconds " << std::endl;
sleep(30);
delete g_client;
g_client = new IrcClient();
g_client->login_twitch();
g_client->join_streamer_channels();
}
}
}
catch (IrcError const &e)
{
std::cerr << e.what() << std::endl;
}
delete g_client;
return 0;
}
| 18.822917
| 74
| 0.596569
|
team-irc
|
1d22621add933a8dbe6aebe2a2ebe969866741e0
| 1,481
|
cc
|
C++
|
src/solvers/wg/WGSolverSI.cc
|
baklanovp/libdetran
|
820efab9d03ae425ccefb9520bdb6c086fdbf939
|
[
"MIT"
] | 4
|
2015-03-07T16:20:23.000Z
|
2020-02-10T13:40:16.000Z
|
src/solvers/wg/WGSolverSI.cc
|
baklanovp/libdetran
|
820efab9d03ae425ccefb9520bdb6c086fdbf939
|
[
"MIT"
] | 3
|
2018-02-27T21:24:22.000Z
|
2020-12-16T00:56:44.000Z
|
src/solvers/wg/WGSolverSI.cc
|
baklanovp/libdetran
|
820efab9d03ae425ccefb9520bdb6c086fdbf939
|
[
"MIT"
] | 9
|
2015-03-07T16:20:26.000Z
|
2022-01-29T00:14:23.000Z
|
//----------------------------------*-C++-*-----------------------------------//
/**
* @file WGSolverSI.cc
* @brief WGSolverSI member definitions
* @note Copyright(C) 2012-2013 Jeremy Roberts
*/
//----------------------------------------------------------------------------//
#include "WGSolverSI.hh"
namespace detran
{
//----------------------------------------------------------------------------//
template <class D>
WGSolverSI<D>::WGSolverSI(SP_state state,
SP_material material,
SP_quadrature quadrature,
SP_boundary boundary,
const vec_externalsource &q_e,
SP_fissionsource q_f,
bool multiply)
: Base(state, material, quadrature, boundary, q_e, q_f, multiply)
{
d_sweeper->set_update_boundary(true);
}
//----------------------------------------------------------------------------//
// EXPLICIT INSTANTIATIONS
//----------------------------------------------------------------------------//
template class WGSolverSI<_1D>;
template class WGSolverSI<_2D>;
template class WGSolverSI<_3D>;
} // end namespace detran
//----------------------------------------------------------------------------//
// end of WGSolverSI.cc
//----------------------------------------------------------------------------//
| 36.121951
| 80
| 0.33761
|
baklanovp
|
1d2265afc047596b4b5b7c72bcfdf714e446044e
| 69,104
|
cc
|
C++
|
cnn/nodes.cc
|
kaishengyao/cnn
|
a034b837e88f82bd8adf2c5b0a5defb26fd52096
|
[
"Apache-2.0"
] | 16
|
2015-09-10T07:50:50.000Z
|
2017-09-17T03:02:38.000Z
|
cnn/nodes.cc
|
kaishengyao/cnn
|
a034b837e88f82bd8adf2c5b0a5defb26fd52096
|
[
"Apache-2.0"
] | null | null | null |
cnn/nodes.cc
|
kaishengyao/cnn
|
a034b837e88f82bd8adf2c5b0a5defb26fd52096
|
[
"Apache-2.0"
] | 10
|
2015-09-08T12:43:13.000Z
|
2018-09-26T07:32:47.000Z
|
#include "cnn/nodes.h"
#include <limits>
#include <cmath>
#include <stdexcept>
#include "cnn/macros.h"
#include "cnn/simd-functors.h"
#include "cnn/functors.h"
#if HAVE_CUDA
#include <thrust/host_vector.h>
#include <thrust/device_vector.h>
#include "cnn/cuda.h"
#include "cnn/gpu-ops.h"
using namespace cnn::gpu;
#endif
using namespace std;
// notes on implementing differentiable components
// 1) fx can be understood as a pointer to the (preallocated) location for the result
// of forward to be stored
// 2) fx is not initialized, so after calling forward fx must point to the correct answer
// 3) fx can be repointed to an input, if forward(x) evaluates to x (e.g., in reshaping)
// 4) dEdxi MUST **ACCUMULATE** a result since multiple calls to forward may depend on
// the same x_i. Even, e.g., Identity must be implemented as
// dEdx1 += dEdf. THIS IS EXTREMELY IMPORTANT
// 5) scalars results of forward are placed in fx.v[0]
// 6) CNN manages its own memory, not Eigen, and it is configured with the
// EIGEN_NO_MALLOC option. If you get an error about Eigen attempting to allocate
// memory, it is (probably) because of an implicit creation of a temporary variable.
// To tell Eigen this is not necessary, the noalias() method is available. If you really
// do need a temporary variable, its capacity must be requested by Node::aux_storage_space
//
// notes on debugging problems with differentiable components
// 1) fx is uninitialized when forward is called- are you relying on it being 0?
// 2) dEdxi must accummulate (see point 4 above!)
//
namespace cnn {
void Pow::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 2);
#ifdef HAVE_CUDA
throw std::runtime_error("Pow not yet implemented for CUDA");
#else
auto x1 = **xs[0];
auto x2 = xs[1]->v[0];
(*fx).array() = x1.array().pow(x2);
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void Pow::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(xs.size() == 2);
#ifdef HAVE_CUDA
throw std::runtime_error("Pow not yet implemented for CUDA");
#else
auto x1 = **xs[0];
auto x2 = xs[1]->v[0];
if (i == 0) {
*dEdxi += (x2 * x1.array().pow(x2 - 1).matrix()).cwiseProduct(*dEdf);
} else {
// y = a^x
// dy/dx = a^x * log(a)
(*dEdxi).noalias() += (*fx).cwiseProduct(x1.array().log().matrix()).transpose() * (*dEdf);
}
#endif
}
size_t Min::aux_storage_size() const {
return dim.size() * sizeof(cnn::real);
}
void Min::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
#ifdef HAVE_CUDA
throw std::runtime_error("Min not yet implemented for CUDA");
#else
auto y = *fx;
auto x1 = **xs[0];
auto x2 = **xs[1];
Tensor t(fx.d, static_cast<cnn::real*>(aux_mem), xs[0]->m_device_id);
auto u = *t;
u = (x1.array() < x2.array()).matrix().cast<cnn::real>();
y = x1.cwiseMin(x2);
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void Min::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(i < 2);
#ifdef HAVE_CUDA
throw std::runtime_error("Min not yet implemented for CUDA");
#else
const Tensor t(dEdxi.d, static_cast<cnn::real*>(aux_mem), xs[0]->m_device_id);
if (i == 0) {
*dEdxi += (*t).cwiseProduct(*dEdf);
} else {
*dEdxi += (*t).binaryExpr(*dEdf, FMaxBackwardInv());
}
#endif
}
size_t Max::aux_storage_size() const {
return dim.size() * sizeof(cnn::real);
}
void Max::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
#ifdef HAVE_CUDA
throw std::runtime_error("Max not yet implemented for CUDA");
#else
auto y = *fx;
auto x1 = **xs[0];
auto x2 = **xs[1];
Tensor t(fx.d, static_cast<cnn::real*>(aux_mem), xs[0]->m_device_id);
auto u = *t;
u = (x1.array() > x2.array()).matrix().cast<cnn::real>();
y = x1.cwiseMax(x2);
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void Max::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(i < 2);
#ifdef HAVE_CUDA
throw std::runtime_error("Max not yet implemented for CUDA");
#else
const Tensor t(dEdxi.d, static_cast<cnn::real*>(aux_mem), xs[0]->m_device_id);
if (i == 0) {
*dEdxi += (*t).cwiseProduct(*dEdf);
} else {
*dEdxi += (*t).binaryExpr(*dEdf, FMaxBackwardInv());
}
#endif
}
void TraceOfProduct::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
#ifdef HAVE_CUDA
throw std::runtime_error("TraceOfProduct not yet implemented for CUDA");
#else
auto x1 = **xs[0];
auto x2 = **xs[1];
fx.v[0] = (x1 * x2.transpose()).trace();
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void TraceOfProduct::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(i < 2);
#ifdef HAVE_CUDA
throw std::runtime_error("TraceOfProduct not yet implemented for CUDA");
#else
const cnn::real d = dEdf.v[0];
auto xother = **xs[1 - i];
*dEdxi += d * xother;
#endif
}
void ConstScalarMultiply::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
#if HAVE_CUDA
gpu::vconstant_multiplyx(fx.d.size(), alpha, xs[0]->v, fx.v);
#else
*fx = (**xs[0]) * alpha;
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void ConstScalarMultiply::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const
{
assert(i == 0);
#if HAVE_CUDA
gpu::vconstant_multiplyx_backward(fx.d.size(), alpha, dEdf.v, dEdxi.v);
#else
*dEdxi += *dEdf * alpha;
#endif
}
void DotProduct::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
#ifdef HAVE_CUDA
throw std::runtime_error("DotProduct not yet implemented for CUDA");
#else
*fx = (**xs[0]).transpose() * (**xs[1]);
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void DotProduct::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#ifdef HAVE_CUDA
throw std::runtime_error("DotProduct not yet implemented for CUDA");
#else
(*dEdxi) += (dEdf.v[0]) * (**xs[1 - i]);
#endif
}
void Transpose::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
if (dim.rows() == 1 || dim.cols() == 1) {
#if HAVE_CUDA
CUDA_CHECK(cudaMemcpy(fx.v, xs[0]->v, sizeof(cnn::real) * dim.size(), cudaMemcpyDeviceToDevice));
#else
fx.v = xs[0]->v;
#endif
}
else {
#ifdef HAVE_CUDA
#ifdef USE_DOUBLE
CUBLAS_CHECK(cublasDgeam(cublas_handle, CUBLAS_OP_T, CUBLAS_OP_T, fx.d.rows(), fx.d.cols(),
kSCALAR_ONE, xs[0]->v, xs[0]->d.rows(), kSCALAR_ZERO, xs[0]->v, xs[0]->d.rows(), fx.v, fx.d.rows()));
#else
CUBLAS_CHECK(cublasSgeam(cublas_handle, CUBLAS_OP_T, CUBLAS_OP_T, fx.d.rows(), fx.d.cols(),
kSCALAR_ONE, xs[0]->v, xs[0]->d.rows(), kSCALAR_ZERO, xs[0]->v, xs[0]->d.rows(), fx.v, fx.d.rows()));
#endif
#else
for(unsigned b = 0; b < xs[0]->d.bd; ++b)
fx.batch_matrix(b).noalias() = xs[0]->batch_matrix(b).transpose();
#endif
}
fx.m_device_id = xs[0]->m_device_id;
}
void Transpose::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#if HAVE_CUDA
/// for usage of of cublassegeam see
/// http://scikit-cuda.readthedocs.org/en/latest/generated/skcuda.cublas.cublasSgeam.html
#ifdef USE_DOUBLE
CUBLAS_CHECK(cublasDgeam(cublas_handle, CUBLAS_OP_T, CUBLAS_OP_N, dEdxi.d.rows(), dEdxi.d.cols(),
kSCALAR_ONE, dEdf.v, dEdf.d.rows(), kSCALAR_ONE, dEdxi.v, dEdxi.d.rows(), dEdxi.v, dEdxi.d.rows()));
#else
CUBLAS_CHECK(cublasSgeam(cublas_handle, CUBLAS_OP_T, CUBLAS_OP_N, dEdxi.d.rows(), dEdxi.d.cols(),
kSCALAR_ONE, dEdf.v, dEdf.d.rows(), kSCALAR_ONE, dEdxi.v, dEdxi.d.rows(), dEdxi.v, dEdxi.d.rows()));
#endif
#else
for(unsigned b = 0; b < xs[0]->d.bd; ++b)
dEdxi.batch_matrix(b) += dEdf.batch_matrix(b).transpose();
#endif
}
void Reshape::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
// BUG will be created if just point to the input memory and change dimensions
fx.v = xs[0]->v;
fx.m_device_id = xs[0]->m_device_id;
}
void Reshape::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
const Tensor reshaped(dEdxi.d, dEdf.v, device_id);
#ifdef HAVE_CUDA
gpu::vconstant_multiplyx_backward(reshaped.d.size(), 1.0, reshaped.v, dEdxi.v);
#else
*dEdxi += *reshaped;
#endif
}
void SumColumns::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
auto x = **xs[0];
auto y = *fx;
if (xs.size() == 1) {
y = x.rowwise().sum();
} else {
throw std::invalid_argument("two inputs in SumColumns::forward!");
}
fx.m_device_id = xs[0]->m_device_id;
}
void SumColumns::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
auto out = *dEdxi;
// this uses Eigen's broadcast capability
// the following doesn't compile, so i use the next line
//out.colwise() += *dEdf;
out.colwise() += (*dEdf).col(0);
}
void KMHNGram::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
auto x = **xs[0];
const int new_cols = x.cols() - n + 1;
assert(new_cols > 0);
auto res = *fx;
res.setZero();
for (int j = 0; j < new_cols; ++j) {
auto c_j = res.col(j);
for (unsigned k = 0; k < n; ++k)
c_j += x.col(j + k);
}
fx.m_device_id = xs[0]->m_device_id;
}
void KMHNGram::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
const int c = dEdf.d.cols();
for (int j = 0; j < c; ++j)
for (unsigned k = 0; k < n; ++k)
(*dEdxi).col(j+k) += (*dEdf).col(j);
}
// Y_ij = A_ijk * B_k (+ C_ij)
void InnerProduct3D_1D::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
auto b = **xs[1];
auto y = *fx;
const unsigned i = y.rows();
const unsigned j = y.cols();
const unsigned k = b.rows();
// the following reshape tensors into order 1 or 2 sizes
// but they point to the same memory
Tensor ta({i*j,k}, xs[0]->v, device_id);
Tensor ty({i*j}, fx.v, device_id);
auto A = *ta;
if (xs.size() == 3) {
Tensor tc({ i*j }, xs[2]->v, device_id);
auto c = *tc;
// want to do A * b + c, but it triggers memory allocation
(*ty) = c;
(*ty).noalias() += A * b;
} else {
assert(xs.size() == 2);
(*ty).noalias() = A * b;
}
fx.m_device_id = xs[0]->m_device_id;
}
void InnerProduct3D_1D::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
auto b = **xs[1];
auto y = *fx;
const unsigned si = y.rows();
const unsigned sj = y.cols();
const unsigned sk = b.rows();
Tensor tdEdf({ si*sj }, dEdf.v, device_id);
if (i == 0) { // 3-tensor
Tensor tdEdxi({ si*sj, sk }, dEdxi.v, device_id);
(*tdEdxi).noalias() += *tdEdf * (**xs[1]).transpose();
} else if (i == 1) { // vector
Tensor ta({ si*sj, sk }, xs[0]->v, device_id);
(*dEdxi).noalias() += (*ta).transpose() * *tdEdf;
} else { // matrix bias
*dEdxi += *dEdf;
}
}
size_t GaussianNoise::aux_storage_size() const {
return dim.size() * sizeof(cnn::real);
}
void GaussianNoise::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
#ifdef HAVE_CUDA
throw std::runtime_error("GaussianNoise not yet implemented for CUDA");
#else
Tensor m(dim, (cnn::real*)aux_mem, xs[0]->m_device_id);
TensorTools::RandomizeNormal(0, stddev, m);
(*fx) = **xs[0] + *m;
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void GaussianNoise::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#ifdef HAVE_CUDA
throw std::runtime_error("GaussianNoise not yet implemented for CUDA");
#else
*dEdxi += *dEdf;
#endif
}
size_t Dropout::aux_storage_size() const {
return dim.size() * sizeof(cnn::real);
}
void Dropout::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
#ifdef HAVE_CUDA
throw std::runtime_error("Dropout not yet implemented for CUDA");
#else
Tensor m(dim, (cnn::real*)aux_mem, xs[0]->m_device_id);
TensorTools::RandomBernoulli(m, (1.f-p), 1.f / (1.f-p));
fx.vec() = xs[0]->vec().cwiseProduct(m.vec());
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void Dropout::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#ifdef HAVE_CUDA
throw std::runtime_error("Pow not yet implemented for CUDA");
#else
Tensor m(dim, (cnn::real*)aux_mem, xs[0]->m_device_id);
dEdxi.vec() += dEdf.vec().cwiseProduct(m.vec());
#endif
}
size_t BlockDropout::aux_storage_size() const {
// we just need to remember whether this entire block is turned on (1.0) or off (0.0)
return 1 * sizeof(cnn::real);
}
void BlockDropout::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
#ifdef HAVE_CUDA
throw std::runtime_error("BlockDropout not yet implemented for CUDA");
#else
bernoulli_distribution distribution(1.0 - dropout_probability);
cnn::real block_multiplier = distribution(*rndeng)? 1.0 : 0.0;
block_multiplier =
dropout_probability == 1.0? 0.0 : block_multiplier / (1.0 - dropout_probability);
if (dropout_probability > 1.0 || dropout_probability < 0.0) {
assert(false && "dropout probability must be in the range [0, 1]");
}
*(static_cast<cnn::real*>(aux_mem)) = block_multiplier;
(*fx) = **xs[0] * block_multiplier;
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void BlockDropout::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#ifdef HAVE_CUDA
throw std::runtime_error("BlockDropout not yet implemented for CUDA");
#else
cnn::real block_multiplier = *(static_cast<cnn::real*>(aux_mem));
(*dEdxi) += (*dEdf) * block_multiplier;
#endif
}
void ConstantPlusX::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
#ifdef HAVE_CUDA
throw std::runtime_error("ConstantPlusX not yet implemented for CUDA");
#else
auto x = **xs[0];
*fx = x.unaryExpr(const_add_op<cnn::real>(c));
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void ConstantPlusX::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
*dEdxi += *dEdf;
}
void ConstantMinusX::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
#if HAVE_CUDA
gpu::vconstant_minusx(fx.d.size(), c, xs[0]->v, fx.v);
#else
auto x = **xs[0];
*fx = x.unaryExpr(const_minus_op<cnn::real>(c));
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void ConstantMinusX::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#if HAVE_CUDA
gpu::vnegate_backward(dEdxi.d.size(), dEdf.v, dEdxi.v);
#else
*dEdxi -= *dEdf;
#endif
}
template <class T>
EIGEN_STRONG_INLINE cnn::real logsumexp(const T& x) {
using std::exp;
using std::log;
const cnn::real m = x.maxCoeff();
#if 1
// these are equivalent, but this can use vectorized arithmetic
cnn::real z = x.unaryExpr(const_add_op<cnn::real>(-m)).array().exp().matrix().sum();
#else
cnn::real z = 0;
for (unsigned i = 0; i < x.rows(); ++i)
z += exp(x(i,0) - m);
#endif
return m + log(z);
}
// this i need to do something better, but this is a work-around
// if this is too small, just make it bigger
#define MAX_LOG_SUM_EXP 65536
size_t LogSumExp::aux_storage_size() const {
return MAX_LOG_SUM_EXP * sizeof(cnn::real);
}
void LogSumExp::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
const unsigned num_args = xs.size();
if (num_args == 1) {
fx.v = xs[0]->v;
return;
}
for (unsigned i = 0; i < xs.size(); ++i)
static_cast<cnn::real*>(aux_mem)[i] = (**xs[i])(0,0);
Dim r = {(unsigned int)xs.size()};
Tensor v(r, static_cast<cnn::real*>(aux_mem), device_id);
fx.v[0] = logsumexp(*v);
fx.m_device_id = xs[0]->m_device_id;
}
void LogSumExp::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
if (xs.size() == 0) {
*dEdxi += *dEdf;
return;
}
// df/dx_i = 1/{sum_j exp(x_j)} * exp(x_i)}
// = 1/{exp f(x)} * exp(x_i)
// = exp(x_i - f(x))
auto d = *dEdxi;
d.array() += (**xs[i] - *fx).array().exp() * (*dEdf).array();
}
void Reduce::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
const unsigned num_args = xs.size();
assert(num_args == 1 && fx.d.cols() == 1);
#if HAVE_CUDA
l2_norm_reducer(xs[0]->d.size(), xs[0]->v, fx.v, false, false);
#else
fx.v[0] = 0.0;
for (int k = 0; k < xs[0]->d.size(); k++)
fx.v[0] += xs[0]->v[k];
#endif
fx.m_device_id = xs[0]->m_device_id;
return;
}
void Reduce::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#if HAVE_CUDA
l2_norm_reducer(1, dEdf.v, dEdxi.v, false, true);
#else
for (int k = 0; k < dEdxi.d.size(); k++)
dEdxi.v[k] += dEdf.v[0];
#endif
}
void Sum::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
const unsigned num_args = xs.size();
fx.m_device_id = xs[0]->m_device_id;
if (num_args == 1) {
fx.v = xs[0]->v;
return;
}
#if HAVE_CUDA
TensorTools::Zero(fx);
for (unsigned i = 0; i < num_args; ++i)
{
if (sizeof(cnn::real) == sizeof(float))
{
CUBLAS_CHECK(cublasSaxpy(cublas_handle, fx.d.size(), reinterpret_cast<float*>(kSCALAR_ONE), reinterpret_cast<float*>(xs[i]->v), 1, reinterpret_cast<float*>(fx.v), 1));
}
else if (sizeof(cnn::real) == sizeof(double))
{
CUBLAS_CHECK(cublasDaxpy(cublas_handle, fx.d.size(), reinterpret_cast<double*>(kSCALAR_ONE), reinterpret_cast<double*>(xs[i]->v), 1, reinterpret_cast<double*>(fx.v), 1));
}
}
#else
auto res = *fx;
const unsigned remainder = num_args % 4;
switch (remainder) {
case 0: res.setZero(); break;
case 1: res = **xs[0]; break;
case 2: res = **xs[0] + **xs[1]; break;
case 3: res = **xs[0] + **xs[1] + **xs[2]; break;
}
for (unsigned i = remainder; i < num_args; i += 4)
res += **xs[i] + **xs[i+1] + **xs[i+2] + **xs[i+3];
#endif
}
void Sum::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#if HAVE_CUDA
if (sizeof(cnn::real) == sizeof(float))
CUBLAS_CHECK(cublasSaxpy(cublas_handle, fx.d.size(), reinterpret_cast<float*>(kSCALAR_ONE), reinterpret_cast<float*>(dEdf.v), 1, reinterpret_cast<float*>(dEdxi.v), 1));
else if (sizeof(cnn::real) == sizeof(double))
CUBLAS_CHECK(cublasDaxpy(cublas_handle, fx.d.size(), reinterpret_cast<double*>(kSCALAR_ONE), reinterpret_cast<double*>(dEdf.v), 1, reinterpret_cast<double*>(dEdxi.v), 1));
#else
*dEdxi += *dEdf;
#endif
}
void SumBatches::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 1);
unsigned num_args = xs[0]->d.bd;
fx.m_device_id = xs[0]->m_device_id;
#if HAVE_CUDA
TensorTools::Zero(fx);
for (unsigned i = 0; i < num_args; ++i)
{
if (sizeof(cnn::real) == sizeof(float))
CUBLAS_CHECK(cublasSaxpy(cublas_handle, fx.d.size(), reinterpret_cast<float*>(kSCALAR_ONE), reinterpret_cast<float*>(xs[0]->v + i * xs[0]->d.batch_size()), 1, reinterpret_cast<float*>(fx.v), 1));
else if (sizeof(cnn::real) == sizeof(double))
CUBLAS_CHECK(cublasDaxpy(cublas_handle, fx.d.size(), reinterpret_cast<double*>(kSCALAR_ONE), reinterpret_cast<double*>(xs[0]->v + i * xs[0]->d.batch_size()), 1, reinterpret_cast<double*>(fx.v), 1));
}
#else
auto res = *fx;
const unsigned remainder = num_args % 4;
switch (remainder) {
case 0: res.setZero(); break;
case 1: res = xs[0]->batch_matrix(0); break;
case 2: res = xs[0]->batch_matrix(0) + xs[0]->batch_matrix(1); break;
case 3: res = xs[0]->batch_matrix(0) + xs[0]->batch_matrix(1) + xs[0]->batch_matrix(2); break;
}
for (unsigned i = remainder; i < num_args; i += 4)
res += xs[0]->batch_matrix(i) + xs[0]->batch_matrix(i+1) + xs[0]->batch_matrix(i+2) + xs[0]->batch_matrix(i+3);
#endif
}
void SumBatches::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(i == 0);
#if HAVE_CUDA
for (unsigned i = 0; i < dEdxi.d.bd; ++i)
{
if (sizeof(cnn::real) == sizeof(float))
CUBLAS_CHECK(cublasSaxpy(cublas_handle, fx.d.size(), reinterpret_cast<float*>(kSCALAR_ONE), reinterpret_cast<float*>(dEdf.v), 1, reinterpret_cast<float*>(dEdxi.v) + i * dEdxi.d.batch_size(), 1));
else if (sizeof(cnn::real) == sizeof(double))
CUBLAS_CHECK(cublasDaxpy(cublas_handle, fx.d.size(), reinterpret_cast<double*>(kSCALAR_ONE), reinterpret_cast<double*>(dEdf.v), 1, reinterpret_cast<double*>(dEdxi.v) + i * dEdxi.d.batch_size(), 1));
}
#else
for (unsigned i = 0; i < dEdxi.d.bd; ++i)
dEdxi.batch_matrix(i) += *dEdf;
#endif
}
size_t Average::aux_storage_size() const {
return sizeof(cnn::real);
}
void Average::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
const unsigned num_args = xs.size();
fx.m_device_id = xs[0]->m_device_id;
#if HAVE_CUDA
TensorTools::Zero(fx);
for (unsigned i = 0; i < num_args; ++i)
{
if (sizeof(cnn::real) == sizeof(float))
CUBLAS_CHECK(cublasSaxpy(cublas_handle, fx.d.size(), reinterpret_cast<float*>(kSCALAR_ONE), reinterpret_cast<float*>(xs[i]->v), 1, reinterpret_cast<float*>(fx.v), 1));
else if (sizeof(cnn::real) == sizeof(double))
CUBLAS_CHECK(cublasDaxpy(cublas_handle, fx.d.size(), reinterpret_cast<double*>(kSCALAR_ONE), reinterpret_cast<double*>(xs[i]->v), 1, reinterpret_cast<double*>(fx.v), 1));
}
gpu::vconstant_multiplyx(fx.d.size(), 1. / num_args, fx.v, fx.v);
#else
auto res = *fx;
const unsigned remainder = num_args % 4;
switch (remainder) {
case 0: res.setZero(); break;
case 1: res = **xs[0]; break;
case 2: res = **xs[0] + **xs[1]; break;
case 3: res = **xs[0] + **xs[1] + **xs[2]; break;
}
for (unsigned i = remainder; i < num_args; i += 4)
res += **xs[i] + **xs[i+1] + **xs[i+2] + **xs[i+3];
res /= num_args;
#endif
}
/**
check if a 1/sz is allready computed and stored in GPU memory,
if so, use it. otherwise, need to compute it and put it in the back_off_mem
*/
#ifdef HAVE_CUDA
cnn::real* pointer_to_one_over_size(int sz, cnn::real * back_off_mem)
{
cnn::real *fdevptr = nullptr;
if (sz > MEM_PRE_ALLOCATED_CONSTS_NUMBERS + 1)
{
cnn::real nbr_samples = 1. / sz;
fdevptr = static_cast<cnn::real*>(back_off_mem);
CUDA_CHECK(cudaMemcpy(fdevptr, &nbr_samples, sizeof(cnn::real), cudaMemcpyHostToDevice));
}
else if (sz == 1)
fdevptr = kSCALAR_ONE;
else{
fdevptr = kSCALAR_ONE_OVER_INT[sz - 2];
}
return fdevptr;
}
#endif
void Average::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#if HAVE_CUDA
/// to speed-up, use pre-allocated const, instead of doing cpu to gpu memcpy of the const
cnn::real *fdevptr = pointer_to_one_over_size(xs.size(), static_cast<cnn::real*>(aux_mem));
if (sizeof(cnn::real) == sizeof(float))
CUBLAS_CHECK(cublasSaxpy(cublas_handle, fx.d.size(), reinterpret_cast<float*>(fdevptr), reinterpret_cast<float*>(dEdf.v), 1, reinterpret_cast<float*>(dEdxi.v), 1));
else if (sizeof(cnn::real) == sizeof(double))
CUBLAS_CHECK(cublasDaxpy(cublas_handle, fx.d.size(), reinterpret_cast<double*>(fdevptr), reinterpret_cast<double*>(dEdf.v), 1, reinterpret_cast<double*>(dEdxi.v), 1));
#else
*dEdxi += (*dEdf / xs.size());
#endif
};
void Sqrt::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
fx.m_device_id = xs[0]->m_device_id;
#ifdef HAVE_CUDA
throw std::runtime_error("Sqrt not yet implemented for CUDA");
#else
auto x = **xs[0];
(*fx) = x.cwiseSqrt();
#endif
}
void Sqrt::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#ifdef HAVE_CUDA
throw std::runtime_error("Sqrt not yet implemented for CUDA");
#else
*dEdxi += (*fx).binaryExpr(*dEdf, FSqrtBackward());
#endif
}
/*void Erf::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
#ifdef HAVE_CUDA
throw std::runtime_error("Erf not yet implemented for CUDA");
#else
auto x = **xs[0];
(*fx).array() = x.array().erf();
#endif
}
void Erf::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#ifdef HAVE_CUDA
throw std::runtime_error("Erf not yet implemented for CUDA");
#else
auto x = **xs[0];
*dEdxi += x.binaryExpr(*dEdf, scalar_erf_backward_op<cnn::real>());
#endif
}
*/
void Tanh::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
fx.m_device_id = xs[0]->m_device_id;
#if HAVE_CUDA
gpu::vtanh(fx.d.size(), xs[0]->v, fx.v);
#else
auto x = **xs[0];
(*fx).array() = x.array().tanh();
#endif
}
void Tanh::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#if HAVE_CUDA
gpu::vtanh_backward(fx.d.size(), fx.v, dEdf.v, dEdxi.v);
#else
*dEdxi += (*fx).binaryExpr(*dEdf, scalar_tanh_backward_op<cnn::real>());
#endif
}
void Square::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
fx.m_device_id = xs[0]->m_device_id;
#ifdef HAVE_CUDA
throw std::runtime_error("Square not yet implemented for CUDA");
#else
auto x = **xs[0];
(*fx).array() = x.array().square();
#endif
}
void Square::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#ifdef HAVE_CUDA
throw std::runtime_error("Square not yet implemented for CUDA");
#else
auto x = **xs[0];
*dEdxi += (*dEdf).cwiseProduct(x) * 2;
#endif
}
void Cube::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
fx.m_device_id = xs[0]->m_device_id;
#ifdef HAVE_CUDA
throw std::runtime_error("Square not yet implemented for CUDA");
#else
auto x = **xs[0];
(*fx).array() = x.array().cube();
#endif
}
void Cube::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#ifdef HAVE_CUDA
throw std::runtime_error("Cube not yet implemented for CUDA");
#else
auto x = **xs[0];
// *dEdxi += (*dEdf).cwiseProduct(x.cwiseProduct(x)) * 3;
(*dEdxi).array() += (*dEdf).array() * x.array().square() * 3;
#endif
}
void Exp::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
fx.m_device_id = xs[0]->m_device_id;
#if HAVE_CUDA
gpu::vexp(xs[0]->d.size(), xs[0]->v, fx.v);
#else
auto x = **xs[0];
*fx = x.array().exp();
#endif
}
void Exp::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#if HAVE_CUDA
gpu::vcwise_product_backward(xs[0]->d.size(), fx.v, dEdf.v, dEdxi.v);
#else
*dEdxi += (*dEdf).cwiseProduct(*fx);
#endif
}
/* eigen speciffunctions.h is not working
TO-DO: need to figure out why
void LogGamma::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
#ifdef HAVE_CUDA
throw std::runtime_error("LogGamma not yet implemented for CUDA");
#else
auto x = **xs[0];
*fx = x.array().lgamma();
#endif
}
void LogGamma::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#ifdef HAVE_CUDA
throw std::runtime_error("LogGamma not yet implemented for CUDA");
#else
auto x = **xs[0];
*dEdxi += x.binaryExpr(*dEdf, FLogGammaBackward());
#endif
}
*/
void Log::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
fx.m_device_id = xs[0]->m_device_id;
#if HAVE_CUDA
gpu::vlog(fx.d.size(), xs[0]->v, fx.v);
#else
auto x = **xs[0];
*fx = x.array().log();
#endif
}
void Log::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#if HAVE_CUDA
gpu::vlog_backward(fx.d.size(), xs[0]->v, dEdf.v, dEdxi.v);
#else
auto x = **xs[0];
*dEdxi += (*dEdf).cwiseQuotient(x);
#endif
}
void Concatenate::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
unsigned rows = 0;
fx.m_device_id = xs[0]->m_device_id;
for (auto x : xs) rows += x->d.rows();
// the following should use auxiliary memory
src_row_indices.resize(xs.size());
unsigned ind = 0;
unsigned cols = xs[0]->d.cols();
unsigned total_rows = 0;
for (auto x : xs) {
if (x->d.cols() != cols)
{
cerr << "columns need to the same for Concatenate " << endl;
abort();
}
total_rows += x->d.rows();
}
unsigned k = 0;
for (auto x : xs) {
src_row_indices[k++] = ind;
auto & xi = *x;
const unsigned rows = xi.d.rows();
#if HAVE_CUDA
/// relaxed to support multiple columns!
int stt = ind;
for (unsigned int k = 0; k < cols; k++) /// not efficient, unfortunately
{
CUDA_CHECK(cudaMemcpyAsync(&fx.v[stt], &xi.v[k * rows], sizeof(cnn::real) * rows, cudaMemcpyDeviceToDevice));
stt += total_rows;
}
#else
(*fx).middleRows(ind, rows) = *xi;
#endif
ind += rows;
}
}
void Concatenate::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(i < src_row_indices.size());
const unsigned total_rows = dEdf.d.rows();
const unsigned cols = dEdxi.d.cols();
const unsigned rows = dEdxi.d.rows();
const unsigned begin = src_row_indices[i];
#if HAVE_CUDA
/// not efficient unfortunately
for (size_t k = 0; k < cols; k++)
{
if (sizeof(cnn::real) == sizeof(float))
CUBLAS_CHECK(cublasSaxpy(cublas_handle, rows, reinterpret_cast<float*>(kSCALAR_ONE), reinterpret_cast<float*>(&dEdf.v[begin + k * total_rows]), 1, reinterpret_cast<float*>(&dEdxi.v[k * rows]), 1));
if (sizeof(cnn::real) == sizeof(double))
CUBLAS_CHECK(cublasDaxpy(cublas_handle, rows, reinterpret_cast<double*>(kSCALAR_ONE), reinterpret_cast<double*>(&dEdf.v[begin + k * total_rows]), 1, reinterpret_cast<double*>(&dEdxi.v[k * rows]), 1));
}
#else
*dEdxi += (*dEdf).middleRows(begin, rows);
#endif
}
void ConcatenateColumns::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
unsigned c = 0;
#ifdef HAVE_CUDA
vector<cudaStream_t> v_stream(xs.size());
for (unsigned i = 0; i < xs.size(); i++)
{
CUDA_CHECK(cudaStreamCreate(&v_stream[i]));
}
#endif
fx.m_device_id = xs[0]->m_device_id;
acc_col_size.clear();
for (unsigned i = 0; i < xs.size(); ++i) {
auto & xi = *xs[i];
const unsigned cols = xi.d.cols();
#if HAVE_CUDA
// CUBLAS matricies are column-major, so just copy the memory
const unsigned rows = xi.d.rows();
CUDA_CHECK(cudaMemcpyAsync(&fx.v[rows*c], xi.v, sizeof(cnn::real) * rows * cols, cudaMemcpyDeviceToDevice, v_stream[i]));
#else
(*fx).middleCols(c, cols) = **xs[i];
#endif
c += cols;
acc_col_size.push_back(c);
}
#ifdef HAVE_CUDA
CUDA_CHECK(cudaDeviceSynchronize());
for (unsigned i = 0; i < xs.size(); i++)
{
CUDA_CHECK(cudaStreamDestroy(v_stream[i]));
}
#endif
}
void ConcatenateColumns::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
unsigned* pp = static_cast<unsigned*>(aux_mem);
unsigned c = acc_col_size[i];
#if HAVE_CUDA
const unsigned rows = dEdxi.d.rows();
const unsigned cols = dEdxi.d.cols();
const unsigned begin = (c - cols)*rows;
if (sizeof(cnn::real) == sizeof(float))
CUBLAS_CHECK(cublasSaxpy(cublas_handle, rows * cols, reinterpret_cast<float*>(kSCALAR_ONE), reinterpret_cast<float*>(&dEdf.v[begin]), 1, reinterpret_cast<float*>(dEdxi.v), 1));
else if (sizeof(cnn::real) == sizeof(double))
CUBLAS_CHECK(cublasDaxpy(cublas_handle, rows * cols, reinterpret_cast<double*>(kSCALAR_ONE), reinterpret_cast<double*>(&dEdf.v[begin]), 1, reinterpret_cast<double*>(dEdxi.v), 1));
#else
auto dEdx = *dEdxi;
int d = dEdx.cols();
dEdx += (*dEdf).middleCols(c - d, d);
#endif
}
void PairwiseRankLoss::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
#if HAVE_CUDA
gpu::vpairwise_rank_loss(fx.d.size(), margin, xs[0]->v, xs[1]->v, fx.v);
#else
auto a = **xs[0];
auto b = **xs[1];
*fx = a.binaryExpr(b, FPairwiseRankLoss(margin));
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void PairwiseRankLoss::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#if HAVE_CUDA
gpu::vpairwise_rank_loss_backward(dEdf.d.size(), (i == 0), fx.v, dEdf.v, dEdxi.v);
#else
if (i == 0) {
*dEdxi -= (*fx).binaryExpr(*dEdf, FRectifyBackward());
} else {
*dEdxi += (*fx).binaryExpr(*dEdf, FRectifyBackward());
}
#endif
}
size_t Hinge::aux_storage_size() const {
return dim.size() * sizeof(cnn::real);
}
void Hinge::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 1);
fx.m_device_id = xs[0]->m_device_id;
#ifdef HAVE_CUDA
throw std::runtime_error("Hinge not yet implemented for CUDA");
#else
auto x = **xs[0];
const unsigned rows = x.rows();
cnn::real y = 0;
cnn::real* eloss = static_cast<cnn::real*>(aux_mem);
const cnn::real mlystar = margin - x(*pelement);
for (unsigned i = 0; i < rows; ++i) {
if (*pelement != i) {
eloss[i] = max<cnn::real>(0.f, mlystar + x(i));
y += eloss[i];
} else {
eloss[i] = 0;
}
}
fx.v[0] = y;
#endif
}
void Hinge::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(i == 0);
#ifdef HAVE_CUDA
throw std::runtime_error("Hinge not yet implemented for CUDA");
#else
if (fx.v[0]) { // there was some loss
const cnn::real d = dEdf.v[0];
const unsigned rows = dEdxi.d.rows();
const cnn::real* eloss = static_cast<const cnn::real*>(aux_mem);
unsigned tne = 0; // total number of errors
for (unsigned i = 0; i < rows; ++i)
if (eloss[i] > 0) {
(*dEdxi)(i) += d;
++tne;
}
(*dEdxi)(*pelement) -= d * tne;
}
#endif
}
void Identity::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
fx.d = xs[0]->d;
fx.v = xs[0]->v;
fx.m_device_id = xs[0]->m_device_id;
}
void Identity::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
*dEdxi += *dEdf;
}
void MaxPooling1D::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
cerr << "FIX IMPL5\n"; abort();
fx.m_device_id = xs[0]->m_device_id;
#if 0
assert(xs.size() == 1);
const Tensor& x = *xs.front();
const unsigned x_rows = x.rows();
assert(x.cols() == 1);
const unsigned fx_rows = x_rows / width;
ind.resize(fx_rows);
Tensor fx = Zero(Dim(fx_rows, 1));
for (unsigned i = 0; i < fx_rows; ++i) {
unsigned from = i * width;
unsigned to = from + width;
if (to > x_rows) to = x_rows;
cnn::real best = x(from, 0);
unsigned bestr = from;
for (unsigned r = from + 1; r < to; ++r) {
if (x(r, 0) > best) {
best = x(r,0);
bestr = r;
}
}
ind[i] = bestr;
fx(i, 0) = best;
}
return fx;
#endif
}
void MaxPooling1D::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
cerr << "FIX IMPL6\n"; abort();
#if 0
const Tensor& x = *xs.front();
const unsigned x_rows = x.rows();
Tensor dEdx = Zero(Dim(x_rows, 1));
const unsigned fx_rows = x_rows / width;
assert(fx_rows == ind.size());
assert(fx_rows == dEdf.rows());
for (unsigned i = 0; i < fx_rows; ++i)
dEdx(ind[i], 0) = dEdf(i, 0);
return dEdx;
#endif
}
void Softmax::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 1);
fx.m_device_id = xs[0]->m_device_id;
#if HAVE_CUDA
gpu::softmax(xs[0]->d.rows(), xs[0]->d.cols(), xs[0]->v, fx.v);
#else
softmax<cnn::real>(xs[0]->d.rows(), xs[0]->d.cols(), xs[0]->v, fx.v, true);
#endif
}
void Softmax::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#if HAVE_CUDA
gpu::softmax_backward(fx.d.rows(), fx.d.cols(), fx.v, dEdf.v, dEdxi.v);
#else
vector<cnn::real> off_diag_sum(fx.d.cols());
int rows = fx.d.rows();
#pragma omp parallel for
for (int k = 0; k < fx.d.cols(); k++)
{
off_diag_sum[k] = 0;
for (unsigned r = 0; r < rows; r++)
off_diag_sum[k] += fx.v[IDX2C(r, k, rows)] * dEdf.v[IDX2C(r, k, rows)];
/// row-element-wise multiplication
for (unsigned r = 0; r < rows; r++)
{
cnn::real d = dEdf.v[IDX2C(r, k, rows)];
cnn::real t = fx.v[IDX2C(r, k, rows)];
dEdxi.v[IDX2C(r, k, rows)] += (d - off_diag_sum[k]) * t;
}
}
#endif
}
/*
void PickNegLogSoftmax::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
if (xs[0]->d.cols() == 1) {
logz = (cnn::real*)fxs->allocate(sizeof(cnn::real)*fx.d.batch_elems());
#if HAVE_CUDA
if(pval) {
gpu::pnlsoftmax(xs[0]->d.size(), *pval, xs[0]->v, fx.v, logz);
} else {
// TODO: It'd be nice to have a kernel that did all batches at once
assert(pvals);
assert(pvals->size() == fx.d.batch_elems());
for(unsigned b = 0; b < pvals->size(); ++b)
gpu::pnlsoftmax(xs[0]->d.batch_size(), (*pvals)[b], xs[0]->batch_ptr(b), fx.v+b, logz+b);
}
#else
if(pval) {
auto x = **xs[0];
*logz = logsumexp(x);
fx.v[0] = *logz - x(*pval);
} else {
assert(pvals);
assert(pvals->size() == fx.d.batch_elems());
for(unsigned b = 0; b < pvals->size(); ++b) {
auto x = xs[0]->batch_matrix(b);
logz[b] = logsumexp(x);
fx.v[b] = logz[b] - x((*pvals)[b]);
}
}
#endif
} else {
throw std::runtime_error("PickNegLogSoftmax::forward not yet implemented for multiple columns");
}
}
there is probably a bug in using batch implementation
when runing on rnnlm2_cls, using pickenglogsoftmax actually get 0 PPL at epoch 4 and then crash, and that is impossible.
when switching back to logsoftmax and do pick operation later, the results look reasonable with training PPL decreased to 40~50 at epoch 9.
*/
/** comment the following out
void PickNegLogSoftmax::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
if (xs[0]->d.cols() == 1) {
#if HAVE_CUDA
if(pval) {
const auto elem = *pval;
gpu::pnlsoftmax_backward(dEdxi.d.size(), elem, xs[0]->v, dEdf.v, logz, dEdxi.v);
} else {
assert(pvals);
assert(pvals->size() == fx.d.batch_elems());
// TODO: Again, it would be nice to do this with a single kernel
for(unsigned b = 0; b < pvals->size(); ++b) {
const auto elem = (*pvals)[b];
gpu::pnlsoftmax_backward(dEdxi.d.batch_size(), elem, xs[0]->batch_ptr(b), dEdf.v+b, logz+b, dEdxi.batch_ptr(b));
}
}
#else
if(pval) {
const auto elem = *pval;
const cnn::real err = dEdf.v[0];
auto x = **xs[0];
// logz is computed in the forward pass and cached
*dEdxi += x.unaryExpr(FNegLogSoftmaxBackward(*logz, err));
//*dEdxi += x.unaryExpr(scalar_nlsoftmax_backward_op<cnn::real>(*logz, err));
(*dEdxi)(elem) -= err;
} else {
assert(pvals);
assert(pvals->size() == fx.d.batch_elems());
for(unsigned b = 0; b < pvals->size(); ++b) {
const auto elem = (*pvals)[b];
const cnn::real err = dEdf.v[b];
auto x = xs[0]->batch_matrix(b);
auto dEdxi_mat = dEdxi.batch_matrix(b);
dEdxi_mat += x.unaryExpr(FNegLogSoftmaxBackward(logz[b], err));
//dEdxi_mat += x.unaryExpr(scalar_nlsoftmax_backward_op<cnn::real>(logz[b], err));
dEdxi_mat(elem) -= err;
}
}
#endif
} else {
throw std::runtime_error("PickNegLogSoftmax::backward not yet implemented for multiple columns");
}
}
*/
size_t LogSoftmax::aux_storage_size() const {
/// save space for softmax and a vector of nutt
#ifdef HAVE_CUDA
return 0;
#else
int sz = dim.size() + dim.cols();
return sz* sizeof(cnn::real);
#endif
}
void LogSoftmax::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
#if HAVE_CUDA
gpu::logsoftmax(xs[0]->d.rows(), xs[0]->d.cols(), xs[0]->v, fx.v);
#else
logsoftmax<cnn::real>(xs[0]->d.rows(), xs[0]->d.cols(), xs[0]->v, fx.v, true);
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void LogSoftmax::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const
{
unsigned rows = dEdf.d.rows();
unsigned cols = dEdf.d.cols();
#if HAVE_CUDA
gpu::logsoftmax_backward(xs[0]->d.rows(), xs[0]->d.cols(), fx.v, dEdf.v, dEdxi.v);
#else
Tensor softmax(fx.d, static_cast<cnn::real*>(aux_mem)+cols, device_id);
cnn::real* off_diag_sum = static_cast<cnn::real*>(aux_mem);
(*softmax).array() = (*fx).array().exp();
#pragma omp parallel for
for (int k = 0; k < cols; k++)
{
off_diag_sum[k] = 0;
for (unsigned r = 0; r < rows; r ++)
off_diag_sum[k] += dEdf.v[IDX2C(r,k, rows)];
/// row-element-wise multiplication
for (unsigned r = 0; r < rows; r++)
{
softmax.v[IDX2C(r, k, rows)] *= off_diag_sum[k];
dEdxi.v[IDX2C(r, k, rows)] += (dEdf.v[IDX2C(r, k, rows)] - softmax.v[IDX2C(r, k, rows)]);
}
}
#endif
}
template <class T>
EIGEN_STRONG_INLINE cnn::real logsumexp(const T& x, const vector<unsigned>& denom) {
cnn::real m = x(denom[0],0);
for (auto i : denom) {
cnn::real r = x(i,0);
if (r > m) m = r;
}
cnn::real z = 0;
for (auto i : denom)
z += expf(x(i,0) - m);
return m + logf(z);
}
void RestrictedLogSoftmax::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
#ifdef HAVE_CUDA
throw std::runtime_error("RestrictedLogSoftmax not yet implemented for CUDA");
#else
// TODO create auxiliary mask with -infty's
// and do usual LogSoftmax stuff
assert(xs.size() == 1);
assert(denom.size() > 0);
auto x = **xs[0];
assert(x.cols() == 1);
const cnn::real logz = logsumexp(x, denom);
TensorTools::Constant(fx, -numeric_limits<cnn::real>::infinity());
for (auto i : denom)
(*fx)(i,0) = x(i,0) - logz;
if (denom.size() == 1) (*fx)(denom.front(), 0) = 0;
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void RestrictedLogSoftmax::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(i == 0);
#ifdef HAVE_CUDA
throw std::runtime_error("RestrictedLogSoftmax not yet implemented for CUDA");
#else
cnn::real z = 0;
for (auto ind : denom)
z += (*dEdf)(ind, 0);
for (auto ind : denom)
(*dEdxi)(ind, 0) += (*dEdf)(ind, 0) - expf((*fx)(ind, 0)) * z;
#endif
}
// x_1 is a vector
// y = (x_1)_{*pval}
void PickElement::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 1);
#if HAVE_CUDA
CUDA_CHECK(cudaMemcpyAsync(&fx.v[0], &xs[0]->v[*pval], sizeof(cnn::real), cudaMemcpyDeviceToDevice));
#else
auto x = **xs[0];
fx.v[0] = x(*pval);
#endif
fx.m_device_id = xs[0]->m_device_id;
}
// derivative is 0 in all dimensions except 1 for the selected element
void PickElement::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(i == 0);
#if HAVE_CUDA
if (sizeof(cnn::real) == sizeof(float))
CUBLAS_CHECK(cublasSaxpy(cublas_handle, 1, reinterpret_cast<float*>(kSCALAR_ONE), reinterpret_cast<float*>(dEdf.v), 1, reinterpret_cast<float*>(&dEdxi.v[*pval]), 1));
else if (sizeof(cnn::real) == sizeof(double))
CUBLAS_CHECK(cublasDaxpy(cublas_handle, 1, reinterpret_cast<double*>(kSCALAR_ONE), reinterpret_cast<double*>(dEdf.v), 1, reinterpret_cast<double*>(&dEdxi.v[*pval]), 1));
#else
(*dEdxi)(*pval) += dEdf.v[0];
#endif
}
// x_1 is a vector
// y = (x_1)[start:end]
// slice of vector from index start (inclusive) to index end (exclusive)
void PickRange::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 1);
auto x = **xs[0];
assert(x.cols() == 1);
assert(start >= 0);
assert(end <= x.rows());
assert(start < end);
assert(int(fx.d.rows()) == int(end - start));
#if HAVE_CUDA
CUDA_CHECK(cudaMemcpyAsync(&fx.v[0], &xs[0]->v[start], sizeof(cnn::real) * (end-start), cudaMemcpyDeviceToDevice));
#else
(*fx) = x.block(start, 0, end - start, 1);
#endif
fx.m_device_id = xs[0]->m_device_id;
}
// derivative is 0 in all dimensions except the slice range
void PickRange::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(i == 0);
assert(int(dEdf.d.rows()) == int(end - start));
assert(dEdf.d.cols() == 1);
#if HAVE_CUDA
if (sizeof(cnn::real) == sizeof(float))
CUBLAS_CHECK(cublasSaxpy(cublas_handle, end - start, reinterpret_cast<float*>(kSCALAR_ONE), reinterpret_cast<float*>(dEdf.v), 1, reinterpret_cast<float*>(&dEdxi.v[start]), 1));
else if (sizeof(cnn::real) == sizeof(double))
CUBLAS_CHECK(cublasDaxpy(cublas_handle, end - start, reinterpret_cast<double*>(kSCALAR_ONE), reinterpret_cast<double*>(dEdf.v), 1, reinterpret_cast<double*>(&dEdxi.v[start]), 1));
#else
(*dEdxi).block(start, 0, end - start, 1) += (*dEdf);
#endif
}
// x_1 is a matrix
// y = x_1[start_column: start_column + rows * (end_column - start_column)]
// (start_column inclusive, end_column exclusive)
void ColumnSlices::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 1);
auto x = **xs[0];
assert(x.cols() >= 1);
assert(start_column >= 0);
assert(rows <= x.rows());
assert(start_column < end_column);
assert(int(fx.d.rows()) == int(rows));
#if HAVE_CUDA
int start = start_column*rows;
CUDA_CHECK(cudaMemcpyAsync(&fx.v[0], &xs[0]->v[start], sizeof(cnn::real) * rows * (end_column - start_column), cudaMemcpyDeviceToDevice));
#else
(*fx) = x.block(0, start_column, rows, end_column - start_column);
#endif
fx.m_device_id = xs[0]->m_device_id;
}
// derivative is 0 in all dimensions except the slice range
void ColumnSlices::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(i == 0);
assert(int(dEdf.d.rows()) == int(rows));
assert(dEdf.d.cols() == end_column - start_column);
#if HAVE_CUDA
if (sizeof(cnn::real) == sizeof(float))
CUBLAS_CHECK(cublasSaxpy(cublas_handle, rows * (end_column - start_column), reinterpret_cast<float*>(kSCALAR_ONE), reinterpret_cast<float*>(dEdf.v), 1, reinterpret_cast<float*>(&dEdxi.v[rows * start_column]), 1));
else if (sizeof(cnn::real) == sizeof(double))
CUBLAS_CHECK(cublasDaxpy(cublas_handle, rows * (end_column - start_column), reinterpret_cast<double*>(kSCALAR_ONE), reinterpret_cast<double*>(dEdf.v), 1, reinterpret_cast<double*>(&dEdxi.v[rows * start_column]), 1));
#else
(*dEdxi).block(0, start_column, rows, end_column -start_column) += (*dEdf);
#endif
}
#if HAVE_CUDA
inline void CUDAMatrixMultiply(const Tensor& l, const Tensor& r, Tensor& y, const cnn::real* acc_scalar) {
// if (r.d.ndims() == 1 || r.d.cols() == 1) {
// CUBLAS_CHECK(cublasSgemv(cublas_handle, CUBLAS_OP_N, l.d.rows(), l.d.cols(),
// kSCALAR_ONE, l.v, l.d.rows(), r.v, 1, acc_scalar, y.v, 1));
// } else {
// CUBLAS_CHECK(cublasSgemm(cublas_handle, CUBLAS_OP_N, CUBLAS_OP_N,
// y.d.rows(), y.d.cols(), l.d.cols(),
// kSCALAR_ONE,
// l.v, l.d.rows(),
// r.v, r.d.rows(),
// acc_scalar, y.v, y.d.rows()));
// }
// If the left side has one batch, multiply by columns
// [x, z, b] = [x, y] * [y, z, b]
// -> [x, z*b] = [x, y], [y, z*b]
#ifdef USE_DOUBLE
CUBLAS_CHECK(cublasDgemm(cublas_handle, CUBLAS_OP_N, CUBLAS_OP_N,
y.d.rows(), y.d.cols(), l.d.cols(),
kSCALAR_ONE,
l.v, l.d.rows(),
r.v, r.d.rows(),
acc_scalar,
y.v, y.d.rows()));
#else
CUBLAS_CHECK(cublasSgemm(cublas_handle, CUBLAS_OP_N, CUBLAS_OP_N,
y.d.rows(), y.d.cols(), l.d.cols(),
kSCALAR_ONE,
l.v, l.d.rows(),
r.v, r.d.rows(),
acc_scalar, y.v, y.d.rows()));
#endif
}
#endif
void MatrixMultiply::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 2);
#if HAVE_CUDA
// fx = 0*fx + xs[0] * xs[1]
CUDAMatrixMultiply(*xs[0], *xs[1], fx, kSCALAR_ZERO);
#else
assert(fx.d.bd == 1);
// If the left side has one batch, multiply by columns
// [x, z, b] = [x, y] * [y, z, b]
// -> [x, z*b] = [x, y], [y, z*b]
fx.colbatch_matrix().noalias() = **xs[0] * xs[1]->colbatch_matrix();
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void MatrixMultiply::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(i < 2);
#if HAVE_CUDA
if (i == 0) {
#ifdef USE_DOUBLE
CUBLAS_CHECK(cublasDgemm(cublas_handle, CUBLAS_OP_N, CUBLAS_OP_T,
dEdxi.d.rows(), dEdxi.d.cols(), dEdf.d.cols(),
kSCALAR_ONE,
dEdf.v, dEdf.d.rows(),
xs[1]->v, xs[1]->d.rows(),
kSCALAR_ONE, dEdxi.v, dEdxi.d.rows()));
#else
CUBLAS_CHECK(cublasSgemm(cublas_handle, CUBLAS_OP_N, CUBLAS_OP_T,
dEdxi.d.rows(), dEdxi.d.cols(), dEdf.d.cols(),
kSCALAR_ONE,
dEdf.v, dEdf.d.rows(),
xs[1]->v, xs[1]->d.rows(),
kSCALAR_ONE, dEdxi.v, dEdxi.d.rows()));
#endif
}
else {
#ifdef USE_DOUBLE
CUBLAS_CHECK(cublasDgemm(cublas_handle, CUBLAS_OP_T, CUBLAS_OP_N,
dEdxi.d.rows(), dEdxi.d.cols(), xs[0]->d.rows(),
kSCALAR_ONE,
xs[0]->v, xs[0]->d.rows(),
dEdf.v, dEdf.d.rows(),
kSCALAR_ONE, dEdxi.v, dEdxi.d.rows()));
#else
CUBLAS_CHECK(cublasSgemm(cublas_handle, CUBLAS_OP_T, CUBLAS_OP_N,
dEdxi.d.rows(), dEdxi.d.cols(), xs[0]->d.rows(),
kSCALAR_ONE,
xs[0]->v, xs[0]->d.rows(),
dEdf.v, dEdf.d.rows(),
kSCALAR_ONE, dEdxi.v, dEdxi.d.rows()));
#endif
}
#else
if (i == 0) {
dEdxi.colbatch_matrix().noalias() += dEdf.colbatch_matrix() * xs[1]->colbatch_matrix().transpose();
} else {
dEdxi.colbatch_matrix().noalias() += xs[0]->colbatch_matrix().transpose() * dEdf.colbatch_matrix();
}
#endif
}
void CwiseQuotient::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 2);
#ifdef HAVE_CUDA
throw std::runtime_error("CwiseQuotient::forward not yet implemented for CUDA");
#else
auto x1 = **xs[0];
auto x2 = **xs[1];
*fx = x1.cwiseQuotient(x2);
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void CwiseQuotient::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(i < 2);
#ifdef HAVE_CUDA
throw std::runtime_error("CwiseQuotient::backward not yet implemented for CUDA");
#else
if (i == 0) {
auto x2 = **xs[1];
*dEdxi += (*dEdf).cwiseQuotient(x2);
} else { // i = 1
auto x1 = **xs[0];
auto x2 = **xs[1];
*dEdxi -= (*dEdf).cwiseQuotient(x2.cwiseProduct(x2)).cwiseProduct(x1);
}
#endif
}
void CwiseMultiply::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 2);
#if HAVE_CUDA
gpu::vcwise_product(fx.d.size(), xs[0]->v, xs[1]->v, fx.v);
#else
auto x1 = **xs[0];
auto x2 = **xs[1];
*fx = x1.cwiseProduct(x2);
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void CwiseMultiply::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(i < 2);
if (i == 0) {
#if HAVE_CUDA
gpu::vcwise_product_backward(fx.d.size(), dEdf.v, xs[1]->v, dEdxi.v);
#else
auto x2 = **xs[1];
*dEdxi += (*dEdf).cwiseProduct(x2);
#endif
} else {
#if HAVE_CUDA
gpu::vcwise_product_backward(fx.d.size(), dEdf.v, xs[0]->v, dEdxi.v);
#else
auto x1 = **xs[0];
*dEdxi += (*dEdf).cwiseProduct(x1);
#endif
}
}
void AffineTransform::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() % 2 == 1);
#if HAVE_CUDA
for (unsigned i = 1; i < xs.size(); i += 2)
// fx = (acc_sclar)*fx + xs[0] * xs[1]
CUDAMatrixMultiply(*xs[i], *xs[i + 1], fx, (i == 1) ? kSCALAR_ZERO : kSCALAR_ONE);
assert(fx.d.bd == 1);
assert(xs[0]->d.bd == 1);
if (sizeof(cnn::real) == sizeof(float))
CUBLAS_CHECK(cublasSaxpy(cublas_handle, fx.d.size(), reinterpret_cast<float*>(kSCALAR_ONE), reinterpret_cast<float*>(xs[0]->v), 1, reinterpret_cast<float*>(fx.v), 1));
else if (sizeof(cnn::real) == sizeof(double))
CUBLAS_CHECK(cublasDaxpy(cublas_handle, fx.d.size(), reinterpret_cast<double*>(kSCALAR_ONE), reinterpret_cast<double*>(xs[0]->v), 1, reinterpret_cast<double*>(fx.v), 1));
#else
assert(fx.d.bd == 1);
// Add, using broadcasting or not
fx.colbatch_matrix().noalias() = xs[0]->colbatch_matrix();
// Multiply
for (unsigned i = 1; i < xs.size(); i += 2) {
fx.colbatch_matrix().noalias() += **xs[i] * xs[i+1]->colbatch_matrix();
}
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void AffineTransform::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(i < xs.size());
if (i == 0) { // bias term
#if HAVE_CUDA
if (sizeof(cnn::real) == sizeof(float))
CUBLAS_CHECK(cublasSaxpy(cublas_handle, dEdxi.d.size(), reinterpret_cast<float*>(kSCALAR_ONE), reinterpret_cast<float*>(dEdf.v), 1, reinterpret_cast<float*>(dEdxi.v), 1));
else if (sizeof(cnn::real) == sizeof(double))
CUBLAS_CHECK(cublasDaxpy(cublas_handle, dEdxi.d.size(), reinterpret_cast<double*>(kSCALAR_ONE), reinterpret_cast<double*>(dEdf.v), 1, reinterpret_cast<double*>(dEdxi.v), 1));
#else
assert(fx.d.bd == 1);
// Add, using broadcasting or not
dEdxi.colbatch_matrix().noalias() += dEdf.colbatch_matrix();
#endif
} else if (i % 2 == 1) { // left argument of matrix multiply
#if HAVE_CUDA
#ifdef USE_DOUBLE
CUBLAS_CHECK(cublasDgemm(cublas_handle, CUBLAS_OP_N, CUBLAS_OP_T,
dEdxi.d.rows(), dEdxi.d.cols(), dEdf.d.cols(),
kSCALAR_ONE,
dEdf.v, dEdf.d.rows(),
xs[i + 1]->v, xs[i + 1]->d.rows(),
kSCALAR_ONE, dEdxi.v, dEdxi.d.rows()));
#else
CUBLAS_CHECK(cublasSgemm(cublas_handle, CUBLAS_OP_N, CUBLAS_OP_T,
dEdxi.d.rows(), dEdxi.d.cols(), dEdf.d.cols(),
kSCALAR_ONE,
dEdf.v, dEdf.d.rows(),
xs[i + 1]->v, xs[i + 1]->d.rows(),
kSCALAR_ONE, dEdxi.v, dEdxi.d.rows()));
#endif
#else
dEdxi.colbatch_matrix().noalias() += dEdf.colbatch_matrix() * xs[i+1]->colbatch_matrix().transpose();
#endif
} else { // right argument of matrix multiply
#if HAVE_CUDA
#ifdef USE_DOUBLE
CUBLAS_CHECK(cublasDgemm(cublas_handle, CUBLAS_OP_T, CUBLAS_OP_N,
dEdxi.d.rows(), dEdxi.d.cols(), xs[i - 1]->d.rows(),
kSCALAR_ONE,
xs[i - 1]->v, xs[i - 1]->d.rows(),
dEdf.v, xs[i - 1]->d.rows(),
kSCALAR_ONE, dEdxi.v, dEdxi.d.rows()));
#else
CUBLAS_CHECK(cublasSgemm(cublas_handle, CUBLAS_OP_T, CUBLAS_OP_N,
dEdxi.d.rows(), dEdxi.d.cols(), xs[i - 1]->d.rows(),
kSCALAR_ONE,
xs[i - 1]->v, xs[i - 1]->d.rows(),
dEdf.v, xs[i - 1]->d.rows(),
kSCALAR_ONE, dEdxi.v, dEdxi.d.rows()));
#endif
#else
dEdxi.colbatch_matrix().noalias() += (**xs[i-1]).transpose() * dEdf.colbatch_matrix();
#endif
}
}
void Negate::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 1);
#if HAVE_CUDA
gpu::vnegate(fx.d.size(), xs[0]->v, fx.v);
#else
auto x = **xs[0];
*fx = -x;
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void Negate::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(i == 0);
#if HAVE_CUDA
gpu::vnegate_backward(fx.d.size(), dEdf.v, dEdxi.v);
#else
*dEdxi -= *dEdf;
#endif
}
void Rectify::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 1);
#if HAVE_CUDA
gpu::vrelu(fx.d.size(), xs[0]->v, fx.v);
#else
auto x = **xs[0];
*fx = x.unaryExpr(FRectify());
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void Rectify::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#if HAVE_CUDA
gpu::vrelu_backward(fx.d.size(), fx.v, dEdf.v, dEdxi.v);
#else
*dEdxi += (*fx).binaryExpr(*dEdf, FRectifyBackward());
#endif
}
void ExponentialLinearUnits::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 1);
#if HAVE_CUDA
gpu::vexponential_linear_units(fx.d.size(), xs[0]->v, scale, fx.v);
#else
auto x = **xs[0];
*fx = x.unaryExpr(FExponentialLinearUnits(scale));
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void ExponentialLinearUnits::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#if HAVE_CUDA
gpu::vexponential_linear_units_backward(fx.d.size(), fx.v, dEdf.v, scale, dEdxi.v);
#else
*dEdxi += (*fx).binaryExpr(*dEdf, FExponentialLinearUnitsBackward(scale));
#endif
}
void HuberDistance::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 2);
#ifdef HAVE_CUDA
throw std::runtime_error("HuberDistance not yet implemented for CUDA");
#else
auto x = *xs[0];
auto y = *xs[1];
const FHuberForward fhf(d);
const size_t s = x.d.size();
cnn::real dist = 0;
for (size_t i = 0; i < s; ++i)
dist += fhf(x.v[i] - y.v[i]);
fx.v[0] = dist;
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void HuberDistance::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(i < 2);
#ifdef HAVE_CUDA
throw std::runtime_error("HuberDistance not yet implemented for CUDA");
#else
auto x = **xs[i];
auto y = **xs[1-i];
*dEdxi += (x - y).unaryExpr(FHuberBackward(d, dEdf.v[0]));
#endif
}
void L1Distance::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 2);
#ifdef HAVE_CUDA
throw std::runtime_error("L1Distance not yet implemented for CUDA");
#else
auto x = **xs[0];
auto y = **xs[1];
fx.v[0] = (x - y).lpNorm<1>();
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void L1Distance::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(i < 2);
#ifdef HAVE_CUDA
throw std::runtime_error("L1Distance not yet implemented for CUDA");
#else
auto x = **xs[i];
auto y = **xs[1-i];
*dEdxi += (x - y).unaryExpr(FL1Backward(dEdf.v[0]));
#endif
}
void PoissonRegressionLoss::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
#ifdef HAVE_CUDA
throw std::runtime_error("PoissonRegressionLoss not yet implemented for CUDA");
#else
const auto y = *pty;
const auto z = lgamma(y + 1);
const auto x = xs[0]->v[0];
fx.v[0] = expf(x) + z - y * x;
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void PoissonRegressionLoss::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#ifdef HAVE_CUDA
throw std::runtime_error("PoissonRegressionLoss not yet implemented for CUDA");
#else
const auto x = xs[0]->v[0];
const auto y = *pty;
auto& dEdx = dEdxi.v[0];
dEdx += expf(x) - y;
#endif
}
void SquaredEuclideanDistance::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 2);
#if HAVE_CUDA
gpu::sqeucdist(xs[0]->d.size(), xs[0]->v, xs[1]->v, fx.v);
#else
auto x1 = **xs[0];
auto x2 = **xs[1];
fx.v[0] = (x1 - x2).squaredNorm();
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void SquaredEuclideanDistance::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
assert(i < 2);
#if HAVE_CUDA
gpu::sqeucdist_backward(xs[0]->d.size(), dEdf.v, xs[0]->v, xs[1]->v, dEdxi.v, i);
#else
auto x1 = **xs[0];
auto x2 = **xs[1];
cnn::real scale = dEdf.v[0] * 2;
if (i == 1) scale = -scale;
*dEdxi += scale * (x1 - x2);
#endif
}
void LogisticSigmoid::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 1);
#if HAVE_CUDA
gpu::vlogistic(fx.d.size(), xs[0]->v, fx.v);
#else
auto x = **xs[0];
*fx = x.unaryExpr(scalar_logistic_sigmoid_op<cnn::real>());
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void LogisticSigmoid::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#if HAVE_CUDA
gpu::vlogistic_backward(dEdf.d.size(), fx.v, dEdf.v, dEdxi.v);
#else
*dEdxi += (*fx).binaryExpr(*dEdf, scalar_logistic_sigmoid_backward_op<cnn::real>());
#endif
}
void SoftSign::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 1);
#ifdef HAVE_CUDA
throw std::runtime_error("SoftSign not yet implemented for CUDA");
#else
auto x = **xs[0];
*fx = x.unaryExpr(FSoftSign());
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void SoftSign::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#ifdef HAVE_CUDA
throw std::runtime_error("SoftSign not yet implemented for CUDA");
#else
*dEdxi += (*fx).binaryExpr(*dEdf, FSoftSignBackward());
#endif
}
void BinaryLogLoss::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
#ifdef HAVE_CUDA
throw std::runtime_error("BinaryLogLoss not yet implemented for CUDA");
#else
auto x = *xs[0];
auto y = *xs[1];
FBinaryLogLoss bll;
const size_t s = x.d.size();
cnn::real dist = 0;
for (size_t i = 0; i < s; ++i)
dist += bll(x.v[i], y.v[i]);
fx.v[0] = dist;
#endif
fx.m_device_id = xs[0]->m_device_id;
}
void BinaryLogLoss::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
#ifdef HAVE_CUDA
throw std::runtime_error("BinaryLogLoss not yet implemented for CUDA");
#else
*dEdxi += (**xs[i]).binaryExpr(**xs[1-i], FBinaryLogLossBackward(dEdf.v[0]));
#endif
}
string Zeroes::as_string(const vector<string>& arg_names) const {
ostringstream s;
s << "zeroes(" << dim << ')';
return s.str();
}
Dim Zeroes::dim_forward(const vector<Dim>& xs) const {
return dim;
}
void Zeroes::forward_impl(const vector<const Tensor*>& xs, Tensor& fx) const {
assert(xs.size() == 0);
if (fx.m_device_id < 0)
memset(fx.v, 0, dim.size() * sizeof(cnn::real));
else{
#if HAVE_CUDA
cudaMemsetAsync(fx.v, 0, dim.size() * sizeof(cnn::real));
#else
memset(fx.v, 0, dim.size() * sizeof(cnn::real));
#endif
}
fx.m_device_id = xs[0]->m_device_id;
}
void Zeroes::backward_impl(const vector<const Tensor*>& xs,
const Tensor& fx,
const Tensor& dEdf,
unsigned i,
Tensor& dEdxi) const {
throw std::runtime_error("Called backward() on an arity 0 node");
}
} // namespace cnn
| 33.127517
| 224
| 0.593236
|
kaishengyao
|
918d6a4d650f78d1c5af8bccf9b6525406a8c969
| 2,056
|
hpp
|
C++
|
include/DREAM/Equations/Fluid/IonSpeciesTransientTerm.hpp
|
chalmersplasmatheory/DREAM
|
715637ada94f5e35db16f23c2fd49bb7401f4a27
|
[
"MIT"
] | 12
|
2020-09-07T11:19:10.000Z
|
2022-02-17T17:40:19.000Z
|
include/DREAM/Equations/Fluid/IonSpeciesTransientTerm.hpp
|
chalmersplasmatheory/DREAM
|
715637ada94f5e35db16f23c2fd49bb7401f4a27
|
[
"MIT"
] | 110
|
2020-09-02T15:29:24.000Z
|
2022-03-09T09:50:01.000Z
|
include/DREAM/Equations/Fluid/IonSpeciesTransientTerm.hpp
|
chalmersplasmatheory/DREAM
|
715637ada94f5e35db16f23c2fd49bb7401f4a27
|
[
"MIT"
] | 3
|
2021-05-21T13:24:31.000Z
|
2022-02-11T14:43:12.000Z
|
#ifndef _DREAM_EQUATION_FLUID_ION_SPECIES_TRANSIENT_TERM_HPP
#define _DREAM_EQUATION_FLUID_ION_SPECIES_TRANSIENT_TERM_HPP
/**
* Implementation of an equation term representing the
* (backward euler) time derivative on an ion species
* with index iz. (which can be scaled using scalefactor)
*/
#include "FVM/Equation/EquationTerm.hpp"
#include "FVM/Grid/Grid.hpp"
#include "FVM/UnknownQuantityHandler.hpp"
namespace DREAM{
class IonSpeciesTransientTerm : public FVM::EquationTerm {
private:
const len_t unknownId;
len_t iz;
real_t scaleFactor;
real_t dt;
real_t *xPrev;
public:
IonSpeciesTransientTerm(FVM::Grid *g, len_t iz, const len_t id, real_t scaleFactor=1.0)
: FVM::EquationTerm(g), unknownId(id), iz(iz), scaleFactor(scaleFactor){}
virtual len_t GetNumberOfNonZerosPerRow() const override { return 1; }
virtual len_t GetNumberOfNonZerosPerRow_jac() const override { return 1; }
virtual void Rebuild(const real_t, const real_t dt, FVM::UnknownQuantityHandler *u) override {
this->dt = dt;
this->xPrev = u->GetUnknownDataPrevious(this->unknownId);
}
virtual bool SetJacobianBlock(const len_t uqtyId, const len_t derivId, FVM::Matrix *jac, const real_t*) override {
if(uqtyId==derivId)
SetMatrixElements(jac, nullptr);
return (uqtyId==derivId);
}
virtual void SetMatrixElements(FVM::Matrix *mat, real_t *rhs) override {
for(len_t ir=0; ir<nr; ir++)
mat->SetElement(iz*nr+ir,iz*nr+ir,scaleFactor/dt);
if(rhs!=nullptr)
for(len_t ir=0; ir<nr; ir++)
rhs[iz*nr+ir] -= scaleFactor/dt;
}
virtual void SetVectorElements(real_t *vec, const real_t *xi) override {
for(len_t ir=0; ir<nr; ir++)
vec[iz*nr+ir] += scaleFactor*(xi[iz*nr+ir]-xPrev[iz*nr+ir])/dt;
}
};
}
#endif/*_DREAM_EQUATION_FLUID_ION_SPECIES_TRANSIENT_TERM_HPP*/
| 39.538462
| 122
| 0.646401
|
chalmersplasmatheory
|
9190e35ac7cfa37484b1cf23e47cf1fc419812e9
| 9,819
|
hpp
|
C++
|
src/Shay/Shay.hpp
|
MajorArkwolf/stonks
|
5671f7811f19af33450e5fd07ab61c700f71ee69
|
[
"0BSD"
] | null | null | null |
src/Shay/Shay.hpp
|
MajorArkwolf/stonks
|
5671f7811f19af33450e5fd07ab61c700f71ee69
|
[
"0BSD"
] | null | null | null |
src/Shay/Shay.hpp
|
MajorArkwolf/stonks
|
5671f7811f19af33450e5fd07ab61c700f71ee69
|
[
"0BSD"
] | null | null | null |
#pragma once
#include <time.h>
#include <SDL2/SDL.h>
#include "Camera.hpp"
#include "ObjLoader/ObjLoader.hpp"
#include "Stonk/BaseState.hpp"
#include "TexturedPolygons.hpp"
/**
* @namespace Shay
* @brief The global Shay namespace
*/
namespace Shay {
/**
* @brief A shay enum, no one knows
*/
enum ShayAxis : GLuint { XY = 0, XZ, YZ, YZ_FLIP, XY_FLIP };
/**
* @brief Enum list for all texture types
*/
enum ShayTexture : GLuint {
GRASS = 0,
GRASS_2,
GRASS_HILL,
PAVEMENT,
PAVEMENT_TOP,
PAVEMENTSIDE_LEFT,
PAVEMENTSIDE_RIGHT,
PAVEMENTSIDE_TOP,
PAVEMENT_CORNER_1,
PAVEMENT_CORNER_2,
PAVEMENT_FLIP,
PAVEMENT_TOP_FLIP,
PAVEMENT_16,
DOORPAVE_1,
WALL_BRICK_YZ,
WALL_BRICK_XY,
WALL_BRICK_XY_87WIDTH,
WALL_BRICK_GAP_YZ,
WALL_BRICK_GAP2_YZ,
WALL_BRICK_USD_YZ,
WALL_BRICK_XY_END,
WALL_BRICK_YZ_END,
WALL_GAP_1,
WALL_BRICK_3_4,
SHADOW_BRICK,
WALL_BRICK_SEC_SIGN,
WINDOWPOST_CHANC_FRONT,
WINDOWPOST_CHANC_RIGHT,
WINDOWPOST_CHANC_LEFT,
WINDOWLEDGE_CHANC_FRONT,
WINDOWLEDGE_CHANC_TOP,
WINDOWPOST_PHYSSCI_FRONT,
WINDOWPOST_PHYSSCI_RIGHT,
WINDOWPOST_PHYSSCI_LEFT,
WINDOWPOST_LIB_FRONT,
WINDOWPOST_LIB_LEFT,
WINDOWPOST_LIB_RIGHT,
DOOR_POST_SECURITY,
WINDOWLEDGE_PS_FRONT,
WINDOWLEDGE_PS_TOP,
WINDOWLEDGE_PS_BOTT,
WINDOWLEDGE_LIB_A,
WINDOWLEDGE_LIB_B,
WINDOWLEDGE_LIB_TOP_A,
WINDOWLEDGE_LIB_TOP_B,
WINDOW_LEDGE_END_1,
WINDOW_LEDGE_END_2,
MAIN_POST,
MAIN_POST_2,
DOOR_POST_CHANC,
DOOR_SIDEPOST_CHANC,
DOOR_POST_LIB,
PURPLE_POST,
PURPLE_POSTSIDE,
RED_POST,
RED_POSTSIDE,
ROOF_TOP,
ROOF_TOP_LIB,
ROOF_PLANKS,
ROOF_BEAM_1,
ROOF_PLANKS_2,
ROOF_BEAM_2,
BELOW_ROOF_FILL,
ROOF_BEAM_3,
ROOF_BEAM_4,
ROOF_BEAM_3_TOP,
KBLT,
KBLT_EDGE,
KBLT_EDGE_2,
KBLT_EDGE_CORNER,
KBLT_SIDE_1,
KBLT_SIDE_2,
NEXUS_SIGN,
NEXUS_SIDE,
SECURITY_SIGN,
SECURITY_SIGN_2,
SIGN_1,
SIGN_1_SIDE_1,
SIGN_1_SIDE_2,
SIGN_2,
SIGN_2_SIDE,
PSC_SIGN,
PSC_SIGN_2,
CO_SIGN,
STA_TRAVEL,
STA_TRAVEL_EDGE,
STA_TRAVEL_BRACKET,
STA_TRAVEL_2,
STA_TRAVEL_BOTTOM,
TOILET_MEN,
TOILET_WOMEN,
GS_SIGN,
GS_SIGN_2,
GS_SIGN_EDGE,
MAP_2,
GLASS_BOARD,
GLASS_BOARD_2,
GLASS_BOARD_3,
GLASS_B_SIDE,
RUSTY_MAN,
NO_SMOKE_SIGN,
CARPET,
DRINKS_SIDE,
DRINKS_TOP,
DRINKS_EDGE,
DRINKS_SIDE_2,
COKE_MACHINE,
COFFEE_MACHINE,
SWEET_MACHINE,
MACHINE_SIDES,
MACHINE_SIDES_2,
Textures,
TELEPHONE_BACK,
TELEPHONE_FRONT,
TELEPHONE_SIDE_1,
TELEPHONE_FRONT_2,
TELEPHONE_MAIN_SIDE,
TELEPHONE_TOP_1,
TELEPHONE_SIDE_2,
TELEPHONE_TOP_2,
TELEPHONE_BOTTOM,
TELEPHONE_FILL,
TELEPHONE_FRONT_3,
STEPS_LIBRARY,
STEPS_LIBRARY_TOP,
STEP_PAVING_1,
STEP_EDGE,
WINDOW_1,
WINDOW_2,
WINDOW_3,
WINDOW_4,
WINDOW_5,
WINDOW_6,
WINDOW_7,
WINDOW_8,
WINDOW_9,
WINDOW_10,
WINDOW_11,
WINDOW_12,
WINDOW_13,
WINDOW_14,
WINDOW_14B,
WINDOW_15,
WINDOW_16,
WINDOW_17,
WINDOW_2B,
WINDOW_2C,
WINDOW_2US,
WINDOW_3B,
WINDOW_2USB,
WINDOW_LIB_1,
WINDOW_LIB_1A,
WINDOW_LIB_1B,
WINDOW_LIB_1C,
WINDOW_LIB_US_A,
WINDOW_LIB_US_B,
WINDOW_LIB_DOOR_1,
WINDOW_LIB_DOOR_2,
WINDOW_LIB_LONG,
ENTRANCE,
ENTRANCE_2,
EXIT_EAST,
EXIT_WEST,
CHANC_DOOR_1,
CHANC_DOOR_2,
WINDOW_2D,
WINDOW_2E,
WINDOW_1B,
STEP_WINDOW,
ABOVE_WINDOW_BLOCK,
ABOVE_WINDOW_BLOCK_2,
ABOVE_WINDOW_BLOCK_3,
ABOVE_WINDOW_EDGE_3B,
ABOVE_WINDOW_BLOCK_XY_3,
ABOVE_LIB,
ABOVE_UNDER_POSTS,
ABOVE_UNDER_POSTS_2,
ABOVE_WINDOW_UNDER_LIB,
ABOVE_WINDOW_BLOCK_CHANC,
ABOVE_WINDOW_EDGE_3B_LIB,
ABOVE_WINDOW_EDGE_4B_LIB,
ABOVE_UNDER_4B,
ABOVE_CHANC_TEXT,
ABOVE_CHANC_TEXT_2,
ABOVE_PHYS_SCI_TEXT,
ABOVE_CHANC_TEXT_3,
ABOVE_LIB_TEXT,
ABOVE_LIB_TEXT_2,
ABOVE_TICKETS_TEXT,
ABOVE_CHANC_EDGE,
TOILET_DOOR_TOP,
LIGHT,
LIGHT_SUPPORT,
LIGHT_SUPPORT_2,
BENCH_TOP,
BENCH_SIDE,
BENCH_SIDE_2,
BENCH_EDGE,
BENCH_EDGE_TOP,
BENCH_EDGE_SIDE,
BENCH_EDGE_TOP_2,
BENCH_EDGE_2,
BENCH_EDGE_3,
TICKET_COUNTER_TOP,
TICKET_COUNTER_EDGE,
TICKET_COUNTER_EDGE_2,
TICKET_COUNTER_EDGE_3,
TICKET_LEDGE,
TICKET_LEDGE_EDGE,
TICKET_LEDGE_EDGE_2,
WALL_BRICK_STEPS_TOP,
WALL_BRICK_STEPS,
WALL_BRICK_STEPS_COVER,
WALL_BRICK_STEPS_EDGE,
WALL_BRICK_STEPS_EDGE_2,
DRAINPIPE,
COUNTER_TOP,
COUNTER_SIDE,
MAP,
WELCOME,
EXIT,
NO_EXIT,
};
/**
* @class ShaysWorld
* @brief The ultimate Shay class used to handle all others
*/
class ShaysWorld : public BaseState {
public:
GLfloat stepIncrement = 0.0f;
GLfloat angleIncrement = 0.0f;
int frameCount = 0;
clock_t lastClock = {};
/// Toggle for displaying on screen map
bool DisplayMap = false;
/// Toggle for displaying the welcome screen
bool DisplayWelcome = true;
/// Toggle for displaying the exit screen
bool DisplayExit = false;
/// Toggle for displaying all lights
bool lightsOn = true;
/// Toggle for displaying ECL
bool displayECL = true;
/// Toggle for displaying the debugMenu
bool displayDebug = true;
/// Toggle for drawing 3d axis
bool shouldDrawAxis = false;
int portalSpinAngle = 0;
GLfloat step = 0.0f;
GLfloat step2 = 0.0f;
GLfloat stepLength = 0.0f;
GLUquadricObj *glu_cylinder = nullptr;
std::vector<Model> modelList;
/**
* @brief Camera object
*/
Camera cam = {};
/**
* @brief Textured polygon object
*/
TexturedPolygons tp = {};
GLfloat light_position[4];
GLfloat light_position1[4];
ShaysWorld();
static auto get() -> ShaysWorld &;
auto teleportToAkuma() -> void;
auto hardInit() -> void;
auto softInit() -> void;
auto handleInput(SDL_Event &event) -> void;
auto unInit() -> void;
auto handleKeyEvents(SDL_Event &event) -> void;
auto handleMouseEvents(SDL_Event &event) -> void;
auto DisplaySigns() -> void;
auto drawAxis(float x, float y, float z, float length) -> void;
void drawSolidCube(float scale);
void displayPentagram(void);
void displayTavern();
void DisplayDebugMenu();
void display();
void update(double dt);
void DrawBackdrop();
void DisplayAboveWindowBlock();
void DisplayBench();
void DisplayBricks();
void DisplayChancPosts();
void DisplayCylinders();
void DisplayDoorPaving();
void DisplayDoorPosts();
void DisplayEntranceSteps();
void DisplayTavSteps();
void DisplayExtras();
void DisplayGrass();
void DisplayLargerTextures();
void DisplayLibraryPosts();
void DisplayMainPosts();
void DisplayPavement();
void DisplayPhysSciPosts();
void DisplayPurplePosts();
void DisplayRedPosts();
void DisplayRoof();
void DisplayStepBricks();
void DisplayTavStepBricks();
void DisplayLights();
void CreateTextureList();
void DrawGrass();
void DrawChancPosts();
void DrawDoorPosts();
void DrawPurplePosts();
void DrawRedPosts();
void DrawMainPosts();
void DrawAboveWindowBlock();
void DrawDoorPaving();
void DrawPhysSciPosts();
void DrawLibraryPosts();
void DrawBricks();
void DrawPavement();
void DrawExtras();
void DrawRoof();
void DrawEntranceSteps();
void DrawTavSteps();
void DrawLargerTextures();
void DrawLights();
void DrawBench();
void DrawCylinders();
void DrawAngledRoofBeam(GLuint listNo, GLfloat x, GLfloat y, GLfloat z,
GLfloat beamSize);
void DrawAngledRoofBeam2(GLuint listNo, GLfloat x, GLfloat y, GLfloat z,
GLfloat beamSize);
void DrawStepBricks();
void DrawTavStepBricks();
void DrawMapExit();
void IncrementFrameCount();
void CreateTextures();
void CreateBoundingBoxes();
void CreatePostBoundingBoxes();
void CreatePlains();
auto getCamPtr() -> Shay::Camera *;
};
}
| 21.771619
| 80
| 0.571749
|
MajorArkwolf
|
9191ae109f05d86c4a9677efb3a038cdebeb4c0b
| 1,266
|
cpp
|
C++
|
cmake/tests/pthread_affinity_np.cpp
|
akemp/hpx
|
1ddf7282e322c30d82f2be044071aed14807ebe1
|
[
"BSL-1.0"
] | null | null | null |
cmake/tests/pthread_affinity_np.cpp
|
akemp/hpx
|
1ddf7282e322c30d82f2be044071aed14807ebe1
|
[
"BSL-1.0"
] | null | null | null |
cmake/tests/pthread_affinity_np.cpp
|
akemp/hpx
|
1ddf7282e322c30d82f2be044071aed14807ebe1
|
[
"BSL-1.0"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2011 Bryce Lelbach
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
////////////////////////////////////////////////////////////////////////////////
#include <pthread.h>
#include <boost/detail/lightweight_test.hpp>
// Based on the example in pthread_setaffinity(3).
int main()
{
int s;
cpu_set_t cpuset;
pthread_t thread;
thread = pthread_self();
// Set affinity mask to include CPUs 0 to 7 (if available - otherwise, uses
// 0 to N where n is the number of cores on the machine.
CPU_ZERO(&cpuset);
for (int j = 0; j < 8; ++j)
CPU_SET(j, &cpuset);
BOOST_TEST_EQ(pthread_setaffinity_np(thread, sizeof(cpu_set_t), &cpuset), 0);
// Check the actual affinity mask assigned to the thread.
BOOST_TEST_EQ(pthread_getaffinity_np(thread, sizeof(cpu_set_t), &cpuset), 0);
std::cout << "set returned by pthread_getaffinity_np() contained:\n";
for (int j = 0; j < CPU_SETSIZE; ++j)
if (CPU_ISSET(j, &cpuset))
std::cout << "CPU" << j << "\n";
return boost::report_errors();
}
| 30.878049
| 81
| 0.57425
|
akemp
|
9191d00a83bf0157b47fd6054fd9a31f2bf7eeb4
| 6,015
|
cpp
|
C++
|
Source/Api/Vulkan/PipelineLayout.cpp
|
Filippo-BSW/AdHoc
|
2559fa6f563283af24ae1da26b4b9164c8206503
|
[
"MIT"
] | null | null | null |
Source/Api/Vulkan/PipelineLayout.cpp
|
Filippo-BSW/AdHoc
|
2559fa6f563283af24ae1da26b4b9164c8206503
|
[
"MIT"
] | null | null | null |
Source/Api/Vulkan/PipelineLayout.cpp
|
Filippo-BSW/AdHoc
|
2559fa6f563283af24ae1da26b4b9164c8206503
|
[
"MIT"
] | null | null | null |
// *********************************************************************************
// MIT License
//
// Copyright (c) 2021 Filippo-BSW
//
// 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 "PipelineLayout.hpp"
#include "Context.hpp"
#include "Initializers.hpp"
namespace adh {
namespace vk {
PipelineLayout::PipelineLayout() noexcept : m_PipelineLayout{ VK_NULL_HANDLE } {
}
PipelineLayout::PipelineLayout(PipelineLayout&& rhs) noexcept {
MoveConstruct(Move(rhs));
}
PipelineLayout& PipelineLayout::operator=(PipelineLayout&& rhs) noexcept {
Clear();
MoveConstruct(Move(rhs));
return *this;
}
PipelineLayout::~PipelineLayout() {
Clear();
}
void PipelineLayout::Create() ADH_NOEXCEPT {
VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo{
initializers::PipelineLayoutCreateInfo(
static_cast<std::uint32_t>(m_DescriptorSetLayout.GetSize()),
m_DescriptorSetLayout.GetData(),
static_cast<std::uint32_t>(m_PushConstants.GetSize()),
m_PushConstants.GetData())
};
ADH_THROW(vkCreatePipelineLayout(Context::Get()->GetDevice(), &pipelineLayoutCreateInfo, nullptr, &m_PipelineLayout) == VK_SUCCESS,
"Failed to create pipeline layout!");
}
void PipelineLayout::Destroy() noexcept {
Clear();
}
void PipelineLayout::AddBinding(std::uint32_t binding,
VkDescriptorType type,
std::uint32_t count,
VkShaderStageFlags shaderStage,
const VkSampler* immutableSampler) {
m_LayoutBindings.EmplaceBack(initializers::DescriptorSetLayoutBinding(binding, type, count, shaderStage, immutableSampler));
}
void PipelineLayout::AddPushConstant(VkShaderStageFlags shaderStage, std::uint32_t size, std::uint32_t offset) {
m_PushConstants.EmplaceBack(initializers::PushConstantRange(shaderStage, offset, size));
}
void PipelineLayout::CreateSet() ADH_NOEXCEPT {
auto layoutCreateInfo{ initializers::DescriptorSetLayoutCreateInfo(m_LayoutBindings.GetData(),
static_cast<std::uint32_t>(m_LayoutBindings.GetSize())) };
auto& temp{ m_DescriptorSetLayout.EmplaceBack() };
ADH_THROW(vkCreateDescriptorSetLayout(Context::Get()->GetDevice(), &layoutCreateInfo, nullptr, &temp) == VK_SUCCESS,
"Failed to create descriptor set layout!");
m_LayoutBindings.Clear();
}
VkPipelineLayout PipelineLayout::GetPipelineLayout() noexcept {
return m_PipelineLayout;
}
const VkPipelineLayout PipelineLayout::GetPipelineLayout() const noexcept {
return m_PipelineLayout;
}
Array<VkDescriptorSetLayout>& PipelineLayout::GetSetLayout() noexcept {
return m_DescriptorSetLayout;
}
const Array<VkDescriptorSetLayout>& PipelineLayout::GetSetLayout() const noexcept {
return m_DescriptorSetLayout;
}
VkPushConstantRange* PipelineLayout::GetPushConstant() noexcept {
return m_PushConstants.GetData();
}
const VkPushConstantRange* PipelineLayout::GetPushConstant() const noexcept {
return m_PushConstants.GetData();
}
PipelineLayout::operator VkPipelineLayout() {
return m_PipelineLayout;
}
PipelineLayout::operator const VkPipelineLayout() const {
return m_PipelineLayout;
}
void PipelineLayout::MoveConstruct(PipelineLayout&& rhs) noexcept {
m_LayoutBindings = Move(rhs.m_LayoutBindings);
m_DescriptorSetLayout = Move(rhs.m_DescriptorSetLayout);
m_PipelineLayout = rhs.m_PipelineLayout;
rhs.m_PipelineLayout = VK_NULL_HANDLE;
}
void PipelineLayout::Clear() noexcept {
auto device{ Context::Get()->GetDevice() };
for (std::size_t i{}; i != m_DescriptorSetLayout.GetSize(); ++i) {
vkDestroyDescriptorSetLayout(device, m_DescriptorSetLayout[i], nullptr);
m_DescriptorSetLayout[i] = VK_NULL_HANDLE;
}
if (m_PipelineLayout != VK_NULL_HANDLE) {
vkDestroyPipelineLayout(device, m_PipelineLayout, nullptr);
}
m_LayoutBindings.Clear();
m_DescriptorSetLayout.Clear();
m_PushConstants.Clear();
m_PipelineLayout = VK_NULL_HANDLE;
}
} // namespace vk
} // namespace adh
| 42.062937
| 143
| 0.615129
|
Filippo-BSW
|
9197dcdd7db83b3ebcb993601323afe1286da0fc
| 5,169
|
cpp
|
C++
|
src/BamToFastq/main.cpp
|
BeneKenobi/ngs-bits
|
cf849deb1c80e87b734d748f37f5878536277386
|
[
"MIT"
] | 85
|
2016-04-26T17:24:20.000Z
|
2022-03-11T12:33:39.000Z
|
src/BamToFastq/main.cpp
|
BeneKenobi/ngs-bits
|
cf849deb1c80e87b734d748f37f5878536277386
|
[
"MIT"
] | 104
|
2016-08-09T22:18:32.000Z
|
2022-03-31T12:39:12.000Z
|
src/BamToFastq/main.cpp
|
BeneKenobi/ngs-bits
|
cf849deb1c80e87b734d748f37f5878536277386
|
[
"MIT"
] | 28
|
2016-05-10T14:34:20.000Z
|
2021-10-14T07:22:39.000Z
|
#include "ToolBase.h"
#include "FastqFileStream.h"
#include "NGSHelper.h"
#include "Helper.h"
#include <QThreadPool>
#include "OutputWorker.h"
class ConcreteTool
: public ToolBase
{
Q_OBJECT
public:
ConcreteTool(int& argc, char *argv[])
: ToolBase(argc, argv)
{
}
virtual void setup()
{
setDescription("Converts a coordinate-sorted BAM file to FASTQ files (paired-end only).");
addInfile("in", "Input BAM/CRAM file.", false, true);
addOutfile("out1", "Read 1 output FASTQ.GZ file.", false);
addOutfile("out2", "Read 2 output FASTQ.GZ file.", false);
//optional
addString("reg", "Export only reads in the given region. Format: chr:start-end.", true);
addFlag("remove_duplicates", "Does not export duplicate reads into the FASTQ file.");
addInt("compression_level", "Output FASTQ compression level from 1 (fastest) to 9 (best compression).", true, 1);
addInt("write_buffer_size", "Output write buffer size (number of FASTQ entry pairs).", true, 100);
addInfile("ref", "Reference genome for CRAM support (mandatory if CRAM is used).", true);
changeLog(2020, 11, 27, "Added CRAM support.");
changeLog(2020, 5, 29, "Massive speed-up by writing in background. Added 'compression_level' parameter.");
changeLog(2020, 3, 21, "Added 'reg' parameter.");
}
static void alignmentToFastq(const QSharedPointer<BamAlignment>& al, FastqEntry& e)
{
e.header = "@" + al->name();
e.bases = al->bases();
e.header2 = "+";
e.qualities = al->qualities();
if (al->isReverseStrand())
{
e.bases.reverseComplement();
std::reverse(e.qualities.begin(), e.qualities.end());
}
}
virtual void main()
{
//init
QTime timer;
timer.start();
QTextStream out(stdout);
BamReader reader(getInfile("in"), getInfile("ref"));
QString reg = getString("reg");
if (reg!="")
{
BedLine region = BedLine::fromString(reg);
if (!region.isValid())
{
THROW(CommandLineParsingException, "Given region '" + reg + "' is not valid!");
}
reader.setRegion(region.chr(), region.start(), region.end());
}
bool remove_duplicates = getFlag("remove_duplicates");
int write_buffer_size = getInt("write_buffer_size");
int compression_level = getInt("compression_level");
//create background FASTQ writer
ReadPairPool pair_pool(write_buffer_size);
QThreadPool analysis_pool;
analysis_pool.setMaxThreadCount(1);
OutputWorker* output_worker = new OutputWorker(pair_pool, getOutfile("out1"), getOutfile("out2"), compression_level);
analysis_pool.start(output_worker);
long long c_unpaired = 0;
long long c_paired = 0;
long long c_duplicates = 0;
int max_cached = 0;
//iterate through reads
QHash<QByteArray, QSharedPointer<BamAlignment>> al_cache;
QSharedPointer<BamAlignment> al = QSharedPointer<BamAlignment>(new BamAlignment());
while (true)
{
bool ok = reader.getNextAlignment(*al);
if (!ok) break;
//out << al.name() << " PAIRED=" << al.isPaired() << " SEC=" << al.isSecondaryAlignment() << " PROP=" << al.isProperPair() << endl;
//skip secondary alinments
if(al->isSecondaryAlignment() || al->isSupplementaryAlignment()) continue;
//skip duplicates
if (remove_duplicates && al->isDuplicate())
{
++c_duplicates;
continue;
}
//skip unpaired
if(!al->isPaired())
{
++c_unpaired;
continue;
}
//store cached read when we encounter the mate
QByteArray name = al->name();
if (al_cache.contains(name))
{
QSharedPointer<BamAlignment> mate = al_cache.take(name);
//out << name << " [AL] First: " << al.isRead1() << " Reverse: " << al.isReverseStrand() << " Seq: " << al.QueryBases.data() << endl;
//out << name << " [MA] First: " << mate.isRead1() << " Reverse: " << mate.isReverseStrand() << " Seq: " << mate.QueryBases.data() << endl;
ReadPair& pair = pair_pool.nextFreePair();
if (al->isRead1())
{
alignmentToFastq(al, pair.e1);
alignmentToFastq(mate, pair.e2);
}
else
{
alignmentToFastq(mate, pair.e1);
alignmentToFastq(al, pair.e2);
}
pair.status = ReadPair::TO_BE_WRITTEN;
++c_paired;
}
//cache read for later retrieval
else
{
al_cache.insert(name, al);
al = QSharedPointer<BamAlignment>(new BamAlignment());
}
max_cached = std::max(max_cached, al_cache.size());
}
//write debug output
out << "Pair reads (written) : " << c_paired << endl;
out << "Unpaired reads (skipped) : " << c_unpaired << endl;
out << "Unmatched paired reads (skipped): " << al_cache.size() << endl;
if (remove_duplicates)
{
out << "Duplicate reads (skipped) : " << c_duplicates << endl;
}
out << endl;
out << "Maximum cached reads : " << max_cached << endl;
out << "Time elapsed : " << Helper::elapsedTime(timer, true) << endl;
//terminate FASTQ writer after all reads are written
pair_pool.waitAllWritten();
output_worker->terminate();
delete output_worker; //has to be deleted before the read pair list > no QScopedPointer is used!
}
};
#include "main.moc"
int main(int argc, char *argv[])
{
ConcreteTool tool(argc, argv);
return tool.execute();
}
| 30.767857
| 143
| 0.655252
|
BeneKenobi
|
91a19688e5139be41a558ee365cb2b434c6db4e7
| 5,086
|
hpp
|
C++
|
include/ygp/win/gui/button.hpp
|
qaqwqaqwq-0/YGP
|
928d53aff1c8ca1327b0cf7ad6e6836d44c3447f
|
[
"MIT"
] | 5
|
2020-12-07T08:58:24.000Z
|
2021-03-22T08:21:16.000Z
|
include/ygp/win/gui/button.hpp
|
qaqwqaqwq-0/YGP
|
928d53aff1c8ca1327b0cf7ad6e6836d44c3447f
|
[
"MIT"
] | null | null | null |
include/ygp/win/gui/button.hpp
|
qaqwqaqwq-0/YGP
|
928d53aff1c8ca1327b0cf7ad6e6836d44c3447f
|
[
"MIT"
] | 2
|
2021-01-26T07:45:52.000Z
|
2021-02-14T15:54:54.000Z
|
//Windows Common Controls Wrapper - The Button Control
#ifndef _YGP_WIN_GUI_BUTTON_HPP_
#define _YGP_WIN_GUI_BUTTON_HPP_
#include"window.hpp"
#include<commctrl.h>
BEGIN_NAMESPACE_YGP
class basic_button:public window
{
public:
using window::create;
basic_button(){}
basic_button(HWND hParent,LPCSTR lpWindowName,int nID,
DWORD dwStyle,DWORD dwExStyle,int X,int Y,
int nWidth,int nHeight):window(hParent,
WC_BUTTONA,lpWindowName,nID,dwStyle,dwExStyle,
X,Y,nWidth,nHeight){}
basic_button(HWND hParent,LPCWSTR lpWindowName,int nID,
DWORD dwStyle,DWORD dwExStyle,int X,int Y,
int nWidth,int nHeight):window(hParent,
WC_BUTTONW,lpWindowName,nID,dwStyle,dwExStyle,
X,Y,nWidth,nHeight){}
basic_button& create(HWND hParent,LPCSTR lpWindowName,int nID,
DWORD dwStyle,DWORD dwExStyle,int X,int Y,
int nWidth,int nHeight)
{
this->create(hParent,
WC_BUTTONA,lpWindowName,nID,dwStyle,dwExStyle,
X,Y,nWidth,nHeight);
return *this;
}
basic_button& create(HWND hParent,LPCWSTR lpWindowName,int nID,
DWORD dwStyle,DWORD dwExStyle,int X,int Y,
int nWidth,int nHeight)
{
this->create(hParent,
WC_BUTTONW,lpWindowName,nID,dwStyle,dwExStyle,
X,Y,nWidth,nHeight);
}
SIZE idealsize()const noexcept
{
SIZE ret;
Button_GetIdealSize(hwnd,&ret);
return ret;
}
rect textmargin()const noexcept
{
rect ret;
Button_GetTextMargin(hwnd,&ret);
return ret;
}
basic_button& textmargin(const rect& rct)
{
Button_SetTextMargin(hwnd,&rct);
return *this;
}
};
class basic_commandlink:public basic_button
{
public:
using window::create;
basic_commandlink(){}
basic_commandlink(HWND hParent,LPCSTR lpWindowName,int nID,
int X,int Y,int nWidth,int nHeight,
bool bIsDefCommandLink=false,DWORD dwStyle=0ul,
DWORD dwExStyle=0ul):basic_button(hParent,lpWindowName,
nID,WS_CHILD|WS_VISIBLE|(bIsDefCommandLink?
BS_COMMANDLINK:BS_DEFCOMMANDLINK)|dwStyle,dwExStyle,
X,Y,nWidth,nHeight){}
basic_commandlink(HWND hParent,LPCWSTR lpWindowName,int nID,
int X,int Y,int nWidth,int nHeight,
bool bIsDefCommandLink=false,DWORD dwStyle=0ul,
DWORD dwExStyle=0ul):basic_button(hParent,lpWindowName,
nID,WS_CHILD|WS_VISIBLE|(bIsDefCommandLink?
BS_COMMANDLINK:BS_DEFCOMMANDLINK)|dwStyle,dwExStyle,
X,Y,nWidth,nHeight){}
basic_commandlink& create(HWND hParent,LPCSTR lpWindowName,int nID,
int X,int Y,int nWidth,int nHeight,
bool bIsDefCommandLink=false,DWORD dwStyle=0ul,
DWORD dwExStyle=0ul)
{
((basic_button*)this)->create(hParent,lpWindowName,
nID,WS_CHILD|WS_VISIBLE|(bIsDefCommandLink?
BS_COMMANDLINK:BS_DEFCOMMANDLINK)|dwStyle,dwExStyle,
X,Y,nWidth,nHeight);
return *this;
}
basic_commandlink& create(HWND hParent,LPCWSTR lpWindowName,int nID,
int X,int Y,int nWidth,int nHeight,
bool bIsDefCommandLink=false,DWORD dwStyle=0ul,
DWORD dwExStyle=0ul)
{
((basic_button*)this)->create(hParent,lpWindowName,
nID,WS_CHILD|WS_VISIBLE|(bIsDefCommandLink?
BS_COMMANDLINK:BS_DEFCOMMANDLINK)|dwStyle,dwExStyle,
X,Y,nWidth,nHeight);
}
basic_commandlink& setnote(LPCWSTR lpszNote)noexcept
{
sendmsgw(BCM_SETNOTE,0,(LPARAM)lpszNote);
//only wide-char version is available
return *this;
}
basic_commandlink& setnote(const std::wstring& strNote)
noexcept
{
return setnote(strNote.c_str());
}
std::size_t notelength()noexcept
{
return (std::size_t)sendmsgw(BCM_GETNOTELENGTH);
}
std::wstring getnote()
{
std::size_t nlength=notelength()+1;
wchar_t* wch=new wchar_t[nlength];
if(!Button_GetNote(hwnd,wch,&nlength))
throw std::runtime_error("ygp::basic_commandlink"
"::getnote (The reply to BCM_GETNOTE message "
"returned FALSE): "
+lasterror<std::string>());
std::wstring ret(wch);
delete []wch;
return ret;
}
};
class basic_checkbutton:public basic_button
{
public:
using basic_button::create;
basic_checkbutton(){}
basic_checkbutton(HWND hParent,LPCSTR lpWindowName,int nID,
int X,int Y,int nWidth,int nHeight):basic_button(){}
};
END_NAMESPACE_YGP
#endif
| 37.674074
| 76
| 0.597719
|
qaqwqaqwq-0
|
91a234e13558671ae7f0614663b0bd36cf26f424
| 521
|
cpp
|
C++
|
Source/Tank_To_Target/MyPlayerController.cpp
|
Mati-C/Tank_To_Target
|
e506dc0744dff975a3d2f555656adf874b395962
|
[
"Apache-2.0"
] | null | null | null |
Source/Tank_To_Target/MyPlayerController.cpp
|
Mati-C/Tank_To_Target
|
e506dc0744dff975a3d2f555656adf874b395962
|
[
"Apache-2.0"
] | null | null | null |
Source/Tank_To_Target/MyPlayerController.cpp
|
Mati-C/Tank_To_Target
|
e506dc0744dff975a3d2f555656adf874b395962
|
[
"Apache-2.0"
] | null | null | null |
// Fill out your copyright notice in the Description page of Project Settings.
#include "MyPlayerController.h"
#include "Blueprint/UserWidget.h"
void AMyPlayerController::BeginPlay()
{
Super::BeginPlay();
if (GetWorld()->GetMapName() == "UEDPIE_0_Level_3")
hud = CreateWidget<UUserWidget>(this, hudComponentLevel3);
else if (GetWorld()->GetMapName() == "UEDPIE_0_Level_1" || GetWorld()->GetMapName() == "UEDPIE_0_Level_2")
hud = CreateWidget<UUserWidget>(this, hudComponent);
if (hud)
hud->AddToViewport();
}
| 32.5625
| 107
| 0.735125
|
Mati-C
|
91a38f8f28ab879faa98399ce1e5ddf7dace99e8
| 768
|
cpp
|
C++
|
Yoshi-DLC/app/Objects/CSharedObjInfo.cpp
|
DeaTh-G/Yoshi-DLC
|
56a86350df9b79d14f83f6f0f65500ed12dc17a1
|
[
"MIT"
] | 12
|
2021-02-02T20:52:33.000Z
|
2022-02-09T15:27:40.000Z
|
slw-dlc-restoration/app/Objects/CSharedObjInfo.cpp
|
DeaTh-G/slw-dlc-restoration
|
dadcc7812af2dc6ec6a3ddcf14d8fa7f3f217f25
|
[
"MIT"
] | 2
|
2021-04-15T14:34:16.000Z
|
2021-04-16T10:48:28.000Z
|
slw-dlc-restoration/app/Objects/CSharedObjInfo.cpp
|
DeaTh-G/slw-dlc-restoration
|
dadcc7812af2dc6ec6a3ddcf14d8fa7f3f217f25
|
[
"MIT"
] | 3
|
2021-04-15T14:12:44.000Z
|
2022-01-30T02:57:33.000Z
|
#include "pch.h"
HOOK(int*, __fastcall, CSharedObjInfoInitialize, ASLR(0x00666C90), char* This, void* edx, app::GameDocument* gameDocument)
{
int* result = originalCSharedObjInfoInitialize(This, edx, gameDocument);
const char* packFileName = app::ObjUtil::GetStagePackName(gameDocument);
if (strncmp(packFileName, "zdlc02", 6) == 0)
{
int coinModel = 0;
int packFile;
app::ObjUtil::GetPackFile(&packFile, app::ObjUtil::GetStagePackName(gameDocument));
app::ObjUtil::GetModelResource(&coinModel, "zdlc02_obj_yoshicoin", &packFile);
if (coinModel)
*(int*)(This + 0x10) = coinModel;
}
return result;
}
void app::CSharedObjInfo::Initialize()
{
INSTALL_HOOK(CSharedObjInfoInitialize);
}
| 28.444444
| 122
| 0.677083
|
DeaTh-G
|
91a5efbcaa131c467e05c7923436c5580bfbb8db
| 2,750
|
cpp
|
C++
|
NewtonRuntime/NewtonRuntime.cpp
|
pguyot/mbedtls-NewtonOS
|
fb33e29239173006b9f2a43622192e47a2dd2643
|
[
"Apache-2.0"
] | 7
|
2020-06-13T21:04:40.000Z
|
2021-05-15T21:28:55.000Z
|
NewtonRuntime/NewtonRuntime.cpp
|
pguyot/mbedtls-NewtonOS
|
fb33e29239173006b9f2a43622192e47a2dd2643
|
[
"Apache-2.0"
] | null | null | null |
NewtonRuntime/NewtonRuntime.cpp
|
pguyot/mbedtls-NewtonOS
|
fb33e29239173006b9f2a43622192e47a2dd2643
|
[
"Apache-2.0"
] | null | null | null |
// =========== Header ===========
// File: NewtonRuntime.cpp
// Project: DCL / ToolchainUtils
// Written by: Paul Guyot (pguyot@kallisys.net)
//
// Created on: 25/05/2020
// Internal version: 1
//
// Copyright: © 2020 by Paul Guyot.
// All rights reserved worldwide.
// ===========
// =========== Change History ===========
// 25/05/2020 v1 [PG] Creation of the file
// ===========
// Various runtime functions and declarations that are missing or rewritten here.
#include <new.h>
#include <stdlib.h>
#include <stdarg.h>
#include <stdio.h>
#include <time.h>
#include <Objects.h>
#include <NewtonMemory.h>
#include <NewtonErrors.h>
#include <NewtonExceptions.h>
#include <NewtonTime.h>
#include <NSandDDKIncludes.h>
void operator delete ( void* ptr, unsigned int sz ) noexcept {
::operator delete ( ptr );
}
// Exceptions
DefineException(evRootEvent, evt);
DefineException(exRootException, evt.ex);
DefineException(exOutOfMemory, evt.ex.outofmem);
DefineException(exDivideByZero, evt.ex.div0);
DeclareException(exFrames, exRootException);
DefineException(exFrames, evt.ex.fr);
DeclareException(exStoreError, exFrames);
DefineException(exStoreError, evt.ex.fr.store);
DeclareException(exInterpreter, exFrames);
DefineException(exInterpreter, evt.ex.fr.intrp);
DeclareException(exInterpreterWithFrameData, exInterpreter);
DefineException(exInterpreterWithFrameData, evt.ex.fr.intrp;type.ref.frame);
// C functions
extern "C" {
time_t time(time_t * timer)
{
time_t clock = RealClockSeconds();
if (timer) {
*timer = clock;
}
return clock;
}
struct tm *
gmtime(const time_t *clock)
{
return NULL;
}
void
__div0(void)
{
Throw(exDivideByZero, NULL, NULL);
}
void * calloc(size_t count, size_t size)
{
size_t total_size = count * size;
void * result = NewPtrClear(total_size);
NewtonErr err = MemError();
if (err == noErr) {
return result;
}
return NULL;
}
};
// ========================================================================== //
// There is, in fact, no reason to believe that any given natural phenomenon, //
// however marvelous it may seem today, will remain forever inexplicable. //
// Soon or late the laws governing the production of life itself will be //
// discovered in the laboratory, and man may set up business as a creator //
// on his own account. The thing, indeed, is not only conceivable; it is //
// even highly probable. //
// -- H. L. Mencken, 1930 //
// ========================================================================== //
| 27.777778
| 81
| 0.599273
|
pguyot
|
91bbeab682671a67926a6782dab5b13da1f08f02
| 2,482
|
cpp
|
C++
|
src/async_web_server_cpp/http_request.cpp
|
iche033/ign-video-server
|
a280eb08a3b8023af74d5d41d2e1d3a792a69dec
|
[
"BSD-3-Clause"
] | 1
|
2020-12-14T22:40:28.000Z
|
2020-12-14T22:40:28.000Z
|
src/async_web_server_cpp/http_request.cpp
|
iche033/ign-video-server
|
a280eb08a3b8023af74d5d41d2e1d3a792a69dec
|
[
"BSD-3-Clause"
] | 1
|
2021-01-19T22:04:02.000Z
|
2021-02-02T03:37:58.000Z
|
src/async_web_server_cpp/http_request.cpp
|
iche033/ign-video-server
|
a280eb08a3b8023af74d5d41d2e1d3a792a69dec
|
[
"BSD-3-Clause"
] | 1
|
2021-01-19T21:40:01.000Z
|
2021-01-19T21:40:01.000Z
|
#include "ignition/async_web_server_cpp/http_request.hh"
#include <regex>
std::vector<std::string> split_string(const std::string &input, char delim) {
std::vector<std::string> tokens;
std::string token;
std::istringstream tokenStream(input);
while (std::getline(tokenStream, token, delim)) {
tokens.push_back(token);
}
return tokens;
}
namespace async_web_server_cpp
{
static std::regex uri_regex("(.*?)(?:\\?(.*?))?");
bool HttpRequest::parse_uri()
{
std::smatch match;
if (regex_match(uri, match, uri_regex))
{
path.assign(match[1].first, match[1].second);
if (match[2].matched)
{
query.assign(match[2].first, match[2].second);
std::vector<std::string> pair_strings;
pair_strings = split_string(query, '&');
for(const auto& pair_string: pair_strings)
{
std::vector<std::string> pair_data;
auto eq_index = pair_string.find_first_of('=');
if (eq_index == std::string::npos)
{
if (pair_string.size() > 0)
{
query_params[pair_string] = "";
}
}
else
{
query_params[pair_string.substr(0, eq_index)] = pair_string.substr(eq_index + 1);
}
}
}
return true;
}
else
{
return false;
}
}
bool HttpRequest::has_header(const std::string &name) const
{
typedef std::vector<async_web_server_cpp::HttpHeader> HeaderList;
for (HeaderList::const_iterator itr = headers.begin(); itr != headers.end(); ++itr)
{
if (itr->name.compare(name) == 0)
return false;
}
return true;
}
std::string HttpRequest::get_header_value_or_default(const std::string &name,
const std::string &default_value) const
{
typedef std::vector<async_web_server_cpp::HttpHeader> HeaderList;
for (HeaderList::const_iterator itr = headers.begin(); itr != headers.end(); ++itr)
{
if (itr->name.compare(name) == 0)
return itr->value;
}
return default_value;
}
bool HttpRequest::has_query_param(const std::string &name) const
{
std::map<std::string, std::string>::const_iterator itr = query_params.find(name);
return itr != query_params.end();
}
std::string HttpRequest::get_query_param_value_or_default(const std::string &name,
const std::string &default_value) const
{
std::map<std::string, std::string>::const_iterator itr = query_params.find(name);
if (itr != query_params.end())
{
return itr->second;
}
else
{
return default_value;
}
}
}
| 24.333333
| 91
| 0.645044
|
iche033
|
91bbfd35872f463ddc44954f1556670b12d280c0
| 1,031
|
cpp
|
C++
|
QCIFSServer/QCIFSFwk/cCallbackChangeListener.cpp
|
rodrigomr/VFS
|
6b68b00df8cb668106c2d0841cbcd46138298717
|
[
"Apache-2.0"
] | 38
|
2018-09-24T09:37:41.000Z
|
2022-02-21T04:16:43.000Z
|
QCIFSServer/QCIFSFwk/cCallbackChangeListener.cpp
|
rodrigomr/VFS
|
6b68b00df8cb668106c2d0841cbcd46138298717
|
[
"Apache-2.0"
] | 1
|
2018-10-02T17:57:44.000Z
|
2018-10-07T06:55:44.000Z
|
QCIFSServer/QCIFSFwk/cCallbackChangeListener.cpp
|
rodrigomr/VFS
|
6b68b00df8cb668106c2d0841cbcd46138298717
|
[
"Apache-2.0"
] | 6
|
2018-10-02T17:12:38.000Z
|
2021-01-27T10:01:30.000Z
|
// Copyright 2018 Grass Valley, A Belden Brand
// 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 "stdafx.h"
#include "cCallbackChangeListener.h"
cCallbackChangeListener::cCallbackChangeListener(vfs::cPtr<iFileChangeListener> fileListener) : m_FileListener(fileListener)
{
}
cCallbackChangeListener::~cCallbackChangeListener()
{
}
bool cCallbackChangeListener::stillListening()
{
return m_FileListener->stillListening();
}
void cCallbackChangeListener::callbackChange()
{
m_FileListener->internalFileChange();
}
| 29.457143
| 124
| 0.776916
|
rodrigomr
|
91c3639ace40f7d179d7847ecb36b80f73938f3d
| 5,855
|
cpp
|
C++
|
src/Parsers/Kusto/KustoFunctions/KQLAggregationFunctions.cpp
|
DevTeamBK/ClickHouse
|
f65b5d21594a07afb017a7cdaa718c5d1caa257d
|
[
"Apache-2.0"
] | null | null | null |
src/Parsers/Kusto/KustoFunctions/KQLAggregationFunctions.cpp
|
DevTeamBK/ClickHouse
|
f65b5d21594a07afb017a7cdaa718c5d1caa257d
|
[
"Apache-2.0"
] | 1
|
2021-12-22T12:08:09.000Z
|
2021-12-22T12:08:09.000Z
|
src/Parsers/Kusto/KustoFunctions/KQLAggregationFunctions.cpp
|
DevTeamBK/ClickHouse
|
f65b5d21594a07afb017a7cdaa718c5d1caa257d
|
[
"Apache-2.0"
] | null | null | null |
#include <Parsers/IParserBase.h>
#include <Parsers/ParserSetQuery.h>
#include <Parsers/ASTExpressionList.h>
#include <Parsers/ASTSelectWithUnionQuery.h>
#include <Parsers/Kusto/ParserKQLQuery.h>
#include <Parsers/Kusto/ParserKQLStatement.h>
#include <Parsers/Kusto/KustoFunctions/IParserKQLFunction.h>
#include <Parsers/Kusto/KustoFunctions/KQLDateTimeFunctions.h>
#include <Parsers/Kusto/KustoFunctions/KQLStringFunctions.h>
#include <Parsers/Kusto/KustoFunctions/KQLDynamicFunctions.h>
#include <Parsers/Kusto/KustoFunctions/KQLCastingFunctions.h>
#include <Parsers/Kusto/KustoFunctions/KQLAggregationFunctions.h>
#include <Parsers/Kusto/KustoFunctions/KQLTimeSeriesFunctions.h>
#include <Parsers/Kusto/KustoFunctions/KQLIPFunctions.h>
#include <Parsers/Kusto/KustoFunctions/KQLBinaryFunctions.h>
#include <Parsers/Kusto/KustoFunctions/KQLGeneralFunctions.h>
namespace DB
{
bool ArgMax::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool ArgMin::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool Avg::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool AvgIf::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool BinaryAllAnd::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool BinaryAllOr::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool BinaryAllXor::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool BuildSchema::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool Count::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool CountIf::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool DCount::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool DCountIf::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool MakeBag::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool MakeBagIf::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool MakeList::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool MakeListIf::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool MakeListWithNulls::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool MakeSet::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool MakeSetIf::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool Max::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool MaxIf::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool Min::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool MinIf::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool Percentiles::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool PercentilesArray::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool Percentilesw::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool PercentileswArray::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool Stdev::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool StdevIf::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool Sum::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool SumIf::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool TakeAny::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool TakeAnyIf::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool Variance::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
bool VarianceIf::convertImpl(String &out,IParser::Pos &pos)
{
String res = String(pos->begin,pos->end);
out = res;
return false;
}
}
| 21.928839
| 66
| 0.67088
|
DevTeamBK
|
91c51789f34e7b9b3e1fda4db790619f8bc421eb
| 65,002
|
cpp
|
C++
|
Modular/library/source/TTApplication.cpp
|
jamoma/JamomaCore
|
7b1becc7f6ae2bc1f283a34af0b3986ce20f3a43
|
[
"BSD-3-Clause"
] | 31
|
2015-02-28T23:51:10.000Z
|
2021-12-25T04:16:01.000Z
|
Modular/library/source/TTApplication.cpp
|
jamoma/JamomaCore
|
7b1becc7f6ae2bc1f283a34af0b3986ce20f3a43
|
[
"BSD-3-Clause"
] | 126
|
2015-01-01T13:42:05.000Z
|
2021-07-13T14:11:42.000Z
|
Modular/library/source/TTApplication.cpp
|
jamoma/JamomaCore
|
7b1becc7f6ae2bc1f283a34af0b3986ce20f3a43
|
[
"BSD-3-Clause"
] | 14
|
2015-02-10T15:08:32.000Z
|
2019-09-17T01:21:25.000Z
|
/** @file
*
* @ingroup modularLibrary
*
* @brief TTObjectBase to handle application data structure like a TTNodeDirectory and a hash tables of names
*
* @details
*
* @authors Théo de la Hogue
*
* @copyright © 2010, Théo de la Hogue @n
* This code is licensed under the terms of the "New BSD License" @n
* http://creativecommons.org/licenses/BSD/
*/
#include "TTApplication.h"
#include <libxml/encoding.h>
#include <libxml/xmlwriter.h>
#include <libxml/xmlreader.h>
#define thisTTClass TTApplication
#define thisTTClassName "Application"
#define thisTTClassTags "modularLibrary, application"
TT_MODULAR_CONSTRUCTOR,
mDirectory(NULL),
mName(kTTSymEmpty),
mType(kTTSym_local),
mVersion(kTTSymEmpty),
mAuthor(kTTSymEmpty),
mMonitor(NO),
mDebug(NO),
mLearn(NO),
mTempAddress(kTTAdrsRoot)
{
addAttributeWithSetter(Name, kTypeSymbol);
addAttribute(Type, kTypeSymbol);
addAttribute(Version, kTypeSymbol);
addAttribute(Author, kTypeSymbol);
addAttribute(Debug, kTypeBoolean);
addAttributeWithSetter(Monitor, kTypeBoolean);
addAttribute(Learn, kTypeBoolean);
TTAttributePtr anAttribute;
registerAttribute(TTSymbol("monitorIn"), kTypeLocalValue, NULL, (TTGetterMethod)& TTApplication::getMonitorIn, (TTSetterMethod)& TTApplication::setMonitorIn);
this->findAttribute(TTSymbol("monitorIn"), &anAttribute);
anAttribute->sethidden(YES);
registerAttribute(TTSymbol("monitorOut"), kTypeLocalValue, NULL, (TTGetterMethod)& TTApplication::getMonitorOut, (TTSetterMethod)& TTApplication::setMonitorOut);
this->findAttribute(TTSymbol("monitorOut"), &anAttribute);
anAttribute->sethidden(YES);
registerAttribute(TTSymbol("cachedAttributes"), kTypeLocalValue, NULL, (TTGetterMethod)& TTApplication::getCachedAttributes, (TTSetterMethod)& TTApplication::setCachedAttributes);
this->findAttribute(TTSymbol("cachedAttributes"), &anAttribute);
anAttribute->sethidden(YES);
addAttribute(Directory, kTypePointer);
addAttributeProperty(Directory, hidden, YES);
addAttributeProperty(Directory, readOnly, YES);
addMessage(Init);
addMessage(DirectoryClear);
addMessage(DirectoryBuild);
addMessageWithArguments(DirectoryObserve);
// directory and attribute listening
addMessageWithArguments(AddDirectoryListener);
addMessageProperty(AddDirectoryListener, hidden, YES);
addMessageWithArguments(AddAttributeListener);
addMessageProperty(AddAttributeListener, hidden, YES);
addMessageWithArguments(RemoveDirectoryListener);
addMessageProperty(RemoveDirectoryListener, hidden, YES);
addMessageWithArguments(RemoveAttributeListener);
addMessageProperty(RemoveAttributeListener, hidden, YES);
addMessageWithArguments(UpdateDirectory);
addMessageProperty(UpdateDirectory, hidden, YES);
addMessageWithArguments(UpdateAttribute);
addMessageProperty(UpdateAttribute, hidden, YES);
addMessageWithArguments(ObjectRegister);
addMessageProperty(ObjectRegister, hidden, YES);
addMessageWithArguments(ObjectUnregister);
addMessageProperty(ObjectUnregister, hidden, YES);
addMessageWithArguments(ObjectRename);
addMessageProperty(ObjectRename, hidden, YES);
addMessageWithArguments(ObjectRetreive);
addMessageProperty(ObjectRetreive, hidden, YES);
addMessageWithArguments(ObjectSend);
addMessageProperty(ObjectSend, hidden, YES);
// symbol conversion
addAttributeWithGetter(AllAppNames, kTypeLocalValue);
addAttributeProperty(AllAppNames, hidden, YES);
addAttributeProperty(AllAppNames, readOnly, YES);
addAttributeWithGetter(AllTTNames, kTypeLocalValue);
addAttributeProperty(AllTTNames, hidden, YES);
addAttributeProperty(AllTTNames, readOnly, YES);
addMessageWithArguments(ConvertToAppName);
addMessageProperty(ConvertToAppName, hidden, YES);
addMessageWithArguments(ConvertToTTName);
addMessageProperty(ConvertToTTName, hidden, YES);
// needed to be handled by a TTXmlHandler
addMessageWithArguments(WriteAsXml);
addMessageProperty(WriteAsXml, hidden, YES);
addMessageWithArguments(ReadFromXml);
addMessageProperty(ReadFromXml, hidden, YES);
// note : this a temporary message to allow proxy data creation
addMessageWithArguments(ProxyDataInstantiate);
addMessageProperty(ProxyDataInstantiate, hidden, YES);
// note : this a temporary message to allow mirror object creation
addMessageWithArguments(MirrorObjectInstantiate);
addMessageProperty(MirrorObjectInstantiate, hidden, YES);
// create a TTNodeDirectory to handle the application namespace
mDirectory = new TTNodeDirectory(mName);
TT_ASSERT("NodeDirectory created successfully", (mDirectory != NULL));
}
#if 0
#pragma mark -
#pragma mark Destructor
#endif
TTApplication::~TTApplication()
{
// TODO : delete observers
if (mDirectory)
delete mDirectory;
}
#if 0
#pragma mark -
#pragma mark Attribute accesors
#endif
TTErr TTApplication::setName(const TTValue& value)
{
TTValue none, args = mName;
args.append(value[0]);
mName = value;
mDirectory->setName(mName);
TTModularApplicationManager->sendMessage("ApplicationRename", args, none);
return kTTErrNone;
}
TTErr TTApplication::setMonitor(const TTValue& value)
{
TTValue protocols = accessApplicationProtocolNames(mName);
TTSymbol protocolName;
mMonitor = value;
for (TTUInt32 i = 0; i < protocols.size(); i++) {
protocolName = protocols[i];
accessProtocol(protocolName)->setAttributeValue(kTTSym_monitor, mMonitor);
}
return kTTErrNone;
}
TTErr TTApplication::getMonitorIn(TTValue& value)
{
// we don't store the monitor in
// TODO : create a notification for this !
return kTTErrNone;
}
TTErr TTApplication::setMonitorIn(const TTValue& value)
{
TTAttributePtr anAttribute;
TTErr err = kTTErrNone;
err = this->findAttribute(kTTSym_monitorIn, &anAttribute);
if (!err)
anAttribute->sendNotification(kTTSym_notify, value); // we use kTTSym_notify because we know that observers are TTCallback
return kTTErrNone;
}
TTErr TTApplication::getMonitorOut(TTValue& value)
{
// we don't store the monitor out
// TODO : create a notification for this !
return kTTErrNone;
}
TTErr TTApplication::setMonitorOut(const TTValue& value)
{
TTAttributePtr anAttribute;
TTErr err = kTTErrNone;
err = this->findAttribute(kTTSym_monitorOut, &anAttribute);
if (!err)
anAttribute->sendNotification(kTTSym_notify, value); // we use kTTSym_notify because we know that observers are TTCallback
return kTTErrNone;
}
TTErr TTApplication::getCachedAttributes(TTValue& value)
{
// this accessor is only available for a mirror application
if (mType != kTTSym_mirror)
return kTTErrGeneric;
mCachedAttributes.getKeys(value);
return kTTErrNone;
}
TTErr TTApplication::setCachedAttributes(const TTValue& value)
{
// this accessor is only available for a mirror application
if (mType != kTTSym_mirror)
return kTTErrGeneric;
// update each node of the directory
if (mDirectory) {
TTUInt32 i;
TTValue v, none;
TTHash lastCachedAttributes;
TTSymbol name;
// keep the last cached attributes
mCachedAttributes.getKeys(v);
for (i = 0; i < v.size(); i++) {
name = v[i];
lastCachedAttributes.append(name, none);
}
// cache the new attributes that are not already cached
mCachedAttributes.clear();
for (i = 0; i < value.size(); i++) {
name = value[i];
mCachedAttributes.append(name, none);
// if the attribute wasn't already cached
if (lastCachedAttributes.lookup(name, none))
cacheAttributeNode(mDirectory->getRoot(), name, YES);
}
// uncache the last cached attributes that are not cached anymore
lastCachedAttributes.getKeys(v);
for (i = 0; i < v.size(); i++) {
name = v[i];
// if the attribute is not cached anymore
if (mCachedAttributes.lookup(name, none))
cacheAttributeNode(mDirectory->getRoot(), name, NO);
}
}
return kTTErrNone;
}
TTErr TTApplication::cacheAttributeNode(TTNodePtr aNode, TTSymbol attributeName, TTBoolean cacheOrUncache)
{
TTObject anObject;
TTList nodeList;
TTNodePtr aChild;
TTValue none;
// Send AttributeCache message to the mirror's node
anObject = aNode->getObject();
if (anObject.valid()) {
if (cacheOrUncache)
anObject.send("AttributeCache", attributeName);
else
anObject.send("AttributeUncache", attributeName);
}
// Cache attribute of node's object below
aNode->getChildren(S_WILDCARD, S_WILDCARD, nodeList);
for (nodeList.begin(); nodeList.end(); nodeList.next())
{
aChild = TTNodePtr((TTPtr)nodeList.current()[0]);
cacheAttributeNode(aChild, attributeName, cacheOrUncache);
}
return kTTErrNone;
}
TTErr TTApplication::Init()
{
return initNode(mDirectory->getRoot());
}
TTErr TTApplication::initNode(TTNodePtr aNode)
{
TTObject anObject;
TTList nodeList;
TTNodePtr aChild;
// Send Init message to node's object
anObject = aNode->getObject();
if (anObject.valid() && anObject.instance() != this)
anObject.send(kTTSym_Init);
// Init nodes below
aNode->getChildren(S_WILDCARD, S_WILDCARD, nodeList);
// Sort children by priority order
nodeList.sort(&compareNodePriorityThenNameThenInstance);
for (nodeList.begin(); nodeList.end(); nodeList.next())
{
aChild = TTNodePtr((TTPtr)nodeList.current()[0]);
initNode(aChild);
}
return kTTErrNone;
}
TTErr TTApplication::DirectoryClear()
{
// only for distant application
if (this == accessApplicationLocal)
return kTTErrGeneric;
mDirectory->init();
mDirectory->getRoot()->setObject(TTObject(this));
return kTTErrNone;
}
TTErr TTApplication::DirectoryBuild()
{
TTSymbol protocolName;
TTProtocolPtr aProtocol;
TTValue v, protocolNames;
// only for distant application
if (this == accessApplicationLocal)
return kTTErrGeneric;
// clear the directory before to not duplicate nodes
DirectoryClear();
// a distant application should have one protocol
protocolNames = accessApplicationProtocolNames(mName);
protocolName = protocolNames[0];
aProtocol = accessProtocol(protocolName);
if (aProtocol)
return buildNode(aProtocol, kTTAdrsRoot);
return kTTErrGeneric;
}
TTErr TTApplication::buildNode(TTProtocolPtr aProtocol, TTAddress anAddress)
{
TTAddress nextAddress, childAddress;
TTSymbol returnedType, service;
TTValue returnedChildren;
TTValue returnedAttributes;
TTValue returnedValue;
TTObject anObject;
TTErr err;
err = aProtocol->SendDiscoverRequest(mName, anAddress, returnedType, returnedChildren, returnedAttributes);
if (!err) {
if (anAddress != kTTAdrsRoot) {
if (mType == kTTSym_mirror) {
TTSymbol cachedAttribute;
TTValue attributesToCache, v, args, none;
anObject = appendMirrorObject(aProtocol, anAddress, returnedType, returnedAttributes);
if (anObject.valid()) {
// cache attributes value
mCachedAttributes.getKeys(attributesToCache);
for (TTUInt32 i = 0; i < attributesToCache.size(); i++) {
cachedAttribute = attributesToCache[i];
// if the attribute exist
if (anObject.get(cachedAttribute, v) != kTTErrInvalidAttribute) {
// cache the attribute value
args = cachedAttribute;
args.append((TTPtr)&v);
anObject.send("AttributeCache", args);
}
}
}
}
else if (mType == kTTSym_proxy) {
// DATA case
if (returnedType == kTTSym_Data) {
// get the service attribute
err = aProtocol->SendGetRequest(mName, anAddress.appendAttribute(kTTSym_service), returnedValue);
if (!err) {
service = returnedValue[0];
anObject = appendProxyData(aProtocol, anAddress, service);
}
}
// other case ?
}
}
for (TTUInt32 i = 0; i < returnedChildren.size(); i++) {
childAddress = returnedChildren[i];
nextAddress = anAddress.appendAddress(childAddress);
// build child nodes (and report any error)
if (buildNode(aProtocol, nextAddress))
err = kTTErrGeneric;
}
}
return err;
}
TTErr TTApplication::DirectoryObserve(const TTValue& inputValue, TTValue& outputValue)
{
if (inputValue.size() == 1)
{
if (inputValue[0].type() == kTypeBoolean || inputValue[0].type() == kTypeInt32)
{
TTBoolean enable = inputValue[0];
// only for distant application
if (this == accessApplicationLocal)
return kTTErrGeneric;
// a distant application should have one protocol
TTSymbol protocolName = accessApplicationProtocolNames(mName)[0];
TTProtocolPtr aProtocol = accessProtocol(protocolName);
if (aProtocol)
return aProtocol->SendListenRequest(mName, kTTAdrsRoot.appendAttribute(TTSymbol("life")), enable);
}
}
return kTTErrGeneric;
}
TTErr TTApplication::AddDirectoryListener(const TTValue& inputValue, TTValue& outputValue)
{
TTString editKey;
TTSymbol appToNotify, key;
TTAddress whereToListen;
TTObject returnValueCallback;
TTValue cacheElement, none;
TTErr err;
appToNotify = inputValue[1];
whereToListen = inputValue[2];
editKey = appToNotify.c_str();
editKey += "<>";
editKey += whereToListen.c_str();
key = TTSymbol(editKey);
// if this listener doesn't exist yet
if (mDirectoryListenersCache.lookup(key, cacheElement)) {
// prepare a callback based on ProtocolDirectoryCallback
returnValueCallback = TTObject("callback");
returnValueCallback.set(kTTSym_baton, inputValue);
returnValueCallback.set(kTTSym_function, TTPtr(&TTProtocolDirectoryCallback));
err = mDirectory->addObserverForNotifications(whereToListen, returnValueCallback); // ask to be notified for any address below
if (!err) {
// cache the observer in the directoryListenersCache
cacheElement.append(returnValueCallback);
return mDirectoryListenersCache.append(key, cacheElement);
}
else
; // TODO : observe the directory in order to add the listener later
}
return kTTErrGeneric;
}
TTErr TTApplication::RemoveDirectoryListener(const TTValue& inputValue, TTValue& outputValue)
{
TTString editKey;
TTSymbol appToNotify, key;
TTAddress whereToListen;
TTObject returnValueCallback;
TTValue cacheElement;
appToNotify = inputValue[0];
whereToListen = inputValue[1];
editKey = appToNotify.c_str();
editKey += "<>";
editKey += whereToListen.c_str();
key = TTSymbol(editKey);
// if this listener exists
if (!mDirectoryListenersCache.lookup(key, cacheElement)) {
returnValueCallback = cacheElement[0];
mDirectory->removeObserverForNotifications(whereToListen, returnValueCallback);
return mDirectoryListenersCache.remove(key);
}
return kTTErrGeneric;
}
TTErr TTApplication::AddAttributeListener(const TTValue& inputValue, TTValue& outputValue)
{
TTString editKey;
TTSymbol appToNotify, key;
TTAddress whereToListen;
TTList aNodeList;
TTNodePtr nodeToListen;
TTObject anObject;
TTAttributePtr anAttribute;
TTValue cacheElement, none;
TTErr err;
appToNotify = inputValue[1];
whereToListen = inputValue[2];
editKey = appToNotify.c_str();
editKey += "<>";
editKey += whereToListen.c_str();
key = TTSymbol(editKey);
// if this listener doesn't exist yet
if (mAttributeListenersCache.lookup(key, cacheElement)) {
err = mDirectory->Lookup(whereToListen, aNodeList, &nodeToListen);
if (!err) {
for (aNodeList.begin(); aNodeList.end(); aNodeList.next())
{
// get a node from the selection
nodeToListen = TTNodePtr((TTPtr)aNodeList.current()[0]);
anObject = nodeToListen->getObject();
if (anObject.valid()) {
// create an Attribute observer
anAttribute = NULL;
err = anObject.instance()->findAttribute(whereToListen.getAttribute(), &anAttribute);
if (!err) {
// prepare a callback based on ProtocolAttributeCallback
TTObject returnValueCallback = TTObject("callback");
returnValueCallback.set(kTTSym_baton, inputValue);
returnValueCallback.set(kTTSym_function, TTPtr(&TTProtocolAttributeCallback));
anAttribute->registerObserverForNotifications(returnValueCallback);
// we have now passed the returnValueCallback pointer to the callback
// it will be fetched back out to free the object in removeAttributeListener()
// cache the listener in the attributeListenersCache
cacheElement.append(returnValueCallback);
}
}
}
return mAttributeListenersCache.append(key, cacheElement);
}
else
; // TODO : observe the directory in order to add the listener later
}
// don't return an error if the listening is already enabled
return kTTErrNone;
}
TTErr TTApplication::RemoveAttributeListener(const TTValue& inputValue, TTValue& outputValue)
{
TTString editKey;
TTSymbol appToNotify, key;
TTAddress whereToListen;
TTList aNodeList;
TTNodePtr nodeToListen;
TTObject anObject;
TTAttributePtr anAttribute;
TTValue cacheElement;
TTUInt32 i;
TTErr err;
appToNotify = inputValue[0];
whereToListen = inputValue[1];
editKey = appToNotify.c_str();
editKey += "<>";
editKey += whereToListen.c_str();
key = TTSymbol(editKey);
// if this listener exists
if (!mAttributeListenersCache.lookup(key, cacheElement)) {
err = mDirectory->Lookup(whereToListen, aNodeList, &nodeToListen);
if (!err) {
i = 0;
for (aNodeList.begin(); aNodeList.end(); aNodeList.next())
{
// get a node from the selection
nodeToListen = TTNodePtr((TTPtr)aNodeList.current()[0]);
anObject = nodeToListen->getObject();
if (anObject.valid()) {
// delete Attribute observer
anAttribute = NULL;
err = anObject.instance()->findAttribute(whereToListen.getAttribute(), &anAttribute);
if (!err) {
TTObject returnValueCallback = cacheElement[i];
anAttribute->unregisterObserverForNotifications(returnValueCallback);
i++;
}
}
}
return mAttributeListenersCache.remove(key);
}
}
return kTTErrGeneric;
}
TTErr TTApplication::UpdateDirectory(const TTValue& inputValue, TTValue& outputValue)
{
TTAddress whereComesFrom;
TTValuePtr newValue;
TTValue none;
TTSymbol type, protocolName;;
TTList aNodeList;
TTNodePtr aNode;
TTProtocolPtr aProtocol;
TTErr err;
whereComesFrom = inputValue[0];
newValue = TTValuePtr((TTPtr)inputValue[1]);
// in learn mode we can only create Data
if (mLearn)
type = kTTSym_Data;
else
type = newValue[0];
err = mDirectory->Lookup(whereComesFrom, aNodeList, &aNode);
// if the node doesn't exist already
if (type != TTSymbol("delete") && err) {
// a distant application should have one protocol
protocolName = accessApplicationProtocolNames(mName)[0];
aProtocol = accessProtocol(protocolName);
if (aProtocol) {
if (mType == kTTSym_mirror)
// instantiate Mirror object for distant application
appendMirrorObject(aProtocol, whereComesFrom, type, none);
if (mType == kTTSym_proxy) {
// instantiate proxy Data object for distant application
TTObject aData = appendProxyData(aProtocol, whereComesFrom, kTTSym_parameter);
// TODO : how to allow to choose what to create when learning ?
// initialize the value with the incoming value
aData.set("value", *newValue);
}
return kTTErrNone;
}
}
// if the node exists : remove it
else if (!err && type == TTSymbol("delete"))
return mDirectory->TTNodeRemove(whereComesFrom);
return kTTErrGeneric;
}
TTErr TTApplication::UpdateAttribute(const TTValue& inputValue, TTValue& outputValue)
{
TTNodePtr nodeToUpdate;
TTAddress whereComesFrom;
TTValuePtr newValue;
TTObject anObject;
TTErr err;
if (mLearn)
UpdateDirectory(inputValue, outputValue);
whereComesFrom = inputValue[0];
newValue = TTValuePtr((TTPtr)inputValue[1]);
err = mDirectory->getTTNode(whereComesFrom, &nodeToUpdate);
if (!err) {
anObject = nodeToUpdate->getObject();
if (anObject.valid()) {
if (anObject.name() == kTTSym_Mirror)
return TTMirrorPtr(anObject.instance())->updateAttributeValue(whereComesFrom.getAttribute(), *newValue);
else
return anObject.set(whereComesFrom.getAttribute(), *newValue);
}
}
return kTTErrGeneric;
}
TTErr TTApplication::ObjectRegister(const TTValue& inputValue, TTValue& outputValue)
{
// get address and object
if (inputValue.size() >= 2) {
if (inputValue[0].type() == kTypeSymbol && inputValue[1].type() == kTypeObject) {
TTAddress address = inputValue[0];
TTObject object = inputValue[1];
// get optional context
TTPtr context = NULL;
if (inputValue.size() == 3)
if (inputValue[2].type() == kTypePointer)
context = inputValue[2];
// register the object
TTNodePtr node;
TTBoolean newInstanceCreated;
if (address == kTTAdrsRoot)
return mDirectory->getRoot()->setObject(object);
else
{
TTErr err = mDirectory->TTNodeCreate(address, object, context, &node, &newInstanceCreated);
// return the effective address and the node
if (!err)
{
if (newInstanceCreated)
node->getAddress(address);
outputValue = TTValue(address, (TTPtr)node);
}
return err;
}
}
}
return kTTErrGeneric;
}
TTErr TTApplication::ObjectUnregister(const TTValue& inputValue, TTValue& outputValue)
{
// get address
if (inputValue.size() == 1) {
if (inputValue[0].type() == kTypeSymbol) {
TTAddress address = inputValue[0];
// retreive the node
TTNodePtr node;
if (!mDirectory->getTTNode(address, &node)) {
// return the object
outputValue = node->getObject();
// unregister it
if (address == kTTAdrsRoot) {
TTObject empty;
return node->setObject(empty);
}
else
return mDirectory->TTNodeRemove(address);
}
}
}
return kTTErrGeneric;
}
TTErr TTApplication::ObjectRename(const TTValue& inputValue, TTValue& outputValue)
{
if (inputValue.size() == 2) {
if (inputValue[0].type() == kTypeObject && inputValue[1].type() == kTypeSymbol) {
TTObject anObject = inputValue[0];
TTAddress newNameInstance = inputValue[1];
// check it is name.instance only
if (newNameInstance.getType() == kAddressRelative && newNameInstance.getParent() == kTTAdrsEmpty) {
TTList aNodeList;
TTBoolean isThere;
TTNodePtr aNode;
// search the object from the root
aNodeList.append(mDirectory->getRoot());
TTErr err = mDirectory->IsThere(&aNodeList, &testNodeObject, anObject.instance(), &isThere, &aNode);
if (!err && isThere) {
TTBoolean newInstanceCreated;
TTSymbol newInstance, effectiveNameInstance;
TTAddress effectiveAddress;
aNode->setNameInstance(newNameInstance, newInstance, &newInstanceCreated);
aNode->getAddress(effectiveAddress);
outputValue = effectiveAddress.getNameInstance();
return kTTErrNone;
}
}
}
}
return kTTErrGeneric;
}
TTErr TTApplication::ObjectRetreive(const TTValue& inputValue, TTValue& outputValue)
{
// get address
if (inputValue.size() == 1) {
if (inputValue[0].type() == kTypeSymbol) {
TTAddress address = inputValue[0];
TTList aNodeList;
TTNodePtr aNode;
// allow to use wilcards
TTErr err = mDirectory->Lookup(address, aNodeList, &aNode);
if (!err) {
for (aNodeList.begin(); aNodeList.end(); aNodeList.next())
{
// get a node from the selection
aNode = TTNodePtr((TTPtr)aNodeList.current()[0]);
TTObject anObject = aNode->getObject();
if (anObject.valid()) {
// return the object
outputValue.append(anObject);
}
}
return kTTErrNone;
}
return err;
}
}
return kTTErrGeneric;
}
TTErr TTApplication::ObjectSend(const TTValue& inputValue, TTValue& outputValue)
{
// get address
if (inputValue.size() >= 1) {
if (inputValue[0].type() == kTypeSymbol) {
TTAddress address = inputValue[0];
TTList aNodeList;
TTNodePtr aNode;
// allow to use wilcards
TTErr err = mDirectory->Lookup(address, aNodeList, &aNode);
if (!err) {
TTValue valueToSend, none;
// remove the address part to get the value to send
valueToSend.copyFrom(inputValue, 1);
for (aNodeList.begin(); aNodeList.end(); aNodeList.next())
{
// get a node from the selection
aNode = TTNodePtr((TTPtr)aNodeList.current()[0]);
TTObject anObject = aNode->getObject();
if (anObject.valid()) {
TTSymbol attributeName = address.getAttribute();
// TTData case : for value attribute use Command message
if (anObject.name() == kTTSym_Data) {
if (attributeName == kTTSym_value || attributeName == kTTSymEmpty)
err = anObject.send(kTTSym_Command, valueToSend);
else
err = anObject.set(attributeName, valueToSend);
}
else {
// try to set an attribute
err = anObject.set(attributeName, valueToSend);
// try to use a message
if (err == address)
err = anObject.send(attributeName, valueToSend);
}
}
if (err)
break;
}
return kTTErrNone;
}
// distant application case : try to send the message even if it is not in the directory
else if (this != accessApplicationLocal) {
TTSymbol protocolName;
TTProtocolPtr aProtocol;
TTValue valueToSend, protocolNames;
// remove the address part to get the value to send
valueToSend.copyFrom(inputValue, 1);
// a distant application should have one protocol
protocolNames = accessApplicationProtocolNames(mName);
protocolName = protocolNames[0];
aProtocol = accessProtocol(protocolName);
if (aProtocol)
return aProtocol->SendSetRequest(mName, address, valueToSend);
}
return err;
}
}
return kTTErrGeneric;
}
TTErr TTApplication::getAllAppNames(TTValue& value)
{
if (mAppToTT.isEmpty())
value = kTTSymEmpty;
else
mAppToTT.getKeys(value);
return kTTErrNone;
}
TTErr TTApplication::getAllTTNames(TTValue& value)
{
if (mTTToApp.isEmpty())
value = kTTSymEmpty;
else
mTTToApp.getKeys(value);
return kTTErrNone;
}
TTErr TTApplication::ConvertToAppName(const TTValue& inputValue, TTValue& outputValue)
{
TTValue c;
TTSymbol ttName;
TTSymbol appName;
// if there is only 1 symbol : replace value directly by the found one.
// because it's possible to have conversion containing several appNames for 1 ttname
if (inputValue.size() == 1) {
if (inputValue[0].type() == kTypeSymbol){
ttName = inputValue[0];
return this->mTTToApp.lookup(ttName, outputValue);
}
}
// else convert each symbol of the value.
// !!! in this case 1 to many conversion is not handled
for (TTUInt8 i = 0; i < inputValue.size(); i++)
if (inputValue[i].type() == kTypeSymbol) {
ttName = inputValue[i];
if (!this->mTTToApp.lookup(ttName, c)) {
appName = c[0];
outputValue[i] = appName;
}
}
return kTTErrNone;
}
TTErr TTApplication::ConvertToTTName(const TTValue& inputValue, TTValue& outputValue)
{
TTValue c;
TTSymbol appName;
TTSymbol ttName;
// if there is only 1 symbol : replace value directly by the founded one.
// because it's possible to have conversion containing several ttNames for 1 appName
if (inputValue.size() == 1) {
if (inputValue[0].type() == kTypeSymbol){
appName = inputValue[0];
return this->mAppToTT.lookup(appName, outputValue);
}
}
// else convert each symbol of the value.
// !!! in this case 1 to many conversion is not handled
for (TTUInt8 i = 0; i < inputValue.size(); i++)
if (inputValue[i].type() == kTypeSymbol) {
appName = inputValue[i];
if (!this->mAppToTT.lookup(appName, c)) {
ttName = c[0];
outputValue[i] = ttName;
}
}
return kTTErrNone;
}
TTErr TTApplication::WriteAsXml(const TTValue& inputValue, TTValue& outputValue)
{
TTObject o = inputValue[0];
TTXmlHandlerPtr aXmlHandler = (TTXmlHandlerPtr)o.instance();
if (!aXmlHandler)
return kTTErrGeneric;
// Start "Application" xml node
xmlTextWriterStartElement((xmlTextWriterPtr)aXmlHandler->mWriter, BAD_CAST "application");
// Write attributes
xmlTextWriterWriteAttribute((xmlTextWriterPtr)aXmlHandler->mWriter, BAD_CAST "name", BAD_CAST mName.c_str());
xmlTextWriterWriteAttribute((xmlTextWriterPtr)aXmlHandler->mWriter, BAD_CAST "author", BAD_CAST mAuthor.c_str());
xmlTextWriterWriteAttribute((xmlTextWriterPtr)aXmlHandler->mWriter, BAD_CAST "version", BAD_CAST mVersion.c_str());
xmlTextWriterWriteAttribute((xmlTextWriterPtr)aXmlHandler->mWriter, BAD_CAST "type", BAD_CAST mType.c_str());
// write cached attributed for mirror application only
if (mType == kTTSym_mirror) {
TTValue v;
mCachedAttributes.getKeys(v);
v.toString();
TTString s = TTString(v[0]);
xmlTextWriterWriteAttribute((xmlTextWriterPtr)aXmlHandler->mWriter, BAD_CAST "cachedAttributes", BAD_CAST s.c_str());
}
// Write all the namespace starting from the root of the directory
if (mDirectory)
writeNodeAsXml(aXmlHandler, mDirectory->getRoot());
// End xml node
xmlTextWriterEndElement((xmlTextWriterPtr)aXmlHandler->mWriter);
return kTTErrNone;
}
void TTApplication::writeNodeAsXml(TTXmlHandlerPtr aXmlHandler, TTNodePtr aNode)
{
TTAddress nameInstance;
TTSymbol objectName, attributeName;
TTObject anObject;
TTValue attributeNameList, v, c, none;
TTList nodeList;
TTNodePtr aChild;
TTString aString;
// Write node's object attributes
anObject = aNode->getObject();
if (anObject.valid()) {
objectName = anObject.name();
if (objectName == kTTSym_Mirror)
objectName = TTMirrorPtr(anObject.instance())->getName();
}
// don't write the application that is registered under the root
if (objectName != kTTSym_Application) {
// Write description attribute as an xml comment for local or proxy application
if (mType != kTTSym_mirror) {
if (anObject.valid()) {
if (!anObject.get(kTTSym_description, v)) {
v.toString();
aString = TTString(v[0]);
xmlTextWriterWriteFormatComment((xmlTextWriterPtr)aXmlHandler->mWriter, "%s", BAD_CAST aString.data());
}
}
}
// Start object type xml node
xmlTextWriterStartElement((xmlTextWriterPtr)aXmlHandler->mWriter, BAD_CAST "node");
// Write address attribute "name.instance"
nameInstance = TTAddress(NO_DIRECTORY, NO_PARENT, aNode->getName(), aNode->getInstance(), NO_ATTRIBUTE);
xmlTextWriterWriteAttribute((xmlTextWriterPtr)aXmlHandler->mWriter, BAD_CAST "address", BAD_CAST nameInstance.c_str());
// Write object type attribute
if (objectName != kTTSymEmpty)
xmlTextWriterWriteAttribute((xmlTextWriterPtr)aXmlHandler->mWriter, BAD_CAST "object", BAD_CAST objectName.c_str());
// TODO : allow to choose which kind of object can write its attributes or not
if (objectName != kTTSym_Data &&
objectName != kTTSym_Mirror &&
objectName != kTTSym_Container &&
objectName != kTTSym_Input &&
objectName != kTTSym_InputAudio &&
objectName != kTTSym_Output &&
objectName != kTTSym_OutputAudio)
; // do nothing
// Write attributes
else if (anObject.valid()) {
anObject.attributes(attributeNameList);
for(TTUInt32 i = 0; i < attributeNameList.size(); i++)
{
attributeName = attributeNameList[i];
// Filter attribute names
if (attributeName != kTTSym_description &&
attributeName != kTTSym_value &&
attributeName != kTTSym_address &&
attributeName != kTTSym_bypass &&
attributeName != kTTSym_monitorIn &&
attributeName != kTTSym_monitorOut &&
attributeName != kTTSym_rampStatus &&
attributeName != kTTSym_baton && // because #TTData inherits #TTCallback
attributeName != kTTSym_object && // because #TTData inherits #TTCallback
attributeName != kTTSym_notification && // because #TTData inherits #TTCallback
attributeName != kTTSym_function) // because #TTData inherits #TTCallback
{
// write only cached attributes
if (mType == kTTSym_mirror)
if (mCachedAttributes.lookup(attributeName, none))
continue;
anObject.get(attributeName, v);
if (v.empty())
continue;
v.toString();
aString = TTString(v[0]);
if (aString.empty())
continue;
xmlTextWriterWriteAttribute((xmlTextWriterPtr)aXmlHandler->mWriter, BAD_CAST attributeName.c_str(), BAD_CAST aString.data());
}
}
// TODO : Write messages ?
}
}
// Write nodes below
aNode->getChildren(S_WILDCARD, S_WILDCARD, nodeList);
for (nodeList.begin(); nodeList.end(); nodeList.next())
{
aChild = TTNodePtr((TTPtr)nodeList.current()[0]);
writeNodeAsXml(aXmlHandler, aChild);
}
// End xml node
// don't write the application that is registered under the root
if (objectName != kTTSym_Application)
xmlTextWriterEndElement((xmlTextWriterPtr)aXmlHandler->mWriter);
}
TTErr TTApplication::ReadFromXml(const TTValue& inputValue, TTValue& outputValue)
{
TTObject o = inputValue[0];
TTXmlHandlerPtr aXmlHandler = (TTXmlHandlerPtr)o.instance();
if (!aXmlHandler)
return kTTErrGeneric;
TTString anAppKey, aTTKey;
TTValue appValue, ttValue, v, nameValue, parameterValue;
// Switch on the name of the XML node
// Starts reading
if (aXmlHandler->mXmlNodeName == kTTSym_xmlHandlerReadingStarts)
return kTTErrNone;
// Ends reading
if (aXmlHandler->mXmlNodeName == kTTSym_xmlHandlerReadingEnds)
return kTTErrNone;
// Comment Node
if (aXmlHandler->mXmlNodeName == kTTSym_xmlHandlerReadingComment)
return kTTErrNone;
// Conversion Table node
if (aXmlHandler->mXmlNodeName == TTSymbol("conversionTable")) {
if (aXmlHandler->mXmlNodeStart)
mAppToTT.clear();
return kTTErrNone;
}
// Entry node
if (aXmlHandler->mXmlNodeName == TTSymbol("entry")) {
// get App Symbol
if (xmlTextReaderMoveToAttribute((xmlTextReaderPtr)aXmlHandler->mReader, BAD_CAST "App") == 1) {
aXmlHandler->fromXmlChar(xmlTextReaderValue((xmlTextReaderPtr)aXmlHandler->mReader), appValue);
v = appValue;
v.toString();
anAppKey = TTString(v[0]);
}
// get TT Value
if (xmlTextReaderMoveToAttribute((xmlTextReaderPtr)aXmlHandler->mReader, BAD_CAST "TT") == 1) {
aXmlHandler->fromXmlChar(xmlTextReaderValue((xmlTextReaderPtr)aXmlHandler->mReader), ttValue);
v = ttValue;
v.toString();
aTTKey = TTString(v[0]);
}
mAppToTT.append(TTSymbol(anAppKey), ttValue); // here we register the entire value to handle 1 to many conversion
mTTToApp.append(TTSymbol(aTTKey), appValue); // here we register the entire value to handle 1 to many conversion
return kTTErrNone;
}
// Application node
if (aXmlHandler->mXmlNodeName == TTSymbol("application")) {
if (aXmlHandler->mXmlNodeStart) {
DirectoryClear();
mTempAddress = kTTAdrsRoot;
// get the type attribute
if (xmlTextReaderMoveToAttribute((xmlTextReaderPtr)aXmlHandler->mReader, (const xmlChar*)("type")) == 1) {
aXmlHandler->fromXmlChar(xmlTextReaderValue((xmlTextReaderPtr)aXmlHandler->mReader), v);
if (v.size() == 1) {
if (v[0].type() == kTypeSymbol) {
mType = v[0];
}
}
}
// get the author attribute
if (xmlTextReaderMoveToAttribute((xmlTextReaderPtr)aXmlHandler->mReader, (const xmlChar*)("author")) == 1) {
aXmlHandler->fromXmlChar(xmlTextReaderValue((xmlTextReaderPtr)aXmlHandler->mReader), v, YES);
if (v.size() == 1) {
if (v[0].type() == kTypeSymbol) {
mAuthor = v[0];
}
}
}
// get the version attribute
if (xmlTextReaderMoveToAttribute((xmlTextReaderPtr)aXmlHandler->mReader, (const xmlChar*)("version")) == 1) {
aXmlHandler->fromXmlChar(xmlTextReaderValue((xmlTextReaderPtr)aXmlHandler->mReader), v);
if (v.size() == 1) {
if (v[0].type() == kTypeSymbol) {
mVersion = v[0];
}
}
}
// get the cached attributes
if (xmlTextReaderMoveToAttribute((xmlTextReaderPtr)aXmlHandler->mReader, (const xmlChar*)("cachedAttributes")) == 1) {
aXmlHandler->fromXmlChar(xmlTextReaderValue((xmlTextReaderPtr)aXmlHandler->mReader), v);
setCachedAttributes(v);
}
}
return kTTErrNone;
}
// Any other node
readNodeFromXml(aXmlHandler);
return kTTErrNone;
}
void TTApplication::readNodeFromXml(TTXmlHandlerPtr aXmlHandler)
{
TTSymbol objectName, protocolName, attributeName, attributeToFilterName;
TTAddress address;
TTBoolean useInstanceAsName = NO;
TTInt32 instance;
TTProtocolPtr aProtocol;
TTObject anObject;
TTValue v, protocolNames, none;
TTHash attributesToFilter;
// when a node starts : append address to the current temp address
if (aXmlHandler->mXmlNodeStart) {
// the address attribute can store names which are problematic with xml (like number)
if (xmlTextReaderMoveToAttribute((xmlTextReaderPtr)aXmlHandler->mReader, (const xmlChar*)("address")) == 1) {
aXmlHandler->fromXmlChar(xmlTextReaderValue((xmlTextReaderPtr)aXmlHandler->mReader), v, YES, YES);
if (v.size() == 1) {
if (v[0].type() == kTypeSymbol) {
address = v[0];
if (address == TTSymbol("instance"))
useInstanceAsName = YES;
else
mTempAddress = mTempAddress.appendAddress(address);
}
}
}
// optionnal : use the node name to build the address
// NOTE : we keep this option for backward compatibility but now the node name is always stored into address attribute (see in : writeNodeAsXml)
else
mTempAddress = mTempAddress.appendAddress(TTAddress(aXmlHandler->mXmlNodeName));
// optionnal : the instance attribute allow to easily duplicate a namespace part
instance = 1;
if (xmlTextReaderMoveToAttribute((xmlTextReaderPtr)aXmlHandler->mReader, (const xmlChar*)("instance")) == 1) {
aXmlHandler->fromXmlChar(xmlTextReaderValue((xmlTextReaderPtr)aXmlHandler->mReader), v);
if (v.size() == 1) {
if (v[0].type() == kTypeInt32) {
instance = v[0];
// if we don't use the instance as a name
if (!useInstanceAsName)
{
// start instance numbering from 1 (and let the nodelib duplication mechanism do the rest)
mTempAddress = mTempAddress.appendInstance(TTSymbol("1"));
// if the node is not empty : we have to duplicate its content too !
if (!aXmlHandler->mXmlNodeIsEmpty)
{
mFoldAddress = mTempAddress;
mFolderSize = instance;
TTLogMessage("TTApplication::readNodeFromXml : %s is a fold address to duplicate %d times\n", mFoldAddress.c_str(), mFolderSize);
}
}
}
}
}
// aXmlHandler->mXmlNodeStart : NO
else
{
// end of content duplication
if (mFoldAddress != kTTAdrsEmpty && mTempAddress == mFoldAddress)
{
TTLogMessage("TTApplication::readNodeFromXml : %s fold address ends\n", mTempAddress.c_str());
mFoldAddress = kTTAdrsEmpty;
mFolderSize = 0;
}
}
// is a parent part of the address is the fold address ?
TTUInt32 duplicate = 1;
TTInt8 duplicateDepth = 0;
if (mFoldAddress != kTTAdrsEmpty && mFoldAddress != mTempAddress)
{
TTAddressComparisonFlag comparison = mTempAddress.compare(mFoldAddress, duplicateDepth);
if (comparison == kAddressLower)
{
duplicate = mFolderSize;
}
}
// read the file several times if duplicate > 1
for (TTUInt32 d = 1; d <= duplicate; d++)
{
// in case of content duplication : duplicate fold address part
TTAddress duplicateFoldAddress;
if (mFoldAddress != kTTAdrsEmpty)
{
v = TTInt32(d);
v.toString();
TTString s = TTString(v[0]);
duplicateFoldAddress = mFoldAddress.appendInstance(s);
}
// read the file several times if instance > 1
for (TTInt32 i = 0; i < instance; i++)
{
if (useInstanceAsName)
{
// start numbering from 1
v = TTInt32(i+1);
v.toString();
TTString s = TTString(v[0]);
address = mTempAddress.appendAddress(TTAddress(s.data()));
}
else
address = mTempAddress;
// in case of content duplication : merge duplicate fold address part and
if (mFoldAddress != kTTAdrsEmpty && duplicateDepth > 0)
{
TTAddress foldPart;
TTAddress tempPart;
TTUInt8 splitAt = address.countSeparator() - duplicateDepth;
if (useInstanceAsName)
splitAt--;
address.splitAt(splitAt, foldPart, tempPart);
address = duplicateFoldAddress.appendAddress(tempPart);
}
// get the object name
objectName = kTTSymEmpty;
if (xmlTextReaderMoveToAttribute((xmlTextReaderPtr)aXmlHandler->mReader, (const xmlChar*)("object")) == 1) {
aXmlHandler->fromXmlChar(xmlTextReaderValue((xmlTextReaderPtr)aXmlHandler->mReader), v);
if (v.size() == 1) {
if (v[0].type() == kTypeSymbol)
objectName = v[0];
}
}
// a distant application should have one protocol
protocolNames = accessApplicationProtocolNames(mName);
protocolName = protocolNames[0];
aProtocol = accessProtocol(protocolName);
if (aProtocol) {
// for mirror application
if (mType == kTTSym_mirror) {
// instantiate a mirror object
anObject = appendMirrorObject(aProtocol, address, objectName, none);
}
// for proxy appplication
else if (mType == kTTSym_proxy) {
// instantiate the real object
// DATA case
if (objectName == kTTSym_Data) {
// get the data service
if (xmlTextReaderMoveToAttribute((xmlTextReaderPtr)aXmlHandler->mReader, (const xmlChar*)("service")) == 1) {
aXmlHandler->fromXmlChar(xmlTextReaderValue((xmlTextReaderPtr)aXmlHandler->mReader), v);
if (v.size() == 1) {
if (v[0].type() == kTypeSymbol) {
// instantiate a proxy data
anObject = appendProxyData(aProtocol, address, v[0]);
// filter service attribute for the parsing of all attributes
attributesToFilter.append(kTTSym_service, none);
// get the data type
if (xmlTextReaderMoveToAttribute((xmlTextReaderPtr)aXmlHandler->mReader, (const xmlChar*)("type")) == 1) {
aXmlHandler->fromXmlChar(xmlTextReaderValue((xmlTextReaderPtr)aXmlHandler->mReader), v);
if (v.size() == 1) {
if (v[0].type() == kTypeSymbol) {
// set data type
anObject.set(kTTSym_type, v);
// filter type attribute for the parsing of all attributes
attributesToFilter.append(kTTSym_type, none);
}
}
}
}
}
}
}
else if (objectName == kTTSym_Container) {
// instantiate a proxy container
anObject = appendProxyContainer(aProtocol, address);
}
else if (objectName == kTTSymEmpty ||
objectName == kTTSym_none) // for backward compatibility because we don't write anything when there is no object
{
// register no object into the directory
TTNodePtr aNode;
TTObject empty;
TTBoolean newInstanceCreated;
this->mDirectory->TTNodeCreate(address, empty, NULL, &aNode, &newInstanceCreated);
}
// OTHER case ? Input, Output, Mapper ?
}
if (anObject.valid()) {
// cache attributes (for mirror application only)
if (mType == kTTSym_mirror) {
TTSymbol cachedAttribute;
TTValue attributesToCache, v, args, none;
TTAttributePtr attribute;
// cache attributes value
mCachedAttributes.getKeys(attributesToCache);
for (TTUInt32 i = 0; i < attributesToCache.size(); i++) {
cachedAttribute = attributesToCache[i];
// if the attribute exist
if (!anObject.instance()->findAttribute(cachedAttribute, &attribute)) {
// cache the attribute with no value (see after)
args = cachedAttribute;
anObject.send("AttributeCache", args);
}
}
}
// return to the first attribute
xmlTextReaderMoveToFirstAttribute((xmlTextReaderPtr)aXmlHandler->mReader);
// get all object attributes and their value
do {
// get attribute name
aXmlHandler->fromXmlChar(xmlTextReaderName((xmlTextReaderPtr)aXmlHandler->mReader), v);
if (v.size() == 1) {
if (v[0].type() == kTypeSymbol) {
attributeName = v[0];
// filter attributes
if (!attributesToFilter.lookup(attributeName, none))
continue;
// get attribute value
aXmlHandler->fromXmlChar(xmlTextReaderValue((xmlTextReaderPtr)aXmlHandler->mReader), v);
// if the attribute is not cached or in proxy application case
anObject.set(attributeName, v);
}
}
} while (xmlTextReaderMoveToNextAttribute((xmlTextReaderPtr)aXmlHandler->mReader) == 1);
}
}
} // for instance
} // for duplication
// when a node is empty : keep the parent address for next nodes
// but if we use instance as name : don't
if (aXmlHandler->mXmlNodeIsEmpty && !useInstanceAsName)
mTempAddress = mTempAddress.getParent();
}
// when a node ends : keep the parent address for next nodes
else
mTempAddress = mTempAddress.getParent();
}
TTErr TTApplication::ProxyDataInstantiate(const TTValue& inputValue, TTValue& outputValue)
{
// for proxy application only
if (mType == kTTSym_proxy) {
// a distant application should have one protocol
TTValue protocolNames = accessApplicationProtocolNames(mName);
TTSymbol protocolName = protocolNames[0];
TTProtocolPtr aProtocol = accessProtocol(protocolName);
if (aProtocol) {
if (inputValue.size() == 2) {
if (inputValue[0].type() == kTypeSymbol && inputValue[1].type() == kTypeSymbol) {
TTAddress address = inputValue[0];
TTSymbol service = inputValue[1];
// instantiate a proxy data object
outputValue = appendProxyData(aProtocol, address.normalize(), service);
return kTTErrNone;
}
}
}
}
return kTTErrGeneric;
}
TTErr TTApplication::MirrorObjectInstantiate(const TTValue& inputValue, TTValue& outputValue)
{
// for mirror application only
if (mType == kTTSym_mirror)
{
// a distant application should have one protocol
TTValue protocolNames = accessApplicationProtocolNames(mName);
TTSymbol protocolName = protocolNames[0];
TTProtocolPtr aProtocol = accessProtocol(protocolName);
if (aProtocol)
{
if (inputValue.size() == 2)
{
if (inputValue[0].type() == kTypeSymbol && inputValue[1].type() == kTypeSymbol)
{
TTAddress address = inputValue[0];
TTSymbol objectName = inputValue[1];
TTValue none;
// instantiate a mirror object
TTObject anObject = appendMirrorObject(aProtocol, address.normalize(), objectName, none);
if (anObject.valid())
{
// cache attributes value
TTValue attributesToCache;
mCachedAttributes.getKeys(attributesToCache);
for (TTUInt32 i = 0; i < attributesToCache.size(); i++)
{
TTSymbol cachedAttribute = attributesToCache[i];
// if the attribute exist
TTAttributePtr anAttribute;
if (anObject.instance()->findAttribute(cachedAttribute, &anAttribute) != kTTErrInvalidAttribute)
{
// cache the attribute value without value
anObject.send("AttributeCache", cachedAttribute);
}
}
}
outputValue = anObject;
return kTTErrNone;
}
}
}
}
return kTTErrGeneric;
}
TTObject TTApplication::appendMirrorObject(TTProtocolPtr aProtocol, TTAddress anAddress, TTSymbol objectName, TTValue& attributesName)
{
TTObject aMirror;
TTNodePtr aNode;
TTBoolean newInstanceCreated, allowGetRequest, allowSetRequest, allowListenRequest;
TTObject getAttributeCallback, setAttributeCallback, sendMessageCallback, listenAttributeCallback;
TTObject empty;
TTValue baton;
if (objectName != kTTSymEmpty && objectName != kTTSym_none) {
TTValue none, v, args = objectName;
aProtocol->getAttributeValue(TTSymbol("get"), allowGetRequest);
if (allowGetRequest) {
getAttributeCallback = TTObject("callback");
// TODO: How to use TTObject instead of TTObjectBasePtr here ?
baton = TTValue(TTObject(TTObjectBasePtr(aProtocol)), mName, anAddress);
getAttributeCallback.set(kTTSym_baton, baton);
getAttributeCallback.set(kTTSym_function, TTPtr(&TTProtocolGetAttributeCallback));
args.append(getAttributeCallback);
}
else
args.append(empty);
aProtocol->getAttributeValue(TTSymbol("set"), allowSetRequest);
if (allowSetRequest) {
setAttributeCallback = TTObject("callback");
// TODO: How to use TTObject instead of TTObjectBasePtr here ?
baton = TTValue(TTObject(TTObjectBasePtr(aProtocol)), mName, anAddress);
setAttributeCallback.set(kTTSym_baton, baton);
setAttributeCallback.set(kTTSym_function, TTPtr(&TTProtocolSetAttributeCallback));
args.append(setAttributeCallback);
sendMessageCallback = TTObject("callback");
// TODO: How to use TTObject instead of TTObjectBasePtr here ?
baton = TTValue(TTObject(TTObjectBasePtr(aProtocol)), mName, anAddress);
sendMessageCallback.set(kTTSym_baton, baton);
sendMessageCallback.set(kTTSym_function, TTPtr(&TTProtocolSendMessageCallback));
args.append(sendMessageCallback);
}
else {
args.append(empty);
args.append(empty);
}
aProtocol->getAttributeValue(TTSymbol("listen"), allowListenRequest);
if (allowListenRequest) {
listenAttributeCallback = TTObject("callback");
// TODO: How to use TTObject instead of TTObjectBasePtr here ?
baton = TTValue(TTObject(TTObjectBasePtr(aProtocol)), mName, anAddress);
listenAttributeCallback.set(kTTSym_baton, baton);
listenAttributeCallback.set(kTTSym_function, TTPtr(&TTProtocolListenAttributeCallback));
args.append(listenAttributeCallback);
}
else
args.append(empty);
aMirror = TTObject(kTTSym_Mirror, args);
// if the Mirror cannot instantiate attributes
aMirror.attributes(v);
if (v.size() == 0)
aMirror.send("AttributesInstantiate", attributesName);
// if the node doesn't exist yet
if (this->mDirectory->getTTNode(anAddress, &aNode))
// register object into the directory
this->mDirectory->TTNodeCreate(anAddress, aMirror, NULL, &aNode, &newInstanceCreated);
else
// update the node's object
aNode->setObject(aMirror);
}
return aMirror;
}
TTObject TTApplication::appendProxyData(TTProtocolPtr aProtocol, TTAddress anAddress, TTSymbol service)
{
TTObject aData;
TTValue baton;
TTNodePtr aNode;
TTBoolean newInstanceCreated;
aData = TTObject(kTTSym_Data, service);
baton = TTValue(TTObject(TTObjectBasePtr(aProtocol)), mName, anAddress);
aData.set(kTTSym_baton, baton);
aData.set(kTTSym_function, TTPtr(&TTApplicationProxyDataValueCallback));
// if the node doesn't exist yet
if (this->mDirectory->getTTNode(anAddress, &aNode))
// register object into the directory
this->mDirectory->TTNodeCreate(anAddress, aData, NULL, &aNode, &newInstanceCreated);
else
// update the node's object
aNode->setObject(aData);
return aData;
}
TTObject TTApplication::appendProxyContainer(TTProtocolPtr aProtocol, TTAddress anAddress)
{
TTObject aContainer;
TTNodePtr aNode;
TTBoolean newInstanceCreated;
aContainer = TTObject(kTTSym_Container);
// register object into the directory
this->mDirectory->TTNodeCreate(anAddress, aContainer, aContainer.instance(), &aNode, &newInstanceCreated);
return aContainer;
}
#if 0
#pragma mark -
#pragma mark Some Methods
#endif
TTErr TTApplicationProxyDataValueCallback(const TTValue& baton, const TTValue& data)
{
TTValue v = kTTSym_value;
v.append((TTPtr)&data);
return TTProtocolSetAttributeCallback(baton, v);
}
| 34.575532
| 183
| 0.557229
|
jamoma
|
91cd8deef9188f6bd7be7bc181888d2249af114d
| 1,041
|
cpp
|
C++
|
others/ancestor.cpp
|
anu9901998/competitive-programming
|
2a3325bc42d027197449d85c519a74d104a5461c
|
[
"MIT"
] | 6
|
2020-04-08T00:25:44.000Z
|
2021-09-04T20:39:15.000Z
|
others/ancestor.cpp
|
anu9901998/competitive-programming
|
2a3325bc42d027197449d85c519a74d104a5461c
|
[
"MIT"
] | 2
|
2020-04-09T06:59:12.000Z
|
2020-04-09T14:56:32.000Z
|
others/ancestor.cpp
|
anu9901998/competitive-programming
|
2a3325bc42d027197449d85c519a74d104a5461c
|
[
"MIT"
] | 6
|
2020-04-16T03:47:06.000Z
|
2021-09-07T10:21:32.000Z
|
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5;
vector<int>adj[maxn+7];
int timein[maxn+7] = {};
int timeout[maxn+7] = {};
int curr_time = 0;
void dfs(int a, int parent){
timein[a] = curr_time++;
for(int b:adj[a]){
if (b == parent) continue;
dfs(b, a);
}
timeout[a] = curr_time++;
}
// Check if node a is ancestor of node b
bool is_ancestor(int a, int b){
if (timein[b] > timein[a] && timeout[b] < timeout[a]) return true;
return false;
}
int main(){
// Sample tree
//
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
adj[1].push_back(2);
adj[1].push_back(3);
adj[2].push_back(4);
adj[2].push_back(5);
adj[3].push_back(6);
adj[3].push_back(7);
dfs(1, 0);
for(int i = 1;i <= 7;i++){
for(int j = i+1;j <= 7;j++){
if (i == j) continue;
cout << i << " is ancestor of " << j << ": " << (is_ancestor(i, j)?"YES":"NO") << endl;
}
}
return 0;
}
| 18.927273
| 99
| 0.473583
|
anu9901998
|
91ce383ea79beac5aa1778bedb9641e2ba8cd436
| 1,884
|
cpp
|
C++
|
USACO Bronze/December 2017 Contest/milk.cpp
|
Alecs-Li/Competitive-Programming
|
39941ff8e2c8994abbae8c96a1ed0a04b10058b8
|
[
"MIT"
] | 1
|
2021-07-06T02:14:03.000Z
|
2021-07-06T02:14:03.000Z
|
USACO Bronze/December 2017 Contest/milk.cpp
|
Alex01890-creator/competitive-programming
|
39941ff8e2c8994abbae8c96a1ed0a04b10058b8
|
[
"MIT"
] | null | null | null |
USACO Bronze/December 2017 Contest/milk.cpp
|
Alex01890-creator/competitive-programming
|
39941ff8e2c8994abbae8c96a1ed0a04b10058b8
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
int main(){
ifstream fin("measurement.in");
ofstream fout("measurement.out");
int N, ans = 0, count = 0, cap = 0; fin >> N;
int day[N], change[N], b = 7, m = 7, e = 7, mostM = 0;
string cows[] = {"Bessie, Mildred, Elsie"}, temp;
string name[N], pogairCow = "";
char type[N];
for(int i=0; i<N; i++){
fin >> day[i] >> name[i] >> type[i] >> change[i];
cap = max(day[i], cap);
}
while(count != N){
for(int i=1; i<=cap; i++){
for(int j=0; j<N; j++){
if(i == day[j]){
count += 1;
if(type[j] == '+'){
if(name[j] == "Bessie"){
b += change[j];
} else if (name[j] == "Mildred"){
m += change[j];
} else if (name[j] == "Elsie"){
e += change[j];
}
} else if (type[j] == '-'){
if(name[j] == "Bessie"){
b -= change[j];
} else if (name[j] == "Mildred"){
m -= change[j];
} else if (name[j] == "Elsie"){
e -= change[j];
}
}
mostM = max(max(b, m), max(m, e));
temp = pogairCow;
pogairCow = "";
if(mostM == b && (b == e || b == m)){
pogairCow += "Bessie";
} else if (mostM == b){
pogairCow = "Bessie";
}
if(mostM == m && (m == b || m == e)){
pogairCow += "Mildred";
} else if (mostM == m){
pogairCow = "Mildred";
}
if(mostM == e && (e == b || e == m)){
pogairCow += "Elsie";
} else if (mostM == e){
pogairCow = "Elsie";
}
if(pogairCow != temp){
ans += 1;
}
}
}
}
}
fout << ans;
}
| 27.304348
| 56
| 0.376327
|
Alecs-Li
|
91d175b58e372795786052e9ef4a82afc1c71d19
| 1,929
|
cpp
|
C++
|
src/coreclr/src/pal/tests/palsuite/file_io/GetStdHandle/test2/GetStdHandle.cpp
|
swaroop-sridhar/runtime
|
d0efddd932f6fb94c3e9436ab393fc390c7b2da9
|
[
"MIT"
] | 52
|
2017-03-15T08:16:52.000Z
|
2019-04-26T07:53:29.000Z
|
src/coreclr/src/pal/tests/palsuite/file_io/GetStdHandle/test2/GetStdHandle.cpp
|
swaroop-sridhar/runtime
|
d0efddd932f6fb94c3e9436ab393fc390c7b2da9
|
[
"MIT"
] | 2
|
2020-03-25T06:25:42.000Z
|
2022-02-25T21:30:33.000Z
|
src/coreclr/src/pal/tests/palsuite/file_io/GetStdHandle/test2/GetStdHandle.cpp
|
swaroop-sridhar/runtime
|
d0efddd932f6fb94c3e9436ab393fc390c7b2da9
|
[
"MIT"
] | 14
|
2019-05-09T13:15:41.000Z
|
2021-11-16T02:54:09.000Z
|
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
/*=====================================================================
**
** Source: GetStdHandle.c (test 2)
**
** Purpose: Smoke Tests the PAL implementation of the GetStdHandle function.
**
**
**===================================================================*/
#include <palsuite.h>
int __cdecl main(int argc, char *argv[])
{
HANDLE hFile = NULL;
if (0 != PAL_Initialize(argc,argv))
{
return FAIL;
}
/*
* attempt to get an invalid handle
*/
hFile = GetStdHandle(-2);
if (hFile != INVALID_HANDLE_VALUE)
{
Fail("GetStdHandle: ERROR -> A request for the STD_INPUT_HANDLE "
"returned an invalid handle.\n");
}
/*
* test the STD_INPUT_HANDLE handle
*/
hFile = GetStdHandle(STD_INPUT_HANDLE);
if (hFile == INVALID_HANDLE_VALUE)
{
Fail("GetStdHandle: ERROR -> A request for the STD_INPUT_HANDLE "
"returned an invalid handle.\n");
}
/*
* test the STD_OUTPUT_HANDLE handle
*/
hFile = GetStdHandle(STD_OUTPUT_HANDLE);
if (hFile == INVALID_HANDLE_VALUE)
{
Fail("GetStdHandle: ERROR -> A request for the STD_OUTPUT_HANDLE "
"returned an invalid handle.\n");
}
/* test the STD_ERROR_HANDLE handle */
hFile = GetStdHandle(STD_ERROR_HANDLE);
if (hFile == INVALID_HANDLE_VALUE)
{
Fail("GetStdHandle: ERROR -> A request for the STD_ERROR_HANDLE "
"returned an invalid handle.\n");
}
/* check to see if we can CloseHandle works on the STD_ERROR_HANDLE */
if (!CloseHandle(hFile))
{
Fail("GetStdHandle: ERROR -> CloseHandle failed. GetLastError "
"returned %u.\n",
GetLastError());
}
PAL_Terminate();
return PASS;
}
| 24.417722
| 76
| 0.567652
|
swaroop-sridhar
|
91d7960b37ae3114f179b49ef7db1d472584d226
| 1,045
|
cpp
|
C++
|
SlidingWindow/longestsubarraywithsumk.cpp
|
thisisnitish/cp-dsa-
|
9ae94930b65f8dc293d088e9148960939b9f6fa4
|
[
"MIT"
] | 4
|
2020-12-29T09:27:10.000Z
|
2022-02-12T14:20:23.000Z
|
SlidingWindow/longestsubarraywithsumk.cpp
|
thisisnitish/cp-dsa-
|
9ae94930b65f8dc293d088e9148960939b9f6fa4
|
[
"MIT"
] | 1
|
2021-11-27T06:15:28.000Z
|
2021-11-27T06:15:28.000Z
|
SlidingWindow/longestsubarraywithsumk.cpp
|
thisisnitish/cp-dsa-
|
9ae94930b65f8dc293d088e9148960939b9f6fa4
|
[
"MIT"
] | 1
|
2021-11-17T21:42:57.000Z
|
2021-11-17T21:42:57.000Z
|
/*
Longest Sub-Array with Sum K
https://practice.geeksforgeeks.org/problems/longest-sub-array-with-sum-k0809/1#
*/
class Solution
{
public:
int lenOfLongSubarr(int A[], int N, int K)
{
int i = 0, j = 0, sum = 0, ans = 0;
while (j < N)
{
sum += A[j];
//here we have to all the 3 cases because it is a variable size S.W.
if (sum < K)
j++;
else if (sum == K)
{
//if we found that sum == k then calulate the length of the
//window and update it
ans = max(ans, (j - i) + 1);
j++;
}
else if (sum > K)
{
while (sum > K)
{
sum = sum - A[i];
i++;
if (sum == K)
{
ans = max(ans, (j - i) + 1);
}
}
j++;
}
}
return ans;
}
};
| 23.75
| 80
| 0.344498
|
thisisnitish
|
91d89092db3a0bdd638a80bdc4fdd0b7d47d2184
| 4,174
|
cpp
|
C++
|
client/include/game/CQuadTreeNode.cpp
|
MayconFelipeA/sampvoiceatt
|
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
|
[
"MIT"
] | 368
|
2015-01-01T21:42:00.000Z
|
2022-03-29T06:22:22.000Z
|
client/include/game/CQuadTreeNode.cpp
|
MayconFelipeA/sampvoiceatt
|
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
|
[
"MIT"
] | 92
|
2019-01-23T23:02:31.000Z
|
2022-03-23T19:59:40.000Z
|
client/include/game/CQuadTreeNode.cpp
|
MayconFelipeA/sampvoiceatt
|
3fae8a2cf37dfad2e3925d56aebfbbcd4162b0ff
|
[
"MIT"
] | 179
|
2015-02-03T23:41:17.000Z
|
2022-03-26T08:27:16.000Z
|
/*
Plugin-SDK (Grand Theft Auto San Andreas) source file
Authors: GTA Community. See more here
https://github.com/DK22Pac/plugin-sdk
Do not delete this comment block. Respect others' work!
*/
#include "CQuadTreeNode.h"
// Converted from thiscall void CQuadTreeNode::AddItem(void *item,CRect const&rect) 0x552CD0
void CQuadTreeNode::AddItem(void* item, CRect const& rect) {
plugin::CallMethod<0x552CD0, CQuadTreeNode *, void*, CRect const&>(this, item, rect);
}
// Converted from thiscall void CQuadTreeNode::CQuadTreeNode(CRect const&rect,int startLevel) 0x552830
CQuadTreeNode::CQuadTreeNode(CRect const& rect, int startLevel) {
plugin::CallMethod<0x552830, CQuadTreeNode *, CRect const&, int>(this, rect, startLevel);
}
// Converted from thiscall void CQuadTreeNode::DeleteItem(void *item) 0x552A40
void CQuadTreeNode::DeleteItem(void* item) {
plugin::CallMethod<0x552A40, CQuadTreeNode *, void*>(this, item);
}
// Converted from thiscall void CQuadTreeNode::DeleteItem(void *item,CRect const&rect) 0x552A90
void CQuadTreeNode::DeleteItem(void* item, CRect const& rect) {
plugin::CallMethod<0x552A90, CQuadTreeNode *, void*, CRect const&>(this, item, rect);
}
// Converted from thiscall int CQuadTreeNode::FindSector(CRect const&rect) 0x5525A0
int CQuadTreeNode::FindSector(CRect const& rect) {
return plugin::CallMethodAndReturn<int, 0x5525A0, CQuadTreeNode *, CRect const&>(this, rect);
}
// Converted from thiscall int CQuadTreeNode::FindSector(CVector2D const&posn) 0x552640
int CQuadTreeNode::FindSector(CVector2D const& posn) {
return plugin::CallMethodAndReturn<int, 0x552640, CQuadTreeNode *, CVector2D const&>(this, posn);
}
// Converted from thiscall void CQuadTreeNode::ForAllMatching(CRect const&rect,void *callback) 0x552980
void CQuadTreeNode::ForAllMatching(CRect const& rect, void(*callback)(CRect const&, void *)) {
plugin::CallMethod<0x552980, CQuadTreeNode *, CRect const&, void(*)(CRect const&, void *)>(this, rect, callback);
}
// Converted from thiscall void CQuadTreeNode::ForAllMatching(CVector2D const&posn,void *callback) 0x5529F0
void CQuadTreeNode::ForAllMatching(CVector2D const& posn, void(*callback)(CVector2D const&, void *)) {
plugin::CallMethod<0x5529F0, CQuadTreeNode *, CVector2D const&, void(*)(CVector2D const&, void *)>(this, posn, callback);
}
// Converted from thiscall void CQuadTreeNode::GetAll(CPtrListSingleLink &list) 0x552870
void CQuadTreeNode::GetAll(CPtrListSingleLink& list) {
plugin::CallMethod<0x552870, CQuadTreeNode *, CPtrListSingleLink&>(this, list);
}
// Converted from thiscall void CQuadTreeNode::GetAllMatching(CRect const&rect,CPtrListSingleLink &list) 0x5528C0
void CQuadTreeNode::GetAllMatching(CRect const& rect, CPtrListSingleLink& list) {
plugin::CallMethod<0x5528C0, CQuadTreeNode *, CRect const&, CPtrListSingleLink&>(this, rect, list);
}
// Converted from thiscall void CQuadTreeNode::GetAllMatching(CVector2D const&posn,CPtrListSingleLink &list) 0x552930
void CQuadTreeNode::GetAllMatching(CVector2D const& posn, CPtrListSingleLink& list) {
plugin::CallMethod<0x552930, CQuadTreeNode *, CVector2D const&, CPtrListSingleLink&>(this, posn, list);
}
// Converted from thiscall bool CQuadTreeNode::InSector(CRect const&rect,int sector) 0x5526A0
bool CQuadTreeNode::InSector(CRect const& rect, int sector) {
return plugin::CallMethodAndReturn<bool, 0x5526A0, CQuadTreeNode *, CRect const&, int>(this, rect, sector);
}
// Converted from thiscall void CQuadTreeNode::InitPool(void) 0x552C00
void CQuadTreeNode::InitPool() {
plugin::CallMethod<0x552C00, CQuadTreeNode *>(this);
}
// Converted from cdecl void CQuadTreeNode::operator delete(void *data) 0x552C90
void CQuadTreeNode::operator delete(void* data) {
plugin::Call<0x552C90, void*>(data);
}
// Converted from cdecl void* CQuadTreeNode::operator new(uint size) 0x552C80
void* CQuadTreeNode::operator new(unsigned int size) {
return plugin::CallAndReturn<void*, 0x552C80, unsigned int>(size);
}
// Converted from thiscall void CQuadTreeNode::~CQuadTreeNode() 0x552520
CQuadTreeNode::~CQuadTreeNode() {
plugin::CallMethod<0x552520, CQuadTreeNode *>(this);
}
| 47.977011
| 125
| 0.763776
|
MayconFelipeA
|
91d942e502a55a0e9d2050fa54b6b8bd75a523da
| 5,255
|
cpp
|
C++
|
src/Configuration.cpp
|
CastMi/warped2
|
86c2fa5ddf777530b637dba800641b30ccee7aa7
|
[
"MIT"
] | null | null | null |
src/Configuration.cpp
|
CastMi/warped2
|
86c2fa5ddf777530b637dba800641b30ccee7aa7
|
[
"MIT"
] | null | null | null |
src/Configuration.cpp
|
CastMi/warped2
|
86c2fa5ddf777530b637dba800641b30ccee7aa7
|
[
"MIT"
] | null | null | null |
#include "Configuration.hpp"
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <memory>
#include <stdexcept>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include <iostream>
#include "json/json.h"
#include "config.h"
#include "CommandLineConfiguration.hpp"
#include "EventDispatcher.hpp"
#include "Partitioner.hpp"
#include "STLLTSFQueue.hpp"
#include "ProfileGuidedPartitioner.hpp"
#include "RoundRobinPartitioner.hpp"
#include "SequentialEventDispatcher.hpp"
#include "utility/memory.hpp"
namespace {
const static std::string DEFAULT_CONFIG = R"x({
// If max-sim-time > 0, the simulation will halt once the time has been reached
"max-sim-time": 0,
// Valid options are "sequential" and "time-warp"
"simulation-type": "time-warp",
"statistics": {
// Valid options are "none", "json", "csv", "graphviz", and "metis".
// "json" and "csv" are individual statistics, others are aggregate.
"type": "none",
// If statistics-type is not "none", save the output in this file
"file": "statistics.out"
},
"time-warp" : {
"gvt-calculation": {
"period": 1000
},
"state-saving": {
"type": "periodic",
"period": 10
},
"cancellation": "aggressive",
"worker-threads": 3,
"scheduler-count": 1,
// LP Migration valid options are "on" and "off"
"lp-migration": "off",
// Name of file to dump stats, "none" to disable
"statistics-file" : "none",
"config-output-file" : "none",
"communication" : {
"max-buffer-size" : 512
}
},
"partitioning": {
// Valid options are "default", "round-robin" and "profile-guided".
// "default" will use user provided partitioning if given, else
// "round-robin".
"type": "default",
// The path to the statistics file that was created from a previous run.
// Only used if "partitioning-type" is "profile-guided".
"file": "statistics.out"
}
})x";
// Recursively copy the values of b into a. Both a and b must be objects.
void update(Json::Value& a, Json::Value& b) {
if (!a.isObject() || !b.isObject()) { return; }
for (const auto& key : b.getMemberNames()) {
if (a[key].isObject()) {
update(a[key], b[key]);
} else {
a[key] = b[key];
}
}
}
Json::Value parseJsonFile(std::string filename) {
Json::Reader reader;
std::ifstream input(filename);
if (!input.is_open()) {
throw std::runtime_error(std::string("Could not open configuration file ") + filename);
}
Json::Value root;
auto success = reader.parse(input, root);
input.close();
if (!success) {
throw std::runtime_error(std::string("Failed to parse configuration\n") +
reader.getFormattedErrorMessages());
}
return root;
}
} // namespace
namespace warped {
Configuration::Configuration(const std::string& config_file_name)
: config_file_name_(config_file_name), root_(nullptr)
{ readUserConfig(); }
Configuration::Configuration(const std::string& model_description, int argc,
const char* const* argv,
const std::vector<TCLAP::Arg*>& cmd_line_args)
: config_file_name_(""), root_(make_unique<Json::Value>())
{ init(model_description, argc, argv, cmd_line_args); }
Configuration::Configuration(const std::string& model_description, int argc,
const char* const* argv)
: config_file_name_(""), root_(make_unique<Json::Value>())
{ init(model_description, argc, argv, {}); }
Configuration::~Configuration() = default;
void Configuration::readUserConfig() {
if (!config_file_name_.empty()) {
auto root2 = parseJsonFile(config_file_name_);
update(*root_, root2);
}
}
void Configuration::init(const std::string& model_description, int argc, const char* const* argv,
const std::vector<TCLAP::Arg*>& cmd_line_args) {
Json::Reader reader;
if (!reader.parse(DEFAULT_CONFIG, *root_)) {
throw std::runtime_error(std::string("Failed to parse default configuration\n") +
reader.getFormattedErrorMessages());
}
// Update the JSON root with any command line args given
bool should_dump;
CommandLineConfiguration clc(*root_);
std::tie(should_dump, config_file_name_) = clc.parse(model_description, argc, argv, cmd_line_args);
readUserConfig();
if (should_dump) {
std::cout << *root_ << std::endl;
std::exit(0);
}
}
std::unique_ptr<EventDispatcher>
Configuration::makeDispatcher() {
std::string invalid_string;
auto simulation_type = (*root_)["simulation-type"].asString();
std::cout << "Simulation type: Sequential" << std::endl;
return make_unique<SequentialEventDispatcher>();
}
std::unique_ptr<Partitioner> Configuration::makePartitioner() {
return make_unique<RoundRobinPartitioner>();
}
std::unique_ptr<Partitioner>
Configuration::makePartitioner(std::unique_ptr<Partitioner> ) {
return makePartitioner();
}
std::unique_ptr<Partitioner> Configuration::makeLocalPartitioner(unsigned int ,
unsigned int& ) {
return makePartitioner();
}
} // namespace warped
| 26.948718
| 103
| 0.646432
|
CastMi
|
91d96346166f89e285e73a00156322a6cfcbcb69
| 1,408
|
cpp
|
C++
|
libkiml/src/states.cpp
|
alexanderdna/KimL
|
58915197ac5a85686a9d6126c4c2fe0374419fde
|
[
"MIT"
] | null | null | null |
libkiml/src/states.cpp
|
alexanderdna/KimL
|
58915197ac5a85686a9d6126c4c2fe0374419fde
|
[
"MIT"
] | 1
|
2020-07-13T03:44:19.000Z
|
2020-07-14T08:32:03.000Z
|
libkiml/src/states.cpp
|
alexanderdna/KimL
|
58915197ac5a85686a9d6126c4c2fe0374419fde
|
[
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "states.h"
#include "utils.h"
#include <string.h>
bool States::loadByteCode(const KIMLBYTE *byteCodeContent, KIMLUINT byteCodeSize)
{
if (byteCodeSize < 24)
return false;
if (this->code)
{
delete []this->code;
this->code = nullptr;
this->codesize = 0;
}
KIMLCHAR magic[4];
KIMLCHAR ver[4];
KIMLBYTE pad[8];
memcpy(magic, byteCodeContent, 4);
memcpy(ver, byteCodeContent + 4, 4);
memcpy(pad, byteCodeContent + 8, 8);
if (strncmp(magic, "kiml", 4))
return false;
// has to be version 13.08, 14.11 or 17.11
if (strncmp(ver, "1308", 4)
&& strncmp(ver, "1411", 4)
&& strncmp(ver, "1711", 4))
return false;
if (*(uint64_t *)pad)
return false;
KIMLUINT codeSize = kimlDeserializeUInt(byteCodeContent + 16);
if (codeSize + 16 + sizeof(KIMLUINT) * 2 > byteCodeSize)
return false;
KIMLBYTE *code = new KIMLBYTE[codeSize];
memcpy(code, byteCodeContent + 16 + sizeof(KIMLUINT), codeSize);
KIMLUINT poolSize = kimlDeserializeUInt(byteCodeContent + 16 + sizeof(KIMLUINT) + codeSize);
if (poolSize + codeSize + 16 + sizeof(KIMLUINT) * 2 > byteCodeSize)
{
delete []code;
return false;
}
KIMLCHAR *pool = new KIMLCHAR[poolSize];
memcpy(pool, byteCodeContent + 16 + sizeof(KIMLUINT) * 2 + codeSize, poolSize);
this->code = code;
this->codesize = codeSize;
this->stringpool = pool;
this->stringpoolsize = poolSize;
return true;
}
| 22
| 93
| 0.681818
|
alexanderdna
|
91daae02c393c77c19acca4b8046968a861a8348
| 1,331
|
cpp
|
C++
|
1273 Drainage Ditches/main.cpp
|
sqc1999-oi/POJ
|
450afa9485bcf5398f9cb7efd5a3b8c40de60e03
|
[
"MIT"
] | 1
|
2016-07-18T12:05:16.000Z
|
2016-07-18T12:05:16.000Z
|
1273 Drainage Ditches/main.cpp
|
sqc1999/POJ
|
450afa9485bcf5398f9cb7efd5a3b8c40de60e03
|
[
"MIT"
] | null | null | null |
1273 Drainage Ditches/main.cpp
|
sqc1999/POJ
|
450afa9485bcf5398f9cb7efd5a3b8c40de60e03
|
[
"MIT"
] | null | null | null |
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
struct Edge { int from, to, cap, flow; };
struct EK
{
static const int INF = 0x7fffffff;
int n, m, a[201], p[201];
vector<int> G[201];
vector<Edge> Edges;
int MaxFlow()
{
int flow = 0;
while (true)
{
fill(a + 1, a + 1 + m, 0);
a[1] = INF;
queue<int> q;
q.push(1);
while (!q.empty())
{
int x = q.front();
q.pop();
for (int i = 0; i < G[x].size(); i++)
{
Edge &e = Edges[G[x][i]];
if (!a[e.to] && e.cap>e.flow)
{
a[e.to] = min(a[x], e.cap - e.flow);
p[e.to] = G[x][i];
q.push(e.to);
}
}
if (a[m]) break;
}
if (!a[m]) break;
for (int u = m; u != 1; u = Edges[p[u]].from)
{
Edges[p[u]].flow += a[m];
Edges[p[u] ^ 1].flow -= a[m];
}
flow += a[m];
}
return flow;
}
};
int main()
{
ios::sync_with_stdio(false);
int n, m;
while (cin >> n >> m)
{
EK ek;
ek.n = n, ek.m = m;
for (int i = 1; i <= n; i++)
{
int s, e, c;
cin >> s >> e >> c;
ek.G[s].push_back(ek.Edges.size());
ek.Edges.push_back(Edge{ s,e,c,0 });
ek.G[e].push_back(ek.Edges.size());
ek.Edges.push_back(Edge{ e,s,0,0 });
}
cout << ek.MaxFlow() << endl;
}
}
| 19.289855
| 49
| 0.458302
|
sqc1999-oi
|
91e29c83725890c5c0c3d62ee5a66e83320e3194
| 1,534
|
hpp
|
C++
|
external/plate/gpu/webgl/scissor.hpp
|
DisQS/AniMolViewer
|
c56293067672a453a3cf3490c0e86004df0130dc
|
[
"BSD-3-Clause"
] | 2
|
2021-11-21T23:26:00.000Z
|
2021-12-18T10:33:17.000Z
|
external/plate/gpu/webgl/scissor.hpp
|
DisQS/AniMolViewer
|
c56293067672a453a3cf3490c0e86004df0130dc
|
[
"BSD-3-Clause"
] | 5
|
2021-11-28T18:26:25.000Z
|
2021-12-06T08:15:06.000Z
|
external/plate/gpu/webgl/scissor.hpp
|
DisQS/animol-viewer
|
c56293067672a453a3cf3490c0e86004df0130dc
|
[
"BSD-3-Clause"
] | null | null | null |
#pragma once
#include <cstddef>
#include <cstdlib>
#include <GLES3/gl3.h>
#include "../gpu.hpp"
namespace plate {
class scissor {
public:
void push(gpu::int_box box) noexcept
{
if (enabled_) // scissor into a scissor area..
{
add_current_to_stack();
box_.p1.x = std::max(box.p1.x, box_.p1.x);
box_.p1.y = std::max(box.p1.y, box_.p1.y);
box_.p2.x = std::min(box.p2.x, box_.p2.x);
box_.p2.y = std::min(box.p2.y, box_.p2.y);
// ensure box size isn't negative
box_.p2.x = std::max(box_.p1.x, box_.p2.x);
box_.p2.y = std::max(box_.p1.y, box_.p2.y);
}
else
{
enabled_ = true;
box_ = box;
glEnable(GL_SCISSOR_TEST);
}
glScissor(box_.p1.x, box_.p1.y, box_.p2.x - box_.p1.x, box_.p2.y - box_.p1.y);
}
void pop() noexcept
{
if (stack_size_)
{
box_ = stack_[--stack_size_];
glScissor(box_.p1.x, box_.p1.y, box_.p2.x - box_.p1.x, box_.p2.y - box_.p1.y);
}
else
if (enabled_)
{
glDisable(GL_SCISSOR_TEST);
enabled_ = false;
}
}
private:
void add_current_to_stack() noexcept
{
if (stack_size_ == max_stack_size_)
{
log_error("Past max stack size");
return;
}
stack_[stack_size_++] = box_;
}
bool enabled_{false};
gpu::int_box box_; // the active box
const static int max_stack_size_ = 10;
std::array<gpu::int_box, max_stack_size_> stack_;
int stack_size_{0};
}; // class scissor
} // namespace plate
| 17.431818
| 84
| 0.576923
|
DisQS
|
91e3c11c437e6a8113f5841b6dd9066dbe442e15
| 1,426
|
cpp
|
C++
|
C++/Variable Sized Arrays/variable sized arrays.cpp
|
IsaacAsante/hackerrank
|
76c430b341ce1e2ab427eda57508eb309d3b215b
|
[
"MIT"
] | 108
|
2021-03-29T05:04:16.000Z
|
2022-03-19T15:11:52.000Z
|
C++/Variable Sized Arrays/variable sized arrays.cpp
|
IsaacAsante/hackerrank
|
76c430b341ce1e2ab427eda57508eb309d3b215b
|
[
"MIT"
] | null | null | null |
C++/Variable Sized Arrays/variable sized arrays.cpp
|
IsaacAsante/hackerrank
|
76c430b341ce1e2ab427eda57508eb309d3b215b
|
[
"MIT"
] | 32
|
2021-03-30T03:56:54.000Z
|
2022-03-27T14:41:32.000Z
|
/* Author: Isaac Asante
* HackerRank URL for this exercise: https://www.hackerrank.com/challenges/variable-sized-arrays/problem
* Original video explanation: https://www.youtube.com/watch?v=JcFUgBOCGKA
* Last verified on: April 17, 2021
*/
/* IMPORTANT:
* This is the full code for the solution.
* Some headers were added/modified.
*/
#include <cstdio>
#include <vector>
#include <iostream>
#include <sstream>
#include <string>
using namespace std;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int n, q;
cin >> n >> q;
cin.ignore();
vector<vector<int>> a(n);
for (int i = 0; i < n; i++) {
string line;
getline(cin, line);
istringstream ss(line);
// First number is the size of k
int k_size, k_item;
ss >> k_size;
vector<int> k(k_size, 0);
// Populate k array
for (int j = 0; j < k_size; j++) {
ss >> k_item;
// Don't use push_back()
k[j] = k_item;
}
// Add k to the array a. Don't use push_back().
a[i] = k;
}
// Read the rest of the queries
for (int i = 0; i < q; i++) {
string query;
getline(cin, query);
istringstream ss(query);
// Get the location in the vector
int x, y;
ss >> x >> y;
cout << a[x][y] << endl;
}
return 0;
}
| 23.766667
| 104
| 0.547686
|
IsaacAsante
|
91e3f126ad303b16b71fdb606b930a6a5e5318f8
| 942
|
hpp
|
C++
|
sprout/compost/effects.hpp
|
osyo-manga/Sprout
|
8885b115f739ef255530f772067475d3bc0dcef7
|
[
"BSL-1.0"
] | 1
|
2020-02-04T05:16:01.000Z
|
2020-02-04T05:16:01.000Z
|
sprout/compost/effects.hpp
|
osyo-manga/Sprout
|
8885b115f739ef255530f772067475d3bc0dcef7
|
[
"BSL-1.0"
] | null | null | null |
sprout/compost/effects.hpp
|
osyo-manga/Sprout
|
8885b115f739ef255530f772067475d3bc0dcef7
|
[
"BSL-1.0"
] | null | null | null |
#ifndef SPROUT_COMPOST_EFFECTS_HPP
#define SPROUT_COMPOST_EFFECTS_HPP
#include <sprout/config.hpp>
#include <sprout/compost/effects/clipped.hpp>
#include <sprout/compost/effects/rectified.hpp>
#include <sprout/compost/effects/changed_volume.hpp>
#include <sprout/compost/effects/reverbed.hpp>
#include <sprout/compost/effects/distorted.hpp>
#include <sprout/compost/effects/overdriven.hpp>
#include <sprout/compost/effects/fuzzed.hpp>
#include <sprout/compost/effects/compressed.hpp>
#include <sprout/compost/effects/tremolo.hpp>
#include <sprout/compost/effects/vibrato.hpp>
#include <sprout/compost/effects/chorus.hpp>
#include <sprout/compost/effects/auto_pan.hpp>
#include <sprout/compost/effects/pseudo_stereo.hpp>
#include <sprout/compost/effects/noise_gated.hpp>
#include <sprout/compost/effects/vocal_cancelled.hpp>
#include <sprout/compost/effects/superposed.hpp>
#endif // #ifndef SPROUT_COMPOST_EFFECTS_HPP
| 40.956522
| 54
| 0.799363
|
osyo-manga
|
91ef43b688c4f48b3c2c7ec28174130ad54197a3
| 510
|
cpp
|
C++
|
Codeforces/902A - Visiting a Friend.cpp
|
naimulcsx/online-judge-solutions
|
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
|
[
"MIT"
] | null | null | null |
Codeforces/902A - Visiting a Friend.cpp
|
naimulcsx/online-judge-solutions
|
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
|
[
"MIT"
] | null | null | null |
Codeforces/902A - Visiting a Friend.cpp
|
naimulcsx/online-judge-solutions
|
0b80f81bcfb05a7cfe7fc925304c70b19eff1d6f
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, m;
scanf("%d %d", &n, &m);
vector<pair<int, int>> arr(n + 1);
arr.push_back({0, 0});
for (int i = 1; i <= n; ++i) scanf("%d %d", &arr[i].first, &arr[i].second);
int curr_pos = 0;
for (int i = 0; i < n; ++i) {
if ( arr[i + 1].first > curr_pos ) continue;
curr_pos = max(curr_pos, arr[i + 1].second);
}
if (curr_pos >= m) printf("YES\n");
else printf("NO\n");
return 0;
}
| 24.285714
| 79
| 0.486275
|
naimulcsx
|
91f003b282553ce1aac84637dc099e10952128e0
| 129
|
hpp
|
C++
|
dependencies/all_include/glm/detail/type_vec.hpp
|
o-micron/IntroToRendering
|
7f1d8a02b2064b96334cbdef519af2048503722b
|
[
"MIT"
] | null | null | null |
dependencies/all_include/glm/detail/type_vec.hpp
|
o-micron/IntroToRendering
|
7f1d8a02b2064b96334cbdef519af2048503722b
|
[
"MIT"
] | null | null | null |
dependencies/all_include/glm/detail/type_vec.hpp
|
o-micron/IntroToRendering
|
7f1d8a02b2064b96334cbdef519af2048503722b
|
[
"MIT"
] | null | null | null |
/// @ref core
/// @file glm/detail/type_vec.hpp
#pragma once
#include "qualifier.hpp"
#include "compute_vector_relational.hpp"
| 16.125
| 40
| 0.736434
|
o-micron
|
91f2809e96bed0678f08f50276eb08c83dc4af19
| 3,746
|
cpp
|
C++
|
lmeditor/src/component/entity_list/entity_list_component.cpp
|
Lawrencemm/LM-Engine
|
9c5e59e64e2a5a24c347538fa49046ab5a88d1f5
|
[
"MIT"
] | 40
|
2020-03-13T06:12:11.000Z
|
2022-01-16T21:05:34.000Z
|
lmeditor/src/component/entity_list/entity_list_component.cpp
|
Lawrencemm/LM-Engine
|
9c5e59e64e2a5a24c347538fa49046ab5a88d1f5
|
[
"MIT"
] | 31
|
2020-02-09T06:25:12.000Z
|
2021-12-31T04:37:08.000Z
|
lmeditor/src/component/entity_list/entity_list_component.cpp
|
Lawrencemm/LM-Engine
|
9c5e59e64e2a5a24c347538fa49046ab5a88d1f5
|
[
"MIT"
] | 2
|
2020-03-13T06:12:12.000Z
|
2020-11-21T15:41:17.000Z
|
#include "entity_list_component.h"
#include <entt/entt.hpp>
#include <lmng/hierarchy.h>
#include <lmng/name.h>
#include <lmtk/vlayout.h>
namespace lmeditor
{
component entity_list_init::operator()()
{
return std::make_unique<entity_list_component>(*this);
}
entity_list_component::entity_list_component(entity_list_init const &init)
: controller{init.registry},
position{init.position},
size{init.size},
selection_background{
init.renderer,
init.resource_cache,
init.position,
{0, 0},
{0.f, 0.f, 0.f, 1.f},
}
{
}
void entity_list_component::update_selection_background()
{
if (controller.named_entities_count == 0)
return;
lmtk::text_layout &line = selected_line();
selection_background.set_rect(
{position.x, line.position.y}, {size.width, line.get_size().height});
}
lmtk::text_layout &entity_list_component::selected_line()
{
return line_layouts[controller.selected_entity_index];
}
entity_list_component &
entity_list_component::move_resources(lmgl::resource_sink &resource_sink)
{
selection_background.move_resources(resource_sink);
for (auto &layout : line_layouts)
layout.move_resources(resource_sink);
return *this;
}
bool entity_list_component::add_to_frame(lmgl::iframe *frame)
{
update_selection_background();
selection_background.add_to_frame(frame);
for (auto &layout : line_layouts)
layout.render(frame, position, size);
return false;
}
void entity_list_component::reset(
lmgl::irenderer &renderer,
lmgl::resource_sink &resource_sink,
lmtk::resource_cache const &resource_cache,
entt::registry const ®istry)
{
for (auto &layout : line_layouts)
layout.move_resources(resource_sink);
line_layouts.clear();
auto layout_factory = lmtk::text_layout_factory{
renderer, resource_cache, {1.f, 1.f, 1.f}, position};
std::function<void(entt::entity, unsigned)> add_children;
add_children = [&](auto entity, unsigned level) {
for (auto child : lmng::child_range{registry, entity})
{
line_layouts.emplace_back(
layout_factory.create(registry.get<lmng::name>(child).string));
auto old_pos = line_layouts.back().position;
old_pos.x += level * 15;
line_layouts.back().set_position(old_pos);
add_children(child, level + 1);
}
};
for (auto [entity, name] :
registry.view<lmng::name const>(entt::exclude<lmng::parent>).proxy())
{
line_layouts.emplace_back(layout_factory.create(name.string));
add_children(entity, 1);
}
lmtk::layout_vertical(lmtk::vertical_layout{position.y, 12}, line_layouts);
}
lm::size2i entity_list_component::get_size() { return size; }
lm::point2i entity_list_component::get_position() { return position; }
entity_list_component &
entity_list_component::set_rect(lm::point2i position, lm::size2i size)
{
this->position = position;
this->size = size;
controller.dirty = true;
return *this;
}
bool entity_list_component::handle(const lmtk::input_event &input_event)
{
return controller.handle(input_event);
}
component_interface &entity_list_component::update(
lmgl::irenderer *renderer,
lmgl::resource_sink &resource_sink,
lmtk::resource_cache const &resource_cache,
lmtk::input_state const &input_state)
{
if (controller.dirty)
{
reset(*renderer, resource_sink, resource_cache, *controller.registry);
controller.dirty = false;
}
return *this;
}
std::vector<command_description>
entity_list_component::get_command_descriptions()
{
return std::vector<command_description>();
}
} // namespace lmeditor
| 26.757143
| 79
| 0.694875
|
Lawrencemm
|
91f6dfba1c37281bf0732e562680e61665b43a72
| 1,376
|
cpp
|
C++
|
spectral/quadrature/gauss_hermite_roots.cpp
|
simonpp/2dRidgeletBTE
|
5d08cbb5c57fc276c7a528f128615d23c37ef6a0
|
[
"BSD-3-Clause"
] | 1
|
2019-11-08T03:15:56.000Z
|
2019-11-08T03:15:56.000Z
|
spectral/quadrature/gauss_hermite_roots.cpp
|
simonpp/2dRidgeletBTE
|
5d08cbb5c57fc276c7a528f128615d23c37ef6a0
|
[
"BSD-3-Clause"
] | null | null | null |
spectral/quadrature/gauss_hermite_roots.cpp
|
simonpp/2dRidgeletBTE
|
5d08cbb5c57fc276c7a528f128615d23c37ef6a0
|
[
"BSD-3-Clause"
] | 1
|
2019-11-08T03:15:56.000Z
|
2019-11-08T03:15:56.000Z
|
#include <Eigen/Core>
#include <Eigen/Eigenvalues>
#include <Eigen/MPRealSupport>
#include <boost/math/constants/constants.hpp>
#include <boost/math/special_functions/gamma.hpp>
#include <boost/multiprecision/mpfr.hpp>
#include <iomanip>
#include <iostream>
#include "gauss_hermite_quadrature.hpp"
#include "spectral/mpfr/import_std_math.hpp"
//#include <quadmath.h>
namespace boltzmann {
namespace mp = boost::multiprecision;
using namespace mpfr;
typedef mp::mpfr_float_backend<100000> mfloat_t;
typedef mp::number<mfloat_t> mpfr_float_t;
using namespace std;
void gauss_hermite_roots(std::vector<double>& roots, const int N, const int ndigits)
{
mpreal::set_default_prec(ndigits);
typedef mpreal mfloat_t;
// typedef double mfloat_t;
typedef Eigen::Matrix<mfloat_t, Eigen::Dynamic, Eigen::Dynamic> MatrixXmp;
MatrixXmp A(N, N);
A.fill(0);
for (int i = 0; i < N - 1; ++i) {
const double beta = ::math::sqrt(1.0 * (i + 1)) / ::math::sqrt(2.0);
A(i, i + 1) = beta;
A(i + 1, i) = beta;
}
Eigen::SelfAdjointEigenSolver<MatrixXmp> eigensolver;
// Eigen::EigenSolver<MatrixXmp> eigensolver;
eigensolver.compute(A, Eigen::EigenvaluesOnly);
const auto w = eigensolver.eigenvalues();
for (int i = 0; i < N; ++i) {
roots[i] = w(i).toDouble();
}
// sort
std::sort(roots.begin(), roots.end());
}
} // end namespace boltzmann
| 25.962264
| 84
| 0.698401
|
simonpp
|
91f6f67124a4c6f0298b8cb4bd954eb81dc45e06
| 239
|
cpp
|
C++
|
src/main.cpp
|
ATiltedTree/APASSTools
|
1702e082ae3b95ec10f3c5c084ef9396de5c3833
|
[
"MIT"
] | null | null | null |
src/main.cpp
|
ATiltedTree/APASSTools
|
1702e082ae3b95ec10f3c5c084ef9396de5c3833
|
[
"MIT"
] | 4
|
2020-02-25T00:21:58.000Z
|
2020-07-03T11:12:03.000Z
|
src/main.cpp
|
ATiltedTree/APASSTools
|
1702e082ae3b95ec10f3c5c084ef9396de5c3833
|
[
"MIT"
] | null | null | null |
#include "ui/APASSTools/APASSTools.hpp"
#include <QApplication>
auto main(int argc, char *argv[]) -> int {
QApplication a(argc, argv);
APASSTools apasstools = APASSTools(nullptr);
apasstools.show();
return QApplication::exec();
}
| 23.9
| 46
| 0.715481
|
ATiltedTree
|
91f7b3f67addd15cb1202107a01569737872616b
| 402
|
cc
|
C++
|
src/SourceRange.cc
|
MarcSeebold/libclangmm
|
a882bec8d15715486d11affac5479fba42b1cce2
|
[
"MIT"
] | null | null | null |
src/SourceRange.cc
|
MarcSeebold/libclangmm
|
a882bec8d15715486d11affac5479fba42b1cce2
|
[
"MIT"
] | null | null | null |
src/SourceRange.cc
|
MarcSeebold/libclangmm
|
a882bec8d15715486d11affac5479fba42b1cce2
|
[
"MIT"
] | null | null | null |
#include "SourceRange.h"
clang::SourceRange::
SourceRange(clang::SourceLocation &start, clang::SourceLocation &end) {
cx_range = clang_getRange(start.cx_location, end.cx_location);
}
std::pair<clang::Offset, clang::Offset> clang::SourceRange::get_offsets() {
SourceLocation start(clang_getRangeStart(cx_range)), end(clang_getRangeEnd(cx_range));
return {start.get_offset(), end.get_offset()};
}
| 36.545455
| 88
| 0.766169
|
MarcSeebold
|
91fa0c05a84a334b9697bc2b356175a4fcd34361
| 1,282
|
cpp
|
C++
|
3111/7809563_AC_547MS_1356K.cpp
|
vandreas19/POJ_sol
|
4895764ab800e8c2c4b2334a562dec2f07fa243e
|
[
"MIT"
] | 18
|
2017-08-14T07:34:42.000Z
|
2022-01-29T14:20:29.000Z
|
3111/7809563_AC_547MS_1356K.cpp
|
pinepara/poj_solutions
|
4895764ab800e8c2c4b2334a562dec2f07fa243e
|
[
"MIT"
] | null | null | null |
3111/7809563_AC_547MS_1356K.cpp
|
pinepara/poj_solutions
|
4895764ab800e8c2c4b2334a562dec2f07fa243e
|
[
"MIT"
] | 14
|
2016-12-21T23:37:22.000Z
|
2021-07-24T09:38:57.000Z
|
#define _CRT_SECURE_NO_WARNINGS
#define DEBUG
#include<cstdio>
#include<cmath>
#include<algorithm>
const int JEWEL_NUM_MAX=100000;
int jewelNum,keep;
double averageValue;
struct Jewel{
int index,value,weight;
bool operator<(const Jewel &another){
//return value-weight*averageValue>another.value-another.weight*averageValue;
return value-another.value>(weight-another.weight)*averageValue;
}
};
Jewel jewels[JEWEL_NUM_MAX];
double getAverageValue(){
double valueSum=0.0,weightSum=0.0;
for(int i=0;i<keep;i++){
valueSum+=jewels[i].value;
weightSum+=jewels[i].weight;
}
return valueSum/weightSum;
}
int main(){
scanf("%d%d",&jewelNum,&keep);
for(int i=0;i<jewelNum;i++){
jewels[i].index=i;
scanf("%d%d",&jewels[i].value,&jewels[i].weight);
}
if(jewelNum!=keep){
averageValue=getAverageValue();
while(true){
std::nth_element(jewels,jewels+keep,jewels+jewelNum);
double newAverageValue=getAverageValue();
if(fabs(averageValue-newAverageValue)<=1e-8)
break;
averageValue=newAverageValue;
}
}
/*
printf("%d",jewels[0].index+1);
for(int i=1;i<keep;i++)
printf(" %d",jewels[i].index+1);
*/
for(int i=0;i<keep;i++)
printf("%d ",jewels[i].index+1);
printf("\n");
return 0;
}
| 22.892857
| 80
| 0.670827
|
vandreas19
|
6206a2b774ccb49cfcacd192dcd8004656402025
| 2,026
|
cpp
|
C++
|
src/Compiler/DumpFile.cpp
|
cstanze/blossom
|
2be90c6f16897a2acc1c40dad933a973e1ef2f57
|
[
"MIT"
] | 3
|
2021-08-16T22:22:02.000Z
|
2021-11-15T02:39:38.000Z
|
src/Compiler/DumpFile.cpp
|
cstanze/blossom
|
2be90c6f16897a2acc1c40dad933a973e1ef2f57
|
[
"MIT"
] | 1
|
2021-09-27T19:22:37.000Z
|
2022-03-29T12:41:24.000Z
|
src/Compiler/DumpFile.cpp
|
cstanze/blossom
|
2be90c6f16897a2acc1c40dad933a973e1ef2f57
|
[
"MIT"
] | null | null | null |
#include "Compiler/DumpFile.hpp"
Errors bmod_dump_file(Bytecode &bc, const char* filename) {
FILE* fp = fopen(filename, "wb");
if (fp == NULL) {
Err::set(E_FILE_IO, 0,
"Failed to open file '%s' for writing",
filename);
return E_FILE_IO;
}
// Write magic header
fwrite("BLSM", 1, 4, fp);
// Write version
size_t version_size = snprintf(NULL, 0, "%d.%d.%d", BLOSSOM_VERSION_MAJOR, BLOSSOM_VERSION_MINOR, BLOSSOM_VERSION_PATCH) + 1;
char *version = (char*)malloc(version_size);
sprintf(version, "%d.%d.%d", BLOSSOM_VERSION_MAJOR, BLOSSOM_VERSION_MINOR, BLOSSOM_VERSION_PATCH);
// Write version size
uint32_t version_size_le = htonl(version_size);
fwrite(&version_size_le, 1, 4, fp);
// Write version
fwrite(version, 1, version_size, fp);
// Write bytecode size
uint32_t bc_size_le = htonl(bc.size());
fwrite(&bc_size_le, 1, 4, fp);
// Write bytecode
for (size_t i = 0; i < bc.size(); i++) {
const Op &op = bc.get()[i];
// Write opcode op
uint32_t op_le = htonl(op.op);
fwrite(&op_le, 1, 4, fp);
// Write opcode dtype
uint32_t dtype_le = htonl(op.dtype);
fwrite(&dtype_le, 1, 4, fp);
// Write opcode rtype
uint32_t rtype_le = htonl(op.rtype);
fwrite(&rtype_le, 1, 4, fp);
// Write opcode data
if(op.rtype == ODT_IDEN || op.rtype == ODT_STRING) {
uint64_t data_size_le = htonll(strlen(op.data.s) + 1);
fwrite(&data_size_le, 1, sizeof(uint64_t), fp);
fwrite(op.data.s, 1, strlen(op.data.s) + 1, fp);
} else if (op.rtype == ODT_INT || op.rtype == ODT_FLOAT || op.rtype == ODT_SZ || op.rtype == ODT_BOOL) {
uint64_t data_le = htonll(op.rtype == ODT_BOOL ? (size_t)op.data.b : op.data.sz);
fwrite(&data_le, 1, sizeof(uint64_t), fp);
} // nothing to write for ODT_NIL
// Write src_id and idx
uint32_t src_id_le = htonl(op.src_id);
fwrite(&src_id_le, 1, 4, fp);
uint32_t idx_le = htonl(op.idx);
fwrite(&idx_le, 1, 4, fp);
}
return E_OK;
}
| 30.69697
| 127
| 0.628825
|
cstanze
|
620816532ff99c8f0343d4570b5ab995e3fe64c6
| 311
|
cpp
|
C++
|
Semester_1/Assignment 2/UVa 11934 - Magic Formula.cpp
|
ryankert01/Programming-1--1-hw7
|
c0b7fcf35000406d0bb3ae6cc862e71ea986d796
|
[
"Apache-2.0"
] | 2
|
2022-03-06T17:37:00.000Z
|
2022-03-06T17:37:02.000Z
|
Semester_1/Assignment 2/UVa 11934 - Magic Formula.cpp
|
ryankert01/Programming-1--1-hw7
|
c0b7fcf35000406d0bb3ae6cc862e71ea986d796
|
[
"Apache-2.0"
] | null | null | null |
Semester_1/Assignment 2/UVa 11934 - Magic Formula.cpp
|
ryankert01/Programming-1--1-hw7
|
c0b7fcf35000406d0bb3ae6cc862e71ea986d796
|
[
"Apache-2.0"
] | null | null | null |
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
int a, b, c, d, L;
while (cin >> a >> b >> c >> d >> L) {
if (!(a+b+c+d+L)) {
break;
}
int t=0;
for (int i=0; i <= L; ++i) {
if ((i * i * a + i * b + c) % d == 0) {
t++;
}
}
cout << t << endl;
}
return 0;
}
| 15.55
| 42
| 0.421222
|
ryankert01
|
6209be364ddfb249cd8b8a87e6d670776edc1feb
| 1,930
|
cpp
|
C++
|
Starters 17/PARPERM.cpp
|
Jks08/CodeChef
|
a8aec8a563c441176a36b8581031764e99f09833
|
[
"MIT"
] | 1
|
2021-09-17T13:10:04.000Z
|
2021-09-17T13:10:04.000Z
|
Starters 17/PARPERM.cpp
|
Jks08/CodeChef
|
a8aec8a563c441176a36b8581031764e99f09833
|
[
"MIT"
] | null | null | null |
Starters 17/PARPERM.cpp
|
Jks08/CodeChef
|
a8aec8a563c441176a36b8581031764e99f09833
|
[
"MIT"
] | null | null | null |
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define pb push_back
#define show(v) for(int i=0; i<(int)v.size(); ++i) cout<<v[i]<<" "
const ll max_size = 1e5+5;
bool prime[max_size];
void prime_seive(ll n)
{
memset(prime, true, sizeof(prime));
for(ll i=2; i*i<=n; i++)
{
if(prime[i])
{
for(ll j=i*i; j<=n; j+=i)
prime[j]=false;
}
}
}
void solve();
int main()
{
prime_seive(max_size);
ll t; cin>>t;
while(t--) {
solve();
}
return 0;
}
void solve()
{
ll n,k; cin>>n>>k;
if(k == 1 || n == 2) {
cout<<"YES"<<endl;
cout<<1<<endl; return ;
}
if(n == 3)
{
cout<<"YES"<<endl;
cout<<1<<" "<<2<<endl;
return;
}
vector<ll> dp;
for(ll i=2; i<=n; i++) {
if(prime[i]) dp.pb(i);
}
ll i = 0; vector<ll> B; B.pb(2);
for(i=1; i<dp.size(); i++)
{
ll val = (2 * dp[i]);
if(val <= n) {
B.pb(dp[i]);
continue;
}
else break;
}
ll rem = dp.size() - i;
vector<ll> v1,v2;
set<ll> s;
for(ll j=i; j<dp.size(); j++) {
v2.pb(dp[j]); s.insert(dp[j]);
}
for(ll i=2; i<=n; i++) {
if(s.find(i) == s.end()) {
v1.pb(i);
}
}
if(k >= v1.size())
{
cout<<"YES"<<endl;
show(v1); k -= v1.size();
while(k > 0) {
cout<<v2.back()<<" ";
v2.pop_back();
k--;
}
cout<<endl;
return;
}
if(k <= v2.size()+1)
{
cout<<"YES"<<endl;
cout<<1<<" "; k--;
while(k > 0) {
cout<<v2.back()<<" ";
v2.pop_back();
k--;
}
cout<<endl;
return;
}
cout<<"NO"<<endl;
return ;
}
| 16.495726
| 66
| 0.371503
|
Jks08
|
620c9b649176f3d40f4093fbba8b0ab088ffc87a
| 11,912
|
cpp
|
C++
|
tests/sim_sample.cpp
|
QuarticCat/toy-mips-simulator-in-800-lines
|
a3fe2cdb93789ef6971d89ca05d54d05bdd1d3dd
|
[
"MIT"
] | null | null | null |
tests/sim_sample.cpp
|
QuarticCat/toy-mips-simulator-in-800-lines
|
a3fe2cdb93789ef6971d89ca05d54d05bdd1d3dd
|
[
"MIT"
] | null | null | null |
tests/sim_sample.cpp
|
QuarticCat/toy-mips-simulator-in-800-lines
|
a3fe2cdb93789ef6971d89ca05d54d05bdd1d3dd
|
[
"MIT"
] | null | null | null |
#include <filesystem>
#include <fstream>
#include <iostream>
#include <iterator>
#include "test_util.hpp"
// clang-format off
SIM_TEST(SimSample, a_plus_b,
R"(
.text
addi $v0, $zero, 5
syscall
add $t0, $zero, $v0
addi $v0, $zero, 5
syscall
add $t1, $zero, $v0
add $a0, $t1, $t0
addi $v0, $zero, 1
syscall
addi $v0, $zero, 10
syscall
)",
"114\n514\n",
"628"
);
SIM_TEST(SimSample, fib,
R"(
.data
# .align 2
FIB_START: .asciiz "fib("
# .align 2
FIB_MID: .asciiz ") = "
# .align 2
LINE_END: .asciiz "\n"
.text
addi $v0, $zero, 5
syscall
add $s1, $zero, $v0
lui $at, 80
ori $a0, $at, 0
addi $v0, $zero, 4
syscall
addu $a0, $s1, $zero
addi $v0, $zero, 1
syscall
lui $at, 80
ori $a0, $at, 8
addi $v0, $zero, 4
syscall
add $a0, $zero, $s1
jal fibonacci
add $a0, $zero, $v0
addi $v0, $zero, 1
syscall
lui $at, 80
ori $a0, $at, 16
addi $v0, $zero, 4
syscall
addi $v0, $zero, 10
syscall
fibonacci:
addi $sp, $sp, -12
sw $ra, 8($sp)
sw $s0, 4($sp)
sw $s1, 0($sp)
add $s0, $a0, $zero
addi $v0, $zero, 1
slti $t7, $s0, 3
bne $t7, $zero, fibonacciExit
addi $a0, $s0, -1
jal fibonacci
add $s1, $zero, $v0
addi $a0, $s0, -2
jal fibonacci
add $v0, $s1, $v0
fibonacciExit:
lw $ra, 8($sp)
lw $s0, 4($sp)
lw $s1, 0($sp)
addi $sp, $sp, 12
jr $ra
)",
"16\n",
"fib(16) = 987\n"
);
// clang-format on
TEST(SimSample, memcpy_hello_world) {
std::istringstream asm_in(R"(
.data
# .align 2
HELLO: .ascii "hello, world\n"
LENGTH: .word 13
.text
lui $at, 80
ori $s0, $at, 16
lw $s0, 0($s0)
lui $at, 80
ori $s3, $at, 0
addi $v0, $zero, 9
addi $a0, $zero, 16
syscall
addu $s1, $zero, $v0
addu $a0, $zero, $v0
addu $a1, $zero, $s3
addu $a2, $zero, $s0
jal __builtin_memcpy
addi $v0, $zero, 15
addi $a0, $zero, 1
addu $a1, $zero, $s1
addu $a2, $zero, $s0
syscall
addi $v0, $zero, 10
syscall
__builtin_memcpy_aligned_large:
addi $t7, $a2, -4
blez $t7, __builtin_memcpy_bytes
lw $t0, 0($a1)
sw $t0, 0($a0)
addi $a2, $a2, -4
addiu $a1, $a1, 4
addiu $a0, $a0, 4
j __builtin_memcpy_aligned_large
__builtin_memcpy_bytes:
beq $a2, $zero, __builtin_memcpy_return
lbu $t0, 0($a1)
sb $t0, 0($a0)
addi $a2, $a2, -1
addiu $a1, $a1, 1
addiu $a0, $a0, 1
j __builtin_memcpy_bytes
__builtin_memcpy_return:
jr $ra
__builtin_memcpy:
addi $t7, $a2, -4
blez $t7, __builtin_memcpy_bytes
xor $t8, $a0, $a1
andi $t8, $t0, 3
subu $t1, $zero, $a0
andi $t1, $t1, 3
__builtin_memcpy_prepare:
beq $t1, $zero, __builtin_memcpy_check
lbu $t0, 0($a1)
sb $t0, 0($a0)
addi $a2, $a2, -1
addi $t1, $t1, -1
addiu $a1, $a1, 1
addiu $a0, $a0, 1
j __builtin_memcpy_prepare
__builtin_memcpy_check:
beq $t8, $zero, __builtin_memcpy_aligned_large
__builtin_memcpy_unaligned_large:
addi $t7, $a2, -4
blez $t7, __builtin_memcpy_bytes
lwl $t0, 0($a1)
lwr $t0, 1($a1)
sw $t0, 0($a0)
addi $a2, $a2, -4
addiu $a1, $a1, 4
addiu $a0, $a0, 4
j __builtin_memcpy_unaligned_large
)");
std::istringstream in("");
std::string ans("hello, world\n");
testing::internal::CaptureStdout();
auto [mem, text_end] = assemble(asm_in);
try {
simulate(in, std::cout, std::move(mem), text_end);
} catch (const ExitError& e) {
EXPECT_EQ(e.code(), 0); // prevent folding
}
EXPECT_EQ(testing::internal::GetCapturedStdout(), ans);
}
TEST(SimSample, many_tests) {
std::istringstream asm_in(R"(
.data #data segment starts at addr 0x00500000 (1MB for text segment)
str1: .asciiz "Testing lb,sb,read/print_char,sbrk" #at 0x00500000
str2: .asciiz "Please enter a char:" #at 0x00500024
str3: .asciiz "The char you entered is:" #at 0x0050003C
str4: .asciiz "Testing for .ascii" #at 0x00500058
str5: .ascii "aaaa" #at 0x0050006C
str6: .ascii "bbbb" #at 0x00500070
str7: .asciiz "ccc" #at 0x00500074
str8: .asciiz "Testing for fileIO syscalls" #at 0x00500078
str9: .asciiz "_tmp_file.txt" #at 0x00500094
str10: .asciiz "If you see this, your fileIO is all cool" #at 0x005000A4
str11: .asciiz "num of chars printed to file:" #at 0x005000D0
str12: .asciiz "Goodbye" #at 0x005000F0
str13: .asciiz "You should see aaaabbbbccc, bbbbccc, ccc for three strings" #at 0x005000F8
half: .half 1,2 #at 0x00500134
byte: .byte 1,2,3,4 #at 0x00500138
str14: .asciiz "Testing for .half,.byte" #at 0x0050013C
str15: .asciiz "For half, the output should be: 65539 in decimal, and you have:" #at 0x00500154
str16: .asciiz "For byte, the output should be: 16909059 in decimal, and you have:" #at 0x00500194
.text
main: addi $a0,$a0, 80 #load str1 addr to $a0 and print.
sll $a0,$a0,16
addi $v0, $zero, 4
syscall
lui $a0, 80 #load str2 addr to $a0 and print.
ori $a0, $a0, 36
addi $v0, $zero, 4
syscall
addi $v0, $v0, 8 #$v0 has 12, read char.
syscall
add $t0, $zero, $v0 #char read now in $t0
addi $v0, $zero, 9 #calling sbrk
addi $a0, $zero, 4
syscall
add $t1, $zero, $v0
sb $t0, 0($t1)
lui $a0, 80 #load str3 addr to $a0 and print.
ori $a0, $a0, 60
addi $v0, $zero, 4
syscall
lb $a0, 0($t1)
addi $v0, $v0, 7 #print char
syscall
############################################
addi $a0,$zero, 80 #print str4
sll $a0, $a0, 20
srl $a0, $a0, 4
ori $a0, $a0, 88
addi $v0, $zero, 4
syscall
lui $a0, 80 #print str5
ori $a0, $a0, 108
addi $v0, $zero, 4
syscall
lui $a0, 80 #print str6
ori $a0, $a0, 112
addi $v0, $zero, 4
syscall
lui $a0, 80 #print str7
ori $a0, $a0, 116
addi $v0, $zero, 4
syscall
lui $a0, 80 #print str13
ori $a0, $a0, 248
addi $v0, $zero, 4
syscall
############################################
lui $a0, 80 #print str8
ori $a0, $a0, 120
addi $v0, $zero, 4
syscall
lui $a0, 80 #open file
ori $a0, $a0, 148
addi $a1, $zero, 2
addi $v0, $v0, 9
syscall
add $t0, $zero, $v0 #transfer the file descriptor to $t0
addi $v0, $zero, 9 #sbrk
addi $a0, $zero, 60
syscall
add $t1, $zero, $v0 #transfer the allocated mem to $t1
add $a0, $t0, $zero #write str10 to file
lui $a1, 80
ori $a1, $a1, 164
addi $a2, $zero, 40
addi $v0, $zero, 15
syscall
add $t2, $zero, $v0 #transfer the num of chars written to $t2
lui $a0, 80 #print str11
ori $a0, $a0, 208
addi $v0, $zero, 4
syscall
add $a0, $zero, $t2 #print num of chars written to file
addi $t5, $zero, 3
sub $v0, $v0, $t5
syscall
addi $v0, $zero, 16 #close file
add $a0, $zero, $t0
syscall
lui $a0, 80 #open the file again
ori $a0, $a0, 148
addi $a1, $zero, 2
addi $v0, $zero, 13
syscall
addi $a0, $t0, 0 #read from the file
addi $a1, $t1, 0
addi $a2, $zero, 41
addi $v0, $zero, 14
syscall
addi $v0, $zero, 16 #close file
add $a0, $zero, $t0
syscall
add $a0, $zero, $t1 #print the content read from file
addi $v0, $zero, 4
syscall
############################################
lui $a0, 80 #print str14
ori $a0, $a0, 316
addi $v0, $zero, 4
syscall
lui $t0, 80 #load half array
ori $t0, $t0, 308
lui $a0, 80 #print str15
ori $a0, $a0, 340
addi $v0, $zero, 4
syscall
lh $a0, 0($t0)
sll $a0, $a0, 16
lh $t2, 2($t0)
or $a0, $a0,$t2
addi $a0, $a0, 1
addi $v0, $zero, 1
syscall
lui $a0, 80 #print str16
ori $a0, $a0, 404
addi $v0, $zero, 4
syscall
lui $t1, 80 #load byte array
ori $t1, $t1, 312
lb $t2, 0($t1)
sll $t2, $t2, 24
lb $t3, 1($t1)
sll $t3, $t3, 16
lb $t4, 2($t1)
sll $t4, $t4, 8
lb $t5, 3($t1)
or $a0, $t2,$t3
or $a0, $a0,$t4
or $a0, $a0,$t5
addi $a0, $a0, -1
addi $v0, $zero, 1
syscall
############################################
lui $a0, 80 #print str12
ori $a0, $a0, 240
addi $v0, $zero, 4
syscall
addi $v0, $zero, 10 #exit
syscall
)");
std::istringstream in("5");
std::ostringstream out;
std::string ans("Testing lb,sb,read/print_char,sbrkPlease enter a char:"
"The char you entered is:5"
"Testing for .asciiaaaabbbbcccbbbbcccccc"
"You should see aaaabbbbccc, bbbbccc, ccc for three strings"
"Testing for fileIO syscalls"
"num of chars printed to file:40"
"If you see this, your fileIO is all cool"
"Testing for .half,.byte"
"For half, the output should be: 65539 in decimal, and you have:65539"
"For byte, the output should be: 16909059 in decimal, and you have:16909059"
"Goodbye");
std::string file_ans("If you see this, your fileIO is all cool");
std::string file_name("_tmp_file.txt");
std::ofstream o_file(file_name);
auto [mem, text_end] = assemble(asm_in);
try {
simulate(in, out, std::move(mem), text_end);
} catch (const ExitError& e) {
EXPECT_EQ(e.code(), 0); // prevent folding
}
std::ifstream i_file(file_name);
EXPECT_EQ(out.str(), ans);
EXPECT_EQ(std::string(std::istreambuf_iterator<char>(i_file), std::istreambuf_iterator<char>{}),
file_ans);
std::filesystem::remove(file_name);
}
| 27.702326
| 107
| 0.453156
|
QuarticCat
|
62172d42da6b75c0194c3031a134c460a356d5c0
| 1,149
|
hpp
|
C++
|
libs/PhiCore/include/phi/type_traits/integral_constant.hpp
|
AMS21/Phi
|
d62d7235dc5307dd18607ade0f95432ae3a73dfd
|
[
"MIT"
] | 3
|
2020-12-21T13:47:35.000Z
|
2022-03-16T23:53:21.000Z
|
libs/PhiCore/include/phi/type_traits/integral_constant.hpp
|
AMS21/Phi
|
d62d7235dc5307dd18607ade0f95432ae3a73dfd
|
[
"MIT"
] | 53
|
2020-08-07T07:46:57.000Z
|
2022-02-12T11:07:08.000Z
|
libs/PhiCore/include/phi/type_traits/integral_constant.hpp
|
AMS21/Phi
|
d62d7235dc5307dd18607ade0f95432ae3a73dfd
|
[
"MIT"
] | 1
|
2020-08-19T15:50:02.000Z
|
2020-08-19T15:50:02.000Z
|
#ifndef INCG_PHI_CORE_TYPE_TRAITS_INTEGRAL_CONSTANT_HPP
#define INCG_PHI_CORE_TYPE_TRAITS_INTEGRAL_CONSTANT_HPP
#include "phi/phi_config.hpp"
#if PHI_HAS_EXTENSION_PRAGMA_ONCE()
# pragma once
#endif
#include "phi/compiler_support/inline.hpp"
#include "phi/compiler_support/nodiscard.hpp"
DETAIL_PHI_BEGIN_NAMESPACE()
template <typename TypeT, TypeT Value>
struct integral_constant
{
using this_type = integral_constant<TypeT, Value>;
using value_type = TypeT;
using type = integral_constant<TypeT, Value>;
static constexpr TypeT value = Value;
PHI_NODISCARD PHI_ALWAYS_INLINE constexpr operator TypeT() const noexcept
{
return value;
}
PHI_NODISCARD PHI_ALWAYS_INLINE constexpr TypeT operator()() const noexcept
{
return value;
}
};
template <typename TypeT, TypeT Value>
constexpr TypeT integral_constant<TypeT, Value>::value;
template <bool Value>
using bool_constant = integral_constant<bool, Value>;
using true_type = bool_constant<true>;
using false_type = bool_constant<false>;
DETAIL_PHI_END_NAMESPACE()
#endif // INCG_PHI_CORE_TYPE_TRAITS_INTEGRAL_CONSTANT_HPP
| 24.446809
| 79
| 0.770235
|
AMS21
|
6217a718561673d06e74609a13b11fa8d6881b42
| 1,409
|
cpp
|
C++
|
Engine/lib/collada/src/dae/daeDatabase.cpp
|
vbillet/Torque3D
|
ece8823599424ea675e5f79d9bcb44e42cba8cae
|
[
"MIT"
] | 2,113
|
2015-01-01T11:23:01.000Z
|
2022-03-28T04:51:46.000Z
|
Engine/lib/collada/src/dae/daeDatabase.cpp
|
vbillet/Torque3D
|
ece8823599424ea675e5f79d9bcb44e42cba8cae
|
[
"MIT"
] | 948
|
2015-01-02T01:50:00.000Z
|
2022-02-27T05:56:40.000Z
|
Engine/lib/collada/src/dae/daeDatabase.cpp
|
vbillet/Torque3D
|
ece8823599424ea675e5f79d9bcb44e42cba8cae
|
[
"MIT"
] | 944
|
2015-01-01T09:33:53.000Z
|
2022-03-15T22:23:03.000Z
|
/*
* Copyright 2007 Sony Computer Entertainment Inc.
*
* Licensed under the SCEA Shared Source License, Version 1.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://research.scea.com/scea_shared_source_license.html
*
* 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 "dae/daeDatabase.h"
using namespace std;
daeDatabase::daeDatabase(DAE& dae) : dae(dae) { }
DAE* daeDatabase::getDAE() {
return &dae;
}
daeDocument* daeDatabase::getDoc(daeUInt index) {
return getDocument(index);
}
daeElement* daeDatabase::idLookup(const string& id, daeDocument* doc) {
vector<daeElement*> elts = idLookup(id);
for (size_t i = 0; i < elts.size(); i++)
if (elts[i]->getDocument() == doc)
return elts[i];
return NULL;
}
vector<daeElement*> daeDatabase::typeLookup(daeInt typeID, daeDocument* doc) {
vector<daeElement*> result;
typeLookup(typeID, result);
return result;
}
vector<daeElement*> daeDatabase::sidLookup(const string& sid, daeDocument* doc) {
vector<daeElement*> result;
sidLookup(sid, result, doc);
return result;
}
| 30.630435
| 103
| 0.733854
|
vbillet
|
621e73ce4b81cb4dff1bd04561944dfe138fc541
| 1,204
|
cpp
|
C++
|
NWNXLib/API/Mac/API/CCallbackImplTemplated8.cpp
|
acaos/nwnxee-unified
|
0e4c318ede64028c1825319f39c012e168e0482c
|
[
"MIT"
] | 1
|
2019-06-04T04:30:24.000Z
|
2019-06-04T04:30:24.000Z
|
NWNXLib/API/Mac/API/CCallbackImplTemplated8.cpp
|
presscad/nwnee
|
0f36b281524e0b7e9796bcf30f924792bf9b8a38
|
[
"MIT"
] | null | null | null |
NWNXLib/API/Mac/API/CCallbackImplTemplated8.cpp
|
presscad/nwnee
|
0f36b281524e0b7e9796bcf30f924792bf9b8a38
|
[
"MIT"
] | 1
|
2019-10-20T07:54:45.000Z
|
2019-10-20T07:54:45.000Z
|
#include "CCallbackImplTemplated8.hpp"
#include "API/Functions.hpp"
#include "Platform/ASLR.hpp"
namespace NWNXLib {
namespace API {
int32_t CCallbackImplTemplated8::GetCallbackSizeBytes()
{
return CCallbackImplTemplated8__GetCallbackSizeBytes(this);
}
void CCallbackImplTemplated8::Run(void* a0, int32_t a1, uint64_t a2)
{
return CCallbackImplTemplated8__Run(this, a0, a1, a2);
}
int32_t CCallbackImplTemplated8__GetCallbackSizeBytes(CCallbackImplTemplated8* thisPtr)
{
using FuncPtrType = int32_t(__attribute__((cdecl)) *)(CCallbackImplTemplated8*);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CCallbackImplTemplated8__GetCallbackSizeBytes);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
return func(thisPtr);
}
void CCallbackImplTemplated8__Run(CCallbackImplTemplated8* thisPtr, void* a0, int32_t a1, uint64_t a2)
{
using FuncPtrType = void(__attribute__((cdecl)) *)(CCallbackImplTemplated8*, void*, int32_t, uint64_t);
uintptr_t address = Platform::ASLR::GetRelocatedAddress(Functions::CCallbackImplTemplated8__Run);
FuncPtrType func = reinterpret_cast<FuncPtrType>(address);
return func(thisPtr, a0, a1, a2);
}
}
}
| 31.684211
| 118
| 0.784884
|
acaos
|
621fa679dda988188b6892a287d4b40f6a50a8c4
| 1,027
|
cpp
|
C++
|
src/core/primitives.cpp
|
YottaYocta/Asc3
|
48e654461a2ec7ccde3f06145a1af13cde34dcbb
|
[
"MIT"
] | null | null | null |
src/core/primitives.cpp
|
YottaYocta/Asc3
|
48e654461a2ec7ccde3f06145a1af13cde34dcbb
|
[
"MIT"
] | null | null | null |
src/core/primitives.cpp
|
YottaYocta/Asc3
|
48e654461a2ec7ccde3f06145a1af13cde34dcbb
|
[
"MIT"
] | null | null | null |
#include <core/primitives.h>
sphere::sphere() : sphere(vec3 {0, 0, -1}, 1) {}
sphere::sphere(const vec3& c, double r) : center {c}, radius {r} {}
const vec3& sphere::get_center() const
{
return center;
}
void sphere::set_center(const vec3& c)
{
center = c;
}
double sphere::get_radius() const
{
return radius;
}
void sphere::set_radius(double r)
{
radius = r;
}
bool sphere::intersects(const ray& r, path_info& info, double far) const
{
vec3 oc {r.origin - center};
double a {r.dir.length_squared()};
double b {dot(r.dir, oc)};
double c {oc.length_squared() - radius * radius};
double discriminant {b * b - a * c};
if (discriminant < 0)
return false;
double t = (-b - sqrt(b * b - a * c)) / a;
if (t < 0.001 || t > far)
{
t = (-b + sqrt(b * b - a * c)) / a;
if (t < 0.001 || t > far)
return false;
}
info.intersection = point3 {r.origin + r.dir * t};
info.normal = normalized(info.intersection - center);
info.t = t;
info.material_hit = material;
return true;
}
| 20.959184
| 72
| 0.602726
|
YottaYocta
|
622497b005a416e7314722aac575eb8a7da833dc
| 4,826
|
cpp
|
C++
|
sfml/src/Audio/SFMLAudioMusicSource.cpp
|
hhsaez/crimild
|
e3efee09489939338df55e8af9a1f9ddc01301f7
|
[
"BSD-3-Clause"
] | 36
|
2015-03-12T10:42:36.000Z
|
2022-01-12T04:20:40.000Z
|
sfml/src/Audio/SFMLAudioMusicSource.cpp
|
hhsaez/crimild
|
e3efee09489939338df55e8af9a1f9ddc01301f7
|
[
"BSD-3-Clause"
] | 1
|
2015-12-17T00:25:43.000Z
|
2016-02-20T12:00:57.000Z
|
sfml/src/Audio/SFMLAudioMusicSource.cpp
|
hhsaez/crimild
|
e3efee09489939338df55e8af9a1f9ddc01301f7
|
[
"BSD-3-Clause"
] | 6
|
2017-06-17T07:57:53.000Z
|
2019-04-09T21:11:24.000Z
|
/*
* Copyright (c) 2013, Hernan Saez
* 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 <organization> nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "SFMLAudioMusicSource.hpp"
#include "Exceptions/FileNotFoundException.hpp"
using namespace crimild;
using namespace crimild::audio;
using namespace crimild::sfml;
SFMLAudioMusicSource::SFMLAudioMusicSource( std::string filename )
{
if ( !_music.openFromFile( filename ) ) {
throw FileNotFoundException( filename );
}
}
SFMLAudioMusicSource::~SFMLAudioMusicSource( void )
{
}
void SFMLAudioMusicSource::play( void )
{
_music.play();
}
void SFMLAudioMusicSource::pause( void )
{
_music.pause();
}
void SFMLAudioMusicSource::stop( void )
{
_music.stop();
}
crimild::Real32 SFMLAudioMusicSource::getDuration( void ) const
{
return _music.getDuration().asSeconds();
}
void SFMLAudioMusicSource::setLoop( crimild::Bool loop )
{
_music.setLoop( loop );
}
crimild::Bool SFMLAudioMusicSource::shouldLoop( void ) const
{
return _music.getLoop();
}
AudioSource::Status SFMLAudioMusicSource::getStatus( void ) const
{
switch ( _music.getStatus() ) {
case sf::SoundSource::Status::Stopped:
return AudioSource::Status::STOPPED;
break;
case sf::SoundSource::Status::Playing:
return AudioSource::Status::PLAYING;
break;
case sf::SoundSource::Status::Paused:
return AudioSource::Status::PAUSED;
break;
}
return AudioSource::Status::STOPPED;
}
void SFMLAudioMusicSource::setPlayingOffset( crimild::Real32 offset )
{
_music.setPlayingOffset( sf::seconds( offset ) );
}
crimild::Real32 SFMLAudioMusicSource::getPlayingOffset( void ) const
{
return _music.getPlayingOffset().asSeconds();
}
void SFMLAudioMusicSource::setVolume( crimild::Real32 volume )
{
_music.setVolume( 100.0f * volume );
}
crimild::Real32 SFMLAudioMusicSource::getVolume( void ) const
{
return 0.01f * _music.getVolume();
}
void SFMLAudioMusicSource::setTransformation( const Transformation &t )
{
AudioSource::setTransformation( t );
const auto position = t.getTranslate();
_music.setPosition( position.x(), position.y(), position.z() );
}
void SFMLAudioMusicSource::setRelativeToListener( crimild::Bool relative )
{
_music.setRelativeToListener( relative );
}
crimild::Bool SFMLAudioMusicSource::isRelativeToListener( void ) const
{
return _music.isRelativeToListener();
}
void SFMLAudioMusicSource::setMinDistance( crimild::Real32 distance )
{
_music.setMinDistance( distance );
}
crimild::Real32 SFMLAudioMusicSource::getMinDistance( void ) const
{
return _music.getMinDistance();
}
void SFMLAudioMusicSource::setAttenuation( crimild::Real32 attenuation )
{
_music.setAttenuation( attenuation );
}
crimild::Real32 SFMLAudioMusicSource::getAttenuation( void ) const
{
return _music.getAttenuation();
}
void SFMLAudioMusicSource::onGetData( AudioSource::GetDataCallback const &callback )
{
_music.setOnGetDataCallback( callback );
}
bool SFMLAudioMusicSource::CustomMusic::onGetData( sf::SoundStream::Chunk &data )
{
auto ret = sf::Music::onGetData( data );
if ( _callback != nullptr ) {
_callback( AudioSource::Chunk {
data.samples,
data.sampleCount
});
}
return ret;
}
crimild::UInt32 SFMLAudioMusicSource::getChannelCount( void ) const
{
return _music.getChannelCount();
}
crimild::UInt32 SFMLAudioMusicSource::getSampleRate( void ) const
{
return _music.getSampleRate();
}
| 26.086486
| 84
| 0.750725
|
hhsaez
|
622c8cf4dd5b43a53dd025b2bda0e12fd5ce8aa4
| 19,031
|
cpp
|
C++
|
src/hwenc_msdk/msdk_video_encoder.cpp
|
tetsu-koba/momo
|
0082e8cdcaba988d1e4ae3e79f57066b4a2857c5
|
[
"Apache-2.0"
] | null | null | null |
src/hwenc_msdk/msdk_video_encoder.cpp
|
tetsu-koba/momo
|
0082e8cdcaba988d1e4ae3e79f57066b4a2857c5
|
[
"Apache-2.0"
] | null | null | null |
src/hwenc_msdk/msdk_video_encoder.cpp
|
tetsu-koba/momo
|
0082e8cdcaba988d1e4ae3e79f57066b4a2857c5
|
[
"Apache-2.0"
] | null | null | null |
#include "msdk_video_encoder.h"
#include <iostream>
// libyuv
#include <libyuv.h>
#include "msdk_utils.h"
const int kLowH264QpThreshold = 34;
const int kHighH264QpThreshold = 40;
MsdkVideoEncoder::MsdkVideoEncoder(std::shared_ptr<MsdkSession> session,
mfxU32 codec)
: session_(session), codec_(codec), bitrate_adjuster_(0.5, 0.95) {}
MsdkVideoEncoder::~MsdkVideoEncoder() {}
std::unique_ptr<MFXVideoENCODE> MsdkVideoEncoder::CreateEncoder(
std::shared_ptr<MsdkSession> session,
mfxU32 codec,
int width,
int height,
int framerate,
int target_kbps,
int max_kbps,
bool init) {
mfxStatus sts = MFX_ERR_NONE;
mfxVideoParam param;
memset(¶m, 0, sizeof(param));
param.mfx.CodecId = codec;
if (codec == MFX_CODEC_VP8) {
//param.mfx.CodecProfile = MFX_PROFILE_VP8_0;
} else if (codec == MFX_CODEC_VP9) {
//param.mfx.CodecProfile = MFX_PROFILE_VP9_0;
} else if (codec == MFX_CODEC_AVC) {
//param.mfx.CodecProfile = MFX_PROFILE_AVC_HIGH;
//param.mfx.CodecLevel = MFX_LEVEL_AVC_51;
//param.mfx.CodecProfile = MFX_PROFILE_AVC_MAIN;
//param.mfx.CodecLevel = MFX_LEVEL_AVC_1;
} else if (codec == MFX_CODEC_AV1) {
//param.mfx.CodecProfile = MFX_PROFILE_AV1_MAIN;
}
param.mfx.TargetUsage = MFX_TARGETUSAGE_BALANCED;
//param.mfx.BRCParamMultiplier = 1;
//param.mfx.InitialDelayInKB = target_kbps;
param.mfx.TargetKbps = target_kbps;
param.mfx.MaxKbps = max_kbps;
param.mfx.RateControlMethod = MFX_RATECONTROL_VBR;
//param.mfx.NumSlice = 1;
//param.mfx.NumRefFrame = 1;
param.mfx.FrameInfo.FrameRateExtN = framerate;
param.mfx.FrameInfo.FrameRateExtD = 1;
param.mfx.FrameInfo.FourCC = MFX_FOURCC_NV12;
param.mfx.FrameInfo.ChromaFormat = MFX_CHROMAFORMAT_YUV420;
param.mfx.FrameInfo.PicStruct = MFX_PICSTRUCT_PROGRESSIVE;
param.mfx.FrameInfo.CropX = 0;
param.mfx.FrameInfo.CropY = 0;
param.mfx.FrameInfo.CropW = width;
param.mfx.FrameInfo.CropH = height;
// Width must be a multiple of 16
// Height must be a multiple of 16 in case of frame picture and a multiple of 32 in case of field picture
param.mfx.FrameInfo.Width = (width + 15) / 16 * 16;
param.mfx.FrameInfo.Height = (height + 15) / 16 * 16;
//param.mfx.GopOptFlag = MFX_GOP_STRICT | MFX_GOP_CLOSED;
//param.mfx.IdrInterval = codec_settings->H264().keyFrameInterval;
//param.mfx.IdrInterval = 0;
param.mfx.GopRefDist = 1;
//param.mfx.EncodedOrder = 0;
param.AsyncDepth = 1;
param.IOPattern =
MFX_IOPATTERN_IN_SYSTEM_MEMORY | MFX_IOPATTERN_OUT_SYSTEM_MEMORY;
mfxExtBuffer* ext_buffers[10];
mfxExtCodingOption ext_coding_option;
mfxExtCodingOption2 ext_coding_option2;
int ext_buffers_size = 0;
if (codec == MFX_CODEC_AVC) {
memset(&ext_coding_option, 0, sizeof(ext_coding_option));
ext_coding_option.Header.BufferId = MFX_EXTBUFF_CODING_OPTION;
ext_coding_option.Header.BufferSz = sizeof(ext_coding_option);
ext_coding_option.AUDelimiter = MFX_CODINGOPTION_OFF;
ext_coding_option.MaxDecFrameBuffering = 1;
//ext_coding_option.NalHrdConformance = MFX_CODINGOPTION_OFF;
//ext_coding_option.VuiVclHrdParameters = MFX_CODINGOPTION_ON;
//ext_coding_option.SingleSeiNalUnit = MFX_CODINGOPTION_ON;
//ext_coding_option.RefPicMarkRep = MFX_CODINGOPTION_OFF;
//ext_coding_option.PicTimingSEI = MFX_CODINGOPTION_OFF;
//ext_coding_option.RecoveryPointSEI = MFX_CODINGOPTION_OFF;
//ext_coding_option.FramePicture = MFX_CODINGOPTION_OFF;
//ext_coding_option.FieldOutput = MFX_CODINGOPTION_ON;
memset(&ext_coding_option2, 0, sizeof(ext_coding_option2));
ext_coding_option2.Header.BufferId = MFX_EXTBUFF_CODING_OPTION2;
ext_coding_option2.Header.BufferSz = sizeof(ext_coding_option2);
ext_coding_option2.RepeatPPS = MFX_CODINGOPTION_ON;
//ext_coding_option2.MaxSliceSize = 1;
//ext_coding_option2.AdaptiveI = MFX_CODINGOPTION_ON;
ext_buffers[0] = (mfxExtBuffer*)&ext_coding_option;
ext_buffers[1] = (mfxExtBuffer*)&ext_coding_option2;
ext_buffers_size = 2;
}
if (ext_buffers_size != 0) {
param.ExtParam = ext_buffers;
param.NumExtParam = ext_buffers_size;
}
std::unique_ptr<MFXVideoENCODE> encoder(new MFXVideoENCODE(session->session));
// MFX_ERR_NONE The function completed successfully.
// MFX_ERR_UNSUPPORTED The function failed to identify a specific implementation for the required features.
// MFX_WRN_PARTIAL_ACCELERATION The underlying hardware does not fully support the specified video parameters; The encoding may be partially accelerated. Only SDK HW implementations may return this status code.
// MFX_WRN_INCOMPATIBLE_VIDEO_PARAM The function detected some video parameters were incompatible with others; incompatibility resolved.
mfxVideoParam bk_param;
memcpy(&bk_param, ¶m, sizeof(bk_param));
sts = encoder->Query(¶m, ¶m);
if (sts < 0) {
memcpy(¶m, &bk_param, sizeof(bk_param));
// 失敗したら LowPower ON にした状態でもう一度確認する
param.mfx.LowPower = MFX_CODINGOPTION_ON;
if (codec == MFX_CODEC_AVC) {
param.mfx.RateControlMethod = MFX_RATECONTROL_CQP;
param.mfx.QPI = 25;
param.mfx.QPP = 33;
param.mfx.QPB = 40;
//param.IOPattern = MFX_IOPATTERN_IN_SYSTEM_MEMORY;
}
memcpy(&bk_param, ¶m, sizeof(bk_param));
sts = encoder->Query(¶m, ¶m);
if (sts < 0) {
const char* codec_str = codec == MFX_CODEC_VP8 ? "MFX_CODEC_VP8"
: codec == MFX_CODEC_VP9 ? "MFX_CODEC_VP9"
: codec == MFX_CODEC_AV1 ? "MFX_CODEC_AV1"
: codec == MFX_CODEC_AVC ? "MFX_CODEC_AVC"
: "MFX_CODEC_UNKNOWN";
//std::cerr << "Unsupported encoder codec: codec=" << codec_str
// << std::endl;
return nullptr;
}
}
//#define F(NAME) \
// if (bk_param.NAME != param.NAME) \
// std::cout << "param " << #NAME << " old=" << bk_param.NAME \
// << " new=" << param.NAME << std::endl
//
// F(mfx.LowPower);
// F(mfx.BRCParamMultiplier);
// F(mfx.FrameInfo.FrameRateExtN);
// F(mfx.FrameInfo.FrameRateExtD);
// F(mfx.FrameInfo.FourCC);
// F(mfx.FrameInfo.ChromaFormat);
// F(mfx.FrameInfo.PicStruct);
// F(mfx.FrameInfo.CropX);
// F(mfx.FrameInfo.CropY);
// F(mfx.FrameInfo.CropW);
// F(mfx.FrameInfo.CropH);
// F(mfx.FrameInfo.Width);
// F(mfx.FrameInfo.Height);
// F(mfx.CodecId);
// F(mfx.CodecProfile);
// F(mfx.CodecLevel);
// F(mfx.GopPicSize);
// F(mfx.GopRefDist);
// F(mfx.GopOptFlag);
// F(mfx.IdrInterval);
// F(mfx.TargetUsage);
// F(mfx.RateControlMethod);
// F(mfx.InitialDelayInKB);
// F(mfx.TargetKbps);
// F(mfx.MaxKbps);
// F(mfx.BufferSizeInKB);
// F(mfx.NumSlice);
// F(mfx.NumRefFrame);
// F(mfx.EncodedOrder);
// F(mfx.DecodedOrder);
// F(mfx.ExtendedPicStruct);
// F(mfx.TimeStampCalc);
// F(mfx.SliceGroupsPresent);
// F(mfx.MaxDecFrameBuffering);
// F(mfx.EnableReallocRequest);
// F(AsyncDepth);
// F(IOPattern);
//#undef F
//if (sts != MFX_ERR_NONE) {
// const char* codec_str = codec == MFX_CODEC_VP8 ? "MFX_CODEC_VP8"
// : codec == MFX_CODEC_VP9 ? "MFX_CODEC_VP9"
// : codec == MFX_CODEC_AV1 ? "MFX_CODEC_AV1"
// : codec == MFX_CODEC_AVC ? "MFX_CODEC_AVC"
// : "MFX_CODEC_UNKNOWN";
// std::cerr << "Supported specified codec but has warning: codec="
// << codec_str << " sts=" << sts << std::endl;
//}
if (init) {
sts = encoder->Init(¶m);
if (sts != MFX_ERR_NONE) {
RTC_LOG(LS_ERROR) << "Failed to Init: sts=" << sts;
return nullptr;
}
}
return encoder;
}
bool MsdkVideoEncoder::IsSupported(std::shared_ptr<MsdkSession> session,
mfxU32 codec) {
auto encoder = CreateEncoder(session, codec, 1920, 1080, 30, 10, 20, false);
return encoder != nullptr;
}
int32_t MsdkVideoEncoder::InitEncode(const webrtc::VideoCodec* codec_settings,
int32_t number_of_cores,
size_t max_payload_size) {
RTC_DCHECK(codec_settings);
RTC_DCHECK_EQ(codec_settings->codecType, webrtc::kVideoCodecH264);
int32_t release_ret = Release();
if (release_ret != WEBRTC_VIDEO_CODEC_OK) {
return release_ret;
}
width_ = codec_settings->width;
height_ = codec_settings->height;
target_bitrate_bps_ = codec_settings->startBitrate * 1000;
max_bitrate_bps_ = codec_settings->maxBitrate * 1000;
bitrate_adjuster_.SetTargetBitrateBps(target_bitrate_bps_);
framerate_ = codec_settings->maxFramerate;
mode_ = codec_settings->mode;
RTC_LOG(LS_INFO) << "InitEncode " << target_bitrate_bps_ << "bit/sec";
// Initialize encoded image. Default buffer size: size of unencoded data.
encoded_image_._encodedWidth = 0;
encoded_image_._encodedHeight = 0;
encoded_image_.set_size(0);
encoded_image_.timing_.flags =
webrtc::VideoSendTiming::TimingFrameFlags::kInvalid;
encoded_image_.content_type_ =
(codec_settings->mode == webrtc::VideoCodecMode::kScreensharing)
? webrtc::VideoContentType::SCREENSHARE
: webrtc::VideoContentType::UNSPECIFIED;
return InitMediaSDK();
}
int32_t MsdkVideoEncoder::RegisterEncodeCompleteCallback(
webrtc::EncodedImageCallback* callback) {
std::lock_guard<std::mutex> lock(mutex_);
callback_ = callback;
return WEBRTC_VIDEO_CODEC_OK;
}
int32_t MsdkVideoEncoder::Release() {
return ReleaseMediaSDK();
}
int32_t MsdkVideoEncoder::Encode(
const webrtc::VideoFrame& frame,
const std::vector<webrtc::VideoFrameType>* frame_types) {
bool send_key_frame = false;
if (frame_types != nullptr) {
// We only support a single stream.
RTC_DCHECK_EQ(frame_types->size(), static_cast<size_t>(1));
// Skip frame?
if ((*frame_types)[0] == webrtc::VideoFrameType::kEmptyFrame) {
return WEBRTC_VIDEO_CODEC_OK;
}
// Force key frame?
send_key_frame =
(*frame_types)[0] == webrtc::VideoFrameType::kVideoFrameKey;
}
// 使ってない入力サーフェスを取り出す
auto surface =
std::find_if(surfaces_.begin(), surfaces_.end(),
[](const mfxFrameSurface1& s) { return !s.Data.Locked; });
if (surface == surfaces_.end()) {
RTC_LOG(LS_ERROR) << "Surface not found";
return WEBRTC_VIDEO_CODEC_ERROR;
}
// I420 から NV12 に変換
rtc::scoped_refptr<const webrtc::I420BufferInterface> frame_buffer =
frame.video_frame_buffer()->ToI420();
libyuv::I420ToNV12(
frame_buffer->DataY(), frame_buffer->StrideY(), frame_buffer->DataU(),
frame_buffer->StrideU(), frame_buffer->DataV(), frame_buffer->StrideV(),
surface->Data.Y, surface->Data.Pitch, surface->Data.U,
surface->Data.Pitch, frame_buffer->width(), frame_buffer->height());
mfxStatus sts;
mfxEncodeCtrl ctrl;
memset(&ctrl, 0, sizeof(ctrl));
//send_key_frame = true;
if (send_key_frame) {
ctrl.FrameType = MFX_FRAMETYPE_I | MFX_FRAMETYPE_IDR | MFX_FRAMETYPE_REF;
} else {
ctrl.FrameType = MFX_FRAMETYPE_UNKNOWN;
}
if (reconfigure_needed_) {
auto start_time = std::chrono::system_clock::now();
RTC_LOG(LS_INFO) << "Start reconfigure: bps="
<< (bitrate_adjuster_.GetAdjustedBitrateBps() / 1000)
<< " framerate=" << framerate_;
// 今の設定を取得する
mfxVideoParam param;
memset(¶m, 0, sizeof(param));
sts = encoder_->GetVideoParam(¶m);
MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts);
// ビットレートとフレームレートを変更する。
// なお、encoder_->Reset() はキューイングしているサーフェスを
// 全て処理してから呼び出す必要がある。
// ここでは encoder_->Init() の時に
// param.mfx.GopRefDist = 1;
// param.AsyncDepth = 1;
// ext_coding_option.MaxDecFrameBuffering = 1;
// を設定して、そもそもキューイングが起きないようにすることで対処している。
if (param.mfx.RateControlMethod == MFX_RATECONTROL_CQP) {
//param.mfx.QPI = h264_bitstream_parser_.GetLastSliceQp().value_or(30);
} else {
param.mfx.TargetKbps = bitrate_adjuster_.GetAdjustedBitrateBps() / 1000;
}
param.mfx.FrameInfo.FrameRateExtN = framerate_;
param.mfx.FrameInfo.FrameRateExtD = 1;
sts = encoder_->Reset(¶m);
MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts);
reconfigure_needed_ = false;
auto end_time = std::chrono::system_clock::now();
RTC_LOG(LS_INFO) << "Finish reconfigure: "
<< std::chrono::duration_cast<std::chrono::milliseconds>(
end_time - start_time)
.count()
<< " ms";
}
// NV12 をハードウェアエンコード
mfxSyncPoint syncp;
sts = encoder_->EncodeFrameAsync(&ctrl, &*surface, &bitstream_, &syncp);
// alloc_request_.NumFrameSuggested が 1 の場合は MFX_ERR_MORE_DATA は発生しない
if (sts == MFX_ERR_MORE_DATA) {
// もっと入力が必要なので出直す
return WEBRTC_VIDEO_CODEC_OK;
}
MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts);
sts = session_->session.SyncOperation(syncp, 600000);
MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts);
//RTC_LOG(LS_ERROR) << "SurfaceSize=" << (surface->Data.U - surface->Data.Y);
//RTC_LOG(LS_ERROR) << "DataLength=" << bitstream_.DataLength;
{
uint8_t* p = bitstream_.Data + bitstream_.DataOffset;
int size = bitstream_.DataLength;
bitstream_.DataLength = 0;
//FILE* fp = fopen("test.mp4", "a+");
//fwrite(p, 1, size, fp);
//fclose(fp);
auto buf = webrtc::EncodedImageBuffer::Create(p, size);
encoded_image_.SetEncodedData(buf);
encoded_image_._encodedWidth = width_;
encoded_image_._encodedHeight = height_;
encoded_image_.content_type_ =
(mode_ == webrtc::VideoCodecMode::kScreensharing)
? webrtc::VideoContentType::SCREENSHARE
: webrtc::VideoContentType::UNSPECIFIED;
encoded_image_.timing_.flags = webrtc::VideoSendTiming::kInvalid;
encoded_image_.SetTimestamp(frame.timestamp());
encoded_image_.ntp_time_ms_ = frame.ntp_time_ms();
encoded_image_.capture_time_ms_ = frame.render_time_ms();
encoded_image_.rotation_ = frame.rotation();
encoded_image_.SetColorSpace(frame.color_space());
if (bitstream_.FrameType == MFX_FRAMETYPE_I ||
bitstream_.FrameType == MFX_FRAMETYPE_IDR) {
encoded_image_._frameType = webrtc::VideoFrameType::kVideoFrameKey;
} else {
encoded_image_._frameType = webrtc::VideoFrameType::kVideoFrameDelta;
}
webrtc::CodecSpecificInfo codec_specific;
if (codec_ == MFX_CODEC_AVC) {
codec_specific.codecType = webrtc::kVideoCodecH264;
codec_specific.codecSpecific.H264.packetization_mode =
webrtc::H264PacketizationMode::NonInterleaved;
}
h264_bitstream_parser_.ParseBitstream(encoded_image_);
encoded_image_.qp_ = h264_bitstream_parser_.GetLastSliceQp().value_or(-1);
webrtc::EncodedImageCallback::Result result =
callback_->OnEncodedImage(encoded_image_, &codec_specific);
if (result.error != webrtc::EncodedImageCallback::Result::OK) {
RTC_LOG(LS_ERROR) << __FUNCTION__
<< " OnEncodedImage failed error:" << result.error;
return WEBRTC_VIDEO_CODEC_ERROR;
}
bitrate_adjuster_.Update(size);
}
return WEBRTC_VIDEO_CODEC_OK;
}
void MsdkVideoEncoder::SetRates(const RateControlParameters& parameters) {
if (parameters.framerate_fps < 1.0) {
RTC_LOG(LS_WARNING) << "Invalid frame rate: " << parameters.framerate_fps;
return;
}
uint32_t new_framerate = (uint32_t)parameters.framerate_fps;
uint32_t new_bitrate = parameters.bitrate.get_sum_bps();
RTC_LOG(LS_INFO) << __FUNCTION__ << " framerate_:" << framerate_
<< " new_framerate: " << new_framerate
<< " target_bitrate_bps_:" << target_bitrate_bps_
<< " new_bitrate:" << new_bitrate
<< " max_bitrate_bps_:" << max_bitrate_bps_;
framerate_ = new_framerate;
target_bitrate_bps_ = new_bitrate;
bitrate_adjuster_.SetTargetBitrateBps(target_bitrate_bps_);
reconfigure_needed_ = true;
}
webrtc::VideoEncoder::EncoderInfo MsdkVideoEncoder::GetEncoderInfo() const {
webrtc::VideoEncoder::EncoderInfo info;
info.supports_native_handle = true;
info.implementation_name = "NvCodec H264";
info.scaling_settings = webrtc::VideoEncoder::ScalingSettings(
kLowH264QpThreshold, kHighH264QpThreshold);
info.is_hardware_accelerated = true;
return info;
}
int32_t MsdkVideoEncoder::InitMediaSDK() {
encoder_ = CreateEncoder(session_, codec_, width_, height_, framerate_,
bitrate_adjuster_.GetAdjustedBitrateBps() / 1000,
max_bitrate_bps_ / 1000, true);
if (encoder_ == nullptr) {
RTC_LOG(LS_ERROR) << "Failed to create encoder";
return WEBRTC_VIDEO_CODEC_ERROR;
}
mfxStatus sts = MFX_ERR_NONE;
mfxVideoParam param;
memset(¶m, 0, sizeof(param));
// Retrieve video parameters selected by encoder.
// - BufferSizeInKB parameter is required to set bit stream buffer size
sts = encoder_->GetVideoParam(¶m);
MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts);
RTC_LOG(LS_INFO) << "BufferSizeInKB=" << param.mfx.BufferSizeInKB;
// Query number of required surfaces for encoder
memset(&alloc_request_, 0, sizeof(alloc_request_));
sts = encoder_->QueryIOSurf(¶m, &alloc_request_);
MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts);
RTC_LOG(LS_INFO) << "Encoder NumFrameSuggested="
<< alloc_request_.NumFrameSuggested;
frame_info_ = param.mfx.FrameInfo;
// 出力ビットストリームの初期化
bitstream_buffer_.resize(param.mfx.BufferSizeInKB * 1000);
memset(&bitstream_, 0, sizeof(bitstream_));
bitstream_.MaxLength = bitstream_buffer_.size();
bitstream_.Data = bitstream_buffer_.data();
// 必要な枚数分の入力サーフェスを作る
{
int width = (alloc_request_.Info.Width + 31) / 32 * 32;
int height = (alloc_request_.Info.Height + 31) / 32 * 32;
// 1枚あたりのバイト数
// NV12 なので 1 ピクセルあたり 12 ビット
int size = width * height * 12 / 8;
surface_buffer_.resize(alloc_request_.NumFrameSuggested * size);
surfaces_.clear();
surfaces_.reserve(alloc_request_.NumFrameSuggested);
for (int i = 0; i < alloc_request_.NumFrameSuggested; i++) {
mfxFrameSurface1 surface;
memset(&surface, 0, sizeof(surface));
surface.Info = frame_info_;
surface.Data.Y = surface_buffer_.data() + i * size;
surface.Data.U = surface_buffer_.data() + i * size + width * height;
surface.Data.V = surface_buffer_.data() + i * size + width * height + 1;
surface.Data.Pitch = width;
surfaces_.push_back(surface);
}
}
return WEBRTC_VIDEO_CODEC_OK;
}
int32_t MsdkVideoEncoder::ReleaseMediaSDK() {
if (encoder_ != nullptr) {
encoder_->Close();
}
encoder_.reset();
return WEBRTC_VIDEO_CODEC_OK;
}
| 37.242661
| 212
| 0.678892
|
tetsu-koba
|
622cad24b8e01326a0ac4dd75c2a8afc90985632
| 86
|
cpp
|
C++
|
src/KawaiiEngine/src/widgets/ComponentInspector.cpp
|
Mathieu-Lala/Cute_Solar_System_-3
|
0bfe496991344709481995af348da2be37a19cac
|
[
"MIT"
] | 4
|
2021-06-03T11:20:09.000Z
|
2022-02-11T06:52:54.000Z
|
src/KawaiiEngine/src/widgets/ComponentInspector.cpp
|
Mathieu-Lala/Cute_Solar_System_-3
|
0bfe496991344709481995af348da2be37a19cac
|
[
"MIT"
] | 35
|
2021-05-29T09:25:57.000Z
|
2021-06-28T04:49:22.000Z
|
src/KawaiiEngine/src/widgets/ComponentInspector.cpp
|
Mathieu-Lala/Kawaii_Engine
|
0bfe496991344709481995af348da2be37a19cac
|
[
"MIT"
] | null | null | null |
#include "widgets/ComponentInspector.hpp"
int kawe::ComponentInspector::s_count = 0;
| 21.5
| 42
| 0.790698
|
Mathieu-Lala
|
623674142e8b82e64bd21731bcaee49b267a8105
| 3,062
|
hpp
|
C++
|
include/nana/gui/widgets/form.hpp
|
StillGreen-san/nana
|
87ffd31013f031ef2a36331a7f776b3a00cd54b8
|
[
"BSL-1.0"
] | null | null | null |
include/nana/gui/widgets/form.hpp
|
StillGreen-san/nana
|
87ffd31013f031ef2a36331a7f776b3a00cd54b8
|
[
"BSL-1.0"
] | null | null | null |
include/nana/gui/widgets/form.hpp
|
StillGreen-san/nana
|
87ffd31013f031ef2a36331a7f776b3a00cd54b8
|
[
"BSL-1.0"
] | null | null | null |
/**
* A Form Implementation
* Nana C++ Library(http://www.nanapro.org)
* Copyright(C) 2003-2020 Jinhao(cnjinhao@hotmail.com)
*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* @file nana/gui/widgets/form.hpp
*/
#ifndef NANA_GUI_WIDGET_FORM_HPP
#define NANA_GUI_WIDGET_FORM_HPP
#include "widget.hpp"
#include <nana/gui/place.hpp>
namespace nana
{
class place;
namespace drawerbase::form
{
class trigger: public drawer_trigger
{
public:
void attached(widget_reference, graph_reference) override;
void refresh(graph_reference) override;
private:
widget* wd_{nullptr};
};
class form_base
: public widget_object<category::root_tag, drawerbase::form::trigger, detail::events_root_extension>
{
public:
form_base(window owner, bool nested, const rectangle&, const appearance&);
//place methods
place & get_place();
void div(std::string div_text);
place::field_reference operator[](const char* field_name);
void collocate() noexcept;
private:
std::unique_ptr<place> place_;
};
}//end namespace drawerbase::form
/// The form widget represents a popup window.
///
/// Overall it is a root widget (\see: Overview of widgets) which attaches the OS/Windowing system's native window.
/// It is different from other window widgets in that its default constructor creates the window.
/// \see nana::appearance
class form
: public drawerbase::form::form_base
{
public:
/// helper template class for creating the appearance of the form.
using appear = ::nana::appear;
/// Creates a window form owned by the desktop, at the point and size specified by rect, and with the specified appearance.
explicit form(const rectangle& = api::make_center(300, 200), const appearance& = {}); //Default constructor
/// Creates a window always floating above its owner at the point and size specified by rect, with the specified appearance. This window is always floating above its owner.
explicit form(window owner, const ::nana::size& = { 300, 200 }, const appearance& = {});
explicit form(window owner, const rectangle&, const appearance& = {});
form(const form&, const ::nana::size& = { 300, 200 }, const appearance& = {}); //Copy constructor
/// Blocks the execution and other windows' messages until this window is closed.
void modality() const;
/// Blocks the execution until this window is closed.
void wait_for_this();
void keyboard_accelerator(const accel_key&, const std::function<void()>& fn);
};
class nested_form
: public drawerbase::form::form_base
{
public:
using appear = ::nana::appear;
nested_form(const form&, const rectangle& = {}, const appearance& = {});
nested_form(const nested_form&, const rectangle& = {}, const appearance& = {});
nested_form(window, const appearance&);
nested_form(window, const rectangle& = {}, const appearance& = {});
};
}//end namespace nana
#endif
| 32.924731
| 180
| 0.703462
|
StillGreen-san
|
623955d76285060ccded346d8bb5da05d86dcd07
| 2,548
|
hpp
|
C++
|
engine/engine/core/allocator/cached_allocator.hpp
|
ddr95070/RMIsaac
|
ee3918f685f0a88563248ddea11d089581077973
|
[
"FSFAP"
] | 1
|
2020-04-14T13:55:16.000Z
|
2020-04-14T13:55:16.000Z
|
engine/engine/core/allocator/cached_allocator.hpp
|
ddr95070/RMIsaac
|
ee3918f685f0a88563248ddea11d089581077973
|
[
"FSFAP"
] | 4
|
2020-09-25T22:34:29.000Z
|
2022-02-09T23:45:12.000Z
|
engine/engine/core/allocator/cached_allocator.hpp
|
ddr95070/RMIsaac
|
ee3918f685f0a88563248ddea11d089581077973
|
[
"FSFAP"
] | 1
|
2020-07-02T11:51:17.000Z
|
2020-07-02T11:51:17.000Z
|
/*
Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#pragma once
#include <atomic>
#include <memory>
#include <queue>
#include <shared_mutex> // NOLINT
#include <unordered_map>
#include "engine/core/allocator/allocator_base.hpp"
namespace isaac {
// Allocator which uses a cache in combination with another allocator to optimize repeated
// allocations and deallocations of the same size.
class CachedAllocator : public AllocatorBase {
public:
CachedAllocator(std::unique_ptr<AllocatorBase> child_allocator);
~CachedAllocator();
pointer_t allocateBytes(size_t size) override;
void deallocateBytes(pointer_t pointer_t, size_t size) override;
// Switches to cached mode with given number of buckets. Buckets are chosen based on collected
// statistics. Can only called once during the lifetime of an object. This will invalidate
// statistics collected so far.
void switchToCachedMode(size_t num_buckets);
// Deallocates all memory. Should only be called just before the end of the lifetime of an
// object.
void finalize();
// Gets the total number of times memory was allocated.
size_t getRequestCount() const;
// Gets the total number of bytes which have been requested.
size_t getTotalBytesRequested() const;
// Gets the total number of bytes which have actually been allocated by the underlying allocator.
size_t getTotalBytesAllocated() const;
// Gets the total number of bytes which have been deallocated by the underlying allocator.
size_t getTotalBytesDeallocated() const;
private:
// The mode in which the allocator is currently in
enum class Mode {
// All allocation and deallocation requests are directly forwarded to the underlying allocator.
// The allocator starts in this mode.
Direct,
// All allocation requests are first checked against an internal storage of buffers.
// Deallocation requests add buffers to the internal storage. The allocator can trafers from
// `Direct` mode to `Cached` mode exactly once during its lifetime.
Cached
};
// A helper type holding the implementation details of this class.
struct Impl;
std::unique_ptr<Impl> impl_;
};
} // namespace isaac
| 36.927536
| 99
| 0.770801
|
ddr95070
|
623ab620ed280b234dd754e12f1adab97004b048
| 1,023
|
cpp
|
C++
|
Samples/Windows/View/CheckBox.cpp
|
Topsens/3DVision
|
a694cf36df3883a5e2d55173e02d865972b8dee2
|
[
"Apache-2.0"
] | 2
|
2020-11-12T07:47:06.000Z
|
2020-11-12T11:49:07.000Z
|
Samples/Windows/View/CheckBox.cpp
|
Topsens/3DVision
|
a694cf36df3883a5e2d55173e02d865972b8dee2
|
[
"Apache-2.0"
] | null | null | null |
Samples/Windows/View/CheckBox.cpp
|
Topsens/3DVision
|
a694cf36df3883a5e2d55173e02d865972b8dee2
|
[
"Apache-2.0"
] | null | null | null |
#include "CheckBox.h"
#include <CommCtrl.h>
using namespace std;
CheckBox CheckBox::Create(HWND parent, UINT id, const wstring& text, DWORD type, HINSTANCE instance)
{
DialogItem di;
if (parent)
{
auto hwnd = CreateWindowExW(0, WC_BUTTONW, text.c_str(), type | BS_CHECKBOX | WS_CHILD | WS_TABSTOP, 0, 0, 0, 0, parent, (HMENU)id, instance, nullptr);
if (hwnd)
{
di = DialogItem(parent, hwnd, id);
}
}
return (CheckBox&)di;
}
void CheckBox::Check() const
{
this->Send(BM_SETCHECK, BST_CHECKED);
}
bool CheckBox::IsChecked() const
{
return BST_CHECKED == this->Send(BM_GETCHECK);
}
void CheckBox::Uncheck() const
{
this->Send(BM_SETCHECK, BST_UNCHECKED);
}
bool CheckBox::IsUnchecked() const
{
return BST_UNCHECKED == this->Send(BM_GETCHECK);
}
void CheckBox::Indeterminate() const
{
this->Send(BM_SETCHECK, BST_INDETERMINATE, 0);
}
bool CheckBox::IsIndeterminate() const
{
return BST_INDETERMINATE == this->Send(BM_GETCHECK);
}
| 20.46
| 159
| 0.664712
|
Topsens
|
623ac25f59d19f7dfcda4878a63e0a8e056b5f6c
| 5,747
|
hpp
|
C++
|
core/src/cogs/math/measurement_types.hpp
|
cogmine/cogs
|
ef1c369a36a4f811704e0ced0493c3a6f8eca821
|
[
"MIT"
] | 5
|
2019-02-08T15:59:14.000Z
|
2022-01-22T19:12:33.000Z
|
core/src/cogs/math/measurement_types.hpp
|
cogmine/cogs
|
ef1c369a36a4f811704e0ced0493c3a6f8eca821
|
[
"MIT"
] | 1
|
2019-12-03T03:11:34.000Z
|
2019-12-03T03:11:34.000Z
|
core/src/cogs/math/measurement_types.hpp
|
cogmine/cogs
|
ef1c369a36a4f811704e0ced0493c3a6f8eca821
|
[
"MIT"
] | null | null | null |
//
// Copyright (C) 2000-2020 - Colen M. Garoutte-Carson <colen at cogmine.com>, Cog Mine LLC
//
// Status: WorkInProgress
#ifndef COGS_HEADER_MATH_MEASUREMENT_TYPES
#define COGS_HEADER_MATH_MEASUREMENT_TYPES
#include <type_traits>
#include "cogs/env.hpp"
#include "cogs/operators.hpp"
#include "cogs/math/fixed_integer_extended.hpp"
#include "cogs/math/fixed_integer_native.hpp"
#include "cogs/math/fixed_integer_extended_const.hpp"
#include "cogs/math/fixed_integer_native_const.hpp"
namespace cogs {
// Base class for conceptual quantity types, such as time, distance, weight, etc.
class quantity_type_base
{
//public: typedef preferred_unit_t;
};
// Base class for all measurement unit types, such as seconds, meters, lbs, etc.
class unit_type_base
{
public:
//public: template <typename char_t, typename unit_t> static composite_string_t<char_t> to_string_t(const unit_t& n);
//public: template <typename unit_t> static composite_string to_string(const unit_t& n);
//public: template <typename unit_t> static composite_cstring to_cstring(const unit_t& n);
};
// A unit_type_base for raw numbers, of no particular unit or quantity type.
class numeric_units : public unit_type_base
{
};
// Base class for measurement unit types of a particular quantity type.
// i.e. class hours : public unit_type<time> { }
// class minutes : public unit_type<time> { }
template <class quantity_type>
class unit_type : public unit_type_base
{
public:
typedef quantity_type quantity_t;
};
// i.e. rate_quantity_type<distance, time>
template <class x, class y>
class rate_quantity_type;
// i.e. mph: rate_unit_type<miles, hour>
template <class x, class y>
class rate_unit_type : public unit_type_base
{
public:
typedef rate_quantity_type<x, y> quantity_t;
};
// i.e. area: quantity_exponent<distance, 2>
template <class T, size_t exponent>
class exponent_quantity_type : public quantity_type_base
{
};
// i.e. square miles: unit_exponent<mile, 2>
template <class T, size_t exponent>
class exponent_unit_type : public unit_type_base
{
public:
typedef exponent_quantity_type<typename T::quantity_t, exponent> quantity_t;
};
class seconds;
class time : public quantity_type_base { public: typedef seconds preferred_unit_t; };
class meters { };
class grams { };
class distance : public quantity_type_base { public: typedef meters preferred_unit_t; };
template <> class exponent_quantity_type<distance, 2> : public quantity_type_base { };
typedef exponent_quantity_type<distance, 2> area;
template <> class exponent_quantity_type<distance, 3> : public quantity_type_base { };
typedef exponent_quantity_type<distance, 3> volume;
template <> class rate_quantity_type<distance, time> { };
typedef rate_quantity_type<distance, time> speed;
typedef speed velocity;
template <> class rate_quantity_type<velocity, time> { };
typedef rate_quantity_type<velocity, time> acceleration;
class mass : public quantity_type_base { public: typedef grams preferred_unit_t; };
class weight : public quantity_type_base { };
template <class T1, class T2, typename enable = void>
class unit_conversion
{
};
template <class T>
class unit_conversion<T, T>
{
public:
typedef one_t ratio_const_t;
};
// Automatically generate conversion in the other direction, if one direction is defined
template <class T1, class T2>
class unit_conversion<
T1,
T2,
std::enable_if_t<
!std::is_same_v<T1, T2>
&& !std::is_same_v<T2, typename T1::quantity_t::preferred_unit_t>
&& std::is_same_v<T1, typename T1::quantity_t::preferred_unit_t>
>
>
{
public:
typedef decltype(reciprocal(std::declval<typename unit_conversion<T2, T1>::ratio_const_t>())) ratio_const_t;
};
template <class from_t, class to_t, class reative_to_t>
class unit_conversion_relative
{
private:
typedef typename unit_conversion<to_t, reative_to_t>::ratio_const_t from_ratio_const_t;
typedef typename unit_conversion<to_t, reative_to_t>::ratio_const_t to_ratio_const_t;
public:
typedef decltype(multiply(std::declval<from_ratio_const_t>(), std::declval<to_ratio_const_t>())) ratio_const_t;
};
// Automatically convert to/from any 2 units that define conversion to/from the preferred unit base
template <class T1, class T2>
class unit_conversion<
T1,
T2,
std::enable_if_t<
!std::is_same_v<T1, T2>
&& !std::is_same_v<T2, typename T1::quantity_t::preferred_unit_t>
&& !std::is_same_v<T1, typename T1::quantity_t::preferred_unit_t>
>
>
{
public:
typedef typename unit_conversion_relative<T1, T2, typename T1::quantity_t::preferred_unit_t>::ratio_const_t ratio_const_t;
};
// based on conversion, determine which type is more course and which is more fine
template <typename T1, typename T2>
struct is_finer
{
static constexpr bool value = const_compared<decltype(std::declval<typename unit_conversion<T1, T2>::ratio_const_t>().floor()), one_t>::value < 0;
};
template <typename T1, typename T2>
constexpr bool is_finer_v = is_finer<T1, T2>::value;
template <typename T> struct is_finer<T, T> : public std::false_type { };
template <typename T1, typename T2>
struct is_courser
{
static constexpr bool value = !is_finer_v<T1, T2>;
};
template <typename T1, typename T2>
constexpr bool is_courser_v = is_courser<T1, T2>::value;
template <typename T> struct is_courser<T, T> : public std::false_type { };
template <typename T1, typename T2>
struct finer
{
typedef std::conditional_t<is_finer_v<T1, T2>, T1, T2> type;
};
template <typename T1, typename T2>
using finer_t = typename finer<T1, T2>::type;
template <typename T1, typename T2>
struct courser
{
typedef std::conditional_t<is_courser_v<T1, T2>, T1, T2> type;
};
template <typename T1, typename T2>
using courser_t = typename courser<T1, T2>::type;
}
#include "cogs/math/time.hpp"
#endif
| 26.122727
| 147
| 0.761963
|
cogmine
|
9a8cd0be49323a2f7cea2ca0d5ff6e4680d281d0
| 1,003
|
cpp
|
C++
|
src/examples/012Chapter/12-3-2-Query-Classes/text_query.cpp
|
artgonzalez/cpp-primer
|
0317e11b5821860d38a236f24c6f7d76638386f3
|
[
"MIT"
] | null | null | null |
src/examples/012Chapter/12-3-2-Query-Classes/text_query.cpp
|
artgonzalez/cpp-primer
|
0317e11b5821860d38a236f24c6f7d76638386f3
|
[
"MIT"
] | null | null | null |
src/examples/012Chapter/12-3-2-Query-Classes/text_query.cpp
|
artgonzalez/cpp-primer
|
0317e11b5821860d38a236f24c6f7d76638386f3
|
[
"MIT"
] | null | null | null |
#include "text_query.h"
using std::getline; using std::ifstream; using std::istringstream;
using std::set; using std::string; using std::vector;
using std::shared_ptr;
TextQuery::TextQuery(ifstream& is) : file(new vector<string>)
{
string text;
while(getline(is, text))
{
file->push_back(text);
decltype(file->size()) line_number = file->size() - 1;
istringstream line(text);
string word;
while(line >> word)
{
auto& lines = word_map[word];
if(!line)
{
lines.reset(new set<line_no>);
}
lines->insert(line_number);
}
}
}
QueryResult TextQuery::query(const string& sought) const
{
static shared_ptr<set<line_no>>nodata(new set<line_no>);
auto loc = word_map.find(sought);
if(loc == word_map.end())
{
return QueryResult(sought, nodata, file);
}
else
{
return QueryResult(sought, loc->second, file);
}
}
| 22.288889
| 66
| 0.575274
|
artgonzalez
|
9a8d9a0d5e0c99f187fc301323b904ac885b4207
| 744
|
cpp
|
C++
|
3rdparty/rdestl/Test/StringTest.cpp
|
navta/opendcd
|
04995312259322815307d3992bbcd1993a7c481c
|
[
"Apache-2.0"
] | 72
|
2015-04-23T10:12:52.000Z
|
2022-03-28T04:46:01.000Z
|
3rdparty/rdestl/Test/StringTest.cpp
|
navta/opendcd
|
04995312259322815307d3992bbcd1993a7c481c
|
[
"Apache-2.0"
] | 4
|
2015-02-03T05:26:44.000Z
|
2020-04-03T09:13:45.000Z
|
3rdparty/rdestl/Test/StringTest.cpp
|
opendcd/opendcd
|
04995312259322815307d3992bbcd1993a7c481c
|
[
"Apache-2.0"
] | 35
|
2015-05-20T04:36:10.000Z
|
2022-03-02T01:39:59.000Z
|
#include <UnitTest++/src/UnitTest++.h>
#include "rdestl/rde_string.h"
#include "rdestl/cow_string_storage.h"
#include <cstdio>
namespace
{
typedef rde::basic_string<char, rde::allocator, rde::simple_string_storage<char, rde::allocator> > simple_string;
typedef rde::basic_string<char, rde::allocator, rde::cow_string_storage<char, rde::allocator> > cow_string;
#define CONCAT_(x, y) x ## y
#define CONCAT2_(x, y) CONCAT_(x, y)
#define TESTC(x) TEST(CONCAT2_(x, POSTFIX))
#define POSTFIX COW
#define STRING_CLASS cow_string
#include "StringTestInc.h"
#undef STRING_CLASS
#undef POSTFIX
#define POSTFIX Simple
#define STRING_CLASS simple_string
#include "StringTestInc.h"
#undef POSTFIX
#undef CONCAT_
#undef CONCAT2_
#undef TESTC
}
| 24.8
| 114
| 0.762097
|
navta
|
9a942ee3573e2b314f4ea00b17fc8d46f3479e93
| 2,088
|
cpp
|
C++
|
contrib/autoboost/libs/serialization/src/shared_ptr_helper.cpp
|
CaseyCarter/autowiring
|
48e95a71308318c8ffb7ed1348e034fd9110f70c
|
[
"Apache-2.0"
] | 87
|
2015-01-18T00:43:06.000Z
|
2022-02-11T17:40:50.000Z
|
contrib/autoboost/libs/serialization/src/shared_ptr_helper.cpp
|
CaseyCarter/autowiring
|
48e95a71308318c8ffb7ed1348e034fd9110f70c
|
[
"Apache-2.0"
] | 274
|
2015-01-03T04:50:49.000Z
|
2021-03-08T09:01:09.000Z
|
contrib/autoboost/libs/serialization/src/shared_ptr_helper.cpp
|
CaseyCarter/autowiring
|
48e95a71308318c8ffb7ed1348e034fd9110f70c
|
[
"Apache-2.0"
] | 15
|
2015-09-30T20:58:43.000Z
|
2020-12-19T21:24:56.000Z
|
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// shared_ptr_helper.hpp: serialization for autoboost shared pointern
// (C) Copyright 2004-2009 Robert Ramey, Martin Ecker and Takatoshi Kondo
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// See http://www.boost.org for updates, documentation, and revision history.
#include <map>
#include <list>
#include <utility>
#include <cstddef> // NULL
#include <cassert>
#define AUTOBOOST_ARCHIVE_SOURCE
// include this to prevent linker errors when the
// same modules are marked export and import.
#define AUTOBOOST_SERIALIZATION_SOURCE
#include <autoboost/serialization/throw_exception.hpp>
#include <autoboost/serialization/void_cast.hpp>
#include <autoboost/serialization/extended_type_info.hpp>
#include <autoboost/serialization/shared_ptr_helper.hpp>
#include <autoboost/archive/archive_exception.hpp>
namespace autoboost {
namespace serialization {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////8
// a common class for holding various types of shared pointers
// #ifdef AUTOBOOST_SERIALIZATION_SHARED_PTR_132_HPP
AUTOBOOST_ARCHIVE_DECL(void)
shared_ptr_helper_base::append(const autoboost_132::shared_ptr<const void> & t){
if(NULL == m_pointers_132)
m_pointers_132 = new std::list<autoboost_132::shared_ptr<const void> >;
m_pointers_132->push_back(t);
}
// #endif
AUTOBOOST_ARCHIVE_DECL(AUTOBOOST_PP_EMPTY())
shared_ptr_helper_base::shared_ptr_helper_base() :
m_o_sp(NULL)
#ifdef AUTOBOOST_SERIALIZATION_SHARED_PTR_132_HPP
, m_pointers_132(NULL)
#endif
{}
AUTOBOOST_ARCHIVE_DECL(AUTOBOOST_PP_EMPTY())
shared_ptr_helper_base::~shared_ptr_helper_base(){
if(NULL != m_o_sp)
delete m_o_sp;
#ifdef AUTOBOOST_SERIALIZATION_SHARED_PTR_132_HPP
if(NULL != m_pointers_132)
delete m_pointers_132;
#endif
}
} // namespace serialization
} // namespace autoboost
| 32.625
| 80
| 0.722701
|
CaseyCarter
|
9a951c29d410837ae8abc7ed02013f1ce3f154ef
| 2,277
|
cpp
|
C++
|
server/cotsb/tile.cpp
|
astrellon/cotsb
|
a04336da54543d95b330e40a67b439f65b036f49
|
[
"MIT"
] | null | null | null |
server/cotsb/tile.cpp
|
astrellon/cotsb
|
a04336da54543d95b330e40a67b439f65b036f49
|
[
"MIT"
] | null | null | null |
server/cotsb/tile.cpp
|
astrellon/cotsb
|
a04336da54543d95b330e40a67b439f65b036f49
|
[
"MIT"
] | null | null | null |
#include "tile.h"
#include <cotsb/logging.h>
namespace cotsb
{
// Tile {{{
Tile::Tile(const std::string &name, uint16_t id) :
_name(name),
_id(id),
_passable(true),
_colour(sf::Color(255, 0, 255, 255))
{
}
void Tile::init(bool passable, const sf::Color &colour)
{
_passable = passable;
_colour = colour;
}
std::string Tile::name() const
{
return _name;
}
uint16_t Tile::id() const
{
return _id;
}
bool Tile::passable() const
{
return _passable;
}
sf::Color Tile::colour() const
{
return _colour;
}
// }}}
// TileManager {{{
uint16_t TileManager::s_id_counter = 0u;
TileManager::TileNameMap TileManager::s_name_map;
TileManager::TileIdMap TileManager::s_id_map;
Tile *TileManager::NullTile = nullptr;
void TileManager::init()
{
NullTile = create("null", 0u);
NullTile->init(false, sf::Color::Black);
create("grass")->init(true, sf::Color::Green);
create("wall")->init(false, sf::Color::Red);
create("water")->init(false, sf::Color::Blue);
create("dirt")->init(true, sf::Color::Yellow);
}
Tile *TileManager::tile(const std::string &name)
{
auto find = s_name_map.find(name);
if (find != s_name_map.end())
{
return find->second.get();
}
return nullptr;
}
Tile *TileManager::tile(uint16_t id)
{
auto find = s_id_map.find(id);
if (find != s_id_map.end())
{
return find->second;
}
return nullptr;
}
Tile *TileManager::create(const std::string &name)
{
auto find = s_name_map.find(name);
if (find != s_name_map.end())
{
logger % "Error" << "A tile with the same name exists: " << name << endl;
return nullptr;
}
auto id = ++s_id_counter;
return create(name, id);
}
Tile *TileManager::create(const std::string &name, uint16_t id)
{
auto new_tile = new Tile(name, id);
s_name_map[name] = std::unique_ptr<Tile>(new_tile);
s_id_map[id] = new_tile;
return new_tile;
}
// }}}
}
| 23
| 85
| 0.536232
|
astrellon
|
9a982cfcfa160381742bcc3f36033e29beef8e9d
| 1,578
|
cpp
|
C++
|
src/testprog/gltf2/litrot.cpp
|
degarashi/revenant
|
9e671320a5c8790f6bdd1b14934f81c37819f7b3
|
[
"MIT"
] | null | null | null |
src/testprog/gltf2/litrot.cpp
|
degarashi/revenant
|
9e671320a5c8790f6bdd1b14934f81c37819f7b3
|
[
"MIT"
] | null | null | null |
src/testprog/gltf2/litrot.cpp
|
degarashi/revenant
|
9e671320a5c8790f6bdd1b14934f81c37819f7b3
|
[
"MIT"
] | null | null | null |
#include "litrot.hpp"
#include "../../input/input.hpp"
#include "../../imgui_sdl2.hpp"
namespace rev::test {
// -------------- LitRot --------------
LitRot::LitRot():
_rot(frea::Quat::Identity())
{}
void LitRot::update(
const HActC& dir_x,
const HActC& dir_y,
const frea::Vec3& right,
const frea::Vec3& up
) {
const float dx = dir_x->getValueAsFloat()*70,
dy = dir_y->getValueAsFloat()*70;
const auto q = frea::Quat::Rotation(up, frea::DegF(-dx))
* frea::Quat::Rotation(right, frea::DegF(-dy));
_rot= q * _rot;
}
frea::Vec3 LitRot::getDir() const {
return _rot.getDir();
}
// -------------- LitRot --------------
LitRotObj::LitRotObj():
_press(false)
{
const auto hM = Mouse::OpenMouse(0);
_act[Act::DirX] = mgr_input.makeAction("lit_x");
_act[Act::DirX]->addLink(hM, InputFlag::Axis, 0);
_act[Act::DirY] = mgr_input.makeAction("lit_y");
_act[Act::DirY]->addLink(hM, InputFlag::Axis, 1);
_act[Act::LitBtn] = mgr_input.makeAction("lit_b");
_act[Act::LitBtn]->addLink(hM, InputFlag::Button, 1);
}
void LitRotObj::update(
const frea::Vec3& right,
const frea::Vec3& up
) {
if(_press) {
LitRot::update(_act[Act::DirX], _act[Act::DirY], right, up);
if(!_act[Act::LitBtn]->isKeyPressing()) {
const auto hM = Mouse::OpenMouse(0);
hM->setMouseMode(MouseMode::Absolute);
_press = false;
}
} else {
if(_act[Act::LitBtn]->isKeyPressed()) {
if(!mgr_gui.pointerOnGUI()) {
const auto hM = Mouse::OpenMouse(0);
hM->setMouseMode(MouseMode::Relative);
_press = true;
}
}
}
}
}
| 26.3
| 63
| 0.60583
|
degarashi
|
9a9dd4a644c6079bccb86e2519b6b997c16578df
| 7,361
|
hpp
|
C++
|
source/Actor.hpp
|
CyberSys/vaultmp
|
341d62202eb47c5f8795c3b93391fd799c6a4ca8
|
[
"MIT"
] | 67
|
2015-01-08T10:40:31.000Z
|
2022-03-29T21:16:51.000Z
|
source/Actor.hpp
|
CyberSys/vaultmp
|
341d62202eb47c5f8795c3b93391fd799c6a4ca8
|
[
"MIT"
] | 20
|
2015-01-05T21:04:05.000Z
|
2018-04-15T11:50:37.000Z
|
source/Actor.hpp
|
CyberSys/vaultmp
|
341d62202eb47c5f8795c3b93391fd799c6a4ca8
|
[
"MIT"
] | 60
|
2015-02-17T00:12:11.000Z
|
2021-08-21T22:16:58.000Z
|
#ifndef ACTOR_H
#define ACTOR_H
#include "vaultmp.hpp"
#include "Container.hpp"
#ifdef VAULTMP_DEBUG
#include "Debug.hpp"
#endif
const unsigned int FLAG_ALIVE = FLAG_SELF << 1;
/**
* \brief Derives from Container class and represents an actor in-game
*
* Data specific to Actors are actor values, animations and various states
*/
class Actor : public Container
{
friend class GameFactory;
private:
#ifdef VAULTMP_DEBUG
static DebugInput<Actor> debug;
#endif
std::unordered_map<unsigned char, Value<float>> actor_Values;
std::unordered_map<unsigned char, Value<float>> actor_BaseValues;
Value<unsigned int> actor_Race;
Value<signed int> actor_Age;
Value<unsigned int> anim_Idle;
Value<unsigned char> anim_Moving;
Value<unsigned char> state_MovingXY;
Value<unsigned char> anim_Weapon;
Value<bool> state_Female;
Value<bool> state_Alerted;
Value<bool> state_Sneaking;
Value<bool> state_Dead;
Value<unsigned short> death_Limbs;
Value<signed char> death_Cause;
void initialize();
Actor(const Actor&) = delete;
Actor& operator=(const Actor&) = delete;
protected:
Actor(unsigned int refID, unsigned int baseID);
Actor(unsigned int baseID) : Actor(0x00000000, baseID) {}
Actor(const pPacket& packet);
Actor(pPacket&& packet) : Actor(packet) {};
public:
virtual ~Actor() noexcept;
static const std::map<unsigned char, std::pair<const float, const float>> default_values;
#ifndef VAULTSERVER
/**
* \brief Creates a Parameter containing a VaultFunctor initialized with the given flags
*
* Used to pass Actor references matching the provided flags to the Interface
* Can also be used to pass data of a given Actor to the Interface
*/
static FuncParameter CreateFunctor(unsigned int flags, RakNet::NetworkID id = 0);
#endif
/**
* \brief Retrieves the Actor's actor value specified by index (actor value hex code)
*/
float GetActorValue(unsigned char index) const;
/**
* \brief Retrieves the Actor's base actor value specified by index (actor value hex code)
*/
float GetActorBaseValue(unsigned char index) const;
/**
* \brief Retrieves the Actor's race
*/
unsigned int GetActorRace() const;
/**
* \brief Retrieves the Actor's relative age
*/
signed int GetActorAge() const;
/**
* \brief Retrieves the Actor's idle animation
*/
unsigned int GetActorIdleAnimation() const;
/**
* \brief Retrieves the Actor's moving animation
*/
unsigned char GetActorMovingAnimation() const;
/**
* \brief Retrieves the Actor's moving state
*
* 0x00 - the actor moves Forward / Backward
* 0x01 - the actor moves ForwardLeft / BackwardRight
* 0x02 - the actor moves ForwardRight / BackwardLeft
*/
unsigned char GetActorMovingXY() const;
/**
* \brief Retrieves the Actor's weapon animation
*/
unsigned char GetActorWeaponAnimation() const;
/**
* \brief Retrieves the Actor's sex
*/
bool GetActorFemale() const;
/**
* \brief Retrieves the Actor's alerted state
*/
bool GetActorAlerted() const;
/**
* \brief Retrieves the Actor's sneaking state
*/
bool GetActorSneaking() const;
/**
* \brief Retrieves the Actor's dead state
*/
bool GetActorDead() const;
/**
* \brief Retrieves the Actor's last limb state after death
*/
unsigned short GetActorLimbs() const;
/**
* \brief Retrieves the Actor's last death cause
*/
signed char GetActorDeathCause() const;
/**
* \brief Sets the Actor's actor value specified by index (actor value hex code)
*/
Lockable* SetActorValue(unsigned char index, float value);
/**
* \brief Sets the Actor's base actor value specified by index (actor value hex code)
*/
Lockable* SetActorBaseValue(unsigned char index, float value);
/**
* \brief Sets the Actor's race
*/
Lockable* SetActorRace(unsigned int race);
/**
* \brief Sets the Actor's relative age
*/
Lockable* SetActorAge(signed int age);
/**
* \brief Sets the Actor's idle animation
*/
Lockable* SetActorIdleAnimation(unsigned int idle);
/**
* \brief Sets the Actor's moving animation
*/
Lockable* SetActorMovingAnimation(unsigned char index);
/**
* \brief Sets the Actor's moving state
*
* 0x00 - the actor moves Forward / Backward
* 0x01 - the actor moves ForwardLeft / BackwardRight
* 0x02 - the actor moves ForwardRight / BackwardLeft
*/
Lockable* SetActorMovingXY(unsigned char moving);
/**
* \brief Sets the Actor's weapon animation
*/
Lockable* SetActorWeaponAnimation(unsigned char index);
/**
* \brief Sets the Actor's sex
*/
Lockable* SetActorFemale(bool state);
/**
* \brief Sets the Actor's alerted state
*/
Lockable* SetActorAlerted(bool state);
/**
* \brief Sets the Actor's sneaking state
*/
Lockable* SetActorSneaking(bool state);
/**
* \brief Sets the Actor's dead state
*/
Lockable* SetActorDead(bool state, unsigned short limbs, signed char cause);
#ifdef VAULTSERVER
/**
* \brief Sets the Actor's base ID
*/
virtual Lockable* SetBase(unsigned int baseID);
#endif
/**
* \brief Returns true if the Actor is jumping
*/
bool IsActorJumping() const;
/**
* \brief Returns true if the Actor is firing a weapon
*
* Only accurate in vaultserver
*/
bool IsActorFiring() const;
/**
* \brief Returns true if the Actor is punching
*
* Only accurate in vaultserver
*/
bool IsActorPunching() const;
/**
* \brief Returns true if the Actor is punching (power)
*/
bool IsActorPowerPunching() const;
/**
* \brief Returns true if the Actor is attacking
*/
bool IsActorAttacking() const;
#ifdef VAULTSERVER
/**
* \brief Returns the baseID of the Actor's equipped weapon
*/
unsigned int GetEquippedWeapon() const;
#endif
/**
* \brief For network transfer
*/
virtual pPacket toPacket() const;
};
#ifndef VAULTSERVER
class ActorFunctor : public ContainerFunctor
{
public:
ActorFunctor(unsigned int flags, RakNet::NetworkID id) : ContainerFunctor(flags, id) {}
virtual ~ActorFunctor() {}
virtual std::vector<std::string> operator()();
virtual bool filter(FactoryWrapper<Reference>& reference);
};
#endif
GF_TYPE_WRAPPER(Actor, Container, ID_ACTOR, ALL_ACTORS)
PF_MAKE(ID_ACTOR_NEW, pGeneratorReferenceExtend, std::map<unsigned char, float>, std::map<unsigned char, float>, unsigned int, signed int, unsigned int, unsigned char, unsigned char, unsigned char, bool, bool, bool, bool, unsigned short, signed char)
template<>
inline const typename pTypesMap<pTypes::ID_ACTOR_NEW>::type* PacketFactory::Cast_<pTypes::ID_ACTOR_NEW>::Cast(const pPacket* packet) {
pTypes type = packet->type();
return (
type == pTypes::ID_ACTOR_NEW ||
type == pTypes::ID_PLAYER_NEW
) ? static_cast<const typename pTypesMap<pTypes::ID_ACTOR_NEW>::type*>(packet) : nullptr;
}
PF_MAKE(ID_UPDATE_STATE, pGeneratorReference, unsigned int, unsigned char, unsigned char, unsigned char, bool, bool, bool)
PF_MAKE(ID_UPDATE_RACE, pGeneratorReference, unsigned int, signed int, signed int)
PF_MAKE(ID_UPDATE_SEX, pGeneratorReference, bool)
PF_MAKE(ID_UPDATE_DEAD, pGeneratorReference, bool, unsigned short, signed char)
PF_MAKE(ID_UPDATE_FIREWEAPON, pGeneratorReference, unsigned int)
PF_MAKE(ID_UPDATE_IDLE, pGeneratorReference, unsigned int, std::string)
#endif
| 28.531008
| 250
| 0.708192
|
CyberSys
|
9aa1f9fe7c0a4ef5d7449129fe4a6e92133f34c3
| 936
|
hpp
|
C++
|
include/basicpp/basicpp_config.hpp
|
avinal/basicpp
|
e7d042c11de73eef4314fe002574f2fddab2df12
|
[
"CC0-1.0"
] | null | null | null |
include/basicpp/basicpp_config.hpp
|
avinal/basicpp
|
e7d042c11de73eef4314fe002574f2fddab2df12
|
[
"CC0-1.0"
] | null | null | null |
include/basicpp/basicpp_config.hpp
|
avinal/basicpp
|
e7d042c11de73eef4314fe002574f2fddab2df12
|
[
"CC0-1.0"
] | null | null | null |
//
// Created by Avinal on 23-11-2020.
//
#ifndef BASICPP_BASICPP_CONFIG_HPP
#define BASICPP_BASICPP_CONFIG_HPP
#define BASICPP_VERSION_MAJOR 0
#define BASICPP_VERSION_MINOR 1
#define BASICPP_VERSION_PATCH 1
// Composing the version string from major, minor and patch
#define BASICPP_CONCATENATE(A, B) BASICPP_CONCATENATE_IMPL(A, B)
#define BASICPP_CONCATENATE_IMPL(A, B) A##B
#define BASICPP_STRINGIFY(a) BASICPP_STRINGIFY_IMPL(a)
#define BASICPP_STRINGIFY_IMPL(a) #a
#define BASICPP_VERSION BASICPP_STRINGIFY(BASICPP_CONCATENATE(BASICPP_VERSION_MAJOR, \
BASICPP_CONCATENATE(.,BASICPP_CONCATENATE(BASICPP_VERSION_MINOR, \
BASICPP_CONCATENATE(.,BASICPP_VERSION_PATCH)))))
#ifdef _WIN32
#ifdef BASICPP_EXPORTS
#define BASICPP_API __declspec(dllexport)
#else
#define BASICPP_API __declspec(dllimport)
#endif
#else
#define BASICPP_API
#endif
#endif //BASICPP_BASICPP_CONFIG_HPP
| 28.363636
| 88
| 0.779915
|
avinal
|
9aaa8f08c9f508d1ca169831c989341355e817f0
| 32,739
|
cpp
|
C++
|
redist/deps/tangelo/tangelo.cpp
|
VIGGEEN/bundle
|
9a7a392ea31780660d5b5c34fbe143693c8f0d7b
|
[
"Zlib"
] | 443
|
2018-01-30T13:36:46.000Z
|
2022-03-30T18:26:26.000Z
|
redist/deps/tangelo/tangelo.cpp
|
VIGGEEN/bundle
|
9a7a392ea31780660d5b5c34fbe143693c8f0d7b
|
[
"Zlib"
] | 3
|
2019-04-18T08:15:34.000Z
|
2022-02-13T00:33:07.000Z
|
redist/deps/tangelo/tangelo.cpp
|
VIGGEEN/bundle
|
9a7a392ea31780660d5b5c34fbe143693c8f0d7b
|
[
"Zlib"
] | 58
|
2018-01-20T12:57:10.000Z
|
2022-03-22T22:10:02.000Z
|
/* TANGELO file compressor 2.41 based on PAQ8 by Matt Mahoney
Release by Jan Ondrus and r-lyeh, Nov. 03, 2015
2.41 - thread safe, std::istream based, MSC friendly (r-lyeh)
2.40 - latest source code available (Jan Ondrus)
Copyright (C) 2013 Matt Mahoney, Serge Osnach, Alexander Ratushnyak,
Bill Pettis, Przemyslaw Skibinski, Matthew Fite, wowtiger, Andrew Paterson,
Jan Ondrus, Andreas Morphis, Pavel L. Holoborodko, KZ., Simon Berger,
Neill Corlett, Marwijn Hessel, Mat Chartier
LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details at
Visit <http://www.gnu.org/copyleft/gpl.html>.
Usage: TANGELO <command> <infile> <outfile>
<Commands>
c Compress
d Decompress
Recommended compiler command for MINGW g++:
g++ tangelo.cpp -Wall -Wextra -O3 -s -march=pentium4 -mtune=pentiumpro -fomit-frame-pointer -o tangelo.exe
*/
#ifndef _CRT_DISABLE_PERFCRIT_LOCKS
# define _CRT_DISABLE_PERFCRIT_LOCKS // for vc8 and later
#endif
#ifndef _CRT_SECURE_NO_DEPRECATE
# define _CRT_SECURE_NO_DEPRECATE // for vc8 and later
#endif
#ifndef _CRT_SECURE_NO_WARNINGS
# define _CRT_SECURE_NO_WARNINGS
#endif
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdint.h>
#include <sstream>
#include <fstream>
#if !defined(__GNUC__)
#if (2 == _M_IX86_FP) || defined(_WIN64)
# define __SSE2__
#endif
#endif
#if defined(__SSE2__)
#include <emmintrin.h>
#endif
namespace tangelo {
typedef uint8_t U8;
typedef uint16_t U16;
typedef uint32_t U32;
// Array
template<class T,int ALIGN=0> class Array {
private:
size_t n;
char *ptr;
T *data;
public:
explicit Array(size_t i): n(i) {
if (!(ptr = (char*)calloc(ALIGN + n * sizeof(T), 1))) throw "Out of memory";
data = (ALIGN ? (T*)(ptr + ALIGN - (((size_t)ptr) & (ALIGN - 1))):(T*)ptr);
}
~Array() { free(ptr); }
T&operator[](U32 i) { return data[i]; }
const T&operator[](U32 i) const { return data[i]; }
size_t size() const { return n; }
private:
Array(const Array&);
Array&operator=(const Array&);
};
// State table
const U8 State_table[256][2] =
{{1,2},{3,163},{143,169},{4,163},{5,165},{6,89},{7,245},{8,217},{9,245},{10,245},{11,233},{12,244},{13,227},{14,74},{15,221},{16,221},{17,218},{18,226},{19,243},{20,218},{21,238},{22,242},{23,74},{24,238},{25,241},{26,240},{27,239},{28,224},{29,225},{30,221},{31,232},{32,72},{33,224},{34,228},{35,223},{36,225},{37,238},{38,73},{39,167},{40,76},{41,237},{42,234},{43,231},{44,72},{45,31},{46,63},{47,225},{48,237},{49,236},{50,235},{51,53},{52,234},{47,53},{54,234},{55,229},{56,219},{57,229},{58,233},{59,232},{60,228},{61,226},{62,72},{63,74},{64,222},{65,75},{66,220},{67,167},{68,57},{69,218},{6,70},{71,168},{71,72},{71,73},{61,74},{75,217},{56,76},{77,167},{78,79},{77,79},{80,166},{81,162},{82,162},{83,162},{84,162},{85,165},{86,89},{87,89},{88,165},{77,89},{90,162},{91,93},{92,93},{80,93},{94,161},{95,100},{96,93},{97,93},{98,93},{99,93},{90,93},{101,161},{94,102},{103,120},{101,104},{102,105},{104,106},{107,108},{104,106},{105,109},{108,110},{111,160},{112,134},{113,108},{114,108},{115,126},{116,117},{92,117},{118,121},{94,119},{103,120},{119,107},{122,124},{123,117},{94,117},{113,125},{126,127},{113,124},{128,139},{129,130},{114,124},{131,133},{132,109},{112,110},{134,135},{111,110},{134,136},{110,137},{134,138},{134,127},{128,140},{128,141},{142,145},{143,144},{115,124},{113,125},{142,146},{128,147},{148,151},{149,125},{79,150},{148,127},{142,152},{148,153},{150,154},{155,156},{149,139},{157,158},{149,139},{159,156},{149,139},{131,130},{101,117},{98,163},{115,164},{114,141},{91,163},{79,147},{58,2},{1,2},{170,199},{129,171},{128,172},{110,173},{174,177},{128,175},{176,171},{129,171},{174,178},{179,180},{174,172},{176,181},{141,182},{157,183},{179,184},{185,186},{157,178},{187,189},{188,181},{168,181},{151,190},{191,193},{192,182},{188,182},{187,194},{172,195},{175,196},{170,197},{152,198},{185,169},{170,200},{176,201},{170,202},{203,204},{148,180},{185,205},{203,206},{185,207},{192,208},{209,210},{188,194},{211,212},{192,184},{213,215},{214,193},{188,184},{216,208},{168,193},{84,163},{54,219},{54,168},{221,94},{54,217},{55,223},{85,224},{69,225},{63,76},{56,227},{86,217},{58,229},{230,219},{231,79},{57,86},{229,165},{56,217},{224,214},{54,225},{54,216},{66,216},{58,234},{54,75},{61,214},{57,237},{222,74},{78,74},{85,163},{82,217},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},{0,0},};
// State map
const short sm[16][256] =
{
{-119,-120,169,-476,-484,-386,-737,-881,-874,-712,-848,-679,-559,-794,-1212,-782,-1205,-1205,-613,-753,-1169,-1169,-1169,-743,-1155,-732,-720,-1131,-1131,-1131,-1131,-1131,-1131,-1131,-1131,-1131,-540,-1108,-1108,-1108,-1108,-1108,-1108,-1108,-1108,-1108,-1108,-2047,-2047,-2047,-2047,-2047,-2047,-782,-569,-389,-640,-720,-568,-432,-379,-640,-459,-590,-1003,-569,-981,-981,-981,-609,416,-1648,-245,-416,-152,-152,416,-1017,-1017,-179,-424,-446,-461,-508,-473,-492,-501,-520,-528,-54,-395,-405,-404,-94,-232,-274,-288,-319,-354,-379,-105,-141,-63,-113,-18,-39,-94,52,103,167,222,130,-78,-135,-253,-321,-343,102,-165,157,-229,155,-108,-188,262,283,56,447,6,-92,242,172,38,304,141,285,285,320,319,462,497,447,-56,-46,374,485,510,479,-71,198,475,549,559,584,586,-196,712,-185,673,-161,237,-63,48,127,248,-34,-18,416,-99,189,-50,39,337,263,660,153,569,832,220,1,318,246,660,660,732,416,732,1,-660,246,660,1,-416,732,262,832,369,781,781,324,1104,398,626,-416,609,1018,1018,1018,1648,732,1856,1,1856,416,-569,1984,-732,-164,416,153,-416,-569,-416,1,-660,1,-660,153,152,-832,-832,-832,-569,0,-95,-660,1,569,153,416,-416,1,1,-569,1,-318,1,1,1,1,1,1,1,1,1,1,},
{-10,-436,401,-521,-623,-689,-736,-812,-812,-900,-865,-891,-1006,-965,-981,-916,-946,-976,-1072,-1014,-1058,-1090,-1044,-1030,-1044,-1104,-1009,-1418,-1131,-1131,-1269,-1332,-1191,-1169,-1108,-1378,-1367,-1126,-1297,-1085,-1355,-1344,-1169,-1269,-1440,-1262,-1332,-2047,-2047,-1984,-2047,-2047,-2047,-225,-402,-556,-502,-746,-609,-647,-625,-718,-700,-805,-748,-935,-838,-1053,-787,-806,-269,-1006,-278,-212,-41,-399,137,-984,-998,-219,-455,-524,-556,-564,-577,-592,-610,-690,-650,-140,-396,-471,-450,-168,-215,-301,-325,-364,-315,-401,-96,-174,-102,-146,-61,-9,54,81,116,140,192,115,-41,-93,-183,-277,-365,104,-134,37,-80,181,-111,-184,194,317,63,394,105,-92,299,166,-17,333,131,386,403,450,499,480,493,504,89,-119,333,558,568,501,-7,-151,203,557,595,603,650,104,960,204,933,239,247,-12,-105,94,222,-139,40,168,-203,566,-53,243,344,542,42,208,14,474,529,82,513,504,570,616,644,92,669,91,-179,677,720,157,-10,687,672,750,686,830,787,683,723,780,783,9,842,816,885,901,1368,188,1356,178,1419,173,-22,1256,240,167,1,-31,-165,70,-493,-45,-354,-25,-142,98,-17,-158,-355,-448,-142,-67,-76,-310,-324,-225,-96,0,46,-72,0,-439,14,-55,1,1,1,1,1,1,1,1,1,1,},
{-32,-521,485,-627,-724,-752,-815,-886,-1017,-962,-1022,-984,-1099,-1062,-1090,-1062,-1108,-1085,-1248,-1126,-1233,-1104,-1233,-1212,-1285,-1184,-1162,-1309,-1240,-1309,-1219,-1390,-1332,-1320,-1262,-1320,-1332,-1320,-1344,-1482,-1367,-1355,-1504,-1390,-1482,-1482,-1525,-2047,-2047,-1984,-2047,-2047,-1984,-251,-507,-480,-524,-596,-608,-658,-713,-812,-700,-653,-820,-820,-752,-831,-957,-690,-402,-689,-189,-28,-13,-312,119,-930,-973,-212,-459,-523,-513,-584,-545,-593,-628,-631,-688,-33,-437,-414,-458,-167,-301,-308,-407,-289,-389,-332,-55,-233,-115,-144,-100,-20,106,59,130,200,237,36,-114,-131,-232,-296,-371,140,-168,0,-16,199,-125,-182,238,310,29,423,41,-176,317,96,-14,377,123,446,458,510,496,463,515,471,-11,-182,268,527,569,553,-58,-146,168,580,602,604,651,87,990,95,977,185,315,82,-25,140,286,-57,85,14,-210,630,-88,290,328,422,-20,271,-23,478,548,64,480,540,591,601,583,26,696,117,-201,740,717,213,-22,566,599,716,709,764,740,707,790,871,925,3,969,990,990,1023,1333,154,1440,89,1368,125,-78,1403,128,100,-88,-20,-250,-140,-164,-14,-175,-6,-13,-23,-251,-195,-422,-419,-107,-89,-24,-69,-244,-51,-27,-250,0,1,-145,74,12,11,1,1,1,1,1,1,1,1,1,1,},
{-25,-605,564,-746,-874,-905,-949,-1044,-1126,-1049,-1099,-1140,-1248,-1122,-1184,-1240,-1198,-1285,-1262,-1332,-1418,-1402,-1390,-1285,-1418,-1418,-1418,-1367,-1552,-1440,-1367,-1584,-1344,-1616,-1344,-1390,-1418,-1461,-1616,-1770,-1648,-1856,-1770,-1584,-1648,-2047,-1685,-2047,-2047,-1856,-2047,-2047,-1770,-400,-584,-523,-580,-604,-625,-587,-739,-626,-774,-857,-737,-839,-656,-888,-984,-624,-26,-745,-211,-103,-73,-328,142,-1072,-1062,-231,-458,-494,-518,-579,-550,-541,-653,-621,-703,-53,-382,-444,-417,-199,-288,-367,-273,-450,-268,-477,-101,-157,-123,-156,-107,-9,71,64,133,174,240,25,-138,-127,-233,-272,-383,105,-144,85,-115,188,-112,-245,236,305,26,395,-3,-164,321,57,-68,346,86,448,482,541,515,461,503,454,-22,-191,262,485,557,550,-53,-152,213,565,570,649,640,122,931,92,990,172,317,54,-12,127,253,8,108,104,-144,733,-64,265,370,485,152,366,-12,507,473,146,462,579,549,659,724,94,679,72,-152,690,698,378,-11,592,652,764,730,851,909,837,896,928,1050,74,1095,1077,1206,1059,1403,254,1552,181,1552,238,-31,1526,199,47,-214,32,-219,-153,-323,-198,-319,-108,-107,-90,-177,-210,-184,-455,-216,-19,-107,-219,-22,-232,-19,-198,-198,-113,-398,0,-49,-29,1,1,1,1,1,1,1,1,1,1,},
{-34,-648,644,-793,-889,-981,-1053,-1108,-1108,-1117,-1176,-1198,-1205,-1140,-1355,-1332,-1418,-1440,-1402,-1355,-1367,-1418,-1402,-1525,-1504,-1402,-1390,-1378,-1525,-1440,-1770,-1552,-1378,-1390,-1616,-1648,-1482,-1616,-1390,-1728,-1770,-2047,-1685,-1616,-1648,-1685,-1584,-2047,-1856,-1856,-2047,-2047,-2047,-92,-481,-583,-623,-602,-691,-803,-815,-584,-728,-743,-796,-734,-884,-728,-1616,-747,-416,-510,-265,1,-44,-409,141,-1014,-1094,-201,-490,-533,-537,-605,-536,-564,-676,-620,-688,-43,-439,-361,-455,-178,-309,-315,-396,-273,-367,-341,-92,-202,-138,-105,-117,-4,107,36,90,169,222,-14,-92,-125,-219,-268,-344,70,-137,-49,4,171,-72,-224,210,319,15,386,-2,-195,298,53,-31,339,95,383,499,557,491,457,468,421,-53,-168,267,485,573,508,-65,-109,115,568,576,619,685,179,878,131,851,175,286,19,-21,113,245,-54,101,210,-121,766,-47,282,441,483,129,303,16,557,460,114,492,596,580,557,605,133,643,154,-115,668,683,332,-44,685,735,765,757,889,890,922,917,1012,1170,116,1104,1192,1199,1213,1368,254,1462,307,1616,359,50,1368,237,52,-112,-47,-416,-255,-101,55,-177,-166,-73,-132,-56,-132,-237,-495,-152,-43,69,46,-121,-191,-102,170,-137,-45,-364,-57,-212,7,1,1,1,1,1,1,1,1,1,1,},
{-30,-722,684,-930,-1006,-1155,-1191,-1212,-1332,-1149,-1276,-1297,-1320,-1285,-1344,-1648,-1402,-1482,-1552,-1255,-1344,-1504,-1728,-1525,-1418,-1728,-1856,-1584,-1390,-1552,-1552,-1984,-1482,-1525,-1856,-2047,-1525,-1770,-1648,-1770,-1482,-1482,-1482,-1584,-2047,-2047,-1552,-2047,-2047,-2047,-2047,-1984,-2047,0,-376,-502,-568,-710,-761,-860,-838,-750,-1058,-897,-787,-865,-646,-844,-979,-1000,-416,-564,-832,-416,-64,-555,304,-954,-1081,-219,-448,-543,-510,-550,-544,-564,-650,-595,-747,-61,-460,-404,-430,-183,-287,-315,-366,-311,-347,-328,-109,-240,-151,-117,-156,-32,64,19,78,116,223,6,-195,-125,-204,-267,-346,63,-125,-92,-22,186,-128,-169,182,290,-14,384,-27,-134,303,0,-5,328,96,351,483,459,529,423,447,390,-104,-165,214,448,588,550,-127,-146,31,552,563,620,718,-50,832,14,851,93,281,60,-5,121,257,-16,103,138,-184,842,-21,319,386,411,107,258,66,475,542,178,501,506,568,685,640,78,694,122,-96,634,826,165,220,794,736,960,746,823,833,939,1045,1004,1248,22,1118,1077,1213,1127,1552,241,1440,282,1483,315,-102,1391,352,124,-188,19,1,-268,-782,0,-322,116,46,-129,95,-102,-238,-459,-262,-100,122,-152,-455,-269,-238,0,-152,-416,-369,-219,-175,-41,1,1,1,1,1,1,1,1,1,1,},
{-11,-533,477,-632,-731,-815,-808,-910,-940,-995,-1094,-1040,-946,-1044,-1198,-1099,-1104,-1090,-1162,-1122,-1145,-1205,-1248,-1269,-1255,-1285,-1140,-1219,-1269,-1285,-1269,-1367,-1344,-1390,-1482,-1332,-1378,-1461,-1332,-1461,-1525,-1584,-1418,-1504,-1648,-1648,-1648,-1856,-1856,-1616,-1984,-1525,-2047,-330,-456,-533,-524,-541,-577,-631,-715,-670,-710,-729,-743,-738,-759,-775,-850,-690,-193,-870,-102,21,-45,-282,96,-1000,-984,-177,-475,-506,-514,-582,-597,-602,-622,-633,-695,-22,-422,-381,-435,-107,-290,-327,-360,-316,-366,-374,-62,-212,-111,-162,-83,-8,127,52,101,193,237,-16,-117,-150,-246,-275,-361,122,-134,-21,28,220,-132,-215,231,330,40,406,-11,-196,329,68,-42,391,101,396,483,519,480,464,516,484,-34,-200,269,487,525,510,-79,-142,150,517,555,594,718,86,861,102,840,134,291,74,10,166,245,16,117,-21,-126,652,-71,291,355,491,10,251,-21,527,525,43,532,531,573,631,640,31,629,87,-164,680,755,145,14,621,647,723,748,687,821,745,794,785,859,23,887,969,996,1007,1286,104,1321,138,1321,169,-24,1227,123,116,13,45,-198,-38,-214,-22,-241,13,-161,-54,-108,-120,-345,-484,-119,-80,-58,-189,-253,-223,-106,-73,-57,-64,-268,-208,-4,12,1,1,1,1,1,1,1,1,1,1,},
{-38,-419,362,-548,-577,-699,-725,-838,-860,-869,-891,-970,-989,-1030,-1014,-1030,-1169,-1067,-1113,-1155,-1212,-1176,-1269,-1205,-1320,-1378,-1169,-1285,-1418,-1240,-1320,-1332,-1402,-1390,-1285,-1402,-1262,-1240,-1616,-1320,-1552,-1440,-1320,-1685,-1482,-1685,-1320,-1616,-1856,-1616,-1856,-2047,-1728,-302,-466,-608,-475,-502,-550,-598,-623,-584,-716,-679,-759,-767,-579,-713,-686,-652,-294,-791,-240,-55,-177,-377,-108,-789,-858,-226,-370,-423,-449,-474,-481,-503,-541,-551,-561,-93,-353,-345,-358,-93,-215,-246,-295,-304,-304,-349,-48,-200,-90,-150,-52,-14,92,19,105,177,217,28,-44,-83,-155,-199,-273,53,-133,-7,26,135,-90,-137,177,250,32,355,55,-89,254,67,-21,318,152,373,387,413,427,385,436,355,41,-121,261,406,470,452,40,-58,223,474,546,572,534,184,682,205,757,263,276,6,-51,78,186,-65,48,-46,-18,483,3,251,334,444,115,254,80,480,480,207,476,511,570,603,561,170,583,145,-7,662,647,287,88,608,618,713,728,725,718,520,599,621,664,135,703,701,771,807,903,324,885,240,880,296,109,920,305,-24,-314,-44,-202,-145,-481,-379,-341,-128,-187,-179,-342,-201,-419,-405,-214,-150,-119,-493,-447,-133,-331,-224,-513,-156,-247,-108,-177,-95,1,1,1,1,1,1,1,1,1,1,},
{-37,-350,295,-455,-569,-592,-653,-686,-764,-819,-825,-897,-954,-908,-951,-984,-987,-924,-995,-1030,-1081,-1019,-1022,-1058,-995,-1122,-1009,-1090,-1085,-1191,-1094,-1000,-1026,-1248,-1162,-1285,-1085,-1108,-1017,-1219,-1126,-1026,-976,-1320,-1320,-1584,-1176,-2047,-1728,-2047,-1685,-2047,-2047,-281,-492,-568,-551,-564,-636,-701,-736,-690,-667,-831,-841,-806,-897,-888,-881,-891,-337,-884,-120,-123,-143,-359,-15,-910,-981,-205,-440,-499,-526,-549,-533,-614,-591,-653,-690,-124,-423,-445,-405,-125,-246,-285,-297,-345,-303,-378,-95,-189,-96,-131,-66,2,63,49,115,146,223,82,-60,-96,-204,-248,-326,90,-142,34,-33,157,-125,-178,234,296,48,383,90,-69,333,139,5,369,152,398,419,426,467,455,528,475,61,-139,316,502,560,502,45,-102,213,537,596,606,622,159,820,222,813,247,254,16,-45,88,214,-73,18,-73,-90,450,-44,237,349,400,61,151,3,405,454,124,431,414,518,618,616,95,647,67,-146,593,697,64,-41,560,589,620,708,826,723,507,555,601,690,-35,778,814,875,894,1248,148,1333,138,1234,136,-7,1298,88,0,-55,-49,-137,-138,-159,-101,-346,-136,-214,47,-219,-199,-411,-416,-187,-82,-97,-416,-241,-267,-436,-343,55,-273,-198,-24,-103,-90,1,1,1,1,1,1,1,1,1,1,},
{-104,-555,421,-707,-754,-855,-874,-943,-970,-1030,-1014,-1113,-1226,-1131,-1122,-1418,-1176,-1276,-1155,-1205,-1367,-1378,-1482,-1332,-1320,-1685,-1482,-1440,-1191,-1552,-1262,-1233,-1440,-1402,-1402,-1240,-1367,-1770,-1355,-1770,-1344,-1344,-1176,-1053,-1145,-1131,-1276,-1616,-1344,-1525,-1418,-1248,-1390,-660,-337,-1122,-359,-511,-549,-1169,-678,-1040,-459,-660,-640,-625,-1019,-1003,-590,-1040,1,1,246,569,62,-337,660,-681,-703,-179,-335,-459,-445,-503,-450,-529,-489,-616,-507,2,-270,-234,-326,-124,-171,-222,-251,-261,-220,-387,-90,-166,-24,-40,-93,28,-88,214,129,119,182,69,-24,-44,-133,-215,-255,42,-123,-12,4,121,-87,-49,172,200,105,315,85,-110,221,117,18,298,151,347,286,359,307,369,371,328,-31,-141,196,432,459,537,14,-215,370,563,662,614,683,84,625,176,652,370,250,-2,74,114,223,8,201,-152,0,550,4,274,270,334,40,280,122,498,381,313,382,388,481,524,555,213,562,460,1,521,449,456,139,620,671,565,732,588,868,612,740,718,736,114,783,820,889,988,1001,270,990,191,1027,146,304,1010,164,48,-56,896,-416,-213,-416,416,-732,-95,95,-208,1,-416,100,-95,95,17,124,1,-416,246,220,0,1,0,0,46,256,-57,1,1,1,1,1,1,1,1,1,1,},
{-44,-551,478,-690,-789,-913,-935,-1006,-995,-1131,-1035,-1169,-1099,-1198,-1297,-1145,-1309,-1198,-1219,-1226,-1332,-1248,-1378,-1297,-1390,-1226,-1378,-1440,-1584,-1418,-1552,-1269,-1402,-1504,-1552,-1461,-1584,-1504,-1616,-1584,-1482,-1685,-1856,-1856,-1685,-1685,-1482,-1770,-1685,-1984,-2047,-1856,-1856,-405,-619,-642,-574,-582,-618,-752,-619,-780,-682,-680,-624,-772,-699,-935,-815,-749,-897,-711,-601,-99,-251,-398,-331,-846,-930,-330,-455,-488,-470,-572,-563,-570,-583,-615,-706,-216,-377,-415,-415,-166,-256,-310,-338,-397,-349,-442,-114,-229,-103,-168,-65,-20,68,26,96,200,239,91,-3,-53,-140,-231,-335,12,-174,-67,-46,91,-44,-225,172,272,74,398,150,-28,299,116,18,377,156,465,470,502,486,439,471,367,64,-97,319,471,506,593,194,34,334,501,637,649,669,321,767,291,799,444,312,-56,-173,4,161,-170,-226,-314,-29,614,93,322,425,460,123,341,185,496,523,250,506,544,613,579,619,312,708,322,184,674,603,372,423,691,767,746,747,792,732,750,776,845,1010,319,977,996,1040,985,1256,381,1277,458,1256,457,0,1321,432,-226,-370,-187,-869,-374,-416,-69,-503,-308,-371,-403,-255,-297,-408,-891,-471,-243,-805,-398,-134,-569,-319,-960,-610,-543,-398,-231,-268,-244,1,1,1,1,1,1,1,1,1,1,},
{-46,-743,732,-916,-1030,-1006,-1090,-1145,-1162,-1117,-1184,-1367,-1378,-1233,-1176,-1309,-1378,-1205,-1616,-1367,-1482,-1402,-1552,-1482,-1461,-1233,-1504,-1390,-1482,-1525,-1504,-1461,-1320,-1402,-1525,-1856,-1504,-1482,-1332,-1648,-1461,-1402,-1440,-1770,-1770,-1504,-2047,-1685,-1856,-2047,-2047,-2047,-2047,-247,-366,-436,-532,-534,-616,-668,-721,-697,-855,-627,-780,-729,-722,-848,-998,-654,-208,-1104,-320,-93,-79,-270,324,-938,-1003,-176,-441,-492,-495,-533,-553,-546,-538,-605,-637,-63,-409,-404,-436,-121,-268,-317,-390,-364,-367,-367,-131,-231,-113,-133,-104,-4,-14,17,106,146,191,95,-58,-115,-216,-278,-388,37,-174,175,-295,128,-162,-239,281,374,13,519,-41,-26,307,130,24,345,128,398,419,468,494,529,545,521,-107,-39,270,538,576,473,-115,171,418,511,585,620,588,-125,823,-85,875,-88,266,-97,-39,32,191,-68,-41,83,-266,875,-11,268,336,502,114,185,15,593,528,121,606,481,633,733,539,85,792,245,-201,653,795,591,-97,606,592,707,794,873,837,925,1001,1100,1156,98,1059,1199,1177,1213,1504,157,1526,183,1526,70,-29,1419,180,104,-109,-38,-219,-150,-255,-169,-280,0,-250,19,-26,-48,-462,-352,-175,16,-60,-195,-255,-63,-121,370,-198,1,-208,-99,-66,4,1,1,1,1,1,1,1,1,1,1,},
{-9,-75,59,-120,-186,-252,-341,-388,-442,-515,-556,-561,-537,-570,-627,-624,-600,-622,-620,-679,-696,-695,-729,-748,-800,-810,-862,-718,-838,-848,-846,-951,-879,-1104,-813,-930,-998,-1162,-838,-935,-872,-949,-1108,-848,-1030,-1145,-865,-1212,-1205,-1367,-1233,-1205,-1226,-874,-505,-483,-449,-446,-454,-462,-506,-479,-490,-510,-546,-511,-592,-563,-575,-589,-365,-501,-409,-315,-363,-470,-386,-597,-599,-357,-336,-329,-365,-404,-408,-430,-432,-476,-484,-256,-325,-316,-268,-184,-159,-190,-207,-252,-281,-302,-107,-103,-57,-62,-3,34,56,30,71,135,184,138,95,41,0,-43,-117,-68,-57,-59,-8,-21,-34,-84,79,169,42,275,197,54,228,146,121,243,176,278,302,327,325,318,327,292,182,25,251,338,356,384,253,210,326,460,448,465,453,366,606,386,601,467,209,-101,-247,-34,12,-191,-124,-350,89,128,67,147,209,256,184,237,155,310,361,260,371,385,443,462,467,280,494,344,249,519,549,409,319,555,551,562,591,601,662,205,281,334,440,248,472,510,562,607,809,463,807,462,832,500,250,878,469,-178,-442,-272,-439,-389,-419,-457,-402,-433,-428,-405,-441,-330,-352,-349,-316,-345,-588,-1019,-569,-862,-433,-374,-471,-577,-532,-556,-333,-225,1,1,1,1,1,1,1,1,1,1,},
{-19,-99,100,-211,-273,-354,-476,-580,-676,-693,-752,-772,-865,-843,-889,-927,-951,-981,-981,-1044,-1017,-1000,-1040,-1030,-984,-995,-1067,-1014,-1094,-1076,-1003,-1017,-1030,-1131,-1053,-1085,-1081,-1136,-1233,-1090,-1155,-1169,-1099,-1067,-1117,-1276,-1058,-1504,-1856,-1482,-1504,-1584,-1482,-508,-415,-521,-445,-467,-471,-522,-510,-528,-573,-579,-579,-598,-612,-653,-636,-623,-482,-757,-362,-278,-314,-391,-256,-620,-669,-380,-359,-385,-402,-433,-438,-474,-498,-501,-540,-290,-312,-369,-298,-166,-152,-185,-221,-231,-292,-302,-108,-102,-45,-64,-24,37,45,16,68,123,167,116,88,52,-1,-51,-106,-25,-84,-47,-16,-16,-32,-83,69,178,61,310,185,93,232,150,82,255,168,274,308,304,320,360,385,336,218,31,287,429,420,430,265,212,321,487,493,504,506,380,674,390,702,433,199,-84,-227,-62,10,-215,-109,-439,116,199,33,133,203,270,176,221,123,322,387,241,377,429,444,501,542,297,535,358,219,598,573,305,321,641,620,662,682,676,722,315,391,479,581,245,647,711,787,785,1199,442,1206,494,1177,486,311,1234,483,-145,-430,-238,-527,-405,-373,-368,-476,-454,-377,-320,-385,-290,-317,-374,-270,-322,-566,-544,-653,-651,-387,-554,-590,-354,-491,-349,-347,-202,1,1,1,1,1,1,1,1,1,1,},
{-15,-126,83,-181,-261,-335,-460,-592,-640,-716,-800,-774,-832,-869,-886,-965,-957,-979,-992,-1000,-970,-1094,-1000,-976,-989,-1062,-1076,-1140,-1030,-1113,-1044,-1017,-1099,-1040,-1081,-1145,-1090,-1076,-1136,-1117,-1090,-1198,-1099,-1184,-1169,-1140,-1076,-1525,-1504,-1616,-1856,-1525,-1525,-637,-419,-510,-461,-473,-565,-519,-569,-523,-558,-608,-608,-619,-684,-587,-631,-692,-350,-678,-352,-239,-344,-411,-174,-669,-647,-354,-370,-383,-448,-441,-431,-482,-490,-507,-534,-268,-342,-340,-297,-169,-173,-208,-217,-236,-283,-291,-109,-95,-46,-72,18,40,51,28,79,138,175,96,83,44,-3,-61,-92,-19,-77,-41,-13,14,-38,-64,78,176,54,311,176,87,231,142,106,246,150,262,311,347,332,345,352,346,207,13,269,393,454,414,253,165,291,491,484,533,498,345,664,388,685,442,203,-83,-260,-60,24,-198,-80,-348,38,240,65,146,218,289,163,263,100,355,370,268,403,441,475,480,542,305,545,339,238,598,593,379,325,643,631,617,671,730,712,350,390,490,583,228,626,675,726,832,1192,443,1277,470,1286,495,128,1248,426,-145,-427,-184,-374,-441,-363,-239,-439,-345,-426,-314,-274,-285,-336,-369,-335,-280,-374,-559,-694,-470,-379,-462,-507,-383,-379,-293,-320,-158,1,1,1,1,1,1,1,1,1,1,},
{-1,-95,89,-151,-218,-277,-429,-483,-610,-643,-756,-775,-749,-775,-839,-855,-883,-895,-921,-893,-908,-1017,-935,-1009,-1030,-973,-989,-976,-1014,-1090,-1011,-1017,-1000,-954,-1226,-1062,-1131,-1081,-1035,-1117,-1104,-1058,-1049,-1191,-1053,-1248,-1169,-1367,-1648,-1418,-1390,-1378,-1525,-844,-587,-618,-562,-573,-606,-581,-595,-592,-628,-670,-652,-633,-648,-721,-656,-683,-359,-810,-497,-505,-422,-495,-286,-694,-679,-411,-378,-375,-414,-464,-478,-469,-509,-488,-505,-337,-306,-345,-295,-169,-171,-171,-206,-211,-267,-284,-100,-114,-43,-58,-7,33,45,22,84,124,166,127,99,49,22,-69,-97,-63,-70,-28,-18,-16,-49,-80,87,189,83,287,223,131,227,150,107,231,157,261,258,288,325,358,380,355,287,68,322,389,426,437,308,287,373,473,485,535,496,431,659,484,627,496,182,-108,-288,-120,-22,-275,-200,-554,42,203,49,154,205,298,194,246,184,338,388,287,427,460,507,501,591,338,614,432,278,591,614,506,403,702,723,738,738,741,769,283,393,489,593,292,629,730,744,851,1263,610,1199,637,1170,713,246,1177,647,-183,-560,-333,-424,-538,-503,-1169,-575,-421,-479,-437,-549,-419,-403,-494,-368,-372,-637,-723,-1461,-850,-603,-515,-670,-613,-445,-484,-378,-233,1,1,1,1,1,1,1,1,1,1},
}
;
template<const bool encode>
class Encoder {
// Buffer - array of n last bytes
int pos = 0;
class Buf {
Array<U8> b;
int &pos;
public:
Buf(size_t i, int& pos):b(i), pos(pos) {}
U8& operator[](U32 i) { return b[i & (b.size() - 1)]; }
int operator()(U32 i) const { return b[(pos - i) & (b.size() - 1)]; }
size_t size() const { return b.size(); }
};
// Global variables
int y = 0, c0 = 1, bpos = 0, bytes_written = 0, bytes_read = 24, rn = 0;
U32 c4 = 0;
Buf buf;
// Hash
inline U32 hash(U32 a, U32 b, U32 c=0xffffffff, U32 d=0xffffffff,
U32 e=0xffffffff) {
U32 h=a*200002979u+b*30005491u+c*50004239u+d*70004807u+e*110002499u;
return h^h>>9^a>>2^b>>3^c>>4^d>>5^e>>6;
}
static int squash(int d) {
const int t[33] = {
1,2,3,6,10,16,27,45,73,120,194,310,488,747,1101,1546,2047,2549,2994,3348,3607,3785,3901,3975,4022,4050,4068,4079,4085,4089,4092,4093,4094};
if (d > 2047) return 4095;
if (d < -2047) return 0;
int w = d & 127;
d = (d >> 7) + 16;
return (t[d] * (128 - w) + t[(d + 1)] * w + 64) >> 7;
}
/*
class Stretch {
Array<short> t;
public:
int operator()(int x) const { return t[x]; }
Stretch():t(4096) {
for (int x = -2047, j = 0; x <= 2047; ++x) {
int i = squash(x);
while (j <= i) t[j++] = x;
}
t[4095] = 2047;
}
} stretch;
*/
#if defined(__SSE2__)
static int dot_product (const short* const t, const short* const w) {
__m128i sum = _mm_madd_epi16 (*(__m128i *) &t[0], *(__m128i *) &w[0]);
sum = _mm_srai_epi32 (sum, 8);
sum = _mm_add_epi32 (sum, _mm_srli_si128 (sum, 8));
sum = _mm_add_epi32 (sum, _mm_srli_si128 (sum, 4));
return _mm_cvtsi128_si32 (sum);
}
static void train (const short* const t, short* const w, const int e) {
if (e) {
const __m128i one = _mm_set1_epi16 (1);
const __m128i err = _mm_set1_epi16 (short(e));
__m128i tmp = _mm_adds_epi16 (*(__m128i *) &t[0], *(__m128i *) &t[0]);
tmp = _mm_mulhi_epi16 (tmp, err);
tmp = _mm_adds_epi16 (tmp, one);
tmp = _mm_srai_epi16 (tmp, 1);
tmp = _mm_adds_epi16 (tmp, *(__m128i *) &w[0]);
*(__m128i *) &w[0] = tmp;
}
}
#else
static int dot_product (const short* const t, const short* const w) {
int sum = 0, n = 8;
while ((n -= 2) >= 0) {
sum += (t[n] * w[n] + t[n + 1] * w[n + 1]) >> 8;
}
return sum;
}
static void train (const short* const t, short* const w, const int err) {
int n = 8;
if (err) {
while ((n -= 1) >= 0) {
int wt = w[n] + ((((t[n] * err * 2) >> 16) + 1) >> 1);
if (wt < -32768) {
w[n] = -32768;
} else if (wt > 32767) {
w[n] = 32767;
} else {
w[n] = wt;
}
}
}
}
#endif
// Mixer - combines models using neural networks
class Mixer {
const int N;
Array<short,16> tx;
int pr, nx, ofs;
int &y;
public:
Mixer(int n, int&y):
N((n + 7) & -8), tx(4096), pr(0), nx(0), ofs(0), y(y) {
for (int i = 0; i < 4096; ++i) {
tx[i] = 0;
}
}
void setcxt(int c) { ofs = c << 4;}
void update() {
int err = ((y << 12) - squash(pr)) * 7;
train(&tx[ofs + 0], &tx[ofs + 8], err);
nx = 0;
}
void add(short x) { tx[ofs + nx++] = x; }
int p() {
while (nx & 7) tx[ofs + nx++] = 64;
return pr = (dot_product(&tx[ofs + 0], &tx[ofs + 8]) >> 7);
}
};
// ContextMap
class ContextMap {
Array<U8, 64> t;
U8* cp[6];
U32 cxt[6];
int cn;
int &y;
int &c0;
int &bpos;
public:
ContextMap(size_t m, int &y, int &c0, int &bpos):t(m), cn(0), y(y), c0(c0), bpos(bpos) {
for (int i = 0; i < 6; ++i) { cp[i] = 0; }
}
void set(U32 cx) {
cxt[cn++] = cx * 16;
}
void mix(Mixer&m) {
for (int i = 0; i < cn; ++i) {
if (cp[i]) {
*cp[i] = State_table[*cp[i]][y]; // Update state
}
}
const int c0b = c0 < 16 ? c0 : (16 * (1 + ((c0 >> (bpos - 4)) & 15))) +
((c0 & ((1 << (bpos - 4)) - 1)) | (1 << (bpos - 4)));
for (int i = 0; i < cn; ++i) {
cp[i] = &t[(cxt[i] + c0b) & (t.size() - 1)]; // Update bit context pointers
}
for (int i = 0; i < cn; ++i) {
m.add(sm[i][*cp[i]]); // Predict from bit context
}
if (bpos == 7) cn = 0;
}
};
// Match submodel
int h = 0, ptr = 0, len = 0;
Array<int> t;
inline void matchModel(Mixer *m) {
const int MAXLEN = 88;
if (!bpos) {
h = (h * 997 * 8 + buf(1) + 1) & (t.size() - 1);
if (len) {
++len, ++ptr;
if (len > MAXLEN) len = MAXLEN;
} else {
ptr = t[h];
if (ptr && pos - ptr < (int)buf.size()) {
while (buf(len + 1) == buf[ptr - len - 1] && len < MAXLEN) ++len;
}
}
t[h] = pos;
}
int p = 0;
if (len) {
if (buf(1) == buf[ptr - 1] && c0 == (buf[ptr] + 256) >> (8 - bpos)) {
if (len<24) p = len << 6; else
p = (24 + ((len-24)>>3))<< 6;
if ((buf[ptr] >> (7 - bpos) & 1) == 0) p = -p;
m->add(p);
} else {
len=0;
}
}
}
class IntBuf {
Array<int> b;
public:
IntBuf(int i=0): b(i) {}
int& operator[](int i) {
return b[i&(b.size()-1)];
}
};
class Ilog {
U8 t[6554];
public:
int operator()(int x) const {return x < 0 ? -t[-x] : t[x];}
// Compute lookup table by numerical integration of 1/x
Ilog() {
U32 x=14155776;
for (int i=2; i<65536; ++i) {
x+=774541002/(i*2-1); // numerator is 2^29/ln 2
if ((i-1) % 10 == 0) t[(i-1) / 10] = (x >> 24) / 10;
}
}
} ilog;
//////////////////////////// jpegModel /////////////////////////
int jpegModel(Mixer& m) {
return 0;
}
Mixer mixer;
ContextMap cm;
// Main model - predicts next bit probability from previous data
int predictNext() {
mixer.update();
c0 += c0 + y;
if (c0 >= 256) {
buf[pos++] = c0;
c4 = (c4 << 8) + c0 - 256;
c0 = 1;
}
bpos = (bpos + 1) & 7;
if (!jpegModel(mixer))
{
if (bpos == 0) {
mixer.setcxt(c4 & 0xff);
cm.set(0);
cm.set(16 *(1 + (c4 & 0xff)));
if (bytes_read + bytes_written > (1 << 9)) bytes_read >>= 1, bytes_written >>= 1;
if ((bytes_written+(bytes_written>>4)) <= bytes_read) {
cm.set(hash(256,c4 & 0x0000ffff));
cm.set(hash(257,c4 & 0x00ffffff));
cm.set(hash(258,c4));
cm.set(hash(c4,(buf(5)<<8)+buf(6)));
rn = 0;
} else {
rn = 1;
}
}
cm.mix(mixer);
matchModel(&mixer);
}
int pr = mixer.p();
if (pr < -2048) pr = -2048;
if (pr > 2047) pr = 2047;
return squash(pr);
}
private:
U32 x = 0, x1 = 0, x2 = 0xffffffff;
int p = 2048;
std::istream ∈
std::ostream &out;
int code(int i = 0) {
p += p < 2048;
U32 xmid = x1 +((x2 - x1) >> 12) * p + (((x2 - x1) & 0xfff) * p >> 12);
if (!encode) y = x <= xmid; else y = i;
p = predictNext(); // Update models and predict next bit probability
y ? (x2 = xmid) : (x1 = xmid + 1);
while (!((x1 ^ x2) >> 24)) {
if (encode) out.put(x2 >> 24);
x1 <<= 8;
x2 = (x2 << 8) + 255;
if (!encode) x = (x << 8) + (in.get() & 255);
bytes_written++;
}
return y;
}
public:
Encoder(std::istream &in, std::ostream &out, size_t MEM = (0x10000u << 7) /* may be increased up to 10 on x64 platforms */ ):
in(in), out(out), buf(MEM * 8, pos), t(MEM), mixer(8,y), cm(MEM * 32, y, c0, bpos)
{
if (!encode) {
for (int i = 0; i < 4; ++i) {
x = (x << 8) + (in.get() & 255);
}
}
}
void flush() { out.put(x1 >> 24); }
void compress(int c) {
for (int i = 7; i >= 0; --i) {
code((c >> i) & 1);
}
bytes_read++;
}
int decompress() {
int c = 0;
for (int i = 0; i < 8; ++i) {
c += c + code();
}
bytes_read++;
return c;
}
};
}
#if 0
// Main program
int main(int argc, char **argv)
{
printf("TANGELO 2.4 compressor (C) 2013, based on PAQ8 by Matt Mahoney et al.\nFree under GPL, http://www.gnu.org/licenses/gpl.txt\n");
if (argc != 4 || argv[1][1] != 0 || (argv[1][0] != 'c' && argv[1][0] != 'd')) {
printf("\nUsage: TANGELO <command> <infile> <outfile>\n");
printf("\n<Commands>\n c\t\tCompress\n d\t\tDecompress\n");
return (1);
}
FILE *in = fopen( argv[2], "rb" );
fseek(in, 0L, SEEK_END);
int len = ftell(in);
fclose(in);
std::ifstream ifs( argv[2], std::ios::binary );
std::ofstream ofs( argv[3], std::ios::binary );
if (ifs.bad() || ofs.bad()) {
printf("Cannot read/write file\n");
return (1);
}
clock_t start_time = clock();
if (argv[1][0] != 'd') {
printf("Compressing %s...\n", argv[2]);
tangelo::Encoder<1> en(ifs, ofs);
en.compress(len >> 24);
en.compress(len >> 16);
en.compress(len >> 8);
en.compress(len);
for (int i = 0; i < len; i++) {
en.compress(ifs.get());
}
en.flush();
printf("Compressed from %d bytes to %d bytes.\n", len, -1);
} else {
printf("Decompressing %s...\n", argv[2]);
tangelo::Encoder<0> en(ifs, ofs);
int len;
len = en.decompress() << 24;
len |= en.decompress() << 16;
len |= en.decompress() << 8;
len |= en.decompress();
for (int i = 0; i < len; i++) {
ofs.put(en.decompress());
}
printf("Decompressed from %d bytes to %d bytes.\n", -1, len);
}
printf("Time %1.2f sec\n", double(clock() - start_time) / CLOCKS_PER_SEC);
return (0);
}
#endif
| 66.139394
| 2,335
| 0.603989
|
VIGGEEN
|
9aaa99d169b73cf6fa5fa041b898a58591681359
| 261
|
hpp
|
C++
|
source/library/progrock/c/fenv.hpp
|
progrock-libraries/C-header-wrappers
|
9b0e870f9833a66becac3379633e8818c0be19b3
|
[
"MIT"
] | 2
|
2021-09-21T18:34:27.000Z
|
2022-02-13T02:50:57.000Z
|
source/library/kickstart/c/fenv.hpp
|
progrock-libraries/kickstart
|
d62c22efc92006dd76d455cf8f9d4f2a045e9126
|
[
"MIT"
] | null | null | null |
source/library/kickstart/c/fenv.hpp
|
progrock-libraries/kickstart
|
d62c22efc92006dd76d455cf8f9d4f2a045e9126
|
[
"MIT"
] | null | null | null |
#pragma once // Source encoding: UTF-8 (π is a lowercase Greek "pi").
// #include <c/fenv.hpp>
//
// Floating-point environment access functions.
// Copyright © 2017 Alf P. Steinbach, distributed under Boost license 1.0.
#include <cfenv>
#include <fenv.h>
| 29
| 74
| 0.697318
|
progrock-libraries
|
9aaca5e0c452f2b8bbf69057aa4a80d9602e5b41
| 8,285
|
hpp
|
C++
|
include/kfusion/internal.hpp
|
chenguowen/dynfu
|
5991e43144e9b3a95005c820f87900a6b21c7826
|
[
"BSD-3-Clause"
] | 34
|
2018-10-10T05:56:53.000Z
|
2022-03-02T09:17:05.000Z
|
include/kfusion/internal.hpp
|
chenguowen/dynfu
|
5991e43144e9b3a95005c820f87900a6b21c7826
|
[
"BSD-3-Clause"
] | 1
|
2019-04-29T12:29:22.000Z
|
2019-05-14T15:33:12.000Z
|
include/kfusion/internal.hpp
|
chenguowen/dynfu
|
5991e43144e9b3a95005c820f87900a6b21c7826
|
[
"BSD-3-Clause"
] | 11
|
2018-08-13T02:27:29.000Z
|
2021-12-02T06:43:18.000Z
|
#pragma once
#include <kfusion/cuda/device_array.hpp>
#include <kfusion/safe_call.hpp>
#include <pcl/point_types.h>
//#define USE_DEPTH
namespace kfusion {
namespace device {
typedef float4 Normal;
typedef float4 Point;
typedef unsigned short ushort;
typedef unsigned char uchar;
typedef PtrStepSz<ushort> Dists;
typedef DeviceArray2D<ushort> Depth;
typedef DeviceArray2D<Normal> Normals;
typedef DeviceArray2D<Point> Points;
typedef DeviceArray2D<uchar4> Image;
typedef float4 PointType;
typedef int3 Vec3i;
typedef float3 Vec3f;
struct Mat3f {
float3 data[3];
};
struct Aff3f {
Mat3f R;
Vec3f t;
};
struct TsdfVolume {
public:
typedef ushort2 elem_type;
elem_type *const data;
const int3 dims;
const float3 voxel_size;
const float trunc_dist;
const int max_weight;
TsdfVolume(elem_type *const data, int3 dims, float3 voxel_size, float trunc_dist, int max_weight);
// TsdfVolume(const TsdfVolume &);
TsdfVolume &operator=(const TsdfVolume &);
__kf_device__ elem_type *operator()(int x, int y, int z);
__kf_device__ const elem_type *operator()(int x, int y, int z) const;
__kf_device__ elem_type *beg(int x, int y) const;
__kf_device__ elem_type *zstep(elem_type *const ptr) const;
};
struct Projector {
float2 f, c;
Projector() {}
Projector(float fx, float fy, float cx, float cy);
__kf_device__ float2 operator()(const float3 &p) const;
};
struct Reprojector {
Reprojector() {}
Reprojector(float fx, float fy, float cx, float cy);
float2 finv, c;
__kf_device__ float3 operator()(int x, int y, float z) const;
};
struct CubeIndexEstimator {
CubeIndexEstimator(const TsdfVolume &vol) : volume(vol) { isoValue = 0.f; }
enum { VOL_X = 128, VOL_Y = 128, VOL_Z = 128 }; /* FIXME (dig15): do not hardcode */
const TsdfVolume volume;
float isoValue;
__kf_device__ void readTsdf(int x, int y, int z, float &f, int &weight) const;
__kf_device__ int computeCubeIndex(int x, int y, int z, float f[8]) const;
};
struct OccupiedVoxels : public CubeIndexEstimator {
OccupiedVoxels(const TsdfVolume &vol) : CubeIndexEstimator({vol}) {}
/* FIXME (dig15) : verify that these values iterate through all indices */
enum {
CTA_SIZE_X = 16,
CTA_SIZE_Y = 4,
CTA_SIZE = CTA_SIZE_X * CTA_SIZE_Y,
WARPS_COUNT = CTA_SIZE / 4
};
mutable int *voxels_indices;
mutable int *vertices_number;
int max_size;
__kf_device__ void operator()() const;
};
struct TrianglesGenerator : public CubeIndexEstimator {
TrianglesGenerator(const TsdfVolume &vol) : CubeIndexEstimator({vol}) {}
/* FIXME (dig15) : verify that these values iterate through all indices */
enum { CTA_SIZE = 128, MAX_GRID_SIZE_X = 65536 };
const int *occupied_voxels;
const int *vertex_ofssets;
int voxels_count;
float3 cell_size;
mutable device::PointType *output;
__kf_device__ float3 getNodeCoo(int x, int y, int z) const;
__kf_device__ float3 vertex_interp(float3 p0, float3 p1, float f0, float f1) const;
__kf_device__ void store_point(float4 *ptr, int index, const float3 &point) const;
__kf_device__ void operator()() const;
}; // namespace device
struct ComputeIcpHelper {
struct Policy;
struct PageLockHelper {
float *data;
PageLockHelper();
~PageLockHelper();
};
float min_cosine;
float dist2_thres;
Aff3f aff;
float rows, cols;
float2 f, c, finv;
PtrStep<ushort> dcurr;
PtrStep<Normal> ncurr;
PtrStep<Point> vcurr;
ComputeIcpHelper(float dist_thres, float angle_thres);
void setLevelIntr(int level_index, float fx, float fy, float cx, float cy);
void operator()(const Depth &dprev, const Normals &nprev, DeviceArray2D<float> &buffer, float *data,
cudaStream_t stream);
void operator()(const Points &vprev, const Normals &nprev, DeviceArray2D<float> &buffer, float *data,
cudaStream_t stream);
static void allocate_buffer(DeviceArray2D<float> &buffer, int partials_count = -1);
// private:
__kf_device__ int find_coresp(int x, int y, float3 &n, float3 &d, float3 &s) const;
__kf_device__ void partial_reduce(const float row[7], PtrStep<float> &partial_buffer) const;
__kf_device__ float2 proj(const float3 &p) const;
__kf_device__ float3 reproj(float x, float y, float z) const;
};
// tsdf volume functions
void clear_volume(TsdfVolume volume);
void integrate(const Dists &depth, TsdfVolume &volume, const Aff3f &aff, const Projector &proj);
void raycast(const TsdfVolume &volume, const Aff3f &aff, const Mat3f &Rinv, const Reprojector &reproj, Depth &depth,
Normals &normals, float step_factor, float delta_factor);
void raycast(const TsdfVolume &volume, const Aff3f &aff, const Mat3f &Rinv, const Reprojector &reproj, Points &points,
Normals &normals, float step_factor, float delta_factor);
__kf_device__ ushort2 pack_tsdf(float tsdf, int weight);
__kf_device__ float unpack_tsdf(ushort2 value, int &weight);
__kf_device__ float unpack_tsdf(ushort2 value);
/* marching cubes functions /*
/** \brief binds marching cubes tables to texture references */
void bindTextures(const int *edgeBuf, const int *triBuf, const int *numVertsBuf);
/** \brief unbinds */
void unbindTextures();
/** \brief scans TSDF volume and retrieves occuped voxes
* \param[in] volume TSDF volume
* \param[out] occupied_voxels buffer for occupied voxels; the function fills the first row with voxel id's and second
* row with the no. of vertices
* \return number of voxels in the buffer
*/
int getOccupiedVoxels(const TsdfVolume &volume, DeviceArray2D<int> &occupied_voxels);
/** \brief computes total number of vertices for all voxels and offsets of vertices in final triangle array
* \param[out] occupied_voxels buffer with occupied voxels; the function fills 3rd only with offsets
* \return total number of vertexes
*/
int computeOffsetsAndTotalVertices(DeviceArray2D<int> &occupied_voxels);
/** \brief generates final triangle array
* \param[in] volume TSDF volume
* \param[in] occupied_voxels occupied voxel ids (1st row), number of vertices (2nd row), offsets (3rd row).
* \param[in] volume_size volume size in meters
* \param[out] output triangle array
*/
void generateTriangles(const TsdfVolume &volume, const DeviceArray2D<int> &occupied_voxels, const float3 &volume_size,
DeviceArray<PointType> &output);
// image proc functions
void compute_dists(const Depth &depth, Dists dists, float2 f, float2 c);
void truncateDepth(Depth &depth, float max_dist /*meters*/);
void bilateralFilter(const Depth &src, Depth &dst, int kernel_size, float sigma_spatial, float sigma_depth);
void depthPyr(const Depth &source, Depth &pyramid, float sigma_depth);
void resizeDepthNormals(const Depth &depth, const Normals &normals, Depth &depth_out, Normals &normals_out);
void resizePointsNormals(const Points &points, const Normals &normals, Points &points_out, Normals &normals_out);
void computeNormalsAndMaskDepth(const Reprojector &reproj, Depth &depth, Normals &normals);
void computePointNormals(const Reprojector &reproj, const Depth &depth, Points &points, Normals &normals);
void renderImage(const Depth &depth, const Normals &normals, const Reprojector &reproj, const Vec3f &light_pose,
Image &image);
void renderImage(const Points &points, const Normals &normals, const Reprojector &reproj, const Vec3f &light_pose,
Image &image);
void renderTangentColors(const Normals &normals, Image &image);
// exctraction functionality
size_t extractCloud(const TsdfVolume &volume, const Aff3f &aff, PtrSz<Point> output);
void extractNormals(const TsdfVolume &volume, const PtrSz<Point> &points, const Aff3f &aff, const Mat3f &Rinv,
float gradient_delta_factor, float4 *output);
struct float8 {
float x, y, z, w, c1, c2, c3, c4;
};
struct float12 {
float x, y, z, w, normal_x, normal_y, normal_z, n4, c1, c2, c3, c4;
};
void mergePointNormal(const DeviceArray<Point> &cloud, const DeviceArray<float8> &normals,
const DeviceArray<float12> &output);
} // namespace device
} // namespace kfusion
| 34.957806
| 118
| 0.719493
|
chenguowen
|
9ab078947313d036adb7cb3bc42672e65b870bd0
| 855
|
hxx
|
C++
|
Client/gui/dialogs/AddNewServerConnectionDialog.hxx
|
voldemarz/OppositeRenderer
|
691817c5ea67b0f5b81c1a2680e07e0e8cd05f13
|
[
"MIT"
] | 5
|
2018-05-10T06:16:57.000Z
|
2021-11-19T11:40:43.000Z
|
Client/gui/dialogs/AddNewServerConnectionDialog.hxx
|
voldemarz/OppositeRenderer
|
691817c5ea67b0f5b81c1a2680e07e0e8cd05f13
|
[
"MIT"
] | null | null | null |
Client/gui/dialogs/AddNewServerConnectionDialog.hxx
|
voldemarz/OppositeRenderer
|
691817c5ea67b0f5b81c1a2680e07e0e8cd05f13
|
[
"MIT"
] | 2
|
2018-02-18T12:36:12.000Z
|
2021-11-19T01:52:53.000Z
|
#pragma once
#include <QDialog>
#include <QTcpSocket>
#include <QHostAddress>
#include "client/RenderServerConnection.hxx"
namespace Ui
{
class AddNewServerConnectionDialog;
}
class QTimer;
class AddNewServerConnectionDialog : public QDialog
{
Q_OBJECT
public:
explicit AddNewServerConnectionDialog(QWidget *parent, QThread* tcpSocketThread);
~AddNewServerConnectionDialog();
signals:
void hasNewServerConnectionSocket(QTcpSocket*);
private slots:
void onFormSubmit();
void onHostConnectionError();
void onConnectedToHost();
void onHostDataAvailable();
void onWaitForGreetingError();
private:
void showFormInitialState();
void setError(const QString&);
void socketDisconnectAndWait();
Ui::AddNewServerConnectionDialog *ui;
QTcpSocket* m_socket;
QTimer* m_timerWaitForGreeting;
};
| 21.375
| 85
| 0.753216
|
voldemarz
|
9ab4ae9caac164997c45cbd29e04a9b1ba384e8e
| 16,069
|
cc
|
C++
|
src/ASP.cc
|
alviano/zuccherino
|
d264ef53cca78382dc08dbe3e236a2670658ba0f
|
[
"Apache-2.0"
] | 1
|
2018-01-29T10:27:13.000Z
|
2018-01-29T10:27:13.000Z
|
src/ASP.cc
|
alviano/zuccherino
|
d264ef53cca78382dc08dbe3e236a2670658ba0f
|
[
"Apache-2.0"
] | null | null | null |
src/ASP.cc
|
alviano/zuccherino
|
d264ef53cca78382dc08dbe3e236a2670658ba0f
|
[
"Apache-2.0"
] | 1
|
2017-09-20T09:14:42.000Z
|
2017-09-20T09:14:42.000Z
|
/*
* Copyright (C) 2017 Mario Alviano (mario@alviano.net)
*
* 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 "ASP.h"
#include <core/Dimacs.h>
extern Glucose::IntOption option_n;
extern Glucose::BoolOption option_print_model;
static Glucose::BoolOption option_asp_dlv_output("ASP", "asp-dlv-output", "Set output format in DLV style.", false);
namespace zuccherino {
void ASP::WeakParser::parse() {
Glucose::StreamBuffer& in = this->in();
Lit lit = parseLit(in, solver);
int64_t weight = parseLong(in);
int level = parseInt(in);
if(weight < 0) cerr << "PARSE ERROR! Weights of soft literals must be nonnegative: " << static_cast<char>(*in) << endl, exit(3);
if(level < 0) cerr << "PARSE ERROR! Levels of soft literals must be nonnegative: " << static_cast<char>(*in) << endl, exit(3);
if(lit != lit_Undef && (solver.data.has(lit) || solver.data.has(~lit))) cerr << "PARSE ERROR! Repeated soft literal: " << lit << endl, exit(3);
solver.addWeakLit(lit, weight, level);
}
void ASP::WeightConstraintParser::parse() {
assert(lits.size() == 0);
assert(weights.size() == 0);
Glucose::StreamBuffer& in = this->in();
Glucose::readClause(in, solver, lits);
for(int i = 0; i < lits.size(); i++) weights.push(parseLong(in));
int64_t weight = parseLong(in);
solver.addGreaterEqual(lits, weights, weight);
}
void ASP::WeightConstraintParser::parseDetach() {
Parser::parseDetach();
vec<Lit> tmp;
lits.moveTo(tmp);
vec<int64_t> tmp2;
weights.moveTo(tmp2);
}
void ASP::SPParser::parse() {
assert(lits.size() == 0);
assert(rec.size() == 0);
Glucose::StreamBuffer& in = this->in();
Glucose::readClause(in, solver, lits);
if(lits.size() < 2) cerr << "PARSE ERROR! Expected two or more literals: " << static_cast<char>(*in) << endl, exit(3);
for(int i = 2; i < lits.size(); i++) rec.push(var(lits[i]));
solver.addSP(var(lits[0]), lits[1], rec);
lits.clear();
}
void ASP::SPParser::parseDetach() {
Parser::parseDetach();
vec<Lit> tmp;
lits.moveTo(tmp);
vec<Var> tmp2;
rec.moveTo(tmp2);
}
void ASP::HCCParser::parse() {
assert(lits.size() == 0);
assert(rec.size() == 0);
assert(rec2.size() == 0);
assert(nonRec.size() == 0);
Glucose::StreamBuffer& in = this->in();
int id = parseInt(in);
if(id < 0) cerr << "PARSE ERROR! Id of HCC must be nonnegative: " << static_cast<char>(*in) << endl, exit(3);
Glucose::readClause(in, solver, lits);
if(lits.size() == 0) cerr << "PARSE ERROR! Expected one or more head atoms: " << static_cast<char>(*in) << endl, exit(3);
for(int i = 0; i < lits.size(); i++) rec.push(var(lits[i]));
Glucose::readClause(in, solver, nonRec);
Glucose::readClause(in, solver, lits);
for(int i = 0; i < lits.size(); i++) rec2.push(var(lits[i]));
lits.clear();
solver.addHCC(id, rec, nonRec, rec2);
}
void ASP::HCCParser::parseDetach() {
Parser::parseDetach();
vec<Lit> tmp;
lits.moveTo(tmp);
vec<Var> tmp2;
rec.moveTo(tmp2);
vec<Var> tmp3;
rec2.moveTo(tmp3);
vec<Lit> tmp4;
nonRec.moveTo(tmp4);
}
ASP::ASP() : weakParser(*this), weightConstraintParser(*this), spParser(*this), hccParser(*this), endParser(*this), ccPropagator(*this), wcPropagator(*this, &ccPropagator), spPropagator(NULL), optimization(false) {
setProlog("asp");
setParser('w', &weakParser);
setParser('a', &weightConstraintParser);
setParser('s', &spParser);
setParser('h', &hccParser);
setParser('n', &endParser);
setNoIds(true);
setModelsUnknown("UNKNOWN\n");
if(option_asp_dlv_output) {
setModelsNone("\n");
setModelsStart("");
setModelsEnd("\n");
setModelStart("{");
setModelSep("");
setModelEnd("}\n");
setLitStart("");
setLitSep(", ");
setLitEnd("");
}
else {
setModelsNone("INCONSISTENT\n");
setModelsStart("");
setModelsEnd("");
setModelStart("ANSWER\n");
setModelSep("");
setModelEnd("\n");
setLitStart("");
setLitSep(" ");
setLitEnd(".");
}
}
ASP::~ASP() {
if(spPropagator != NULL) delete spPropagator;
for(int i = 0; i < hccs.size(); i++) delete hccs[i];
}
bool ASP::interrupt() {
GlucoseWrapper::interrupt();
if(model.size() > 0) printModel();
onDoneIteration();
onDone();
return model.size() > 0;
}
void ASP::addWeakLit(Lit lit, int64_t weight, int level) {
assert(weight >= 0);
assert(level >= 0);
if(lit != lit_Undef) {
assert(!data.has(lit) && !data.has(~lit));
data.push(*this, lit);
this->weight(lit) = weight;
this->level(lit) = level;
softLits.push(lit);
}
Level l;
l.level = level;
l.lowerBound = lit != lit_Undef ? 0 : weight;
l.upperBound = INT64_MAX;
int i = 0;
for(; i < levels.size(); i++) {
if(levels[i].level == l.level) { levels[i].lowerBound += l.lowerBound; break; }
if(levels[i].level > l.level) {
Level tmp = levels[i];
levels[i] = l;
l = tmp;
}
}
if(i == levels.size()) levels.push(l);
optimization = true;
}
void ASP::addSP(Var atom, Lit body, vec<Var>& rec) {
if(spPropagator == NULL) spPropagator = new SourcePointers(*this);
spPropagator->add(atom, body, rec);
}
void ASP::addHCC(int hccId, vec<Var>& recHead, vec<Lit>& nonRecLits, vec<Var>& recBody) {
while(hccId >= hccs.size()) hccs.push(new HCC(*this, hccs.size()));
assert(hccId < hccs.size());
assert(hccs[hccId] != NULL);
hccs[hccId]->add(recHead, nonRecLits, recBody);
}
void ASP::endProgram(int numberOfVariables) {
while(nVars() < numberOfVariables) { newVar(); }
if(levels.size() == 0) {
levels.push();
levels.last().level = 0;
levels.last().lowerBound = 0;
levels.last().upperBound = INT64_MAX;
}
for(int i = 0; i < softLits.size(); i++) setFrozen(var(softLits[i]), true);
if(!activatePropagators()) return;
if(!simplify()) return;
}
void ASP::printModel() {
if(!option_print_model) return;
onModel();
if(isOptimizationProblem()) {
cout << "COST";
for(int i = 0; i < solved.size(); i++) cout << " " << solved[i].lowerBound << "@" << solved[i].level;
for(int i = levels.size()-1; i >= 0; i--) cout << " " << levels[i].upperBound << "@" << levels[i].level;
cout << endl;
if(levels.size() == 0) cout << "OPTIMUM" << endl;
}
}
lbool ASP::solveInternal() {
if(!ok) return l_False;
if(isOptimizationProblem()) {
lbool status = solveWithBudget();
if(status == l_True) updateUpperBound();
cancelUntil(0);
softLits.copyTo(assumptions);
status = solveWithBudget();
if(status == l_True) updateUpperBound();
cancelUntil(0);
}
do{
assert(levels.size() > 0);
lbool status;
int64_t limit = computeNextLimit(INT64_MAX);
for(;;) {
hardening();
setAssumptions(limit);
if(levels.last().lowerBound == levels.last().upperBound) break;
status = solveWithBudget();
if(status == l_Undef) return l_Undef;
if(status == l_True) {
updateUpperBound();
limit = computeNextLimit(limit);
}
else {
assert(status == l_False);
trace(asp, 2, "UNSAT! Conflict of size " << conflict.size());
trace(asp, 100, "Conflict: " << conflict);
if(conflict.size() == 0) { ok = false; levels.last().lowerBound = levels.last().upperBound; limit = 1; continue; }
assert_msg(computeConflictWeight() == limit, "computeConflictWeight()=" << computeConflictWeight() << "; limit=" << limit << "; conflict=" << conflict);
shrinkConflict(limit);
trimConflict(); // last trim, just in case some new learned clause may help to further reduce the core
int64_t w = computeConflictWeight();
assert(w == limit);
addToLowerBound(w);
assert(conflict.size() > 0);
trace(asp, 4, "Analyze conflict of size " << conflict.size() << " and weight " << w);
processConflict(w);
}
}
assert(assumptions.size() == 0);
assert(levels.size() > 0);
assert(levels.last().lowerBound == levels.last().upperBound);
if(levels.last().upperBound == INT64_MAX) return l_False;
solved.push(levels.last());
levels.pop();
}while(levels.size() > 0);
assert(softLits.size() == 0);
if(option_n == 1) printModel();
else enumerateModels();
return l_True;
}
lbool ASP::solve() {
assert(decisionLevel() == 0);
assert(assumptions.size() == 0);
onStartIteration();
lbool status = solveInternal();
onDoneIteration();
return status;
}
void ASP::hardening() {
cancelUntil(0);
int j = 0;
for(int i = 0; i < softLits.size(); i++) {
if(level(softLits[i]) == levels.last().level) {
int64_t diff = weight(softLits[i]) + levels.last().lowerBound - levels.last().upperBound;
if(option_n == 1 && levels.size() == 1 ? diff >= 0 : diff > 0) {
addClause(softLits[i]);
trace(asp, 30, "Hardening of " << softLits[i] << " of weight " << weight(softLits[i]));
weight(softLits[i]) = 0;
continue;
}
}
softLits[j++] = softLits[i];
}
softLits.shrink_(softLits.size()-j);
}
int64_t ASP::computeNextLimit(int64_t limit) const {
int64_t next = limit;
for(int i = 0; i < softLits.size(); i++) {
if(level(softLits[i]) != levels.last().level) continue;
int64_t w = weight(softLits[i]);
if(w == 0) continue;
if(w >= limit) continue;
if(next == limit || w > next) next = w;
}
return next;
}
void ASP::setAssumptions(int64_t limit) {
cancelUntil(0);
assumptions.clear();
int j = 0;
for(int i = 0; i < softLits.size(); i++) {
int64_t w = weight(softLits[i]);
if(w == 0) continue;
softLits[j++] = softLits[i];
if(level(softLits[i]) != levels.last().level) continue;
if(w >= limit) assumptions.push(softLits[i]);
}
softLits.shrink_(softLits.size()-j);
}
void ASP::addToLowerBound(int64_t value) {
assert(value > 0);
levels.last().lowerBound += value;
cout << "% lb " << levels.last().lowerBound << "@" << levels.last().level << endl;
}
void ASP::updateUpperBound() {
bool better = false;
for(int l = levels.size()-1; l >= 0; l--) {
int64_t sum = levels[l].lowerBound;
for(int i = 0; i < softLits.size(); i++) if(level(softLits[i]) == levels[l].level && value(softLits[i]) == l_False) sum += weight(softLits[i]);
if(sum > levels[l].upperBound) return;
if(sum < levels[l].upperBound) better = true;
if(better) {
if(isOptimizationProblem()) cout << "% ub " << sum << "@" << levels[l].level << endl;
levels[l].upperBound = sum;
}
}
if(better) { copyModel(); }
}
int64_t ASP::computeConflictWeight() const {
int64_t min = INT64_MAX;
for(int i = 0; i < conflict.size(); i++) if(weight(~conflict[i]) < min) min = weight(~conflict[i]);
return min;
}
void ASP::processConflict(int64_t weight) {
assert(decisionLevel() == 0);
assert(conflict.size() > 0);
trace(asp, 10, "Use algorithm one");
vec<Lit> lits;
int bound = conflict.size() - 1;
while(conflict.size() > 0) {
this->weight(~conflict.last()) -= weight;
lits.push(~conflict.last());
conflict.pop();
}
assert(conflict.size() == 0);
for(int i = 0; i < bound; i++) {
newVar();
if(i != 0) addClause(~softLits.last(), mkLit(nVars()-1));
softLits.push(mkLit(nVars()-1));
data.push(*this, softLits.last());
this->weight(softLits.last()) = weight;
this->level(softLits.last()) = levels.last().level;
lits.push(~softLits.last());
}
ccPropagator.addGreaterEqual(lits, bound);
}
void ASP::trimConflict() {
cancelUntil(0);
if(conflict.size() <= 1) return;
int counter = 0;
do{
counter++;
assumptions.clear();
for(int i = 0; i < conflict.size(); i++) assumptions.push(~conflict[i]);
solveWithBudget();
trace(asp, 15, "Trim " << assumptions.size() - conflict.size() << " literals from conflict");
trace(asp, 100, "Conflict: " << conflict);
cancelUntil(0);
if(conflict.size() <= 1) return;
}while(assumptions.size() > conflict.size());
if(counter % 2 == 1) for(int i = 0; i < assumptions.size(); i++) conflict[i] = ~assumptions[i];
assert(conflict.size() > 1);
}
void ASP::shrinkConflict(int64_t limit) {
cancelUntil(0);
if(conflict.size() <= 1) return;
trimConflict();
vec<Lit> core;
conflict.moveTo(core);
vec<Lit> allAssumptions;
for(int i = 0; i < core.size(); i++) allAssumptions.push(~core[i]);
assumptions.clear();
const int progressionFrom = 1;
int progression = progressionFrom;
int fixed = 0;
while(levels.last().lowerBound + limit < levels.last().upperBound) {
if(fixed + progression >= allAssumptions.size()) {
if(progression == progressionFrom) break;
progression = progressionFrom;
fixed = assumptions.size();
continue;
}
trace(asp, 15, "Shrink: progress to " << progression << "; fixed = " << fixed);
int prec = assumptions.size();
for(int i = assumptions.size(); i < fixed + progression; i++) {
assert(i < allAssumptions.size());
assumptions.push(allAssumptions[i]);
}
if(solveWithBudget() == l_False) {
trace(asp, 10, "Shrink: reduce to size " << conflict.size());
progression = progressionFrom;
assumptions.moveTo(core);
cancelUntil(0);
trimConflict();
core.moveTo(assumptions);
conflict.moveTo(core);
int j = 0;
for(int i = 0, k = core.size() - 1; i < prec; i++) {
if(k < 0) break;
if(assumptions[i] != ~core[k]) continue;
assumptions[j++] = assumptions[i];
k--;
}
assumptions.shrink_(assumptions.size() - j);
fixed = assumptions.size();
j = 0;
for(int i = 0, k = core.size() - 1; i < allAssumptions.size(); i++) {
if(k < 0) break;
if(allAssumptions[i] != ~core[k]) continue;
allAssumptions[j++] = allAssumptions[i];
k--;
}
allAssumptions.shrink_(allAssumptions.size() - j);
}
else {
// trace(asp, 20, (status == l_True ? "SAT!" : "UNDEF"));
progression *= 2;
}
cancelUntil(0);
}
core.moveTo(conflict);
}
void ASP::enumerateModels() {
assert(decisionLevel() == 0);
assert(assumptions.size() == 0);
int count = 0;
while(solveWithBudget() == l_True) {
count++;
copyModel();
printModel();
if(count == option_n) break;
if(decisionLevel() == 0) break;
learnClauseFromModel();
}
}
}
| 31.384766
| 214
| 0.564752
|
alviano
|
9abfbe0cea25e84e352703c27167b2db2ced38eb
| 1,724
|
cpp
|
C++
|
main.cpp
|
aprithul/SDL-Software-Renderer
|
3eea2b6e363d691ec1c206b35b24321f9882203f
|
[
"MIT"
] | null | null | null |
main.cpp
|
aprithul/SDL-Software-Renderer
|
3eea2b6e363d691ec1c206b35b24321f9882203f
|
[
"MIT"
] | null | null | null |
main.cpp
|
aprithul/SDL-Software-Renderer
|
3eea2b6e363d691ec1c206b35b24321f9882203f
|
[
"MIT"
] | null | null | null |
#include <iostream>
#include <SDL2/SDL.h>
#include "Display.h"
#include "Event_Handler.h"
bool is_running = true; // to determine when to quit game
SDL_Event sdl_event; //event handler
Event_Handler event_handler;
int main( int argc, char* args[] )
{
// initial setups-------------------------------------------------
Display display(800,600,"hello"); // reference to a display oboject, cotains all rendering stuff
// set all required commands here
event_handler.set_exit_command(&is_running);
// end setup--------------------------------------------------------
unsigned int last_time = SDL_GetTicks() ,current_time = 0;
unsigned int total_time = 0;
unsigned int fps = 0;
// main loop
while(is_running == true)
{
// execute any event that occured
Command* command = event_handler.handle_event();
if(command != NULL)
command->execute();
// render
display.clear_screen(0,0,0,255);
//display.draw_point(glm::vec2(display.SCREEN_WIDTH/2,display.SCREEN_HEIGHT/2),255,0,0,255);
//display.draw_line(glm::vec2(display.SCREEN_WIDTH/2, display.SCREEN_HEIGHT/2),glm::vec2(display.SCREEN_WIDTH/2 - 100, display.SCREEN_HEIGHT/2 + 100),255,0,0,255);
display.draw_triangle_filled( Vector(100,100,0), Vector(150,200,0), Vector(200,30,0),255,0,255,255);
display.swap_buffers();
current_time = SDL_GetTicks();
//std::cout<< ((current_time - last_time))/(float)1000 <<std::endl;
total_time += (current_time - last_time);
if(total_time>=1000)
{
total_time -=1000;
std::cout<<fps<<std::endl;
fps = 0;
}
else
fps++;
last_time = current_time;
}
// ran successfully
return 0;
}
| 22.986667
| 166
| 0.62239
|
aprithul
|
9ac6b20d2c5e201bca0e7dd44e94aea53acb0aaa
| 368
|
hpp
|
C++
|
library/ATF/_NLA_CONNECTIVITY_TYPE.hpp
|
lemkova/Yorozuya
|
f445d800078d9aba5de28f122cedfa03f26a38e4
|
[
"MIT"
] | 29
|
2017-07-01T23:08:31.000Z
|
2022-02-19T10:22:45.000Z
|
library/ATF/_NLA_CONNECTIVITY_TYPE.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 90
|
2017-10-18T21:24:51.000Z
|
2019-06-06T02:30:33.000Z
|
library/ATF/_NLA_CONNECTIVITY_TYPE.hpp
|
kotopes/Yorozuya
|
605c97d3a627a8f6545cc09f2a1b0a8afdedd33a
|
[
"MIT"
] | 44
|
2017-12-19T08:02:59.000Z
|
2022-02-24T23:15:01.000Z
|
// This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
START_ATF_NAMESPACE
enum _NLA_CONNECTIVITY_TYPE
{
NLA_NETWORK_AD_HOC = 0x0,
NLA_NETWORK_MANAGED = 0x1,
NLA_NETWORK_UNMANAGED = 0x2,
NLA_NETWORK_UNKNOWN = 0x3,
};
END_ATF_NAMESPACE
| 23
| 108
| 0.722826
|
lemkova
|
9ac6c996a6f005b38a54b38d6fe8b2975aae4277
| 1,393
|
cpp
|
C++
|
ch16/ex16.4/main.cpp
|
regconfi/Cpp-Primer
|
6e59f24f4c7f3be4f679b7d29084d9d859a463d9
|
[
"CC0-1.0"
] | 46
|
2015-07-07T11:13:12.000Z
|
2022-03-27T10:20:54.000Z
|
ch16/ex16.4/main.cpp
|
lafener/Cpp-Primer
|
8cf1568f2d27622bce2d41493158f58527e5072f
|
[
"CC0-1.0"
] | 11
|
2015-03-10T12:52:06.000Z
|
2015-04-20T12:24:00.000Z
|
ch16/ex16.4/main.cpp
|
lafener/Cpp-Primer
|
8cf1568f2d27622bce2d41493158f58527e5072f
|
[
"CC0-1.0"
] | 65
|
2015-07-01T14:15:48.000Z
|
2021-04-10T08:44:19.000Z
|
/***************************************************************************
* @file main.cpp
* @author Alan.W
* @date 02 Feb 2014
* @remark This code is for the exercises from C++ Primer 5th Edition
* @note
***************************************************************************/
//!
//! Exercise 16.4:
//! Write a template that acts like the library find algorithm. The function
//! will need two template type parameters, one to represent the function’s
//! iterator parameters and the other for the type of the value. Use your
//! function to find a given value in a vector<int> and in a list<string>.
//!
#include <iostream>
#include <vector>
#include <list>
#include <string>
template<typename iteratorT, typename valueT>
iteratorT find(const iteratorT& first, const iteratorT& last,const valueT& value )
{
auto iter = first;
while(iter != last && *iter != value) ++iter;
return iter;
}
int main()
{
/** @brief test using vector<int>
*/
std::vector<int> vi = {1,2,3,4,5,6,7,8,9};
auto it = find(vi.cbegin(), vi.cend(), 5);
std::cout << *it << std::endl;
/** @brief test using list<int>
*/
std::list<std::string> l = {"aa","bb","cc","dd","ee","ff","gg"};
std::list<std::string>::const_iterator itL = find(l.cbegin(), l.cend(), "ee");
std::cout << *itL << std::endl;
return 0;
}
| 26.788462
| 82
| 0.543431
|
regconfi
|
9ac7d5bcd8db249fac32b0191f994723434910d3
| 3,666
|
hpp
|
C++
|
src/referenced/libsysinfo/lib/linux_memoryload.hpp
|
SoaringLoong/sloongnet
|
1a4ef3068ede28363dcd8ac27a6bac11ea9a1077
|
[
"MIT"
] | 2
|
2019-06-28T05:47:44.000Z
|
2020-12-29T11:32:53.000Z
|
src/referenced/libsysinfo/lib/linux_memoryload.hpp
|
SoaringLoong/sloongnet
|
1a4ef3068ede28363dcd8ac27a6bac11ea9a1077
|
[
"MIT"
] | null | null | null |
src/referenced/libsysinfo/lib/linux_memoryload.hpp
|
SoaringLoong/sloongnet
|
1a4ef3068ede28363dcd8ac27a6bac11ea9a1077
|
[
"MIT"
] | 1
|
2021-01-13T03:05:22.000Z
|
2021-01-13T03:05:22.000Z
|
/***
* @Author: Chuanbin Wang - wcb@sloong.com
* @Date: 2021-09-23 17:27:14
* @LastEditTime: 2021-09-24 11:24:01
* @LastEditors: Chuanbin Wang
* @FilePath: /engine/src/referenced/libsysinfo/lib/linux_memoryload.hpp
* @Copyright 2015-2020 Sloong.com. All Rights Reserved
* @Description:
*/
/**
* @author: Daniel Fuchs
* @contact: fuxeysolutions@gmail.com
*
* distributed under the MIT License (MIT).
* Copyright (c) Daniel Fuchs
*
*/
#pragma once
#include <chrono>
#include <cinttypes>
#include <cmath>
#include <fstream>
#include <iostream>
#include <string>
class memoryLoad
{
public:
explicit memoryLoad(std::string memInfo = "/proc/meminfo", std::string memInfoOfProcess = "/proc/self/status",
std::string memInfoOfProcessPrefix = "/proc/self/")
: totalMemoryInKB(0), currentMemoryUsageInKB(0), memInfoFile(memInfo), memInfoOfProcessFile(memInfoOfProcess),
memInfoOfProcessPrefixFile(memInfoOfProcessPrefix){};
/**
* @brief get total memory of the system in KB
* @return total memory in KB
*/
uint64_t getTotalMemoryInKB()
{
this->parseMemoryFile();
return this->totalMemoryInKB;
}
/**
* @brief get current Memory Usage of the system in KB
* @return used memory in KB
*/
uint64_t getCurrentMemUsageInKB()
{
this->parseMemoryFile();
return this->getTotalMemoryInKB() - this->currentMemoryUsageInKB;
}
/**
* @brief get current memory usage of the system in percent 0-100%
* @return 0-100%
*/
float getCurrentMemUsageInPercent()
{
this->parseMemoryFile();
uint64_t memavail = this->getCurrentMemUsageInKB();
return round((((memavail * 100.0 / this->getTotalMemoryInKB()))) * 100.0) / 100.0;
}
/**
* @brief get the current memory usage of a process
* @param pid - process id
* @return memory usage in KB
*/
static uint64_t getMemoryUsedByProcess(int pid)
{
return memoryLoad::parseProcessMemoryFile("/proc/" + std::to_string(pid) + "/status");
}
/**
* @brief get memory usage of this process (self)
* @return memory usage in KB
*/
uint64_t getMemoryUsageByThisProcess()
{
return this->parseProcessMemoryFile(this->memInfoOfProcessFile);
}
private:
bool parseMemoryFile()
{
if (timeStamp + std::chrono::milliseconds(100) > std::chrono::steady_clock::now())
{
return true;
}
std::ifstream memoryFile;
memoryFile.open(this->memInfoFile);
this->timeStamp = std::chrono::steady_clock::now();
if (!memoryFile.is_open())
{
return false;
}
std::string line;
while (std::getline(memoryFile, line))
{
sscanf(line.c_str(), "MemTotal: %" PRIu64, &this->totalMemoryInKB);
sscanf(line.c_str(), "MemAvailable: %" PRIu64, &this->currentMemoryUsageInKB);
}
memoryFile.close();
return true;
}
static uint64_t parseProcessMemoryFile(std::string fileToParse)
{
uint64_t MemFree = 0;
std::ifstream memoryFile;
memoryFile.open(fileToParse);
std::string line;
while (std::getline(memoryFile, line))
{
sscanf(line.c_str(), "VmSize: %" PRIu64, &MemFree);
}
return MemFree;
}
uint64_t totalMemoryInKB;
uint64_t currentMemoryUsageInKB;
std::string memInfoFile;
std::string memInfoOfProcessFile;
std::string memInfoOfProcessPrefixFile;
std::chrono::time_point<std::chrono::steady_clock> timeStamp;
};
| 29.804878
| 118
| 0.624932
|
SoaringLoong
|
9acc3e30d824bd999f1bced4670ff9c426bcbf68
| 21,957
|
cpp
|
C++
|
src/Engine/ChuShogi.cpp
|
jweathers777/mShogi
|
941cd4dc37e6e6210d4f993c96a553753e228b19
|
[
"BSD-3-Clause"
] | 4
|
2015-12-24T04:52:48.000Z
|
2021-11-09T11:31:36.000Z
|
src/Engine/ChuShogi.cpp
|
jweathers777/mShogi
|
941cd4dc37e6e6210d4f993c96a553753e228b19
|
[
"BSD-3-Clause"
] | null | null | null |
src/Engine/ChuShogi.cpp
|
jweathers777/mShogi
|
941cd4dc37e6e6210d4f993c96a553753e228b19
|
[
"BSD-3-Clause"
] | null | null | null |
////////////////////////////////////////////////////////////////////////////
// Name: ChuShogi.cpp
// Description: Interface for a class that represents the
// game of Chu Shogi
// Created: 02/04/2005 11:10:32 Eastern Standard Time
// Last Updated: $Date$
// Revision: $Revision$
// Author: John Weathers
// Email: hotanguish@hotmail.com
// Copyright: (c) 2005 John Weathers
////////////////////////////////////////////////////////////////////////////
// STL declaration
#include <vector>
// mShogi header files
#include "common.hpp"
#include "ChuShogi.hpp"
#include "Board.hpp"
#include "MoveRec.hpp"
#include "MoveGenerator.hpp"
#include "Evaluator.hpp"
#include "Notator.hpp"
// Chu Shogi Pieces header files
#include "Pawn.hpp"
#include "GoBetween.hpp"
#include "CopperGeneral.hpp"
#include "SilverGeneral.hpp"
#include "FerociousLeopard.hpp"
#include "BlindTiger.hpp"
#include "DrunkElephant.hpp"
#include "GoldGeneral.hpp"
#include "Lance.hpp"
#include "ReverseChariot.hpp"
#include "Kylin.hpp"
#include "Phoenix.hpp"
#include "SideMover.hpp"
#include "VerticalMover.hpp"
#include "Bishop.hpp"
#include "Rook.hpp"
#include "DragonHorse.hpp"
#include "DragonKing.hpp"
#include "FreeKing.hpp"
#include "Lion.hpp"
#include "King.hpp"
#include "Jewel.hpp"
#include "Tokin.hpp"
#include "FlyingStag.hpp"
#include "CrownPrince.hpp"
#include "Whale.hpp"
#include "WhiteHorse.hpp"
#include "FreeBoar.hpp"
#include "FlyingOx.hpp"
#include "HornedFalcon.hpp"
#include "SoaringEagle.hpp"
// Define useful shorthand for describing initial board lay out
#define bK ChuShogi::JEWEL + 1
#define bLn ChuShogi::LION + 1
#define bFK ChuShogi::FREE_KING + 1
#define bDK ChuShogi::DRAGON_KING + 1
#define bDH ChuShogi::DRAGON_HORSE + 1
#define bR ChuShogi::ROOK + 1
#define bB ChuShogi::BISHOP + 1
#define bVM ChuShogi::VERTICAL_MOVER + 1
#define bSM ChuShogi::SIDE_MOVER + 1
#define bPh ChuShogi::PHOENIX + 1
#define bKy ChuShogi::KYLIN + 1
#define bRC ChuShogi::REVERSE_CHARIOT + 1
#define bL ChuShogi::LANCE + 1
#define bG ChuShogi::GOLD_GENERAL + 1
#define bDE ChuShogi::DRUNK_ELEPHANT + 1
#define bBT ChuShogi::BLIND_TIGER + 1
#define bFL ChuShogi::FEROCIOUS_LEOPARD + 1
#define bS ChuShogi::SILVER_GENERAL + 1
#define bC ChuShogi::COPPER_GENERAL + 1
#define bGB ChuShogi::GO_BETWEEN + 1
#define bP ChuShogi::PAWN + 1
#define wK ChuShogi::KING + 23
#define wLn ChuShogi::LION + 23
#define wFK ChuShogi::FREE_KING + 23
#define wDK ChuShogi::DRAGON_KING + 23
#define wDH ChuShogi::DRAGON_HORSE + 23
#define wR ChuShogi::ROOK + 23
#define wB ChuShogi::BISHOP + 23
#define wVM ChuShogi::VERTICAL_MOVER + 23
#define wSM ChuShogi::SIDE_MOVER + 23
#define wPh ChuShogi::PHOENIX + 23
#define wKy ChuShogi::KYLIN + 23
#define wRC ChuShogi::REVERSE_CHARIOT + 23
#define wL ChuShogi::LANCE + 23
#define wG ChuShogi::GOLD_GENERAL + 23
#define wDE ChuShogi::DRUNK_ELEPHANT + 23
#define wBT ChuShogi::BLIND_TIGER + 23
#define wFL ChuShogi::FEROCIOUS_LEOPARD + 23
#define wS ChuShogi::SILVER_GENERAL + 23
#define wC ChuShogi::COPPER_GENERAL + 23
#define wGB ChuShogi::GO_BETWEEN + 23
#define wP ChuShogi::PAWN + 23
using std::vector;
// Constants
const int ChuShogi::WIDTH;
const int ChuShogi::HEIGHT;
const int ChuShogi::SIZE;
const int ChuShogi::PIECE_COUNT;
const int ChuShogi::PIECE_TYPES;
// Array that defines the inital board lay out
const int ChuShogi::mStartingPattern[] = {
wL, wFL, wC, wS, wG, wK, wDE, wG, wS, wC, wFL, wL,
wRC, 0, wB, 0, wBT, wKy, wPh, wBT, 0, wB, 0, wRC,
wSM, wVM, wR, wDH, wDK, wLn, wFK, wDK, wDH, wR, wVM, wSM,
wP, wP, wP, wP, wP, wP, wP, wP, wP, wP, wP, wP,
0, 0, 0, wGB, 0, 0, 0, 0, wGB, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, bGB, 0, 0, 0, 0, bGB, 0, 0, 0,
bP, bP, bP, bP, bP, bP, bP, bP, bP, bP, bP, bP,
bSM, bVM, bR, bDH, bDK, bFK, bLn, bDK, bDH, bR, bVM, bSM,
bRC, 0, bB, 0, bBT, bPh, bKy, bBT, 0, bB, 0, bRC,
bL, bFL, bC, bS, bG, bDE, bK, bG, bS, bC, bFL, bL
};
// Array that defines promotions
const int ChuShogi::mPromotionMap[] = {
// PAWN, GO_BETWEEN,
TOKIN, DRUNK_ELEPHANT,
// COPPER_GENERAL, SILVER_GENERAL, FEROCIOUS_LEOPARD, BLIND_TIGER,
SIDE_MOVER, VERTICAL_MOVER, BISHOP, FLYING_STAG,
// DRUNK_ELEPHANT, GOLD_GENERAL, LANCE, REVERSE_CHARIOT,
CROWN_PRINCE, ROOK, WHITE_HORSE, WHALE,
// KYLIN, PHOENIX, SIDE_MOVER, VERTICAL_MOVER,
LION, FREE_KING, FREE_BOAR, FLYING_OX,
// BISHOP, ROOK, DRAGON_HORSE, DRAGON_KING,
DRAGON_HORSE, DRAGON_KING, HORNED_FALCON, SOARING_EAGLE,
// FREE_KING, LION,
NO_PROMOTION, NO_PROMOTION,
// KING, JEWEL
NO_PROMOTION, NO_PROMOTION
};
//--------------------------------------------------------------------------
// Class: ChuShogi
// Method: ChuShogi
// Description: Create an instance of a chu shogi game
//--------------------------------------------------------------------------
ChuShogi::ChuShogi()
{
// Create a 12x12 board
mpBoard = new Board(WIDTH, HEIGHT, 4, PIECE_TYPES);
// Create the piece types that we need
mPieceTypes.push_back( new Pawn(mpBoard, 1000, PAWN) );
mPieceTypes.push_back( new GoBetween(mpBoard, 1200, GO_BETWEEN) );
mPieceTypes.push_back( new CopperGeneral(mpBoard, 2534, COPPER_GENERAL) );
mPieceTypes.push_back( new SilverGeneral(mpBoard, 3310, SILVER_GENERAL) );
mPieceTypes.push_back( new FerociousLeopard(mpBoard, 3425, FEROCIOUS_LEOPARD) );
mPieceTypes.push_back( new BlindTiger(mpBoard, 3580, BLIND_TIGER) );
mPieceTypes.push_back( new DrunkElephant(mpBoard, 4230, DRUNK_ELEPHANT) );
mPieceTypes.push_back( new GoldGeneral(mpBoard, 4355, GOLD_GENERAL) );
mPieceTypes.push_back( new Lance(mpBoard, 4563, LANCE) );
mPieceTypes.push_back( new ReverseChariot(mpBoard, 4721, REVERSE_CHARIOT) );
mPieceTypes.push_back( new Kylin(mpBoard, 5211, KYLIN) );
mPieceTypes.push_back( new Phoenix(mpBoard, 5291, PHOENIX) );
mPieceTypes.push_back( new SideMover(mpBoard, 5371, SIDE_MOVER) );
mPieceTypes.push_back( new VerticalMover(mpBoard, 5620, VERTICAL_MOVER) );
mPieceTypes.push_back( new Bishop(mpBoard, 8644, BISHOP) );
mPieceTypes.push_back( new Rook(mpBoard, 8776, ROOK) );
mPieceTypes.push_back( new DragonHorse(mpBoard, 11456, DRAGON_HORSE) );
mPieceTypes.push_back( new DragonKing(mpBoard, 11631, DRAGON_KING) );
mPieceTypes.push_back( new FreeKing(mpBoard, 13800, FREE_KING) );
mPieceTypes.push_back( new Lion(mpBoard, 14578, LION) );
mPieceTypes.push_back( new King(mpBoard, 650000, KING) );
mPieceTypes.push_back( new Jewel(mpBoard, 650000, JEWEL) );
mPieceTypes.push_back( new Tokin(mpBoard, 1501, TOKIN) );
mPieceTypes.push_back( new FlyingStag(mpBoard, 4810, FLYING_STAG) );
mPieceTypes.push_back( new CrownPrince(mpBoard, 5135, CROWN_PRINCE) );
mPieceTypes.push_back( new Whale(mpBoard, 5240, WHALE) );
mPieceTypes.push_back( new WhiteHorse(mpBoard, 5276, WHITE_HORSE) );
mPieceTypes.push_back( new FreeBoar(mpBoard, 9234, FREE_BOAR) );
mPieceTypes.push_back( new FlyingOx(mpBoard, 9375, FLYING_OX) );
mPieceTypes.push_back( new HornedFalcon(mpBoard, 12451, HORNED_FALCON) );
mPieceTypes.push_back( new SoaringEagle(mpBoard, 12672, SOARING_EAGLE) );
// Assign positional weights to the piece types
SetWeights();
// Create pieces and place them on the board
Reset();
// Create a new move generator
mpMoveGenerator = new MoveGenerator(this, PIECE_COUNT);
// Create a new evaluator
mpEvaluator = new Evaluator(mPieces);
// Create a new Notator
mpNotator = new Notator(mpBoard);
// Turn on the special lion capture rules for Chu Shogi
Lion::sLionCaptureRules = true;
}
//--------------------------------------------------------------------------
// Class: ChuShogi
// Method: ~ChuShogi
// Description: Destroy this instance of a mini shogi game
//--------------------------------------------------------------------------
ChuShogi::~ChuShogi()
{
for (unsigned int i = 0; i < mPieceTypes.size(); i++) {
if (mPieceTypes[i]) {
delete mPieceTypes[i];
}
}
}
//--------------------------------------------------------------------------
// Class: ChuShogi
// Method: IsLegal
// Description: Returns true if the given move for the given side is legal
//--------------------------------------------------------------------------
bool ChuShogi::IsLegal(Move* move, int side)
{
unsigned int i;
Piece* mover = move->mpMover;
// Is the right side that is moving?
if (mover->mColor != side) {
return false;
}
// Validate the captures
for (i=0; i < move->mCaptures.size(); i++) {
if (move->mCaptures[i]->mColor == side) {
return false; // Cannot capture own piece
}
}
// Is this a forced promotion?
if (ForcePromotion(*move)) {
move->mPromote = true;
}
// Can this piece actually make this move?
vector<Move> movelist;
mover->mpType->GenerateCaptures(movelist, mover);
mover->mpType->GenerateNonCaptures(movelist, mover);
mpMoveGenerator->CheckForPromotions(movelist, side);
PostProcess(movelist, side);
for (i=0; i < movelist.size(); i++) {
if (movelist[i] == *move) {
return true;
}
}
// No matching legal move was found
return false;
}
//--------------------------------------------------------------------------
// Class: ChuShogi
// Method: IsValid
// Description: Returns true if the given pseudo-legal move for the
// given side is truly legal
//--------------------------------------------------------------------------
bool ChuShogi::IsValid(Move* move, int side)
{
int value;
// Is this a double capture move?
if (move->mCaptures.size() == 2) {
// Is the first capture neither a pawn nor a go-between?
value = move->mCaptures[0]->mTypeValue;
if ((value != GO_BETWEEN) && (value != PAWN)) {
return true;
}
}
// Temporarily remove your attacking lion from the board
int square = move->mSource;
Piece* attackerLion = mpBoard->mSquares[square];
mpBoard->mSquares[square] = 0;
mpBoard->mColoredPieces[side].set(square, false);
mpBoard->mAllPieces.set(square, false);
mpBoard->mNoPieces.set(square, true);
// Is the enemy lion that is being captured protected when you remove
// your attacking lion from the board?
bool result = true;
int color = 1-side;
Piece* piecePtr;
square = move->mDestination;
for (int i = 0; i < PIECE_COUNT; i++) {
piecePtr = &(mPieces[color][i]);
if (piecePtr->mpType->ThreatensSquare(piecePtr, square)) {
result = false;
break;
}
}
// Restore your attacking lion to the board
square = move->mSource;
mpBoard->mSquares[square] = attackerLion;
mpBoard->mColoredPieces[side].set(square, true);
mpBoard->mAllPieces.set(square, true);
mpBoard->mNoPieces.set(square, false);
return result;
}
//--------------------------------------------------------------------------
// Class: ChuShogi
// Method: CanPromote
// Description: Returns true if the given move offers the
// opportunity for promotion
//--------------------------------------------------------------------------
bool ChuShogi::CanPromote(Move* move)
{
vector<Move> movelist;
int side = move->mpMover->mColor;
movelist.push_back(*move);
mpMoveGenerator->CheckForPromotions(movelist, side);
return (movelist.size() > 1);
}
//------------------------------------------------------------------------
// Class: ChuShogi
// Method: CanMoveTwice
// Description: Returns true if this move offers the opportunity to move
// twice in one move
//------------------------------------------------------------------------
bool ChuShogi::CanMoveTwice(int start, int finish)
{
int delta;
int factor;
bool result = false;
if (mpBoard->mSquares[start]) {
int factor = (mpBoard->mSquares[start]->mColor == BLACK) ? -1 : 1;
switch (mpBoard->mSquares[start]->mpType->mTypeValue) {
case LION:
delta = (finish > start)? (finish - start):(start - finish);
if ((delta == 1) ||
(delta == WIDTH) ||
(delta == (WIDTH+1)) ||
(delta == (WIDTH-1)) )
{
result = true;
}
break;
case SOARING_EAGLE:
delta = factor*(finish - start);
if ((delta == (WIDTH+1)) ||
(delta == (WIDTH-1)) )
{
result = true;
}
break;
case HORNED_FALCON:
delta = factor*(finish - start);
if (delta == WIDTH) {
result = true;
}
break;
}
}
return result;
}
//--------------------------------------------------------------------------
// Class: ChuShogi
// Method: GameWon
// Description: Returns true if the current game state is a winning state
//--------------------------------------------------------------------------
bool ChuShogi::GameWon(int side)
{
int enemy = 1-side;
if (mpCrownPrinces[enemy])
return (mpCrownPrinces[enemy]->mCaptured &&
mpKings[enemy]->mCaptured);
else
return mpKings[enemy]->mCaptured;
}
//--------------------------------------------------------------------------
// Class: ChuShogi
// Method: GameDrawn
// Description: Returns true if the current game state is drawn
//--------------------------------------------------------------------------
bool ChuShogi::GameDrawn()
{
bool drawn = false;
int reps = 0;
uint64 key = mpBoard->mHashKey;
// Check for draw by repetition
for (unsigned int i=0; i < mHashKeys.size(); i++) {
if (mHashKeys[i] == key) {
// We have a repetition
reps++;
}
if (reps >= 3) {
drawn = true;
break;
}
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Warning: code below needs to be adjusted to account
// for crown princes at some point
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Check for draw by naked kings
if (!drawn) {
int pieces = 0;
for (int color = 0; color < 2; color++) {
for (unsigned int i = 0; i < mPieces[color].size(); i++) {
if (!mPieces[color][i].mCaptured)
pieces++;
}
}
if (pieces == 2) {
drawn = true;
// There are only the two kings left on the board
// Can one king capture the other?
vector<Move> movelist;
Piece* target = mpKings[0];
Piece* mover = mpKings[1];
mover->mpType->GenerateCaptures(movelist, mover);
for (unsigned int i = 0; i < movelist.size(); i++) {
if (movelist[i].mDestination == target->mSquare) {
drawn = false;
break;
}
}
}
}
return drawn;
}
//--------------------------------------------------------------------------
// Class: ChuShogi
// Method: ForcePromotion
// Description: Returns true if this move forces a promotion
//--------------------------------------------------------------------------
bool ChuShogi::ForcePromotion(const Move& move)
{
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
// Needs to be implemented
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
return false;
}
//--------------------------------------------------------------------------
// Class: ChuShogi
// Method: SetWeights
// Description: Assign positional weight matrices to the piece types
//--------------------------------------------------------------------------
void ChuShogi::SetWeights()
{
for (unsigned int i=0; i < mPieceTypes.size(); i++) {
mPieceTypes[i]->mWeights[0].resize(SIZE);
mPieceTypes[i]->mWeights[1].resize(SIZE);
for (int square = 0; square < SIZE; square++) {
mPieceTypes[i]->mWeights[0][square] = 0;
mPieceTypes[i]->mWeights[1][square] = 0;
}
}
}
//--------------------------------------------------------------------------
// Class: ChuShogi
// Method: Reset
// Description: Resets the game to its initial state
//--------------------------------------------------------------------------
void ChuShogi::Reset()
{
unsigned int i;
int piecetype, color, promoted;
// Remove old pieces from the board and delete them
for (color = 0; color < 2; color++) {
mPieces[color].clear();
}
// Re-initialize pointers on board squares to the NULL pointer
mpBoard->mSquares.assign(SIZE, (Piece*)0);
// Re-initialize the board hash key to an empty board key
mpBoard->mHashKey = (uint64)0;
// Create a new set of pieces
for (i = 0; i < SIZE; i++) {
if (mStartingPattern[i] != 0) {
piecetype = (mStartingPattern[i] - 1) % UNPROMOTED_PIECE_TYPES;
color = (mStartingPattern[i] - 1) / UNPROMOTED_PIECE_TYPES;
if (mPromotionMap[piecetype] != NO_PROMOTION) {
promoted = mPromotionMap[piecetype];
mPieces[color].push_back(
Piece(mPieceTypes[piecetype], color, i, mPieceTypes[promoted])
);
}
else {
mPieces[color].push_back(Piece(mPieceTypes[piecetype], color, i));
}
}
}
int square;
// At the start of the game there are no crown princes
mpCrownPrinces[0] = mpCrownPrinces[1] = 0;
// Place the new pieces on the board in their starting positions
for (color = 0; color < 2; color++) {
for (i = 0; i < mPieces[color].size(); i++) {
square = mPieces[color][i].mSquare;
piecetype = mPieces[color][i].mTypeValue;
mpBoard->mSquares[square] =&(mPieces[color][i]);
// Establish pointers to the kings for quick checks
// on whether a king has been captured
if ((piecetype == KING) || (piecetype == JEWEL)) {
mpKings[color] = mpBoard->mSquares[square];
}
// Update the hash key
mpBoard->mHashKey ^= mpBoard->KeyComponents(color, piecetype, square);
}
}
// Resync the boards bitboards
mpBoard->ResyncBitboards();
// Set the status to in progress
mStatus = IN_PROGRESS;
// Clear the hashkeys history
mHashKeys.clear();
}
//--------------------------------------------------------------------------
// Class: ChuShogi
// Method: CreateMove
// Description: Returns a pointer to a new move constructed
// from a move record
//--------------------------------------------------------------------------
Move* ChuShogi::CreateMove(const MoveRec& moverec)
{
unsigned int i;
Piece* mover = (Piece*)moverec.mPiecePtr;
Move* movePtr = 0;
// Generate the possible moves that this piece can make
vector<Move> movelist;
mover->mpType->GenerateCaptures(movelist, mover);
mover->mpType->GenerateNonCaptures(movelist, mover);
mpMoveGenerator->CheckForPromotions(movelist, mover->mColor);
PostProcess(movelist, mover->mColor);
for (i=0; i < movelist.size(); i++) {
if (movelist[i] == moverec) {
movePtr = new Move( movelist[i] );
break;
}
}
return movePtr;
}
//------------------------------------------------------------------------
// Class: ChuShogi
// Method: GetSecondSquares
// Description: Return a vector of integers representing possible
// destination squares for the piece at the given
// board location when making a second part of a two
// part move
//------------------------------------------------------------------------
void ChuShogi::GetSecondSquares(int start, int middle, vector<int>& squares)
{
squares.clear();
Piece* mover = mpBoard->mSquares[start];
if (!mover) return;
int type = mover->mpType->mTypeValue;
if ((type != LION) && (type != SOARING_EAGLE) &&
(type != HORNED_FALCON)) {
return;
}
vector<int> final_squares;
int factor = (mover->mColor == BLACK) ? 1 : -1;
switch (type) {
case LION:
final_squares.push_back(middle-WIDTH-1);
final_squares.push_back(middle-WIDTH);
final_squares.push_back(middle-WIDTH+1);
final_squares.push_back(middle-1);
final_squares.push_back(middle+1);
final_squares.push_back(middle+WIDTH-1);
final_squares.push_back(middle+WIDTH);
final_squares.push_back(middle+WIDTH+1);
break;
case SOARING_EAGLE:
final_squares.push_back(middle - factor*(WIDTH+1));
final_squares.push_back(middle - factor*(WIDTH-1));
break;
case HORNED_FALCON:
final_squares.push_back(middle - factor*WIDTH);
break;
}
vector<Move> movelist;
mover->mpType->GenerateCaptures(movelist, mover);
mover->mpType->GenerateNonCaptures(movelist, mover);
// Allow any game specific processing
int color = mover->mColor;
PostProcess(movelist, color);
Move* movePtr;
unsigned j;
squares.push_back(start);
for (unsigned int i = 0; i < movelist.size(); i++) {
movePtr = &(movelist[i]);
if (!movePtr->mValidate || IsValid(movePtr, color)) {
for (j = 0; j < final_squares.size(); j++) {
if (final_squares[j] == movelist[i].mDestination) {
squares.push_back(movelist[i].mDestination);
break;
}
}
}
}
}
| 33.522137
| 83
| 0.559138
|
jweathers777
|
9aceaf1cd1869beb5c0a03abe7e4ac593152a726
| 1,155
|
cpp
|
C++
|
c++/leetcode/0849-Maximize_Distance_to_Closest_Person-E.cpp
|
levendlee/leetcode
|
35e274cb4046f6ec7112cd56babd8fb7d437b844
|
[
"Apache-2.0"
] | 1
|
2020-03-02T10:56:22.000Z
|
2020-03-02T10:56:22.000Z
|
c++/leetcode/0849-Maximize_Distance_to_Closest_Person-E.cpp
|
levendlee/leetcode
|
35e274cb4046f6ec7112cd56babd8fb7d437b844
|
[
"Apache-2.0"
] | null | null | null |
c++/leetcode/0849-Maximize_Distance_to_Closest_Person-E.cpp
|
levendlee/leetcode
|
35e274cb4046f6ec7112cd56babd8fb7d437b844
|
[
"Apache-2.0"
] | null | null | null |
// 849 Maximize Distance to Closest Person
// https://leetcode.com/problems/maximize-distance-to-closest-person
// version: 1; create time: 2020-01-30 21:48:14;
class Solution {
public:
int maxDistToClosest(vector<int>& seats) {
const int n = seats.size();
/*
vector<int> ldist(n, 0);
int dist = n;
for (int i = 0; i < n; ++i) {
if (seats[i] == 0) {
ldist[i] = dist++;
} else {
dist = 1;
}
}
dist = n;
int max_dist = 0;
for (int i = n - 1; i >= 0; --i) {
if (seats[i] == 0) {
max_dist = std::max(max_dist, std::min(ldist[i], dist++));
} else {
dist = 1;
}
}
*/
int max_dist = 0;
int last = -1;
for (int i = 0; i < n; ++i) {
if (seats[i]) {
int dist = last < 0 ? i : (i - last) / 2;
max_dist = std::max(max_dist, dist);
last = i;
}
}
max_dist = std::max(max_dist, (n - last - 1));
return max_dist;
}
};
| 27.5
| 74
| 0.406926
|
levendlee
|
9ad369805f423f314d75e414303e38bca834d1da
| 2,341
|
cpp
|
C++
|
UT_MOS_6502_Emulator/ProcessingUnitTest_Logic.cpp
|
yu830425/MOS-6502-Simulator
|
b08495e1225b65df51ba2ad561f27b048a506c31
|
[
"MIT"
] | null | null | null |
UT_MOS_6502_Emulator/ProcessingUnitTest_Logic.cpp
|
yu830425/MOS-6502-Simulator
|
b08495e1225b65df51ba2ad561f27b048a506c31
|
[
"MIT"
] | null | null | null |
UT_MOS_6502_Emulator/ProcessingUnitTest_Logic.cpp
|
yu830425/MOS-6502-Simulator
|
b08495e1225b65df51ba2ad561f27b048a506c31
|
[
"MIT"
] | null | null | null |
#include "gtest/gtest.h"
#include "../MOS_6502_Emulator/ProcessingUnit.h"
using ::testing::Test;
TEST(ProcessingUnit, AND_0xFFAnd0x01_ResultShouldBe0x01)
{
ProcessingUnit testItem;
testItem.LDA(0xFF);
testItem.AND(0x01);
auto accumulator = testItem.getAccumulator();
ASSERT_EQ(0x01, accumulator);
}
TEST(ProcessingUnit, AND_ResultIsNegative_SetNegativeFlag)
{
ProcessingUnit testItem;
testItem.LDA(0xFF);
testItem.AND(0x80);
auto accumulator = testItem.getAccumulator();
ASSERT_EQ(0x80, accumulator);
auto negative = testItem.getFlag('N');
ASSERT_TRUE(negative);
}
TEST(ProcessingUnit, AND_ResultIsZero_SetZeroFlag)
{
ProcessingUnit testItem;
testItem.LDA(0xFF);
testItem.AND(0x00);
auto accumulator = testItem.getAccumulator();
ASSERT_EQ(0x00, accumulator);
auto zero = testItem.getFlag('Z');
ASSERT_TRUE(zero);
}
TEST(ProcessingUnit, ORA_0x0FOr0xF0_ResultShouldBe0xFF)
{
ProcessingUnit testItem;
testItem.LDA(0x0F);
testItem.ORA(0xF0);
auto accumulator = testItem.getAccumulator();
ASSERT_EQ(0xFF, accumulator);
}
TEST(ProcessingUnit, ORA_ResultIsNegative_SetNegativeFlag)
{
ProcessingUnit testItem;
testItem.LDA(0x0F);
testItem.ORA(0xF0);
auto accumulator = testItem.getAccumulator();
ASSERT_EQ(0xFF, accumulator);
auto negative = testItem.getFlag('N');
ASSERT_TRUE(negative);
}
TEST(ProcessingUnit, ORA_ResultIsZero_SetZeroFlag)
{
ProcessingUnit testItem;
testItem.LDA(0x00);
testItem.ORA(0x00);
auto accumulator = testItem.getAccumulator();
ASSERT_EQ(0x00, accumulator);
auto zero = testItem.getFlag('Z');
ASSERT_TRUE(zero);
}
TEST(ProcessingUnit, EOR_0x85EOR0xFA_ResultShouldBe0x7F)
{
ProcessingUnit testItem;
testItem.LDA(0x85);
testItem.EOR(0xFA);
auto accumulator = testItem.getAccumulator();
ASSERT_EQ(0x7F, accumulator);
}
TEST(ProcessingUnit, EOR_ResultIsNegative_SetNegativeFlag)
{
ProcessingUnit testItem;
testItem.LDA(0x05);
testItem.EOR(0xFA);
auto accumulator = testItem.getAccumulator();
ASSERT_EQ(0xFF, accumulator);
auto negative = testItem.getFlag('N');
ASSERT_TRUE(negative);
}
TEST(ProcessingUnit, EOR_ResultIsZero_SetZeroFlag)
{
ProcessingUnit testItem;
testItem.LDA(0xFF);
testItem.EOR(0xFF);
auto accumulator = testItem.getAccumulator();
ASSERT_EQ(0x00, accumulator);
auto zero = testItem.getFlag('Z');
ASSERT_TRUE(zero);
}
| 19.188525
| 58
| 0.770184
|
yu830425
|
9ae4e7d8e894e61a567eee34bb5e78ef4c2c6056
| 2,376
|
cpp
|
C++
|
runner-app/runner-app.cpp
|
sgrottel/open-here
|
4834e7064d92c49592585e83c930015a7b407615
|
[
"Apache-2.0"
] | null | null | null |
runner-app/runner-app.cpp
|
sgrottel/open-here
|
4834e7064d92c49592585e83c930015a7b407615
|
[
"Apache-2.0"
] | null | null | null |
runner-app/runner-app.cpp
|
sgrottel/open-here
|
4834e7064d92c49592585e83c930015a7b407615
|
[
"Apache-2.0"
] | null | null | null |
//
// Open Here
// runner-app.cpp -- Runner app main entry point
// This app is to be triggered by the hot key.
//
// Copyright 2022 SGrottel (https://www.sgrottel.de)
//
// 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 permissionsand
// limitations under the License.
//
#include "oh-core/InstanceList.h"
#include "oh-core/ExplorerDetector.h"
#include "oh-core/WindowInfo.h"
#include "CmdLineParser.h"
#include <string>
#include <sstream>
#include <iomanip>
#define VC_EXTRALEAN
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
int APIENTRY wWinMain(_In_ HINSTANCE hInstance, _In_opt_ HINSTANCE hPrevInstance, _In_ LPWSTR lpCmdLine, _In_ int nShowCmd) {
openhere::CoInitialize coInit;
CmdLineParser cmdLine;
cmdLine.parse(lpCmdLine);
openhere::InstanceList results;
{
openhere::ExplorerDetector det{ coInit };
results = det.runDetection();
}
// If now explorer windows found, would we want to detect the selected files/folders on the desktop?
{
openhere::WindowInfo winInfo;
winInfo.AddInfo(results);
}
results.sortByZ();
std::wstringstream msg;
msg << L"Found explorer instances: " << results.size();
for (unsigned int idx = 0; idx < results.size(); ++idx) {
auto const& inst = results.get(idx);
msg << L"\n\t" << inst.getInstanceType() << L" 0x" << std::hex << std::setw(8) << std::setfill(L'0') << inst.getWindowHandle() << L" z: " << std::dec << inst.getZDepth();
if (inst.isMarkedAsForegroundWindow()) msg << L" FG";
if (inst.isMarkedAsTopWindow()) msg << L" T";
for (unsigned int i2 = 0; i2 < inst.getOpenedPathsCount(); i2++) {
msg << L"\n\t\tP: " << inst.getOpenedPath(i2);
}
for (unsigned int i2 = 0; i2 < inst.getSelectedItemsCount(); i2++) {
msg << L"\n\t\tF: " << inst.getSelectedItem(i2);
}
}
MessageBoxW(NULL, msg.str().c_str(), L"open-here", MB_OK);
return 0;
}
| 33
| 173
| 0.671717
|
sgrottel
|
9ae747b25fc041232e217a0dc36484ab0b0472ec
| 210
|
hpp
|
C++
|
sprout/weed/parser/string.hpp
|
osyo-manga/Sprout
|
8885b115f739ef255530f772067475d3bc0dcef7
|
[
"BSL-1.0"
] | 1
|
2020-02-04T05:16:01.000Z
|
2020-02-04T05:16:01.000Z
|
sprout/weed/parser/string.hpp
|
jwakely/Sprout
|
a64938fad0a64608f22d39485bc55a1e0dc07246
|
[
"BSL-1.0"
] | null | null | null |
sprout/weed/parser/string.hpp
|
jwakely/Sprout
|
a64938fad0a64608f22d39485bc55a1e0dc07246
|
[
"BSL-1.0"
] | null | null | null |
#ifndef SPROUT_WEED_PARSER_STRING_HPP
#define SPROUT_WEED_PARSER_STRING_HPP
#include <sprout/config.hpp>
#include <sprout/weed/parser/string/string.hpp>
#endif // #ifndef SPROUT_WEED_PARSER_STRING_HPP
| 26.25
| 48
| 0.809524
|
osyo-manga
|
9af242420da16a4c011c59bcf7d66fe1ca433b84
| 739
|
hh
|
C++
|
modules/Robbie/RobbieModule.hh
|
ElonKou/genetic
|
507f739b44399b8dbae1bde4523fbb718704e223
|
[
"MIT"
] | 11
|
2020-04-12T19:53:40.000Z
|
2022-01-28T16:56:22.000Z
|
modules/Robbie/RobbieModule.hh
|
ElonKou/genetic
|
507f739b44399b8dbae1bde4523fbb718704e223
|
[
"MIT"
] | null | null | null |
modules/Robbie/RobbieModule.hh
|
ElonKou/genetic
|
507f739b44399b8dbae1bde4523fbb718704e223
|
[
"MIT"
] | 2
|
2020-03-14T08:48:19.000Z
|
2021-04-22T06:56:01.000Z
|
#pragma once
#ifndef ROBBIE_MODULE_HH_
#define ROBBIE_MODULE_HH_
#include "InspectWindow.hh"
#include "ModuleBase.hh"
#include "RobbieControlWindow.hh"
#include "RobbieController.hh"
#include "SimpleMap.hh"
#include "SimpleMapWindow.hh"
typedef struct RobbieModuleData {
vector<SimpleMap*> maps;
SimpleMap* dis_map;
RobbieController* controller;
RobbieControlWindow* rc_window;
SimpleMapWindow* map_window;
InspectWindow* isp_window;
InspectInfo* isp_info;
} RobbieModuleData;
class RobbieModule : public ModuleBase {
public:
RobbieModuleData* data;
RobbieModule();
~RobbieModule();
virtual void InitModule();
virtual void UpdateModule();
};
#endif
| 21.114286
| 40
| 0.710419
|
ElonKou
|
9af475eb6dc4aaa627b9e46a5a633ab3185af9ea
| 3,516
|
cpp
|
C++
|
src/compiler.cpp
|
martinogden/mer
|
33b4b39b1604ce0708b0d3d1c809b95683a2f4cb
|
[
"Unlicense"
] | 2
|
2019-11-17T22:54:16.000Z
|
2020-08-07T20:53:25.000Z
|
src/compiler.cpp
|
martinogden/mer
|
33b4b39b1604ce0708b0d3d1c809b95683a2f4cb
|
[
"Unlicense"
] | null | null | null |
src/compiler.cpp
|
martinogden/mer
|
33b4b39b1604ce0708b0d3d1c809b95683a2f4cb
|
[
"Unlicense"
] | null | null | null |
#include <memory>
#include <sstream>
#include <set>
#include "compiler.hpp"
#include "generator.hpp"
#include "parser/lexer.hpp"
#include "parser/parser.hpp"
#include "sca/return-checker.hpp"
#include "sca/init-checker.hpp"
#include "sca/use-checker.hpp"
#include "type/checker.hpp"
#include "inst/codegen.hpp"
#include "cst/printer.hpp"
#include "ast/elaborator/stmt.hpp"
#include "ast/printer.hpp"
#include "irt/translator/translator.hpp"
#include "irt/printer.hpp"
#include "irt/translator/structs.hpp"
#include "graph.hpp"
#include "x86/codegen.hpp"
#include "regalloc/regalloc.hpp"
#include "print-utils.hpp"
const std::string MAIN_PREFIX("_c0_");
std::pair<bool, std::string> compile(std::string src, Stage stage) {
Generator gen;
// Front end
Lexer lexer(std::move(src));
Parser parser(lexer);
ParseTree tree = parser.run();
if (parser.errors.exist())
return {false, join( parser.errors.get(), "\n" )};
if (stage == Stage::PARSE) {
CSTPrinter printer;
return {true, printer.get(tree)};
}
Elaborator elab(tree, gen);
std::vector<FunNodePtr> defns = elab.run();
Map<FunTypePtr> funTypes = elab.getFunTypes();
Map<StructTypePtr> structTypes = elab.getStructTypes();
if (elab.errors.exist())
return {false, join( elab.errors.get(), "\n" )};
if (stage == Stage::AST) {
ASTPrinter printer;
for (auto& ast : defns)
std::cout << printer.get(ast) << std::endl;
return {true, ""};
}
// Semantic analysis stage
Errors errors;
for (auto& ast : defns) {
InitChecker initChecker(ast);
initChecker.run();
if (initChecker.errors.exist()) {
errors.append(initChecker.errors);
continue;
}
UseChecker useChecker(ast);
useChecker.run();
if (useChecker.errors.exist()) {
errors.append(useChecker.errors);
continue;
}
ReturnChecker retChecker(ast);
retChecker.run();
if (retChecker.errors.exist()) {
errors.append(retChecker.errors);
continue;
}
TypeChecker typeChecker(ast, funTypes, structTypes);
typeChecker.run();
if (typeChecker.errors.exist()) {
errors.append(typeChecker.errors);
continue;
}
}
if (errors.exist())
return {false, join( errors.get(), "\n" )};
Map<IRTStruct> structs = toIRTStructs(structTypes);
// Middle end (intermediate code gen)
if (stage == Stage::ASM) {
// TODO: tidy up
std::cout << ".section __TEXT,__text" << std::endl;
std::cout << ".globl __c0_main" << std::endl;
}
for (auto& ast : defns) {
Translator tr(gen, structs);
IRTFun irt = tr.get(ast);
if (stage == Stage::HIR) {
IRTPrinter printer;
std::cout << printer.get(irt) << std::endl;
continue;
}
CodeGen codegen(irt, gen);
InstFun fun = codegen.run();
std::string prefix = (fun.id == "main") ? MAIN_PREFIX : "";
std::cout << "\n" << "_" << prefix << fun.id << ":" << std::endl;
if (stage == Stage::LIR) {
for (Inst& inst : fun.insts)
std::cout << inst << std::endl;
continue;
}
// Back end
Alloc alloc = regAlloc(fun);
if (stage == Stage::REGALLOC) {
for (const auto& pair : alloc.map) {
if (pair.first.is(Operand::TMP))
std::cout << pair.first << " -> " << pair.second << std::endl;
}
}
fun = regAssign(fun, alloc);
if (stage == Stage::REGALLOC) {
for (Inst& inst : fun.insts)
std::cout << inst << std::endl;
continue;
}
X86CodeGen x86codegen(fun, alloc);
X86Fun x86fun = x86codegen.run();
if (stage == Stage::ASM) {
for (auto& as : x86fun.code)
std::cout << as << std::endl;
}
}
return {true, ""};
}
| 21.180723
| 68
| 0.641069
|
martinogden
|
9af6a6510bcd11cdafcf9c23398eb64f5a7c1543
| 2,433
|
cpp
|
C++
|
models/maxcut-random/code/src/learning/graph.cpp
|
qcappart/learning-DD
|
93094c450f8f0929168b303b4d0680889deeb9b0
|
[
"MIT"
] | 23
|
2018-09-18T20:04:32.000Z
|
2022-03-24T19:31:36.000Z
|
models/maxcut-random/code/src/learning/graph.cpp
|
qcappart/learning-DD
|
93094c450f8f0929168b303b4d0680889deeb9b0
|
[
"MIT"
] | null | null | null |
models/maxcut-random/code/src/learning/graph.cpp
|
qcappart/learning-DD
|
93094c450f8f0929168b303b4d0680889deeb9b0
|
[
"MIT"
] | 3
|
2019-07-26T01:22:29.000Z
|
2022-03-10T13:48:18.000Z
|
/* MIT License
[Initial work] Copyright (c) 2018 Dai, Hanjun and Khalil, Elias B and Zhang, Yuyu and Dilkina, Bistra and Song, Le
[Adaptation] Copyright (c) 2018 Quentin Cappart, Emmanuel Goutierre, David Bergman and Louis-Martin Rousseau
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 "graph.h"
#include <cassert>
#include <iostream>
#include <random>
Graph::Graph() : num_nodes(0), num_edges(0)
{
adj_list.clear();
}
Graph::Graph(const int _num_nodes, const int _num_edges, const int* edges_from, const int* edges_to, const double* weights)
: num_nodes(_num_nodes), num_edges(_num_edges)
{
adj_list.resize(num_nodes);
for (int i = 0; i < num_nodes; ++i)
adj_list[i].clear();
for (int i = 0; i < num_edges; ++i)
{
int x = edges_from[i], y = edges_to[i];
double w = weights[i];
adj_list[x].push_back( std::make_pair(y, w) );
adj_list[y].push_back( std::make_pair(x, w) );
}
}
GSet::GSet()
{
graph_pool.clear();
}
void GSet::InsertGraph(int gid, std::shared_ptr<Graph> graph)
{
assert(graph_pool.count(gid) == 0);
graph_pool[gid] = graph;
}
std::shared_ptr<Graph> GSet::Get(int gid)
{
assert(graph_pool.count(gid));
return graph_pool[gid];
}
std::shared_ptr<Graph> GSet::Sample()
{
assert(graph_pool.size());
int gid = rand() % graph_pool.size();
assert(graph_pool[gid]);
return graph_pool[gid];
}
GSet GSetTrain, GSetTest;
| 31.192308
| 126
| 0.7164
|
qcappart
|
9afa3a324470aa730a985a63c907f109ff7f453c
| 18,490
|
cpp
|
C++
|
src/v8binder/V8Context.cpp
|
daphnis-kau/XScript
|
8dabb5f1138c2f5ee7a7aa5605c053d18ef72bba
|
[
"MIT"
] | 43
|
2020-03-09T02:09:09.000Z
|
2022-02-25T01:29:57.000Z
|
src/v8binder/V8Context.cpp
|
daphnis-kau/XScript
|
8dabb5f1138c2f5ee7a7aa5605c053d18ef72bba
|
[
"MIT"
] | 1
|
2021-07-22T05:01:10.000Z
|
2021-10-15T09:57:52.000Z
|
src/v8binder/V8Context.cpp
|
daphnis-kau/XScript
|
8dabb5f1138c2f5ee7a7aa5605c053d18ef72bba
|
[
"MIT"
] | 5
|
2020-03-09T01:55:14.000Z
|
2020-08-28T23:12:03.000Z
|
#include "V8Context.h"
#include "CScriptJS.h"
#include "CDebugJS.h"
#include "CTypeJS.h"
#include "core/CClassInfo.h"
#include "core/CCallInfo.h"
#define MAX_STRING_BUFFER_SIZE 65536
namespace XS
{
SV8Context::SV8Context( CScriptJS* pScript )
: m_pScript(pScript)
, m_platform(nullptr)
, m_pIsolate(nullptr)
, m_nStringID(0)
, m_pTempStrBuffer64K(new tbyte[MAX_STRING_BUFFER_SIZE])
, m_nCurUseSize(0)
, m_nStrBufferStack(0)
{
}
void SV8Context::CallJSStatck(bool bAdd)
{
if (bAdd)
{
if (m_nStrBufferStack == 0)
ClearCppString((void*)(uintptr_t)(-1));
++m_nStrBufferStack;
}
else
{
assert(m_nStrBufferStack);
--m_nStrBufferStack;
}
}
//==================================================================================================================================//
// 字符串函数 //
//==================================================================================================================================//
void SV8Context::ClearCppString(void* pStack)
{
uint32 nIndex = (uint32)m_vecStringInfo.size();
while (nIndex && m_vecStringInfo[nIndex - 1].m_pStack < pStack)
delete[] (char*)m_vecStringInfo[--nIndex].m_pBuffer;
if (nIndex < m_vecStringInfo.size())
m_vecStringInfo.erase(m_vecStringInfo.begin() + nIndex, m_vecStringInfo.end());
while (m_nCurUseSize >= sizeof(SStringFixed))
{
SStringFixed* pFixeString = ((SStringFixed*)(m_pTempStrBuffer64K + m_nCurUseSize)) - 1;
if (pFixeString->m_pStack >= pStack)
break;
m_nCurUseSize -= (uint32)(sizeof(SStringFixed) + pFixeString->m_nLen);
}
}
LocalValue SV8Context::StringFromUtf8(const char* szUtf8)
{
if (!szUtf8)
return v8::Null(m_pIsolate);
return v8::String::NewFromUtf8(m_pIsolate, szUtf8);
}
LocalValue SV8Context::StringFromUcs(const wchar_t* szUcs)
{
if (!szUcs)
return v8::Null(m_pIsolate);
if (sizeof(wchar_t) == sizeof(uint16_t))
return v8::String::NewFromTwoByte(m_pIsolate,
(uint16_t*)szUcs, v8::NewStringType::kNormal).ToLocalChecked();
m_szTempUcs2 = szUcs;
size_t nSize = m_szTempUcs2.size();
uint16_t* szDes = (uint16_t*)&m_szTempUcs2[0];
for (size_t i = 0; i < nSize; i++)
szDes[i] = m_szTempUcs2[i];
szDes[nSize] = 0;
return v8::String::NewFromTwoByte(m_pIsolate,
(uint16_t*)szDes, v8::NewStringType::kNormal).ToLocalChecked();
}
const char* SV8Context::StringToUtf8(LocalValue obj)
{
if (obj == v8::Null(m_pIsolate))
return nullptr;
v8::Local<v8::Context> context = m_pIsolate->GetCurrentContext();
v8::MaybeLocal<v8::String> v = obj->ToString(context);
if (v.IsEmpty())
return nullptr;
v8::Local<v8::String> StringObject = v.ToLocalChecked();
size_t nStrLen = StringObject->Utf8Length(m_pIsolate);
if (nStrLen == 0)
return "";
size_t nAllocSize = AligenUp((uint32)(nStrLen + 1), sizeof(void*));
if (nAllocSize + m_nCurUseSize + sizeof(SStringFixed) < MAX_STRING_BUFFER_SIZE)
{
char* szUtf8 = (char*)(m_pTempStrBuffer64K + m_nCurUseSize);
StringObject->WriteUtf8(m_pIsolate, szUtf8);
SStringFixed strCpp;
strCpp.m_pStack = &strCpp;
strCpp.m_nLen = AligenUp((uint32)(nStrLen + 1), sizeof(void*));
m_nCurUseSize += strCpp.m_nLen + sizeof(SStringFixed);
memcpy(m_pTempStrBuffer64K + m_nCurUseSize - sizeof(SStringFixed), &strCpp, sizeof(SStringFixed));
return szUtf8;
}
else
{
SStringDynamic strCpp;
strCpp.m_pStack = &strCpp;
strCpp.m_pBuffer = new char[nStrLen + 1];
StringObject->WriteUtf8(m_pIsolate, (char*)strCpp.m_pBuffer);
m_vecStringInfo.push_back(strCpp);
return (char*)strCpp.m_pBuffer;
}
}
const wchar_t* SV8Context::StringToUcs(LocalValue obj)
{
if (obj == v8::Null(m_pIsolate))
return nullptr;
v8::Local<v8::Context> context = m_pIsolate->GetCurrentContext();
v8::MaybeLocal<v8::String> v = obj->ToString(context);
if (v.IsEmpty())
return nullptr;
v8::Local<v8::String> StringObject = v.ToLocalChecked();
size_t nStrLen = StringObject->Utf8Length(m_pIsolate);
if (nStrLen == 0)
return L"";
uint32 nAllocSize = AligenUp(uint32(nStrLen + 1) * sizeof(wchar_t), sizeof(void*));
wchar_t* szUcs2 = nullptr;
if (nAllocSize + m_nCurUseSize < MAX_STRING_BUFFER_SIZE)
{
szUcs2 = (wchar_t*)(m_pTempStrBuffer64K + m_nCurUseSize);
StringObject->Write(m_pIsolate, (uint16_t*)szUcs2);
szUcs2[nStrLen] = 0;
SStringFixed strCpp;
strCpp.m_pStack = &strCpp;
strCpp.m_nLen = nAllocSize;
m_nCurUseSize += strCpp.m_nLen + sizeof(SStringFixed);
memcpy(m_pTempStrBuffer64K + m_nCurUseSize - sizeof(SStringFixed), &strCpp, sizeof(SStringFixed));
}
else
{
SStringDynamic strCpp;
strCpp.m_pStack = &strCpp;
strCpp.m_pBuffer = szUcs2 = new wchar_t[nStrLen + 1];
StringObject->Write(m_pIsolate, (uint16_t*)szUcs2);
m_vecStringInfo.push_back(strCpp);
}
if (sizeof(wchar_t) == sizeof(uint16_t))
return szUcs2;
uint16_t* szSrc = (uint16_t*)szUcs2;
while (nStrLen--)
szUcs2[nStrLen] = szSrc[nStrLen];
return szUcs2;
}
//==================================================================================================================================//
// 对内部提供的功能性函数 //
//==================================================================================================================================//
void SV8Context::ReportException(v8::TryCatch* try_catch, v8::Local<v8::Context> context)
{
v8::Local<v8::Message> message = try_catch->Message();
v8::String::Utf8Value exception(m_pIsolate, try_catch->Exception());
if (message.IsEmpty())
{
// V8 didn't provide any extra information about this error; just
// print the exception.
m_pScript->Output("Error:", -1);
m_pScript->Output(*exception, -1);
m_pScript->Output("\n", -1);
return;
}
char szNumber[32];
// Print (filename):(line number): (message).
v8::String::Utf8Value filename(m_pIsolate, message->GetScriptResourceName());
sprintf(szNumber, "%d", message->GetLineNumber(context).ToChecked());
m_pScript->Output(*filename, -1);
m_pScript->Output(":", -1);
m_pScript->Output(szNumber, -1);
m_pScript->Output("\n\t", -1);
m_pScript->Output(*exception, -1);
m_pScript->Output("\n", -1);
// Print line of source code.
auto souceline = message->GetSourceLine(context).ToLocalChecked();
m_pScript->Output(*v8::String::Utf8Value(m_pIsolate, souceline), -1);
m_pScript->Output("\n", -1);
// Print wavy underline (GetUnderline is deprecated).
int start = message->GetStartColumn();
for (int i = 0; i < start; i++)
m_pScript->Output(" ", -1);
int end = message->GetEndColumn();
for (int i = start; i < end; i++)
m_pScript->Output(" ^", -1);
m_pScript->Output("\n", -1);
auto backTrace = try_catch->StackTrace(context);
if (backTrace.IsEmpty())
return;
v8::Local<v8::Value> strBackTrace = backTrace.ToLocalChecked();
v8::String::Utf8Value stack_trace(m_pIsolate, strBackTrace->ToString(m_pIsolate));
if (!stack_trace.length())
return;
m_pScript->Output(*stack_trace, -1);
}
void SV8Context::Log( const v8::FunctionCallbackInfo<v8::Value>& args )
{
v8::Local<v8::External> wrap = v8::Local<v8::External>::Cast( args.Data() );
CScriptJS* pScript = (CScriptJS*)wrap->Value();
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope scope( isolate );
for( int32 i = 0; i < args.Length(); i++ )
{
v8::Local<v8::Value> arg = args[i];
v8::String::Utf8Value value( isolate, arg );
const char* szValue = *value;
pScript->Output( szValue, -1 );
pScript->Output( " ", -1 );
}
pScript->Output( "\n", -1 );
}
void SV8Context::Break( const v8::FunctionCallbackInfo<v8::Value>& args )
{
v8::Local<v8::External> wrap = v8::Local<v8::External>::Cast(args.Data());
CScriptJS* pScript = (CScriptJS*)wrap->Value();
( (CDebugJS*)( pScript->GetDebugger() ) )->Stop();
}
void SV8Context::CallFromV8( const v8::FunctionCallbackInfo<v8::Value>& args )
{
v8::Local<v8::External> wrap = v8::Local<v8::External>::Cast( args.Data() );
SCallInfo* pCallInfo = (SCallInfo*)wrap->Value();
if( !pCallInfo )
return;
v8::Isolate* isolate = args.GetIsolate();
v8::HandleScope scope( isolate );
CScriptJS& Script = *pCallInfo->m_pScript;
const CCallInfo* pCallBase = pCallInfo->m_pCallBase;
try
{
auto& listParam = pCallBase->GetParamList();
auto& listParamSize = pCallBase->GetParamSize();
uint32 nParamSize = pCallBase->GetParamTotalSize();
uint32 nParamCount = (uint32)listParam.size();
DataType nResultType = pCallBase->GetResultType();
size_t nReturnSize = nResultType ? pCallBase->GetResultSize() : sizeof( int64 );
size_t nArgSize = nParamCount*sizeof( void* );
char* pDataBuf = (char*)alloca( nParamSize + nArgSize + nReturnSize );
void** pArgArray = (void**)( pDataBuf + nParamSize );
char* pResultBuf = pDataBuf + nParamSize + nArgSize;
int32 nFunctionIndex = pCallBase->GetFunctionIndex();
int32 nArgCount = args.Length();
SV8Context& Context = Script.GetV8Context();
v8::Isolate* isolate = Context.m_pIsolate;
LocalValue undefined = Undefined( isolate );
int32 nArgIndex = nFunctionIndex >= eCT_ClassFunction ? -1 : 0;
for( uint32 nParamIndex = 0; nParamIndex < nParamCount; nParamIndex++, nArgIndex++ )
{
DataType nType = listParam[nParamIndex];
CJSTypeBase* pParamType = GetJSTypeBase( nType );
LocalValue arg = undefined;
if( nArgIndex < 0 )
pParamType->FromVMValue( nType, Script, pDataBuf, args.This() );
else if( nArgIndex < nArgCount )
pParamType->FromVMValue( nType, Script, pDataBuf, args[nArgIndex] );
else
pParamType->FromVMValue( nType, Script, pDataBuf, undefined );
pArgArray[nParamIndex] = IsValueClass( nType ) ? *(void**)pDataBuf : pDataBuf;
pDataBuf += listParamSize[nParamIndex];
}
pCallBase->Call( pResultBuf, pArgArray, Script );
if( !nResultType )
return;
CJSTypeBase* pReturnType = GetJSTypeBase( nResultType );
args.GetReturnValue().Set( pReturnType->ToVMValue( nResultType, Script, pResultBuf ) );
if( IsValueClass( nResultType ) )
{
auto pClassInfo = (const CClassInfo*)( ( nResultType >> 1 ) << 1 );
pClassInfo->Destruct( &Script, pResultBuf );
}
}
catch( ... )
{
}
}
void SV8Context::NewObject( const v8::FunctionCallbackInfo<v8::Value>& args )
{
SJSClassInfo* pInfo = (SJSClassInfo*)v8::External::Cast( *args.Data() )->Value();
if( pInfo == nullptr )
return;
CScriptJS& Script = *static_cast<CScriptJS*>( pInfo->m_pScript );
SV8Context& Context = Script.GetV8Context();
v8::Isolate* isolate = Context.m_pIsolate;
v8::Local<v8::Object> ScriptObj = args.This();
v8::External* pCppBind = nullptr;
if( ScriptObj->InternalFieldCount() )
pCppBind = v8::External::Cast( *ScriptObj->GetInternalField( 0 ) );
else
{
v8::Local<v8::Value> key = Context.m_CppField.Get( isolate );
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::MaybeLocal<v8::Value> field = ScriptObj->Get( context, key );
pCppBind = v8::External::Cast( *( field.ToLocalChecked() ) );
}
if( pCppBind->Value() )
{
args.GetReturnValue().Set( ScriptObj );
return;
}
auto& listParam = pInfo->m_pClassInfo->GetConstructorParamType();
auto& listParamSize = pInfo->m_pClassInfo->GetConstructorParamSize();
uint32 nParamSize = pInfo->m_pClassInfo->GetConstructorParamTotalSize();
uint32 nParamCount = (uint32)listParam.size();
size_t nArgSize = nParamCount*sizeof( void* );
char* pDataBuf = (char*)alloca( nParamSize + nArgSize );
void** pArgArray = (void**)( pDataBuf + nParamSize );
int32 nArgCount = args.Length();
LocalValue undefined = Undefined( isolate );
for( uint32 nParamIndex = 0; nParamIndex < nParamCount; nParamIndex++ )
{
DataType nType = listParam[nParamIndex];
CJSTypeBase* pParamType = GetJSTypeBase( nType );
LocalValue arg = undefined;
if( (int32)nParamIndex < nArgCount )
pParamType->FromVMValue( nType, Script, pDataBuf, args[nParamIndex] );
else
pParamType->FromVMValue( nType, Script, pDataBuf, undefined );
pArgArray[nParamIndex] = IsValueClass( nType ) ? *(void**)pDataBuf : pDataBuf;
pDataBuf += listParamSize[nParamIndex];
}
void* pObject = new tbyte[pInfo->m_pClassInfo->GetClassSize()];
pInfo->m_pClassInfo->Construct( &Script, pObject, pArgArray );
Context.BindObj( pObject, args.This(), pInfo->m_pClassInfo, true );
}
void SV8Context::Destruction( const v8::FunctionCallbackInfo<v8::Value>& args )
{
v8::Local<v8::External> wrap = v8::Local<v8::External>::Cast( args.Data() );
SJSClassInfo* pClassInfo = (SJSClassInfo*)wrap->Value();
CScriptJS& Script = *(CScriptJS*)pClassInfo->m_pScript;
SV8Context& Context = Script.GetV8Context();
v8::Isolate* isolate = Context.m_pIsolate;
v8::Object* pScriptObject = v8::Object::Cast( *args.This() );
v8::External* pCppBind = nullptr;
if( pScriptObject->InternalFieldCount() )
pCppBind = v8::External::Cast( *pScriptObject->GetInternalField( 0 ) );
else
{
v8::Local<v8::Value> key = Context.m_CppField.Get( isolate );
v8::Local<v8::Context> context = isolate->GetCurrentContext();
v8::MaybeLocal<v8::Value> field = pScriptObject->Get( context, key );
pCppBind = v8::External::Cast( *( field.ToLocalChecked() ) );
}
SObjInfo* pObjectInfo = (SObjInfo*)pCppBind->Value();
if( !pObjectInfo )
return;
Context.UnbindObj( pObjectInfo, false );
}
void SV8Context::GCCallback( const v8::WeakCallbackInfo<SObjInfo>& data )
{
SObjInfo* pObjectInfo = data.GetParameter();
SJSClassInfo* pInfo = pObjectInfo->m_pClassInfo;
pInfo->m_pScript->GetV8Context().UnbindObj( pObjectInfo, true );
}
void SV8Context::GetterFromV8( v8::Local<v8::Name> property,
const v8::PropertyCallbackInfo<v8::Value>& info )
{
v8::Local<v8::External> wrap = v8::Local<v8::External>::Cast( info.Data() );
SCallInfo* pCallInfo = (SCallInfo*)wrap->Value();
if( !pCallInfo )
return;
v8::Isolate* isolate = info.GetIsolate();
v8::HandleScope scope( isolate );
CScriptJS& Script = *pCallInfo->m_pScript;
const CCallInfo* pCallBase = pCallInfo->m_pCallBase;
try
{
void* pObject = nullptr;
DataType nThisType = pCallBase->GetParamList()[0];
CJSObject::GetInst().FromVMValue( nThisType, Script, (char*)&pObject, info.This() );
if( pObject == nullptr )
return;
DataType nResultType = pCallBase->GetResultType();
size_t nReturnSize = nResultType ? pCallBase->GetResultSize() : sizeof( int64 );
char* pResultBuf = (char*)alloca( nReturnSize );
void* aryArg[] = { &pObject, nullptr };
pCallBase->Call( pResultBuf, aryArg, Script );
if( !nResultType )
return;
CJSTypeBase* pReturnType = GetJSTypeBase( nResultType );
info.GetReturnValue().Set( pReturnType->ToVMValue( nResultType, Script, pResultBuf ) );
if( IsValueClass( nResultType ) )
{
auto pClassInfo = (const CClassInfo*)( ( nResultType >> 1 ) << 1 );
pClassInfo->Destruct( &Script, pResultBuf );
}
}
catch( ... )
{
}
}
void SV8Context::SetterFromV8( v8::Local<v8::Name> property,
LocalValue value, const v8::PropertyCallbackInfo<void>& info )
{
v8::Local<v8::External> wrap = v8::Local<v8::External>::Cast( info.Data() );
SCallInfo* pCallInfo = (SCallInfo*)wrap->Value();
if( !pCallInfo )
return;
v8::Isolate* isolate = info.GetIsolate();
v8::HandleScope scope( isolate );
CScriptJS& Script = *pCallInfo->m_pScript;
const CCallInfo* pCallBase = pCallInfo->m_pCallBase;
try
{
void* pObject = nullptr;
DataType nThisType = pCallBase->GetParamList()[0];
CJSObject::GetInst().FromVMValue( nThisType, Script, (char*)&pObject, info.This() );
if (pObject == nullptr)
return;
DataType nType = pCallBase->GetParamList()[1];
size_t nParamSize = pCallBase->GetParamSize()[1];
char* pDataBuf = (char*)alloca( nParamSize );
SV8Context& Context = Script.GetV8Context();
v8::Isolate* isolate = Context.m_pIsolate;
LocalValue undefined = Undefined(isolate);
CJSTypeBase* pParamType = GetJSTypeBase( nType );
pParamType->FromVMValue( nType, Script, pDataBuf, value );
void* pArg = IsValueClass( nType ) ? *(void**)pDataBuf : pDataBuf;
void* aryArg[] = { &pObject, pArg, nullptr };
pCallBase->Call( nullptr, aryArg, Script );
}
catch (...)
{
}
}
void SV8Context::BindObj( void* pObject, v8::Local<v8::Object> ScriptObj,
const CClassInfo* pInfo, bool bRecycle )
{
if( !pObject )
return;
SObjInfo& ObjectInfo = *m_pScript->AllocObjectInfo();
ObjectInfo.m_bRecycle = bRecycle;
ObjectInfo.m_Object.Reset( m_pIsolate, ScriptObj );
ObjectInfo.m_pClassInfo = m_pScript->m_mapClassInfo.Find( (const void*)pInfo );
ObjectInfo.m_pObject = pObject;
m_pScript->m_mapObjInfo.Insert( ObjectInfo );
// 注册回调函数
if( pInfo && pInfo->IsCallBack() )
pInfo->ReplaceVirtualTable( m_pScript, pObject, ObjectInfo.m_bRecycle, 0 );
v8::Local<v8::External> cppInfo = v8::External::New( m_pIsolate, &ObjectInfo );
if( ScriptObj->InternalFieldCount() )
ScriptObj->SetInternalField( 0, cppInfo );
else
ScriptObj->Set( m_pIsolate->GetCurrentContext(), m_CppField.Get( m_pIsolate ), cppInfo );
ObjectInfo.m_Object.SetWeak( &ObjectInfo,
&SV8Context::GCCallback, v8::WeakCallbackType::kParameter );
}
void SV8Context::UnbindObj( SObjInfo* pObjectInfo, bool bFromGC )
{
void* pObject = pObjectInfo->m_pObject;
bool bRecycle = pObjectInfo->m_bRecycle;
v8::HandleScope handle_scope( m_pIsolate );
v8::TryCatch try_catch( m_pIsolate );
if( !bFromGC )
{
v8::Local<v8::Object> ScriptObj = pObjectInfo->m_Object.Get( m_pIsolate );
assert( !ScriptObj.IsEmpty()&&ScriptObj->IsObject() );
if( ScriptObj->InternalFieldCount() )
ScriptObj->SetInternalField( 0, v8::Null( m_pIsolate ) );
else
ScriptObj->Set( m_pIsolate->GetCurrentContext(),
m_CppField.Get( m_pIsolate ), v8::Null( m_pIsolate ) );
}
pObjectInfo->Remove();
pObjectInfo->m_pObject = nullptr;
pObjectInfo->m_Object.Reset();
m_pScript->FreeObjectInfo( pObjectInfo );
if( !pObject || !pObjectInfo->m_pClassInfo )
return;
const CClassInfo* pInfo = pObjectInfo->m_pClassInfo->m_pClassInfo;
pInfo->RecoverVirtualTable( m_pScript, pObject );
if( !bRecycle )
return;
pInfo->Destruct( m_pScript, pObject );
delete[]( tbyte* )pObject;
}
}
| 35.694981
| 135
| 0.662304
|
daphnis-kau
|
9afb396ed5145b36f6d5b74f009da25f29cd4ebc
| 1,177
|
hpp
|
C++
|
Checklist.hpp
|
Aerobreaker/ChecklistLoader
|
54ce95d541331c644a9711e4e24eee65295a0ee8
|
[
"Unlicense"
] | null | null | null |
Checklist.hpp
|
Aerobreaker/ChecklistLoader
|
54ce95d541331c644a9711e4e24eee65295a0ee8
|
[
"Unlicense"
] | null | null | null |
Checklist.hpp
|
Aerobreaker/ChecklistLoader
|
54ce95d541331c644a9711e4e24eee65295a0ee8
|
[
"Unlicense"
] | null | null | null |
#pragma once
#include <string>
#include <map>
#include <unordered_map>
#include <vector>
#include <memory>
class Checklist;
class Node {
public:
std::string key {};
std::string value {};
Checklist *sublist {};
Node();
Node(const std::string &key);
Node(const std::string &key, const std::string &val);
bool operator< (const Node &other) const;
bool operator> (const Node &other) const;
bool operator== (const Node &other) const;
bool operator<= (const Node &other) const;
bool operator>= (const Node &other) const;
bool operator!= (const Node &other) const;
};
namespace ChecklistUtil {
class strcomp {
public:
strcomp() {}
bool operator()(const std::string &a, const std::string &b) const {
if (a.length() < b.length()) return true;
if (a.length() > b.length()) return false;
if (a < b) return true;
if (a > b) return false;
return false;
}
};
}
class Checklist : public std::unordered_map<std::string, Node *> {
protected:
std::vector<Node *> ordered_nodes {};
public:
static Checklist *from_file(const std::string &fname);
Checklist &add(std::string &key, Node *node);
void update_order();
Node *operator[] (size_t ind);
};
| 21.796296
| 69
| 0.669499
|
Aerobreaker
|
b108c289612443f1b2eca3906c04a18503b4cff6
| 2,502
|
hpp
|
C++
|
Source/AliveLibAE/Renderer/IRenderer.hpp
|
mouzedrift/alive_reversing
|
be7dfbaed3be99b452459e974bc4e79f9503c178
|
[
"MIT"
] | 208
|
2018-06-06T13:14:03.000Z
|
2022-03-30T02:21:27.000Z
|
Source/AliveLibAE/Renderer/IRenderer.hpp
|
mouzedrift/alive_reversing
|
be7dfbaed3be99b452459e974bc4e79f9503c178
|
[
"MIT"
] | 537
|
2018-06-06T16:50:45.000Z
|
2022-03-31T16:41:15.000Z
|
Source/AliveLibAE/Renderer/IRenderer.hpp
|
mouzedrift/alive_reversing
|
be7dfbaed3be99b452459e974bc4e79f9503c178
|
[
"MIT"
] | 42
|
2018-06-06T00:40:08.000Z
|
2022-03-23T08:38:55.000Z
|
#pragma once
#include "../AliveLibCommon/Sys_common.hpp"
#include "Primitives.hpp"
#include "../AliveLibCommon/Psx_common.hpp"
#include <SDL.h>
struct PrimHeader;
class IRenderer
{
public:
enum class Renderers
{
Software,
DirectX9,
OpenGL,
};
enum class BitDepth
{
e16Bit,
e8Bit,
e4Bit,
};
EXPORT static IRenderer* GetRenderer();
EXPORT static void CreateRenderer(Renderers type);
EXPORT static void FreeRenderer();
struct PalRecord final
{
s16 x = 0;
s16 y = 0;
s16 depth = 0;
};
public:
virtual ~IRenderer()
{ }
virtual void Destroy() = 0;
virtual bool Create(TWindowHandleType window) = 0;
virtual void Clear(u8 r, u8 g, u8 b) = 0;
virtual void StartFrame(s32 xOff, s32 yOff) = 0;
virtual void EndFrame() = 0;
virtual void BltBackBuffer(const SDL_Rect* pCopyRect, const SDL_Rect* pDst) = 0;
virtual void OutputSize(s32* w, s32* h) = 0;
virtual bool UpdateBackBuffer(const void* pPixels, s32 pitch) = 0;
virtual void CreateBackBuffer(bool filter, s32 format, s32 w, s32 h) = 0;
virtual void SetTPage(s16 tPage) = 0;
virtual void SetClip(Prim_PrimClipper& clipper) = 0;
virtual void SetScreenOffset(Prim_ScreenOffset& offset) = 0;
virtual void PalFree(const PalRecord& record) = 0; // Use to free textures/pals via a vram point.
[[nodiscard]] virtual bool PalAlloc(PalRecord& record) = 0;
virtual void PalSetData(const PalRecord& record, const u8* pPixels) = 0;
virtual void Upload(BitDepth bitDepth, const PSX_RECT& rect, const u8* pPixels) = 0;
// FG1/zaplines/blood/hintfly
virtual void Draw(Prim_Sprt& sprt) = 0;
virtual void Draw(Prim_GasEffect& gasEffect) = 0;
// CircularFade/EffectBase
virtual void Draw(Prim_Tile& tile) = 0;
// ThrowableTotal
virtual void Draw(Line_F2& line) = 0;
// AO: Spark/SnoozeParticle, AE: Spark/SnoozeParticle + ThrowableTotal
virtual void Draw(Line_G2& line) = 0;
// SnoozeParticle
virtual void Draw(Line_G4& line) = 0;
// MotionDetector
virtual void Draw(Poly_F3& poly) = 0;
// MainMenuTransistion
virtual void Draw(Poly_G3& poly) = 0;
// PauseMenu, ability ring
virtual void Draw(Poly_F4& poly) = 0;
// FG1, Animation, Font, ScreenWave, Water
virtual void Draw(Poly_FT4& poly) = 0;
// Fleech (tounge), DeathGas, ColourfulMeter
virtual void Draw(Poly_G4& poly) = 0;
};
| 27.195652
| 101
| 0.657074
|
mouzedrift
|
6248383ac011f9aa17f6c6ff58f76bae5ead3d0f
| 2,663
|
cpp
|
C++
|
phenomenon/SceneLoader.cpp
|
Limvot/Phenomenon-Engine
|
3476a45124cf33b80748c488038ca43a23b160dc
|
[
"Zlib",
"MIT"
] | 1
|
2016-05-02T22:00:18.000Z
|
2016-05-02T22:00:18.000Z
|
phenomenon/SceneLoader.cpp
|
Limvot/Phenomenon-Engine
|
3476a45124cf33b80748c488038ca43a23b160dc
|
[
"Zlib",
"MIT"
] | null | null | null |
phenomenon/SceneLoader.cpp
|
Limvot/Phenomenon-Engine
|
3476a45124cf33b80748c488038ca43a23b160dc
|
[
"Zlib",
"MIT"
] | null | null | null |
#include "SceneLoader.h"
namespace phen {
SceneLoader::SceneLoader()
{
}
SceneLoader::~SceneLoader()
{
}
int SceneLoader::loadScene(Scene* scene, std::string file_path)
{
FILE * file = fopen(file_path.c_str(), "r");
if (file == NULL)
{
std::cout << "Could not open the scene file " << file_path << "\n";
return false;
}
char buffer[1024];
std::string loading_obj_file_path;
std::string loading_texture_file_path;
std::string loading_name;
ModelLoader model_loader;
Node* loading_obj_group;
Light* loading_light;
Vector loading_position, loading_rotation, loading_scale;
Color3f loading_ambient, loading_diffuse;
while (1)
{
char lineHeader[1024]; //Assuming words are less than 1024 chars, which is pretty bad
int res = fscanf(file, "%s", lineHeader);
if (res == EOF)
break; //Reached end of file
if (strcmp(lineHeader, "o") == 0) //If its a plain object type
{
fscanf(file, "%s %f/%f/%f %f/%f/%f %f/%f/%f\n", buffer, &loading_position.x, &loading_position.y, &loading_position.z, &loading_rotation.x, &loading_rotation.y, &loading_rotation.z, &loading_scale.x, &loading_scale.y, &loading_scale.z);
loading_obj_file_path = buffer;
model_loader.setScene(scene);
loading_obj_group = model_loader.loadOBJ(loading_obj_file_path, loading_obj_file_path);
loading_obj_group->setLocalPosition(loading_position);
loading_obj_group->setLocalRotation(loading_rotation);
loading_obj_group->setLocalScale(loading_scale);
scene->getRootNode()->addChild(loading_obj_group);
if(loading_obj_group)
std::cout << "Loaded object group from " << loading_obj_file_path << "\n";
loading_obj_group = NULL;
loading_obj_file_path = "";
}
if (strcmp(lineHeader, "l") == 0) //If its a plain object type
{
fscanf(file, "%s %f/%f/%f %f/%f/%f %f/%f/%f\n", buffer, &loading_position.x, &loading_position.y, &loading_position.z, &loading_ambient.r, &loading_ambient.g, &loading_ambient.b, &loading_diffuse.r, &loading_diffuse.g, &loading_diffuse.b);
loading_name = buffer;
loading_light = scene->newLight(loading_name);
loading_light->setLocalPosition(loading_position);
loading_light->setAmbient(loading_ambient);
loading_light->setDiffuse(loading_diffuse);
loading_light = NULL;
}
}
return 0;
}
} //End Namespace
| 32.084337
| 251
| 0.622606
|
Limvot
|
625381d20511f4023aee0620a57a371db92bd936
| 2,147
|
hpp
|
C++
|
source/Container.hpp
|
CyberSys/vaultmp
|
341d62202eb47c5f8795c3b93391fd799c6a4ca8
|
[
"MIT"
] | 67
|
2015-01-08T10:40:31.000Z
|
2022-03-29T21:16:51.000Z
|
source/Container.hpp
|
CyberSys/vaultmp
|
341d62202eb47c5f8795c3b93391fd799c6a4ca8
|
[
"MIT"
] | 20
|
2015-01-05T21:04:05.000Z
|
2018-04-15T11:50:37.000Z
|
source/Container.hpp
|
CyberSys/vaultmp
|
341d62202eb47c5f8795c3b93391fd799c6a4ca8
|
[
"MIT"
] | 60
|
2015-02-17T00:12:11.000Z
|
2021-08-21T22:16:58.000Z
|
#ifndef CONTAINER_H
#define CONTAINER_H
#include "vaultmp.hpp"
#include "Object.hpp"
#include "ItemList.hpp"
#ifdef VAULTMP_DEBUG
#include "Debug.hpp"
#endif
class Container : public Object, public ItemList
{
friend class GameFactory;
private:
#ifdef VAULTMP_DEBUG
static DebugInput<Container> debug;
#endif
void initialize();
Container(const Container&) = delete;
Container& operator=(const Container&) = delete;
protected:
Container(unsigned int refID, unsigned int baseID);
Container(unsigned int baseID) : Container(0x00000000, baseID) {}
Container(const pPacket& packet);
Container(pPacket&& packet) : Container(packet) {};
public:
virtual ~Container() noexcept;
#ifndef VAULTSERVER
/**
* \brief Creates a Parameter containing a VaultFunctor initialized with the given flags
*
* Used to pass Container references matching the provided flags to the Interface
* Can also be used to pass data of a given Container to the Interface
*/
static FuncParameter CreateFunctor(unsigned int flags, RakNet::NetworkID id = 0);
#endif
#ifdef VAULTSERVER
/**
* \brief Sets the Container's base ID
*/
virtual Lockable* SetBase(unsigned int baseID);
#endif
/**
* \brief For network transfer
*/
virtual pPacket toPacket() const;
};
#ifndef VAULTSERVER
class ContainerFunctor : public ObjectFunctor
{
public:
ContainerFunctor(unsigned int flags, RakNet::NetworkID id) : ObjectFunctor(flags, id) {}
virtual ~ContainerFunctor() {}
virtual std::vector<std::string> operator()();
virtual bool filter(FactoryWrapper<Reference>& reference);
};
#endif
GF_TYPE_WRAPPER(Container, Object, ID_CONTAINER, ALL_CONTAINERS)
PF_MAKE(ID_CONTAINER_NEW, pGeneratorReferenceExtend, pPacket)
template<>
inline const typename pTypesMap<pTypes::ID_CONTAINER_NEW>::type* PacketFactory::Cast_<pTypes::ID_CONTAINER_NEW>::Cast(const pPacket* packet) {
pTypes type = packet->type();
return (
type == pTypes::ID_CONTAINER_NEW ||
type == pTypes::ID_ACTOR_NEW ||
type == pTypes::ID_PLAYER_NEW
) ? static_cast<const typename pTypesMap<pTypes::ID_CONTAINER_NEW>::type*>(packet) : nullptr;
}
#endif
| 25.559524
| 142
| 0.7415
|
CyberSys
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.