hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c79023a9fe05d4a6200b4ddc889e4239dc6498e9 | 717 | cpp | C++ | concurrency/call_once.cpp | miaogen123/daily-coding | 5d7f463ad1fee5e512aeb36206526b53b9a781f6 | [
"MIT"
] | 19 | 2018-07-06T06:53:56.000Z | 2022-01-01T16:36:26.000Z | concurrency/call_once.cpp | miaogen123/daily-coding | 5d7f463ad1fee5e512aeb36206526b53b9a781f6 | [
"MIT"
] | null | null | null | concurrency/call_once.cpp | miaogen123/daily-coding | 5d7f463ad1fee5e512aeb36206526b53b9a781f6 | [
"MIT"
] | 17 | 2019-03-27T23:18:43.000Z | 2021-01-18T11:17:57.000Z | #include<iostream>
#include<thread>
#include<mutex>
#include<vector>
#include<string>
using namespace std;
class TestCallOnce
{
public:
TestCallOnce(){}
void init(){
hello=new temp;
std::cout<<"i'm initing\n";
}
int getvi1(){
call_once(IsInitFlag, init, this);
cout<<"1 out "<<hello->vi[1];
return hello->vi[1];
}
int getvi2(){
call_once(IsInitFlag, init, this);
cout<<"2 out "<<hello->vi[0];
return hello->vi[0];
}
private:
class temp{
public:
std::vector<int> vi {100, 10};
};
temp* hello;
std::once_flag IsInitFlag;
};
int main(void)
{
TestCallOnce temp1;
thread t1(TestCallOnce::getvi1, &temp1);
thread t2(TestCallOnce::getvi2,&temp1);
t1.join();
t2.join();
return 0;
}
| 15.933333 | 41 | 0.65272 | miaogen123 |
c79403c084bed9899b2cbdd2441962b0fdf49e2b | 4,172 | cpp | C++ | third-party/Empirical/tests/tools/keyname_utils.cpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | third-party/Empirical/tests/tools/keyname_utils.cpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | third-party/Empirical/tests/tools/keyname_utils.cpp | koellingh/empirical-p53-simulator | aa6232f661e8fc65852ab6d3e809339557af521b | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_MAIN
#include "third-party/Catch/single_include/catch2/catch.hpp"
#include "emp/tools/keyname_utils.hpp"
#include <sstream>
#include <iostream>
#include <string>
TEST_CASE("Test keyname_utils", "[tools]")
{
// test unpack
emp::keyname::unpack_t goal{
{"seed", "100"},
{"foobar", "20"},
{"_hash", "asdf"},
{"ext", ".txt"}
};
std::string name;
name = "seed=100+foobar=20+_hash=asdf+ext=.txt";
goal["_"] = name;
REQUIRE( emp::keyname::unpack(name) == goal );
// reorderings
name = "foobar=20+seed=100+_hash=asdf+ext=.txt";
goal["_"] = name;
REQUIRE( emp::keyname::unpack(name) == goal );
name = "_hash=asdf+foobar=20+seed=100+ext=.txt";
goal["_"] = name;
REQUIRE( emp::keyname::unpack(name) == goal );
// should ignore path
name = "path/seed=100+foobar=20+_hash=asdf+ext=.txt";
goal["_"] = name;
REQUIRE( emp::keyname::unpack(name) == goal );
name = "~/more=path/+blah/seed=100+foobar=20+_hash=asdf+ext=.txt";
goal["_"] = name;
REQUIRE( emp::keyname::unpack(name) == goal );
name = "just/a/regular/file.pdf";
REQUIRE( emp::keyname::unpack(name) == (emp::keyname::unpack_t{
{"file.pdf", ""},
{"_", "just/a/regular/file.pdf"}
}));
name = "key/with/no+=value/file+ext=.pdf";
REQUIRE( emp::keyname::unpack(name) == (emp::keyname::unpack_t{
{"file", ""},
{"ext", ".pdf"},
{"_", "key/with/no+=value/file+ext=.pdf"}
}));
name = "multiple/=s/file=biz=blah+ext=.pdf";
REQUIRE( emp::keyname::unpack(name) == (emp::keyname::unpack_t{
{"file", "biz=blah"},
{"ext", ".pdf"},
{"_", "multiple/=s/file=biz=blah+ext=.pdf"}
}));
// test pack
// reorderings
REQUIRE( (emp::keyname::pack({
{"seed", "100"},
{"foobar", "20"},
{"_hash", "asdf"},
{"ext", ".txt"}
})) == "foobar=20+seed=100+_hash=asdf+ext=.txt"
);
REQUIRE( (emp::keyname::pack({
{"_hash", "asdf"},
{"seed", "100"},
{"foobar", "20"},
{"ext", ".txt"}
})) == "foobar=20+seed=100+_hash=asdf+ext=.txt"
);
REQUIRE( (emp::keyname::pack({
{"_hash", "asdf"},
{"foobar", "20"},
{"ext", ".txt"},
{"seed", "100"}
})) == "foobar=20+seed=100+_hash=asdf+ext=.txt"
);
// different values
REQUIRE( (emp::keyname::pack({
{"seed", "100"},
{"foobar", "blip"},
{"_hash", "asdf"},
{"ext", ".txt"}
})) == "foobar=blip+seed=100+_hash=asdf+ext=.txt"
);
REQUIRE( (emp::keyname::pack({
{"seed", "a100"},
{"foobar", "blip"},
{"_hash", "asdf"},
{"ext", ".txt"}
})) == "foobar=blip+seed=a100+_hash=asdf+ext=.txt"
);
REQUIRE( (emp::keyname::pack({
{"aseed", "a100"},
{"foobar", "blip"},
{"_hash", "asdf"},
{"ext", ".txt"}
})) == "aseed=a100+foobar=blip+_hash=asdf+ext=.txt"
);
// should ignore "_" key
REQUIRE( (emp::keyname::pack({
{"seed", "100"},
{"foobar", "20"},
{"_hash", "asdf"},
{"ext", ".txt"},
{"_", "foobar=20+seed=100+_hash=asdf+ext=.txt"}
})) == "foobar=20+seed=100+_hash=asdf+ext=.txt"
);
REQUIRE( (emp::keyname::pack({
{"seed", "100"},
{"foobar", "20"},
{"_hash", "asdf"},
{"ext", ".txt"},
{"_", "path/seed=100+foobar=20+_hash=asdf+ext=.txt"}
})) == "foobar=20+seed=100+_hash=asdf+ext=.txt"
);
REQUIRE( (emp::keyname::pack({
{"seed", "100"},
{"foobar", "20"},
{"_hash", "asdf"},
{"ext", ".txt"},
{"_", "~/more=path/+blah/seed=100+foobar=20+_hash=asdf+ext=.txt"}
})) == "foobar=20+seed=100+_hash=asdf+ext=.txt"
);
REQUIRE( (emp::keyname::pack({
{"seed", "100"},
{"foobar", "20"},
{"_hash", "asdf"},
{"ext", ".txt"},
{"_", "\"whatever+=/\""}
})) == "foobar=20+seed=100+_hash=asdf+ext=.txt"
);
// missing extension
REQUIRE( (emp::keyname::pack({
{"_hash", "asdf"},
{"foobar", "20"},
{"seed", "100"}
})) == "foobar=20+seed=100+_hash=asdf"
);
}
| 24.397661 | 72 | 0.495686 | koellingh |
c798c9b0820c4864c89849e547a44a61d0b182e0 | 1,655 | hpp | C++ | src/tensorrt/src/core/dataset/tensor_dataset.hpp | tfindlay-au/dlcookbook-dlbs | a4e65f022523a10531817533a4244c3050e9336d | [
"Apache-2.0"
] | null | null | null | src/tensorrt/src/core/dataset/tensor_dataset.hpp | tfindlay-au/dlcookbook-dlbs | a4e65f022523a10531817533a4244c3050e9336d | [
"Apache-2.0"
] | null | null | null | src/tensorrt/src/core/dataset/tensor_dataset.hpp | tfindlay-au/dlcookbook-dlbs | a4e65f022523a10531817533a4244c3050e9336d | [
"Apache-2.0"
] | null | null | null | /*
(c) Copyright [2017] Hewlett Packard Enterprise Development LP
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 "core/dataset/dataset.hpp"
#include "core/logger.hpp"
#ifndef DLBS_TENSORRT_BACKEND_CORE_DATASET_TENSOR_DATASET
#define DLBS_TENSORRT_BACKEND_CORE_DATASET_TENSOR_DATASET
class tensor_dataset : public dataset {
private:
std::vector<std::string> file_names_;
std::vector<std::thread*> prefetchers_;
dataset_opts opts_;
logger_impl& logger_;
private:
static void prefetcher_func(tensor_dataset* myself, const size_t prefetcher_id, const size_t num_prefetchers);
public:
tensor_dataset(const dataset_opts& opts, inference_msg_pool* pool,
abstract_queue<inference_msg*>* request_queue, logger_impl& logger);
void run() override;
static float benchmark(const std::string dir, const size_t batch_size=512, const size_t img_size=227,
const size_t num_prefetches=4, const size_t num_infer_msgs=10,
const int num_warmup_batches=10, const int num_batches=100,
const std::string& dtype="float");
};
#endif
| 38.488372 | 114 | 0.731118 | tfindlay-au |
c7a09c927211c77e9ba3528c5c77d3f11982d0ef | 2,350 | cpp | C++ | cpp/pipe2.cpp | cs1730/cs1730-syscalls | 868047de2a95d2abdcb5d22f34af1e55de8ffe42 | [
"MIT"
] | 1 | 2016-11-05T01:53:05.000Z | 2016-11-05T01:53:05.000Z | cpp/pipe2.cpp | cs1730/cs1730-syscalls | 868047de2a95d2abdcb5d22f34af1e55de8ffe42 | [
"MIT"
] | null | null | null | cpp/pipe2.cpp | cs1730/cs1730-syscalls | 868047de2a95d2abdcb5d22f34af1e55de8ffe42 | [
"MIT"
] | null | null | null |
#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
using namespace std;
void close_pipe(int pipefd [2]);
vector<char *> mk_cstrvec(vector<string> & strvec);
void dl_cstrvec(vector<char *> & cstrvec);
void nice_exec(vector<string> args);
inline void nope_out(const string & sc_name);
int main(const int argc, const char * argv []) {
int pipefd [2];
int pid;
// create pipe
if (pipe(pipefd) == -1) nope_out("pipe");
if ((pid = fork()) == -1) {
nope_out("fork");
} else if (pid == 0) {
vector<string> strargs { "cat", "pipe2.cpp" };
if (dup2(pipefd[1], STDOUT_FILENO) == -1) nope_out("dup2");
close_pipe(pipefd);
nice_exec(strargs);
} // if
if ((pid = fork()) == -1) {
nope_out("fork");
} else if (pid == 0) {
vector<string> strargs { "less" };
if (dup2(pipefd[0], STDIN_FILENO) == -1) nope_out("dup2");
close_pipe(pipefd);
nice_exec(strargs);
} // if
close_pipe(pipefd);
waitpid(pid, nullptr, 0);
return EXIT_SUCCESS;
} // main
void close_pipe(int pipefd [2]) {
if (close(pipefd[0]) == -1) nope_out("close");
if (close(pipefd[1]) == -1) nope_out("close");
} // close_pipe
vector<char *> mk_cstrvec(vector<string> & strvec) {
vector<char *> cstrvec;
for (unsigned int i = 0; i < strvec.size(); ++i) {
cstrvec.push_back(new char [strvec.at(i).size() + 1]);
strcpy(cstrvec.at(i), strvec.at(i).c_str());
} // for
cstrvec.push_back(nullptr);
return cstrvec;
} // mk_cstrvec
void dl_cstrvec(vector<char *> & cstrvec) {
for (unsigned int i = 0; i < cstrvec.size(); ++i) {
delete[] cstrvec.at(i);
} // for
} // dl_cstrvec
void nice_exec(vector<string> strargs) {
vector<char *> cstrargs = mk_cstrvec(strargs);
execvp(cstrargs.at(0), &cstrargs.at(0));
perror("execvp");
dl_cstrvec(cstrargs);
exit(EXIT_FAILURE);
} // nice_exec
/** Prints out the latest errno error and exits the process with EXIT_FAILURE.
* It should be noted that the name of this function is not portable. Most
* persons older than you will NOT understand the name of this function. They
* will be confused. Keep this in mind.
*/
inline void nope_out(const string & sc_name) {
perror(sc_name.c_str());
exit(EXIT_FAILURE);
} // nope_out
| 25.824176 | 78 | 0.64 | cs1730 |
c7a6d631064fc09fc6d9b87ad01167f0329722ff | 119 | cpp | C++ | Source/XeluIcons/Private/XeluIconsLog.cpp | mklabs/ue-xelu-icons | 4aaf54ecb9533fc3689f457b280b79293b861b47 | [
"MIT"
] | 5 | 2022-02-01T22:49:51.000Z | 2022-03-03T10:18:36.000Z | Source/XeluIcons/Private/XeluIconsLog.cpp | mklabs/ue-xelu-icons | 4aaf54ecb9533fc3689f457b280b79293b861b47 | [
"MIT"
] | 1 | 2022-01-31T23:09:04.000Z | 2022-01-31T23:09:04.000Z | Source/XeluIcons/Private/XeluIconsLog.cpp | mklabs/ue-xelu-icons | 4aaf54ecb9533fc3689f457b280b79293b861b47 | [
"MIT"
] | null | null | null | // Copyright 2022 Mickael Daniel. All Rights Reserved.
#include "XeluIconsLog.h"
DEFINE_LOG_CATEGORY(LogXeluIcons)
| 17 | 55 | 0.789916 | mklabs |
c7ab8df954b5e2dd2a4684c9ea99eba630034172 | 632 | hpp | C++ | include/rive/world_transform_component.hpp | kariem2k/rive-cpp | f58c3b3d48ea03947a76971bce17e7f567cf0de0 | [
"MIT"
] | 139 | 2020-08-17T20:10:24.000Z | 2022-03-28T12:22:44.000Z | include/rive/world_transform_component.hpp | kariem2k/rive-cpp | f58c3b3d48ea03947a76971bce17e7f567cf0de0 | [
"MIT"
] | 89 | 2020-08-28T16:41:01.000Z | 2022-03-28T19:10:49.000Z | include/rive/world_transform_component.hpp | kariem2k/rive-cpp | f58c3b3d48ea03947a76971bce17e7f567cf0de0 | [
"MIT"
] | 19 | 2020-10-19T00:54:40.000Z | 2022-02-28T05:34:17.000Z | #ifndef _RIVE_WORLD_TRANSFORM_COMPONENT_HPP_
#define _RIVE_WORLD_TRANSFORM_COMPONENT_HPP_
#include "rive/generated/world_transform_component_base.hpp"
#include "rive/math/mat2d.hpp"
namespace rive
{
class TransformComponent;
class WorldTransformComponent : public WorldTransformComponentBase
{
friend class TransformComponent;
protected:
Mat2D m_WorldTransform;
public:
void markWorldTransformDirty();
virtual float childOpacity();
Mat2D& mutableWorldTransform();
const Mat2D& worldTransform() const;
void worldTranslation(Vec2D& result) const;
void opacityChanged() override;
};
} // namespace rive
#endif | 24.307692 | 67 | 0.803797 | kariem2k |
c7ad4046737db1af7a765380184a7a2030614c9e | 10,143 | hpp | C++ | stf-inc/stf_fstream.hpp | sparcians/stf_lib | 9e4933bff0c956dba464ced72e311e73507342dc | [
"MIT"
] | 1 | 2022-02-17T00:48:44.000Z | 2022-02-17T00:48:44.000Z | stf-inc/stf_fstream.hpp | sparcians/stf_lib | 9e4933bff0c956dba464ced72e311e73507342dc | [
"MIT"
] | null | null | null | stf-inc/stf_fstream.hpp | sparcians/stf_lib | 9e4933bff0c956dba464ced72e311e73507342dc | [
"MIT"
] | null | null | null | #ifndef __STF_FSTREAM_HPP__
#define __STF_FSTREAM_HPP__
#include <ios>
#include <string_view>
#include <fcntl.h>
#include <unistd.h>
#include <sys/stat.h>
#include <mutex>
#include <set>
#include <vector>
#include "stf_exception.hpp"
#include "stf_pc_tracker.hpp"
#include "stf_vlen.hpp"
namespace stf {
/**
* \class STFFstream
*
* Base class that all STF I/O classes inherit from
*/
class STFFstream {
private:
bool used_popen_ = false; /**< Indicates whether we opened the file with an external command */
static std::mutex open_streams_mutex_; /**< Mutex used to ensure atexit handler is thread-safe */
static bool lock_open_streams_; /**< Flag used to indicate whether close() methods should also remove STFFstreams from open_streams_ */
static std::set<STFFstream*> open_streams_; /**< Set containing all streams that need to be closed in the atexit handler */
static bool atexit_handler_registered_; /**< Flag used to indicate whether atexit handler has already been registered */
vlen_t vlen_ = 0; /**< Vector vlen parameter - if 0, the parameter has not been set and
attempting to read/write a vector register record will cause an error */
protected:
FILE* stream_ = nullptr; /**< Underlying file stream */
PCTracker pc_tracker_; /**< Tracks the current and next instruction PC */
size_t num_records_read_ = 0; /**< Number of records seen so far */
size_t num_insts_ = 0; /**< Number of instructions seen so far */
bool has_32bit_events_ = false; /**< If true, EventRecord event values are packed into 32 bits */
STFFstream() = default;
/**
* Checks whether the file extension matches the given extension
* \param filename filename to check
* \param ext extension to check for
*/
static inline bool check_extension_(const std::string_view filename, const std::string_view ext) {
return filename.rfind(ext) != std::string_view::npos;
}
/**
* Popens the given command on the given filename, in read or write mode
* \param cmd command to run
* \param filename filename to run command with
* \param mode read-write mode
*/
static inline FILE* popen_cmd_(const std::string_view cmd, const std::string_view filename, const char* mode) {
std::stringstream ss;
ss << cmd << filename;
return popen(ss.str().c_str(), mode);
}
/**
* Calls fstat() on the stream and returns the result
*/
struct stat getFileStat_() const {
stf_assert(!used_popen_, "Cannot get block size of a stream input.");
stf_assert(stream_, "Attempted to query blocksize without opening a file first.");
struct stat stat_result;
stf_assert(fstat(fileno(stream_), &stat_result) == 0, "Failed to stat file");
return stat_result;
}
/**
* Gets the block size of the filesystem we are reading from
*/
size_t getFSBlockSize_() const {
struct stat stat_result = getFileStat_();
return static_cast<size_t>(stat_result.st_blksize);
}
/**
* atexit handler that cleanly closes all open streams
*/
static void cleanupStreams_();
/**
* Registers this instance with the atexit handler
*/
void registerExitHandler_() {
// Ensuring that open_streams_mutex_, lock_open_streams_, and open_streams_
// are instantiated before we register the atexit handler
std::lock_guard<std::mutex> l(open_streams_mutex_);
lock_open_streams_ = false;
open_streams_.insert(this);
// Register the handler if it hasn't already been registered
if(!atexit_handler_registered_) {
stf_assert(atexit(cleanupStreams_) == 0,
"Failed to register exit handler for STFFstream");
atexit_handler_registered_ = true;
}
}
public:
// Prevents copying any STF I/O objects
STFFstream(const STFFstream&) = delete;
void operator=(const STFFstream&) = delete;
virtual ~STFFstream() {
if (stream_) {
STFFstream::close();
}
}
/**
* Returns whether the stream is valid
*/
explicit virtual operator bool() const {
return stream_;
}
/**
* \brief Open a file using an external process through a pipe
* \param cmd The command to run
* \param filename The filename to run the command with
* \param rw_mode R/W mode
*/
inline void openWithProcess(const std::string_view cmd, const std::string_view filename, const char* rw_mode) {
stream_ = popen_cmd_(cmd, filename, rw_mode);
used_popen_ = true;
stf_assert(stream_, "Failed to run command: " << cmd << ' ' << filename);
registerExitHandler_();
}
/**
* \brief Open a regular file
* \param filename The file to open
* \param rw_mode R/W mode
*/
inline void open(const std::string_view filename, const std::string_view rw_mode) {
// special handling for stdin/stdout
if(filename.compare("-") == 0) {
if(rw_mode.compare("rb") == 0) {
stream_ = stdin;
}
else if(rw_mode.compare("wb") == 0) {
stream_ = stdout;
}
else {
stf_throw("Attempted to open stdin/stdout with invalid mode: " << rw_mode);
}
}
else {
stream_ = fopen (filename.data(), rw_mode.data());
}
used_popen_ = false;
stf_assert(stream_, "Failed to open file: " << filename);
registerExitHandler_();
}
/**
* \brief close the trace reader/writer
*/
virtual int close()
{
int retcode = 0;
if (stream_) {
if(stream_ == stdout) {
fflush(stream_); // need to manually flush stdout
}
else if(stream_ != stdin) { // don't close stdin/stdout
if (used_popen_) {
retcode = pclose (stream_);
}
else if (stream_ != stdout) {
retcode = fclose (stream_);
}
}
stream_ = nullptr;
}
num_records_read_ = 0;
num_insts_ = 0;
// If we aren't closing this from the atexit handler, go ahead and remove ourselves
// from open_streams_
if(!lock_open_streams_) {
std::lock_guard<std::mutex> l(open_streams_mutex_);
open_streams_.erase(this);
}
return retcode;
}
/**
* Gets the current instruction PC
*/
uint64_t getPC() const {
return pc_tracker_.getPC();
}
/**
* Updates the PC tracker with the given record
* \param rec Record to update PC tracker with
*/
template<typename RecordType>
void trackPC(const RecordType& rec) {
pc_tracker_.track(rec);
}
/**
* Callback for all record types - just counts how many records have been read/written
*/
void recordCallback() {
++num_records_read_;
}
/**
* Gets how many records have been read/written
*/
size_t getNumRecords() const {
return num_records_read_;
}
/**
* Callback for instruction opcode record types - just counts how many instruction record groups have been read/written
*/
virtual void instructionRecordCallback() {
// If this was an instruction record, increment the instruction count
++num_insts_;
}
/**
* Gets how many instruction record groups have been read/written
*/
size_t getNumInsts() const {
return num_insts_;
}
/**
* Sets the vlen parameter
* \param vlen Vlen value to set
*/
void setVLen(vlen_t vlen);
/**
* Gets the vlen parameter
*/
vlen_t getVLen() const {
return vlen_;
}
/**
* Returns whether the trace uses 32-bit event records
*/
bool has32BitEvents() const {
return has_32bit_events_;
}
/**
* Sets whether the trace uses 32-bit event records
* \param has_32bit_events If true, the trace to be read/written uses 32-bit event records
*/
void set32BitEvents(const bool has_32bit_events) {
has_32bit_events_ = has_32bit_events;
}
};
} // end namespace stf
#endif
| 37.290441 | 147 | 0.506458 | sparcians |
c7b41672c7d475a0d9a0d7f83066cc93a594382e | 17,506 | cpp | C++ | src/config/ui_preferences_display.cpp | dinfinity/foo_openlyrics | cf42d61ce172f374b76140b5922f7eae1aef33b3 | [
"MIT"
] | 132 | 2021-01-26T11:19:30.000Z | 2022-03-28T09:52:45.000Z | src/config/ui_preferences_display.cpp | dinfinity/foo_openlyrics | cf42d61ce172f374b76140b5922f7eae1aef33b3 | [
"MIT"
] | 108 | 2021-04-08T10:57:27.000Z | 2022-03-27T08:02:15.000Z | src/config/ui_preferences_display.cpp | dinfinity/foo_openlyrics | cf42d61ce172f374b76140b5922f7eae1aef33b3 | [
"MIT"
] | 13 | 2021-08-06T06:21:05.000Z | 2022-03-28T08:19:37.000Z | #include "stdafx.h"
#pragma warning(push, 0)
#include "resource.h"
#include "foobar2000/helpers/atl-misc.h"
#pragma warning(pop)
#include "config/config_auto.h"
#include "config/config_font.h"
#include "logging.h"
#include "preferences.h"
#include "ui_hooks.h"
static const GUID GUID_PREFERENCES_PAGE_DISPLAY = { 0xa31b1608, 0xe77f, 0x4fe5, { 0x80, 0x4b, 0xcf, 0x8c, 0xc8, 0x17, 0xd8, 0x69 } };
static const GUID GUID_CFG_DISPLAY_CUSTOM_FONT = { 0x828be475, 0x8e26, 0x4504, { 0x87, 0x53, 0x22, 0xf5, 0x69, 0xd, 0x53, 0xb7 } };
static const GUID GUID_CFG_DISPLAY_CUSTOM_FOREGROUND_COLOUR = { 0x675418e1, 0xe0b0, 0x4c85, { 0xbf, 0xde, 0x1c, 0x17, 0x9b, 0xbc, 0xca, 0xa7 } };
static const GUID GUID_CFG_DISPLAY_CUSTOM_BACKGROUND_COLOUR = { 0x13da3237, 0xaa1d, 0x4065, { 0x82, 0xb0, 0xe4, 0x3, 0x31, 0xe0, 0x69, 0x5b } };
static const GUID GUID_CFG_DISPLAY_CUSTOM_HIGHLIGHT_COLOUR = { 0xfa2fed99, 0x593c, 0x4828, { 0xbf, 0x7d, 0x95, 0x8e, 0x99, 0x26, 0x9d, 0xcb } };
static const GUID GUID_CFG_DISPLAY_FONT = { 0xc06f95f7, 0x9358, 0x42ab, { 0xb7, 0xa0, 0x19, 0xe6, 0x74, 0x5f, 0xb9, 0x16 } };
static const GUID GUID_CFG_DISPLAY_FOREGROUND_COLOUR = { 0x36724d22, 0xe51e, 0x4c84, { 0x9e, 0xb2, 0x58, 0xa4, 0xd8, 0x23, 0xb3, 0x67 } };
static const GUID GUID_CFG_DISPLAY_BACKGROUND_COLOUR = { 0x7eaeeae6, 0xd41d, 0x4c0d, { 0x97, 0x86, 0x20, 0xa2, 0x8f, 0x27, 0x98, 0xd4 } };
static const GUID GUID_CFG_DISPLAY_HIGHLIGHT_COLOUR = { 0xfa16da6c, 0xb22d, 0x49cb, { 0x97, 0x53, 0x94, 0x8c, 0xec, 0xf8, 0x37, 0x35 } };
static const GUID GUID_CFG_DISPLAY_LINEGAP = { 0x4cc61a5c, 0x58dd, 0x47ce, { 0xa9, 0x35, 0x9, 0xbb, 0xfa, 0xc6, 0x40, 0x43 } };
static const GUID GUID_CFG_DISPLAY_SCROLL_TIME = { 0xc1c7dbf7, 0xd3ce, 0x40dc, { 0x83, 0x29, 0xed, 0xa0, 0xc6, 0xc8, 0xb6, 0x70 } };
static const GUID GUID_CFG_DISPLAY_SCROLL_DIRECTION = { 0x6b1f47ae, 0xa383, 0x434b, { 0xa7, 0xd2, 0x43, 0xbe, 0x55, 0x54, 0x2a, 0x33 } };
static const GUID GUID_CFG_DISPLAY_SCROLL_TYPE = { 0x3f2f17d8, 0x9309, 0x4721, { 0x9f, 0xa7, 0x79, 0x6d, 0x17, 0x84, 0x2a, 0x5d } };
static const COLORREF cfg_display_fg_colour_default = RGB(35,85,125);
static const COLORREF cfg_display_bg_colour_default = RGB(255,255,255);
static const COLORREF cfg_display_hl_colour_default = RGB(225,65,60);
static const cfg_auto_combo_option<LineScrollDirection> g_scroll_direction_options[] =
{
{_T("Vertical"), LineScrollDirection::Vertical},
{_T("Horizontal"), LineScrollDirection::Horizontal},
};
static const cfg_auto_combo_option<LineScrollType> g_scroll_type_options[] =
{
{_T("Automatic"), LineScrollType::Automatic},
{_T("Manual"), LineScrollType::Manual},
};
static cfg_auto_bool cfg_display_custom_font(GUID_CFG_DISPLAY_CUSTOM_FONT, IDC_FONT_CUSTOM, false);
static cfg_auto_bool cfg_display_custom_fg_colour(GUID_CFG_DISPLAY_CUSTOM_FOREGROUND_COLOUR, IDC_FOREGROUND_COLOUR_CUSTOM, false);
static cfg_auto_bool cfg_display_custom_bg_colour(GUID_CFG_DISPLAY_CUSTOM_BACKGROUND_COLOUR, IDC_BACKGROUND_COLOUR_CUSTOM, false);
static cfg_auto_bool cfg_display_custom_hl_colour(GUID_CFG_DISPLAY_CUSTOM_HIGHLIGHT_COLOUR, IDC_HIGHLIGHT_COLOUR_CUSTOM, false);
static cfg_font_t cfg_display_font(GUID_CFG_DISPLAY_FONT);
static cfg_int_t<uint32_t> cfg_display_fg_colour(GUID_CFG_DISPLAY_FOREGROUND_COLOUR, cfg_display_fg_colour_default);
static cfg_int_t<uint32_t> cfg_display_bg_colour(GUID_CFG_DISPLAY_BACKGROUND_COLOUR, cfg_display_bg_colour_default);
static cfg_int_t<uint32_t> cfg_display_hl_colour(GUID_CFG_DISPLAY_HIGHLIGHT_COLOUR, cfg_display_hl_colour_default);
static cfg_auto_int cfg_display_linegap(GUID_CFG_DISPLAY_LINEGAP, IDC_RENDER_LINEGAP_EDIT, 4);
static cfg_auto_ranged_int cfg_display_scroll_time(GUID_CFG_DISPLAY_SCROLL_TIME, IDC_DISPLAY_SCROLL_TIME, 10, 2000, 500);
static cfg_auto_combo<LineScrollDirection, 2> cfg_display_scroll_direction(GUID_CFG_DISPLAY_SCROLL_DIRECTION, IDC_DISPLAY_SCROLL_DIRECTION, LineScrollDirection::Vertical, g_scroll_direction_options);
static cfg_auto_combo<LineScrollType, 2> cfg_display_scroll_type(GUID_CFG_DISPLAY_SCROLL_TYPE, IDC_DISPLAY_SCROLL_TYPE, LineScrollType::Automatic, g_scroll_type_options);
static cfg_auto_property* g_display_auto_properties[] =
{
&cfg_display_custom_font,
&cfg_display_custom_fg_colour,
&cfg_display_custom_bg_colour,
&cfg_display_custom_hl_colour,
&cfg_display_linegap,
&cfg_display_scroll_time,
&cfg_display_scroll_direction,
&cfg_display_scroll_type,
};
//
// Globals
//
static HFONT g_display_font = nullptr;
static COLORREF g_custom_colours[16] = {
RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255),
RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255), RGB(255,255,255),
};
//
// Preference retrieval functions
//
t_ui_font preferences::display::font()
{
if(cfg_display_custom_font.get_value())
{
if(g_display_font == nullptr)
{
LOG_INFO("Creating new display font handle");
g_display_font = CreateFontIndirect(&cfg_display_font.get_value());
}
return g_display_font;
}
return nullptr;
}
std::optional<t_ui_color> preferences::display::foreground_colour()
{
if(cfg_display_custom_fg_colour.get_value())
{
return (COLORREF)cfg_display_fg_colour.get_value();
}
return {};
}
std::optional<t_ui_color> preferences::display::background_colour()
{
if(cfg_display_custom_bg_colour.get_value())
{
return (COLORREF)cfg_display_bg_colour.get_value();
}
return {};
}
std::optional<t_ui_color> preferences::display::highlight_colour()
{
if(cfg_display_custom_hl_colour.get_value())
{
return (COLORREF)cfg_display_hl_colour.get_value();
}
return {};
}
int preferences::display::linegap()
{
return cfg_display_linegap.get_value();
}
double preferences::display::scroll_time_seconds()
{
return ((double)cfg_display_scroll_time.get_value())/1000.0;
}
LineScrollDirection preferences::display::scroll_direction()
{
return cfg_display_scroll_direction.get_value();
}
LineScrollType preferences::display::scroll_type()
{
return cfg_display_scroll_type.get_value();
}
//
// Preference page UI
//
class PreferencesDisplay : public CDialogImpl<PreferencesDisplay>, public auto_preferences_page_instance
{
public:
// Constructor - invoked by preferences_page_impl helpers - don't do Create() in here, preferences_page_impl does this for us
PreferencesDisplay(preferences_page_callback::ptr callback);
~PreferencesDisplay() override;
// Dialog resource ID - Required by WTL/Create()
enum {IDD = IDD_PREFERENCES_DISPLAY};
void apply() override;
void reset() override;
bool has_changed() override;
//WTL message map
BEGIN_MSG_MAP_EX(PreferencesDisplay)
MSG_WM_INITDIALOG(OnInitDialog)
MSG_WM_HSCROLL(OnScrollTimeChange)
COMMAND_HANDLER_EX(IDC_FONT_CUSTOM, BN_CLICKED, OnCustomToggle)
COMMAND_HANDLER_EX(IDC_FOREGROUND_COLOUR_CUSTOM, BN_CLICKED, OnCustomToggle)
COMMAND_HANDLER_EX(IDC_BACKGROUND_COLOUR_CUSTOM, BN_CLICKED, OnCustomToggle)
COMMAND_HANDLER_EX(IDC_HIGHLIGHT_COLOUR_CUSTOM, BN_CLICKED, OnCustomToggle)
COMMAND_HANDLER_EX(IDC_FONT, BN_CLICKED, OnFontChange)
COMMAND_HANDLER_EX(IDC_FOREGROUND_COLOUR, BN_CLICKED, OnFgColourChange)
COMMAND_HANDLER_EX(IDC_BACKGROUND_COLOUR, BN_CLICKED, OnBgColourChange)
COMMAND_HANDLER_EX(IDC_HIGHLIGHT_COLOUR, BN_CLICKED, OnHlColourChange)
COMMAND_HANDLER_EX(IDC_RENDER_LINEGAP_EDIT, EN_CHANGE, OnUIChange)
COMMAND_HANDLER_EX(IDC_DISPLAY_SCROLL_DIRECTION, CBN_SELCHANGE, OnUIChange)
COMMAND_HANDLER_EX(IDC_DISPLAY_SCROLL_TYPE, CBN_SELCHANGE, OnUIChange)
MESSAGE_HANDLER_EX(WM_CTLCOLORBTN, ColourButtonPreDraw)
END_MSG_MAP()
private:
BOOL OnInitDialog(CWindow, LPARAM);
void OnFontChange(UINT, int, CWindow);
void OnFgColourChange(UINT, int, CWindow);
void OnBgColourChange(UINT, int, CWindow);
void OnHlColourChange(UINT, int, CWindow);
void OnCustomToggle(UINT, int, CWindow);
void OnUIChange(UINT, int, CWindow);
void OnScrollTimeChange(int, int, HWND);
LRESULT ColourButtonPreDraw(UINT, WPARAM, LPARAM);
void UpdateFontButtonText();
void SelectBrushColour(HBRUSH& brush);
void RepaintColours();
void UpdateScrollTimePreview();
LOGFONT m_font;
HBRUSH m_brush_foreground;
HBRUSH m_brush_background;
HBRUSH m_brush_highlight;
};
PreferencesDisplay::PreferencesDisplay(preferences_page_callback::ptr callback) :
auto_preferences_page_instance(callback, g_display_auto_properties)
{
m_font = cfg_display_font.get_value();
m_brush_foreground = CreateSolidBrush(cfg_display_fg_colour.get_value());
m_brush_background = CreateSolidBrush(cfg_display_bg_colour.get_value());
m_brush_highlight = CreateSolidBrush(cfg_display_hl_colour.get_value());
}
PreferencesDisplay::~PreferencesDisplay()
{
DeleteObject(m_brush_foreground);
DeleteObject(m_brush_background);
DeleteObject(m_brush_highlight);
}
void PreferencesDisplay::apply()
{
// Reset the global configured font handle so that it can be re-created with the new value
DeleteObject(g_display_font);
g_display_font = nullptr;
cfg_display_font.set_value(m_font);
LOGBRUSH brushes[3] = {};
GetObject(m_brush_foreground, sizeof(brushes[0]), &brushes[0]);
GetObject(m_brush_background, sizeof(brushes[0]), &brushes[1]);
GetObject(m_brush_highlight, sizeof(brushes[0]), &brushes[2]);
cfg_display_fg_colour = brushes[0].lbColor;
cfg_display_bg_colour = brushes[1].lbColor;
cfg_display_hl_colour = brushes[2].lbColor;
auto_preferences_page_instance::apply();
repaint_all_lyric_panels();
}
void PreferencesDisplay::reset()
{
m_font = cfg_display_font.get_value();
DeleteObject(m_brush_foreground);
DeleteObject(m_brush_background);
DeleteObject(m_brush_highlight);
m_brush_foreground = CreateSolidBrush(cfg_display_fg_colour_default);
m_brush_background = CreateSolidBrush(cfg_display_bg_colour_default);
m_brush_highlight = CreateSolidBrush(cfg_display_hl_colour_default);
auto_preferences_page_instance::reset();
UpdateScrollTimePreview();
UpdateFontButtonText();
RepaintColours();
}
bool PreferencesDisplay::has_changed()
{
LOGBRUSH brushes[3] = {};
GetObject(m_brush_foreground, sizeof(brushes[0]), &brushes[0]);
GetObject(m_brush_background, sizeof(brushes[0]), &brushes[1]);
GetObject(m_brush_highlight, sizeof(brushes[0]), &brushes[2]);
bool changed = false;
changed |= !(cfg_display_font == m_font);
changed |= (cfg_display_fg_colour != brushes[0].lbColor);
changed |= (cfg_display_bg_colour != brushes[1].lbColor);
changed |= (cfg_display_hl_colour != brushes[2].lbColor);
return changed || auto_preferences_page_instance::has_changed();
}
BOOL PreferencesDisplay::OnInitDialog(CWindow, LPARAM)
{
init_auto_preferences();
UpdateFontButtonText();
UpdateScrollTimePreview();
RepaintColours();
return FALSE;
}
void PreferencesDisplay::OnFontChange(UINT, int, CWindow)
{
CHOOSEFONT fontOpts = {};
fontOpts.lStructSize = sizeof(fontOpts);
fontOpts.hwndOwner = m_hWnd;
fontOpts.lpLogFont = &m_font;
fontOpts.Flags = CF_FORCEFONTEXIST | CF_INITTOLOGFONTSTRUCT;
fontOpts.nFontType = SCREEN_FONTTYPE;
BOOL font_selected = ChooseFont(&fontOpts);
if(font_selected)
{
UpdateFontButtonText();
on_ui_interaction();
}
on_ui_interaction();
}
void PreferencesDisplay::OnFgColourChange(UINT, int, CWindow)
{
LRESULT custom = SendDlgItemMessage(IDC_FOREGROUND_COLOUR_CUSTOM, BM_GETCHECK, 0, 0);
if(custom == BST_CHECKED)
{
SelectBrushColour(m_brush_foreground);
}
}
void PreferencesDisplay::OnBgColourChange(UINT, int, CWindow)
{
LRESULT custom = SendDlgItemMessage(IDC_BACKGROUND_COLOUR_CUSTOM, BM_GETCHECK, 0, 0);
if(custom == BST_CHECKED)
{
SelectBrushColour(m_brush_background);
}
}
void PreferencesDisplay::OnHlColourChange(UINT, int, CWindow)
{
LRESULT custom = SendDlgItemMessage(IDC_HIGHLIGHT_COLOUR_CUSTOM, BM_GETCHECK, 0, 0);
if(custom == BST_CHECKED)
{
SelectBrushColour(m_brush_highlight);
}
}
void PreferencesDisplay::OnCustomToggle(UINT, int, CWindow)
{
UpdateFontButtonText();
RepaintColours();
on_ui_interaction();
}
void PreferencesDisplay::OnUIChange(UINT, int, CWindow)
{
on_ui_interaction();
}
void PreferencesDisplay::OnScrollTimeChange(int /*request_type*/, int /*new_position*/, HWND source_window)
{
// Docs say this handle will be the scroll bar that sent the message if any, otherwise null.
// Currently the only scroll bar is the setting for synced-line-scroll-time
if(source_window == nullptr) return;
UpdateScrollTimePreview();
on_ui_interaction();
}
LRESULT PreferencesDisplay::ColourButtonPreDraw(UINT, WPARAM, LPARAM lparam)
{
static_assert(sizeof(LRESULT) >= sizeof(HBRUSH));
HWND btn_handle = (HWND)lparam;
int btn_id = ::GetDlgCtrlID(btn_handle);
if(btn_id == IDC_FOREGROUND_COLOUR)
{
LRESULT custom_fg = SendDlgItemMessage(IDC_FOREGROUND_COLOUR_CUSTOM, BM_GETCHECK, 0, 0);
if(custom_fg == BST_CHECKED)
{
return (LRESULT)m_brush_foreground;
}
}
else if(btn_id == IDC_HIGHLIGHT_COLOUR)
{
LRESULT custom_hl = SendDlgItemMessage(IDC_HIGHLIGHT_COLOUR_CUSTOM, BM_GETCHECK, 0, 0);
if(custom_hl == BST_CHECKED)
{
return (LRESULT)m_brush_highlight;
}
}
else if(btn_id == IDC_BACKGROUND_COLOUR)
{
LRESULT custom_bg = SendDlgItemMessage(IDC_BACKGROUND_COLOUR_CUSTOM, BM_GETCHECK, 0, 0);
if(custom_bg == BST_CHECKED)
{
return (LRESULT)m_brush_background;
}
}
return FALSE;
}
void PreferencesDisplay::UpdateFontButtonText()
{
bool custom_font = (SendDlgItemMessage(IDC_FONT_CUSTOM, BM_GETCHECK, 0, 0) == BST_CHECKED);
CWindow font_btn = GetDlgItem(IDC_FONT);
assert(font_btn != nullptr);
font_btn.EnableWindow(custom_font);
HDC dc = GetDC();
int point_size = -MulDiv(m_font.lfHeight, 72, GetDeviceCaps(dc, LOGPIXELSY));
ReleaseDC(dc);
const int point_buffer_len = 32;
TCHAR point_buffer[point_buffer_len];
_sntprintf_s(point_buffer, point_buffer_len, _T(", %dpt"), point_size);
std::tstring font_str;
font_str += m_font.lfFaceName;
font_str += point_buffer;
if(m_font.lfWeight == FW_BOLD)
{
font_str += _T(", Bold");
}
if(m_font.lfItalic)
{
font_str += _T(", Italic");
}
font_btn.SetWindowText(font_str.c_str());
ReleaseDC(dc);
}
void PreferencesDisplay::SelectBrushColour(HBRUSH& handle)
{
LOGBRUSH brush = {};
GetObject(handle, sizeof(LOGBRUSH), &brush);
CHOOSECOLOR colourOpts = {};
colourOpts.lStructSize = sizeof(colourOpts);
colourOpts.hwndOwner = m_hWnd;
colourOpts.rgbResult = brush.lbColor;
colourOpts.lpCustColors = g_custom_colours;
colourOpts.Flags = CC_ANYCOLOR | CC_FULLOPEN | CC_RGBINIT;
BOOL colour_selected = ChooseColor(&colourOpts);
if(colour_selected)
{
DeleteObject(handle);
handle = CreateSolidBrush(colourOpts.rgbResult);
RepaintColours();
on_ui_interaction();
}
}
void PreferencesDisplay::RepaintColours()
{
int ids_to_repaint[] = {
IDC_FOREGROUND_COLOUR,
IDC_BACKGROUND_COLOUR,
IDC_HIGHLIGHT_COLOUR
};
for(int id : ids_to_repaint)
{
CWindow handle = GetDlgItem(id);
if(handle != nullptr)
{
handle.RedrawWindow(nullptr, nullptr, RDW_ERASE | RDW_INVALIDATE | RDW_UPDATENOW);
}
}
}
void PreferencesDisplay::UpdateScrollTimePreview()
{
// We get the position specifically because the value passed in the parameter is sometimes 0
LRESULT value = SendDlgItemMessage(IDC_DISPLAY_SCROLL_TIME, TBM_GETPOS, 0, 0);
const int preview_length = 32;
TCHAR preview[preview_length];
_sntprintf_s(preview, preview_length, _T("%d milliseconds"), value);
SetDlgItemText(IDC_DISPLAY_SCROLL_TIME_PREVIEW, preview);
}
class PreferencesDisplayImpl : public preferences_page_impl<PreferencesDisplay>
{
public:
const char* get_name() final { return "Display"; }
GUID get_guid() final { return GUID_PREFERENCES_PAGE_DISPLAY; }
GUID get_parent_guid() final { return GUID_PREFERENCES_PAGE_ROOT; }
};
static preferences_page_factory_t<PreferencesDisplayImpl> g_preferences_page_display_factory;
| 37.405983 | 200 | 0.711299 | dinfinity |
c7b485395c03893055e1620e229a5b814a8d6cac | 759 | cpp | C++ | Cfiles/sayitahmin.cpp | HilalSolak/Cprojects | e7cec37cbcdbe227c74f1fc35e1c76c9223f3b3d | [
"MIT"
] | null | null | null | Cfiles/sayitahmin.cpp | HilalSolak/Cprojects | e7cec37cbcdbe227c74f1fc35e1c76c9223f3b3d | [
"MIT"
] | null | null | null | Cfiles/sayitahmin.cpp | HilalSolak/Cprojects | e7cec37cbcdbe227c74f1fc35e1c76c9223f3b3d | [
"MIT"
] | null | null | null | #include<stdio.h>
#include<stdlib.h>
void sayitahmin(int sayi){
int tahmin;
printf(" Tahmin Gir:");
scanf("%d",&tahmin);
if(tahmin<sayi){
printf("daha buyuk tahmin yap:");
sayitahmin(sayi);
}
else if(tahmin>sayi){
printf("daha kucuk tahmin yap:");
sayitahmin(sayi);
}
else{
printf("Tebrikler bildiniz");
int cevap;
printf("\ndevam etmek istiyorsaniz 1, istemiyorsaniz -1 girin:");
scanf("%d",&cevap);
if(cevap==1){
sayitahmin(sayi);
}
if(cevap==-1){
printf("----oyundan cikis yapildi----");
}
if(cevap!=1 && cevap!=-1){
printf("hatali giris");
}}}
int main(){
int sayi=56;
sayitahmin(sayi);
return 0;
}
| 21.685714 | 75 | 0.536232 | HilalSolak |
c7b56f1866133878f851dcb11e3f009fdabf90d2 | 17,979 | cpp | C++ | Cube First Phase/cube.cpp | mriddell001/encryption-cube | fd3c8ecd1cffb44bfe0bcfb361165237299cb619 | [
"Apache-2.0"
] | null | null | null | Cube First Phase/cube.cpp | mriddell001/encryption-cube | fd3c8ecd1cffb44bfe0bcfb361165237299cb619 | [
"Apache-2.0"
] | null | null | null | Cube First Phase/cube.cpp | mriddell001/encryption-cube | fd3c8ecd1cffb44bfe0bcfb361165237299cb619 | [
"Apache-2.0"
] | null | null | null | //Cube.cpp
#include "cube.h"
#include <string>
#include <vector>
#include <fstream>
#include <iterator>
#include <iostream>
using namespace std;
/**
* Cube - Initial creation of cube.
*
* Notes: May be impacted by changing load order. Check when project reaches
* applicable phase in development. Current load order: Front, Right, Top,
* Back, Left, Bottom
*
* #################
* # Top #
* # 16 17 18 #
* # 19 $ 20 #
* # 21 22 23 #
* ####################################################
* # Left # Front # Right #
* # 32 33 34 # 0 1 2 # 8 9 10 #
* # 35 $ 36 # 3 $ 4 # 11 $ 12 #
* # 37 38 39 # 5 6 7 # 13 14 15 #
* ####################################################
* # Bottom #
* # 40 41 42 #
* # 43 $ 44 #
* # 45 46 47 #
* #################
* # Back #
* # 31 30 29 #
* # 28 $ 27 #
* # 26 25 24 #
* #################
*
* Debugging: Confirmed data was loaded into bands 2D array.
*/
Cube::Cube() {
init = 1;
int nums[72] = {0, 1, 2, 8, 9, 10, 24, 25, 26, 32, 33, 34, //Band 0
5, 6, 7, 13, 14, 15, 29, 30, 31, 37, 38, 39, //Band 1
0, 3, 5, 40, 43, 45, 31, 28, 26, 16, 19, 21, //Band 2
2, 4, 7, 42, 44, 47, 29, 27, 24, 18, 20, 23, //Band 3
16, 17, 18, 10, 12, 15, 47, 46, 45, 37, 35, 32, //Band 4
21, 22, 23, 8, 11, 13, 42, 41, 40, 39, 36, 34}; //Band 5
int l = 0;
for (int i = 0; i < 48; i++) {
Pip *tmp = new Pip();
pips.push_back(tmp);
}
for (int i = 0; i < 6; i++) {
for (int k = 0; k < 12; k++) {
bands[i][k] = nums[l];
l++;
}
}
}
/**
* initializeCube - function to take input stream and load cube with strings of
* data in the order: Front, Right, Top, Back, Left, Bottom
* @param {fstream} stream - input stream to load cube with data.
*
* Notes: Will be impacted by changing load order. Check when project reaches
* applicable phase in development.
*/
void Cube::initializeCube(fstream& stream) {
char ch;
int index = 0;
while (stream.get(ch)) {
string str = "";
str.push_back(ch);
pips[index]->data += str;
index++;
index = index % 48;
}
if (index != 0) {
while(index != 0) {
pips[index]->data += " ";
index++;
index = index % 48;
}
}
init++;
}
/**
* deconstructCube - function to print cube to output file.
* @param {fstream} stream - output stream to offload cube data.
*
* Notes: Deconstruction cube should also call the destructor for the cube. This
* still needs to be implimented.
*/
void Cube::deconstructCube(fstream& stream) {
print(stream);
}
/**
* transformationStream - accept input file of cube manipulations.
* @param {fstream} stream - input stream of cube transformations.
*/
void Cube::transformationStream(fstream& stream) {
string a = "", b = "", tmp = "";
while (getline(stream, tmp)) {
a += tmp[0];
b += tmp[1];
}
cout << "string a: " << a << "\tstring b: " << b << endl;
transformationDispatch(a, b);
}
/**
* transformationDispatch - function to take string of orders ()
* @param {String} a - string of faces to be opperated on
* @param {String} b - string indication clockwise or counterclockwise.
*/
void Cube::transformationDispatch(string a, string b) {
for (unsigned int i = 0; i < a.size(); i++) {
int x, y;
x = a[i] - '0';
y = b[i] - '0';
switch (x) {
case 0:{ if(y == 0){clockwise(x);} else{counterclockwise(x);} break;}
case 1:{ if(y == 0){clockwise(x);} else{counterclockwise(x);} break;}
case 2:{ if(y == 0){clockwise(x);} else{counterclockwise(x);} break;}
case 3:{ if(y == 0){clockwise(x);} else{counterclockwise(x);} break;}
case 4:{ if(y == 0){clockwise(x);} else{counterclockwise(x);} break;}
case 5:{ if(y == 0){clockwise(x);} else{counterclockwise(x);} break;}
default:
{//If input if formatted correctly, this should never trigger.
ofstream err ("error.txt", ofstream::out);
err << "Error occured in transformationDispatch";
err.close();
break;
}
}
}
}
/**
* clockwise - function that takes an instruction for which face to opperate on
* and it preforms the shifting of the indicators in the clockwise
* direction
* @param {Int} a - numerical indicator of which face to manipulate.
*
* Notes: All cases are complete. Next step is to confirm by testing each case.
* Case 0 is confirmed. Entire function needs reworked with vector instead
* of array.
*/
void Cube::clockwise(int a) {
vector<int> x;
vector<int> y;
switch (a) {
case 0://Top - Back, Right, Front, Left
{//0(0-11) = 0(3-11,0-2)
threeBack(a);
for (int i = 0; i < 3; i++) {//2(11-9) => 4(0-2) && 3(11-9) => 5(0-2)
x.push_back(bands[4][i]);
y.push_back(bands[5][i]);
bands[4][i] = bands[2][11-i];
bands[5][i] = bands[3][11-i];
}
for (int i = 9; i < 12; i++) {//4(0-2) => 3(9-11) && 5(0-2) => 2(9-11)
bands[3][i] = x[i-9];
bands[2][i] = y[i-9];
}
bands[2][0] = bands[a][0];
bands[2][8] = bands[a][8];
bands[3][0] = bands[a][2];
bands[3][8] = bands[a][6];
bands[4][3] = bands[a][5];
bands[4][11] = bands[a][9];
bands[5][3] = bands[a][3];
bands[5][11] = bands[a][11];
break;
}
case 1://Bottom - Front, Right, Back, Left
{//1(0-11) = 1(9-11,0-8)
//Take the last three elements and move them to the front of the array.
threeFront(a);
for (int i = 3; i < 6; i++) {//4(8-6) => 2(3-5) && 5(8-6) => 3(3-5)
x.push_back(bands[2][i]);
y.push_back(bands[3][i]);
bands[2][i] = bands[4][11-i];
bands[3][i] = bands[5][11-i];
}
for (int i = 6; i < 9; i++) {//2(3-5) => 5(6-8) && 3(3-5) => 4(6-8)
bands[5][i] = x[i-6];
bands[4][i] = y[i-6];
}
bands[2][2] = bands[a][0];
bands[2][6] = bands[a][8];
bands[3][2] = bands[a][2];
bands[3][6] = bands[a][6];
bands[4][5] = bands[a][5];
bands[4][9] = bands[a][9];
bands[5][5] = bands[a][3];
bands[5][9] = bands[a][11];
break;
}
case 2://Left - Top, Front, Bottom, Back
{//2(0-11) = 2(9-11,0-8)
//Take the last three elements and move them to the front of the array.
threeFront(a);
for (int i = 9; i < 12; i++) {//5(9-11) => 1(9-11) && 4(9-11) => 0(9-11)
x.push_back(bands[0][i]);
y.push_back(bands[1][i]);
bands[0][i] = bands[4][i];
bands[1][i] = bands[5][i];
}
for (int i = 9; i < 12; i++) {//0(11-9) => 5(9-11) && 3(11-9) => 4(9-11)
bands[5][i] = x[11-i];
bands[4][i] = y[11-i];
}
bands[0][0] = bands[a][0];
bands[0][8] = bands[a][8];
bands[1][0] = bands[a][2];
bands[1][8] = bands[a][6];
bands[4][0] = bands[a][9];
bands[4][8] = bands[a][5];
bands[5][0] = bands[a][11];
bands[5][8] = bands[a][3];
break;
}
case 3://Right - Top, Back, Bottom, Front
{//3(0-11) = 3(3-11,0-2)
threeBack(a);
for (int i = 3; i < 6; i++) {//0(3-5) => 4(3-5) && 1(3-5) => 5(3-5)
x.push_back(bands[0][i]);
y.push_back(bands[1][i]);
bands[0][i] = bands[5][8-i];
bands[1][i] = bands[4][8-i];
}
for (int i = 3; i < 6; i++) {//5(5-3) => 0(3-5) && 4(5-3) => 1(3-5)
bands[4][i] = x[i-3];
bands[5][i] = y[i-3];
}
bands[0][2] = bands[a][0];
bands[0][6] = bands[a][8];
bands[1][2] = bands[a][2];
bands[1][6] = bands[a][6];
bands[4][2] = bands[a][9];
bands[4][6] = bands[a][5];
bands[5][2] = bands[a][11];
bands[5][6] = bands[a][3];
break;
}
case 4://Back - Top, Left, Bottom, Right
{//4(0-11) = 4(3-11,0-2)
threeBack(a);
for (int i = 6; i < 9; i++) {//3(6-8) => 0(6-8) && 2(6-8) => 1(6-8)
x.push_back(bands[0][i]);
y.push_back(bands[1][i]);
bands[0][i] = bands[3][i];
bands[1][i] = bands[2][i];
}
for (int i = 6; i < 9; i++) {//0(6-8) => 2(8-6) && 1(6-8) => 3(8-6)
bands[2][i] = x[8-i];
bands[3][i] = y[8-i];
}
bands[0][5] = bands[a][3];
bands[0][9] = bands[a][11];
bands[1][5] = bands[a][5];
bands[1][9] = bands[a][9];
bands[2][5] = bands[a][8];
bands[2][9] = bands[a][0];
bands[3][5] = bands[a][6];
bands[3][9] = bands[a][2];
break;
}
case 5://Front - Top, Right, Bottom, Left
{//5(0-11) = 5(9-11,0-8)
//Take the last three elements and move them to the front of the array.
threeFront(a);
for (int i = 0; i < 3; i++) {//1(0-2) => 2(0-2) && 0(0-2) => 3(0-2)
x.push_back(bands[2][i]);
y.push_back(bands[3][i]);
bands[2][i] = bands[1][i];
bands[3][i] = bands[0][i];
}
for (int i = 0; i < 3; i++) {//0(11-9) => 5(9-11) && 3(11-9) => 4(9-11)
bands[0][i] = x[2-i];
bands[1][i] = y[2-i];
}
bands[0][3] = bands[a][3];
bands[0][11] = bands[a][11];
bands[1][3] = bands[a][5];
bands[1][11] = bands[a][9];
bands[2][3] = bands[a][8];
bands[2][11] = bands[a][0];
bands[3][3] = bands[a][6];
bands[3][11] = bands[a][2];
break;
}
}
x.erase (x.begin(),x.begin()+3);
y.erase (y.begin(),y.begin()+3);
}
/**
* counterclockwise - function that takes an instruction for which face to
* opperate on and it preforms the shifting of the indicators
* in the counterclockwise direction
* @param {Int} a - numerical indicator of which face to manipulate.
*
* Notes: This function cheats by calling the clockwise function three times.
* This works because the changes are equal.
*/
void Cube::counterclockwise(int a) {clockwise(a); clockwise(a); clockwise(a);}
/**
* threeBack - accepts a band to move three elements to the back of the array.
* @param {Int} a - numerical indicator of which face to manipulate.
*/
void Cube::threeBack(int a) {
vector<int> v;
for (int i = 0; i < 3; i++) {v.push_back(bands[a][i]);}
for (int i = 3; i < 12; i++) {bands[a][i-3] = bands[a][i];}
for (int i = 9; i < 12; i++) {bands[a][i] = v[i-9];}
v.erase (v.begin(),v.begin()+3);
}
/**
* threeFront - accepts a band to move three elements to the front of the array.
* @param {Int} a - numerical indicator of which face to manipulate.
*/
void Cube::threeFront(int a) {
vector<int> v;
for (int i = 9; i < 12; i++) {v.push_back(bands[a][i]);}
for (int i = 8; i > -1; i--) {bands[a][i+3] = bands[a][i];}
for (int i = 0; i < 3; i++) {bands[a][i] = v[i];}
v.erase (v.begin(),v.begin()+3);
}
/**
* print - outputs the data on the cube in the face order that it was entered.
* @param {fstream} stream - output stream to send the data from the cube.
*
* Notes: If the face order is changed then this hard coding will not work. this
* only works in the case where the input order is: Front, Right, Top,
* Back, Left, Bottom.
* #################
* # Top #
* # 16 17 18 #
* # 19 $ 20 #
* # 21 22 23 #
* ####################################################
* # Left # Front # Right #
* # 32 33 34 # 0 1 2 # 8 9 10 #
* # 35 $ 36 # 3 $ 4 # 11 $ 12 #
* # 37 38 39 # 5 6 7 # 13 14 15 #
* ####################################################
* # Bottom #
* # 40 41 42 #
* # 43 $ 44 #
* # 45 46 47 #
* #################
* # Back #
* # 31 30 29 #
* # 28 $ 27 #
* # 26 25 24 #
* #################
*/
void Cube::print(fstream& stream) {
vector<int> v;
//Print faces in order: Front, Right, Top, Back, Left, Bottom
/* Front - band(0): 0, 1, 2 | band(2): 1 | band(3): 1 | band(1): 0, 1, 2 */
v.push_back(bands[0][0]); v.push_back(bands[0][1]); v.push_back(bands[0][2]);
v.push_back(bands[2][1]);
v.push_back(bands[3][1]);
v.push_back(bands[1][0]); v.push_back(bands[1][1]); v.push_back(bands[1][2]);
/* Right - band(0): 3, 4, 5 | band(5): 4 | band(4): 4 | band(1): 3, 4, 5 */
v.push_back(bands[0][3]); v.push_back(bands[0][4]); v.push_back(bands[0][5]);
v.push_back(bands[5][4]);
v.push_back(bands[4][4]);
v.push_back(bands[1][3]); v.push_back(bands[1][4]); v.push_back(bands[1][5]);
/* Top - band(4): 0, 1, 2 | band(2): 10 | band(3): 10 | band(5): 0, 1, 2 */
v.push_back(bands[4][0]); v.push_back(bands[4][1]); v.push_back(bands[4][2]);
v.push_back(bands[2][10]);
v.push_back(bands[3][10]);
v.push_back(bands[5][0]); v.push_back(bands[5][1]); v.push_back(bands[5][2]);
/* Back - band(0): 6, 7, 8 | band(2): 7 | band(3): 7 | band(1): 6, 7, 8 */
v.push_back(bands[0][6]); v.push_back(bands[0][7]); v.push_back(bands[0][8]);
v.push_back(bands[3][7]);
v.push_back(bands[2][7]);
v.push_back(bands[1][6]); v.push_back(bands[1][7]); v.push_back(bands[1][8]);
/* Left - band(0): 9, 10, 11 | band(4): 10 | band(5): 10 | band(1): 9, 10, 11 */
v.push_back(bands[0][9]); v.push_back(bands[0][10]); v.push_back(bands[0][11]);
v.push_back(bands[4][10]);
v.push_back(bands[5][10]);
v.push_back(bands[1][9]); v.push_back(bands[1][10]); v.push_back(bands[1][11]);
/* Bottom - band(5): 8, 7, 6 | band(2): 4 | band(3): 4 | band(4): 8, 7, 6 */
v.push_back(bands[5][8]); v.push_back(bands[5][7]); v.push_back(bands[5][6]);
v.push_back(bands[2][4]);
v.push_back(bands[3][4]);
v.push_back(bands[4][8]); v.push_back(bands[4][7]); v.push_back(bands[4][6]);
int index;
for (auto it = begin(v); it!=end(v); ++it) {
index = *it;
stream << pips[index]->data;
}
v.erase (v.begin(),v.begin()+48);
}
/**
* print - outputs the data on the cube in the face order that it was entered.
* @param {fstream} stream - output stream to send the data from the cube.
*
* Notes: If the face order is changed then this hard coding will not work. this
* only works in the case where the input order is: Front, Right, Top,
* Back, Left, Bottom.
* #################
* # Top #
* # 16 17 18 #
* # 19 $ 20 #
* # 21 22 23 #
* ####################################################
* # Left # Front # Right #
* # 32 33 34 # 0 1 2 # 8 9 10 #
* # 35 $ 36 # 3 $ 4 # 11 $ 12 #
* # 37 38 39 # 5 6 7 # 13 14 15 #
* ####################################################
* # Bottom #
* # 40 41 42 #
* # 43 $ 44 #
* # 45 46 47 #
* #################
* # Back #
* # 31 30 29 #
* # 28 $ 27 #
* # 26 25 24 #
* #################
*/
void Cube::print() {
vector<int> v;
//Print faces in order: Front, Right, Top, Back, Left, Bottom
/* Front - band(0): 0, 1, 2 | band(2): 1 | band(3): 1 | band(1): 0, 1, 2 */
v.push_back(bands[0][0]); v.push_back(bands[0][1]); v.push_back(bands[0][2]);
v.push_back(bands[2][1]);
v.push_back(bands[3][1]);
v.push_back(bands[1][0]); v.push_back(bands[1][1]); v.push_back(bands[1][2]);
/* Right - band(0): 3, 4, 5 | band(5): 4 | band(4): 4 | band(1): 3, 4, 5 */
v.push_back(bands[0][3]); v.push_back(bands[0][4]); v.push_back(bands[0][5]);
v.push_back(bands[5][4]);
v.push_back(bands[4][4]);
v.push_back(bands[1][3]); v.push_back(bands[1][4]); v.push_back(bands[1][5]);
/* Top - band(4): 0, 1, 2 | band(2): 10 | band(3): 10 | band(5): 0, 1, 2 */
v.push_back(bands[4][0]); v.push_back(bands[4][1]); v.push_back(bands[4][2]);
v.push_back(bands[2][10]);
v.push_back(bands[3][10]);
v.push_back(bands[5][0]); v.push_back(bands[5][1]); v.push_back(bands[5][2]);
/* Back - band(0): 6, 7, 8 | band(2): 7 | band(3): 7 | band(1): 6, 7, 8 */
v.push_back(bands[0][6]); v.push_back(bands[0][7]); v.push_back(bands[0][8]);
v.push_back(bands[3][7]);
v.push_back(bands[2][7]);
v.push_back(bands[1][6]); v.push_back(bands[1][7]); v.push_back(bands[1][8]);
/* Left - band(0): 9, 10, 11 | band(4): 10 | band(5): 10 | band(1): 9, 10, 11 */
v.push_back(bands[0][9]); v.push_back(bands[0][10]); v.push_back(bands[0][11]);
v.push_back(bands[4][10]);
v.push_back(bands[5][10]);
v.push_back(bands[1][9]); v.push_back(bands[1][10]); v.push_back(bands[1][11]);
/* Bottom - band(5): 8, 7, 6 | band(2): 4 | band(3): 4 | band(4): 8, 7, 6 */
v.push_back(bands[5][8]); v.push_back(bands[5][7]); v.push_back(bands[5][6]);
v.push_back(bands[2][4]);
v.push_back(bands[3][4]);
v.push_back(bands[4][8]); v.push_back(bands[4][7]); v.push_back(bands[4][6]);
int index;
string str = "";
for (auto it = begin(v); it!=end(v); ++it) {
index = *it;
str += pips[index]->data;
}
cout << str << endl;
v.erase (v.begin(),v.begin()+48);
}
void Cube::print_bands() {
for (int i = 0; i < 6; i++) {
for (int k = 0; k < 12; k++) {
cout << bands[i][k] << "\t";
}
cout << endl;
}
}
| 35.115234 | 81 | 0.47333 | mriddell001 |
c7be54e3819e4ae3845255f7944b014d29338612 | 1,864 | cpp | C++ | utils/files.cpp | Bill2462/calculon | 8caa1b346eae5b1320b2786468ec3caac607d583 | [
"MIT"
] | null | null | null | utils/files.cpp | Bill2462/calculon | 8caa1b346eae5b1320b2786468ec3caac607d583 | [
"MIT"
] | null | null | null | utils/files.cpp | Bill2462/calculon | 8caa1b346eae5b1320b2786468ec3caac607d583 | [
"MIT"
] | null | null | null | /**
* @file files.cpp
* @brief This source file contains code for saving and loading numpy array.
* @author Krzysztof Adamkiewicz
* @date 31/9/2019
*/
// This file is part of measurements laboratory excercise solution.
// Copyright (c) 2019 Krzysztof Adamkiewicz <kadamkiewicz835@gmail.com>
//
// 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 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 "utils.hpp"
#include "cnpy/cnpy.h"
/**
* @brief Load signal from file.
* @param fileName Name of the file.
* @return Vector of data points.
*/
std::vector<double> loadSignal(const std::string& fileName)
{
cnpy::NpyArray arr = cnpy::npy_load(fileName);
double* ptr = arr.data<double>();
return std::vector<double>(ptr, ptr+arr.shape[0]);
}
/**
* @brief Save signal to a file.
* @param signal Vector of signal points.
* @param fileName Name of thw file.
*/
void saveSignal(const std::vector<double>& signal, const std::string& fileName)
{
cnpy::npy_save(fileName, &signal[0], {signal.size()}, "w");
}
| 39.659574 | 88 | 0.73176 | Bill2462 |
c7c5a05817b97764658b2f9ca69b2a485a7699fb | 1,017 | hpp | C++ | src/integrated/IntegratedRunner.hpp | Person-93/aima-cpp | 08d062dcb971edeaddb9a10083cf6da5a1b869f7 | [
"MIT"
] | null | null | null | src/integrated/IntegratedRunner.hpp | Person-93/aima-cpp | 08d062dcb971edeaddb9a10083cf6da5a1b869f7 | [
"MIT"
] | null | null | null | src/integrated/IntegratedRunner.hpp | Person-93/aima-cpp | 08d062dcb971edeaddb9a10083cf6da5a1b869f7 | [
"MIT"
] | null | null | null | #pragma once
#include <vector>
#include <atomic>
#include "forward.hpp"
namespace aima::gui { struct ImGuiWrapper; }
namespace aima::IntegratedRunner {
/**
* Represents an integrated runner that can run apps and demos
*/
class IntegratedRunner {
public:
IntegratedRunner();
IntegratedRunner( const IntegratedRunner& ) = delete;
IntegratedRunner( IntegratedRunner&& ) = delete;
~IntegratedRunner();
IntegratedRunner& operator=( const IntegratedRunner& ) = delete;
IntegratedRunner& operator=( IntegratedRunner&& ) = delete;
/**
* Show the window with the menu bar for running apps and demos
* @param imGuiWrapper
* @param shouldRun
*/
void run( gui::ImGuiWrapper& imGuiWrapper, const std::atomic_bool& shouldRun );
private:
void menuBar( gui::ImGuiWrapper& imGuiWrapper );
std::vector<AppPtr> apps;
std::vector<IntegratedDemoPtr> demos;
};
}
| 24.804878 | 87 | 0.629302 | Person-93 |
c7c73b9ff219087d1cd00a932d0332e83f052dd7 | 7,318 | cpp | C++ | ProcessLib/ComponentTransport/CreateComponentTransportProcess.cpp | hosseinsotudeh/ogs | 214afcb00af23e4393168a846c7ee8ce4f13e489 | [
"BSD-4-Clause"
] | null | null | null | ProcessLib/ComponentTransport/CreateComponentTransportProcess.cpp | hosseinsotudeh/ogs | 214afcb00af23e4393168a846c7ee8ce4f13e489 | [
"BSD-4-Clause"
] | null | null | null | ProcessLib/ComponentTransport/CreateComponentTransportProcess.cpp | hosseinsotudeh/ogs | 214afcb00af23e4393168a846c7ee8ce4f13e489 | [
"BSD-4-Clause"
] | null | null | null | /**
* \copyright
* Copyright (c) 2012-2018, OpenGeoSys Community (http://www.opengeosys.org)
* Distributed under a Modified BSD License.
* See accompanying file LICENSE.txt or
* http://www.opengeosys.org/project/license
*
*/
#include "CreateComponentTransportProcess.h"
#include "MaterialLib/Fluid/FluidProperties/CreateFluidProperties.h"
#include "MaterialLib/PorousMedium/CreatePorousMediaProperties.h"
#include "ProcessLib/Output/CreateSecondaryVariables.h"
#include "ProcessLib/Parameter/ConstantParameter.h"
#include "ProcessLib/Utils/ProcessUtils.h"
#include "ComponentTransportProcess.h"
#include "ComponentTransportProcessData.h"
namespace ProcessLib
{
namespace ComponentTransport
{
std::unique_ptr<Process> createComponentTransportProcess(
MeshLib::Mesh& mesh,
std::unique_ptr<ProcessLib::AbstractJacobianAssembler>&& jacobian_assembler,
std::vector<ProcessVariable> const& variables,
std::vector<std::unique_ptr<ParameterBase>> const& parameters,
unsigned const integration_order,
BaseLib::ConfigTree const& config)
{
//! \ogs_file_param{prj__processes__process__type}
config.checkConfigParameter("type", "ComponentTransport");
DBUG("Create ComponentTransportProcess.");
auto const staggered_scheme =
//! \ogs_file_param{prj__processes__process__ComponentTransport__coupling_scheme}
config.getConfigParameterOptional<std::string>("coupling_scheme");
const bool use_monolithic_scheme =
!(staggered_scheme && (*staggered_scheme == "staggered"));
// Process variable.
//! \ogs_file_param{prj__processes__process__ComponentTransport__process_variables}
auto const pv_config = config.getConfigSubtree("process_variables");
std::vector<std::vector<std::reference_wrapper<ProcessVariable>>>
process_variables;
if (use_monolithic_scheme) // monolithic scheme.
{
auto per_process_variables = findProcessVariables(
variables, pv_config,
{
//! \ogs_file_param_special{prj__processes__process__ComponentTransport__process_variables__concentration}
"concentration",
//! \ogs_file_param_special{prj__processes__process__ComponentTransport__process_variables__pressure}
"pressure"});
process_variables.push_back(std::move(per_process_variables));
}
else // staggered scheme.
{
std::array<std::string, 2> variable_names = {
{"concentration",
"pressure"}}; // double-braces required in C++11 (not in C++14)
for (int i = 0; i < 2; i++)
{
auto per_process_variables =
findProcessVariables(variables, pv_config, {variable_names[i]});
process_variables.push_back(std::move(per_process_variables));
}
}
MaterialLib::PorousMedium::PorousMediaProperties porous_media_properties{
MaterialLib::PorousMedium::createPorousMediaProperties(
mesh, config, parameters)};
//! \ogs_file_param{prj__processes__process__ComponentTransport__fluid}
auto const& fluid_config = config.getConfigSubtree("fluid");
auto fluid_properties =
MaterialLib::Fluid::createFluidProperties(fluid_config);
// Parameter for the density of the fluid.
auto& fluid_reference_density= findParameter<double>(
config,
//! \ogs_file_param_special{prj__processes__process__ComponentTransport__fluid_reference_density}
"fluid_reference_density", parameters, 1);
DBUG("Use \'%s\' as fluid_reference_density parameter.",
fluid_reference_density.name.c_str());
// Parameter for the longitudinal molecular diffusion coefficient.
auto const& molecular_diffusion_coefficient = findParameter<double>(
config,
//! \ogs_file_param_special{prj__processes__process__ComponentTransport__molecular_diffusion_coefficient}
"molecular_diffusion_coefficient", parameters, 1);
DBUG("Use \'%s\' as molecular diffusion coefficient parameter.",
molecular_diffusion_coefficient.name.c_str());
// Parameter for the longitudinal solute dispersivity.
auto const& solute_dispersivity_longitudinal = findParameter<double>(
config,
//! \ogs_file_param_special{prj__processes__process__ComponentTransport__solute_dispersivity_longitudinal}
"solute_dispersivity_longitudinal", parameters, 1);
DBUG("Use \'%s\' as longitudinal solute dispersivity parameter.",
solute_dispersivity_longitudinal.name.c_str());
// Parameter for the transverse solute dispersivity.
auto const& solute_dispersivity_transverse = findParameter<double>(
config,
//! \ogs_file_param_special{prj__processes__process__ComponentTransport__solute_dispersivity_transverse}
"solute_dispersivity_transverse", parameters, 1);
DBUG("Use \'%s\' as transverse solute dispersivity parameter.",
solute_dispersivity_transverse.name.c_str());
// Parameter for the retardation factor.
auto const& retardation_factor =
findParameter<double>(config,
//! \ogs_file_param_special{prj__processes__process__ComponentTransport__retardation_factor}
"retardation_factor", parameters, 1);
// Parameter for the decay rate.
auto const& decay_rate =
findParameter<double>(config,
//! \ogs_file_param_special{prj__processes__process__ComponentTransport__decay_rate}
"decay_rate", parameters, 1);
// Specific body force parameter.
Eigen::VectorXd specific_body_force;
std::vector<double> const b =
//! \ogs_file_param{prj__processes__process__ComponentTransport__specific_body_force}
config.getConfigParameter<std::vector<double>>("specific_body_force");
assert(b.size() > 0 && b.size() < 4);
if (b.size() < mesh.getDimension())
OGS_FATAL(
"specific body force (gravity vector) has %d components, mesh "
"dimension is %d",
b.size(), mesh.getDimension());
bool const has_gravity = MathLib::toVector(b).norm() > 0;
if (has_gravity)
{
specific_body_force.resize(b.size());
std::copy_n(b.data(), b.size(), specific_body_force.data());
}
ComponentTransportProcessData process_data{
std::move(porous_media_properties),
fluid_reference_density,
std::move(fluid_properties),
molecular_diffusion_coefficient,
solute_dispersivity_longitudinal,
solute_dispersivity_transverse,
retardation_factor,
decay_rate,
specific_body_force,
has_gravity};
SecondaryVariableCollection secondary_variables;
NumLib::NamedFunctionCaller named_function_caller(
{"ComponentTransport_concentration_pressure"});
ProcessLib::createSecondaryVariables(config, secondary_variables,
named_function_caller);
return std::make_unique<ComponentTransportProcess>(
mesh, std::move(jacobian_assembler), parameters, integration_order,
std::move(process_variables), std::move(process_data),
std::move(secondary_variables), std::move(named_function_caller),
use_monolithic_scheme);
}
} // namespace ComponentTransport
} // namespace ProcessLib
| 41.344633 | 118 | 0.715633 | hosseinsotudeh |
c7cf7c6d391920a9196732d9aefc37a83e4938ca | 1,559 | cpp | C++ | src/iislua/cluahttpmodule.cpp | shibayan/iislua | b0fe6fb0c204748928b6dd3205d0fe42f899d20c | [
"Apache-2.0"
] | 16 | 2015-10-09T08:03:24.000Z | 2022-03-30T08:54:10.000Z | src/iislua/cluahttpmodule.cpp | shibayan/iislua | b0fe6fb0c204748928b6dd3205d0fe42f899d20c | [
"Apache-2.0"
] | 6 | 2015-09-18T08:12:42.000Z | 2020-04-05T07:00:14.000Z | src/iislua/cluahttpmodule.cpp | shibayan/iislua | b0fe6fb0c204748928b6dd3205d0fe42f899d20c | [
"Apache-2.0"
] | 7 | 2017-09-12T09:53:20.000Z | 2022-02-28T23:50:03.000Z |
#include "stdafx.h"
CLuaHttpModule::CLuaHttpModule(CLuaStatePool* pLuaStatePool)
: L(nullptr), pLuaStatePool(pLuaStatePool)
{
}
CLuaHttpModule::~CLuaHttpModule()
{
if (L != nullptr)
{
pLuaStatePool->Release(L);
L = nullptr;
}
}
REQUEST_NOTIFICATION_STATUS CLuaHttpModule::OnExecuteCore(IN IHttpContext* pHttpContext, IN IHttpEventProvider* pProvider, IN const char* name)
{
if (L == nullptr)
{
L = pLuaStatePool->Acquire(pHttpContext, pProvider);
}
lua_getglobal(L, name);
if (!lua_isfunction(L, -1))
{
lua_pop(L, 1);
return RQ_NOTIFICATION_CONTINUE;
}
if (lua_pcall(L, 0, 1, 0))
{
auto error = lua_tostring(L, -1);
pHttpContext->GetResponse()->SetStatus(500, "Internal Server Error");
return RQ_NOTIFICATION_FINISH_REQUEST;
}
return iislua_finish_request(L);
}
REQUEST_NOTIFICATION_STATUS CLuaHttpModule::OnAsyncCompletion(IN IHttpContext* pHttpContext, IN DWORD dwNotification, IN BOOL fPostNotification, IN IHttpEventProvider* pProvider, IN IHttpCompletionInfo* pCompletionInfo)
{
UNREFERENCED_PARAMETER(pHttpContext);
UNREFERENCED_PARAMETER(dwNotification);
UNREFERENCED_PARAMETER(fPostNotification);
UNREFERENCED_PARAMETER(pProvider);
UNREFERENCED_PARAMETER(pCompletionInfo);
auto storedContext = CLuaHttpStoredContext::GetContext(pHttpContext);
storedContext->GetChildContext()->ReleaseClonedContext();
storedContext->SetChildContext(nullptr);
return RQ_NOTIFICATION_CONTINUE;
} | 25.983333 | 219 | 0.717768 | shibayan |
c7d089ee746f7b991c88b51b978fe3b04a663a31 | 4,775 | cpp | C++ | src/Player.cpp | ScaredStorm/Platformer-Prototype | 6ef4463e6e939f3bf06918150cb07933a40baa83 | [
"MIT"
] | null | null | null | src/Player.cpp | ScaredStorm/Platformer-Prototype | 6ef4463e6e939f3bf06918150cb07933a40baa83 | [
"MIT"
] | null | null | null | src/Player.cpp | ScaredStorm/Platformer-Prototype | 6ef4463e6e939f3bf06918150cb07933a40baa83 | [
"MIT"
] | null | null | null | #include "Player.h"
Player::Player(Level *level, SDL_Texture* sprite, float x, float y, int id)
: Entity(sprite, x, y)
, m_level(level)
{
std::printf("Player position: %fx%f\n", m_x, m_y);
m_leftPressed = false;
m_rightPressed = false;
m_upPressed = false;
m_downPressed = false;
m_onGround = false;
m_xVel = 0;
m_yVel = 0;
m_width = 16;
m_height = 16;
m_playerId = id;
m_dir = 1;
flip = SDL_FLIP_NONE;
}
void Player::update()
{
checkCollision();
m_x += m_xVel;
m_y += m_yVel;
if(!m_onGround)
{
if (m_yVel < 5.0f)
m_yVel += 0.5f;
}
/* PLAYER MOVEMENT */
if(m_rightPressed)
{
m_dir = 1;
m_xVel = 1.0f;
flip = SDL_FLIP_NONE;
}
if(m_leftPressed)
{
m_dir = -1;
m_xVel = -1.0f;
flip = SDL_FLIP_HORIZONTAL;
}
if (!m_rightPressed && !m_leftPressed)
{
m_xVel = 0.0f;
}
if (m_upPressed && m_onGround)
m_yVel = -6.0f;
std::printf("yVel: %f, xVel: %f\n", m_yVel, m_xVel);
}
void Player::setPos(int x, int y)
{
m_x = (float)x;
m_y = (float)y;
}
void Player::handleInput(SDL_Event &e)
{
// Key Pressed
if(e.type == SDL_KEYDOWN)
{
SDL_Keycode k = e.key.keysym.sym;
switch(k)
{
case SDLK_z:
m_upPressed = true;
break;
case SDLK_DOWN:
//m_downPressed = true;
break;
case SDLK_LEFT:
m_leftPressed = true;
break;
case SDLK_RIGHT:
m_rightPressed = true;
break;
}
}
// Key Released
if(e.type == SDL_KEYUP)
{
SDL_Keycode k = e.key.keysym.sym;
switch(k)
{
case SDLK_z:
m_upPressed = false;
break;
case SDLK_DOWN:
//m_downPressed = false;
break;
case SDLK_LEFT:
m_leftPressed = false;
m_xVel = 0.0f;
break;
case SDLK_RIGHT:
m_rightPressed = false;
m_xVel = 0.0f;
break;
}
}
}
void Player::render(SDL_Renderer *renderer)
{
SDL_Rect src;
SDL_Rect dst;
src.x = m_playerId * 16;
src.y = 0;
src.w = dst.w = 16;
src.h = dst.h = 16;
dst.x = m_x;
dst.y = m_y;
SDL_RenderCopyEx(renderer, m_sprite, &src, &dst, 0.0, NULL, flip);
// render weapon
SDL_Rect wsrc;
SDL_Rect wdst;
wsrc.x = m_playerId * 16;
wsrc.y = 32;
wsrc.w = wdst.w = 16;
wsrc.h = wdst.h = 16;
wdst.x = m_x+(3 * m_dir);
wdst.y = m_y;
SDL_RenderCopyEx(renderer, m_sprite, &wsrc, &wdst, 0.0, NULL, flip);
#ifdef _DEBUG
SDL_SetRenderDrawColor(renderer, 255, 0, 0, 255);
SDL_RenderDrawLine(renderer, m_x + 8, m_y + 16, m_x + 8, m_y + 16 + m_yVel);
#endif
}
void Player::checkCollision()
{
int currRow = (int)m_y/m_level->getTileSize();
int currColumn = (int)m_x/m_level->getTileSize();
int xdest, ydest, xtemp, ytemp;
xdest = m_x + m_xVel;
ydest = m_y + m_yVel;
xtemp = m_x;
ytemp = m_y;
calculateCorners(m_x, ydest);
if (m_yVel < 0)
{
if (m_topLeft || m_topRight)
{
m_yVel = 0;
}
}
if (m_yVel > 0)
{
if (m_bottomLeft || m_bottomRight)
{
m_yVel = 0;
m_onGround = true;
}
}
if (!m_bottomLeft && !m_bottomRight)
{
m_onGround = false;
}
else
{
m_onGround = true;
m_yVel = 0;
}
calculateCorners(xdest, m_y);
if(m_xVel > 0)
{
if(m_topRight || m_bottomRight)
{
m_xVel = 0;
//m_x = currColumn * m_level->getTileSize();
}
}
if(m_xVel < 0)
{
if(m_topLeft || m_bottomLeft)
{
m_xVel = 0;
//m_x = currColumn * m_level->getTileSize();
}
}
}
void Player::calculateCorners(float x, float y)
{
int left = (int)(x+2)/m_level->getTileSize();
int right = (int)(x+m_width-2)/m_level->getTileSize();
int top = (int)(y+4)/m_level->getTileSize();
int bottom = (int)(y+m_height-1)/m_level->getTileSize();
bool tl = m_level->canCollide(left, top);
bool tr = m_level->canCollide(right, top);
bool bl = m_level->canCollide(left, bottom);
bool br = m_level->canCollide(right, bottom);
m_topLeft = tl;
m_topRight = tr;
m_bottomLeft = bl;
m_bottomRight = br;
} | 20.76087 | 78 | 0.493613 | ScaredStorm |
c7d3cb0b68196ff15483ee6a770f3849d60111ed | 389 | hpp | C++ | UnsharpMask/Include/ImageFilter/ImageFilter.hpp | cristian-szabo/unsharp-mask-opencl | c760a45ff9af38089ca1fa5cfd99a9f85dc36bff | [
"MIT"
] | 4 | 2017-10-28T08:54:55.000Z | 2020-06-08T12:30:30.000Z | UnsharpMask/Include/ImageFilter/ImageFilter.hpp | cristian-szabo/unsharp-mask-opencl | c760a45ff9af38089ca1fa5cfd99a9f85dc36bff | [
"MIT"
] | null | null | null | UnsharpMask/Include/ImageFilter/ImageFilter.hpp | cristian-szabo/unsharp-mask-opencl | c760a45ff9af38089ca1fa5cfd99a9f85dc36bff | [
"MIT"
] | null | null | null | #pragma once
#include "PPM.hpp"
class ImageProcess;
class UNSHARP_MASK_PUBLIC ImageFilter
{
public:
virtual ~ImageFilter();
protected:
virtual bool onLoad(std::shared_ptr<ImageProcess> proc);
virtual void onBefore(std::uint32_t glTexId);
virtual std::uint64_t onApply(const PPM& image) = 0;
virtual void onAfter();
private:
friend class ImageProcess;
}; | 14.407407 | 60 | 0.714653 | cristian-szabo |
93a573fa04137ea2d7c1bfd9a3b0c52f5275f052 | 1,172 | cpp | C++ | data/dailyCodingProblem546.cpp | vidit1999/daily_coding_problem | b90319cb4ddce11149f54010ba36c4bd6fa0a787 | [
"MIT"
] | 2 | 2020-09-04T20:56:23.000Z | 2021-06-11T07:42:26.000Z | data/dailyCodingProblem546.cpp | vidit1999/daily_coding_problem | b90319cb4ddce11149f54010ba36c4bd6fa0a787 | [
"MIT"
] | null | null | null | data/dailyCodingProblem546.cpp | vidit1999/daily_coding_problem | b90319cb4ddce11149f54010ba36c4bd6fa0a787 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
/*
Given an array of integers, return a new array where each element in
the new array is the number of smaller elements to the right of that element in the original input array.
For example, given the array [3, 4, 9, 6, 1], return [1, 1, 2, 1, 0], since:
There is 1 smaller element to the right of 3
There is 1 smaller element to the right of 4
There are 2 smaller elements to the right of 9
There is 1 smaller element to the right of 6
There are no smaller elements to the right of 1
*/
vector<int> rightSmaller(vector<int> arr){
set<int> s;
vector<int> ans(arr.size());
for(int i=arr.size()-1;i>=0;i--){
auto it = s.insert(arr[i]);
ans[i] = distance(s.begin(), it.first);
}
return ans;
}
void testFunc(vector<vector<int>> v){
for(auto ans : v){
for(int i : rightSmaller(ans))
cout << i << " ";
cout << "\n";
}
}
// main function
int main(){
testFunc({
{12, 1, 2, 3, 0, 11, 4},
{5, 4, 3, 2, 1},
{1, 2, 3, 4, 5},
{12, 10, 5, 4, 2, 20, 6, 1, 0, 2},
{10, 6, 15, 20, 30, 5, 7}
});
return 0;
} | 24.93617 | 105 | 0.574232 | vidit1999 |
93a8f707ae5655d1ac5edefbb732624f9294292b | 1,294 | cpp | C++ | Part 9 - Standard Template Library/Range_finding_pair_and_sets.cpp | rudrajit1729/CPP-Learning-Course | 3c39b2f31b10b5e8dfd3214f924c6d8af021dc94 | [
"MIT"
] | null | null | null | Part 9 - Standard Template Library/Range_finding_pair_and_sets.cpp | rudrajit1729/CPP-Learning-Course | 3c39b2f31b10b5e8dfd3214f924c6d8af021dc94 | [
"MIT"
] | null | null | null | Part 9 - Standard Template Library/Range_finding_pair_and_sets.cpp | rudrajit1729/CPP-Learning-Course | 3c39b2f31b10b5e8dfd3214f924c6d8af021dc94 | [
"MIT"
] | null | null | null | #include<iostream>
#include<set>
#include<algorithm>
using namespace std;
void problem()
{
/*
add([2,3])
add([10,20])
add([30,400])
add([401,450]) - Now given a number output the interval
*/
set<pair<int, int>> S;
// Insert in any random order but it will still be sorted - BST nature
// Pair (a, b) smaller than (c, d) iff (a<c) or (a==c and b<d)
// Insertion takes O(logn)
S.insert({401, 450});
S.insert({2, 3});
S.insert({30, 400});
S.insert({10, 20});
//2,3
//10,20
//30,400
//401,450
//Given no. n we will create pair p {number, INT_MAX} -> Perform upper bound -> Get one index backwards
// If no.present in that interval print yes else no
int point = 13;
auto it = S.upper_bound({point, INT_MAX});
if(it == S.begin())// Corner case - number lower than lowest index
{
cout<<"NOT PRESENT\n";
}
it--; // One step backwards
pair<int, int> current = *it;
// Accessing elements of pair - pair.first , pair.second
if(current.first <= point && point <= current.second)
{
cout<<"PRESENT\t"<<current.first<<" "<<current.second<<endl;
}
else
{
cout<<"NOT PRESENT\n";
}
}
int main()
{
problem();
} | 23.107143 | 108 | 0.553323 | rudrajit1729 |
93abe497a662d8cb28f3edee41c32ddbb680bced | 1,880 | cpp | C++ | test_board/pal_arbiter_test.cpp | rdolbeau/XiBus | 44d7267ff802b54cebda7e0a643a90cff71247e4 | [
"MIT"
] | 3 | 2021-12-11T21:53:57.000Z | 2022-03-29T16:44:51.000Z | test_board/pal_arbiter_test.cpp | rdolbeau/XiBus | 44d7267ff802b54cebda7e0a643a90cff71247e4 | [
"MIT"
] | 1 | 2021-12-06T07:49:41.000Z | 2021-12-07T17:17:37.000Z | test_board/pal_arbiter_test.cpp | rdolbeau/XiBus | 44d7267ff802b54cebda7e0a643a90cff71247e4 | [
"MIT"
] | 1 | 2021-12-11T09:31:00.000Z | 2021-12-11T09:31:00.000Z | #include "PalArbiter.h"
#include "verilated.h"
struct TestCase {
const char* name;
uint8_t ID;
uint8_t ARB_I;
bool GRANT;
};
int main(int argc, char **argv, char **env) {
Verilated::commandArgs(argc, argv);
PalArbiter* arbitera = new PalArbiter;
PalArbiter* arbiterb = new PalArbiter;
arbitera->ARBENA = 0;
arbitera->ID = 0;
arbitera->ARB_I = arbitera->ARB_O;
arbitera->eval();
arbitera->ARBENA = 1;
arbiterb->ARBENA = 0;
arbiterb->ID = 0;
arbiterb->ARB_I = arbiterb->ARB_O;
arbiterb->eval();
arbiterb->ARBENA = 1;
for(uint8_t ida = 0; ida < 16; ida++) {
arbitera->ID = ida;
for(uint8_t idb = 0; idb < 16; idb++) {
if (ida == idb)
continue;
arbiterb->ID = idb;
arbitera->ARB_I = arbitera->ARB_O | arbiterb->ARB_O;
arbiterb->ARB_I = arbitera->ARB_O | arbiterb->ARB_O;
arbitera->eval();
arbiterb->eval();
// because test require ouput signals on input we have to make two steps
// first we produce outputs then second we copy output on input and make
// one more step
arbitera->ARB_I = arbitera->ARB_O | arbiterb->ARB_O;
arbiterb->ARB_I = arbitera->ARB_O | arbiterb->ARB_O;
arbitera->eval();
arbiterb->eval();
bool expected_grant = arbitera->ID > arbiterb->ID;
if (expected_grant != arbitera->GRANT) {
printf(" fail (%01X vs %01X) (expected GRANT=%01X but was %01X) (ARB_I=%01X ARB_Out=%01X)\n",
arbitera->ID,
arbiterb->ID,
expected_grant,
arbitera->GRANT,
arbitera->ARB_I,
arbitera->ARB_O);
}
else {
printf("passed (%01X vs %01X) (ARB_Out=%01X)\n", arbitera->ID, arbiterb->ID, arbitera->ARB_O);
}
}
}
arbitera->final();
arbiterb->final();
delete arbitera;
delete arbiterb;
exit(0);
} | 26.857143 | 102 | 0.592021 | rdolbeau |
93b0a056194e9fa637132278509c8638e439e692 | 8,243 | cpp | C++ | nersis/libstatemodule/luastate.cpp | MoltenPlastic/nersis-love | 4fafd429643c8b546992f5b4a0dca5d4ae5d5427 | [
"MIT"
] | null | null | null | nersis/libstatemodule/luastate.cpp | MoltenPlastic/nersis-love | 4fafd429643c8b546992f5b4a0dca5d4ae5d5427 | [
"MIT"
] | null | null | null | nersis/libstatemodule/luastate.cpp | MoltenPlastic/nersis-love | 4fafd429643c8b546992f5b4a0dca5d4ae5d5427 | [
"MIT"
] | null | null | null | //implementation of a lua state (this file is included in the middle of module.cpp)
class LuaState : public State {
lua_State *L;
int id;
public:
LuaState(lua_State *L, int index);
virtual ~LuaState();
virtual void enter() {
lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */
lua_getfield(L, -1, "enter"); /* func table */
lua_remove(L, -2); /* func */
if (lua_isfunction(L, -1)) {
if (lua_pcall(L, 0, 0, 0) != 0) { /* error */
printf("Error in LuaState: %s\n",lua_tostring(L, -1));
lua_pop(L, 1);
}
} else {
lua_pop(L, 1);
}
};
virtual void leave() {
lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */
lua_getfield(L, -1, "leave"); /* func table */
lua_remove(L, -2); /* func */
if (lua_isfunction(L, -1)) {
if (lua_pcall(L, 0, 0, 0) != 0) { /* error */
printf("Error in LuaState: %s\n",lua_tostring(L, -1));
lua_pop(L, 1);
}
} else {
lua_pop(L, 1);
}
delete this;
};
virtual void suspend() {
lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */
lua_getfield(L, -1, "suspend"); /* func table */
lua_remove(L, -2); /* func */
if (lua_isfunction(L, -1)) {
if (lua_pcall(L, 0, 0, 0) != 0) { /* error */
printf("Error in LuaState: %s\n",lua_tostring(L, -1));
lua_pop(L, 1);
}
} else {
lua_pop(L, 1);
}
};
virtual void resume() {
lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */
lua_getfield(L, -1, "resume"); /* func table */
lua_remove(L, -2); /* func */
if (lua_isfunction(L, -1)) {
if (lua_pcall(L, 0, 0, 0) != 0) { /* error */
printf("Error in LuaState: %s\n",lua_tostring(L, -1));
lua_pop(L, 1);
}
} else {
lua_pop(L, 1);
}
};
virtual void update(double dt) {
lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */
lua_getfield(L, -1, "update"); /* func table */
lua_remove(L, -2); /* func */
if (lua_isfunction(L, -1)) {
lua_pushnumber(L, dt);
if (lua_pcall(L, 1, 0, 0) != 0) { /* error */
printf("Error in LuaState: %s\n",lua_tostring(L, -1));
lua_pop(L, 1);
}
} else {
lua_pop(L, 1);
}
};
virtual void draw() {
lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */
lua_getfield(L, -1, "draw"); /* func table */
lua_remove(L, -2); /* func */
if (lua_isfunction(L, -1)) {
if (lua_pcall(L, 0, 0, 0) != 0) { /* error */
printf("Error in LuaState: %s\n",lua_tostring(L, -1));
lua_pop(L, 1);
}
} else {
lua_pop(L, 1);
}
};
virtual void focus(bool windowFocus) {
lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */
lua_getfield(L, -1, "focus"); /* func table */
lua_remove(L, -2); /* func */
if (lua_isfunction(L, -1)) {
lua_pushboolean(L, windowFocus);
if (lua_pcall(L, 1, 0, 0) != 0) { /* error */
printf("Error in LuaState: %s\n",lua_tostring(L, -1));
lua_pop(L, 1);
}
} else {
lua_pop(L, 1);
}
};
virtual void keyPressed(love::keyboard::Keyboard::Key key, bool isRepeat) {
lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */
lua_getfield(L, -1, "keypressed"); /* func table */
lua_remove(L, -2); /* func */
if (lua_isfunction(L, -1)) {
const char *keystring;
love::keyboard::Keyboard::getConstant(key, keystring);
lua_pushstring(L, keystring);
lua_pushboolean(L, isRepeat);
if (lua_pcall(L, 2, 0, 0) != 0) { /* error */
printf("Error in LuaState: %s\n",lua_tostring(L, -1));
lua_pop(L, 1);
}
} else {
lua_pop(L, 1);
}
};
virtual void keyReleased(love::keyboard::Keyboard::Key key) {
lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */
lua_getfield(L, -1, "keyreleased"); /* func table */
lua_remove(L, -2); /* func */
if (lua_isfunction(L, -1)) {
const char *keystring;
love::keyboard::Keyboard::getConstant(key, keystring);
lua_pushstring(L, keystring);
if (lua_pcall(L, 1, 0, 0) != 0) { /* error */
printf("Error in LuaState: %s\n",lua_tostring(L, -1));
lua_pop(L, 1);
}
} else {
lua_pop(L, 1);
}
};
virtual void mouseFocus(bool mouseFocus) {
lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */
lua_getfield(L, -1, "mousefocus"); /* func table */
lua_remove(L, -2); /* func */
if (lua_isfunction(L, -1)) {
lua_pushboolean(L, mouseFocus);
if (lua_pcall(L, 1, 0, 0) != 0) { /* error */
printf("Error in LuaState: %s\n",lua_tostring(L, -1));
lua_pop(L, 1);
}
} else {
lua_pop(L, 1);
}
};
virtual void mouseMoved(int x, int y, int dx, int dy) {
lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */
lua_getfield(L, -1, "mousemoved"); /* func table */
lua_remove(L, -2); /* func */
if (lua_isfunction(L, -1)) {
lua_pushinteger(L, x);
lua_pushinteger(L, y);
lua_pushinteger(L, dx);
lua_pushinteger(L, dy);
if (lua_pcall(L, 4, 0, 0) != 0) { /* error */
printf("Error in LuaState: %s\n",lua_tostring(L, -1));
lua_pop(L, 1);
}
} else {
lua_pop(L, 1);
}
};
virtual void mousePressed(int x, int y, int button) {
lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */
lua_getfield(L, -1, "mousepressed"); /* func table */
lua_remove(L, -2); /* func */
if (lua_isfunction(L, -1)) {
lua_pushinteger(L, x);
lua_pushinteger(L, y);
lua_pushinteger(L, button);
if (lua_pcall(L, 3, 0, 0) != 0) { /* error */
printf("Error in LuaState: %s\n",lua_tostring(L, -1));
lua_pop(L, 1);
}
} else {
lua_pop(L, 1);
}
};
virtual void mouseReleased(int x, int y, int button) {
lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */
lua_getfield(L, -1, "mousereleased"); /* func table */
lua_remove(L, -2); /* func */
if (lua_isfunction(L, -1)) {
lua_pushinteger(L, x);
lua_pushinteger(L, y);
lua_pushinteger(L, button);
if (lua_pcall(L, 3, 0, 0) != 0) { /* error */
printf("Error in LuaState: %s\n",lua_tostring(L, -1));
lua_pop(L, 1);
}
} else {
lua_pop(L, 1);
}
};
virtual bool quit() {
lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */
lua_getfield(L, -1, "quit"); /* func table */
lua_remove(L, -2); /* func */
if (lua_isfunction(L, -1)) {
if (lua_pcall(L, 0, 1, 0) != 0) { /* error */
printf("Error in LuaState: %s\n",lua_tostring(L, -1));
lua_pop(L, 1);
}
bool q = lua_toboolean(L, -1);
lua_pop(L, 1);
return q;
} else {
lua_pop(L, 1);
}
return false;
};
virtual void resize(int w, int h) {
lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */
lua_getfield(L, -1, "resize"); /* func table */
lua_remove(L, -2); /* func */
if (lua_isfunction(L, -1)) {
lua_pushinteger(L, w);
lua_pushinteger(L, h);
if (lua_pcall(L, 2, 0, 0) != 0) { /* error */
printf("Error in LuaState: %s\n",lua_tostring(L, 1));
lua_pop(L, 1);
}
} else {
lua_pop(L, 1);
}
};
virtual void textInput(std::string text) {
lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */
lua_getfield(L, -1, "textinput"); /* func table */
lua_remove(L, -2); /* func */
if (lua_isfunction(L, -1)) {
lua_pushstring(L, text.c_str());
if (lua_pcall(L, 1, 0, 0) != 0) { /* error */
printf("Error in LuaState: %s\n",lua_tostring(L, 1));
lua_pop(L, 1);
}
} else {
lua_pop(L, 1);
}
};
virtual void threadError(love::thread::LuaThread *thread, std::string error) {
lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */
lua_getfield(L, -1, "threaderror"); /* func table */
lua_remove(L, -2); /* func */
if (lua_isfunction(L, -1)) {
luax_pushtype(L, "Thread", THREAD_THREAD_ID, thread);
lua_pushstring(L, error.c_str());
if (lua_pcall(L, 2, 0, 0) != 0) { /* error */
printf("Error in LuaState: %s\n",lua_tostring(L, 1));
lua_pop(L, 1);
}
} else {
lua_pop(L, 1);
}
};
virtual void visible(bool visibility) {
lua_rawgeti(L, LUA_REGISTRYINDEX, id); /* table */
lua_getfield(L, -1, "visible"); /* func table */
lua_remove(L, -2); /* func */
if (lua_isfunction(L, -1)) {
lua_pushboolean(L, visibility);
if (lua_pcall(L, 1, 0, 0) != 0) { /* error */
printf("Error in LuaState: %s\n",lua_tostring(L, 1));
lua_pop(L, 1);
}
} else {
lua_pop(L, 1);
}
};
virtual void sdlEvent(SDL_Event e) {}; //TODO: SDL_Event wrapper maybe?
};
LuaState::LuaState(lua_State *L, int index) {
this->L = L;
id = luaL_ref(L, LUA_REGISTRYINDEX);
}
LuaState::~LuaState() {
luaL_unref(L, LUA_REGISTRYINDEX, id);
}
| 28.32646 | 83 | 0.581584 | MoltenPlastic |
93b415e4319d7228244f28553e9cb82f858419c6 | 72 | cc | C++ | gcj/apac2016/a/a.cc | stauntonknight/algorithm | 39dbe6dc952ab7db3a469e1ca785003a4660fedb | [
"CNRI-Python"
] | null | null | null | gcj/apac2016/a/a.cc | stauntonknight/algorithm | 39dbe6dc952ab7db3a469e1ca785003a4660fedb | [
"CNRI-Python"
] | null | null | null | gcj/apac2016/a/a.cc | stauntonknight/algorithm | 39dbe6dc952ab7db3a469e1ca785003a4660fedb | [
"CNRI-Python"
] | null | null | null | #include <iostream>
int getNum(int power, int n) {
}
int main() {
}
| 7.2 | 30 | 0.597222 | stauntonknight |
93b906b8c4b078e5be06ce9ccf911b68e15f4c08 | 1,070 | cpp | C++ | lib/AST/ASTNode.cpp | mattapet/dusk-lang | 928b027429a3fd38cece78a89a9619406dcdd9f0 | [
"MIT"
] | 1 | 2022-03-30T22:01:44.000Z | 2022-03-30T22:01:44.000Z | lib/AST/ASTNode.cpp | mattapet/dusk-lang | 928b027429a3fd38cece78a89a9619406dcdd9f0 | [
"MIT"
] | null | null | null | lib/AST/ASTNode.cpp | mattapet/dusk-lang | 928b027429a3fd38cece78a89a9619406dcdd9f0 | [
"MIT"
] | null | null | null | //===--- ASTNode.cpp ------------------------------------------------------===//
//
// dusk-lang
// This source file is part of a dusk-lang project, which is a semestral
// assignement for BI-PJP course at Czech Technical University in Prague.
// The software is provided "AS IS", WITHOUT WARRANTY OF ANY KIND.
//
//===----------------------------------------------------------------------===//
#include "dusk/AST/ASTNode.h"
#include "dusk/AST/ASTContext.h"
#include "dusk/AST/ASTWalker.h"
#include "dusk/AST/Decl.h"
#include "dusk/AST/Expr.h"
#include "dusk/AST/Stmt.h"
using namespace dusk;
void *ASTNode::operator new(size_t Bytes, ASTContext &Context) {
return Context.Allocate(Bytes);
}
bool ASTNode::walk(ASTWalker &Walker) {
if (auto D = dynamic_cast<Decl *>(this))
return D->walk(Walker);
else if (auto E = dynamic_cast<Expr *>(this))
return E->walk(Walker) != nullptr;
else if (auto S = dynamic_cast<Stmt *>(this))
return S->walk(Walker);
else
llvm_unreachable("Unexpected AST node found.");
}
| 28.157895 | 80 | 0.581308 | mattapet |
93bc192e6e56eca126b4254ea8d1436324d903c5 | 2,019 | cpp | C++ | 2021/day10.cpp | mly32/advent-of-code | 8c07ac69b3933403357688efc02f6d4adf1d0592 | [
"BSD-3-Clause"
] | null | null | null | 2021/day10.cpp | mly32/advent-of-code | 8c07ac69b3933403357688efc02f6d4adf1d0592 | [
"BSD-3-Clause"
] | null | null | null | 2021/day10.cpp | mly32/advent-of-code | 8c07ac69b3933403357688efc02f6d4adf1d0592 | [
"BSD-3-Clause"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using ull = unsigned long long;
struct solution {
vector<string> lines;
solution(const string& filename) {
string line;
ifstream input_file(filename);
if (!input_file.is_open()) {
cerr << "Could not open the file - '" << filename << "'" << endl;
return;
}
while (getline(input_file, line)) {
lines.push_back(line);
}
input_file.close();
}
inline bool is_closing(const char c) {
return c == ')' || c == ']' || c == '}' || c == '>';
}
inline bool is_matching(const char b, const char c) {
return (b == '(' && c == ')') || (b == '[' && c == ']') ||
(b == '{' && c == '}') || (b == '<' && c == '>');
}
ull solve() {
const map<char, int> points = {{'(', 1}, {'[', 2}, {'{', 3},
{'<', 4}, {')', 3}, {']', 57},
{'}', 1197}, {'>', 25137}};
ull res = 0;
vector<ull> scores;
for (const string& line : lines) {
ull score_corrupt = 0, score_incomplete = 0;
stack<char> stk;
for (char c : line) {
if (!is_closing(c)) {
stk.push(c);
continue;
}
if (stk.empty()) {
score_corrupt += points.at(c);
break;
} else if (is_matching(stk.top(), c)) {
stk.pop();
} else {
score_corrupt += points.at(c);
break;
}
}
if (score_corrupt == 0) {
while (!stk.empty()) {
score_incomplete = 5 * score_incomplete + points.at(stk.top());
stk.pop();
}
scores.push_back(score_incomplete);
}
res += score_corrupt;
}
sort(scores.begin(), scores.end());
printf("res: %llu, %llu\n", res, scores[scores.size() / 2]);
return res;
}
};
int main() {
const bool final = 1;
const string filename =
"./input/" + string(final ? "final" : "practice") + "/day10.txt";
solution(filename).solve();
}
| 24.621951 | 73 | 0.464091 | mly32 |
93bd5138539c84a381d7e7b0d4b7629b9912ac63 | 447 | hpp | C++ | Engine/Networking/Packets.hpp | artur-kink/nhns | bc1ccef4e4a9cba9047051d73202ee2b1482066f | [
"Apache-2.0"
] | null | null | null | Engine/Networking/Packets.hpp | artur-kink/nhns | bc1ccef4e4a9cba9047051d73202ee2b1482066f | [
"Apache-2.0"
] | null | null | null | Engine/Networking/Packets.hpp | artur-kink/nhns | bc1ccef4e4a9cba9047051d73202ee2b1482066f | [
"Apache-2.0"
] | null | null | null | #ifndef _PACKETS_
#define _PACKETS_
#include <cstring>
#include "Types.hpp"
#include <stdlib.h>
namespace Packet{
//Keep packet structure in alphabetic order
//All packets must be packed.
#pragma pack(push, 1)
/**
* Entity location information from the server.
*/
struct ServerEntityLocation {
uint16_t id;
byte direction;
float x;
float y;
};
#pragma pack(pop)
};
#endif | 16.555556 | 51 | 0.621924 | artur-kink |
93bf27d1fbd5252030c3a7e7683ce4e9b0538823 | 3,047 | cc | C++ | src/player.cc | lxndr/node-gst | 9f2d49ffbdac7cc938b411f57b4cbfc302edb84b | [
"MIT"
] | null | null | null | src/player.cc | lxndr/node-gst | 9f2d49ffbdac7cc938b411f57b4cbfc302edb84b | [
"MIT"
] | null | null | null | src/player.cc | lxndr/node-gst | 9f2d49ffbdac7cc938b411f57b4cbfc302edb84b | [
"MIT"
] | null | null | null | /*
* Copyright 2018 Humanity
*/
#include <vector>
#include <string>
#include "player.h"
static Nan::Persistent<v8::Function> constructor;
v8::Local<v8::Function> Player::Init() {
auto tpl = Nan::New<v8::FunctionTemplate>(New);
tpl->SetClassName(Nan::New("GstPlayer").ToLocalChecked());
tpl->InstanceTemplate()->SetInternalFieldCount(1);
Nan::SetPrototypeMethod(tpl, "play", Play);
Nan::SetPrototypeMethod(tpl, "pause", Pause);
Nan::SetPrototypeMethod(tpl, "stop", Stop);
Nan::SetPrototypeMethod(tpl, "seek", Seek);
Nan::SetPrototypeMethod(tpl, "close", Close);
auto inst = tpl->InstanceTemplate();
Nan::SetAccessor(inst, Nan::New("uri").ToLocalChecked(), UriGetter, UriSetter);
Nan::SetAccessor(inst, Nan::New("duration").ToLocalChecked(), DurationGetter);
Nan::SetAccessor(inst, Nan::New("position").ToLocalChecked(), PositionGetter);
constructor.Reset(tpl->GetFunction());
return tpl->GetFunction();
}
NAN_METHOD(Player::New) {
if (info.IsConstructCall()) {
auto self = new Player();
self->Wrap(info.This());
info.GetReturnValue().Set(info.This());
} else {
Nan::ThrowTypeError("Called as plain function is not permitted");
}
}
Player::Player() {
m_gst_player = gst_player_new(NULL, NULL);
}
Player::~Player() {
OnClose();
}
void Player::OnClose() {
gst_object_unref(m_gst_player);
}
NAN_METHOD(Player::Play) {
auto self = Nan::ObjectWrap::Unwrap<Player>(info.Holder());
gst_player_play(self->m_gst_player);
}
NAN_METHOD(Player::Pause) {
auto self = Nan::ObjectWrap::Unwrap<Player>(info.Holder());
gst_player_pause(self->m_gst_player);
}
NAN_METHOD(Player::Stop) {
auto self = Nan::ObjectWrap::Unwrap<Player>(info.Holder());
gst_player_stop(self->m_gst_player);
}
NAN_METHOD(Player::Seek) {
auto self = Nan::ObjectWrap::Unwrap<Player>(info.Holder());
if (info.Length() < 1) {
Nan::ThrowTypeError("Argument #1 must be a number");
}
auto pos = info[0]->NumberValue();
gst_player_seek(self->m_gst_player, static_cast<GstClockTime>(pos));
}
NAN_METHOD(Player::Close) {
auto self = Nan::ObjectWrap::Unwrap<Player>(info.Holder());
self->OnClose();
}
NAN_GETTER(Player::UriGetter) {
auto self = Nan::ObjectWrap::Unwrap<Player>(info.Holder());
auto uri = gst_player_get_uri(self->m_gst_player);
info.GetReturnValue().Set(Nan::New((const char*) uri).ToLocalChecked());
g_free(uri);
}
NAN_SETTER(Player::UriSetter) {
auto self = Nan::ObjectWrap::Unwrap<Player>(info.Holder());
Nan::Utf8String uri(value->ToString());
gst_player_set_uri(self->m_gst_player, *uri);
info.GetReturnValue().Set(true);
}
NAN_GETTER(Player::DurationGetter) {
auto self = Nan::ObjectWrap::Unwrap<Player>(info.Holder());
auto dur = gst_player_get_duration(self->m_gst_player);
info.GetReturnValue().Set(static_cast<int32_t>(dur));
}
NAN_GETTER(Player::PositionGetter) {
auto self = Nan::ObjectWrap::Unwrap<Player>(info.Holder());
auto pos = gst_player_get_position(self->m_gst_player);
info.GetReturnValue().Set(static_cast<double>(pos));
}
| 27.205357 | 81 | 0.70233 | lxndr |
93c4b43a82bd22e095c5d0b5e1ceed48a21471fb | 2,501 | cpp | C++ | Estructura/plantilla de archivo binario/main.cpp | dkmaster17/DKM | ef22411e57cb37f18b9ddd2305001050855cd137 | [
"MIT"
] | null | null | null | Estructura/plantilla de archivo binario/main.cpp | dkmaster17/DKM | ef22411e57cb37f18b9ddd2305001050855cd137 | [
"MIT"
] | null | null | null | Estructura/plantilla de archivo binario/main.cpp | dkmaster17/DKM | ef22411e57cb37f18b9ddd2305001050855cd137 | [
"MIT"
] | null | null | null | #include "Archivo.h"
class Alumno
{
unsigned int ced;
char nom[30];
public:
Alumno() { ced=0; }
Alumno( char *n, int c ) { ced=c; strcpy(nom,n); }
int get_clave() { return ced; }
char *get_nom() { return nom; }
void set_nom(char *n) { strcpy(nom,n); }
void set_ced(char *n) { ced= atoi(n); }
void imprime() { cout<<ced<<" "<<nom<<endl; }
};
class Materia
{
unsigned int cod;
char tit[80], uc;
public:
Materia( char *n, int c, char v ) { cod=c; strcpy(tit,n); uc=v; }
Materia() { cod=0; }
int get_clave() { return cod; }
char get_uc() { return uc; }
char *get_tit() { return tit; }
void set_tit(char *n) { strcpy(tit,n); }
void set_cod(char *n) { cod= atoi(n); }
void set_uc (char v) { uc=v; }
void imprime() { cout<<cod<<" "<<tit<<" "<<uc<<endl;}
};
class Semestre
{
unsigned int cod;
unsigned int ced;
public:
Semestre ( int v1, int v2 ) { cod=v1; ced=v2; }
Semestre ( ) { }
int get_cod() { return cod; }
int get_ced() { return ced; }
int get_clave(int tipo=0){if(tipo==1){return cod;}else return ced;}
void imprime() { cout<<cod<<" "<<ced<<endl; }
};
int main(int argc, char *argv[])
{
Alumno clabus("",19567987);
Archivo <Alumno> objalu("Datos.dat");
Archivo <Materia> objmat("Materia.dat");
Archivo <Semestre> objsem("Inscritos.dat");
objmat.Abrir(ios::in | ios::binary);
objalu.Abrir(ios::in | ios::binary);
objsem.Abrir(ios::in | ios::binary);
objalu.Imprimir();
if ( objalu.Buscar_Sec(clabus) )
{
cout<<"Alumno encontrado:"<<endl;
clabus.imprime();
Materia clamat("",111,' ');
if ( objmat.Buscar_Sec(clamat) )
{
cout<<"Materia encontrada: ";
clamat.imprime();
}
}
else
cout<<"No se localizo Alumno!"<<endl;
cout<<endl;
objmat.Imprimir();
cout<<endl;
objsem.Imprimir();
objalu.Cerrar();
objmat.Cerrar();
objsem.Cerrar();
system("PAUSE");
return EXIT_SUCCESS;
}
| 31.2625 | 74 | 0.458217 | dkmaster17 |
93c87521b40d86e1102b745d288fd79e5e300ac7 | 194 | cpp | C++ | Challenges/codcad_par_ou_impar.cpp | oJordany/CodCad | d3c76d8631583428f5e32caf79a421f2487dbd4c | [
"MIT"
] | null | null | null | Challenges/codcad_par_ou_impar.cpp | oJordany/CodCad | d3c76d8631583428f5e32caf79a421f2487dbd4c | [
"MIT"
] | 8 | 2021-12-23T13:55:40.000Z | 2022-01-03T18:55:52.000Z | Challenges/codcad_par_ou_impar.cpp | oJordany/CodCad | d3c76d8631583428f5e32caf79a421f2487dbd4c | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main(){
int b, c;
cin >> b >> c;
if ((b+c) % 2 == 0){
cout << "Bino";
}else{
cout << "Cino";
}
return 0;
}
| 12.933333 | 24 | 0.42268 | oJordany |
93cf34a5bb4da518ad3f64c17f1c1dd1937feb37 | 5,000 | cpp | C++ | test/board/board_test.cpp | portatlas/tictactoe-cpp | 2bae6287881f02e8608c5e3cc7d0031724f09dda | [
"MIT"
] | null | null | null | test/board/board_test.cpp | portatlas/tictactoe-cpp | 2bae6287881f02e8608c5e3cc7d0031724f09dda | [
"MIT"
] | null | null | null | test/board/board_test.cpp | portatlas/tictactoe-cpp | 2bae6287881f02e8608c5e3cc7d0031724f09dda | [
"MIT"
] | null | null | null | #define CATCH_CONFIG_MAIN
#include "../../lib/catch.hpp"
#include "../../src/marker.hpp"
#include "../../src/board/board.hpp"
SCENARIO ("Board: Empty Board ", "[empty-board]") {
std::vector<std::string> empty_grid = {" ", " ", " ",
" ", " ", " ",
" ", " ", " "};
GIVEN("Empty Board initialized with a size of 9") {
Board board(9);
WHEN("#getSize is called") {
THEN("return the size of the board") {
REQUIRE(board.getSize() == 9);
}
}
WHEN("#getSlot is called for the first slot") {
THEN("return an empty slot") {
REQUIRE(board.getSlot(1) == " ");
}
}
WHEN("#isSlotEmpty is called for the first slot") {
THEN("return true") {
REQUIRE(board.isSlotEmpty(1) == true);
}
}
WHEN("#countMarker is called for X") {
THEN("return 0") {
REQUIRE(board.countMarker(X) == 0);
}
}
WHEN("#countMarker is called for O") {
THEN("return 0") {
REQUIRE(board.countMarker(O) == 0);
}
}
WHEN("#isGridFull is called") {
THEN("return false") {
REQUIRE(board.isGridFull() == false);
}
}
WHEN("#validSlots is called") {
THEN("return the values from 1 to 9") {
std::vector<int> valid_slots = {1, 2, 3, 4, 5, 6, 7, 8, 9};
REQUIRE(board.validSlots() == valid_slots);
}
}
}
}
SCENARIO("Board: Marked Board", "[marked-board]") {
GIVEN("Marked Board with X on the first slot") {
Board board(9);
board.fillSlot(1, X);
WHEN("#getSlot is called with the first slot") {
THEN("return X since it was placed on the first slot") {
REQUIRE(board.getSlot(1) == X);
}
}
WHEN("#isSlotEmpty is called for the first slot") {
THEN("return false") {
REQUIRE(board.isSlotEmpty(1) == false);
}
}
WHEN("#countMarker is called") {
THEN("return 1") {
REQUIRE(board.countMarker(X) == 1);
}
}
WHEN("#validSlots is called") {
THEN("return a vector with values from 2 to 9") {
std::vector<int> empty_slots = {2, 3, 4, 5, 6, 7, 8, 9};
REQUIRE(board.validSlots() == empty_slots);
}
}
WHEN("#fillSlot is called with 2") {
board.fillSlot(2, O);
AND_WHEN("#getSlot is called on 2") {
THEN("return O") {
REQUIRE(board.getSlot(2) == O);
}
AND_WHEN("#fillSlot is called with 7") {
board.fillSlot(7, X);
THEN("#getSlot on 7 returns X") {
REQUIRE(board.getSlot(7) == X);
}
}
}
}
}
GIVEN("A board initialized with another grid") {
std::vector<std::string> marked_grid = { X , X , X ,
" ", " ", " ",
O , O , " "};
Board active_board(marked_grid);
WHEN("#countMarker is called") {
THEN("return 3 for X") {
REQUIRE(active_board.countMarker(X) == 3);
}
}
WHEN("#countMarker is called") {
THEN("return 2 for O") {
REQUIRE(active_board.countMarker(O) == 2);
}
}
WHEN("#validSlots is called") {
THEN("return the values from 4,5,6,9") {
std::vector<int> valid_slots = {4, 5, 6, 9};
REQUIRE(active_board.validSlots() == valid_slots);
}
}
}
}
SCENARIO("Board: Full board", "[full-board]") {
GIVEN("A full 3x3 board") {
std::vector<std::string> current_board = {X, O, X,
O, X, O,
X, O, X};
Board full_board(current_board);
WHEN("#countMarker is called") {
THEN("return 5 for X") {
REQUIRE(full_board.countMarker(X) == 5);
}
}
WHEN("#countMarker is called") {
THEN("return 4 for O") {
REQUIRE(full_board.countMarker(O) == 4);
}
}
WHEN("#isGridFull is called") {
THEN("return true") {
REQUIRE(full_board.isGridFull() == true);
}
}
WHEN("#validSlots is called") {
THEN("#return an empty vector") {
std::vector<int> empty_slots = {};
REQUIRE(full_board.validSlots() == empty_slots);
}
}
}
}
| 30.487805 | 75 | 0.4278 | portatlas |
93cfd92585dd834d156563d2de55120aebce2403 | 572 | cpp | C++ | Fractal Image Generator/Mandelbrot.cpp | PhantomSabre/Fractal-Image-Generator | 9419be7638ea9e5522c09304af9e20f6cd1e2cb9 | [
"MIT"
] | null | null | null | Fractal Image Generator/Mandelbrot.cpp | PhantomSabre/Fractal-Image-Generator | 9419be7638ea9e5522c09304af9e20f6cd1e2cb9 | [
"MIT"
] | null | null | null | Fractal Image Generator/Mandelbrot.cpp | PhantomSabre/Fractal-Image-Generator | 9419be7638ea9e5522c09304af9e20f6cd1e2cb9 | [
"MIT"
] | null | null | null | #include <complex>
#include "Mandelbrot.h"
namespace frctl
{
Mandelbrot::Mandelbrot() {
}
Mandelbrot::~Mandelbrot()
{}
//Mandelbrot Algorithm here
int Mandelbrot::getIterations(double x, double y)
{
std::complex<double> z = 0;
std::complex<double> c(x, y); //passing in two numbers into this;
int iterations = 0;
while (iterations < MAX_ITERATIONS)
{
z = z*z + c; //Mandelbrot algorithm
if (abs(z) > 2) //catches numbers not in mandelbrot set (nums approaching infinity)
{
break;
}
iterations++;
}
return iterations;
}
} | 15.459459 | 86 | 0.65035 | PhantomSabre |
93d13743765166a697c43974a5dcae7b9a26404a | 581 | cpp | C++ | Part_Five/Net_income.cpp | ayushpareek179/CPP-course | b2b8b8d2dd06cd772e3c9838abd5b841237bb306 | [
"MIT"
] | null | null | null | Part_Five/Net_income.cpp | ayushpareek179/CPP-course | b2b8b8d2dd06cd772e3c9838abd5b841237bb306 | [
"MIT"
] | null | null | null | Part_Five/Net_income.cpp | ayushpareek179/CPP-course | b2b8b8d2dd06cd772e3c9838abd5b841237bb306 | [
"MIT"
] | null | null | null | //To calculate the net income based on an allowance and deduction percentage
#include <iostream>
using namespace std;
int main()
{
float income, net, allowance_percent, deduction_percent;
cout<<"Enter the basic salary, percentage of allowances and percentage of deductions\n";
cin>>income>>allowance_percent>>deduction_percent;
cout<<"For "<<allowance_percent<<"% allowances and "<<deduction_percent<<"% deductions on an income of $"<<income<<",\nNet income = $";
net = income + income*allowance_percent/100 - income*deduction_percent/100;
cout<<net<<endl;
return 0;
}
| 34.176471 | 136 | 0.748709 | ayushpareek179 |
93d4b924650078bb8d2ed5770c5e0d4ad625d61f | 28 | cc | C++ | dev/form-poll/form-poll-srch.cc | chlewey/ilecto-util | a48afc43fb7a355b49d4f9ec4626a7f6dbb32c6c | [
"BSD-3-Clause"
] | null | null | null | dev/form-poll/form-poll-srch.cc | chlewey/ilecto-util | a48afc43fb7a355b49d4f9ec4626a7f6dbb32c6c | [
"BSD-3-Clause"
] | null | null | null | dev/form-poll/form-poll-srch.cc | chlewey/ilecto-util | a48afc43fb7a355b49d4f9ec4626a7f6dbb32c6c | [
"BSD-3-Clause"
] | null | null | null | #include "form-poll-srch.h"
| 14 | 27 | 0.714286 | chlewey |
93e950a39232154d4647947860306ddaa38a4dfa | 332 | cpp | C++ | cards/MalaLapka.cpp | programistagd/TrachOnline | 2acd9ffac0add87fd0f1824ae2b75132933496c7 | [
"MIT"
] | 3 | 2016-06-07T11:55:23.000Z | 2016-06-09T17:17:52.000Z | cards/MalaLapka.cpp | radeusgd/TrachOnline | 2acd9ffac0add87fd0f1824ae2b75132933496c7 | [
"MIT"
] | 25 | 2016-06-13T16:14:18.000Z | 2017-07-29T08:12:23.000Z | cards/MalaLapka.cpp | radeusgd/TrachOnline | 2acd9ffac0add87fd0f1824ae2b75132933496c7 | [
"MIT"
] | null | null | null | #include "cards/MalaLapka.hpp"
using namespace Cards;
string MalaLapka::getName(){
return "mala_lapka";
}
CardPtr MalaLapka::makeNew(){
return make_shared<MalaLapka>();
}
void MalaLapka::reset(){
Feature::reset();
value = 1;
}
void MalaLapka::apply(GameServer::Player& player){
player.handCards -= value;
}
| 15.809524 | 50 | 0.680723 | programistagd |
93eb077ffe00c08369ff5127a26010d2f26ac52d | 670 | cpp | C++ | kittycat/forms/uigetpin.cpp | siilky/catomania | cb3a05cbef523d16b8929b390e190e0cd5924ee9 | [
"MIT"
] | 1 | 2021-02-05T23:20:07.000Z | 2021-02-05T23:20:07.000Z | kittycat/forms/uigetpin.cpp | siilky/catomania | cb3a05cbef523d16b8929b390e190e0cd5924ee9 | [
"MIT"
] | null | null | null | kittycat/forms/uigetpin.cpp | siilky/catomania | cb3a05cbef523d16b8929b390e190e0cd5924ee9 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "ui_getpin.h"
#include "uigetpin.h"
GetPinView::GetPinView(QString email, QString pcName, QWidget *parent)
: QDialog(parent, Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint)
, ui(new Ui::GetPin)
{
ui->setupUi(this);
ui->lbEmail->setText(email);
ui->lbPcName->setText(pcName);
ui->buttonBox->button(QDialogButtonBox::Save)->setEnabled(false);
}
GetPinView::~GetPinView()
{
}
QString GetPinView::pin() const
{
return ui->lePin->text();
}
void GetPinView::on_lePin_textChanged(const QString &text)
{
ui->buttonBox->button(QDialogButtonBox::Save)->setEnabled(!text.isEmpty());
}
| 20.9375 | 96 | 0.702985 | siilky |
93f1b5d463ad5f948dafe4ca4077ebeda6a6f920 | 2,399 | cpp | C++ | Game/Source/Collision.cpp | Omicrxn/Apollo-Mission | 5eec170a9ca9250acfef27c81cc16c4608a78f9f | [
"MIT"
] | null | null | null | Game/Source/Collision.cpp | Omicrxn/Apollo-Mission | 5eec170a9ca9250acfef27c81cc16c4608a78f9f | [
"MIT"
] | null | null | null | Game/Source/Collision.cpp | Omicrxn/Apollo-Mission | 5eec170a9ca9250acfef27c81cc16c4608a78f9f | [
"MIT"
] | null | null | null | #include "Collision.h"
RectCollision::RectCollision(SDL_Rect collider, Module* listener) {
this->collider = collider;
this->listener = listener;
}
bool RectCollision::Intersects(SDL_Rect& colliderB) {
return (collider.x < (colliderB.x + colliderB.w) &&
(collider.x + collider.w) > colliderB.x &&
collider.y < (colliderB.y + colliderB.h) &&
(collider.y + collider.h) > colliderB.y);
}
bool RectCollision::Intersects(CircleCollider& colliderB) {
iPoint closestPoint = { 0,0 };
if (colliderB.position.x < collider.x)
{
closestPoint.x = collider.x;
}
else if (colliderB.position.x > collider.x + collider.w)
{
closestPoint.x = collider.x + collider.w;
}
else
{
closestPoint.x = colliderB.position.x;
}
if (colliderB.position.y < collider.y)
{
closestPoint.y = collider.y;
}
else if (colliderB.position.y > collider.y + collider.h)
{
closestPoint.y = collider.y + collider.h;
}
else
{
closestPoint.y = colliderB.position.y;
}
iPoint colliderAPos = { collider.x,collider.y };
int distance = colliderAPos.DistanceTo(closestPoint);
if (distance < colliderB.radius) {
return true;
}
return false;
}
void RectCollision::SetPosition(Vec2f position) {
this->collider.x = position.x;
this->collider.y = position.y;
}
CircleCollision::CircleCollision(float x, float y, float radius, Module* listener) {
this->collider.position.x = x;
this->collider.position.y = y;
this->collider.radius = radius;
this->listener = listener;
}
bool CircleCollision::Intersects(CircleCollider& colliderB) {
return this->collider.position.DistanceTo(colliderB.position) < (this->collider.radius + colliderB.radius);
}
bool CircleCollision::Intersects(SDL_Rect& colliderB) {
iPoint closestPoint = { 0,0 };
if ( this->collider.position.x < colliderB.x)
{
closestPoint.x = colliderB.x;
}
else if (this->collider.position.x > colliderB.x + colliderB.w)
{
closestPoint.x = colliderB.x + colliderB.w;
}
else
{
closestPoint.x = this->collider.position.x;
}
if (this->collider.position.y< colliderB.y)
{
closestPoint.y = colliderB.y;
}
else if (this->collider.position.y > colliderB.y + colliderB.h)
{
closestPoint.y = colliderB.y + colliderB.h;
}
else
{
closestPoint.y = this->collider.position.y;
}
int distance = this->collider.position.DistanceTo(closestPoint);
if (distance < this->collider.radius) {
return true;
}
return false;
}
| 23.291262 | 108 | 0.702793 | Omicrxn |
93f21977ed594d80eebd5ff4c14837e74471695c | 2,064 | cpp | C++ | sources/Engine/Modules/Graphics/GraphicsSystem/Camera.cpp | n-paukov/swengine | ca7441f238e8834efff5d2b61b079627824bf3e4 | [
"MIT"
] | 22 | 2017-07-26T17:42:56.000Z | 2022-03-21T22:12:52.000Z | sources/Engine/Modules/Graphics/GraphicsSystem/Camera.cpp | n-paukov/swengine | ca7441f238e8834efff5d2b61b079627824bf3e4 | [
"MIT"
] | 50 | 2017-08-02T19:37:48.000Z | 2020-07-24T21:10:38.000Z | sources/Engine/Modules/Graphics/GraphicsSystem/Camera.cpp | n-paukov/swengine | ca7441f238e8834efff5d2b61b079627824bf3e4 | [
"MIT"
] | 4 | 2018-08-20T08:12:48.000Z | 2020-07-19T14:10:05.000Z | #include "precompiled.h"
#pragma hdrstop
#include "Camera.h"
Camera::Camera()
: m_transform(new Transform())
{
}
Camera::~Camera()
{
}
Transform* Camera::getTransform() const
{
return m_transform.get();
}
const Frustum& Camera::getFrustum()
{
if (m_needFrustumUpdate || m_transform->isCacheOutdated()) {
m_frustum = Frustum::extractFromViewProjection(getViewMatrix(), getProjectionMatrix());
m_needFrustumUpdate = false;
}
return m_frustum;
}
void Camera::setAspectRatio(float ratio)
{
m_aspectRatio = ratio;
resetProjectionCache();
}
float Camera::getAspectRatio() const
{
return m_aspectRatio;
}
void Camera::setNearClipDistance(float distance)
{
m_nearClipDistance = distance;
resetProjectionCache();
}
float Camera::getNearClipDistance() const
{
return m_nearClipDistance;
}
void Camera::setFarClipDistance(float distance)
{
m_farClipDistance = distance;
resetProjectionCache();
}
float Camera::getFarClipDistance() const
{
return m_farClipDistance;
}
void Camera::setFOVy(float fov)
{
m_FOVy = fov;
resetProjectionCache();
}
float Camera::getFOVy() const
{
return m_FOVy;
}
#include <boost/stacktrace.hpp>
#include <boost/exception/error_info.hpp>
glm::mat4x4 Camera::getProjectionMatrix()
{
if (m_needProjectionMatrixCacheUpdate) {
m_projectionMatrixCache = glm::perspective(m_FOVy, m_aspectRatio, m_nearClipDistance, m_farClipDistance);
m_needFrustumUpdate = true;
m_needProjectionMatrixCacheUpdate = false;
}
return m_projectionMatrixCache;
}
glm::mat4x4 Camera::getViewMatrix()
{
if (m_transform->isCacheOutdated()) {
m_viewMatrixCache = glm::lookAt(m_transform->getPosition(),
m_transform->getPosition() + m_transform->getFrontDirection(),
m_transform->getUpDirection());
// Trigger transformation cache update
(void)m_transform->getTransformationMatrix();
m_needFrustumUpdate = true;
}
return m_viewMatrixCache;
}
void Camera::resetProjectionCache()
{
m_needProjectionMatrixCacheUpdate = true;
m_needFrustumUpdate = true;
}
| 17.491525 | 109 | 0.739341 | n-paukov |
93f2f04242d771dd7a604be5f80dadc16ea0037b | 1,630 | hpp | C++ | src/wrappers/glfw/Exception.hpp | JoaoBaptMG/INF443-Project | 8c43007a8092931b125cc7feae2adf162e04534e | [
"MIT"
] | 8 | 2020-06-09T00:43:39.000Z | 2021-09-27T13:55:46.000Z | src/wrappers/glfw/Exception.hpp | JoaoBaptMG/INF584-Project | a9cf6d4e7d32eb62e7b20fe465c9e75989cca6ac | [
"MIT"
] | 1 | 2020-06-09T02:38:55.000Z | 2020-06-09T13:28:13.000Z | src/wrappers/glfw/Exception.hpp | JoaoBaptMG/INF584-Project | a9cf6d4e7d32eb62e7b20fe465c9e75989cca6ac | [
"MIT"
] | 3 | 2020-06-09T00:28:11.000Z | 2020-12-30T08:07:34.000Z | #pragma once
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <stdexcept>
namespace glfw
{
class Exception : public std::runtime_error
{
public:
Exception(const char* what) : runtime_error(what) {}
};
#define EXCEPTION_CLASS(name) class name final : public Exception \
{\
public:\
name(const char* what) : Exception(what) {}\
}
EXCEPTION_CLASS(NotInitialized);
EXCEPTION_CLASS(NoCurrentContext);
EXCEPTION_CLASS(InvalidEnum);
EXCEPTION_CLASS(InvalidValue);
EXCEPTION_CLASS(OutOfMemory);
EXCEPTION_CLASS(ApiUnavailable);
EXCEPTION_CLASS(VersionUnavailable);
EXCEPTION_CLASS(PlatformError);
EXCEPTION_CLASS(FormatUnavailable);
EXCEPTION_CLASS(NoWindowContext);
#undef EXCEPTION_CLASS
inline static void checkError(int code, const char* desc)
{
switch (code)
{
case GLFW_NOT_INITIALIZED: throw NotInitialized(desc);
case GLFW_NO_CURRENT_CONTEXT: throw NoCurrentContext(desc);
case GLFW_INVALID_ENUM: throw InvalidEnum(desc);
case GLFW_INVALID_VALUE: throw InvalidValue(desc);
case GLFW_OUT_OF_MEMORY: throw OutOfMemory(desc);
case GLFW_API_UNAVAILABLE: throw ApiUnavailable(desc);
case GLFW_VERSION_UNAVAILABLE: throw VersionUnavailable(desc);
case GLFW_PLATFORM_ERROR: throw PlatformError(desc);
case GLFW_FORMAT_UNAVAILABLE: throw FormatUnavailable(desc);
case GLFW_NO_WINDOW_CONTEXT: throw NoWindowContext(desc);
}
}
inline static void checkError()
{
const char* desc = nullptr;
int error = glfwGetError(&desc);
checkError(error, desc);
}
template <typename T>
std::enable_if_t<!std::is_void_v<T>, T> checkError(T value)
{
checkError();
return value;
}
} | 26.290323 | 67 | 0.770552 | JoaoBaptMG |
93f4fc6e924107501755d219494537308dd17f74 | 4,453 | hpp | C++ | remisen_run/include/shape/cube.hpp | tobanteGaming/template-opengl | 7eac0d5c49f93b0567cc49fae2b88fd72686e554 | [
"MIT"
] | 4 | 2021-07-11T02:07:38.000Z | 2022-03-19T06:14:32.000Z | remisen_run/include/shape/cube.hpp | tobanteGaming/template-opengl | 7eac0d5c49f93b0567cc49fae2b88fd72686e554 | [
"MIT"
] | null | null | null | remisen_run/include/shape/cube.hpp | tobanteGaming/template-opengl | 7eac0d5c49f93b0567cc49fae2b88fd72686e554 | [
"MIT"
] | null | null | null | #pragma once
#include <GL/glew.h>
namespace tobanteGaming
{
// Our vertices. Three consecutive floats give a 3D vertex; Three consecutive
// vertices give a triangle. A cube has 6 faces with 2 triangles each, so this
// makes 6*2=12 triangles, and 12*3 vertices
static const GLfloat g_vertex_buffer_data[] = {
-1.0f, -1.0f, -1.0f, // triangle 1 : begin //
-1.0f, -1.0f, 1.0f, //
-1.0f, 1.0f, 1.0f, // triangle 1 : end //
1.0f, 1.0f, -1.0f, // triangle 2 : begin //
-1.0f, -1.0f, -1.0f, //
-1.0f, 1.0f, -1.0f, // triangle 2 : end //
1.0f, -1.0f, 1.0f, //
-1.0f, -1.0f, -1.0f, //
1.0f, -1.0f, -1.0f, //
1.0f, 1.0f, -1.0f, //
1.0f, -1.0f, -1.0f, //
-1.0f, -1.0f, -1.0f, //
-1.0f, -1.0f, -1.0f, //
-1.0f, 1.0f, 1.0f, //
-1.0f, 1.0f, -1.0f, //
1.0f, -1.0f, 1.0f, //
-1.0f, -1.0f, 1.0f, //
-1.0f, -1.0f, -1.0f, //
-1.0f, 1.0f, 1.0f, //
-1.0f, -1.0f, 1.0f, //
1.0f, -1.0f, 1.0f, //
1.0f, 1.0f, 1.0f, //
1.0f, -1.0f, -1.0f, //
1.0f, 1.0f, -1.0f, //
1.0f, -1.0f, -1.0f, //
1.0f, 1.0f, 1.0f, //
1.0f, -1.0f, 1.0f, //
1.0f, 1.0f, 1.0f, //
1.0f, 1.0f, -1.0f, //
-1.0f, 1.0f, -1.0f, //
1.0f, 1.0f, 1.0f, //
-1.0f, 1.0f, -1.0f, //
-1.0f, 1.0f, 1.0f, //
1.0f, 1.0f, 1.0f, //
-1.0f, 1.0f, 1.0f, //
1.0f, -1.0f, 1.0f //
};
// One color for each vertex. They were generated randomly.
static const GLfloat g_color_buffer_data[] = {
0.583f, 0.771f, 0.014f, //
0.609f, 0.115f, 0.436f, //
0.327f, 0.483f, 0.844f, //
0.822f, 0.569f, 0.201f, //
0.435f, 0.602f, 0.223f, //
0.310f, 0.747f, 0.185f, //
0.597f, 0.770f, 0.761f, //
0.559f, 0.436f, 0.730f, //
0.359f, 0.583f, 0.152f, //
0.483f, 0.596f, 0.789f, //
0.559f, 0.861f, 0.639f, //
0.195f, 0.548f, 0.859f, //
0.014f, 0.184f, 0.576f, //
0.771f, 0.328f, 0.970f, //
0.406f, 0.615f, 0.116f, //
0.676f, 0.977f, 0.133f, //
0.971f, 0.572f, 0.833f, //
0.140f, 0.616f, 0.489f, //
0.997f, 0.513f, 0.064f, //
0.945f, 0.719f, 0.592f, //
0.543f, 0.021f, 0.978f, //
0.279f, 0.317f, 0.505f, //
0.167f, 0.620f, 0.077f, //
0.347f, 0.857f, 0.137f, //
0.055f, 0.953f, 0.042f, //
0.714f, 0.505f, 0.345f, //
0.783f, 0.290f, 0.734f, //
0.722f, 0.645f, 0.174f, //
0.302f, 0.455f, 0.848f, //
0.225f, 0.587f, 0.040f, //
0.517f, 0.713f, 0.338f, //
0.053f, 0.959f, 0.120f, //
0.393f, 0.621f, 0.362f, //
0.673f, 0.211f, 0.457f, //
0.820f, 0.883f, 0.371f, //
0.982f, 0.099f, 0.879f //
};
class Cube
{
public:
Cube()
{
GLuint VBO;
glGenVertexArrays(1, &m_vao);
glGenBuffers(1, &VBO);
// bind the Vertex Array Object first, then bind and set vertex
// buffer(s), and then configure vertex attributes(s).
glBindVertexArray(m_vao);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(g_vertex_buffer_data),
g_vertex_buffer_data, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float),
(void*)nullptr);
glEnableVertexAttribArray(0);
// note that this is allowed, the call to glVertexAttribPointer
// registered VBO as the vertex attribute's bound vertex buffer object
// so afterwards we can safely unbind
glBindBuffer(GL_ARRAY_BUFFER, 0);
// remember: do NOT unbind the EBO while a VAO is active as the bound
// element buffer object IS stored in the VAO; keep the EBO bound.
// glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
// You can unbind the VAO afterwards so other VAO calls won't
// accidentally modify this VAO, but this rarely happens. Modifying
// other VAOs requires a call to glBindVertexArray anyways so we
// generally don't unbind VAOs (nor VBOs) when it's not directly
// necessary.
glBindVertexArray(0);
}
GLuint getVAO() { return m_vao; }
void render()
{
glBindVertexArray(m_vao);
// 12*3 indices starting at 0 ->12 triangles -> 6 squares
glDrawArrays(GL_TRIANGLES, 0, 12 * 3);
// glDisableVertexAttribArray(0);
}
private:
GLuint m_vao;
};
} // namespace tobanteGaming | 32.268116 | 78 | 0.525488 | tobanteGaming |
93f8503058898c5eae1871a38fcd9a79863fade2 | 479 | cpp | C++ | src/snek.cpp | aleksiy325/snek-two | da589b945e347c5178f6cc0c8b190a28651cce50 | [
"MIT"
] | 9 | 2018-03-13T03:34:46.000Z | 2021-12-17T16:30:27.000Z | src/snek.cpp | mapld/snek-two | da589b945e347c5178f6cc0c8b190a28651cce50 | [
"MIT"
] | null | null | null | src/snek.cpp | mapld/snek-two | da589b945e347c5178f6cc0c8b190a28651cce50 | [
"MIT"
] | 5 | 2018-03-13T03:41:38.000Z | 2022-02-15T08:02:43.000Z | #include "strategies/random_snake.cpp"
#include "strategies/eat_snake.cpp"
#include "arena/arena.cpp"
int main(int argc, char **argv){
Arena arena = Arena(10, 10, 5, 1000);
RandomSnake rsnake = RandomSnake{};
Strategy* strat = &rsnake;
EatSnake esnake = EatSnake{};
Strategy* estrat = &esnake;
arena.addStrategy(strat);
arena.addStrategy(strat);
arena.addStrategy(estrat);
arena.addStrategy(estrat);
arena.execute();
}
| 23.95 | 40 | 0.655532 | aleksiy325 |
93f86c81425598e98c8add36f7bc444ca7f0ff86 | 3,061 | cpp | C++ | example/up2date_client/main.cpp | rtsoft-gmbh/up2date-cpp | 6df40513617d54d72813c49d95df236474379631 | [
"Apache-2.0"
] | 3 | 2022-03-24T14:56:29.000Z | 2022-03-25T12:42:05.000Z | example/up2date_client/main.cpp | rtsoft-gmbh/up2date-cpp | 6df40513617d54d72813c49d95df236474379631 | [
"Apache-2.0"
] | 9 | 2022-03-15T18:27:49.000Z | 2022-03-25T13:00:28.000Z | example/up2date_client/main.cpp | rtsoft-gmbh/up2date-cpp | 6df40513617d54d72813c49d95df236474379631 | [
"Apache-2.0"
] | null | null | null | #include "basic_handler.hpp"
#include "ritms_dps.hpp"
#include <exception>
#include <thread>
const char *AUTH_CERT_PATH_ENV_NAME = "CERT_PATH";
const char *PROVISIONING_ENDPOINT_ENV_NAME = "PROVISIONING_ENDPOINT";
const char *X_APIG_TOKEN_ENV_NAME = "X_APIG_TOKEN";
using namespace ritms::dps;
using namespace ddi;
class DPSInfoReloadHandler : public AuthErrorHandler {
std::unique_ptr<ProvisioningClient> client;
public:
explicit DPSInfoReloadHandler(std::unique_ptr<ProvisioningClient> client_) : client(std::move(client_)) {};
void onAuthError(std::unique_ptr<AuthRestoreHandler> ptr) override {
for (;;) {
try {
std::cout << "==============================================" << std::endl;
std::cout << "|DPSInfoReloadHandler| Starting provisioning..." << std::endl;
auto payload = client->doProvisioning();
std::cout << "|DPSInfoReloadHandler| ... done" << std::endl;
auto keyPair = payload->getKeyPair();
std::cout << "|DPSInfoReloadHandler| Setting TLS ..." << std::endl;
ptr->setTLS(keyPair->getCrt(), keyPair->getKey());
std::cout << "|DPSInfoReloadHandler| Setting endpoint [" << payload->getUp2DateEndpoint() << "] ..." << std::endl;
ptr->setEndpoint(payload->getUp2DateEndpoint());
std::cout << "==============================================" << std::endl;
return;
}
catch (std::exception &e) {
std::cout << "provisioning error: " << e.what() << " still trying..." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(3000));
}
}
}
};
int main() {
std::cout << "up2date hawkBit-cpp client started..." << std::endl;
auto clientCertificatePath = getEnvOrExit(AUTH_CERT_PATH_ENV_NAME);
auto provisioningEndpoint = getEnvOrExit(PROVISIONING_ENDPOINT_ENV_NAME);
// special variable for cloud
auto xApigToken = getEnvOrExit(X_APIG_TOKEN_ENV_NAME);
std::ifstream t((std::string(clientCertificatePath)));
if (!t.is_open()) {
std::cout << "File " << clientCertificatePath << " not exists" << std::endl;
throw std::runtime_error(std::string("fail: cannot open file :").append(clientCertificatePath));
}
std::string crt((std::istreambuf_iterator<char>(t)),
std::istreambuf_iterator<char>());
auto dpsBuilder = CloudProvisioningClientBuilder::newInstance();
auto dpsClient = dpsBuilder->setEndpoint(provisioningEndpoint)
->setAuthCrt(crt)
->addHeader("X-Apig-AppCode", std::string(xApigToken))
->build();
auto authErrorHandler = std::shared_ptr<AuthErrorHandler>(new DPSInfoReloadHandler(std::move(dpsClient)));
auto builder = DDIClientBuilder::newInstance();
builder->setAuthErrorHandler(authErrorHandler)
->setEventHandler(std::shared_ptr<EventHandler>(new Handler()))
->build()
->run();
} | 42.513889 | 130 | 0.608298 | rtsoft-gmbh |
93fd448608a779c8db5c904028e225426c228234 | 721 | cpp | C++ | VModel - 2017/Vmodel2017S3E3 - Luchian.cpp | LoopieDoo/Variante-INFO | fe42ea7b1b2fb88594c5f103129ee4fa3971ba10 | [
"MIT"
] | null | null | null | VModel - 2017/Vmodel2017S3E3 - Luchian.cpp | LoopieDoo/Variante-INFO | fe42ea7b1b2fb88594c5f103129ee4fa3971ba10 | [
"MIT"
] | null | null | null | VModel - 2017/Vmodel2017S3E3 - Luchian.cpp | LoopieDoo/Variante-INFO | fe42ea7b1b2fb88594c5f103129ee4fa3971ba10 | [
"MIT"
] | 1 | 2021-09-24T22:44:08.000Z | 2021-09-24T22:44:08.000Z | #include <iostream>
using namespace std;
/*
Subprogramul nrDiv are doi parametri, a și b (a≤b), prin care primeste câte un număr
natural din intervalul [1,10^9]. Subprogramul returnează numărul valorilor din intervalul
[a,b] care pot fi scrise ca produs de două numere naturale consecutive.
Scrieti definitia completă a subprogramului.
*/
unsigned int nrDiv(unsigned int a, unsigned int b)
{
unsigned int nr, i=1, contor=0;
for (a; a<=b; a++)
{
nr = a;
while (i*(i+1) <= nr)
{
if (i*(i+1) == nr)
{
contor++;
break;
}
i++;
}
}
return contor;
}
int main()
{
cout << nrDiv(10, 40);
}
| 20.6 | 89 | 0.554785 | LoopieDoo |
9e02f89180c8e757402b76819f4aef2c6996d36b | 910 | cpp | C++ | main/main.cpp | ivyknob/avionics_wifi | 2e21b2af6dd01045663c69df119d5fabdfd25ff7 | [
"MIT"
] | null | null | null | main/main.cpp | ivyknob/avionics_wifi | 2e21b2af6dd01045663c69df119d5fabdfd25ff7 | [
"MIT"
] | 4 | 2020-04-13T09:09:34.000Z | 2021-08-31T16:47:29.000Z | main/main.cpp | ivyknob/avionics_wifi | 2e21b2af6dd01045663c69df119d5fabdfd25ff7 | [
"MIT"
] | null | null | null | #include "main.hpp"
DataStorage storage;
// Status status;
void init_system() {
gpio_pad_select_gpio(BLINK_GPIO);
gpio_set_direction(BLINK_GPIO, GPIO_MODE_OUTPUT);
// wifi_setup();
esp_err_t ret = nvs_flash_init();
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
ESP_ERROR_CHECK(nvs_flash_erase());
ret = nvs_flash_init();
}
ESP_ERROR_CHECK(ret);
wifi_init_sta();
demo_init();
// gyro_init();
// gyro init fires gyro_task if everything is ok
// if not ok, it adds fake gyro
ws_server_start();
can_init();
xTaskCreate(&server_task, "server_task", 3000, NULL, 6, NULL);
xTaskCreate(&server_handle_task, "server_handle_task", 4000, NULL, 6, NULL);
xTaskCreate(&websockets_task, "websockets_task", 6000, NULL, 6, NULL);
xTaskCreate(&status_task, "status_task", 7000, NULL, 6, NULL);
}
extern "C" void app_main() {
init_system();
}
| 26.764706 | 81 | 0.708791 | ivyknob |
9e0be4c95944c47b45f72799b9c89bcf8dd1a8e0 | 13,909 | hpp | C++ | framework/areg/base/SharedBuffer.hpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 70 | 2021-07-20T11:26:16.000Z | 2022-03-27T11:17:43.000Z | framework/areg/base/SharedBuffer.hpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 32 | 2021-07-31T05:20:44.000Z | 2022-03-20T10:11:52.000Z | framework/areg/base/SharedBuffer.hpp | Ali-Nasrolahi/areg-sdk | 4fbc2f2644220196004a31672a697a864755f0b6 | [
"Apache-2.0"
] | 40 | 2021-11-02T09:45:38.000Z | 2022-03-27T11:17:46.000Z | #pragma once
/************************************************************************
* This file is part of the AREG SDK core engine.
* AREG SDK is dual-licensed under Free open source (Apache version 2.0
* License) and Commercial (with various pricing models) licenses, depending
* on the nature of the project (commercial, research, academic or free).
* You should have received a copy of the AREG SDK license description in LICENSE.txt.
* If not, please contact to info[at]aregtech.com
*
* \copyright (c) 2017-2021 Aregtech UG. All rights reserved.
* \file areg/base/SharedBuffer.hpp
* \ingroup AREG SDK, Asynchronous Event Generator Software Development Kit
* \author Artak Avetyan
* \brief AREG Platform, Shared Buffer class
* This Buffer is used for Read and Write of data and
* it might be shared between different threads and objects.
* The Data in buffer remains valid until the number of references
* to the buffer is more than zero.
*
************************************************************************/
/************************************************************************
* Include files.
************************************************************************/
#include "areg/base/GEGlobal.h"
#include "areg/base/BufferStreamBase.hpp"
#include "areg/base/private/BufferPosition.hpp"
//////////////////////////////////////////////////////////////////////////
// SharedBuffer class declaration
//////////////////////////////////////////////////////////////////////////
/**
* \brief Shared Buffer uses instance of Byte Buffer and keeps track
* of reference counter. Every time the same Byte Buffer is used
* by other instance of Shared Buffer object, the reference
* count will be increased by one. When Shared Buffer
* release Byte Buffer, the reference count decreased by one.
* The Byte Buffer will be freed when Reference Count is zero.
* This mechanism prevents having multiple copy operation when
* binary data is passed to multiple objects.
* Any write operation preformed by one of Shared Buffer will have
* impact on data shared between different instances.
* The difference with Raw Buffer is that Raw Buffer object frees
* Byte Buffer data in destructor without checking reference count.
* By this, the user should prevent passing Byte Buffer object
* instantiated by Raw Buffer object. Passing Byte Buffer to
* Raw Buffer object is allowed, since Raw Buffer will make a
* copy of data and any write operation will not have impact
* on other instances of Shared Buffer.
*
* \note Shared Buffer is not thread safe. There is no data access
* synchronization mechanism in this class. The SharedBuffer is
* designed to avoid multiple copies of same data, rather than
* to share data between different instances of thread.
* The instance of Shared Buffer can be used for data streaming.
**/
class AREG_API SharedBuffer : public BufferStreamBase // This is data streaming object
, public BufferPosition // To control read and write operations
{
friend class FileBuffer;
//////////////////////////////////////////////////////////////////////////
// Constructors / destructor
//////////////////////////////////////////////////////////////////////////
public:
/**
* \brief Default constructor
* \param blockSize The size of minimum block size to increase on resize.
* It is aligned to NEMemory::BLOCK_SIZE (minimum size)
**/
explicit SharedBuffer(unsigned int blockSize = NEMemory::BLOCK_SIZE);
/**
* \brief Constructor to reserve space for byte buffer object
* \param reserveSize Size in bytes to reserve
* \param blockSize The size of minimum block size to increase on resize.
* It is aligned to NEMemory::BLOCK_SIZE (minimum size)
**/
SharedBuffer( unsigned int reserveSize, unsigned int blockSize );
/**
* \brief Initialization constructor, writes given data into byte buffer
* \param buffer The data to initialize byte buffer
* \param size The length in bytes of data
* \param blockSize The size of minimum block size to increase on resize.
* It is aligned to NEMemory::BLOCK_SIZE (minimum size)
**/
SharedBuffer( const unsigned char * buffer, unsigned int size, unsigned int blockSize = NEMemory::BLOCK_SIZE );
/**
* \brief Initialization constructor, writes given null-terminated string into byte buffer.
* It will write including EOS character ('\0').
* If given string is null, it will write only end-of-string ('\0') character.
* \param textString The byte buffer as a null-terminated string
* \param blockSize The size of minimum block size to increase on resize.
* It is aligned to NEMemory::BLOCK_SIZE (minimum size)
**/
explicit SharedBuffer( const char * textString, unsigned int blockSize = NEMemory::BLOCK_SIZE );
explicit SharedBuffer( const wchar_t * textString, unsigned int blockSize = NEMemory::BLOCK_SIZE );
/**
* \brief Copy constructor. It does not copy data from src, it will refer to the same shared
* byte buffer object and will increase reference counter by one to prevent any other
* shared buffer object deleting used data
* \param src The source of shared buffer object instance.
**/
SharedBuffer(const SharedBuffer& src);
/**
* \brief Moves data from given source.
* \param src The source of shared buffer to mvoe data.
**/
SharedBuffer( SharedBuffer && src ) noexcept;
/**
* \brief Destructor
**/
virtual ~SharedBuffer( void ) = default;
//////////////////////////////////////////////////////////////////////////
// Operators
//////////////////////////////////////////////////////////////////////////
public:
/**
* \brief Compares 2 instances of shared buffer and returns true if they are equal
* \param other Reference to another shared buffer object instance to compare
* \return Returns true if 2 objects are same or have similar data.
* If 2 objects are invalid, it will return false.
**/
inline bool operator == (const SharedBuffer & other) const;
/**
* \brief Compares 2 instances of shared buffer and returns true if they are not equal
* \param other Reference to another shared buffer object instance to compare
* \return Returns true if 2 objects are having different data or they are invalid.
**/
inline bool operator != (const SharedBuffer & other) const;
/**
* \brief Assigning operator, it does not copy source data, it increases
* byte buffer reference counter by one to prevent other shared
* object instance to delete buffer
* \param src Reference to source object
**/
SharedBuffer & operator = (const SharedBuffer & src);
/**
* \brief Moves shared buffer data from given source.
* \param src The source to move data.
**/
SharedBuffer & operator = ( SharedBuffer && src ) noexcept;
/************************************************************************/
// Friend global operators to stream Shared Buffer
/************************************************************************/
/**
* \brief Friend operator declaration to make Shared Buffer streamable.
* Writes the data from streaming object to Shared Buffer
* \param stream The data streaming object to read data
* \param input The Shared Buffer object to write data
* \return Reference to Streaming object.
**/
friend inline const IEInStream & operator >> ( const IEInStream & stream, SharedBuffer & input );
/**
* \brief Friend global operator declaration to make Shared Buffer streamable.
* Writes the data from shared buffer to streaming
* \param stream The data streaming object to write data
* \param input The Shared Buffer object to write data
* \return Reference to Streaming object.
**/
friend inline IEOutStream & operator << ( IEOutStream & stream, const SharedBuffer & output );
//////////////////////////////////////////////////////////////////////////
// Operations
//////////////////////////////////////////////////////////////////////////
public:
/**
* \brief Returns true if either buffer is invalid,
* or current position is equal to zero,
* or current position is equal to IECursorPosition::INVALID_CURSOR_POSITION.
* Otherwise, it returns false.
**/
inline bool isBeginOfBuffer( void ) const;
/**
* \brief Returns true the buffer is valid and the current position
* is equal to used size of buffer.
* Otherwise, it returns false.
**/
inline bool isEndOfBuffer( void ) const;
/**
* \brief Returns the pointer to the data buffer at current position.
* If position is invalid (IECursorPosition::INVALID_CURSOR_POSITION), it will return nullptr
* If it is a start position (IECursorPosition::START_CURSOR_POSITION), it will return pointer to complete buffer
* If it is an end of position, it will return nullptr
* In other cases it will return (GetBuffer() + GetCursorPosition())
**/
const unsigned char* getBufferAtCurrentPosition( void ) const;
/**
* \brief Returns the size of block set in the constructor.
**/
inline unsigned int getBlockSize( void ) const;
//////////////////////////////////////////////////////////////////////////
// Overrides
//////////////////////////////////////////////////////////////////////////
/************************************************************************/
// IEByteBuffer interface overrides, not implemented in BufferStreamBase
/************************************************************************/
/**
* \brief Returns true if buffer is shared between several byte buffer instances.
**/
virtual bool isShared( void ) const final;
/**
* \brief Returns true if buffer can be shared.
* The Raw Buffer object should return false.
* The Shared Buffer object should return true.
**/
virtual bool canShare( void ) const final;
/**
* \brief Invalidates the buffer. Removes reference, assigns to invalid buffer,
* invalidates writing and reading positions.
**/
virtual void invalidate( void ) override;
protected:
/************************************************************************/
// IEByteBuffer protected overrides
/************************************************************************/
/**
* \brief Returns the offset value from the beginning of byte buffer, which should be set
**/
virtual unsigned int getDataOffset( void ) const override;
/**
* \brief Returns the size of data byte structure to allocate.
**/
virtual unsigned int getHeaderSize( void ) const override;
/**
* \brief Returns the size to align the buffer. By default it is sizeof(NEMemory::uAlign)
**/
virtual unsigned int getAlignedSize( void ) const override;
//////////////////////////////////////////////////////////////////////////
// Member variables
//////////////////////////////////////////////////////////////////////////
protected:
/**
* \brief The size of block to increase at once every time when need to resize.
* This value is a constant and cannot be changed. Set during initialization.
**/
const unsigned int mBlockSize;
//////////////////////////////////////////////////////////////////////////
// Local function member
//////////////////////////////////////////////////////////////////////////
private:
/**
* \brief Returns reference to Shared Buffer.
**/
inline SharedBuffer & self( void );
};
//////////////////////////////////////////////////////////////////////////
// SharedBuffer class inline function implementation
//////////////////////////////////////////////////////////////////////////
inline bool SharedBuffer::operator == ( const SharedBuffer &other ) const
{
return isEqual(other);
}
inline bool SharedBuffer::operator != ( const SharedBuffer &other ) const
{
return (isEqual(other) == false);
}
inline bool SharedBuffer::isBeginOfBuffer( void ) const
{
unsigned int curPos = getPosition();
return ((isValid() == false) || (curPos == 0) || (curPos == IECursorPosition::INVALID_CURSOR_POSITION));
}
inline bool SharedBuffer::isEndOfBuffer( void ) const
{
return ( isValid() && (getPosition() == getSizeUsed()) );
}
inline unsigned int SharedBuffer::getBlockSize(void) const
{
return mBlockSize;
}
/************************************************************************/
// Friend streamable operators
/************************************************************************/
inline const IEInStream & operator >> (const IEInStream & stream, SharedBuffer & input)
{
if ( static_cast<const IEInStream *>(&stream) != static_cast<const IEInStream *>(&input) )
{
stream.read(input);
input.moveToBegin();
}
return stream;
}
inline IEOutStream & operator << (IEOutStream & stream, const SharedBuffer & output)
{
if ( static_cast<const IEOutStream *>(&stream) != static_cast<const IEOutStream *>(&output) )
{
stream.write( output );
output.moveToBegin();
}
return stream;
}
| 42.405488 | 126 | 0.562226 | Ali-Nasrolahi |
9e1260b1c4fe8ef58f2cc639b320e2b2b3d2ab1e | 452 | cpp | C++ | Check Capital.cpp | Subhash3/Algorithms-For-Software-Developers | 2e0ac4f51d379a2b10a40fca7fa82a8501d3db94 | [
"BSD-2-Clause"
] | 2 | 2021-10-01T04:20:04.000Z | 2021-10-01T04:20:06.000Z | Check Capital.cpp | Subhash3/Algorithms-For-Software-Developers | 2e0ac4f51d379a2b10a40fca7fa82a8501d3db94 | [
"BSD-2-Clause"
] | 1 | 2021-10-01T18:00:09.000Z | 2021-10-01T18:00:09.000Z | Check Capital.cpp | Subhash3/Algorithms-For-Software-Developers | 2e0ac4f51d379a2b10a40fca7fa82a8501d3db94 | [
"BSD-2-Clause"
] | 8 | 2021-10-01T04:20:38.000Z | 2022-03-19T17:05:05.000Z | class Solution {
public:
bool detectCapitalUse(string word) {
int u=0;
int l=0;
for(int i=0;i<word.size();i++){
if(word[i]>=65&&word[i]<=90)
u++;
else if(word[i]>=97&&word[i]<=122)
l++;
}
if(u==word.size()||l==word.size())
return true;
if(word[0]>=65&&word[0]<=90&&word.size()-1==l)
return true;
return false;
}
};
| 23.789474 | 47 | 0.426991 | Subhash3 |
9e1b53cdb570a629d5a43418b190dda178e7a274 | 8,019 | cpp | C++ | plugins/vkeyboard/vkeyboard.cpp | eayus/wayfire | e71beff56eb8d82b16d02a48efc66fa127886d35 | [
"MIT"
] | null | null | null | plugins/vkeyboard/vkeyboard.cpp | eayus/wayfire | e71beff56eb8d82b16d02a48efc66fa127886d35 | [
"MIT"
] | null | null | null | plugins/vkeyboard/vkeyboard.cpp | eayus/wayfire | e71beff56eb8d82b16d02a48efc66fa127886d35 | [
"MIT"
] | null | null | null | #include <core.hpp>
#include <debug.hpp>
#include <config.hpp>
#include <view.hpp>
#include <output.hpp>
#include <plugin.hpp>
#include <signal-definitions.hpp>
#include <workspace-manager.hpp>
#include <linux/input-event-codes.h>
#include "proto/wayfire-shell-server.h"
class vkeyboard : public wayfire_plugin_t
{
static weston_layer input_layer;
static weston_seat *vseat;
static weston_keyboard *vkbd;
touch_gesture_callback swipe;
key_callback disable_real_keyboard;
std::string keyboard_exec_path = INSTALL_PREFIX "/lib/wayfire/wayfire-virtual-keyboard";
public:
static wl_resource *resource;
static wayfire_view view;
void init(wayfire_config *config);
void bind(wl_resource *resource);
void show_keyboard();
void set_keyboard(wayfire_view view);
void unset_keyboard();
void configure_keyboard(wayfire_view view, int x, int y);
void send_key_up(uint32_t key);
void send_key_down(uint32_t key);
};
weston_layer vkeyboard::input_layer;
weston_seat *vkeyboard::vseat = nullptr;
weston_keyboard *vkeyboard::vkbd;
wl_resource *vkeyboard::resource = nullptr;
wayfire_view vkeyboard::view;
void send_key_pressed(struct wl_client *client,
struct wl_resource *resource,
uint32_t key)
{
auto vk = (vkeyboard*) wl_resource_get_user_data(resource);
vk->send_key_down(key);
}
void send_key_released(struct wl_client *client,
struct wl_resource *resource,
uint32_t key)
{
auto vk = (vkeyboard*) wl_resource_get_user_data(resource);
vk->send_key_up(key);
}
void set_virtual_keyboard(struct wl_client *client,
struct wl_resource *resource,
struct wl_resource *surface)
{
auto vk = (vkeyboard*) wl_resource_get_user_data(resource);
auto wsurf = (weston_surface*) wl_resource_get_user_data(surface);
auto view = core->find_view(wsurf);
vk->resource = resource;
vk->set_keyboard(view);
}
void configure_keyboard(struct wl_client *client,
struct wl_resource *resource,
struct wl_resource *surface,
int32_t x,
int32_t y)
{
auto vk = (vkeyboard*) wl_resource_get_user_data(resource);
auto wsurf = (weston_surface*) wl_resource_get_user_data(surface);
auto view = core->find_view(wsurf);
vk->configure_keyboard(view, x, y);
}
void start_interactive_move(struct wl_client *client,
struct wl_resource *resource,
struct wl_resource *surface)
{
auto wsurf = (weston_surface*) wl_resource_get_user_data(surface);
auto view = core->find_view(wsurf);
move_request_signal data;
data.view = view;
auto touch = weston_seat_get_touch(core->get_current_seat());
if (!touch)
{
auto ptr = weston_seat_get_pointer(core->get_current_seat());
data.serial = ptr->grab_serial;
} else {
data.serial = touch->grab_serial;
}
view->output->emit_signal("move-request", &data);
}
static const struct wayfire_virtual_keyboard_interface vk_iface =
{
send_key_pressed,
send_key_released,
set_virtual_keyboard,
configure_keyboard,
start_interactive_move
};
void unbind_virtual_keyboard(wl_resource* resource)
{
vkeyboard *vk = (vkeyboard*) wl_resource_get_user_data(resource);
vk->unset_keyboard();
}
void bind_virtual_keyboard(wl_client *client, void *data, uint32_t version, uint32_t id)
{
vkeyboard *vk = (vkeyboard*) data;
auto resource = wl_resource_create(client, &wayfire_virtual_keyboard_interface, 1, id);
wl_resource_set_implementation(resource, &vk_iface,
vk, unbind_virtual_keyboard);
vk->bind(resource);
}
using default_grab_key_type = void (*) (weston_keyboard_grab*, const timespec*, uint32_t, uint32_t);
default_grab_key_type default_grab_cb;
wayfire_key disabling_key;
weston_keyboard_grab_interface ignore_grab_iface;
void ignore_key(weston_keyboard_grab* kbd, const timespec*, uint32_t key, uint32_t)
{ }
void vkeyboard::init(wayfire_config *config)
{
grab_interface->name = "vkeyboard";
grab_interface->abilities_mask = 0;
/* we must make sure that we do not create multiple interfaces */
if (core->get_num_outputs() == 0)
{
wl_global *kbd;
if ((kbd = wl_global_create(core->ec->wl_display, &wayfire_virtual_keyboard_interface,
1, this, bind_virtual_keyboard)) == NULL)
{
errio << "Failed to create wayfire_shell interface" << std::endl;
}
weston_layer_init(&input_layer, core->ec);
weston_layer_set_position(&input_layer, WESTON_LAYER_POSITION_TOP_UI);
}
swipe = [=] (wayfire_touch_gesture *gesture)
{
if (gesture->direction == GESTURE_DIRECTION_RIGHT)
show_keyboard();
};
wayfire_touch_gesture show_gesture;
show_gesture.type = GESTURE_EDGE_SWIPE;
show_gesture.finger_count = 3;
output->add_gesture(show_gesture, &swipe);
auto section = config->get_section("vkeyboard");
disabling_key = section->get_key("disable_real_keyboard",
{WLR_MODIFIER_ALT | WLR_MODIFIER_CTRL, KEY_K});
if (disabling_key.keyval)
{
disable_real_keyboard = [=] (weston_keyboard *kbd, uint32_t key)
{
ignore_grab_iface.cancel = kbd->default_grab.interface->cancel;
ignore_grab_iface.modifiers = kbd->default_grab.interface->modifiers;
ignore_grab_iface.key = kbd->default_grab.interface->key;
if (ignore_grab_iface.key == ignore_key)
{
ignore_grab_iface.key = default_grab_cb;
} else
{
default_grab_cb = kbd->default_grab.interface->key;
ignore_grab_iface.key = ignore_key;
}
kbd->default_grab.interface = &ignore_grab_iface;
};
output->add_key(disabling_key.mod, disabling_key.keyval, &disable_real_keyboard);
}
keyboard_exec_path = section->get_string("path", keyboard_exec_path);
}
void vkeyboard::bind(wl_resource *res)
{
GetTuple(sw, sh, output->get_screen_size());
wayfire_virtual_keyboard_send_match_output_size(res, sw, sh);
if (!vseat)
{
vseat = new weston_seat;
weston_seat_init(vseat, core->ec, "virtual-input");
weston_seat_init_keyboard(vseat, NULL);
vkbd = weston_seat_get_keyboard(vseat);
}
}
void vkeyboard::send_key_down(uint32_t key)
{
auto kbd = weston_seat_get_keyboard(core->get_current_seat());
weston_seat_set_keyboard_focus(vseat, kbd->focus);
timespec t;
timespec_get(&t, TIME_UTC);
notify_key(vseat, &t, key, WL_KEYBOARD_KEY_STATE_PRESSED, STATE_UPDATE_AUTOMATIC);
}
void vkeyboard::send_key_up(uint32_t key)
{
timespec t;
timespec_get(&t, TIME_UTC);
notify_key(vseat, &t, key, WL_KEYBOARD_KEY_STATE_RELEASED, STATE_UPDATE_AUTOMATIC);
}
void vkeyboard::set_keyboard(wayfire_view view)
{
this->view = view;
view->is_special = true;
auto output = view->output;
output->detach_view(view);
view->output = output;
weston_layer_entry_insert(&input_layer.view_list, &view->handle->layer_link);
output->workspace->add_renderable_view(view);
}
void vkeyboard::unset_keyboard()
{
if (resource)
{
resource = NULL;
view->output->workspace->rem_renderable_view(view);
}
}
void vkeyboard::configure_keyboard(wayfire_view view, int x, int y)
{
view->move(x, y);
}
void vkeyboard::show_keyboard()
{
if (!resource)
{
core->run(keyboard_exec_path.c_str());
} else
{
wayfire_virtual_keyboard_send_show_virtual_keyboard(resource);
}
}
extern "C" {
wayfire_plugin_t *newInstance()
{
return new vkeyboard;
}
}
| 28.537367 | 100 | 0.667415 | eayus |
9e1d1a0125375d4de5f27d874f39293343130325 | 2,058 | cpp | C++ | cetty-core/src/cetty/handler/codec/http/CookieHeaderNames.cpp | frankee/cetty2 | 62ac0cd1438275097e47a9ba471e72efd2746ded | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 26 | 2015-11-08T10:58:21.000Z | 2021-02-25T08:27:26.000Z | cetty-core/src/cetty/handler/codec/http/CookieHeaderNames.cpp | frankee/cetty2 | 62ac0cd1438275097e47a9ba471e72efd2746ded | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 1 | 2019-02-18T08:46:17.000Z | 2019-02-18T08:46:17.000Z | cetty-core/src/cetty/handler/codec/http/CookieHeaderNames.cpp | frankee/cetty2 | 62ac0cd1438275097e47a9ba471e72efd2746ded | [
"BSL-1.0",
"Apache-2.0",
"BSD-3-Clause"
] | 8 | 2016-02-27T02:37:10.000Z | 2021-09-29T05:25:00.000Z | /*
* Copyright (c) 2010-2011 frankee zhou (frankee.zhou at gmail dot com)
* Distributed under under the Apache License, version 2.0 (the "License").
*/
#include <map>
#include <boost/algorithm/string/case_conv.hpp>
#include <cetty/handler/codec/http/CookieHeaderNames.h>
namespace cetty {
namespace handler {
namespace codec {
namespace http {
const std::string CookieHeaderNames::COOKIE_PATH = "Path";
const std::string CookieHeaderNames::COOKIE_EXPIRES = "Expires";
const std::string CookieHeaderNames::COOKIE_MAX_AGE = "Max-Age";
const std::string CookieHeaderNames::COOKIE_DOMAIN = "Domain";
const std::string CookieHeaderNames::COOKIE_SECURE = "Secure";
const std::string CookieHeaderNames::COOKIE_HTTP_ONLY = "HTTPOnly";
const std::string CookieHeaderNames::COOKIE_COMMENT = "Comment";
const std::string CookieHeaderNames::COOKIE_COMMENT_URL = "CommentURL";
const std::string CookieHeaderNames::COOKIE_DISCARD = "Discard";
const std::string CookieHeaderNames::COOKIE_PORT = "Port";
const std::string CookieHeaderNames::COOKIE_VERSION = "Version";
bool CookieHeaderNames::isReserved(const std::string& name) {
static bool init = false;
static std::map<std::string, int> reservedNames;
if (!init) {
reservedNames[boost::to_lower_copy(COOKIE_PATH)] = 1;
reservedNames[boost::to_lower_copy(COOKIE_EXPIRES)] = 1;
reservedNames[boost::to_lower_copy(COOKIE_MAX_AGE)] = 1;
reservedNames[boost::to_lower_copy(COOKIE_DOMAIN)] = 1;
reservedNames[boost::to_lower_copy(COOKIE_SECURE)] = 1;
reservedNames[boost::to_lower_copy(COOKIE_HTTP_ONLY)] = 1;
reservedNames[boost::to_lower_copy(COOKIE_COMMENT)] = 1;
reservedNames[boost::to_lower_copy(COOKIE_COMMENT_URL)] = 1;
reservedNames[boost::to_lower_copy(COOKIE_DISCARD)] = 1;
reservedNames[boost::to_lower_copy(COOKIE_PORT)] = 1;
reservedNames[boost::to_lower_copy(COOKIE_VERSION)] = 1;
init = true;
}
return reservedNames.find(boost::to_lower_copy(name)) != reservedNames.end();
}
}
}
}
}
| 38.111111 | 81 | 0.733722 | frankee |
9e208c41429c363e1ae00723158281882173af82 | 952 | cpp | C++ | raygame/Enemy.cpp | JCoshua/SteeringBehaivors | 9c14f69f9be4da46de9a5db693dc14a801a41712 | [
"MIT"
] | null | null | null | raygame/Enemy.cpp | JCoshua/SteeringBehaivors | 9c14f69f9be4da46de9a5db693dc14a801a41712 | [
"MIT"
] | null | null | null | raygame/Enemy.cpp | JCoshua/SteeringBehaivors | 9c14f69f9be4da46de9a5db693dc14a801a41712 | [
"MIT"
] | null | null | null | #include "Enemy.h"
#include "Transform2D.h"
#include "SeekDecision.h"
#include "IdleDecision.h"
#include "WanderDecision.h"
#include "IsAggressiveDecision.h"
#include "InRangeDecision.h"
#include "DecisionComponent.h"
#include <Vector2.h>
void Enemy::start()
{
Agent::start();
IdleDecision* idle = new IdleDecision();
WanderDecision* wander = new WanderDecision();
SeekDecision* seek = new SeekDecision();
IsAggressiveDecision* aggression = new IsAggressiveDecision(idle, wander);
InRangeDecision* inRange = new InRangeDecision(aggression, seek);
addComponent(new DecisionComponent(inRange));
}
bool Enemy::getTargetInSight()
{
MathLibrary::Vector2 direction = getTarget()->getTransform()->getWorldPosition() - getTransform()->getWorldPosition();
float distance = direction.getMagnitude();
float fov = MathLibrary::Vector2::dotProduct(direction.getNormalized(), getTransform()->getForward());
return distance <= 300 && acos(fov) < 1;
}
| 29.75 | 119 | 0.756303 | JCoshua |
9e208f8d3c31f4ab6a37df033f145eb11eb1089f | 765 | cpp | C++ | shared/source/gmm_helper/windows/gmm_configure_device_address_space_drm_or_wddm.cpp | troels/compute-runtime | 3269e719a3ee7bcd97c50ec2cfe78fc8674adec0 | [
"Intel",
"MIT"
] | 778 | 2017-09-29T20:02:43.000Z | 2022-03-31T15:35:28.000Z | shared/source/gmm_helper/windows/gmm_configure_device_address_space_drm_or_wddm.cpp | troels/compute-runtime | 3269e719a3ee7bcd97c50ec2cfe78fc8674adec0 | [
"Intel",
"MIT"
] | 478 | 2018-01-26T16:06:45.000Z | 2022-03-30T10:19:10.000Z | shared/source/gmm_helper/windows/gmm_configure_device_address_space_drm_or_wddm.cpp | troels/compute-runtime | 3269e719a3ee7bcd97c50ec2cfe78fc8674adec0 | [
"Intel",
"MIT"
] | 215 | 2018-01-30T08:39:32.000Z | 2022-03-29T11:08:51.000Z | /*
* Copyright (C) 2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "shared/source/gmm_helper/client_context/gmm_client_context.h"
#include "shared/source/gmm_helper/windows/gmm_memory_base.h"
#include "shared/source/helpers/debug_helpers.h"
#include "shared/source/os_interface/windows/windows_defs.h"
namespace NEO {
bool GmmMemoryBase::configureDeviceAddressSpace(GMM_ESCAPE_HANDLE hAdapter,
GMM_ESCAPE_HANDLE hDevice,
GMM_ESCAPE_FUNC_TYPE pfnEscape,
GMM_GFX_SIZE_T svmSize,
BOOLEAN bdwL3Coherency) {
return true;
}
}; // namespace NEO
| 31.875 | 79 | 0.597386 | troels |
9e24d276b8f5690beca3a05b0978b80faa042c04 | 5,110 | cc | C++ | ch14_markov_decision_processes/src/main.cc | Amit10311/probabilistic_robotics | d31a9f1a3f5e500bd85d98d7fb4fb5743d1222ad | [
"MIT"
] | 959 | 2018-05-21T00:29:23.000Z | 2022-03-29T03:53:05.000Z | ch14_markov_decision_processes/src/main.cc | Amit10311/probabilistic_robotics | d31a9f1a3f5e500bd85d98d7fb4fb5743d1222ad | [
"MIT"
] | 9 | 2018-11-10T10:43:07.000Z | 2021-05-03T09:42:03.000Z | ch14_markov_decision_processes/src/main.cc | Amit10311/probabilistic_robotics | d31a9f1a3f5e500bd85d98d7fb4fb5743d1222ad | [
"MIT"
] | 347 | 2018-05-17T13:18:08.000Z | 2022-03-29T03:53:13.000Z | #include "markovdp.h"
void move(const std::valarray<int>&, const std::valarray<int>&, std::map<std::valarray<int>, double, valarray_comp>&,double&);
void move_rdm(const std::valarray<int>&, const std::valarray<int>&, std::map<std::valarray<int>, double, valarray_comp>&,double&);
void warp(const std::valarray<int>&, std::map<std::valarray<int>, double, valarray_comp>&,double&);
std::vector<tst_data> build_transitions(const mat&,
std::vector<void (*)(const std::valarray<int>&, std::map<std::valarray<int>, double, valarray_comp>&,double&)>&);
int main(int argc, char** argv){
mat occupancy;
occupancy.load(arma::hdf5_name("occupancy_map.h5", "occupancy"));
uint n = 0;
for (size_t i = 0; i < occupancy.n_rows; i++) {
for (size_t j = 0; j < occupancy.n_cols; j++) {
if (occupancy(i,j) == 0) {
occupancy(i,j) =n++;
continue;
}
}
}
vec jvalues = zeros<vec>(54);
//terminal states.
jvalues(0) = +100;
jvalues(1) = -100;
jvalues(36) = -100;
jvalues(37) = +100;
std::vector<void (*)(const std::valarray<int>&, std::map<std::valarray<int>, double, valarray_comp>&,double&)> moves;
moves.push_back([](const auto& from, auto& to, double& cost){
return move_rdm(std::valarray<int>({0,1,0}),from,to,cost);});
moves.push_back([](const auto& from, auto& to, double& cost){
return move_rdm(std::valarray<int>({1,0,0}),from,to,cost);});
moves.push_back([](const auto& from, auto& to, double& cost){
return move_rdm(std::valarray<int>({0,-1,0}),from,to,cost);});
moves.push_back([](const auto& from, auto& to, double& cost){
return move_rdm(std::valarray<int>({-1,0,0}),from,to,cost);});
moves.push_back(warp);
std::vector<tst_data> transitions = build_transitions(occupancy, moves);
MarkovDP mdp(jvalues, transitions);
uvec policy(54);
uint last_iter(0);
double epsilon = 1e-2;
uint max_iter = 1000;
mdp.value_iteration(epsilon, max_iter, jvalues, policy, last_iter);
std::cout << "converged in " << last_iter << " iterations." << '\n';
jvalues.print("Jvalues: ");
policy.print("optimal policy: ");
return 0;
}
void move(const std::valarray<int>& dxy, const std::valarray<int>& from, std::map<std::valarray<int>, double, valarray_comp>& to,double& cost) {
cost = -1.0;
if (from[0] == 0 || ( from[0] == 7 && from[1] == 6 && from[2] == 0 )) {
return;
}
to[from + dxy] = 1.0;
}
void move_rdm(const std::valarray<int>& dxy, const std::valarray<int>& from, std::map<std::valarray<int>, double, valarray_comp>& to,double& cost) {
cost = -1.0;
if (from[0] == 0 || ( from[0] == 7 && from[1] == 6 && from[2] == 0 )) {
return;
}
to[from + dxy] = 0.9;
to[from - dxy] = 0.1/3;
to[from + std::valarray<int>({dxy[1],dxy[0],dxy[2]})] = 0.1/3;
to[from - std::valarray<int>({dxy[1],dxy[0],dxy[2]})] = 0.1/3;
}
void warp(const std::valarray<int>& from, std::map<std::valarray<int>, double, valarray_comp>& to,double& cost) {
cost = 0.0;
if (from[0] == 0 && from[2] == 0) {
to[std::valarray<int>({from[0], from[1], 1})] = 0.5;
to[std::valarray<int>({from[0], from[1], -1})] = 0.5;
return;
}
if ( from[0] == 7 && from[1] == 6 && from[2] == 0) {
to[std::valarray<int>({7, 6, 1})] = 0.5;
to[std::valarray<int>({7, 6, -1})] = 0.5;
return;
}
}
inline uint to_linear(std::valarray<int> coord, const mat& occupancy) {
return (coord[2]+1)*18 + (uint)occupancy(coord[0],coord[1]);
}
std::vector<tst_data> build_transitions(const mat& occupancy,
std::vector<void (*)(const std::valarray<int>&, std::map<std::valarray<int>, double, valarray_comp>&,double&)>& moves) {
std::vector<tst_data> transitions;
for (size_t i = 0; i < moves.size(); i++) {
transitions.push_back({sp_mat(54,54),vec(54)});
}
int nr = occupancy.n_rows;
int nc = occupancy.n_cols;
for (int i = 0; i < nr; i++) {
for (int j = 0; j < nc; j++) {
if (occupancy(i,j)==-1) {
continue;
}
for (int z = -1; z < 2; z++) {
std::valarray<int> from({i, j, z});
uint lin_indx = to_linear(from, occupancy);
for ( uint m=0; m < moves.size(); ++m) {
std::map<std::valarray<int>, double, valarray_comp> to;
double cost;
moves[m](from,to,cost);
double stay(0);
for( auto const& tovtx : to ) {
auto const& tocoord = tovtx.first;
auto const& toprob = tovtx.second;
if (tocoord[0] < 0 || tocoord[0] >= nr ||
tocoord[1] < 0 || tocoord[1] >= nc ||
occupancy(tocoord[0], tocoord[1]) == -1) {
stay += toprob;
}
else {
uint lin_indx1 = to_linear(tocoord, occupancy);
transitions[m].tst_proba(lin_indx,lin_indx1) = toprob;
}
}
transitions[m].tst_proba(lin_indx,lin_indx) = (to.size())?stay:1;
transitions[m].tst_cost(lin_indx) = (stay<1)?cost:0;
}
}
}
}
return transitions;
}
| 33.398693 | 148 | 0.568102 | Amit10311 |
9e2790ee393aa1834c2123024d8bbb5ee6c4101f | 3,150 | cpp | C++ | libs/anari_test_scenes/scenes/cornell_box_cylinder_geom.cpp | Piromancer/ANARI-SDK | 636b8521b0f0c05a4d7b9cf50a643377d4cd00b9 | [
"Apache-2.0"
] | null | null | null | libs/anari_test_scenes/scenes/cornell_box_cylinder_geom.cpp | Piromancer/ANARI-SDK | 636b8521b0f0c05a4d7b9cf50a643377d4cd00b9 | [
"Apache-2.0"
] | null | null | null | libs/anari_test_scenes/scenes/cornell_box_cylinder_geom.cpp | Piromancer/ANARI-SDK | 636b8521b0f0c05a4d7b9cf50a643377d4cd00b9 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 The Khronos Group
// SPDX-License-Identifier: Apache-2.0
#include "cornell_box_cylinder_geom.h"
namespace anari {
namespace scenes {
// cone mesh data
static std::vector<glm::vec3> vertices = {
// Cylinder
{0.00f, 0.80f, 0.00f},
{0.00f, -0.80f, 0.00f}};
static std::vector<float> radiuses = {
// Cylinder
0.5f};
static std::vector<glm::uint8> caps = {
// Cylinder
1, 1};
static std::vector<glm::vec4> colors = {
// Cone
{1.0f, 0.0f, 0.0f, 1.0f},
{0.0f, 1.0f, 0.0f, 1.0f}
};
// CornelBox definitions //////////////////////////////////////////////////////
CornellBoxCylinder::CornellBoxCylinder(anari::Device d) : TestScene(d)
{
m_world = anari::newObject<anari::World>(m_device);
}
CornellBoxCylinder::~CornellBoxCylinder()
{
anari::release(m_device, m_world);
}
anari::World CornellBoxCylinder::world()
{
return m_world;
}
void CornellBoxCylinder::commit()
{
auto d = m_device;
auto geom = anari::newObject<anari::Geometry>(d, "cylinder");
anari::setAndReleaseParameter(d,
geom,
"vertex.position",
anari::newArray1D(d, vertices.data(), vertices.size()));
anari::setAndReleaseParameter(d,
geom,
"vertex.color",
anari::newArray1D(d, colors.data(), colors.size()));
anari::setAndReleaseParameter(
d,
geom,
"vertex.cap",
anari::newArray1D(d, caps.data(), caps.size()));
anari::setAndReleaseParameter(d,
geom,
"primitive.radius",
anari::newArray1D(d, radiuses.data(), radiuses.size()));
anari::commit(d, geom);
auto surface = anari::newObject<anari::Surface>(d);
anari::setAndReleaseParameter(d, surface, "geometry", geom);
auto mat = anari::newObject<anari::Material>(d, "matte");
anari::setParameter(d, mat, "color", "color");
anari::commit(d, mat);
anari::setAndReleaseParameter(d, surface, "material", mat);
anari::commit(d, surface);
anari::setAndReleaseParameter(
d, m_world, "surface", anari::newArray1D(d, &surface));
anari::release(d, surface);
anari::Light light;
float irradiance = 2.5f;
float angularDiameter = 0.0f;
float red = 0.22f;
float green = 0.22f;
float blue = 0.15f;
float dirX = 0.0f;
float dirY = 0.0f;
float dirZ = 1.0f;
if (anari::deviceImplements(d, "ANARI_KHR_AREA_LIGHTS")) {
light = anari::newObject<anari::Light>(d, "directional");
anari::setParameter(d, light, "color", glm::vec3(red, green, blue));
anari::setParameter(d, light, "direction", glm::vec3(dirX, dirY, dirZ));
anari::setParameter(d, light, "irradiance", irradiance);
anari::setParameter(d, light, "angularDiameter", angularDiameter);
} else {
light = anari::newObject<anari::Light>(d, "directional");
anari::setParameter(d, light, "direction", glm::vec3(0.f, -0.5f, 1.f));
}
anari::commit(d, light);
anari::setAndReleaseParameter(
d, m_world, "light", anari::newArray1D(d, &light));
anari::release(d, light);
anari::commit(d, m_world);
}
TestScene *sceneCornellBoxCylinder(anari::Device d)
{
return new CornellBoxCylinder(d);
}
} // namespace scenes
} // namespace anari
| 24.80315 | 79 | 0.64 | Piromancer |
9e287519aa0fc0426501b3bbd19f6df8d2cc1ed2 | 910 | cpp | C++ | examples/qcor_demos/pirq_workshop/qcor/demo3_nisq_noise_mitigation/mitiq_noise_mitigation.cpp | ahayashi/qcor | 929988b92cfec52d321c48e6cc01545e46edc024 | [
"BSD-3-Clause"
] | null | null | null | examples/qcor_demos/pirq_workshop/qcor/demo3_nisq_noise_mitigation/mitiq_noise_mitigation.cpp | ahayashi/qcor | 929988b92cfec52d321c48e6cc01545e46edc024 | [
"BSD-3-Clause"
] | null | null | null | examples/qcor_demos/pirq_workshop/qcor/demo3_nisq_noise_mitigation/mitiq_noise_mitigation.cpp | ahayashi/qcor | 929988b92cfec52d321c48e6cc01545e46edc024 | [
"BSD-3-Clause"
] | null | null | null | /// mitiq_noise_mitigation.cpp: Run error mitigation with mitiq ZNE (zero-noise extrapolation)
/// Compile:
/// $ qcor -qpu aer[noise-model:noise_model.json] -shots 8192 -em mitiq-zne
/// mitiq_noise_mitigation.cpp Execute: specify the number of repeating CNOT
/// ./a.out N
// Repeating CNOT's to evaluate noise mitigation.
// This is a do-nothing circuit: qubits should return to the |00> state.
__qpu__ void noisy_zero(qreg q, int cx_count) {
H(q);
for (int i = 0; i < cx_count; i++) {
X::ctrl(q[0], q[1]);
}
H(q);
Measure(q);
}
int main(int argc, char *argv[]) {
// Default depth
int CX_depth = 0;
// Parse number of CX cycles:
if (argc == 2) {
CX_depth = std::stoi(argv[1]);
}
qreg q = qalloc(2);
// noisy_zero::print_kernel(q, CX_depth);
noisy_zero(q, CX_depth);
// q.print();
std::cout << "CX depth: " << CX_depth << "; Expectation: " << q.exp_val_z() << "\n";
} | 29.354839 | 94 | 0.637363 | ahayashi |
9e364de25be765a96eed09a558dac3cc907c7fd2 | 22,479 | hpp | C++ | include/BStringt.hpp | ANOTHEL/Awesome-mix-vol.1 | 58134a7300ce057343d622511600623eaae10042 | [
"Apache-2.0"
] | null | null | null | include/BStringt.hpp | ANOTHEL/Awesome-mix-vol.1 | 58134a7300ce057343d622511600623eaae10042 | [
"Apache-2.0"
] | null | null | null | include/BStringt.hpp | ANOTHEL/Awesome-mix-vol.1 | 58134a7300ce057343d622511600623eaae10042 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021~2022 `anothel` All rights reserved
#ifndef BSTRINGT_HPP_
#define BSTRINGT_HPP_
#include "include/amvalloc.hpp"
#include "include/amvcore.hpp"
#include "include/amvsimpstr.hpp"
#include "salieri-src/salieri.h"
namespace AMV {
template <typename BaseType, class StringTraits>
class BStringT : public CSimpleStringT<BaseType> {
public:
typedef CSimpleStringT<BaseType> CThisSimpleString;
typedef StringTraits StrTraits;
public:
BStringT() throw() : CThisSimpleString(StringTraits::GetDefaultManager()) {}
explicit BStringT(_In_ IAmvStringMgr* pStringMgr) throw()
: CThisSimpleString(pStringMgr) {}
// Copy constructor
// explicit BStringT(_In_ const BStringT& strSrc) : CThisSimpleString(strSrc)
// {}
/* Todo(jpk, 20220118): 파라미터가 한개이기 때문에 explicit를 걸어서 암시적
* 형변환을 막아야 한다면 이 상황에서는 처치할 수가 없음 */
BStringT(_In_ const BStringT& strSrc) : CThisSimpleString(strSrc) {}
// // Construct from CSimpleStringT
// operator CSimpleStringT<BaseType>&() {
//
// return *(CSimpleStringT<BaseType>*)this;
// }
explicit BStringT(_In_ const CSimpleStringT<BaseType>& strSrc)
: CThisSimpleString(strSrc) {}
explicit BStringT(_In_opt_z_ const char* pszSrc)
: CThisSimpleString(StringTraits::GetDefaultManager()) {
*this = pszSrc;
}
BStringT(_In_opt_z_ const char* pszSrc, _In_ IAmvStringMgr* pStringMgr)
: CThisSimpleString(pStringMgr) {
*this = pszSrc;
}
BStringT(_In_opt_z_ const unsigned char* pszSrc,
_In_ IAmvStringMgr* pStringMgr)
: CThisSimpleString(pStringMgr) {
*this = reinterpret_cast<const char*>(pszSrc);
}
BStringT(_In_reads_(nLength) const unsigned char* puch, _In_ int nLength)
: CThisSimpleString(puch, nLength, StringTraits::GetDefaultManager()) {}
// Destructor
~BStringT() throw() {}
// Assignment operators
BStringT& operator=(_In_ const BStringT& strSrc) {
CThisSimpleString::operator=(strSrc);
return (*this);
}
BStringT& operator=(_In_ const CSimpleStringT<BaseType>& strSrc) {
CThisSimpleString::operator=(strSrc);
return (*this);
}
BStringT& operator=(_In_opt_z_ const char* pszSrc) {
CThisSimpleString::operator=(pszSrc);
return (*this);
}
BStringT& operator=(_In_ char ch) {
char ach[2] = {ch, 0};
return (operator=(ach));
}
BStringT& operator+=(_In_ const CThisSimpleString& str) {
CThisSimpleString::operator+=(str);
return (*this);
}
BStringT& operator+=(_In_z_ const char* pszSrc) {
CThisSimpleString::operator+=(pszSrc);
return (*this);
}
template <int t_nSize>
BStringT& operator+=(_In_ const CStaticString<char, t_nSize>& strSrc) {
CThisSimpleString::operator+=(strSrc);
return (*this);
}
BStringT& operator+=(_In_ char ch) {
CThisSimpleString::operator+=(ch);
return (*this);
}
BStringT& operator+=(_In_ unsigned char ch) {
CThisSimpleString::operator+=(ch);
return (*this);
}
// Override from base class
IAmvStringMgr* GetManager() const throw() {
IAmvStringMgr* pStringMgr = CThisSimpleString::GetManager();
if (pStringMgr) {
return pStringMgr;
}
return StringTraits::GetDefaultManager()->Clone();
}
// Comparison
int Compare(_In_z_ const char* psz) const {
AMVENSURE(AmvIsValidString(psz));
// AmvIsValidString guarantees that psz != NULL
return (StringTraits::StringCompare(this->GetString(), psz));
}
int CompareNoCase(_In_z_ const char* psz) const {
AMVENSURE(AmvIsValidString(psz));
// AmvIsValidString guarantees that psz != NULL
return (StringTraits::StringCompareIgnore(this->GetString(), psz));
}
// Advanced manipulation
// Delete 'nCount' characters, starting at index 'iIndex'
int Delete(_In_ int iIndex, _In_ int nCount = 1) {
if (iIndex < 0) iIndex = 0;
if (nCount < 0) nCount = 0;
int nLength = this->GetLength();
if ((::AMV::AmvAddThrow(nCount, iIndex)) > nLength) {
nCount = nLength - iIndex;
}
if (nCount > 0) {
int nNewLength = nLength - nCount;
int nXCHARsToCopy = nLength - (iIndex + nCount) + 1;
char* pszBuffer = this->GetBuffer();
memmove_s(pszBuffer + iIndex, nXCHARsToCopy * sizeof(char),
pszBuffer + iIndex + nCount, nXCHARsToCopy * sizeof(char));
this->ReleaseBufferSetLength(nNewLength);
}
return (this->GetLength());
}
// Insert character 'ch' before index 'iIndex'
int Insert(_In_ int iIndex, _In_ char ch) {
if (iIndex < 0) iIndex = 0;
if (iIndex > this->GetLength()) {
iIndex = this->GetLength();
}
int nNewLength = this->GetLength() + 1;
char* pszBuffer = this->GetBuffer(nNewLength);
// move existing bytes down
memmove_s(pszBuffer + iIndex + 1, (nNewLength - iIndex) * sizeof(char),
pszBuffer + iIndex, (nNewLength - iIndex) * sizeof(char));
pszBuffer[iIndex] = ch;
this->ReleaseBufferSetLength(nNewLength);
return (nNewLength);
}
// Insert string 'psz' before index 'iIndex'
int Insert(_In_ int iIndex, _In_z_ const char* psz) {
if (iIndex < 0) iIndex = 0;
if (iIndex > this->GetLength()) {
iIndex = this->GetLength();
}
// nInsertLength and nNewLength are in XCHARs
int nInsertLength = StringTraits::SafeStringLen(psz);
int nNewLength = this->GetLength();
if (nInsertLength > 0) {
nNewLength += nInsertLength;
char* pszBuffer = this->GetBuffer(nNewLength);
// move existing bytes down
memmove_s(pszBuffer + iIndex + nInsertLength,
(nNewLength - iIndex - nInsertLength + 1) * sizeof(char),
pszBuffer + iIndex,
(nNewLength - iIndex - nInsertLength + 1) * sizeof(char));
memcpy_s(pszBuffer + iIndex, nInsertLength * sizeof(char), psz,
nInsertLength * sizeof(char));
this->ReleaseBufferSetLength(nNewLength);
}
return (nNewLength);
}
// Replace all occurrences of character 'chOld' with character 'chNew'
int Replace(_In_ char chOld, _In_ char chNew) {
int nCount = 0;
// short-circuit the nop case
if (chOld != chNew) {
// otherwise modify each character that matches in the string
bool bCopied = false;
// We don't actually write to pszBuffer until we've called GetBuffer().
char* pszBuffer = const_cast<char*>(this->GetString());
int nLength = this->GetLength();
int iChar = 0;
while (iChar < nLength) {
// replace instances of the specified character only
if (pszBuffer[iChar] == chOld) {
if (!bCopied) {
bCopied = true;
pszBuffer = this->GetBuffer(nLength);
}
pszBuffer[iChar] = chNew;
nCount++;
}
iChar = static_cast<int>(StringTraits::CharNext(pszBuffer + iChar) -
pszBuffer);
}
if (bCopied) {
this->ReleaseBufferSetLength(nLength);
}
}
return (nCount);
}
// Replace all occurrences of string 'pszOld' with string 'pszNew'
int Replace(_In_z_ const char* pszOld, _In_z_ const char* pszNew) {
// can't have empty or NULL lpszOld
// nSourceLen is in XCHARs
int nSourceLen = StringTraits::SafeStringLen(pszOld);
if (nSourceLen == 0) return (0);
// nReplacementLen is in XCHARs
int nReplacementLen = StringTraits::SafeStringLen(pszNew);
// loop once to figure out the size of the result string
int nCount = 0;
{
const char* pszStart = this->GetString();
const char* pszEnd = pszStart + this->GetLength();
while (pszStart < pszEnd) {
const char* pszTarget;
while ((pszTarget = StringTraits::StringFindString(pszStart, pszOld)) !=
NULL) {
nCount++;
pszStart = pszTarget + nSourceLen;
}
pszStart += StringTraits::SafeStringLen(pszStart) + 1;
}
}
// if any changes were made, make them
if (nCount > 0) {
// if the buffer is too small, just allocate a new buffer (slow but sure)
int nOldLength = this->GetLength();
int nNewLength = nOldLength + (nReplacementLen - nSourceLen) * nCount;
char* pszBuffer = this->GetBuffer(__max(nNewLength, nOldLength));
char* pszStart = pszBuffer;
char* pszEnd = pszStart + nOldLength;
// loop again to actually do the work
while (pszStart < pszEnd) {
char* pszTarget;
while ((pszTarget = StringTraits::StringFindString(pszStart, pszOld)) !=
NULL) {
int nBalance =
nOldLength - static_cast<int>(pszTarget - pszBuffer + nSourceLen);
memmove_s(pszTarget + nReplacementLen, nBalance * sizeof(char),
pszTarget + nSourceLen, nBalance * sizeof(char));
memcpy_s(pszTarget, nReplacementLen * sizeof(char), pszNew,
nReplacementLen * sizeof(char));
pszStart = pszTarget + nReplacementLen;
pszTarget[nReplacementLen + nBalance] = 0;
nOldLength += (nReplacementLen - nSourceLen);
}
pszStart += StringTraits::SafeStringLen(pszStart) + 1;
}
AMVASSERT(pszBuffer[nNewLength] == 0);
this->ReleaseBufferSetLength(nNewLength);
}
return (nCount);
}
// Remove all occurrences of character 'chRemove'
int Remove(_In_ char chRemove) {
int nLength = this->GetLength();
char* pszBuffer = this->GetBuffer(nLength);
char* pszSource = pszBuffer;
char* pszDest = pszBuffer;
char* pszEnd = pszBuffer + nLength;
while (pszSource < pszEnd) {
char* pszNewSource = StringTraits::CharNext(pszSource);
if (*pszSource != chRemove) {
/* Copy the source to the destination. Remember to copy all bytes of an
* MBCS character */
size_t NewSourceGap = (pszNewSource - pszSource);
char* pszNewDest = pszDest + NewSourceGap;
size_t i = 0;
for (i = 0; pszDest != pszNewDest && i < NewSourceGap; i++) {
*pszDest = *pszSource;
pszSource++;
pszDest++;
}
}
pszSource = pszNewSource;
}
*pszDest = 0;
int nCount = static_cast<int>(pszSource - pszDest);
this->ReleaseBufferSetLength(nLength - nCount);
return (nCount);
}
// find routines
// Find the first occurrence of character 'ch', starting at index 'iStart'
int Find(_In_ char ch, _In_ int iStart = 0) const throw() {
// iStart is in XCHARs
AMVASSERT(iStart >= 0);
// nLength is in XCHARs
int nLength = this->GetLength();
if (iStart < 0 || iStart >= nLength) {
return (-1);
}
// find first single character
const char* psz =
StringTraits::StringFindChar(this->GetString() + iStart, ch);
// return -1 if not found and index otherwise
return ((psz == NULL) ? -1 : static_cast<int>(psz - this->GetString()));
}
// look for a specific sub-string
// Find the first occurrence of string 'pszSub', starting at index 'iStart'
int Find(_In_z_ const char* pszSub, _In_ int iStart = 0) const throw() {
// iStart is in XCHARs
AMVASSERT(iStart >= 0);
AMVASSERT(AmvIsValidString(pszSub));
if (pszSub == NULL) {
return (-1);
}
// nLength is in XCHARs
int nLength = this->GetLength();
if (iStart < 0 || iStart > nLength) {
return (-1);
}
// find first matching substring
const char* psz =
StringTraits::StringFindString(this->GetString() + iStart, pszSub);
// return -1 for not found, distance from beginning otherwise
return ((psz == NULL) ? -1 : static_cast<int>(psz - this->GetString()));
}
// Find the first occurrence of any of the characters in string 'pszCharSet'
int FindOneOf(_In_z_ const char* pszCharSet) const throw() {
AMVASSERT(AmvIsValidString(pszCharSet));
const char* psz =
StringTraits::StringScanSet(this->GetString(), pszCharSet);
return ((psz == NULL) ? -1 : static_cast<int>(psz - this->GetString()));
}
// Find the last occurrence of character 'ch'
int ReverseFind(_In_ char ch) const throw() {
// find last single character
const char* psz = StringTraits::StringFindCharRev(this->GetString(), ch);
// return -1 if not found, distance from beginning otherwise
return ((psz == NULL) ? -1 : static_cast<int>(psz - this->GetString()));
}
// trimming
// Remove all trailing whitespace
BStringT& TrimRight() {
// find beginning of trailing spaces by starting at beginning (DBCS aware)
const char* psz = this->GetString();
const char* pszLast = NULL;
while (*psz != 0) {
if (StringTraits::IsSpace(*psz)) {
if (pszLast == NULL) pszLast = psz;
} else {
pszLast = NULL;
}
psz = StringTraits::CharNext(psz);
}
if (pszLast != NULL) {
// truncate at trailing space start
int iLast = static_cast<int>(pszLast - this->GetString());
this->Truncate(iLast);
}
return (*this);
}
// Remove all leading whitespace
BStringT& TrimLeft() {
// find first non-space character
const char* psz = this->GetString();
while (StringTraits::IsSpace(*psz)) {
psz = StringTraits::CharNext(psz);
}
if (psz != this->GetString()) {
// fix up data and length
int iFirst = static_cast<int>(psz - this->GetString());
char* pszBuffer = this->GetBuffer(this->GetLength());
psz = pszBuffer + iFirst;
int nDataLength = this->GetLength() - iFirst;
memmove_s(pszBuffer, (this->GetLength() + 1) * sizeof(char), psz,
(nDataLength + 1) * sizeof(char));
this->ReleaseBufferSetLength(nDataLength);
}
return (*this);
}
// Remove all leading and trailing whitespace
BStringT& Trim() { return (TrimRight().TrimLeft()); }
// Remove all leading and trailing occurrences of character 'chTarget'
BStringT& Trim(_In_ char chTarget) {
return (TrimRight(chTarget).TrimLeft(chTarget));
}
/* Remove all leading and trailing occurrences of any of the characters in the
* string 'pszTargets' */
BStringT& Trim(_In_z_ const char* pszTargets) {
return (TrimRight(pszTargets).TrimLeft(pszTargets));
}
void Print() {
printf("%s\n", this->GetString());
return;
}
// trimming anything (either side)
// Remove all trailing occurrences of character 'chTarget'
BStringT& TrimRight(_In_ char chTarget) {
// find beginning of trailing matches
// by starting at beginning (DBCS aware)
const char* psz = this->GetString();
const char* pszLast = NULL;
while (*psz != 0) {
if (*psz == chTarget) {
if (pszLast == NULL) {
pszLast = psz;
}
} else {
pszLast = NULL;
}
psz = StringTraits::CharNext(psz);
}
if (pszLast != NULL) {
// truncate at left-most matching character
int iLast = static_cast<int>(pszLast - this->GetString());
this->Truncate(iLast);
}
return (*this);
}
/* Remove all trailing occurrences of any of the characters in string
* 'pszTargets' */
BStringT& TrimRight(_In_z_ const char* pszTargets) {
// if we're not trimming anything, we're not doing any work
if ((pszTargets == NULL) || (*pszTargets == 0)) {
return (*this);
}
// find beginning of trailing matches
// by starting at beginning (DBCS aware)
const char* psz = this->GetString();
const char* pszLast = NULL;
while (*psz != 0) {
if (StringTraits::StringFindChar(pszTargets, *psz) != NULL) {
if (pszLast == NULL) {
pszLast = psz;
}
} else {
pszLast = NULL;
}
psz = StringTraits::CharNext(psz);
}
if (pszLast != NULL) {
// truncate at left-most matching character
int iLast = static_cast<int>(pszLast - this->GetString());
this->Truncate(iLast);
}
return (*this);
}
// Remove all leading occurrences of character 'chTarget'
BStringT& TrimLeft(_In_ char chTarget) {
// find first non-matching character
const char* psz = this->GetString();
while (chTarget == *psz) {
psz = StringTraits::CharNext(psz);
}
if (psz != this->GetString()) {
// fix up data and length
int iFirst = static_cast<int>(psz - this->GetString());
char* pszBuffer = this->GetBuffer(this->GetLength());
psz = pszBuffer + iFirst;
int nDataLength = this->GetLength() - iFirst;
memmove_s(pszBuffer, (this->GetLength() + 1) * sizeof(char), psz,
(nDataLength + 1) * sizeof(char));
this->ReleaseBufferSetLength(nDataLength);
}
return (*this);
}
/* Remove all leading occurrences of any of the characters in string
* 'pszTargets' */
BStringT& TrimLeft(_In_z_ const char* pszTargets) {
// if we're not trimming anything, we're not doing any work
if ((pszTargets == NULL) || (*pszTargets == 0)) {
return (*this);
}
const char* psz = this->GetString();
while ((*psz != 0) &&
(StringTraits::StringFindChar(pszTargets, *psz) != NULL)) {
psz = StringTraits::CharNext(psz);
}
if (psz != this->GetString()) {
// fix up data and length
int iFirst = static_cast<int>(psz - this->GetString());
char* pszBuffer = this->GetBuffer(this->GetLength());
psz = pszBuffer + iFirst;
int nDataLength = this->GetLength() - iFirst;
memmove_s(pszBuffer, (this->GetLength() + 1) * sizeof(char), psz,
(nDataLength + 1) * sizeof(char));
this->ReleaseBufferSetLength(nDataLength);
}
return (*this);
}
friend BStringT operator+(_In_ const BStringT& str1,
_In_ const BStringT& str2) {
BStringT strResult(str1.GetManager());
CThisSimpleString::Concatenate(strResult, str1, str1.GetLength(), str2,
str2.GetLength());
return (strResult);
}
friend BStringT operator+(_In_ const BStringT& str1,
_In_z_ const char* psz2) {
BStringT strResult(str1.GetManager());
CThisSimpleString::Concatenate(strResult, str1, str1.GetLength(), psz2,
CThisSimpleString::StringLength(psz2));
return (strResult);
}
friend BStringT operator+(_In_z_ const char* psz1,
_In_ const BStringT& str2) {
BStringT strResult(str2.GetManager());
CThisSimpleString::Concatenate(strResult, psz1,
CThisSimpleString::StringLength(psz1), str2,
str2.GetLength());
return (strResult);
}
friend BStringT operator+(_In_ const BStringT& str1, _In_ char ch2) {
BStringT strResult(str1.GetManager());
CThisSimpleString::Concatenate(strResult, str1, str1.GetLength(), &ch2, 1);
return (strResult);
}
friend BStringT operator+(_In_ char ch1, _In_ const BStringT& str2) {
BStringT strResult(str2.GetManager());
CThisSimpleString::Concatenate(strResult, &ch1, 1, str2, str2.GetLength());
return (strResult);
}
friend bool operator==(_In_ const BStringT& str1,
_In_ const BStringT& str2) throw() {
return (str1.Compare(str2) == 0);
}
friend bool operator==(_In_ const BStringT& str1,
_In_z_ const char* psz2) throw() {
return (str1.Compare(psz2) == 0);
}
friend bool operator==(_In_z_ const char* psz1,
_In_ const BStringT& str2) throw() {
return (str2.Compare(psz1) == 0);
}
friend bool operator!=(_In_ const BStringT& str1,
_In_ const BStringT& str2) throw() {
return (str1.Compare(str2) != 0);
}
friend bool operator!=(_In_ const BStringT& str1,
_In_z_ const char* psz2) throw() {
return (str1.Compare(psz2) != 0);
}
friend bool operator!=(_In_z_ const char* psz1,
_In_ const BStringT& str2) throw() {
return (str2.Compare(psz1) != 0);
}
friend bool operator<(_In_ const BStringT& str1,
_In_ const BStringT& str2) throw() {
return (str1.Compare(str2) < 0);
}
friend bool operator<(_In_ const BStringT& str1,
_In_z_ const char* psz2) throw() {
return (str1.Compare(psz2) < 0);
}
friend bool operator<(_In_z_ const char* psz1,
_In_ const BStringT& str2) throw() {
return (str2.Compare(psz1) > 0);
}
friend bool operator>(_In_ const BStringT& str1,
_In_ const BStringT& str2) throw() {
return (str1.Compare(str2) > 0);
}
friend bool operator>(_In_ const BStringT& str1,
_In_z_ const char* psz2) throw() {
return (str1.Compare(psz2) > 0);
}
friend bool operator>(_In_z_ const char* psz1,
_In_ const BStringT& str2) throw() {
return (str2.Compare(psz1) < 0);
}
friend bool operator<=(_In_ const BStringT& str1,
_In_ const BStringT& str2) throw() {
return (str1.Compare(str2) <= 0);
}
friend bool operator<=(_In_ const BStringT& str1,
_In_z_ const char* psz2) throw() {
return (str1.Compare(psz2) <= 0);
}
friend bool operator<=(_In_z_ const char* psz1,
_In_ const BStringT& str2) throw() {
return (str2.Compare(psz1) >= 0);
}
friend bool operator>=(_In_ const BStringT& str1,
_In_ const BStringT& str2) throw() {
return (str1.Compare(str2) >= 0);
}
friend bool operator>=(_In_ const BStringT& str1,
_In_z_ const char* psz2) throw() {
return (str1.Compare(psz2) >= 0);
}
friend bool operator>=(_In_z_ const char* psz1,
_In_ const BStringT& str2) throw() {
return (str2.Compare(psz1) <= 0);
}
friend bool operator==(_In_ char ch1, _In_ const BStringT& str2) throw() {
return ((str2.GetLength() == 1) && (str2[0] == ch1));
}
friend bool operator==(_In_ const BStringT& str1, _In_ char ch2) throw() {
return ((str1.GetLength() == 1) && (str1[0] == ch2));
}
friend bool operator!=(_In_ char ch1, _In_ const BStringT& str2) throw() {
return ((str2.GetLength() != 1) || (str2[0] != ch1));
}
friend bool operator!=(_In_ const BStringT& str1, _In_ char ch2) throw() {
return ((str1.GetLength() != 1) || (str1[0] != ch2));
}
};
} // namespace AMV
#endif // BSTRINGT_HPP_
| 30.132708 | 80 | 0.615196 | ANOTHEL |
9e3671d34f079f3ffe3b580e1f08082deb37ef71 | 177 | cpp | C++ | TestComponent/Class.cpp | jkotas/TestWinRT | e7682136641caf9713268761ec8188ca452e85f9 | [
"MIT"
] | 14 | 2019-10-29T02:39:37.000Z | 2022-02-21T03:45:58.000Z | TestComponent/Class.cpp | jkotas/TestWinRT | e7682136641caf9713268761ec8188ca452e85f9 | [
"MIT"
] | 24 | 2020-01-30T16:28:35.000Z | 2022-03-17T15:50:45.000Z | TestComponent/Class.cpp | jkotas/TestWinRT | e7682136641caf9713268761ec8188ca452e85f9 | [
"MIT"
] | 8 | 2019-10-31T13:51:54.000Z | 2021-10-10T21:29:44.000Z | #include "pch.h"
#include "Class.h"
#include "Class.g.cpp"
namespace winrt::TestComponent::implementation
{
int32_t Class::One()
{
return 1;
}
}
| 14.75 | 47 | 0.581921 | jkotas |
9e38b73cce6b3c456e9db8140791c625fa05cf02 | 6,145 | cpp | C++ | src/IKSolverRT.cpp | GuillaumeVDu/RTIKIDQualisys | 9b70e2c0eb1f3492f74119c4339a6f5404ede290 | [
"MIT"
] | 2 | 2019-07-25T18:11:13.000Z | 2019-09-08T16:02:23.000Z | src/IKSolverRT.cpp | GuillaumeVDu/RTIKIDQualisys | 9b70e2c0eb1f3492f74119c4339a6f5404ede290 | [
"MIT"
] | null | null | null | src/IKSolverRT.cpp | GuillaumeVDu/RTIKIDQualisys | 9b70e2c0eb1f3492f74119c4339a6f5404ede290 | [
"MIT"
] | null | null | null | // Copyright (c) 2015, Guillaume Durandau and Massimo Sartori
// 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.
#include "IKSolverRT.h"
IKSolverRT::IKSolverRT(const OpenSim::Model &model, const std::vector<std::string>& markerNames,
const std::vector<double>& markerWeights, double constraintWeight) :
Solver(model), markerNames_(markerNames), markerWeights_(markerWeights), constraintWeight_(constraintWeight), enforceContraint_(
false)
{
assembler_ = NULL;
accuracy_ = 1e-4;
}
IKSolverRT::~IKSolverRT()
{
delete assembler_;
//delete markerAssemblyCondition_;
}
void IKSolverRT::setupGoals(SimTK::State &s)
{
// Setup coordinates performed by the base class
// Crate the IK solver.
//delete assembler_;
assembler_ = new SimTK::Assembler(getModel().getMultibodySystem());
// Set Accuracy of the IK.
assembler_->setAccuracy(accuracy_);
// Set the Assembler weight.
assembler_->setSystemConstraintsWeight(constraintWeight_);
// Enforce the constraint limit of each joint, if needed.
if (enforceContraint_)
{
// Get model coordinates.
const OpenSim::CoordinateSet &modelCoordSet = getModel().getCoordinateSet();
// Restrict solution to set range of any of the coordinates that are clamped.
for (int i = 0; i < modelCoordSet.getSize(); ++i)
{
const OpenSim::Coordinate& coord = modelCoordSet[i];
if (coord.getClamped(s))
{
assembler_->restrictQ(coord.getBodyIndex(), SimTK::MobilizerQIndex(coord.getMobilizerQIndex()),
coord.getRangeMin(), coord.getRangeMax());
}
}
}
// Create the markers for the IK solver.
markerAssemblyCondition_ = new SimTK::Markers();
// get markers defined by the model
const OpenSim::MarkerSet &modelMarkerSet = getModel().getMarkerSet();
int index = -1;
// Loop through all markers in the reference.
for (std::vector<std::string>::const_iterator it1 = markerNames_.begin(); it1 != markerNames_.end(); it1++)
{
// Check if we have this marker in the model, else ignore it
index = modelMarkerSet.getIndex(*it1, index);
if (index >= 0)
{
const OpenSim::Marker &marker = modelMarkerSet.get(*it1);
const SimTK::MobilizedBody &mobod = getModel().getMatterSubsystem().getMobilizedBody(
marker.getBody().getIndex());
markerAssemblyCondition_->addMarker(marker.getName(), mobod, marker.getOffset(),
markerWeights_[std::distance<std::vector<std::string>::const_iterator>(markerNames_.begin(), it1)]);
}
}
// Add marker goal to the IK objective.
assembler_->adoptAssemblyGoal(markerAssemblyCondition_);
// lock-in the order that the observations (markers) are in and this cannot change from frame to frame
// and we can use an array of just the data for updating
markerAssemblyCondition_->defineObservationOrder(markerNames_);
updateGoals(s);
}
void IKSolverRT::updateGoals(const SimTK::State &s)
{
// update coordinates performed by the base class
markerAssemblyCondition_->moveAllObservations(markerValues_);
}
void IKSolverRT::assemble(SimTK::State &state)
{
// Make a working copy of the state that will be used to set the internal state of the solver
// This is necessary because we may wish to disable redundant constraints, but do not want this
// to effect the state of constraints the user expects
SimTK::State s = state;
// Make sure goals are up-to-date.
setupGoals(s);
// Let assembler perform some internal setup
assembler_->initialize(s);
try
{
// Now do the assembly and return the updated state.
assembler_->assemble();
// Update the q's in the state passed in
assembler_->updateFromInternalState(s);
state.updQ() = s.getQ();
state.updU() = s.getU();
// Get model coordinates
const OpenSim::CoordinateSet &modelCoordSet = getModel().getCoordinateSet();
// Make sure the locks in original state are restored
for (int i = 0; i < modelCoordSet.getSize(); ++i)
{
bool isLocked = modelCoordSet[i].getLocked(state);
if (isLocked)
modelCoordSet[i].setLocked(state, isLocked);
}
} catch (const std::exception& ex)
{
std::string msg = "AssemblySolver::assemble() Failed: ";
msg += ex.what();
throw OpenSim::Exception(msg);
}
}
void IKSolverRT::track(SimTK::State &s)
{
// move the target locations or angles, etc... just do not change number of goals
// and their type (constrained vs. weighted)
if (assembler_ && assembler_->isInitialized())
{
updateGoals(s);
}
else
{
throw OpenSim::Exception("AssemblySolver::track() failed: assemble() must be called first.");
}
try
{
// Now do the assembly and return the updated state.
assembler_->track(s.getTime());
// update the state from the result of the assembler
assembler_->updateFromInternalState(s);
} catch (const std::exception& ex)
{
std::cout << "AssemblySolver::track() attempt Failed: " << ex.what() << std::endl;
throw OpenSim::Exception("AssemblySolver::track() attempt failed.");
}
}
| 33.579235 | 130 | 0.732954 | GuillaumeVDu |
9e3d12fb5ec3726a9bc8b01bfde2273c6ed4b9f5 | 2,779 | cpp | C++ | src/Switch.System.Drawing/src/Switch/System/Drawing/FontFamily.cpp | victor-timoshin/Switch | 8e8e687a8bdc4f79d482680da3968e9b3e464b8b | [
"MIT"
] | 4 | 2020-02-11T13:22:58.000Z | 2022-02-24T00:37:43.000Z | src/Switch.System.Drawing/src/Switch/System/Drawing/FontFamily.cpp | sgf/Switch | 8e8e687a8bdc4f79d482680da3968e9b3e464b8b | [
"MIT"
] | null | null | null | src/Switch.System.Drawing/src/Switch/System/Drawing/FontFamily.cpp | sgf/Switch | 8e8e687a8bdc4f79d482680da3968e9b3e464b8b | [
"MIT"
] | 2 | 2020-02-01T02:19:01.000Z | 2021-12-30T06:44:00.000Z | #include <Switch/System/Collections/Generic/List.hpp>
#include <Switch/System/NotImplementedException.hpp>
#include "../../../../include/Switch/System/Drawing/FontFamily.hpp"
#include "../../../../include/Switch/System/Drawing/Text/InstalledFontCollection.hpp"
#include "../../../Native/Api.hpp"
System::Drawing::FontFamily::FontFamily(const string& name) {
if (name == "") throw ArgumentException(caller_);
*this = Native::FontFamilyApi::GetFontFamilyFromName(name);
}
System::Drawing::FontFamily::FontFamily(System::Drawing::Text::GenericFontFamilies genericFamily) {
if (genericFamily == System::Drawing::Text::GenericFontFamilies::Serif)
*this = System::Drawing::FontFamily(Native::FontFamilyApi::GenericFontFamilySerifName());
else if (genericFamily == System::Drawing::Text::GenericFontFamilies::SansSerif)
*this = System::Drawing::FontFamily(Native::FontFamilyApi::GenericFontFamilySansSerifName());
else
*this = System::Drawing::FontFamily(Native::FontFamilyApi::GenericFontFamilyMonospaceName());
}
System::Drawing::FontFamily::FontFamily(const string& name, const System::Drawing::Text::FontCollection& fontCollection) {
for (FontFamily fontFamily : fontCollection.Families())
if (name == fontFamily.Name) {
*this = fontFamily;
return;
}
throw ArgumentException(caller_);
}
System::Drawing::FontFamily::~FontFamily() {
if (this->data.IsUnique())
Native::FontFamilyApi::ReleaseResource(this->data().handle);
}
property_<System::Array<System::Drawing::FontFamily>, readonly_> System::Drawing::FontFamily::Families {
[] {return System::Drawing::Text::InstalledFontCollection().Families();}
};
property_<System::Drawing::FontFamily, readonly_> System::Drawing::FontFamily::GenericMonospace {
[] {return FontFamily(System::Drawing::Text::GenericFontFamilies::Monospace);}
};
property_<System::Drawing::FontFamily, readonly_> System::Drawing::FontFamily::GenericSansSerif {
[] {return FontFamily(System::Drawing::Text::GenericFontFamilies::SansSerif);}
};
property_<System::Drawing::FontFamily, readonly_> System::Drawing::FontFamily::GenericSerif {
[] {return FontFamily(System::Drawing::Text::GenericFontFamilies::Serif);}
};
int32 System::Drawing::FontFamily::GetCellAscent(FontStyle style) {
return Native::FontFamilyApi::GetCellAscent(this->GetName(), style);
}
int32 System::Drawing::FontFamily::GetCellDescent(FontStyle style) {
return Native::FontFamilyApi::GetCellDescent(this->GetName(), style);
}
string System::Drawing::FontFamily::GetName() const {
return Native::FontFamilyApi::GetName(this->data().handle);
}
bool System::Drawing::FontFamily::IsStyleAvailable(System::Drawing::FontStyle style) const {
return Native::FontFamilyApi::IsStyleAvailable(this->data().handle, style);
}
| 42.106061 | 122 | 0.74955 | victor-timoshin |
9e42d79251e7022f24660c2137062505dfc3b13b | 38,037 | cpp | C++ | server/ClientHandler.cpp | cjcliffe/SoapyRemote | aa8208879ef09c10350a1b4a95bd612ba544c50e | [
"BSL-1.0"
] | 1 | 2021-05-16T21:00:09.000Z | 2021-05-16T21:00:09.000Z | server/ClientHandler.cpp | cjcliffe/SoapyRemote | aa8208879ef09c10350a1b4a95bd612ba544c50e | [
"BSL-1.0"
] | null | null | null | server/ClientHandler.cpp | cjcliffe/SoapyRemote | aa8208879ef09c10350a1b4a95bd612ba544c50e | [
"BSL-1.0"
] | null | null | null | // Copyright (c) 2015-2015 Josh Blum
// SPDX-License-Identifier: BSL-1.0
#include "ClientHandler.hpp"
#include "ServerStreamData.hpp"
#include "LogForwarding.hpp"
#include "SoapyRemoteDefs.hpp"
#include "FormatToElemSize.hpp"
#include "SoapyURLUtils.hpp"
#include "SoapyRPCSocket.hpp"
#include "SoapyRPCPacker.hpp"
#include "SoapyRPCUnpacker.hpp"
#include "SoapyStreamEndpoint.hpp"
#include <SoapySDR/Device.hpp>
#include <SoapySDR/Logger.hpp>
#include <iostream>
#include <mutex>
//! The device factory make and unmake requires a process-wide mutex
static std::mutex factoryMutex;
/***********************************************************************
* Client handler constructor
**********************************************************************/
SoapyClientHandler::SoapyClientHandler(SoapyRPCSocket &sock):
_sock(sock),
_dev(nullptr),
_logForwarder(nullptr),
_nextStreamId(0)
{
return;
}
SoapyClientHandler::~SoapyClientHandler(void)
{
//stop all stream threads and close streams
for (auto &data : _streamData)
{
data.second.stopThreads();
_dev->closeStream(data.second.stream);
}
//release the device handle if we have it
if (_dev != nullptr)
{
std::lock_guard<std::mutex> lock(factoryMutex);
SoapySDR::Device::unmake(_dev);
_dev = nullptr;
}
//finally stop and cleanup log forwarding
delete _logForwarder;
}
/***********************************************************************
* Transaction handler
**********************************************************************/
bool SoapyClientHandler::handleOnce(void)
{
if (not _sock.selectRecv(SOAPY_REMOTE_SOCKET_TIMEOUT_US)) return true;
//receive the client's request
SoapyRPCUnpacker unpacker(_sock);
SoapyRPCPacker packer(_sock);
//handle the client's request
bool again = true;
try
{
again = this->handleOnce(unpacker, packer);
}
catch (const std::exception &ex)
{
packer & ex;
}
//send the result back
packer();
return again;
}
/***********************************************************************
* Handler dispatcher implementation
**********************************************************************/
bool SoapyClientHandler::handleOnce(SoapyRPCUnpacker &unpacker, SoapyRPCPacker &packer)
{
SoapyRemoteCalls call;
unpacker & call;
switch (call)
{
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_FIND:
////////////////////////////////////////////////////////////////////
{
SoapySDR::Kwargs args;
unpacker & args;
packer & SoapySDR::Device::enumerate(args);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_MAKE:
////////////////////////////////////////////////////////////////////
{
SoapySDR::Kwargs args;
unpacker & args;
std::lock_guard<std::mutex> lock(factoryMutex);
if (_dev == nullptr) _dev = SoapySDR::Device::make(args);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_UNMAKE:
////////////////////////////////////////////////////////////////////
{
std::lock_guard<std::mutex> lock(factoryMutex);
if (_dev != nullptr) SoapySDR::Device::unmake(_dev);
_dev = nullptr;
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_HANGUP:
////////////////////////////////////////////////////////////////////
{
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_SERVER_ID:
////////////////////////////////////////////////////////////////////
{
packer & uniqueProcessId();
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_START_LOG_FORWARDING:
////////////////////////////////////////////////////////////////////
{
if (_logForwarder == nullptr) _logForwarder = new SoapyLogForwarder(_sock);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_STOP_LOG_FORWARDING:
////////////////////////////////////////////////////////////////////
{
if (_logForwarder != nullptr) delete _logForwarder;
_logForwarder = nullptr;
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_DRIVER_KEY:
////////////////////////////////////////////////////////////////////
{
packer & _dev->getDriverKey();
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_HARDWARE_KEY:
////////////////////////////////////////////////////////////////////
{
packer & _dev->getHardwareKey();
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_HARDWARE_INFO:
////////////////////////////////////////////////////////////////////
{
packer & _dev->getHardwareInfo();
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_SET_FRONTEND_MAPPING:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
std::string mapping;
unpacker & direction;
unpacker & mapping;
_dev->setFrontendMapping(direction, mapping);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_FRONTEND_MAPPING:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
unpacker & direction;
packer & _dev->getFrontendMapping(direction);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_NUM_CHANNELS:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
unpacker & direction;
packer & int(_dev->getNumChannels(direction));
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_FULL_DUPLEX:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->getFullDuplex(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_SETUP_STREAM:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
std::string format;
std::vector<size_t> channels;
SoapySDR::Kwargs args;
std::string clientBindPort;
std::string statusBindPort;
unpacker & direction;
unpacker & format;
unpacker & channels;
unpacker & args;
unpacker & clientBindPort;
unpacker & statusBindPort;
//parse args for buffer configuration
size_t mtu = SOAPY_REMOTE_DEFAULT_ENDPOINT_MTU;
const auto mtuIt = args.find(SOAPY_REMOTE_KWARG_MTU);
if (mtuIt != args.end()) mtu = size_t(std::stod(mtuIt->second));
size_t window = SOAPY_REMOTE_DEFAULT_ENDPOINT_WINDOW;
const auto windowIt = args.find(SOAPY_REMOTE_KWARG_WINDOW);
if (windowIt != args.end()) window = size_t(std::stod(windowIt->second));
double priority = SOAPY_REMOTE_DEFAULT_THREAD_PRIORITY;
const auto priorityIt = args.find(SOAPY_REMOTE_KWARG_PRIORITY);
if (priorityIt != args.end()) priority = std::stod(priorityIt->second);
//create stream
auto stream = _dev->setupStream(direction, format, channels, args);
//load data structure
auto &data = _streamData[_nextStreamId];
data.streamId = _nextStreamId++;
data.device = _dev;
data.stream = stream;
data.format = format;
for (const auto chan : channels) data.chanMask |= (1 << chan);
data.priority = priority;
//extract socket node information
std::string serverBindPort;
std::string localNode, remoteNode;
std::string scheme, node, service;
splitURL(_sock.getsockname(), scheme, localNode, service);
splitURL(_sock.getpeername(), scheme, remoteNode, service);
//bind the stream socket to an automatic port
const auto bindURL = combineURL("udp", localNode, "0");
int ret = data.streamSock.bind(bindURL);
if (ret != 0)
{
const std::string errorMsg = data.streamSock.lastErrorMsg();
_streamData.erase(data.streamId);
throw std::runtime_error("SoapyRemote::setupStream("+bindURL+") -- bind FAIL: " + errorMsg);
}
SoapySDR::logf(SOAPY_SDR_INFO, "Server side stream bound to %s", data.streamSock.getsockname().c_str());
splitURL(data.streamSock.getsockname(), scheme, node, serverBindPort);
//connect the stream socket to the specified port
auto connectURL = combineURL("udp", remoteNode, clientBindPort);
ret = data.streamSock.connect(connectURL);
if (ret != 0)
{
const std::string errorMsg = data.streamSock.lastErrorMsg();
_streamData.erase(data.streamId);
throw std::runtime_error("SoapyRemote::setupStream("+connectURL+") -- connect FAIL: " + errorMsg);
}
SoapySDR::logf(SOAPY_SDR_INFO, "Server side stream connected to %s", data.streamSock.getpeername().c_str());
//connect the status socket to the specified port
connectURL = combineURL("udp", remoteNode, statusBindPort);
ret = data.statusSock.connect(connectURL);
if (ret != 0)
{
const std::string errorMsg = data.statusSock.lastErrorMsg();
_streamData.erase(data.streamId);
throw std::runtime_error("SoapyRemote::setupStream("+connectURL+") -- connect FAIL: " + errorMsg);
}
SoapySDR::logf(SOAPY_SDR_INFO, "Server side status connected to %s", data.statusSock.getpeername().c_str());
//create endpoint
data.endpoint = new SoapyStreamEndpoint(data.streamSock, data.statusSock,
direction == SOAPY_SDR_TX, channels.size(), formatToSize(format), mtu, window);
//start worker thread, this is not backwards,
//receive from device means using a send endpoint
//transmit to device means using a recv endpoint
if (direction == SOAPY_SDR_RX) data.startSendThread();
if (direction == SOAPY_SDR_TX) data.startRecvThread();
data.startStatThread();
packer & data.streamId;
packer & serverBindPort;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_CLOSE_STREAM:
////////////////////////////////////////////////////////////////////
{
int streamId = 0;
unpacker & streamId;
//cleanup data and stop worker thread
auto &data = _streamData.at(streamId);
data.stopThreads();
_dev->closeStream(data.stream);
_streamData.erase(streamId);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_ACTIVATE_STREAM:
////////////////////////////////////////////////////////////////////
{
int streamId = 0;
int flags = 0;
long long timeNs = 0;
int numElems = 0;
unpacker & streamId;
unpacker & flags;
unpacker & timeNs;
unpacker & numElems;
auto &data = _streamData.at(streamId);
packer & _dev->activateStream(data.stream, flags, timeNs, size_t(numElems));
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_DEACTIVATE_STREAM:
////////////////////////////////////////////////////////////////////
{
int streamId = 0;
int flags = 0;
long long timeNs = 0;
unpacker & streamId;
unpacker & flags;
unpacker & timeNs;
auto &data = _streamData.at(streamId);
packer & _dev->deactivateStream(data.stream, flags, timeNs);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_LIST_ANTENNAS:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->listAntennas(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_SET_ANTENNA:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
std::string name;
unpacker & direction;
unpacker & channel;
unpacker & name;
_dev->setAntenna(direction, channel, name);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_ANTENNA:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->getAntenna(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_HAS_DC_OFFSET_MODE:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->hasDCOffsetMode(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_SET_DC_OFFSET_MODE:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
bool automatic = false;
unpacker & direction;
unpacker & channel;
unpacker & automatic;
_dev->setDCOffsetMode(direction, channel, automatic);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_DC_OFFSET_MODE:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->getDCOffsetMode(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_HAS_DC_OFFSET:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->hasDCOffset(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_SET_DC_OFFSET:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
std::complex<double> offset;
unpacker & direction;
unpacker & channel;
unpacker & offset;
_dev->setDCOffset(direction, channel, offset);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_DC_OFFSET:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->getDCOffset(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_HAS_IQ_BALANCE_MODE:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->hasIQBalance(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_SET_IQ_BALANCE_MODE:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
std::complex<double> balance;
unpacker & direction;
unpacker & channel;
unpacker & balance;
_dev->setIQBalance(direction, channel, balance);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_IQ_BALANCE_MODE:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->getIQBalance(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_LIST_GAINS:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->listGains(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_SET_GAIN_MODE:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
bool automatic = false;
unpacker & direction;
unpacker & channel;
unpacker & automatic;
_dev->setGainMode(direction, channel, automatic);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_GAIN_MODE:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->getGainMode(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_SET_GAIN:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
double value = 0;
unpacker & direction;
unpacker & channel;
unpacker & value;
_dev->setGain(direction, channel, value);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_SET_GAIN_ELEMENT:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
std::string name;
double value = 0;
unpacker & direction;
unpacker & channel;
unpacker & name;
unpacker & value;
_dev->setGain(direction, channel, name, value);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_GAIN:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->getGain(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_GAIN_ELEMENT:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
std::string name;
unpacker & direction;
unpacker & channel;
unpacker & name;
packer & _dev->getGain(direction, channel, name);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_GAIN_RANGE:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->getGainRange(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_GAIN_RANGE_ELEMENT:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
std::string name;
unpacker & direction;
unpacker & channel;
unpacker & name;
packer & _dev->getGainRange(direction, channel, name);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_SET_FREQUENCY:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
double value = 0;
SoapySDR::Kwargs args;
unpacker & direction;
unpacker & channel;
unpacker & value;
unpacker & args;
_dev->setFrequency(direction, channel, value, args);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_SET_FREQUENCY_COMPONENT:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
std::string name;
double value = 0;
SoapySDR::Kwargs args;
unpacker & direction;
unpacker & channel;
unpacker & name;
unpacker & value;
unpacker & args;
_dev->setFrequency(direction, channel, name, value, args);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_FREQUENCY:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->getFrequency(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_FREQUENCY_COMPONENT:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
std::string name;
unpacker & direction;
unpacker & channel;
unpacker & name;
packer & _dev->getFrequency(direction, channel, name);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_LIST_FREQUENCIES:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->listFrequencies(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_FREQUENCY_RANGE:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->getFrequencyRange(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_FREQUENCY_RANGE_COMPONENT:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
std::string name;
unpacker & direction;
unpacker & channel;
unpacker & name;
packer & _dev->getFrequencyRange(direction, channel, name);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_SET_SAMPLE_RATE:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
double rate = 0;
unpacker & direction;
unpacker & channel;
unpacker & rate;
_dev->setSampleRate(direction, channel, rate);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_SAMPLE_RATE:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->getSampleRate(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_LIST_SAMPLE_RATES:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->listSampleRates(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_SET_BANDWIDTH:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
double bw = 0;
unpacker & direction;
unpacker & channel;
unpacker & bw;
_dev->setBandwidth(direction, channel, bw);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_BANDWIDTH:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->getBandwidth(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_LIST_BANDWIDTHS:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->listBandwidths(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_SET_MASTER_CLOCK_RATE:
////////////////////////////////////////////////////////////////////
{
double rate = 0;
unpacker & rate;
_dev->setMasterClockRate(rate);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_MASTER_CLOCK_RATE:
////////////////////////////////////////////////////////////////////
{
packer & _dev->getMasterClockRate();
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_LIST_CLOCK_SOURCES:
////////////////////////////////////////////////////////////////////
{
packer & _dev->listClockSources();
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_SET_CLOCK_SOURCE:
////////////////////////////////////////////////////////////////////
{
std::string source;
unpacker & source;
_dev->setClockSource(source);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_CLOCK_SOURCE:
////////////////////////////////////////////////////////////////////
{
packer & _dev->getClockSource();
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_LIST_TIME_SOURCES:
////////////////////////////////////////////////////////////////////
{
packer & _dev->listTimeSources();
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_SET_TIME_SOURCE:
////////////////////////////////////////////////////////////////////
{
std::string source;
unpacker & source;
_dev->setTimeSource(source);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_TIME_SOURCE:
////////////////////////////////////////////////////////////////////
{
packer & _dev->getTimeSource();
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_HAS_HARDWARE_TIME:
////////////////////////////////////////////////////////////////////
{
std::string what;
unpacker & what;
packer & _dev->hasHardwareTime(what);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_GET_HARDWARE_TIME:
////////////////////////////////////////////////////////////////////
{
std::string what;
unpacker & what;
packer & _dev->getHardwareTime(what);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_SET_HARDWARE_TIME:
////////////////////////////////////////////////////////////////////
{
long long timeNs = 0;
std::string what;
unpacker & timeNs;
unpacker & what;
_dev->setHardwareTime(timeNs, what);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_SET_COMMAND_TIME:
////////////////////////////////////////////////////////////////////
{
long long timeNs = 0;
std::string what;
unpacker & timeNs;
unpacker & what;
_dev->setCommandTime(timeNs, what);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_LIST_SENSORS:
////////////////////////////////////////////////////////////////////
{
packer & _dev->listSensors();
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_READ_SENSOR:
////////////////////////////////////////////////////////////////////
{
std::string name;
unpacker & name;
packer & _dev->readSensor(name);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_LIST_CHANNEL_SENSORS:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
unpacker & direction;
unpacker & channel;
packer & _dev->listSensors(direction, channel);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_READ_CHANNEL_SENSOR:
////////////////////////////////////////////////////////////////////
{
char direction = 0;
int channel = 0;
std::string name;
unpacker & direction;
unpacker & channel;
unpacker & name;
packer & _dev->readSensor(direction, channel, name);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_WRITE_REGISTER:
////////////////////////////////////////////////////////////////////
{
int addr = 0;
int value = 0;
unpacker & addr;
unpacker & value;
_dev->writeRegister(unsigned(addr), unsigned(value));
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_READ_REGISTER:
////////////////////////////////////////////////////////////////////
{
int addr = 0;
unpacker & addr;
packer & int(_dev->readRegister(unsigned(addr)));
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_WRITE_SETTING:
////////////////////////////////////////////////////////////////////
{
std::string key;
std::string value;
unpacker & key;
unpacker & value;
_dev->writeSetting(key, value);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_READ_SETTING:
////////////////////////////////////////////////////////////////////
{
std::string key;
unpacker & key;
packer & _dev->readSetting(key);
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_LIST_GPIO_BANKS:
////////////////////////////////////////////////////////////////////
{
packer & _dev->listGPIOBanks();
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_WRITE_GPIO:
////////////////////////////////////////////////////////////////////
{
std::string bank;
int value = 0;
unpacker & bank;
unpacker & value;
_dev->writeGPIO(bank, unsigned(value));
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_WRITE_GPIO_MASKED:
////////////////////////////////////////////////////////////////////
{
std::string bank;
int value = 0;
int mask = 0;
unpacker & bank;
unpacker & value;
unpacker & mask;
_dev->writeGPIO(bank, unsigned(value), unsigned(mask));
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_READ_GPIO:
////////////////////////////////////////////////////////////////////
{
std::string bank;
unpacker & bank;
packer & int(_dev->readGPIO(bank));
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_WRITE_GPIO_DIR:
////////////////////////////////////////////////////////////////////
{
std::string bank;
int dir = 0;
unpacker & bank;
unpacker & dir;
_dev->writeGPIODir(bank, unsigned(dir));
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_WRITE_GPIO_DIR_MASKED:
////////////////////////////////////////////////////////////////////
{
std::string bank;
int dir = 0;
int mask = 0;
unpacker & bank;
unpacker & dir;
unpacker & mask;
_dev->writeGPIODir(bank, unsigned(dir), unsigned(mask));
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_READ_GPIO_DIR:
////////////////////////////////////////////////////////////////////
{
std::string bank;
unpacker & bank;
packer & int(_dev->readGPIODir(bank));
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_WRITE_I2C:
////////////////////////////////////////////////////////////////////
{
int addr = 0;
std::string data;
unpacker & addr;
unpacker & data;
_dev->writeI2C(addr, data);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_READ_I2C:
////////////////////////////////////////////////////////////////////
{
int addr = 0;
int numBytes = 0;
unpacker & addr;
unpacker & numBytes;
packer & _dev->readI2C(addr, unsigned(numBytes));
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_TRANSACT_SPI:
////////////////////////////////////////////////////////////////////
{
int addr = 0;
int data = 0;
int numBits = 0;
unpacker & addr;
unpacker & data;
unpacker & numBits;
packer & int(_dev->transactSPI(addr, unsigned(data), size_t(numBits)));
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_LIST_UARTS:
////////////////////////////////////////////////////////////////////
{
packer & _dev->listUARTs();
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_WRITE_UART:
////////////////////////////////////////////////////////////////////
{
std::string which;
std::string data;
unpacker & which;
unpacker & data;
_dev->writeUART(which, data);
packer & SOAPY_REMOTE_VOID;
} break;
////////////////////////////////////////////////////////////////////
case SOAPY_REMOTE_READ_UART:
////////////////////////////////////////////////////////////////////
{
std::string which;
int timeoutUs = 0;
unpacker & which;
unpacker & timeoutUs;
packer & _dev->readUART(which, long(timeoutUs));
} break;
default: throw std::runtime_error(
"SoapyClientHandler::handleOnce("+std::to_string(int(call))+") unknown call");
}
return call != SOAPY_REMOTE_HANGUP;
}
| 33.840747 | 116 | 0.396719 | cjcliffe |
9e4908e36ce15baf336b7934459ed7ff00ef8aa3 | 25,444 | hpp | C++ | disc-fe/src/evaluators/Panzer_GatherSolution_BlockedEpetra_decl.hpp | hillyuan/Panzer | 13ece3ea4c145c4d7b6339e3ad6332a501932ea8 | [
"BSD-3-Clause"
] | 1 | 2022-03-22T03:49:50.000Z | 2022-03-22T03:49:50.000Z | disc-fe/src/evaluators/Panzer_GatherSolution_BlockedEpetra_decl.hpp | hillyuan/Panzer | 13ece3ea4c145c4d7b6339e3ad6332a501932ea8 | [
"BSD-3-Clause"
] | null | null | null | disc-fe/src/evaluators/Panzer_GatherSolution_BlockedEpetra_decl.hpp | hillyuan/Panzer | 13ece3ea4c145c4d7b6339e3ad6332a501932ea8 | [
"BSD-3-Clause"
] | null | null | null | // @HEADER
// ***********************************************************************
//
// Panzer: A partial differential equation assembly
// engine for strongly coupled complex multiphysics systems
// Copyright (2011) Sandia Corporation
//
// Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
// the U.S. Government retains certain rights in this software.
//
// 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 Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY SANDIA CORPORATION "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 SANDIA CORPORATION OR THE
// 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.
//
// Questions? Contact Roger P. Pawlowski (rppawlo@sandia.gov) and
// Eric C. Cyr (eccyr@sandia.gov)
// ***********************************************************************
// @HEADER
#ifndef __Panzer_GatherSolution_BlockedEpetra_decl_hpp__
#define __Panzer_GatherSolution_BlockedEpetra_decl_hpp__
///////////////////////////////////////////////////////////////////////////////
//
// Include Files
//
///////////////////////////////////////////////////////////////////////////////
// Panzer
#include "Panzer_BlockedVector_ReadOnly_GlobalEvaluationData.hpp"
#include "Panzer_CloneableEvaluator.hpp"
#include "Panzer_Dimension.hpp"
#include "PanzerDiscFE_config.hpp"
#include "Panzer_Evaluator_WithBaseImpl.hpp"
#include "Panzer_Traits.hpp"
// Phalanx
#include "Phalanx_config.hpp"
#include "Phalanx_Evaluator_Macros.hpp"
#include "Phalanx_MDField.hpp"
// Teuchos
#include "Teuchos_ParameterList.hpp"
///////////////////////////////////////////////////////////////////////////////
//
// Forward Declarations
//
///////////////////////////////////////////////////////////////////////////////
namespace panzer
{
class GlobalIndexer;
}
namespace Thyra
{
template<typename> class ProductVectorBase;
}
namespace panzer
{
/**
* \brief Gathers solution values from the Newton solution vector into the
* nodal fields of the field manager.
*
* Currently makes an assumption that the stride is constant for degrees of
* freedom (DOFs) and that the nmber of DOFs is equal to the size of the
* solution names vector.
*/
template<typename EvalT, typename TRAITS, typename LO, typename GO>
class GatherSolution_BlockedEpetra
:
public panzer::EvaluatorWithBaseImpl<TRAITS>,
public PHX::EvaluatorDerived<panzer::Traits::Residual, TRAITS>,
public panzer::CloneableEvaluator
{
public:
/**
* \brief The scalar type.
*/
typedef typename EvalT::ScalarT ScalarT;
/**
* \brief Constructor.
*
* For this unspecialized class, this constructor is empty; that is, it
* doesn't do anything with the input `ParameterList`.
*
* \param[in] p A `ParameterList` that isn't used.
*/
GatherSolution_BlockedEpetra(
const Teuchos::ParameterList& p)
{
} // end of Constructor
/**
* \brief Create a copy.
*
* For this unspecialized class, this actually just calls the Default
* Constructor and doesn't copy anything.
*
* \param[in] pl A `ParameterList`, which is passed to the Default
* Constructor.
*
* \returns A `GatherSolution_BlockedEpetra` created by the Default
* Constructor.
*/
virtual Teuchos::RCP<CloneableEvaluator>
clone(
const Teuchos::ParameterList& pl) const
{
return Teuchos::rcp(new
GatherSolution_BlockedEpetra<EvalT, TRAITS, LO, GO>(pl));
} // end of clone()
/**
* \brief Post-Registration Setup.
*
* For this unspecialized class, this routine does nothing.
*
* \param[in] d Unused.
* \param[in] fm Unused.
*/
void
postRegistrationSetup(
typename TRAITS::SetupData d,
PHX::FieldManager<TRAITS>& fm)
{
} // end of postRegistrationSetup()
/**
* \brief Evaluate Fields.
*
* For this unspecialized class, this routine does nothing, other than
* tell you that you can't use it.
*
* \param[in] d Unused.
*/
void
evaluateFields(
typename TRAITS::EvalData d)
{
using PHX::print;
using std::cout;
using std::endl;
cout << "Unspecialized version of \"GatherSolution_BlockedEpetra::" \
"evaluateFields\" on " + print<EvalT>() + "\" should not " \
"be used!" << endl;
TEUCHOS_ASSERT(false);
} // end of evaluateFields()
}; // end of class GatherSolution_BlockedEpetra
/**
* \brief GatherSolution_BlockedEpetra (Residual Specialization).
*
* Gathers solution values from the Newton solution vector into the nodal
* fields of the field manager.
*
* Currently makes an assumption that the stride is constant for degrees of
* freedom (DOFs) and that the number of DOFs is equal to the size of the
* solution names vector.
*/
template<typename TRAITS, typename LO, typename GO>
class GatherSolution_BlockedEpetra<panzer::Traits::Residual, TRAITS, LO, GO>
:
public panzer::EvaluatorWithBaseImpl<TRAITS>,
public PHX::EvaluatorDerived<panzer::Traits::Residual, TRAITS>,
public panzer::CloneableEvaluator
{
public:
/**
* \brief Constructor.
*
* Simply saves the input `indexers` as this object's `indexers_`.
*
* \param[in] indexers The `vector` of `GlobalIndexer`s that
* handle the global unknown numbering.
*/
GatherSolution_BlockedEpetra(
const std::vector<Teuchos::RCP<const GlobalIndexer>>&
indexers)
:
indexers_(indexers)
{
} // end of Constructor
/**
* \brief Initializing Constructor.
*
* Saves the input `indexers` as this object's `indexers_`, allocates
* fields, sets up dependent tangent fields (if requested), and
* determines the first active name.
*
* \param[in] indexers The `vector` of `GlobalIndexer`s that
* handle the global unknown numbering.
* \param[in] p A `ParameterList` used as input for
* `GatherSolution_Input`.
*/
GatherSolution_BlockedEpetra(
const std::vector<Teuchos::RCP<const GlobalIndexer>>&
indexers,
const Teuchos::ParameterList& p);
/**
* \brief Post-Registration Setup.
*
* Loops over the `gatherFields_` and sets the `indexerIds_` and
* `subFieldIds_`.
*
* \param[in] d Unused.
* \param[in] fm Unused.
*/
void
postRegistrationSetup(
typename TRAITS::SetupData d,
PHX::FieldManager<TRAITS>& fm);
/**
* \brief Pre-Evaluate: Sets the solution vector.
*
* If using a `BlockedVector_ReadOnly_GlobalEvaluationData`, this saves
* it for use later in `evaluateFields()`. If using the older
* `BlockedEpetraLinearObjContainer`, this sets the solution vector.
*
* \param[in] d The `PreEvalData` containing the
* `GlobalEvaluationDataContainer`.
*/
void
preEvaluate(
typename TRAITS::PreEvalData d);
/**
* \brief Evaluate Fields: Gather operation.
*
* Loops over the fields to be gathered, the cells in the workset, and
* the basis functions, and fills in the fields.
*
* \param[in] d The `Workset` on which we're going to do all the work.
*/
void
evaluateFields(
typename TRAITS::EvalData d);
/**
* \brief Create a copy.
*
* Creates a `GatherSolution_BlockedEpetra` using the Initializing
* Constructor and the current object's `indexers_`.
*
* \param[in] pl A `ParameterList` used as input for
* `GatherSolution_Input`.
*
* \returns A `GatherSolution_BlockedEpetra` constructed with this
* object's `indexers_` and the input `ParameterList`.
*/
virtual Teuchos::RCP<CloneableEvaluator>
clone(
const Teuchos::ParameterList& pl) const
{
using panzer::Traits;
using Teuchos::rcp;
return rcp(new
GatherSolution_BlockedEpetra<Traits::Residual, TRAITS, LO, GO>
(indexers_, pl));
} // end of clone()
private:
/**
* \brief The evaluation type.
*/
typedef typename panzer::Traits::Residual EvalT;
/**
* \brief The scalar type.
*/
typedef typename panzer::Traits::Residual::ScalarT ScalarT;
/**
* \brief These map the local (field, element, basis) triplet to a
* global ID for scattering.
*/
std::vector<Teuchos::RCP<const GlobalIndexer>> indexers_;
/**
* \brief The block index into `indexers_`.
*/
std::vector<int> indexerIds_;
/**
* \brief Sub-field IDs, which need to be mapped.
*/
std::vector<int> subFieldIds_;
/**
* \brief The fields to be gathered.
*/
std::vector<PHX::MDField<ScalarT, Cell, NODE>> gatherFields_;
/**
* \brief A list of the names of the fields to be gathered.
*/
std::vector<std::string> indexerNames_;
/**
* \brief A flag indicating whether we should be working with \f$ x \f$
* or \f$ \dot{x} \f$.
*/
bool useTimeDerivativeSolutionVector_;
/**
* \brief The key identifying the `GlobalEvaluationData`.
*/
std::string globalDataKey_;
/**
* \brief The solution vector.
*/
Teuchos::RCP<Thyra::ProductVectorBase<double>> x_;
/**
* \brief The `GlobalEvaluationData` containing both the owned and
* ghosted solution vectors.
*/
Teuchos::RCP<panzer::BlockedVector_ReadOnly_GlobalEvaluationData>
xBvRoGed_;
/**
* \brief A flag indicating whether or not we have tangent fields.
*/
bool hasTangentFields_;
/**
* \brief Fields for storing the tangent components
* \f$\left(\frac{dx}{dp}\right)\f$ of the solution vector
* \f$(x)\f$.
*
* These are not actually used by the residual specialization of this
* evaluator, even if they are supplied, but it is useful to declare
* them as dependencies anyway when saving the tangent components to the
* output file.
*/
std::vector<std::vector<PHX::MDField<const ScalarT, Cell, NODE>>>
tangentFields_;
/**
* \brief Default Constructor (disabled)
*/
GatherSolution_BlockedEpetra();
}; // end of class GatherSolution_BlockedEpetra (Residual Specialization)
/**
* \brief GatherSolution_BlockedEpetra (Tangent Specialization).
*
* Gathers solution values from the Newton solution vector into the nodal
* fields of the field manager.
*
* Currently makes an assumption that the stride is constant for degrees of
* freedom (DOFs) and that the nmber of DOFs is equal to the size of the
* solution names vector.
*/
template<typename TRAITS, typename LO, typename GO>
class GatherSolution_BlockedEpetra<panzer::Traits::Tangent, TRAITS, LO, GO>
:
public panzer::EvaluatorWithBaseImpl<TRAITS>,
public PHX::EvaluatorDerived<panzer::Traits::Tangent, TRAITS>,
public panzer::CloneableEvaluator
{
public:
/**
* \brief Constructor.
*
* Simply saves the input `indexers` as this object's `indexers_`.
*
* \param[in] indexers The `vector` of `GlobalIndexer`s that
* handle the global unknown numbering.
*/
GatherSolution_BlockedEpetra(
const std::vector<Teuchos::RCP<const GlobalIndexer>>&
indexers)
:
indexers_(indexers)
{
} // end of Constructor
/**
* \brief Initializing Constructor.
*
* Saves the input `indexers` as this object's `indexers_`, allocates
* fields, sets up dependent tangent fields (if requested), and
* determines the first active name.
*
* \param[in] indexers The `vector` of `GlobalIndexer`s that
* handle the global unknown numbering.
* \param[in] p A `ParameterList` used as input for
* `GatherSolution_Input`.
*/
GatherSolution_BlockedEpetra(
const std::vector<Teuchos::RCP<const GlobalIndexer>>&
indexers,
const Teuchos::ParameterList& p);
/**
* \brief Post-Registration Setup.
*
* Loops over the `gatherFields_` and sets the `indexerIds_` and
* `subFieldIds_`.
*
* \param[in] d Unused.
* \param[in] fm Unused.
*/
void
postRegistrationSetup(
typename TRAITS::SetupData d,
PHX::FieldManager<TRAITS>& fm);
/**
* \brief Pre-Evaluate: Sets the solution vector.
*
* If using a `BlockedVector_ReadOnly_GlobalEvaluationData`, this saves
* it for use later in `evaluateFields()`. If using the older
* `BlockedEpetraLinearObjContainer`, this sets the solution vector.
*
* \param[in] d The `PreEvalData` containing the
* `GlobalEvaluationDataContainer`.
*/
void
preEvaluate(
typename TRAITS::PreEvalData d);
/**
* \brief Evaluate Fields: Gather operation.
*
* Loops over the fields to be gathered, the cells in the workset, and
* the basis functions, and fills in the fields. Also sets derivative
* information if tangent fields are enabled.
*
* \param[in] d The `Workset` on which we're going to do all the work.
*/
void
evaluateFields(
typename TRAITS::EvalData d);
/**
* \brief Create a copy.
*
* Creates a `GatherSolution_BlockedEpetra` using the Initializing
* Constructor and the current object's `indexers_`.
*
* \param[in] pl A `ParameterList` used as input for
* `GatherSolution_Input`.
*
* \returns A `GatherSolution_BlockedEpetra` constructed with this
* object's `indexers_` and the input `ParameterList`.
*/
virtual Teuchos::RCP<CloneableEvaluator>
clone(
const Teuchos::ParameterList& pl) const
{
using panzer::Traits;
using Teuchos::rcp;
return rcp(new
GatherSolution_BlockedEpetra<Traits::Tangent, TRAITS, LO, GO>
(indexers_, pl));
} // end of clone()
private:
/**
* \brief The evaluation type.
*/
typedef typename panzer::Traits::Tangent EvalT;
/**
* \brief The scalar type.
*/
typedef typename panzer::Traits::Tangent::ScalarT ScalarT;
/**
* \brief These map the local (field, element, basis) triplet to a
* global ID for scattering.
*/
std::vector<Teuchos::RCP<const GlobalIndexer>> indexers_;
/**
* \brief The block index into `indexers_`.
*/
std::vector<int> indexerIds_;
/**
* \brief Sub-field IDs, which need to be mapped.
*/
std::vector<int> subFieldIds_;
/**
* \brief The fields to be gathered.
*/
std::vector<PHX::MDField<ScalarT, Cell, NODE>> gatherFields_;
/**
* \brief A list of the names of the fields to be gathered.
*/
std::vector<std::string> indexerNames_;
/**
* \brief A flag indicating whether we should be working with \f$ x \f$
* or \f$ \dot{x} \f$.
*/
bool useTimeDerivativeSolutionVector_;
/**
* \brief The key identifying the `GlobalEvaluationData`.
*/
std::string globalDataKey_;
/**
* \brief The solution vector.
*/
Teuchos::RCP<Thyra::ProductVectorBase<double>> x_;
/**
* \brief The `GlobalEvaluationData` containing both the owned and
* ghosted solution vectors.
*/
Teuchos::RCP<panzer::BlockedVector_ReadOnly_GlobalEvaluationData>
xBvRoGed_;
/**
* \brief A flag indicating whether or not we have tangent fields.
*/
bool hasTangentFields_;
/**
* \brief Fields for storing the tangent components
* \f$\left(\frac{dx}{dp}\right)\f$ of the solution vector
* \f$(x)\f$.
*
* These are not actually used by the residual specialization of this
* evaluator, even if they are supplied, but it is useful to declare
* them as dependencies anyway when saving the tangent components to the
* output file.
*/
std::vector<std::vector<PHX::MDField<const ScalarT, Cell, NODE>>>
tangentFields_;
/**
* \brief Default Constructor (disabled)
*/
GatherSolution_BlockedEpetra();
}; // end of class GatherSolution_BlockedEpetra (Tangent Specialization)
/**
* \brief GatherSolution_BlockedEpetra (Jacobian Specialization).
*
* Gathers solution values from the Newton solution vector into the nodal
* fields of the field manager.
*
* Currently makes an assumption that the stride is constant for degrees of
* freedom (DOFs) and that the nmber of DOFs is equal to the size of the
* solution names vector.
*/
template<typename TRAITS, typename LO, typename GO>
class GatherSolution_BlockedEpetra<panzer::Traits::Jacobian, TRAITS, LO, GO>
:
public panzer::EvaluatorWithBaseImpl<TRAITS>,
public PHX::EvaluatorDerived<panzer::Traits::Jacobian, TRAITS>,
public panzer::CloneableEvaluator
{
public:
/**
* \brief Constructor.
*
* Simply saves the input `indexers` as this object's `indexers_`.
*
* \param[in] indexers The `vector` of `GlobalIndexer`s that
* handle the global unknown numbering.
*/
GatherSolution_BlockedEpetra(
const std::vector<Teuchos::RCP<const GlobalIndexer>>&
indexers)
:
indexers_(indexers)
{
} // end of Constructor
/**
* \brief Initializing Constructor.
*
* Saves the input `indexers` as this object's `indexers_`, allocates
* fields, sets up dependent tangent fields (if requested), and
* determines the first active name.
*
* \param[in] indexers The `vector` of `GlobalIndexer`s that
* handle the global unknown numbering.
* \param[in] p A `ParameterList` used as input for
* `GatherSolution_Input`.
*/
GatherSolution_BlockedEpetra(
const std::vector<Teuchos::RCP<const GlobalIndexer>>&
indexers,
const Teuchos::ParameterList& p);
/**
* \brief Post-Registration Setup.
*
* Loops over the `gatherFields_` and sets the `indexerIds_` and
* `subFieldIds_`.
*
* \param[in] d Unused.
* \param[in] fm Unused.
*/
void
postRegistrationSetup(
typename TRAITS::SetupData d,
PHX::FieldManager<TRAITS>& fm);
/**
* \brief Pre-Evaluate: Sets the solution vector.
*
* If using a `BlockedVector_ReadOnly_GlobalEvaluationData`, this saves
* it for use later in `evaluateFields()`. If using the older
* `BlockedEpetraLinearObjContainer`, this sets the solution vector.
* Also determines whether or not to apply sensitivities.
*
* \param[in] d The `PreEvalData` containing the
* `GlobalEvaluationDataContainer`.
*/
void
preEvaluate(
typename TRAITS::PreEvalData d);
/**
* \brief Evaluate Fields: Gather operation.
*
* Loops over the fields to be gathered, the cells in the workset, and
* the basis functions, and fills in the fields. If sensitivities are
* to be applied, this also seeds the derivatives.
*
* \param[in] d The `Workset` on which we're going to do all the work.
*/
void
evaluateFields(
typename TRAITS::EvalData d);
/**
* \brief Create a copy.
*
* Creates a `GatherSolution_BlockedEpetra` using the Initializing
* Constructor and the current object's `indexers_`.
*
* \param[in] pl A `ParameterList` used as input for
* `GatherSolution_Input`.
*
* \returns A `GatherSolution_BlockedEpetra` constructed with this
* object's `indexers_` and the input `ParameterList`.
*/
virtual Teuchos::RCP<CloneableEvaluator>
clone(
const Teuchos::ParameterList& pl) const
{
using panzer::Traits;
using Teuchos::rcp;
return rcp(new
GatherSolution_BlockedEpetra<Traits::Jacobian, TRAITS, LO, GO>
(indexers_, pl));
} // end of clone()
private:
/**
* \brief The evaluation type.
*/
typedef typename panzer::Traits::Jacobian EvalT;
/**
* \brief The scalar type.
*/
typedef typename panzer::Traits::Jacobian::ScalarT ScalarT;
/**
* \brief These map the local (field, element, basis) triplet to a
* global ID for scattering.
*/
std::vector<Teuchos::RCP<const GlobalIndexer>> indexers_;
/**
* \brief The block index into `indexers_`.
*/
std::vector<int> indexerIds_;
/**
* \brief Sub-field IDs, which need to be mapped.
*/
std::vector<int> subFieldIds_;
/**
* \brief The fields to be gathered.
*/
std::vector<PHX::MDField<ScalarT, Cell, NODE>> gatherFields_;
/**
* \brief A list of the names of the fields to be gathered.
*/
std::vector<std::string> indexerNames_;
/**
* \brief A flag indicating whether we should be working with \f$ x \f$
* or \f$ \dot{x} \f$.
*/
bool useTimeDerivativeSolutionVector_;
/**
* \brief Flag to disable sensitivities absolutely.
*/
bool disableSensitivities_;
/**
* \brief Sets which gather operations have sensitivities.
*/
std::string sensitivitiesName_;
/**
* \brief Used by `evaluateFields()` to turn on/off a certain set of
* sensitivities.
*/
bool applySensitivities_;
/**
* \brief The key identifying the `GlobalEvaluationData`.
*/
std::string globalDataKey_;
/**
* \brief Which gather seed in the workset to use.
*
* If it's less than zero, then use alpha or beta as appropriate.
*/
int gatherSeedIndex_;
/**
* \brief The solution vector.
*/
Teuchos::RCP<Thyra::ProductVectorBase<double>> x_;
/**
* \brief The `GlobalEvaluationData` containing both the owned and
* ghosted solution vectors.
*/
Teuchos::RCP<panzer::BlockedVector_ReadOnly_GlobalEvaluationData>
xBvRoGed_;
/**
* \brief Default Constructor (disabled)
*/
GatherSolution_BlockedEpetra();
}; // end of class GatherSolution_BlockedEpetra (Jacobian Specialization)
} // end of namespace panzer
#ifdef Panzer_BUILD_HESSIAN_SUPPORT
#include "Panzer_GatherSolution_BlockedEpetra_Hessian.hpp"
#endif // Panzer_BUILD_HESSIAN_SUPPORT
#endif // __Panzer_GatherSolution_BlockedEpetra_decl_hpp__
| 31.964824 | 79 | 0.591141 | hillyuan |
9e4a6a22b25123d459a150af8cd659e1bbbd7a3c | 25,168 | cpp | C++ | code/Plugins/Renderer/Direct3D11/Source/T3DD3D11Mappings.cpp | answerear/Fluid | 7b7992547a7d3ac05504dd9127e779eeeaddb3ab | [
"MIT"
] | 1 | 2021-11-16T15:11:52.000Z | 2021-11-16T15:11:52.000Z | code/Plugins/Renderer/Direct3D11/Source/T3DD3D11Mappings.cpp | answerear/Fluid | 7b7992547a7d3ac05504dd9127e779eeeaddb3ab | [
"MIT"
] | null | null | null | code/Plugins/Renderer/Direct3D11/Source/T3DD3D11Mappings.cpp | answerear/Fluid | 7b7992547a7d3ac05504dd9127e779eeeaddb3ab | [
"MIT"
] | null | null | null | /*******************************************************************************
* This file is part of Tiny3D (Tiny 3D Graphic Rendering Engine)
* Copyright (C) 2015-2020 Answer Wong
* For latest info, see https://github.com/answerear/Tiny3D
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
#include "T3DD3D11Mappings.h"
#include "T3DD3D11Context.h"
namespace Tiny3D
{
//--------------------------------------------------------------------------
const char * const D3D11Mappings::POSITION = "POSITION";
const char * const D3D11Mappings::BLENDWEIGHT = "BLENDWEIGHT";
const char * const D3D11Mappings::BLENDINDICES = "BLENDINDICES";
const char * const D3D11Mappings::NORMAL = "NORMAL";
const char * const D3D11Mappings::COLOR = "COLOR";
const char * const D3D11Mappings::TEXCOORD = "TEXCOORD";
const char * const D3D11Mappings::TANGENT = "TANGENT";
const char * const D3D11Mappings::BINORMAL = "BINORMAL";
//--------------------------------------------------------------------------
const char *D3D11Mappings::get(VertexAttribute::Semantic semantic)
{
switch (semantic)
{
case VertexAttribute::Semantic::E_VAS_POSITION:
return POSITION;
break;
case VertexAttribute::Semantic::E_VAS_BLENDWEIGHT:
return BLENDWEIGHT;
break;
case VertexAttribute::Semantic::E_VAS_BLENDINDICES:
return BLENDINDICES;
break;
case VertexAttribute::Semantic::E_VAS_NORMAL:
return NORMAL;
break;
case VertexAttribute::Semantic::E_VAS_DIFFUSE:
case VertexAttribute::Semantic::E_VAS_SPECULAR:
return COLOR;
break;
case VertexAttribute::Semantic::E_VAS_TEXCOORD:
return TEXCOORD;
break;
case VertexAttribute::Semantic::E_VAS_TANGENT:
return TANGENT;
break;
case VertexAttribute::Semantic::E_VAS_BINORMAL:
return BINORMAL;
break;
}
return nullptr;
}
//--------------------------------------------------------------------------
DXGI_FORMAT D3D11Mappings::get(VertexAttribute::Type type)
{
DXGI_FORMAT d3dformat;
switch (type)
{
case VertexAttribute::Type::E_VAT_COLOR:
d3dformat = DXGI_FORMAT_R32G32B32A32_FLOAT;
break;
case VertexAttribute::Type::E_VAT_FLOAT1:
d3dformat = DXGI_FORMAT_R32_FLOAT;
break;
case VertexAttribute::Type::E_VAT_FLOAT2:
d3dformat = DXGI_FORMAT_R32G32_FLOAT;
break;
case VertexAttribute::Type::E_VAT_FLOAT3:
d3dformat = DXGI_FORMAT_R32G32B32_FLOAT;
break;
case VertexAttribute::Type::E_VAT_FLOAT4:
d3dformat = DXGI_FORMAT_R32G32B32A32_FLOAT;
break;
case VertexAttribute::Type::E_VAT_SHORT2:
d3dformat = DXGI_FORMAT_R16G16_SINT;
break;
case VertexAttribute::Type::E_VAT_SHORT4:
d3dformat = DXGI_FORMAT_R16G16B16A16_SINT;
break;
case VertexAttribute::Type::E_VAT_UBYTE4:
d3dformat = DXGI_FORMAT_R8G8B8A8_UINT;
break;
}
return d3dformat;
}
//--------------------------------------------------------------------------
D3D11_PRIMITIVE_TOPOLOGY D3D11Mappings::get(RenderContext::PrimitiveType primitive)
{
D3D11_PRIMITIVE_TOPOLOGY d3dPrimitive;
switch (primitive)
{
case RenderContext::PrimitiveType::E_PT_POINT_LIST:
d3dPrimitive = D3D11_PRIMITIVE_TOPOLOGY_POINTLIST;
break;
case RenderContext::PrimitiveType::E_PT_LINE_LIST:
d3dPrimitive = D3D11_PRIMITIVE_TOPOLOGY_LINELIST;
break;
case RenderContext::PrimitiveType::E_PT_LINE_STRIP:
d3dPrimitive = D3D11_PRIMITIVE_TOPOLOGY_LINESTRIP;
break;
case RenderContext::PrimitiveType::E_PT_TRIANGLE_LIST:
d3dPrimitive = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
break;
case RenderContext::PrimitiveType::E_PT_TRIANGLE_STRIP:
d3dPrimitive = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP;
break;
default:
d3dPrimitive = D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST;
break;
}
return d3dPrimitive;
}
//--------------------------------------------------------------------------
DXGI_FORMAT D3D11Mappings::get(HardwareIndexBuffer::Type idxType)
{
DXGI_FORMAT d3dFormat;
switch (idxType)
{
case HardwareIndexBuffer::Type::E_IT_16BITS:
d3dFormat = DXGI_FORMAT_R16_UINT;
break;
case HardwareIndexBuffer::Type::E_IT_32BITS:
d3dFormat = DXGI_FORMAT_R32_UINT;
break;
default:
d3dFormat = DXGI_FORMAT_R16_UINT;
break;
}
return d3dFormat;
}
//--------------------------------------------------------------------------
TResult D3D11Mappings::get(HardwareBuffer::Usage usage, uint32_t mode,
D3D11_USAGE &d3dUsage, uint32_t &d3dAccessFlag)
{
TResult ret = T3D_OK;
do
{
switch (usage)
{
case HardwareBuffer::Usage::STATIC:
{
if (mode == HardwareBuffer::AccessMode::CPU_NONE)
{
// 静态缓冲,CPU不可读写,只能初始化时候设置数据
d3dUsage = D3D11_USAGE_IMMUTABLE;
d3dAccessFlag = 0;
}
else if (mode == HardwareBuffer::AccessMode::CPU_WRITE)
{
d3dUsage = D3D11_USAGE_DEFAULT;
d3dAccessFlag = 0;
}
else
{
// 其他 CPU 访问标签在这里都是非法
ret = T3D_ERR_INVALID_PARAM;
T3D_LOG_ERROR(LOG_TAG_D3D11RENDERER,
"Usage is STATIC, so access mode must be CPU_NONE "
"or CPU_WRITE !");
}
}
break;
case HardwareBuffer::Usage::DYNAMIC:
case HardwareBuffer::Usage::STREAM:
{
if (mode == HardwareBuffer::AccessMode::CPU_NONE)
{
// CPU不读也不写,这里建议使用STATIC性能更好
d3dUsage = D3D11_USAGE_DEFAULT;
d3dAccessFlag = 0;
T3D_LOG_WARNING(LOG_TAG_D3D11RENDERER,
"Usage is DYNAMIC, but CPU access mode is CPU_NONE."
" Here suggests STATIC instead of DYNAMIC !");
}
else if ((mode == (HardwareBuffer::AccessMode::CPU_READ
| HardwareBuffer::AccessMode::CPU_WRITE)))
{
// CPU读写,GPU读写
d3dUsage = D3D11_USAGE_STAGING;
d3dAccessFlag
= D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ;
}
else if (mode == HardwareBuffer::AccessMode::CPU_READ)
{
// CPU读,GPU读写
d3dUsage = D3D11_USAGE_STAGING;
d3dAccessFlag = D3D11_CPU_ACCESS_READ;
}
else if (mode == HardwareBuffer::AccessMode::CPU_WRITE)
{
// CPU写,GPU读
d3dUsage = D3D11_USAGE_DYNAMIC;
d3dAccessFlag = D3D11_CPU_ACCESS_WRITE;
}
else if (mode == HardwareBuffer::AccessMode::GPU_COPY)
{
// CPU读写,GPU读写
d3dUsage = D3D11_USAGE_STAGING;
d3dAccessFlag
= D3D11_CPU_ACCESS_WRITE | D3D11_CPU_ACCESS_READ;
}
else
{
// 无效 CPU 访问方式参数
ret = T3D_ERR_INVALID_PARAM;
T3D_LOG_ERROR(LOG_TAG_D3D11RENDERER,
"Invalid CPU access mode parameter !");
}
}
break;
default:
{
ret = T3D_ERR_INVALID_PARAM;
}
break;
}
} while (0);
return ret;
}
//--------------------------------------------------------------------------
D3D11_MAP D3D11Mappings::get(HardwareBuffer::LockOptions options)
{
D3D11_MAP d3dOpt = D3D11_MAP_READ;
switch (options)
{
case HardwareBuffer::LockOptions::READ:
{
d3dOpt = D3D11_MAP_READ;
}
break;
case HardwareBuffer::LockOptions::WRITE:
{
d3dOpt = D3D11_MAP_WRITE;
}
break;
case HardwareBuffer::LockOptions::READ_WRITE:
{
d3dOpt = D3D11_MAP_READ_WRITE;
}
break;
case HardwareBuffer::LockOptions::WRITE_DISCARD:
{
d3dOpt = D3D11_MAP_WRITE_DISCARD;
}
break;
case HardwareBuffer::LockOptions::WRITE_NO_OVERWRITE:
{
d3dOpt = D3D11_MAP_WRITE_NO_OVERWRITE;
}
break;
default:
{
T3D_LOG_ERROR(LOG_TAG_D3D11RENDERER,
"Invalid LockOptions !");
}
break;
}
return d3dOpt;
}
//--------------------------------------------------------------------------
DXGI_FORMAT D3D11Mappings::get(PixelFormat format)
{
DXGI_FORMAT fmt;
switch (format)
{
case PixelFormat::E_PF_PALETTE8:
break;
case PixelFormat::E_PF_R5G6B5:
break;
case PixelFormat::E_PF_A1R5G5B5:
break;
case PixelFormat::E_PF_A4R4G4B4:
break;
case PixelFormat::E_PF_R8G8B8:
break;
case PixelFormat::E_PF_B8G8R8:
break;
case PixelFormat::E_PF_A8R8G8B8:
fmt = DXGI_FORMAT_R8G8B8A8_UNORM;
break;
case PixelFormat::E_PF_B8G8R8A8:
break;
case PixelFormat::E_PF_X8R8G8B8:
break;
case PixelFormat::E_PF_B8G8R8X8:
break;
}
return fmt;
}
//--------------------------------------------------------------------------
D3D11_COMPARISON_FUNC D3D11Mappings::get(CompareFunction func)
{
switch (func)
{
case CompareFunction::ALWAYS_FAIL:
return D3D11_COMPARISON_NEVER;
case CompareFunction::ALWAYS_PASS:
return D3D11_COMPARISON_ALWAYS;
case CompareFunction::LESS:
return D3D11_COMPARISON_LESS;
case CompareFunction::LESS_EQUAL:
return D3D11_COMPARISON_LESS_EQUAL;
case CompareFunction::EQUAL:
return D3D11_COMPARISON_EQUAL;
case CompareFunction::NOT_EQUAL:
return D3D11_COMPARISON_NOT_EQUAL;
case CompareFunction::GREATER_EQUAL:
return D3D11_COMPARISON_GREATER_EQUAL;
case CompareFunction::GREATER:
return D3D11_COMPARISON_GREATER;
};
return D3D11_COMPARISON_ALWAYS;
}
//--------------------------------------------------------------------------
D3D11_BLEND D3D11Mappings::get(BlendFactor factor)
{
switch (factor)
{
case BlendFactor::ONE:
return D3D11_BLEND_ONE;
case BlendFactor::ZERO:
return D3D11_BLEND_ZERO;
case BlendFactor::DEST_COLOR:
return D3D11_BLEND_DEST_COLOR;
case BlendFactor::SOURCE_COLOR:
return D3D11_BLEND_SRC_COLOR;
case BlendFactor::ONE_MINUS_DEST_COLOR:
return D3D11_BLEND_INV_DEST_COLOR;
case BlendFactor::ONE_MINUS_SOURCE_COLOR:
return D3D11_BLEND_INV_SRC_COLOR;
case BlendFactor::DEST_ALPHA:
return D3D11_BLEND_DEST_ALPHA;
case BlendFactor::SOURCE_ALPHA:
return D3D11_BLEND_SRC_ALPHA;
case BlendFactor::ONE_MINUS_DEST_ALPHA:
return D3D11_BLEND_INV_DEST_ALPHA;
case BlendFactor::ONE_MINUS_SOURCE_ALPHA:
return D3D11_BLEND_INV_SRC_ALPHA;
}
return D3D11_BLEND_ONE;
}
//--------------------------------------------------------------------------
D3D11_BLEND_OP D3D11Mappings::get(BlendOperation op)
{
switch (op)
{
case BlendOperation::ADD:
return D3D11_BLEND_OP_ADD;
case BlendOperation::SUBTRACT:
return D3D11_BLEND_OP_SUBTRACT;
case BlendOperation::REVERSE_SUBTRACT:
return D3D11_BLEND_OP_REV_SUBTRACT;
case BlendOperation::MIN:
return D3D11_BLEND_OP_MIN;
case BlendOperation::MAX:
return D3D11_BLEND_OP_MAX;
}
return D3D11_BLEND_OP_ADD;
}
//--------------------------------------------------------------------------
void D3D11Mappings::get(D3D11_BLEND_DESC &desc, const BlendState& state)
{
desc.AlphaToCoverageEnable = state.isAlpha2CoverageEnabled() ? TRUE : FALSE;
desc.IndependentBlendEnable = state.isIndependentBlendEnabled();
if (desc.IndependentBlendEnable)
{
for (int32_t i = 0; i < BlendState::MAX_RENDER_TARGET; ++i)
{
desc.RenderTarget[i].BlendEnable = state.isBlendEnabled(i) ? TRUE : FALSE;
desc.RenderTarget[i].SrcBlend = get(state.getSrcBlend(i));
desc.RenderTarget[i].DestBlend = get(state.getDstBlend(i));
desc.RenderTarget[i].BlendOp = get(state.getBlendOp(i));
desc.RenderTarget[i].SrcBlendAlpha = get(state.getSrcBlendAlpha(i));
desc.RenderTarget[i].DestBlendAlpha = get(state.getDstBlendAlpha(i));
desc.RenderTarget[i].BlendOpAlpha = get(state.getBlendOpAlpha(i));
desc.RenderTarget[i].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
}
}
else
{
desc.RenderTarget[0].BlendEnable = state.isBlendEnabled(0) ? TRUE : FALSE;
desc.RenderTarget[0].SrcBlend = get(state.getSrcBlend(0));
desc.RenderTarget[0].DestBlend = get(state.getDstBlend(0));
desc.RenderTarget[0].BlendOp = get(state.getBlendOp(0));
desc.RenderTarget[0].SrcBlendAlpha = get(state.getSrcBlendAlpha(0));
desc.RenderTarget[0].DestBlendAlpha = get(state.getDstBlendAlpha(0));
desc.RenderTarget[0].BlendOpAlpha = get(state.getBlendOpAlpha(0));
desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
}
}
//--------------------------------------------------------------------------
D3D11_DEPTH_WRITE_MASK D3D11Mappings::get(DepthWriteMask mask)
{
switch (mask)
{
case DepthWriteMask::ZERO:
return D3D11_DEPTH_WRITE_MASK_ZERO;
case DepthWriteMask::ALL:
return D3D11_DEPTH_WRITE_MASK_ALL;
}
return D3D11_DEPTH_WRITE_MASK_ALL;
}
//--------------------------------------------------------------------------
D3D11_STENCIL_OP D3D11Mappings::get(StencilOp op)
{
switch (op)
{
case StencilOp::KEEP:
return D3D11_STENCIL_OP_KEEP;
case StencilOp::ZERO:
return D3D11_STENCIL_OP_ZERO;
case StencilOp::REPLACE:
return D3D11_STENCIL_OP_REPLACE;
case StencilOp::INCR:
return D3D11_STENCIL_OP_INCR_SAT;
case StencilOp::INCR_WRAP:
return D3D11_STENCIL_OP_INCR;
case StencilOp::DECR:
return D3D11_STENCIL_OP_DECR_SAT;
case StencilOp::DECR_WRAP:
return D3D11_STENCIL_OP_DECR;
case StencilOp::INVERT:
return D3D11_STENCIL_OP_INVERT;
}
return D3D11_STENCIL_OP_KEEP;
}
//--------------------------------------------------------------------------
void D3D11Mappings::get(D3D11_DEPTH_STENCIL_DESC &desc, const DepthStencilState& state)
{
desc.DepthEnable = state.isDepthTestEnabled() ? TRUE : FALSE;
desc.DepthWriteMask = get(state.getDepthWriteMask());
desc.DepthFunc = get(state.getDepthFunction());
desc.StencilEnable = state.isStencilEnabled() ? TRUE : FALSE;
desc.StencilReadMask = state.getStencilReadMask();
desc.StencilWriteMask = state.getStencilWriteMask();
StencilOp stencilFailOp, depthFailOp, passOp;
state.getStencilOp(stencilFailOp, depthFailOp, passOp);
desc.FrontFace.StencilFailOp = get(stencilFailOp);
desc.FrontFace.StencilDepthFailOp = get(depthFailOp);
desc.FrontFace.StencilPassOp = get(passOp);
desc.FrontFace.StencilFunc = get(state.getStencilFunction());
}
//--------------------------------------------------------------------------
D3D11_FILL_MODE D3D11Mappings::get(PolygonMode mode)
{
D3D11_FILL_MODE d3dMode = D3D11_FILL_SOLID;
switch (mode)
{
case PolygonMode::POINT:
case PolygonMode::WIREFRAME:
d3dMode = D3D11_FILL_WIREFRAME;
break;
default:
d3dMode = D3D11_FILL_SOLID;
break;
}
return d3dMode;
}
//--------------------------------------------------------------------------
D3D11_CULL_MODE D3D11Mappings::get(CullingMode mode)
{
D3D11_CULL_MODE d3dMode = D3D11_CULL_NONE;
switch (mode)
{
case CullingMode::CLOCKWISE:
d3dMode = D3D11_CULL_BACK;
break;
case CullingMode::ANTICLOCKWISE:
d3dMode = D3D11_CULL_FRONT;
break;
default:
d3dMode = D3D11_CULL_NONE;
break;
}
return d3dMode;
}
//--------------------------------------------------------------------------
void D3D11Mappings::get(D3D11_RASTERIZER_DESC &desc, const RasterizerState& state)
{
desc.FillMode = get(state.getPolygonMode());
desc.CullMode = get(state.getCullingMode());
desc.FrontCounterClockwise = TRUE;
desc.DepthBias = state.getDepthBias();
desc.DepthBiasClamp = state.getDepthBiasClamp();
desc.SlopeScaledDepthBias = state.getSlopeScaledDepthBias();
desc.DepthClipEnable = state.isDepthClipEnabled() ? TRUE : FALSE;
desc.ScissorEnable = state.isScissorEnabled() ? TRUE : FALSE;
desc.MultisampleEnable = state.isMSAAEnabled() ? TRUE : FALSE;
desc.AntialiasedLineEnable = FALSE;
}
//--------------------------------------------------------------------------
D3D11_TEXTURE_ADDRESS_MODE D3D11Mappings::get(TextureAddressMode mode)
{
if (D3D11_CONTEXT.getFeatureLevel() == D3D_FEATURE_LEVEL_9_1)
return D3D11_TEXTURE_ADDRESS_WRAP;
switch (mode)
{
case TextureAddressMode::WRAP:
return D3D11_TEXTURE_ADDRESS_WRAP;
case TextureAddressMode::MIRROR:
return D3D11_TEXTURE_ADDRESS_MIRROR;
case TextureAddressMode::CLAMP:
return D3D11_TEXTURE_ADDRESS_CLAMP;
case TextureAddressMode::BORDER:
return D3D11_TEXTURE_ADDRESS_BORDER;
}
return D3D11_TEXTURE_ADDRESS_WRAP;
}
//--------------------------------------------------------------------------
D3D11_FILTER D3D11Mappings::get(FilterOptions min, FilterOptions mag,
FilterOptions mip, bool comparison /* = false */)
{
if (min == FilterOptions::ANISOTROPIC
|| mag == FilterOptions::ANISOTROPIC
|| mip == FilterOptions::ANISOTROPIC)
return comparison ? D3D11_FILTER_COMPARISON_ANISOTROPIC : D3D11_FILTER_ANISOTROPIC;
// FilterOptions::FilterOptions::NONE is not supported
#define MERGE_FOR_SWITCH(_comparison_, _min_ , _mag_, _mip_ ) \
((_comparison_ ? 8 : 0) | (_min_ == FilterOptions::LINEAR ? 4 : 0) | (_mag_ == FilterOptions::LINEAR ? 2 : 0) | (_mip_ == FilterOptions::LINEAR ? 1 : 0))
switch ((MERGE_FOR_SWITCH(comparison, min, mag, mip)))
{
case MERGE_FOR_SWITCH(true, FilterOptions::POINT, FilterOptions::POINT, FilterOptions::POINT):
return D3D11_FILTER_COMPARISON_MIN_MAG_MIP_POINT;
case MERGE_FOR_SWITCH(true, FilterOptions::POINT, FilterOptions::POINT, FilterOptions::LINEAR):
return D3D11_FILTER_COMPARISON_MIN_MAG_POINT_MIP_LINEAR;
case MERGE_FOR_SWITCH(true, FilterOptions::POINT, FilterOptions::LINEAR, FilterOptions::POINT):
return D3D11_FILTER_COMPARISON_MIN_POINT_MAG_LINEAR_MIP_POINT;
case MERGE_FOR_SWITCH(true, FilterOptions::POINT, FilterOptions::LINEAR, FilterOptions::LINEAR):
return D3D11_FILTER_COMPARISON_MIN_POINT_MAG_MIP_LINEAR;
case MERGE_FOR_SWITCH(true, FilterOptions::LINEAR, FilterOptions::POINT, FilterOptions::POINT):
return D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_MIP_POINT;
case MERGE_FOR_SWITCH(true, FilterOptions::LINEAR, FilterOptions::POINT, FilterOptions::LINEAR):
return D3D11_FILTER_COMPARISON_MIN_LINEAR_MAG_POINT_MIP_LINEAR;
case MERGE_FOR_SWITCH(true, FilterOptions::LINEAR, FilterOptions::LINEAR, FilterOptions::POINT):
return D3D11_FILTER_COMPARISON_MIN_MAG_LINEAR_MIP_POINT;
case MERGE_FOR_SWITCH(true, FilterOptions::LINEAR, FilterOptions::LINEAR, FilterOptions::LINEAR):
return D3D11_FILTER_COMPARISON_MIN_MAG_MIP_LINEAR;
case MERGE_FOR_SWITCH(false, FilterOptions::POINT, FilterOptions::POINT, FilterOptions::POINT):
return D3D11_FILTER_MIN_MAG_MIP_POINT;
case MERGE_FOR_SWITCH(false, FilterOptions::POINT, FilterOptions::POINT, FilterOptions::LINEAR):
return D3D11_FILTER_MIN_MAG_POINT_MIP_LINEAR;
case MERGE_FOR_SWITCH(false, FilterOptions::POINT, FilterOptions::LINEAR, FilterOptions::POINT):
return D3D11_FILTER_MIN_POINT_MAG_LINEAR_MIP_POINT;
case MERGE_FOR_SWITCH(false, FilterOptions::POINT, FilterOptions::LINEAR, FilterOptions::LINEAR):
return D3D11_FILTER_MIN_POINT_MAG_MIP_LINEAR;
case MERGE_FOR_SWITCH(false, FilterOptions::LINEAR, FilterOptions::POINT, FilterOptions::POINT):
return D3D11_FILTER_MIN_LINEAR_MAG_MIP_POINT;
case MERGE_FOR_SWITCH(false, FilterOptions::LINEAR, FilterOptions::POINT, FilterOptions::LINEAR):
return D3D11_FILTER_MIN_LINEAR_MAG_POINT_MIP_LINEAR;
case MERGE_FOR_SWITCH(false, FilterOptions::LINEAR, FilterOptions::LINEAR, FilterOptions::POINT):
return D3D11_FILTER_MIN_MAG_LINEAR_MIP_POINT;
case MERGE_FOR_SWITCH(false, FilterOptions::LINEAR, FilterOptions::LINEAR, FilterOptions::LINEAR):
return D3D11_FILTER_MIN_MAG_MIP_LINEAR;
}
#undef MERGE_FOR_SWITCH
return D3D11_FILTER_MIN_MAG_MIP_LINEAR;
}
//--------------------------------------------------------------------------
void D3D11Mappings::get(D3D11_SAMPLER_DESC &desc, const SamplerState& state)
{
FilterOptions minFilter, magFilter, mipFilter;
state.getFilter(minFilter, magFilter, mipFilter);
const UVWAddressMode &mode = state.getAddressMode();
const ColorRGBA &clrBorder = state.getBorderColor();
desc.Filter = get(minFilter, magFilter, mipFilter);
desc.AddressU = get(mode.u);
desc.AddressV = get(mode.v);
desc.AddressW = get(mode.w);
desc.MipLODBias = state.getMipmapBias();
desc.MaxAnisotropy = state.getAnisotropy();
desc.ComparisonFunc = get(state.getCompareFunction());
desc.BorderColor[0] = clrBorder.red();
desc.BorderColor[1] = clrBorder.green();
desc.BorderColor[2] = clrBorder.blue();
desc.BorderColor[3] = clrBorder.alpha();
}
}
| 37.452381 | 157 | 0.560791 | answerear |
eafbf30cff755e79f9b6a2680e9c4834be8f1257 | 586 | hpp | C++ | source/lucio/core/callback.hpp | joserossini/lucioengine | 643941cf29e23824af28e60df62bb1aaa0f6a7f1 | [
"MIT"
] | null | null | null | source/lucio/core/callback.hpp | joserossini/lucioengine | 643941cf29e23824af28e60df62bb1aaa0f6a7f1 | [
"MIT"
] | null | null | null | source/lucio/core/callback.hpp | joserossini/lucioengine | 643941cf29e23824af28e60df62bb1aaa0f6a7f1 | [
"MIT"
] | null | null | null | #include <functional>
namespace lucio {
/*
* CallBack
* Use to call class member function from another class or Lambda.
*
* Example:
* {
* auto funcCallBack = new CallBack<void>([]() {
* std::cout << "Hello World\n";
* });
*
* funcCallBack->execute();
* }
*
* Note: Can also be use whit std::bind"
*/
template <typename T, typename... Args>
class CallBack{
public:
CallBack(std::function<T(Args...)> func) : _func(func) {};
void execute(Args... args) const { _func(std::forward<Args>(args)...); };
private:
std::function<T(Args...)> _func;
};
} | 18.3125 | 76 | 0.602389 | joserossini |
eaff3a558d9b8924d4c9eeb2bd85e06f0e4d0359 | 5,162 | hpp | C++ | include/incavery/core.hpp | helixd2s/Incavery | b33737fc879fe9ef52158d8193b95633eef1321b | [
"BSD-3-Clause"
] | 6 | 2021-02-14T22:51:28.000Z | 2021-07-30T18:35:25.000Z | include/incavery/core.hpp | helixd2s/Incavery | b33737fc879fe9ef52158d8193b95633eef1321b | [
"BSD-3-Clause"
] | null | null | null | include/incavery/core.hpp | helixd2s/Incavery | b33737fc879fe9ef52158d8193b95633eef1321b | [
"BSD-3-Clause"
] | null | null | null | #pragma once
//
#include <glm/glm.hpp>
#include <vkf/swapchain.hpp>
//
namespace icv {
//
struct DescriptorInfo {
VkDescriptorSetLayout layout = VK_NULL_HANDLE;
//VkPipelineLayout pipelineLayout = VK_NULL_HANDLE;
};
//
struct GraphicsPipelinePath
{
std::string vertex = "";
std::string geometry = "";
std::string fragment = "";
};
//
struct ComputePipelinePath
{
std::string compute = "";
};
// Vulkan needs f&cking SoA, EVERY TIME!
struct BuildInfo
{
std::vector<vkh::VkAccelerationStructureGeometryKHR> builds = {};
std::vector<vkh::VkAccelerationStructureBuildRangeInfoKHR> ranges = {};
vkh::VkAccelerationStructureBuildGeometryInfoKHR info = {};
};
//
struct BufferCreateInfo
{
FLAGS(VkBufferUsage) usage;
VkDeviceSize size = 16ull;
VkDeviceSize stride = sizeof(uint8_t);
VmaMemoryUsage memoryUsage = VMA_MEMORY_USAGE_GPU_ONLY;
};
//
struct ImageCreateInfo
{
FLAGS(VkImageUsage) usage;
VkFormat format = VK_FORMAT_R32G32B32A32_SFLOAT;
vkh::VkExtent3D extent = {};
bool isDepth = false;
};
//
enum class IndexType : uint32_t {
None = 0u,
Uint32 = 1u,
Uint16 = 2u,
Uint8 = 3u
};
//
class DeviceBased {
protected:
vkh::uni_ptr<vkf::Device> device = {};
vkh::VkAccelerationStructureDeviceAddressInfoKHR deviceAddressInfo = {};
vkh::VkBufferDeviceAddressInfo bufferAddressInfo = {};
//
virtual VkDeviceAddress bufferDeviceAddress(vkh::VkDescriptorBufferInfo buffer)
{
return (device->dispatch->GetBufferDeviceAddress(bufferAddressInfo = buffer.buffer) + buffer.offset);
};
//
virtual vkf::VectorBase createBuffer(vkh::uni_arg<BufferCreateInfo> info)
{ //
auto bufferCreateInfo = vkh::VkBufferCreateInfo{
.size = info->size,
.usage = (info->memoryUsage == VMA_MEMORY_USAGE_GPU_ONLY ? VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT : 0u) | VkBufferUsageFlags(info->usage)
};
auto vmaCreateInfo = vkf::VmaMemoryInfo{
.memUsage = info->memoryUsage,
.instanceDispatch = device->instance->dispatch,
.deviceDispatch = device->dispatch
};
auto allocation = std::make_shared<vkf::VmaBufferAllocation>(device->allocator, bufferCreateInfo, vmaCreateInfo);
return vkf::VectorBase(allocation, 0ull, info->size, sizeof(uint8_t));
};
//
virtual vkf::ImageRegion createImage2D(vkh::uni_arg<ImageCreateInfo> info)
{ //
vkh::VkImageCreateInfo imageCreateInfo = {};
imageCreateInfo.imageType = VK_IMAGE_TYPE_2D;
imageCreateInfo.format = info->format;
imageCreateInfo.extent = vkh::VkExtent3D{ info->extent.width, info->extent.height, 1u };
imageCreateInfo.mipLevels = 1u;
imageCreateInfo.arrayLayers = 1u;
imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT;
imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
imageCreateInfo.usage = info->usage | VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT;
imageCreateInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
//
auto vmaCreateInfo = vkf::VmaMemoryInfo{
.memUsage = VMA_MEMORY_USAGE_GPU_ONLY,
.instanceDispatch = device->instance->dispatch,
.deviceDispatch = device->dispatch
};
//
auto aspectFlags = info->isDepth ? (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT) : (VK_IMAGE_ASPECT_COLOR_BIT);
//
vkh::VkImageViewCreateInfo imageViewCreateInfo = {};
imageViewCreateInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
imageViewCreateInfo.format = info->format;
imageViewCreateInfo.components = vkh::VkComponentMapping{};
imageViewCreateInfo.subresourceRange = vkh::VkImageSubresourceRange{ .aspectMask = VkImageAspectFlags(aspectFlags), .baseMipLevel = 0u, .levelCount = 1u, .baseArrayLayer = 0u, .layerCount = 1u };
//
auto allocation = std::make_shared<vkf::VmaImageAllocation>(device->allocator, imageCreateInfo, vmaCreateInfo);
return vkf::ImageRegion(allocation, imageViewCreateInfo, info->isDepth?VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL:VK_IMAGE_LAYOUT_GENERAL);
};
//
virtual VkIndexType getIndexType(IndexType indexType = IndexType::None)
{ //
if (indexType == IndexType::None) { return VK_INDEX_TYPE_NONE_KHR; };
if (indexType == IndexType::Uint32) { return VK_INDEX_TYPE_UINT32; };
if (indexType == IndexType::Uint16) { return VK_INDEX_TYPE_UINT16; };
if (indexType == IndexType::Uint8) { return VK_INDEX_TYPE_UINT8_EXT; };
return VK_INDEX_TYPE_NONE_KHR;
};
};
};
| 36.352113 | 207 | 0.623596 | helixd2s |
d802831f56e4e78ff6ca7bf64bfa12cce270be68 | 401 | hpp | C++ | old/Net.Server.Basic/inc/net/CFlushEvent.hpp | raduionita/project-hermes | 7935a1486d7b0f3c05208d2c7a2e36552581a23b | [
"MIT"
] | null | null | null | old/Net.Server.Basic/inc/net/CFlushEvent.hpp | raduionita/project-hermes | 7935a1486d7b0f3c05208d2c7a2e36552581a23b | [
"MIT"
] | null | null | null | old/Net.Server.Basic/inc/net/CFlushEvent.hpp | raduionita/project-hermes | 7935a1486d7b0f3c05208d2c7a2e36552581a23b | [
"MIT"
] | null | null | null | #ifndef __net_cflushevent_hpp__
#define __net_cflushevent_hpp__
#include <core/CEvent.hpp>
#include <net.hpp>
#include <net/CConnection.hpp>
namespace net
{
class CFlushEvent : public core::CEvent
{
public:
CConnection& mConnection;
public:
CFlushEvent(CConnection& conn) : core::CEvent("flush"), mConnection(conn)
{
}
};
}
#endif // __net_cflushevent_hpp__
| 16.708333 | 77 | 0.690773 | raduionita |
d80293402defa5c3fd763d977595de32ba8ebfc4 | 7,520 | cpp | C++ | contract/lite-client/crypto/parser/lexer.cpp | TONCommunity/ton-sync-payments-channel | 2e5cd4902406923fdba32b8309ab8c40db3ae5bc | [
"MIT"
] | 5 | 2019-10-15T18:26:06.000Z | 2020-05-09T14:09:49.000Z | contract/lite-client/crypto/parser/lexer.cpp | TONCommunity/ton-sync-payments-channel | 2e5cd4902406923fdba32b8309ab8c40db3ae5bc | [
"MIT"
] | null | null | null | contract/lite-client/crypto/parser/lexer.cpp | TONCommunity/ton-sync-payments-channel | 2e5cd4902406923fdba32b8309ab8c40db3ae5bc | [
"MIT"
] | 2 | 2020-07-24T16:09:02.000Z | 2021-08-18T17:08:28.000Z | /*
This file is part of TON Blockchain Library.
TON Blockchain Library is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 2 of the License, or
(at your option) any later version.
TON Blockchain Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with TON Blockchain Library. If not, see <http://www.gnu.org/licenses/>.
Copyright 2017-2019 Telegram Systems LLP
*/
#include "lexer.h"
#include "symtable.h"
#include <sstream>
#include <cassert>
namespace src {
/*
*
* LEXER
*
*/
std::string Lexem::lexem_name_str(int idx) {
if (idx == Eof) {
return "end of file";
} else if (idx == Ident) {
return "identifier";
} else if (idx == Number) {
return "number";
} else if (idx == String) {
return "string";
} else if (idx == Special) {
return "special";
} else if (sym::symbols.get_keyword(idx)) {
return "`" + sym::symbols.get_keyword(idx)->str + "`";
} else {
std::ostringstream os{"<unknown lexem of type "};
os << idx << ">";
return os.str();
}
}
std::string Lexem::name_str() const {
if (tp == Ident) {
return std::string{"identifier `"} + sym::symbols.get_name(val) + "`";
} else if (tp == String) {
return std::string{"string \""} + str + '"';
} else {
return lexem_name_str(tp);
}
}
bool is_number(std::string str) {
auto st = str.begin(), en = str.end();
if (st == en) {
return false;
}
if (*st == '-') {
st++;
}
bool hex = false;
if (st + 1 < en && *st == '0' && st[1] == 'x') {
st += 2;
hex = true;
}
if (st == en) {
return false;
}
while (st < en) {
int c = *st;
if (c >= '0' && c <= '9') {
++st;
continue;
}
if (!hex) {
return false;
}
c |= 0x20;
if (c < 'a' || c > 'f') {
return false;
}
++st;
}
return true;
}
int Lexem::classify() {
if (tp != Unknown) {
return tp;
}
sym::sym_idx_t i = sym::symbols.lookup(str);
if (i) {
assert(str == sym::symbols[i]->str);
str = sym::symbols[i]->str;
sym::sym_idx_t idx = sym::symbols[i]->idx;
tp = (idx < 0 ? -idx : Ident);
val = i;
} else if (is_number(str)) {
tp = Number;
} else {
tp = lexem_is_special(str);
}
if (tp == Unknown) {
tp = Ident;
val = sym::symbols.lookup(str, 1);
}
return tp;
}
int Lexem::set(std::string _str, const SrcLocation& _loc, int _tp, int _val) {
str = _str;
loc = _loc;
tp = _tp;
val = _val;
return classify();
}
Lexer::Lexer(SourceReader& _src, bool init, std::string active_chars, std::string eol_cmts, std::string open_cmts,
std::string close_cmts, std::string quote_chars)
: src(_src), eof(false), lexem("", src.here(), Lexem::Undefined), peek_lexem("", {}, Lexem::Undefined) {
std::memset(char_class, 0, sizeof(char_class));
unsigned char activity = cc::active;
for (char c : active_chars) {
if (c == ' ') {
if (!--activity) {
activity = cc::allow_repeat;
}
} else if ((unsigned)c < 0x80) {
char_class[(unsigned)c] |= activity;
}
}
set_spec(eol_cmt, eol_cmts);
set_spec(cmt_op, open_cmts);
set_spec(cmt_cl, close_cmts);
for (int c : quote_chars) {
if (c > ' ' && c <= 0x7f) {
char_class[(unsigned)c] |= cc::quote_char;
}
}
if (init) {
next();
}
}
void Lexer::set_spec(std::array<int, 3>& arr, std::string setup) {
arr[0] = arr[1] = arr[2] = -0x100;
std::size_t n = setup.size(), i;
for (i = 0; i < n; i++) {
if (setup[i] == ' ') {
continue;
}
if (i == n - 1 || setup[i + 1] == ' ') {
arr[0] = setup[i];
} else if (i == n - 2 || (i < n - 2 && setup[i + 2] == ' ')) {
arr[1] = setup[i];
arr[2] = setup[++i];
} else {
while (i < n && setup[i] != ' ') {
i++;
}
}
}
}
void Lexer::expect(int exp_tp, const char* msg) {
if (tp() != exp_tp) {
throw ParseError{lexem.loc, (msg ? std::string{msg} : Lexem::lexem_name_str(exp_tp)) + " expected instead of " +
cur().name_str()};
}
next();
}
const Lexem& Lexer::next() {
if (peek_lexem.valid()) {
lexem = std::move(peek_lexem);
peek_lexem.clear({}, Lexem::Undefined);
eof = (lexem.tp == Lexem::Eof);
return lexem;
}
if (eof) {
return lexem.clear(src.here(), Lexem::Eof);
}
long long comm = 1;
while (!src.seek_eof()) {
int cc = src.cur_char(), nc = src.next_char();
if (cc == eol_cmt[0] || (cc == eol_cmt[1] && nc == eol_cmt[2])) {
src.load_line();
} else if (cc == cmt_op[1] && nc == cmt_op[2]) {
src.advance(2);
comm = comm * 2 + 1;
} else if (cc == cmt_op[0]) {
src.advance(1);
comm *= 2;
} else if (comm == 1) {
break;
} else if (cc == cmt_cl[1] && nc == cmt_cl[2]) {
if (!(comm & 1)) {
src.error(std::string{"a `"} + (char)cmt_op[0] + "` comment closed by `" + (char)cmt_cl[1] + (char)cmt_cl[2] +
"`");
}
comm >>= 1;
src.advance(2);
} else if (cc == cmt_cl[0]) {
if (!(comm & 1)) {
src.error(std::string{"a `"} + (char)cmt_op[1] + (char)cmt_op[2] + "` comment closed by `" + (char)cmt_cl[0] +
"`");
}
comm >>= 1;
src.advance(1);
} else {
src.advance(1);
}
if (comm < 0) {
src.error("too many nested comments");
}
}
if (src.seek_eof()) {
eof = true;
if (comm > 1) {
if (comm & 1) {
src.error(std::string{"`"} + (char)cmt_op[1] + (char)cmt_op[2] + "` comment extends past end of file");
} else {
src.error(std::string{"`"} + (char)cmt_op[0] + "` comment extends past end of file");
}
}
return lexem.clear(src.here(), Lexem::Eof);
}
int c = src.cur_char();
const char* end = src.get_ptr();
if (is_quote_char(c) || c == '`') {
int qc = c;
++end;
while (end < src.get_end_ptr() && *end != qc) {
++end;
}
if (*end != qc) {
src.error(qc == '`' ? "a `back-quoted` token extends past end of line" : "string extends past end of line");
}
lexem.set(std::string{src.get_ptr() + 1, end}, src.here(), qc == '`' ? Lexem::Unknown : Lexem::String);
src.set_ptr(end + 1);
// std::cerr << lexem.name_str() << ' ' << lexem.str << std::endl;
return lexem;
}
int len = 0, pc = -0x100;
while (end < src.get_end_ptr()) {
c = *end;
bool repeated = (c == pc && is_repeatable(c));
if (c == ' ' || c == 9 || (len && is_left_active(c) && !repeated)) {
break;
}
++len;
++end;
if (is_right_active(c) && !repeated) {
break;
}
pc = c;
}
lexem.set(std::string{src.get_ptr(), end}, src.here());
src.set_ptr(end);
// std::cerr << lexem.name_str() << ' ' << lexem.str << std::endl;
return lexem;
}
const Lexem& Lexer::peek() {
if (peek_lexem.valid()) {
return peek_lexem;
}
if (eof) {
return lexem.clear(src.here(), Lexem::Eof);
}
Lexem keep = std::move(lexem);
next();
peek_lexem = std::move(lexem);
lexem = std::move(keep);
eof = false;
return peek_lexem;
}
} // namespace src
| 26.020761 | 118 | 0.534574 | TONCommunity |
d802c2cc4b75ab95f2436f576382c3ea9e824257 | 420 | hpp | C++ | include/dr_util/expand.hpp | fizyr-private/dr_util | 41d21712d7eceaa09e11b95f6635bd9df952481f | [
"Apache-2.0"
] | null | null | null | include/dr_util/expand.hpp | fizyr-private/dr_util | 41d21712d7eceaa09e11b95f6635bd9df952481f | [
"Apache-2.0"
] | 2 | 2019-08-05T11:58:20.000Z | 2020-02-14T10:14:57.000Z | include/dr_util/expand.hpp | fizyr-private/dr_util | 41d21712d7eceaa09e11b95f6635bd9df952481f | [
"Apache-2.0"
] | 1 | 2019-08-05T05:24:56.000Z | 2019-08-05T05:24:56.000Z | #include <map>
#include <string>
namespace dr {
/// Expand variables in a string.
/**
* A variable can be written as $NAME or ${NAME}.
*/
std::string expandVariables(std::string const & source, std::map<std::string, std::string> const & variables);
/// Expand environment variables in a string.
/**
* A variable can be written as $NAME or ${NAME}.
*/
std::string expandEnvironment(std::string const & source);
}
| 22.105263 | 110 | 0.683333 | fizyr-private |
d80bbfde1f94d2017e9863063c31759a920681f0 | 26 | cpp | C++ | src/external_library/bitmap/BitmapImage.cpp | MatthieuHernandez/StraightforwardNeuralNetwork | e0b99a80bb1b3f76dcb08134aa0f1bc3e6b705d7 | [
"Apache-2.0"
] | 14 | 2019-08-29T07:20:19.000Z | 2022-03-22T12:51:02.000Z | src/external_library/bitmap/BitmapImage.cpp | MatthieuHernandez/StraightforwardNeuralNetwork | e0b99a80bb1b3f76dcb08134aa0f1bc3e6b705d7 | [
"Apache-2.0"
] | 7 | 2020-08-07T11:08:45.000Z | 2021-05-08T17:11:12.000Z | src/external_library/bitmap/BitmapImage.cpp | MatthieuHernandez/StraightforwardNeuralNetwork | e0b99a80bb1b3f76dcb08134aa0f1bc3e6b705d7 | [
"Apache-2.0"
] | 3 | 2020-08-07T10:53:52.000Z | 2021-02-16T22:13:22.000Z | #include "BitmapImage.hpp" | 26 | 26 | 0.807692 | MatthieuHernandez |
d80c7ea5404eb1fb95d99bc9225a5ccf76f71805 | 1,013 | cpp | C++ | 3rdparty/diy/examples/simple/read-blocks.cpp | wgq-iapcm/Parvoro- | 9459e1081ff948628358c59207d5fcd8ce60ef8f | [
"BSD-3-Clause"
] | 43 | 2016-10-23T14:52:59.000Z | 2022-03-18T20:47:06.000Z | 3rdparty/diy/examples/simple/read-blocks.cpp | wgq-iapcm/Parvoro- | 9459e1081ff948628358c59207d5fcd8ce60ef8f | [
"BSD-3-Clause"
] | 39 | 2016-11-25T22:14:09.000Z | 2022-01-13T21:44:51.000Z | 3rdparty/diy/examples/simple/read-blocks.cpp | wgq-iapcm/Parvoro- | 9459e1081ff948628358c59207d5fcd8ce60ef8f | [
"BSD-3-Clause"
] | 21 | 2016-11-28T22:08:36.000Z | 2022-03-16T10:31:32.000Z | #include <iostream>
#include <diy/master.hpp>
#include <diy/io/block.hpp>
#include "block.h"
void output(Block* b, const diy::Master::ProxyWithLink& cp)
{
std::cout << cp.gid() << " " << b->average << std::endl;
for (int i = 0; i < cp.link()->size(); ++i)
std::cout << " " << cp.link()->target(i).gid << " " << cp.link()->target(i).proc << std::endl;
}
int main(int argc, char* argv[])
{
diy::mpi::environment env(argc, argv);
diy::mpi::communicator world;
diy::Master master(world, 1, -1,
&create_block, // master will take ownership after read_blocks(),
&destroy_block); // so it needs create and destroy functions
diy::ContiguousAssigner assigner(world.size(), 0);
//diy::RoundRobinAssigner assigner(world.size(), 0); // nblocks will be filled by read_blocks()
diy::io::read_blocks("blocks.out", world, assigner, master, &load_block);
master.foreach(&output);
}
| 33.766667 | 110 | 0.574531 | wgq-iapcm |
d80cf59a55c78e5ad525148400e785da63fabd5d | 656 | cpp | C++ | Source/GameService/Net/Network/Crypto/KeyExchange.cpp | BaekTaehyun/T1Project | d7d98c7cfc88e57513631124c32dfee8794307db | [
"MIT"
] | 3 | 2019-06-25T05:09:47.000Z | 2020-09-30T18:06:17.000Z | Source/GameService/Net/Network/Crypto/KeyExchange.cpp | BaekTaehyun/T1Project | d7d98c7cfc88e57513631124c32dfee8794307db | [
"MIT"
] | null | null | null | Source/GameService/Net/Network/Crypto/KeyExchange.cpp | BaekTaehyun/T1Project | d7d98c7cfc88e57513631124c32dfee8794307db | [
"MIT"
] | 2 | 2018-10-15T08:09:16.000Z | 2020-04-07T05:25:52.000Z |
#include "KeyExchange.h"
#include <cassert>
std::vector<uint64_t> KeyExchange::getPublicKey(uint64_t p, uint64_t g, size_t count)
{
dhs_.clear();
std::vector<uint64_t> pk;
for (size_t i = 0; i < count; ++i)
{
DiffieHellman dh;
pk.push_back(dh.getPublicKey(p, g));
dhs_.push_back(dh);
}
return pk;
}
std::vector<uint8_t> KeyExchange::getSecretKey(const std::vector<uint64_t>& Bs) const
{
assert(dhs_.size() == Bs.size());
std::vector<uint8_t> sk;
for (size_t i = 0; i < dhs_.size(); ++i)
{
if (i >= Bs.size())
{
break;
}
auto s = dhs_[i].getSecretKey(Bs[i]);
sk.insert(sk.end(), s.begin(), s.end());
}
return sk;
}
| 16 | 85 | 0.625 | BaekTaehyun |
d80ddb7432a2682168f55dff3ed25a45d4aba3c9 | 1,396 | cpp | C++ | examples/cpp/src/utils/Reader.cpp | TEE-AI/SAI | f2a43d704078057c8f957f4751317e8fea75a07f | [
"Apache-2.0"
] | 34 | 2019-01-16T14:54:10.000Z | 2021-11-16T11:19:15.000Z | examples/cpp/src/utils/Reader.cpp | TEE-AI/SAI | f2a43d704078057c8f957f4751317e8fea75a07f | [
"Apache-2.0"
] | 2 | 2019-02-16T06:41:31.000Z | 2019-04-23T05:34:01.000Z | examples/cpp/src/utils/Reader.cpp | TEE-AI/SAI | f2a43d704078057c8f957f4751317e8fea75a07f | [
"Apache-2.0"
] | 4 | 2019-04-10T00:48:27.000Z | 2021-04-12T01:21:01.000Z | #include "Reader.h"
Reader::Reader(std::vector<std::string> *filelist) {
filelist_ = filelist;
fileIndex_ = 0;
processor_ = 0;
}
Reader::~Reader() {
filelist_ = 0;
fileIndex_ = 0;
processor_ = 0;
}
void Reader::register_processor(Preprocessor *processor) {
processor_ = processor;
}
ImageReader::ImageReader(std::vector<std::string> *filelist) : Reader(filelist) {}
cv::Mat ImageReader::get() {
if (fileIndex_ < filelist_->size()) {
cv::Mat cvImage= cv::imread((*filelist_)[fileIndex_++]);
if (processor_) {
cv::Mat procImage = processor_->process(cvImage);
return procImage;
}
else {
return cvImage;
}
}
else {
return cv::Mat();
}
}
/*
VideoReader::VideoReader(std::vector<std::string> *filelist) : Reader(filelist) {
// Open the first file if possible
if (fileIndex_ < filelist_->size()) {
videoCap_.open((*filelist_)[fileIndex_]);
}
}
cv::Mat VideoReader::get() {
cv::Mat rawImage;
videoCap_.read(rawImage);
if (rawImage.empty()) {
// Reach the end of the current file
fileIndex_++;
if (fileIndex_ < filelist_->size()) {
videoCap_.open((*filelist_)[fileIndex_]);
videoCap_.read(rawImage);
}
}
if (processor_) {
cv::Mat procImage = processor_->process(rawImage);
return procImage;
}
return rawImage;
}
*/
| 21.151515 | 82 | 0.611032 | TEE-AI |
d8112d6d727919c9cd82b4e19ef74e99ee43676b | 1,233 | cpp | C++ | benchmark/utils.cpp | Karamaz0V1/Higra | 216d9e47641171b5a6f8b7e2b42c269b8dc34abd | [
"CECILL-B"
] | 64 | 2019-08-18T19:23:23.000Z | 2022-03-21T04:15:04.000Z | benchmark/utils.cpp | higra/Higra | e6d5984a585f652c87d303a6a6bec19f0eb7432e | [
"CECILL-B"
] | 120 | 2019-08-16T09:10:35.000Z | 2022-03-17T09:42:58.000Z | benchmark/utils.cpp | Karamaz0V1/Higra | 216d9e47641171b5a6f8b7e2b42c269b8dc34abd | [
"CECILL-B"
] | 12 | 2019-10-04T07:35:55.000Z | 2021-01-10T19:59:11.000Z | /***************************************************************************
* Copyright ESIEE Paris (2021) *
* *
* Contributor(s) : Benjamin Perret *
* *
* Distributed under the terms of the CECILL-B License. *
* *
* The full license is in the file LICENSE, distributed with this software. *
****************************************************************************/
#include "utils.h"
using namespace hg;
bool is_power_of_two(std::size_t x) {
return (x != 0) && ((x & (x - 1)) == 0);
}
hg::tree get_complete_binary_tree(std::size_t num_leaves) {
assert(is_power_of_two(num_leaves));
array_1d<std::size_t> parent = array_1d<std::size_t>::from_shape({num_leaves * 2 - 1});
for (std::size_t i = 0, j = num_leaves; i < parent.size() - 1; j++) {
parent(i++) = j;
parent(i++) = j;
}
parent(parent.size() - 1) = parent.size() - 1;
return tree(std::move(parent));
} | 44.035714 | 91 | 0.379562 | Karamaz0V1 |
d8112d8960eb885acb99ea8d5b081331a5122bf0 | 94 | cpp | C++ | BASIC c++/beginning_with_cpp/before_oop/exercise of 4 .cpp | jattramesh/Learning_git | 5191ecc6c0c11b69b9786f2a8bdd3db7228987d6 | [
"MIT"
] | null | null | null | BASIC c++/beginning_with_cpp/before_oop/exercise of 4 .cpp | jattramesh/Learning_git | 5191ecc6c0c11b69b9786f2a8bdd3db7228987d6 | [
"MIT"
] | null | null | null | BASIC c++/beginning_with_cpp/before_oop/exercise of 4 .cpp | jattramesh/Learning_git | 5191ecc6c0c11b69b9786f2a8bdd3db7228987d6 | [
"MIT"
] | null | null | null | #include<iostream>
using namespace std;
int main()
{
int x,i;
i=-2;
cout<<-4*i++-6%4<<endl;
}
| 10.444444 | 23 | 0.617021 | jattramesh |
d8120c0c46c988618764ba5662c38ae2c5bc925c | 2,766 | cpp | C++ | qsimplespatial/paintscheme.cpp | folibis/qsimplespatial | e39b07678ced3199cc518adf251e683759442dc3 | [
"MIT"
] | 1 | 2020-03-16T09:59:28.000Z | 2020-03-16T09:59:28.000Z | qsimplespatial/paintscheme.cpp | folibis/qsimplespatial | e39b07678ced3199cc518adf251e683759442dc3 | [
"MIT"
] | null | null | null | qsimplespatial/paintscheme.cpp | folibis/qsimplespatial | e39b07678ced3199cc518adf251e683759442dc3 | [
"MIT"
] | null | null | null | /*
* The MIT License (MIT)
*
* Copyright (c) 20014 Moukhlynin Ruslan <me@ruslan.pw>
*
* paintscheme.cpp
* This file is part of the QSimpleSpatial.
*
* 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 "paintscheme.h"
#include "maptranslator.h"
#include <QColor>
#include <QDateTime>
PaintScheme::PaintScheme() :
p_colorsInitialized(false),
p_filter_func(NULL)
{
}
PaintScheme::PaintScheme(const QPen &pen, const QBrush &brush) :
p_colorsInitialized(true),
p_filter_func(NULL)
{
init(pen,brush);
}
QPen PaintScheme::GetPen() const
{
return p_pen;
}
void PaintScheme::setPen(const QPen &pen)
{
p_pen = pen;
}
QBrush PaintScheme::GetBrush() const
{
return p_brush;
}
void PaintScheme::setBrush(const QBrush &brush)
{
p_brush = brush;
}
bool PaintScheme::IsDefault()
{
return (p_filter_func == NULL);
}
void PaintScheme::init(const QPen &pen, const QBrush &brush)
{
p_pen = pen;
p_brush = brush;
}
QPair<QColor, QColor> PaintScheme::getGhostColors(Feature *feature)
{
if(p_ghostColors.contains(feature))
return p_ghostColors[feature];
qsrand(QDateTime::currentMSecsSinceEpoch());
return p_ghostColors.insert(feature,QPair<QColor,QColor>(QColor::fromRgb(rrand(130,255),rrand(130,255),rrand(130,255)),
QColor::fromRgb(rrand(130,255),rrand(130,255),rrand(130,255))))
.value();
}
void PaintScheme::SetFilterFunction(bool (*filter_func)(Feature *))
{
p_filter_func = filter_func;
}
bool PaintScheme::TestFilter(Feature *feature)
{
if(p_filter_func == NULL)
return false;
return p_filter_func(feature);
}
QSimpleSpatial::ShapeTypes PaintScheme::getShapeType()
{
return QSimpleSpatial::NullShape;
}
| 25.145455 | 123 | 0.720897 | folibis |
d8197aab074d8788bddf671d07a4e2f95f146e8b | 462 | cpp | C++ | leetcode/422. Valid Word Square/s1.cpp | zhuohuwu0603/leetcode_cpp_lzl124631x | 6a579328810ef4651de00fde0505934d3028d9c7 | [
"Fair"
] | 787 | 2017-05-12T05:19:57.000Z | 2022-03-30T12:19:52.000Z | leetcode/422. Valid Word Square/s1.cpp | aerlokesh494/LeetCode | 0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f | [
"Fair"
] | 8 | 2020-03-16T05:55:38.000Z | 2022-03-09T17:19:17.000Z | leetcode/422. Valid Word Square/s1.cpp | aerlokesh494/LeetCode | 0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f | [
"Fair"
] | 247 | 2017-04-30T15:07:50.000Z | 2022-03-30T09:58:57.000Z | // OJ: https://leetcode.com/problems/valid-word-square/
// Author: github.com/lzl124631x
// Time: O(MN)
// Space: O(1)
class Solution {
public:
bool validWordSquare(vector<string>& words) {
for (int i = 0, M = words.size(); i < M; ++i) {
for (int j = 0, N = words[i].size(); j < N; ++j) {
if (j >= M || i >= words[j].size() || words[i][j] != words[j][i]) return false;
}
}
return true;
}
}; | 30.8 | 95 | 0.493506 | zhuohuwu0603 |
d8211212f095c10cb7d9de126a936bfce4d71079 | 971 | cpp | C++ | SecondaryTreeIndexTest.cpp | spakai/index_search | 75a39d536781cb3e2f91ffea496b003ca5c51ebf | [
"Apache-2.0"
] | null | null | null | SecondaryTreeIndexTest.cpp | spakai/index_search | 75a39d536781cb3e2f91ffea496b003ca5c51ebf | [
"Apache-2.0"
] | null | null | null | SecondaryTreeIndexTest.cpp | spakai/index_search | 75a39d536781cb3e2f91ffea496b003ca5c51ebf | [
"Apache-2.0"
] | null | null | null | #include "gmock/gmock.h"
#include "SecondaryTreeIndex.h"
#include "FileTable.h"
using namespace testing;
class SecondaryTreeIndexTest : public Test {
public:
FileTable ft;
SecondaryTreeIndex index;
void SetUp() override {
ft.init("../csv/abnumber.csv");
index.buildIndex(ft, 0);
}
};
TEST_F(SecondaryTreeIndexTest,GetSizeofIndex) {
ASSERT_THAT(index.size(), Eq(5));
}
TEST_F(SecondaryTreeIndexTest,ExactMatchWhenExactMatchLookupIsCalled) {
ASSERT_THAT(index.exactMatch("00605"), ElementsAre(0,1));
}
TEST_F(SecondaryTreeIndexTest,BestMatchLookup) {
ASSERT_THAT(index.bestMatch("006051"), ElementsAre(0,1));
}
TEST_F(SecondaryTreeIndexTest,ExactMatchWhenBestMatchLookupIsCalled) {
ASSERT_THAT(index.bestMatch("00605"), ElementsAre(0,1));
}
TEST_F(SecondaryTreeIndexTest,AllMatchesLookup) {
ASSERT_THAT(index.allMatches("006051"), ElementsAre(0,1,3));
}
| 26.243243 | 71 | 0.69413 | spakai |
d82341412f1d05f2ee915c5899a853d5c0a3814b | 25,543 | cpp | C++ | Clerk/UI/Schedulers/SchedulerDialog.cpp | sergeylenkov/Clerk | b220864e89559207c5eeea113668891236fcbfb9 | [
"MIT"
] | 14 | 2016-11-01T15:48:02.000Z | 2020-07-15T13:00:27.000Z | Clerk/UI/Schedulers/SchedulerDialog.cpp | sergeylenkov/Clerk | b220864e89559207c5eeea113668891236fcbfb9 | [
"MIT"
] | 29 | 2017-11-16T04:15:33.000Z | 2021-12-22T07:15:42.000Z | Clerk/UI/Schedulers/SchedulerDialog.cpp | sergeylenkov/Clerk | b220864e89559207c5eeea113668891236fcbfb9 | [
"MIT"
] | 2 | 2018-08-15T15:25:11.000Z | 2019-01-28T12:49:50.000Z | #include "SchedulerDialog.h"
SchedulerDialog::SchedulerDialog(wxFrame *parent, const wxChar *title, int x, int y, int width, int height) : wxFrame(parent, -1, title, wxPoint(x, y), wxSize(width, height), wxDEFAULT_FRAME_STYLE & ~(wxRESIZE_BORDER | wxMAXIMIZE_BOX)) {
SetBackgroundColour(wxColor(*wxWHITE));
this->SetSizeHints(wxDefaultSize, wxDefaultSize);
this->SetIcon(wxICON(APP_ICON));
wxString allowedChars[13] = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ".", ",", " " };
wxArrayString chars(13, allowedChars);
wxTextValidator amountValidator(wxFILTER_INCLUDE_CHAR_LIST);
amountValidator.SetIncludes(chars);
int daysValue;
int dayValue;
int monthValue;
int weekValue;
wxIntegerValidator<int> daysValidator(&daysValue, wxNUM_VAL_DEFAULT);
daysValidator.SetRange(1, 365);
wxIntegerValidator<int> dayValidator(&dayValue, wxNUM_VAL_DEFAULT);
dayValidator.SetRange(1, 31);
wxIntegerValidator<int> weekValidator(&weekValue, wxNUM_VAL_DEFAULT);
weekValidator.SetRange(1, 52);
wxIntegerValidator<int> monthValidator(&monthValue, wxNUM_VAL_DEFAULT);
monthValidator.SetRange(1, 12);
wxBoxSizer *mainSizer = new wxBoxSizer(wxVERTICAL);
mainPanel = new wxPanel(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
wxBoxSizer *panelSizer = new wxBoxSizer(wxVERTICAL);
wxBoxSizer *horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
nameLabel = new wxStaticText(mainPanel, wxID_ANY, wxT("Name:"), wxDefaultPosition, wxSize(40, -1), 0);
horizontalSizer->Add(nameLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
nameField = new wxTextCtrl(mainPanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0);
horizontalSizer->Add(nameField, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5);
panelSizer->Add(horizontalSizer, 0, wxALL | wxEXPAND, 5);
wxBoxSizer *staticBoxSizer = new wxStaticBoxSizer(new wxStaticBox(mainPanel, wxID_ANY, wxT("Recurrence pattern")), wxHORIZONTAL);
wxPanel *buttonsPanel = new wxPanel(mainPanel, wxID_ANY, wxDefaultPosition, wxSize(80, -1), wxTAB_TRAVERSAL);
wxBoxSizer *buttonsSizer = new wxBoxSizer(wxVERTICAL);
dailyButton = new wxRadioButton(buttonsPanel, wxID_ANY, wxT("Daily"), wxDefaultPosition, wxDefaultSize, 0);
buttonsSizer->Add(dailyButton, 0, wxALL, 5);
weeklyButton = new wxRadioButton(buttonsPanel, wxID_ANY, wxT("Weekly"), wxDefaultPosition, wxDefaultSize, 0);
buttonsSizer->Add(weeklyButton, 0, wxALL, 5);
monthlyButton = new wxRadioButton(buttonsPanel, wxID_ANY, wxT("Monthly"), wxDefaultPosition, wxDefaultSize, 0);
buttonsSizer->Add(monthlyButton, 0, wxALL, 5);
yearlyButton = new wxRadioButton(buttonsPanel, wxID_ANY, wxT("Yearly"), wxDefaultPosition, wxDefaultSize, 0);
buttonsSizer->Add(yearlyButton, 0, wxALL, 5);
buttonsPanel->SetSizer(buttonsSizer);
buttonsPanel->Layout();
staticBoxSizer->Add(buttonsPanel, 0, wxALL, 5);
wxStaticLine *staticLine = new wxStaticLine(mainPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_VERTICAL);
staticBoxSizer->Add(staticLine, 0, wxEXPAND | wxALL, 5);
patternPanel = new wxPanel(mainPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize);
staticBoxSizer->Add(patternPanel, 1, wxEXPAND | wxALL, 5);
patternSizer = new wxBoxSizer(wxVERTICAL);
patternPanel->SetSizer(patternSizer);
patternPanel->Layout();
patternSizer->Fit(patternPanel);
panelSizer->Add(staticBoxSizer, 1, wxEXPAND | wxALL, 10);
staticBoxSizer = new wxStaticBoxSizer(new wxStaticBox(this, wxID_ANY, wxT("Transaction")), wxVERTICAL);
horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
fromLabel = new wxStaticText(mainPanel, wxID_ANY, wxT("From:"), wxDefaultPosition, wxSize(40, -1), 0);
horizontalSizer->Add(fromLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
fromList = new wxBitmapComboBox(mainPanel, wxID_ANY, wxT(""), wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY);
horizontalSizer->Add(fromList, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5);
fromAmountField = new wxTextCtrl(mainPanel, wxID_ANY, wxT("1000"), wxDefaultPosition, wxSize(80, -1), wxTE_RIGHT, amountValidator);
horizontalSizer->Add(fromAmountField, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
fromAmountLabel = new wxStaticText(mainPanel, wxID_ANY, wxT("RUB"), wxDefaultPosition, wxDefaultSize, 0);
horizontalSizer->Add(fromAmountLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
staticBoxSizer->Add(horizontalSizer, 0, wxALL | wxEXPAND, 5);
horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
toLabel = new wxStaticText(mainPanel, wxID_ANY, wxT("To:"), wxDefaultPosition, wxSize(40, -1), 0);
toLabel->Wrap(-1);
horizontalSizer->Add(toLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
toList = new wxBitmapComboBox(mainPanel, wxID_ANY, wxT(""), wxDefaultPosition, wxDefaultSize, 0, NULL, wxCB_READONLY);
horizontalSizer->Add(toList, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5);
toAmountField = new wxTextCtrl(mainPanel, wxID_ANY, wxT("1000"), wxDefaultPosition, wxSize(80, -1), wxTE_RIGHT, amountValidator);
horizontalSizer->Add(toAmountField, 0, wxALL, 5);
toAmountLabel = new wxStaticText(mainPanel, wxID_ANY, wxT("RUB"), wxDefaultPosition, wxDefaultSize, 0);
horizontalSizer->Add(toAmountLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
staticBoxSizer->Add(horizontalSizer, 0, wxALL | wxEXPAND, 5);
horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
tagsLabel = new wxStaticText(mainPanel, wxID_ANY, wxT("Tags:"), wxDefaultPosition, wxSize(40, -1), 0);
horizontalSizer->Add(tagsLabel, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
tagsField = new wxTextCtrl(mainPanel, wxID_ANY, wxEmptyString, wxDefaultPosition, wxDefaultSize, 0);
horizontalSizer->Add(tagsField, 1, wxALIGN_CENTER_VERTICAL | wxALL, 5);
staticBoxSizer->Add(horizontalSizer, 0, wxALL | wxEXPAND, 5);
panelSizer->Add(staticBoxSizer, 1, wxEXPAND | wxALL, 10);
horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
okButton = new wxButton(mainPanel, wxID_ANY, wxT("OK"), wxDefaultPosition, wxDefaultSize, 0);
horizontalSizer->Add(okButton, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
cancelButton = new wxButton(mainPanel, wxID_ANY, wxT("Cancel"), wxDefaultPosition, wxDefaultSize, 0);
horizontalSizer->Add(cancelButton, 0, wxALIGN_CENTER_VERTICAL | wxALL, 5);
panelSizer->Add(horizontalSizer, 0, wxALIGN_RIGHT | wxALL, 5);
//
dailyPatternPanel = new wxPanel(patternPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
wxStaticText *dailyPatternLabel = new wxStaticText(dailyPatternPanel, wxID_ANY, wxT("Every"), wxDefaultPosition, wxDefaultSize, 0);
horizontalSizer->Add(dailyPatternLabel, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5);
dailyDayField = new wxTextCtrl(dailyPatternPanel, wxID_ANY, wxT("1"), wxDefaultPosition, wxSize(40, -1), wxTE_RIGHT, daysValidator);
horizontalSizer->Add(dailyDayField, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5);
wxStaticText *daysLabel = new wxStaticText(dailyPatternPanel, wxID_ANY, wxT("days"), wxDefaultPosition, wxDefaultSize, 0);
horizontalSizer->Add(daysLabel, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5);
dailyPatternPanel->SetSizer(horizontalSizer);
dailyPatternPanel->Layout();
horizontalSizer->Fit(dailyPatternPanel);
patternSizer->Add(dailyPatternPanel, 0, wxALIGN_TOP | wxALL, 0);
//
weeklyPatternPanel = new wxPanel(patternPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
wxBoxSizer *verticalSizer = new wxBoxSizer(wxVERTICAL);
horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
wxStaticText *m_staticText1011 = new wxStaticText(weeklyPatternPanel, wxID_ANY, wxT("Every"), wxDefaultPosition, wxDefaultSize, 0);
horizontalSizer->Add(m_staticText1011, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5);
weeklyWeekField = new wxTextCtrl(weeklyPatternPanel, wxID_ANY, wxT("1"), wxDefaultPosition, wxSize(40, -1), wxTE_RIGHT, weekValidator);
horizontalSizer->Add(weeklyWeekField, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5);
wxStaticText *m_staticText911 = new wxStaticText(weeklyPatternPanel, wxID_ANY, wxT("weeks on:"), wxDefaultPosition, wxDefaultSize, 0);
horizontalSizer->Add(m_staticText911, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5);
verticalSizer->Add(horizontalSizer, 0, wxALIGN_TOP | wxBOTTOM, 5);
wxWrapSizer *wrapSizer = new wxWrapSizer(wxHORIZONTAL, wxWRAPSIZER_DEFAULT_FLAGS);
mondayCheckBox = new wxRadioButton(weeklyPatternPanel, wxID_ANY, wxT("Monday"), wxDefaultPosition, wxDefaultSize, 0);
wrapSizer->Add(mondayCheckBox, 0, wxALL, 5);
tuesdayCheckBox = new wxRadioButton(weeklyPatternPanel, wxID_ANY, wxT("Tuesday"), wxDefaultPosition, wxDefaultSize, 0);
wrapSizer->Add(tuesdayCheckBox, 0, wxALL, 5);
wednesdayCheckBox = new wxRadioButton(weeklyPatternPanel, wxID_ANY, wxT("Wednesday"), wxDefaultPosition, wxDefaultSize, 0);
wrapSizer->Add(wednesdayCheckBox, 0, wxALL, 5);
thursdayCheckBox = new wxRadioButton(weeklyPatternPanel, wxID_ANY, wxT("Thursday"), wxDefaultPosition, wxDefaultSize, 0);
wrapSizer->Add(thursdayCheckBox, 0, wxALL, 5);
fridayCheckBox = new wxRadioButton(weeklyPatternPanel, wxID_ANY, wxT("Friday"), wxDefaultPosition, wxDefaultSize, 0);
wrapSizer->Add(fridayCheckBox, 0, wxALL, 5);
saturdayCheckBox = new wxRadioButton(weeklyPatternPanel, wxID_ANY, wxT("Saturday"), wxDefaultPosition, wxDefaultSize, 0);
wrapSizer->Add(saturdayCheckBox, 0, wxALL, 5);
sundayCheckBox = new wxRadioButton(weeklyPatternPanel, wxID_ANY, wxT("Sunday"), wxDefaultPosition, wxDefaultSize, 0);
wrapSizer->Add(sundayCheckBox, 0, wxALL, 5);
verticalSizer->Add(wrapSizer, 1, wxEXPAND, 5);
weeklyPatternPanel->SetSizer(verticalSizer);
weeklyPatternPanel->Layout();
wrapSizer->Fit(weeklyPatternPanel);
patternSizer->Add(weeklyPatternPanel, 1, wxEXPAND | wxALL, 0);
//
monthlyPatternPanel = new wxPanel(patternPanel, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxTAB_TRAVERSAL);
horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
wxStaticText *m_staticText912 = new wxStaticText(monthlyPatternPanel, wxID_ANY, wxT("Day"), wxDefaultPosition, wxDefaultSize, 0);
horizontalSizer->Add(m_staticText912, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5);
monthlyDayField = new wxTextCtrl(monthlyPatternPanel, wxID_ANY, wxT("1"), wxDefaultPosition, wxSize(40, -1), wxTE_RIGHT, dayValidator);
horizontalSizer->Add(monthlyDayField, 0, wxLEFT | wxRIGHT, 5);
wxStaticText *m_staticText1012 = new wxStaticText(monthlyPatternPanel, wxID_ANY, wxT("every"), wxDefaultPosition, wxDefaultSize, 0);
horizontalSizer->Add(m_staticText1012, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5);
monthlyMonthField = new wxTextCtrl(monthlyPatternPanel, wxID_ANY, wxT("1"), wxDefaultPosition, wxSize(40, -1), wxTE_RIGHT, monthValidator);
horizontalSizer->Add(monthlyMonthField, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5);
wxStaticText *m_staticText10121 = new wxStaticText(monthlyPatternPanel, wxID_ANY, wxT("month(s)"), wxDefaultPosition, wxDefaultSize, 0);
horizontalSizer->Add(m_staticText10121, 0, wxALIGN_CENTER_VERTICAL | wxLEFT, 5);
monthlyPatternPanel->SetSizer(horizontalSizer);
monthlyPatternPanel->Layout();
horizontalSizer->Fit(monthlyPatternPanel);
patternSizer->Add(monthlyPatternPanel, 0, wxALIGN_TOP | wxALL, 0);
//
yearlyPatternPanel = new wxPanel(patternPanel, wxID_ANY, wxDefaultPosition, wxSize(-1, -1), wxTAB_TRAVERSAL);
horizontalSizer = new wxBoxSizer(wxHORIZONTAL);
wxStaticText *m_staticText913 = new wxStaticText(yearlyPatternPanel, wxID_ANY, wxT("Every"), wxDefaultPosition, wxDefaultSize, 0);
horizontalSizer->Add(m_staticText913, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5);
yearlyDayField = new wxTextCtrl(yearlyPatternPanel, wxID_ANY, wxT("1"), wxDefaultPosition, wxSize(40, -1), wxTE_RIGHT, dayValidator);
horizontalSizer->Add(yearlyDayField, 0, wxALIGN_CENTER_VERTICAL | wxLEFT | wxRIGHT, 5);
wxString months[] = { wxT("January"), wxT("February"), wxT("March"), wxT("April"), wxT("May"), wxT("June"), wxT("Jule"), wxT("August"), wxT("September"), wxT("October"), wxT("November"), wxT("December") };
yearlyMonthChoice = new wxComboBox(yearlyPatternPanel, wxID_ANY, "", wxDefaultPosition, wxDefaultSize, 12, months, wxCB_READONLY);
yearlyMonthChoice->SetSelection(0);
horizontalSizer->Add(yearlyMonthChoice, 0, wxLEFT | wxRIGHT, 5);
yearlyPatternPanel->SetSizer(horizontalSizer);
yearlyPatternPanel->Layout();
horizontalSizer->Fit(yearlyPatternPanel);
patternSizer->Add(yearlyPatternPanel, 0, wxALIGN_TOP | wxALL, 0);
mainPanel->SetSizer(panelSizer);
mainPanel->Layout();
panelSizer->Fit(mainPanel);
mainSizer->Add(mainPanel, 1, wxEXPAND | wxALL, 0);
this->SetSizer(mainSizer);
this->Layout();
this->Centre(wxBOTH);
tagsPopup = new TagsPopup(this);
tagsPopup->OnSelectTag = std::bind(&SchedulerDialog::OnSelectTag, this);
okButton->Bind(wxEVT_BUTTON, &SchedulerDialog::OnOK, this);
cancelButton->Bind(wxEVT_BUTTON, &SchedulerDialog::OnCancel, this);
fromList->Bind(wxEVT_COMBOBOX, &SchedulerDialog::OnFromAccountSelect, this);
toList->Bind(wxEVT_COMBOBOX, &SchedulerDialog::OnToAccountSelect, this);
fromAmountField->Bind(wxEVT_KILL_FOCUS, &SchedulerDialog::OnFromAmountKillFocus, this);
toAmountField->Bind(wxEVT_KILL_FOCUS, &SchedulerDialog::OnToAmountKillFocus, this);
tagsField->Bind(wxEVT_KEY_UP, &SchedulerDialog::OnTextChanged, this);
tagsField->Bind(wxEVT_KILL_FOCUS, &SchedulerDialog::OnTagsKillFocus, this);
dailyButton->Bind(wxEVT_RADIOBUTTON, &SchedulerDialog::OnPatternSelect, this);
weeklyButton->Bind(wxEVT_RADIOBUTTON, &SchedulerDialog::OnPatternSelect, this);
monthlyButton->Bind(wxEVT_RADIOBUTTON, &SchedulerDialog::OnPatternSelect, this);
yearlyButton->Bind(wxEVT_RADIOBUTTON, &SchedulerDialog::OnPatternSelect, this);
Bind(wxEVT_CHAR_HOOK, &SchedulerDialog::OnKeyDown, this);
fromValue = 0;
toValue = 0;
/*for (auto account : DataHelper::GetInstance().GetAccountsByType(AccountType::Receipt))
{
accounts.push_back(account);
}
for (auto account : DataHelper::GetInstance().GetAccountsByType(AccountType::Deposit))
{
accounts.push_back(account);
}
for (auto account : DataHelper::GetInstance().GetAccountsByType(AccountType::Virtual))
{
accounts.push_back(account);
}
for (auto account : DataHelper::GetInstance().GetAccountsByType(AccountType::Expens))
{
accounts.push_back(account);
}
for (auto account : DataHelper::GetInstance().GetAccountsByType(AccountType::Debt))
{
accounts.push_back(account);
}*/
UpdateFromList();
SelectFromAccount(0);
UpdateToList(fromAccount);
SelectToAccount(0);
SelectPatternType(SchedulerType::Daily);
SelectWeekday(1);
nameField->SetFocus();
}
SchedulerDialog::~SchedulerDialog() {
delete tagsPopup;
}
void SchedulerDialog::SetScheduler(std::shared_ptr<SchedulerModel> scheduler) {
this->scheduler = scheduler;
/*nameField->SetValue(*scheduler->name);
fromAmountField->SetValue(wxString::Format("%.2f", scheduler->fromAmount));
toAmountField->SetValue(wxString::Format("%.2f", scheduler->toAmount));
tagsField->SetValue(*scheduler->tags);
if (scheduler->fromAccount) {
for (unsigned int i = 0; i < fromAccounts.size(); i++) {
if (scheduler->fromAccount->id == fromAccounts[i]->id) {
SelectFromAccount(i);
UpdateToList(fromAccounts[i]);
break;
}
}
}
else {
SelectFromAccount(0);
}
if (scheduler->toAccount) {
for (unsigned int i = 0; i < toAccounts.size(); i++) {
if (scheduler->toAccount->id == toAccounts[i]->id) {
SelectToAccount(i);
break;
}
}
}
else {
SelectToAccount(0);
}
fromAmountField->SetFocus();
fromAmountField->SelectAll();
SelectPatternType(scheduler->type);
if (scheduler->type == Scheduler::Type::Daily) {
dailyDayField->SetValue(wxString::Format("%d", scheduler->day));
}
if (scheduler->type == Scheduler::Type::Weekly) {
weeklyWeekField->SetValue(wxString::Format("%d", scheduler->week));
SelectWeekday(scheduler->day);
}
if (scheduler->type == Scheduler::Type::Monthly) {
monthlyDayField->SetValue(wxString::Format("%d", scheduler->day));
monthlyMonthField->SetValue(wxString::Format("%d", scheduler->month));
}
if (scheduler->type == Scheduler::Type::Yearly) {
yearlyDayField->SetValue(wxString::Format("%d", scheduler->day));
yearlyMonthChoice->SetSelection(scheduler->month);
}
nameField->SetFocus();*/
}
void SchedulerDialog::UpdateFromList() {
/*for (auto account : accounts) {
if (account->type == Account::Type::Receipt || account->type == Account::Type::Deposit || account->type == Account::Type::Virtual) {
int iconId = 0;
if (account->iconId < DataHelper::GetInstance().accountsImageList->GetImageCount()) {
iconId = account->iconId;
}
//fromList->Append(*account->name, DataHelper::GetInstance().accountsImageList->GetBitmap(iconId));
fromAccounts.push_back(account);
}
}*/
}
void SchedulerDialog::UpdateToList(std::shared_ptr<AccountModel> account) {
toList->Clear();
toAccounts.clear();
/*for (auto toAccount : accounts)
{
if (account->id == toAccount->id) {
continue;
}
if (account->type == Account::Type::Receipt) {
if (toAccount->type == Account::Type::Deposit) {
int iconId = 0;
if (toAccount->iconId < DataHelper::GetInstance().accountsImageList->GetImageCount()) {
iconId = toAccount->iconId;
}
//toList->Append(*toAccount->name, DataHelper::GetInstance().accountsImageList->GetBitmap(iconId));
toAccounts.push_back(toAccount);
}
}
else if (account->type == Account::Type::Deposit || account->type == Account::Type::Virtual) {
if (toAccount->type == Account::Type::Deposit || toAccount->type == Account::Type::Expens
|| toAccount->type == Account::Type::Debt || toAccount->type == Account::Type::Virtual) {
int iconId = 0;
if (toAccount->iconId < DataHelper::GetInstance().accountsImageList->GetImageCount()) {
iconId = toAccount->iconId;
}
toList->Append(toAccount->name, DataHelper::GetInstance().accountsImageList->GetBitmap(iconId));
toAccounts.push_back(toAccount);
}
}
}*/
}
void SchedulerDialog::SelectFromAccount(int index) {
auto account = fromAccounts[index];
fromList->Select(index);
//fromAmountLabel->SetLabel(account->currency->shortName);
fromAccount = account;
}
void SchedulerDialog::SelectToAccount(int id) {
auto account = toAccounts[id];
toList->Select(id);
//toAmountLabel->SetLabel(*account->currency->shortName);
toAccount = account;
}
void SchedulerDialog::SelectToAccount(std::shared_ptr<AccountModel> account) {
for (unsigned int i = 0; i < toAccounts.size(); i++) {
if (toAccounts[i]->id == account->id) {
SelectToAccount(i);
return;
}
}
SelectToAccount(0);
}
void SchedulerDialog::OnFromAccountSelect(wxCommandEvent &event) {
SelectFromAccount(fromList->GetSelection());
UpdateToList(fromAccount);
SelectToAccount(toAccount);
}
void SchedulerDialog::OnToAccountSelect(wxCommandEvent &event) {
SelectToAccount(toList->GetSelection());
}
void SchedulerDialog::OnOK(wxCommandEvent &event) {
/*scheduler->name = make_shared<wxString>(nameField->GetValue());
scheduler->fromAccount = fromAccounts[fromList->GetSelection()];
scheduler->toAccount = toAccounts[toList->GetSelection()];
scheduler->tags = make_shared<wxString>(tagsField->GetValue());
scheduler->type = type;
double amountValue;
wxString value = fromAmountField->GetValue();
value.Replace(" ", "");
value.Replace(",", ".");
value.ToDouble(&amountValue);
scheduler->fromAmount = amountValue;
value = toAmountField->GetValue();
value.Replace(" ", "");
value.Replace(",", ".");
value.ToDouble(&amountValue);
scheduler->toAmount = amountValue;
unsigned long intValue;
if (type == Scheduler::Type::Daily) {
dailyDayField->GetValue().ToULong(&intValue);
scheduler->day = intValue;
}
if (type == Scheduler::Type::Weekly) {
weeklyWeekField->GetValue().ToULong(&intValue);
scheduler->week = intValue;
scheduler->day = 1;
if (mondayCheckBox->GetValue()) {
scheduler->day = 1;
}
if (tuesdayCheckBox->GetValue()) {
scheduler->day = 2;
}
if (wednesdayCheckBox->GetValue()) {
scheduler->day = 3;
}
if (thursdayCheckBox->GetValue()) {
scheduler->day = 4;
}
if (fridayCheckBox->GetValue()) {
scheduler->day = 5;
}
if (saturdayCheckBox->GetValue()) {
scheduler->day = 6;
}
if (sundayCheckBox->GetValue()) {
scheduler->day = 7;
}
}
if (type == Scheduler::Type::Monthly) {
monthlyDayField->GetValue().ToULong(&intValue);
scheduler->day = intValue;
monthlyMonthField->GetValue().ToULong(&intValue);
scheduler->month = intValue;
}
if (type == Scheduler::Type::Yearly) {
yearlyDayField->GetValue().ToULong(&intValue);
scheduler->day = intValue;
scheduler->month = yearlyMonthChoice->GetSelection();
}
//TODO moved method to interactor
//scheduler->Save();
Close();
if (OnClose) {
OnClose();
}*/
}
void SchedulerDialog::OnCancel(wxCommandEvent &event) {
Close();
}
void SchedulerDialog::OnFromAmountKillFocus(wxFocusEvent &event) {
event.Skip();
/*wxString stringAmount = this->ClearAmountValue(fromAmountField->GetValue());
fromAmountField->SetValue(stringAmount);
int fromCurrencyId = fromAccounts[fromList->GetSelection()]->currency->id;
int toCurrencyId = toAccounts[toList->GetSelection()]->currency->id;
double val;
toAmountField->GetValue().ToDouble(&val);
if (val == 0 && fromCurrencyId == toCurrencyId) {
toAmountField->SetValue(fromAmountField->GetValue());
}*/
}
void SchedulerDialog::OnToAmountKillFocus(wxFocusEvent &event) {
event.Skip();
wxString stringAmount = this->ClearAmountValue(toAmountField->GetValue());
toAmountField->SetValue(stringAmount);
}
void SchedulerDialog::OnTextChanged(wxKeyEvent &event) {
if (event.GetKeyCode() == WXK_ESCAPE) {
tagsPopup->Hide();
}
else if (event.GetKeyCode() == WXK_UP) {
tagsPopup->SelectPrev();
event.StopPropagation();
}
else if (event.GetKeyCode() == WXK_DOWN) {
tagsPopup->SelectNext();
}
else if (event.GetKeyCode() == WXK_RETURN) {
AddTag();
tagsPopup->Hide();
}
else {
wxStringTokenizer tokenizer(tagsField->GetValue(), ",");
std::vector<wxString> tokens;
while (tokenizer.HasMoreTokens()) {
wxString token = tokenizer.GetNextToken().Trim(true).Trim(false);
tokens.push_back(token);
}
if (!tokens.empty()) {
//TODO
auto tags = std::vector<std::shared_ptr<wxString>>(); //DataHelper::GetInstance().GetTagsBySearch(tokens.back());
if (!tokens.empty()) {
//tagsPopup->Update(tags);
wxPoint pos = tagsField->GetScreenPosition();
wxSize size = tagsField->GetSize();
tagsPopup->Position(wxPoint(pos.x - 200, pos.y - 200 + size.GetHeight()), wxSize(200, 200));
tagsPopup->Show();
}
else {
tagsPopup->Hide();
}
}
}
event.Skip();
}
void SchedulerDialog::OnTagsKillFocus(wxFocusEvent &event) {
tagsPopup->Hide();
event.Skip();
}
void SchedulerDialog::OnSelectTag() {
AddTag();
tagsPopup->Hide();
}
void SchedulerDialog::AddTag() {
/*wxString tag = tagsPopup->GetSelectedTag();
wxString result = "";
wxStringTokenizer tokenizer(tagsField->GetValue(), ",");
vector<wxString> tokens;
while (tokenizer.HasMoreTokens()) {
wxString token = tokenizer.GetNextToken().Trim(true).Trim(false);
tokens.push_back(token);
}
for (unsigned int i = 0; i < tokens.size() - 1; i++) {
result.Append(tokens[i]);
result.Append(", ");
}
result.Append(tag);
tagsField->SetValue(result);
tagsField->SetInsertionPointEnd();*/
}
wxString SchedulerDialog::ClearAmountValue(wxString &value) {
value.Trim(true);
value.Trim(false);
value.Replace(",", ".", true);
value.Replace(" ", "", true);
return value;
}
void SchedulerDialog::OnPatternSelect(wxCommandEvent &event) {
if (dailyButton->GetValue()) {
SelectPatternType(SchedulerType::Daily);
}
if (weeklyButton->GetValue()) {
SelectPatternType(SchedulerType::Weekly);
}
if (monthlyButton->GetValue()) {
SelectPatternType(SchedulerType::Monthly);
}
if (yearlyButton->GetValue()) {
SelectPatternType(SchedulerType::Yearly);
}
}
void SchedulerDialog::SelectPatternType(SchedulerType type) {
this->type = type;
dailyPatternPanel->Hide();
weeklyPatternPanel->Hide();
monthlyPatternPanel->Hide();
yearlyPatternPanel->Hide();
if (type == SchedulerType::Daily) {
dailyButton->SetValue(true);
dailyPatternPanel->Show();
}
if (type == SchedulerType::Weekly) {
weeklyButton->SetValue(true);
weeklyPatternPanel->Show();
}
if (type == SchedulerType::Monthly) {
monthlyButton->SetValue(true);
monthlyPatternPanel->Show();
}
if (type == SchedulerType::Yearly) {
yearlyButton->SetValue(true);
yearlyPatternPanel->Show();
}
patternPanel->Layout();
}
void SchedulerDialog::SelectWeekday(int day) {
mondayCheckBox->SetValue(false);
tuesdayCheckBox->SetValue(false);
wednesdayCheckBox->SetValue(false);
thursdayCheckBox->SetValue(false);
fridayCheckBox->SetValue(false);
saturdayCheckBox->SetValue(false);
sundayCheckBox->SetValue(false);
switch (day)
{
case 1:
mondayCheckBox->SetValue(true);
break;
case 2:
tuesdayCheckBox->SetValue(true);
break;
case 3:
wednesdayCheckBox->SetValue(true);
break;
case 4:
thursdayCheckBox->SetValue(true);
break;
case 5:
fridayCheckBox->SetValue(true);
break;
case 6:
saturdayCheckBox->SetValue(true);
break;
case 7:
sundayCheckBox->SetValue(true);
break;
default:
mondayCheckBox->SetValue(true);
break;
}
}
void SchedulerDialog::OnKeyDown(wxKeyEvent &event) {
if ((int)event.GetKeyCode() == 27) {
event.StopPropagation();
Close();
}
else {
event.Skip();
}
} | 31.849127 | 237 | 0.737501 | sergeylenkov |
d835aa288ed1ec0e1c7e231d37c119144dfa4e37 | 1,482 | cpp | C++ | libyangmeeting2/src/src/YangMeetingFactory.cpp | yangxinghai/yangrtc | 92cc28ade5af6cbe22c151cd1220ab12816694e7 | [
"MIT"
] | 23 | 2021-09-13T06:24:34.000Z | 2022-03-24T10:05:12.000Z | libyangmeeting2/src/src/YangMeetingFactory.cpp | yangxinghai/yangrtc | 92cc28ade5af6cbe22c151cd1220ab12816694e7 | [
"MIT"
] | null | null | null | libyangmeeting2/src/src/YangMeetingFactory.cpp | yangxinghai/yangrtc | 92cc28ade5af6cbe22c151cd1220ab12816694e7 | [
"MIT"
] | 9 | 2021-09-13T06:27:44.000Z | 2022-03-02T00:23:17.000Z | /*
* YangUtilFactory.cpp
*
* Created on: 2020年10月17日
* Author: yang
*/
#include "YangMeetingHandleImpl.h"
#include <yangmeeting/yangmeetingtype.h>
#include <yangmeeting/YangMeetingFactory.h>
#include "yangutil/sys/YangIni.h"
#include "YangMeetingMessageHandle.h"
YangMeetingFactory::YangMeetingFactory() {
}
YangSysMessageHandle* YangMeetingFactory::createSysMessageHandle(YangMeetingContext *pcontext,YangReceiveMessageI* prec){
return new YangMeetingMessageHandle(pcontext,prec);
}
YangMeetingHandle* YangMeetingFactory::createMeetingHandle(YangMeetingContext *pcontext){
return new YangMeetingHandleImpl(pcontext);
}
YangMeetingHandle* YangMeetingFactory::getMeetingHandle(YangSysMessageHandle *phandle){
return ((YangMeetingMessageHandle*)phandle)->m_videoMeeting;
}
/**
void YangMeetingFactory::createIni(const char* p_filename,YangMeetingContext *pcontext){
YangMeetingConfigIni yi;
yi.init(p_filename);
//pcontext->m_log=new YangLog();
yi.initAudio(&pcontext->audio);
yi.initVideo(&pcontext->video);
yi.initSys(&pcontext->sys);
yi.initHd(&pcontext->hd);
yi.initEnc(&pcontext->enc);
yi.initRtc(&pcontext->rtc);
//yi.initCamera(&pcontext->camera);
//pcontext->hasVr=yi.readIntValue("sys","hasVr",0);
memset(pcontext->bgFilename, 0, sizeof(pcontext->bgFilename));
yi.readStringValue("sys", "bgFilename", pcontext->bgFilename, "/home/yang/bmp/jpg/03.jpeg");
//pcontext->isMulterCamera=0;
//pcontext->context=new YangMeetingContext1();
}
**/
| 29.64 | 121 | 0.772605 | yangxinghai |
d838ab09c72fdd45c44f768858bf4401a4632c58 | 1,513 | cpp | C++ | vivi/vivi64/CommandLine.cpp | vivisuke/openViVi | d3e57727393bfc48625945f09ca743e81bf14817 | [
"MIT"
] | 54 | 2020-02-15T23:17:25.000Z | 2021-11-14T17:13:22.000Z | vivi/vivi64/CommandLine.cpp | vivisuke/openViVi | d3e57727393bfc48625945f09ca743e81bf14817 | [
"MIT"
] | 11 | 2020-06-01T08:04:40.000Z | 2020-11-22T02:18:41.000Z | vivi/vivi64/CommandLine.cpp | vivisuke/openViVi | d3e57727393bfc48625945f09ca743e81bf14817 | [
"MIT"
] | 1 | 2020-06-01T07:51:47.000Z | 2020-06-01T07:51:47.000Z | #include <QKeyEvent>
#include "CommandLine.h"
CommandLine::CommandLine(QWidget *parent)
: QLineEdit(parent)
{
}
CommandLine::~CommandLine()
{
}
void CommandLine::focusOutEvent( QFocusEvent * event )
{
QLineEdit::focusOutEvent(event);
emit focusOut();
}
void CommandLine::keyPressEvent(QKeyEvent *event)
{
const bool ctrl = (event->modifiers() & Qt::ControlModifier) != 0;
const bool shift = (event->modifiers() & Qt::ShiftModifier) != 0;
const bool alt = (event->modifiers() & Qt::AltModifier) != 0;
if( event->key() == Qt::Key_Backspace
&& !hasSelectedText() && cursorPosition() == 1 )
{
emit escPressed();
return;
}
if( event->key() == Qt::Key_Home ) {
setCursorPosition(1);
return;
}
if( event->key() == Qt::Key_Up ) {
emit upPressed();
return;
}
if( event->key() == Qt::Key_Down ) {
emit downPressed();
return;
}
if( event->key() == Qt::Key_Left && cursorPosition() == 1 ) {
return;
}
if( event->key() == Qt::Key_A && ctrl ) {
setSelection(1, text().size());
return;
}
QLineEdit::keyPressEvent(event); // 基底クラスの処理
if( event->key() == Qt::Key_Escape ) {
emit escPressed();
}
if( event->key() == Qt::Key_Space ) {
emit spacePressed();
}
if( event->key() == Qt::Key_Slash || event->key() == Qt::Key_Backslash ) {
emit slashPressed(); // ディレクトリ区切り文字が入力された
}
if( event->key() == Qt::Key_Colon) {
emit colonPressed();
}
if( event->key() == Qt::Key_Tab) {
emit tabPressed();
}
}
bool CommandLine::focusNextPrevChild(bool next)
{
return false;
}
| 22.25 | 75 | 0.630535 | vivisuke |
d83ac1d2a5b8f88c4c3ec8caac492348a20fd75a | 1,826 | cpp | C++ | CarpOS/Keyboard.cpp | cartman300/CarpOS | c8ab9332f5cd7953601aa5b528cd3f0467770c8c | [
"Unlicense"
] | 2 | 2015-12-24T10:12:55.000Z | 2017-05-03T12:13:54.000Z | CarpOS/Keyboard.cpp | cartman300/CarpOS | c8ab9332f5cd7953601aa5b528cd3f0467770c8c | [
"Unlicense"
] | null | null | null | CarpOS/Keyboard.cpp | cartman300/CarpOS | c8ab9332f5cd7953601aa5b528cd3f0467770c8c | [
"Unlicense"
] | 1 | 2022-01-21T02:06:42.000Z | 2022-01-21T02:06:42.000Z | #include "Keyboard.h"
#include "Kernel.h"
#include <intrin.h>
#include <string.h>
byte kbdus[128] = {
0, 27, '1', '2', '3', '4', '5', '6', '7', '8', /* 9 */
'9', '0', '-', '=', '\b', /* Backspace */
'\t', /* Tab */
'q', 'w', 'e', 'r', /* 19 */
't', 'y', 'u', 'i', 'o', 'p', '[', ']', '\n', /* Enter key */
0, /* 29 - Control */
'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', ';', /* 39 */
'\'', '`', 0, /* Left shift */
'\\', 'z', 'x', 'c', 'v', 'b', 'n', /* 49 */
'm', ',', '.', '/', 0, /* Right shift */
'*',
0, /* Alt */
' ', /* Space bar */
0, /* Caps lock */
0, /* 59 - F1 key ... > */
0, 0, 0, 0, 0, 0, 0, 0,
0, /* < ... F10 */
0, /* 69 - Num lock*/
0, /* Scroll Lock */
0, /* Home key */
0, /* Up Arrow */
0, /* Page Up */
'-',
0, /* Left Arrow */
0,
0, /* Right Arrow */
'+',
0, /* 79 - End key*/
0, /* Down Arrow */
0, /* Page Down */
0, /* Insert Key */
0, /* Delete Key */
0, 0, 0,
0, /* F11 Key */
0, /* F12 Key */
0, /* All other keys are undefined */
};
bool Keyboard::CapsLock = false;
bool Keyboard::IgnoreInput = false;
void Keyboard::OnKey(byte Scancode) {
if (IgnoreInput)
return;
if (Scancode & 0x80) {
//print("RELEASED\n");
} else {
if (Scancode == 0x3A) { // Caps lock
CapsLock = !CapsLock;
SetLED((CapsLock ? 1 : 0) << 2);
return;
}
//char Key = (CapsLock ? -32 : 0) + kbdus[Scancode];
}
}
void Keyboard::SetLED(byte LED) {
while (IsBusy());
OutData(0xED);
InData();
OutData(LED);
InData();
}
bool Keyboard::IsBusy() {
return (InCommand() & 2) != 0;
}
void Keyboard::OutCommand(byte Cmd) {
__outbyte(0x64, Cmd);
}
void Keyboard::OutData(byte Data) {
__outbyte(0x60, Data);
}
byte Keyboard::InCommand() {
return __inbyte(0x64);
}
byte Keyboard::InData() {
return __inbyte(0x60);
} | 20.065934 | 63 | 0.470975 | cartman300 |
d83e3f875685afba035e04f1be00ffa7404c6728 | 6,821 | cpp | C++ | game/client/hud_redraw.cpp | DannyParker0001/Kisak-Strike | 99ed85927336fe3aff2efd9b9382b2b32eb1d05d | [
"Unlicense"
] | 252 | 2020-12-16T15:34:43.000Z | 2022-03-31T23:21:37.000Z | game/client/hud_redraw.cpp | DannyParker0001/Kisak-Strike | 99ed85927336fe3aff2efd9b9382b2b32eb1d05d | [
"Unlicense"
] | 23 | 2020-12-20T18:02:54.000Z | 2022-03-28T16:58:32.000Z | game/client/hud_redraw.cpp | DannyParker0001/Kisak-Strike | 99ed85927336fe3aff2efd9b9382b2b32eb1d05d | [
"Unlicense"
] | 42 | 2020-12-19T04:32:33.000Z | 2022-03-30T06:00:28.000Z | //===== Copyright � 1996-2005, Valve Corporation, All rights reserved. ======//
//
// Purpose:
//
// $NoKeywords: $
//
//===========================================================================//
//
// hud_redraw.cpp
//
#include "cbase.h"
#include "hudelement.h"
#include "iclientmode.h"
#include "itextmessage.h"
#include "vgui_basepanel.h"
#include "hud_crosshair.h"
#if defined( INCLUDE_SCALEFORM )
#include "HUD/sfhudflashinterface.h"
#endif
#include <vgui/ISurface.h>
// memdbgon must be the last include file in a .cpp file!!!
#include "tier0/memdbgon.h"
using namespace vgui;
//For progress bar orientations
const int CHud::HUDPB_HORIZONTAL = 0;
const int CHud::HUDPB_VERTICAL = 1;
const int CHud::HUDPB_HORIZONTAL_INV = 2;
// Called when a ConVar changes value
static void FovChanged_Callback( IConVar *pConVar, const char *pOldString, float flOldValue )
{
ConVarRef var( pConVar );
if ( engine->IsInGame() )
{
engine->ServerCmd( VarArgs( "fov %f\n", var.GetFloat() ) );
}
}
static ConVar fov_watcher( "_fov", "0", 0, "Automates fov command to server.", FovChanged_Callback );
void CHud::DoElementThink( CHudElement* pElement, vgui::Panel* pPanel )
{
bool visible = true;
//if we are globally disabling the HUD (and the pElement obeys global hiding), override the ShouldDraw check
if ( m_iDisabledCount > 0 && !pElement->GetIgnoreGlobalHudDisable() )
{
visible = false;
}
else
{
visible = pElement->ShouldDraw();
}
pElement->SetActive( visible );
pElement->Think();
if ( pPanel && pPanel->IsVisible() != visible )
{
pPanel->SetVisible( visible );
}
bool bProcessInput = visible;
#if defined( INCLUDE_SCALEFORM )
if ( bProcessInput )
{
if ( SFHudFlashInterface *pHudFlashInterface = dynamic_cast< SFHudFlashInterface * >( pElement ) )
{
if ( !pHudFlashInterface->FlashAPIIsValid() && !pHudFlashInterface->ShouldProcessInputBeforeFlashApiReady() )
bProcessInput = false;
}
}
#endif
if ( bProcessInput )
{
pElement->ProcessInput();
}
}
//-----------------------------------------------------------------------------
// Purpose: Think
//-----------------------------------------------------------------------------
void CHud::Think( void )
{
// Determine the visibility of all hud elements
CUtlVector< CHudElement * > & list = GetHudList();
CUtlVector< vgui::Panel * > & hudPanelList = GetHudPanelList();
int c = list.Count();
Assert( c == hudPanelList.Count() );
m_bEngineIsInGame = engine->IsInGame() && ( engine->IsLevelMainMenuBackground() == false );
for ( int i = 0; i < c; ++i )
{
CHudElement* pElement = list[i];
if ( !pElement->m_bWantLateUpdate )
{
DoElementThink( pElement, hudPanelList[ i ] );
}
}
// Let the active weapon at the keybits
C_BasePlayer *pPlayer = C_BasePlayer::GetLocalPlayer();
if ( pPlayer )
{
C_BaseCombatWeapon *pWeapon = pPlayer->GetActiveWeapon();
if ( pWeapon )
{
pWeapon->HandleInput();
}
}
if ( ( m_flScreenShotTime > 0 ) && ( m_flScreenShotTime < gpGlobals->curtime ) )
{
if ( !IsGameConsole() )
{
engine->ClientCmd( "screenshot" );
}
m_flScreenShotTime = -1;
}
}
void CHud::OnTimeJump(void)
{
CUtlVector< CHudElement * > & list = GetHudList();
int c = list.Count();
for ( int i = 0; i < c; ++i )
{
CHudElement* pElement = list[i];
if ( !pElement->m_bWantLateUpdate )
{
pElement->OnTimeJump();
}
}
}
void CHud::LateThink( void )
{
SNPROF("LateThink");
CUtlVector< CHudElement * > & list = GetHudList();
CUtlVector< vgui::Panel * > & hudPanelList = GetHudPanelList();
int c = list.Count();
Assert( c == hudPanelList.Count() );
m_bEngineIsInGame = engine->IsInGame() && ( engine->IsLevelMainMenuBackground() == false );
for ( int i = 0; i < c; ++i )
{
CHudElement* pElement = list[i];
if ( pElement->m_bWantLateUpdate )
{
DoElementThink( pElement, hudPanelList[ i ] );
}
}
}
//-----------------------------------------------------------------------------
// Purpose: The percentage passed in is expected and clamped to 0.0f to 1.0f
// Input : x -
// y -
// width -
// height -
// percentage -
// clr -
// type -
//-----------------------------------------------------------------------------
void CHud::DrawProgressBar( int x, int y, int width, int height, float percentage, Color& clr, unsigned char type )
{
//Clamp our percentage
percentage = MIN( 1.0f, percentage );
percentage = MAX( 0.0f, percentage );
Color lowColor = clr;
lowColor[ 0 ] /= 2;
lowColor[ 1 ] /= 2;
lowColor[ 2 ] /= 2;
//Draw a vertical progress bar
if ( type == HUDPB_VERTICAL )
{
int barOfs = height * percentage;
surface()->DrawSetColor( lowColor );
surface()->DrawFilledRect( x, y, x + width, y + barOfs );
surface()->DrawSetColor( clr );
surface()->DrawFilledRect( x, y + barOfs, x + width, y + height );
}
else if ( type == HUDPB_HORIZONTAL )
{
int barOfs = width * percentage;
surface()->DrawSetColor( lowColor );
surface()->DrawFilledRect( x, y, x + barOfs, y + height );
surface()->DrawSetColor( clr );
surface()->DrawFilledRect( x + barOfs, y, x + width, y + height );
}
else if ( type == HUDPB_HORIZONTAL_INV )
{
int barOfs = width * percentage;
surface()->DrawSetColor( clr );
surface()->DrawFilledRect( x, y, x + barOfs, y + height );
surface()->DrawSetColor( lowColor );
surface()->DrawFilledRect( x + barOfs, y, x + width, y + height );
}
}
//-----------------------------------------------------------------------------
// Purpose: The percentage passed in is expected and clamped to 0.0f to 1.0f
// Input : x -
// y -
// *icon -
// percentage -
// clr -
// type -
//-----------------------------------------------------------------------------
void CHud::DrawIconProgressBar( int x, int y, CHudTexture *icon, CHudTexture *icon2, float percentage, Color& clr, int type )
{
if ( icon == NULL )
return;
//Clamp our percentage
percentage = MIN( 1.0f, percentage );
percentage = MAX( 0.0f, percentage );
int height = icon->Height();
int width = icon->Width();
//Draw a vertical progress bar
if ( type == HUDPB_VERTICAL )
{
int barOfs = height * percentage;
icon2->DrawSelfCropped(
x, y, // Pos
0, 0, width, barOfs, // Cropped subrect
clr );
icon->DrawSelfCropped(
x, y + barOfs,
0, barOfs, width, height - barOfs, // Cropped subrect
clr );
}
else if ( type == HUDPB_HORIZONTAL )
{
int barOfs = width * percentage;
icon2->DrawSelfCropped(
x, y, // Pos
0, 0, barOfs, height, // Cropped subrect
clr );
icon->DrawSelfCropped(
x + barOfs, y,
barOfs, 0, width - barOfs, height, // Cropped subrect
clr );
}
}
| 25.077206 | 125 | 0.581586 | DannyParker0001 |
d84900f81fd56ef599a889883f58c237053d8f18 | 1,731 | cpp | C++ | BulletPhysicsWrapper/physics/bullet/cPlaneComponent.cpp | BobEh/Game-Engine | 2086336c8e0d4b49166b8f9c8b8c1db99728e206 | [
"MIT"
] | 1 | 2020-03-14T18:51:09.000Z | 2020-03-14T18:51:09.000Z | BulletPhysicsWrapper/physics/bullet/cPlaneComponent.cpp | BobEh/Game-Engine | 2086336c8e0d4b49166b8f9c8b8c1db99728e206 | [
"MIT"
] | null | null | null | BulletPhysicsWrapper/physics/bullet/cPlaneComponent.cpp | BobEh/Game-Engine | 2086336c8e0d4b49166b8f9c8b8c1db99728e206 | [
"MIT"
] | null | null | null | #include "cPlaneComponent.h"
#include "nConvert.h"
nPhysics::cPlaneComponent::cPlaneComponent(nPhysics::sPlaneDef thePlaneDef)
{
btCollisionShape* shape = new btStaticPlaneShape(nConvert::ToBullet(thePlaneDef.Normal), thePlaneDef.Constant);
btTransform transform;
transform.setIdentity();
//using motionstate is optional, it provides interpolation capabilities, and only synchronizes 'active' objects
btDefaultMotionState* myMotionState = new btDefaultMotionState(transform);
btRigidBody::btRigidBodyConstructionInfo rbInfo(0.f, myMotionState, shape, btVector3(0, 0, 0));
rbInfo.m_restitution = 0.8f;
mBody = new btRigidBody(rbInfo);
mBody->setUserPointer(this);
}
nPhysics::cPlaneComponent::~cPlaneComponent()
{
mBody->setUserPointer(0);
delete mBody->getCollisionShape();
delete mBody->getMotionState();
delete mBody;
}
void nPhysics::cPlaneComponent::GetTransform(glm::mat4& transformOut)
{
btTransform transform;
mBody->getMotionState()->getWorldTransform(transform);
nConvert::ToSimple(transform, transformOut);
}
void nPhysics::cPlaneComponent::GetPosition(glm::vec3& positionOut)
{
positionOut = position;
}
void nPhysics::cPlaneComponent::SetPosition(glm::vec3 positionIn)
{
position = positionIn;
}
void nPhysics::cPlaneComponent::GetVelocity(glm::vec3& velocityOut)
{
velocityOut = velocity;
}
int nPhysics::cPlaneComponent::GetMassType()
{
return _physicsType;
}
void nPhysics::cPlaneComponent::SetMassType(int physicsType)
{
_physicsType = physicsType;
}
std::string nPhysics::cPlaneComponent::GetPlaneType()
{
return planeType;
}
void nPhysics::cPlaneComponent::ApplyForce(const glm::vec3& force)
{
//mBody->activate(true);
//mBody->applyCentralForce(nConvert::ToBullet(force));
}
| 24.728571 | 112 | 0.780474 | BobEh |
d8496c4aae9eb9232814c8266b91bfe72bcc1201 | 12,523 | cpp | C++ | CppImport/src/manager/TranslateManager.cpp | patrick-luethi/Envision | b93e6f9bbb2a534b5534a5e48ed40a2c43baba8a | [
"BSD-3-Clause"
] | null | null | null | CppImport/src/manager/TranslateManager.cpp | patrick-luethi/Envision | b93e6f9bbb2a534b5534a5e48ed40a2c43baba8a | [
"BSD-3-Clause"
] | null | null | null | CppImport/src/manager/TranslateManager.cpp | patrick-luethi/Envision | b93e6f9bbb2a534b5534a5e48ed40a2c43baba8a | [
"BSD-3-Clause"
] | null | null | null | /***********************************************************************************************************************
**
** Copyright (c) 2011, 2014 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the
** following disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich 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.
**
**********************************************************************************************************************/
#include "TranslateManager.h"
namespace CppImport {
TranslateManager::TranslateManager(OOModel::Project* root)
: rootProject_{root}
{}
TranslateManager::~TranslateManager()
{
SAFE_DELETE(nh_);
}
void TranslateManager::setSourceManager(const clang::SourceManager* mngr)
{
nh_->setSourceManager(mngr);
}
void TranslateManager::setUtils(CppImportUtilities* utils)
{
Q_ASSERT(utils);
utils_ = utils;
}
OOModel::Module *TranslateManager::insertNamespace(clang::NamespaceDecl* namespaceDecl)
{
const QString hash = nh_->hashNameSpace(namespaceDecl);
if(nameSpaceMap_.contains(hash))
return nameSpaceMap_.value(hash);
OOModel::Module* ooModule = new OOModel::Module(QString::fromStdString(namespaceDecl->getNameAsString()));
nameSpaceMap_.insert(hash, ooModule);
if(namespaceDecl->getDeclContext()->isTranslationUnit())
rootProject_->modules()->append(ooModule);
else if(auto p = llvm::dyn_cast<clang::NamespaceDecl>(namespaceDecl->getDeclContext()))
{
const QString pHash = nh_->hashNameSpace(p);
if(!nameSpaceMap_.contains(pHash))
return nullptr;
nameSpaceMap_.value(pHash)->modules()->append(ooModule);
}
else
return nullptr;
return ooModule;
}
bool TranslateManager::insertClass(clang::CXXRecordDecl* rDecl, OOModel::Class* ooClass)
{
const QString hash = nh_->hashRecord(rDecl);
// if rdecl is not managed yet add it:
if(!classMap_.contains(hash))
{
classMap_.insert(hash,ooClass);
return true;
}
return false;
}
bool TranslateManager::insertClassTemplate(clang::ClassTemplateDecl* classTemplate, OOModel::Class* ooClass)
{
const QString hash = nh_->hashClassTemplate(classTemplate);
if(!classMap_.contains(hash))
{
classMap_.insert(hash, ooClass);
return true;
}
return false;
}
bool TranslateManager::insertClassTemplateSpec
(clang::ClassTemplateSpecializationDecl* classTemplate, OOModel::Class* ooClass)
{
const QString hash = nh_->hashClassTemplateSpec(classTemplate);
if(!classMap_.contains(hash))
{
classMap_.insert(hash, ooClass);
return true;
}
return false;
}
OOModel::Method* TranslateManager::insertMethodDecl(clang::CXXMethodDecl* mDecl, OOModel::Method::MethodKind kind)
{
OOModel::Method* method = nullptr;
// only consider methods where the parent has already been visited
if(classMap_.contains(nh_->hashRecord(mDecl->getParent())))
{
const QString hash = nh_->hashMethod(mDecl);
if(!methodMap_.contains(hash))
method = addNewMethod(mDecl, kind);
else
{
method = methodMap_.value(hash);
// If the method in the map is just a declaration and the method we currently have is a definition
// there might be some argument names in the definition which are not yet considered.
// Therefore we look at them now.
if(method->items()->size() || !mDecl->isThisDeclarationADefinition())
return method;
for(int i = 0; i< method->arguments()->size(); i++)
{
OOModel::FormalArgument* ooArg = method->arguments()->at(i);
// note that this never should/can be out of range otherwise the hash would be different
ooArg->setName(QString::fromStdString(mDecl->getParamDecl(i)->getNameAsString()));
}
return method;
}
}
return method;
}
OOModel::Method* TranslateManager::insertFunctionDecl(clang::FunctionDecl* functionDecl)
{
OOModel::Method* ooFunction = nullptr;
const QString hash = nh_->hashFunction(functionDecl);
if(!functionMap_.contains(hash))
ooFunction = addNewFunction(functionDecl);
else
{
ooFunction = functionMap_.value(hash);
if(ooFunction->items()->size())
return ooFunction;
// the method which is in the map is just a declaration
// therefore it might miss some arguments name which we collect here
for(int i = 0; i< ooFunction->arguments()->size(); i++)
{
OOModel::FormalArgument* ooArg = ooFunction->arguments()->at(i);
// note that this never should/can be out of range otherwise the hash would be different
ooArg->setName(QString::fromStdString(functionDecl->getParamDecl(i)->getNameAsString()));
}
return ooFunction;
}
return ooFunction;
}
OOModel::Field* TranslateManager::insertField(clang::FieldDecl* fieldDecl)
{
const QString hash = nh_->hashRecord(fieldDecl->getParent());
if(classMap_.contains(hash))
{
OOModel::Field* ooField = new OOModel::Field();
ooField->setName(QString::fromStdString(fieldDecl->getNameAsString()));
classMap_.value(hash)->fields()->append(ooField);
return ooField;
}
return nullptr;
}
OOModel::Field* TranslateManager::insertStaticField(clang::VarDecl* varDecl, bool& wasDeclared)
{
const QString hash = nh_->hashStaticField(varDecl);
if(staticFieldMap_.contains(hash))
{
wasDeclared = true;
return staticFieldMap_.value(hash);
}
wasDeclared = false;
const QString parentHash = nh_->hashParentOfStaticField(varDecl->getDeclContext());
if(classMap_.contains(parentHash))
{
OOModel::Field* ooField = new OOModel::Field(QString::fromStdString(varDecl->getNameAsString()));
classMap_.value(parentHash)->fields()->append(ooField);
staticFieldMap_.insert(hash, ooField);
return ooField;
}
return nullptr;
}
OOModel::ExplicitTemplateInstantiation* TranslateManager::insertExplicitTemplateInstantiation
(const clang::ClassTemplateSpecializationDecl* explicitTemplateInst)
{
OOModel::ExplicitTemplateInstantiation* ooExplicitTemplateInst = nullptr;
const QString hash = nh_->hashClassTemplateSpec(explicitTemplateInst);
if(!explicitTemplateInstMap_.contains(hash))
{
ooExplicitTemplateInst = new OOModel::ExplicitTemplateInstantiation();
explicitTemplateInstMap_.insert(hash, ooExplicitTemplateInst);
}
return ooExplicitTemplateInst;
}
OOModel::NameImport* TranslateManager::insertUsingDecl(clang::UsingDecl* usingDecl)
{
OOModel::NameImport* ooName = nullptr;
const QString hash = nh_->hashUsingDecl(usingDecl);
if(!usingDeclMap_.contains(hash))
{
ooName = new OOModel::NameImport();
usingDeclMap_.insert(hash, ooName);
}
return ooName;
}
OOModel::NameImport* TranslateManager::insertUsingDirective(clang::UsingDirectiveDecl* usingDirective)
{
OOModel::NameImport* ooName = nullptr;
const QString hash = nh_->hashUsingDirective(usingDirective);
if(!usingDirectiveMap_.contains(hash))
{
ooName = new OOModel::NameImport();
usingDirectiveMap_.insert(hash, ooName);
}
return ooName;
}
OOModel::NameImport* TranslateManager::insertUnresolvedUsing(clang::UnresolvedUsingValueDecl* unresolvedUsing)
{
OOModel::NameImport* ooName = nullptr;
const QString hash = nh_->hashUnresolvedUsingDecl(unresolvedUsing);
if(!usingDeclMap_.contains(hash))
{
ooName = new OOModel::NameImport();
usingDeclMap_.insert(hash, ooName);
}
return ooName;
}
OOModel::TypeAlias*TranslateManager::insertNamespaceAlias(clang::NamespaceAliasDecl* namespaceAlias)
{
OOModel::TypeAlias* ooAlias = nullptr;
const QString hash = nh_->hashNameSpaceAlias(namespaceAlias);
if(!namespacAliasMap_.contains(hash))
{
ooAlias = new OOModel::TypeAlias();
namespacAliasMap_.insert(hash, ooAlias);
}
return ooAlias;
}
OOModel::TypeAlias*TranslateManager::insertTypeAlias(clang::TypedefNameDecl* typeAlias)
{
OOModel::TypeAlias* ooAlias = nullptr;
const QString hash = nh_->hashTypeAlias(typeAlias);
if(!typeAliasMap_.contains(hash))
{
ooAlias = new OOModel::TypeAlias();
typeAliasMap_.insert(hash, ooAlias);
}
return ooAlias;
}
OOModel::TypeAlias* TranslateManager::insertTypeAliasTemplate(clang::TypeAliasTemplateDecl* typeAliasTemplate)
{
OOModel::TypeAlias* ooAlias = nullptr;
const QString hash = nh_->hashTypeAliasTemplate(typeAliasTemplate);
if(!typeAliasMap_.contains(hash))
{
ooAlias = new OOModel::TypeAlias();
typeAliasMap_.insert(hash, ooAlias);
}
return ooAlias;
}
OOModel::Method* TranslateManager::addNewMethod(clang::CXXMethodDecl* mDecl, OOModel::Method::MethodKind kind)
{
const QString hash = nh_->hashMethod(mDecl);
// remove type argument from name because clang has that in the name of constructors of template classes.
// template<class T> class List{ List();}; results in List<T> as name.
QString name = QString::fromStdString(mDecl->getNameAsString());
if(name.endsWith(">"))
name = name.left(name.indexOf("<"));
OOModel::Method* method = new OOModel::Method(name, kind);
if(!llvm::isa<clang::CXXConstructorDecl>(mDecl) && !llvm::isa<clang::CXXDestructorDecl>(mDecl))
{
// process result type
OOModel::Expression* restype = utils_->translateQualifiedType(mDecl->getResultType(), mDecl->getLocStart());
if(restype)
{
OOModel::FormalResult* methodResult = new OOModel::FormalResult();
methodResult->setTypeExpression(restype);
method->results()->append(methodResult);
}
}
// process arguments
clang::FunctionDecl::param_const_iterator it = mDecl->param_begin();
for(;it != mDecl->param_end();++it)
{
OOModel::FormalArgument* arg = new OOModel::FormalArgument();
arg->setName(QString::fromStdString((*it)->getNameAsString()));
OOModel::Expression* type = utils_->translateQualifiedType((*it)->getType(), (*it)->getLocStart());
if(type) arg->setTypeExpression(type);
method->arguments()->append(arg);
}
// find the correct class to add the method
if(classMap_.contains(nh_->hashRecord(mDecl->getParent())))
{
OOModel::Class* parent = classMap_.value(nh_->hashRecord(mDecl->getParent()));
parent->methods()->append(method);
}
else
std::cout << "ERROR TRANSLATEMNGR: METHOD DECL NO PARENT FOUND" << std::endl;
methodMap_.insert(hash, method);
return method;
}
OOModel::Method* TranslateManager::addNewFunction(clang::FunctionDecl* functionDecl)
{
// add a new method
OOModel::Method* ooFunction= new OOModel::Method();
ooFunction->setName(QString::fromStdString(functionDecl->getNameAsString()));
// process result type
OOModel::Expression* restype = utils_->translateQualifiedType(functionDecl->getResultType(),
functionDecl->getLocStart());
if(restype)
{
OOModel::FormalResult* methodResult = new OOModel::FormalResult();
methodResult->setTypeExpression(restype);
ooFunction->results()->append(methodResult);
}
// process arguments
clang::FunctionDecl::param_const_iterator it = functionDecl->param_begin();
for(;it != functionDecl->param_end();++it)
{
OOModel::FormalArgument* arg = new OOModel::FormalArgument();
arg->setName(QString::fromStdString((*it)->getNameAsString()));
OOModel::Expression* type = utils_->translateQualifiedType((*it)->getType(), (*it)->getLocStart());
if(type) arg->setTypeExpression(type);
ooFunction->arguments()->append(arg);
}
functionMap_.insert(nh_->hashFunction(functionDecl),ooFunction);
return ooFunction;
}
bool TranslateManager::containsClass(clang::CXXRecordDecl* recordDecl)
{
return classMap_.contains(nh_->hashRecord(recordDecl));
}
}
| 34.980447 | 120 | 0.735926 | patrick-luethi |
d84debae06b721217690a3aaa6ae822731c7984f | 345 | inl | C++ | Refureku/Library/Include/Public/Refureku/TypeInfo/Archetypes/Template/NonTypeTemplateArgument.inl | jsoysouvanh/Refureku | 7548cb3b196793119737a51c1cedc136aa60d3ee | [
"MIT"
] | 143 | 2020-04-07T21:38:21.000Z | 2022-03-30T01:06:33.000Z | Refureku/Library/Include/Public/Refureku/TypeInfo/Archetypes/Template/NonTypeTemplateArgument.inl | jsoysouvanh/Refureku | 7548cb3b196793119737a51c1cedc136aa60d3ee | [
"MIT"
] | 7 | 2021-03-30T07:26:21.000Z | 2022-03-28T16:31:02.000Z | Refureku/Library/Include/Public/Refureku/TypeInfo/Archetypes/Template/NonTypeTemplateArgument.inl | jsoysouvanh/Refureku | 7548cb3b196793119737a51c1cedc136aa60d3ee | [
"MIT"
] | 11 | 2020-06-06T09:45:12.000Z | 2022-01-25T17:17:55.000Z | /**
* Copyright (c) 2021 Julien SOYSOUVANH - All Rights Reserved
*
* This file is part of the Refureku library project which is released under the MIT License.
* See the README.md file for full license details.
*/
template <typename T>
T NonTypeTemplateArgument::getValue() const noexcept
{
return *reinterpret_cast<T const*>(getValuePtr());
} | 28.75 | 92 | 0.756522 | jsoysouvanh |
d84ebb81df863d7fc70ad11d01650f1cfb93cd31 | 72 | cpp | C++ | build/staticLib/main.cpp | NoCodeProgram/ModernCPP | ac7b05a4d720678e68878d70c0a7a69f56885d00 | [
"MIT"
] | 5 | 2020-08-17T12:14:44.000Z | 2022-01-21T06:57:56.000Z | build/staticLib/main.cpp | NoCodeProgram/ModernCPP | ac7b05a4d720678e68878d70c0a7a69f56885d00 | [
"MIT"
] | null | null | null | build/staticLib/main.cpp | NoCodeProgram/ModernCPP | ac7b05a4d720678e68878d70c0a7a69f56885d00 | [
"MIT"
] | 2 | 2022-01-18T03:20:51.000Z | 2022-02-11T14:50:19.000Z | #include "cat.h"
int main()
{
Cat kitty;
kitty.speak();
return 0;
} | 8 | 16 | 0.597222 | NoCodeProgram |
d84f0e706e3b56b718041ddfda630ecadfad0384 | 301 | cpp | C++ | c++/84-7897-268-4/cap.2/Entrada/cadena3.cpp | leopansa/libros | 1fd44aaa230eedb493f52497e82bed1ab1cc6252 | [
"MIT"
] | null | null | null | c++/84-7897-268-4/cap.2/Entrada/cadena3.cpp | leopansa/libros | 1fd44aaa230eedb493f52497e82bed1ab1cc6252 | [
"MIT"
] | null | null | null | c++/84-7897-268-4/cap.2/Entrada/cadena3.cpp | leopansa/libros | 1fd44aaa230eedb493f52497e82bed1ab1cc6252 | [
"MIT"
] | null | null | null | //PROG204.CPP - Operacion de cadenas
// Imprimir unicamente cuando detecta numeros
#include <iostream>
int main()
{
int n; //solo acepta numeros
std::cout << "Introducir numeros: " << std::endl;
while(std::cin >> n)
{
std::cout << n << std::endl;
}
return 0;
} | 17.705882 | 53 | 0.578073 | leopansa |
d851e7ebb2246acf9264a52af3b5a7d47b05970c | 2,105 | cpp | C++ | src/signal.cpp | orbitrc/blusher-qt | 23a868875fbe600a14ea6d49226226fea8931ab6 | [
"MIT"
] | null | null | null | src/signal.cpp | orbitrc/blusher-qt | 23a868875fbe600a14ea6d49226226fea8931ab6 | [
"MIT"
] | null | null | null | src/signal.cpp | orbitrc/blusher-qt | 23a868875fbe600a14ea6d49226226fea8931ab6 | [
"MIT"
] | null | null | null | #include <blusher/signal.h>
#include <stdint.h>
#include "signal-impl.h"
#ifdef emit
#undef emit
#endif
#define BLUSHER_SIGNAL_CONSTRUCTOR { this->_impl = new SignalImpl(); }
#define BLUSHER_CONNECTION_CONSTRUCTOR { this->_impl = impl; }
#define BLUSHER_CONNECTION_CONSTRUCTOR_ARG(type) template<> \
Signal<type>::Connection::Connection(ConnectionImpl *impl) \
{ this->_impl = impl; }
#define BLUSHER_CONNECTION_DISCONNECT_VOID template<> \
bool Signal<>::Connection::disconnect() \
{ return this->_impl->disconnect(); }
#define BLUSHER_CONNECTION_DISCONNECT_ARG(type) template<> \
bool Signal<type>::Connection::disconnect() \
{ return this->_impl->disconnect(); }
namespace bl {
//===============
// void
//===============
template<>
Signal<>::Signal()
BLUSHER_SIGNAL_CONSTRUCTOR
template<>
Signal<>::Connection::Connection(ConnectionImpl *impl)
BLUSHER_CONNECTION_CONSTRUCTOR
BLUSHER_CONNECTION_DISCONNECT_VOID
template<>
void Signal<>::emit()
{
this->_impl->emitSignal();
}
template<>
Signal<>::Connection Signal<>::connect(std::function<void()> slot)
{
return Connection(this->_impl->connect(slot));
}
//===============
// int
//===============
template<>
Signal<int>::Signal()
BLUSHER_SIGNAL_CONSTRUCTOR
BLUSHER_CONNECTION_CONSTRUCTOR_ARG(int)
BLUSHER_CONNECTION_DISCONNECT_ARG(int)
template<>
void Signal<int>::emit(int arg)
{
this->_impl->emitSignal(arg);
}
template<>
Signal<int>::Connection Signal<int>::connect(std::function<void(int)> slot)
{
return Connection(this->_impl->connect(slot));
}
//==================
// Surface::State
//==================
template<>
Signal<Surface::State>::Signal()
BLUSHER_SIGNAL_CONSTRUCTOR
BLUSHER_CONNECTION_CONSTRUCTOR_ARG(Surface::State)
BLUSHER_CONNECTION_DISCONNECT_ARG(Surface::State)
template<>
void Signal<Surface::State>::emit(Surface::State arg)
{
this->_impl->emitSignal(arg);
}
template<>
Signal<Surface::State>::Connection Signal<Surface::State>::connect(
std::function<void(Surface::State)> slot)
{
return Connection(this->_impl->connect(slot));
}
} // namespace bl
| 20.841584 | 75 | 0.695962 | orbitrc |
d852f59d03cc9769dfe656042d4898b851006831 | 1,598 | hpp | C++ | src/tts/include/ttsService.hpp | 3rang/TTS | 5a84b49ea08af599ad553ae27efb36b2682f3f76 | [
"MIT"
] | null | null | null | src/tts/include/ttsService.hpp | 3rang/TTS | 5a84b49ea08af599ad553ae27efb36b2682f3f76 | [
"MIT"
] | null | null | null | src/tts/include/ttsService.hpp | 3rang/TTS | 5a84b49ea08af599ad553ae27efb36b2682f3f76 | [
"MIT"
] | null | null | null |
// SPDX-FileCopyrightText: 2021 MBition GmbH
//
// SPDX-License-Identifier: Closed software
#ifndef INC_TTSSERVICE_HPP_
#define INC_TTSSERVICE_HPP_
#include <iostream>
#include <vector>
#include <cstdint>
#include <cstring>
#include <string>
#include <chrono>
#include <fstream>
#include <tensorflow/lite/interpreter.h>
#include <tensorflow/lite/kernels/register.h>
#include <tensorflow/lite/model.h>
#include <tensorflow/lite/optional_debug_tools.h>
typedef struct
{
float *mel_Data;
std::vector<int32_t> mel_Shape;
int32_t mel_bytes;
} MelGenData;
#define TFLITE_MINIMAL_CHECK(x) \
if (!(x)) { \
fprintf(stderr, "Error at %s:%d\n", __FILE__, __LINE__); \
exit(1); \
}
class ttsBase
{
public:
std::unique_ptr<tflite::FlatBufferModel> model;
std::unique_ptr<tflite::Interpreter> interpreter;
tflite::ops::builtin::BuiltinOpResolver resolver;
};
class ttsBaseMel:public ttsBase
{
private:
const char* melgenPath;
public:
ttsBaseMel(const char* melgenfile): melgenPath(melgenfile)
{
std::cout << "TTSModel melgenPath" << std::endl;
};
MelGenData interpreterBuildMel(std::vector<int32_t> &localbuf);
};
class ttsBasevocodoer:public ttsBase
{
private:
const char* vocoderPath;
public:
ttsBasevocodoer(const char* vocoderfile): vocoderPath(vocoderfile)
{
std::cout << "TTSModel vocoderfile" << std::endl;
};
std::vector<float> interpreterBuildvocoder(MelGenData &localbufV);
};
#endif /* INC_TTSSERVICE_HPP_ */
| 18.581395 | 68 | 0.673342 | 3rang |
d85738cfcfa355fa4fddd2fd103c87dcc3d0baac | 1,226 | cpp | C++ | Search/binarysearch.cpp | JobayerAhmmed/DSA_C | 2af3d702820dd3e1b9db49558e4398ea978e71ca | [
"MIT"
] | null | null | null | Search/binarysearch.cpp | JobayerAhmmed/DSA_C | 2af3d702820dd3e1b9db49558e4398ea978e71ca | [
"MIT"
] | null | null | null | Search/binarysearch.cpp | JobayerAhmmed/DSA_C | 2af3d702820dd3e1b9db49558e4398ea978e71ca | [
"MIT"
] | null | null | null | #include<stdio.h>
int parti(int* data, int left, int right)
{
int pivot = data[left + (right - left)/2];
int i = left - 1;
int j = right + 1;
while (true) {
do {
i++;
} while(data[i] < pivot);
do {
j--;
} while(data[j] > pivot);
if (i >= j)
return j;
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
void quicksort(int* data, int left, int right)
{
if (left < right) {
int p = parti(data, left, right);
quicksort(data, left, p);
quicksort(data, p + 1, right);
}
}
int binarysearch(int* data, int left, int right, int item)
{
while (left <= right) {
int p = left + (right - left) / 2;
if(data[p] < item)
left = p + 1;
else if(data[p] > item)
right = p - 1;
else
return p;
}
return -1;
}
int main()
{
int data[] = {20, 30, 40, 50, 80, 90, 100};
int n = sizeof(data) / sizeof(data[0]);
quicksort(data, 0, n-1);
int searchItem = 50;
int index = binarysearch(data, 0, n-1, searchItem);
printf("Index of %d = %d\n", searchItem, index);
return 0;
}
| 18.575758 | 58 | 0.468189 | JobayerAhmmed |
d85dfef9fd06f50ff2d53810a7109b851c3697d0 | 17,905 | cpp | C++ | opengl-text/src/freetype.cpp | Deception666/opengl-font-renderer | 32007d89389c426657d0025ec1a09f75176a1281 | [
"MIT"
] | null | null | null | opengl-text/src/freetype.cpp | Deception666/opengl-font-renderer | 32007d89389c426657d0025ec1a09f75176a1281 | [
"MIT"
] | null | null | null | opengl-text/src/freetype.cpp | Deception666/opengl-font-renderer | 32007d89389c426657d0025ec1a09f75176a1281 | [
"MIT"
] | null | null | null | #include "freetype.h"
#include "error_reporting_private.h"
#include <algorithm>
#if __linux__
#include <cstdlib>
#include <filesystem>
#endif
#include <stdexcept>
#include <utility>
#if _WIN32
#include <windows.h>
#elif __linux__
#include <dlfcn.h>
#endif
namespace opengl
{
template < typename T >
inline T GetFuncAddress(
const char * const function,
void * const module,
T ) noexcept
{
#if _WIN32
return
reinterpret_cast< T >(
GetProcAddress(
reinterpret_cast< const HMODULE >(module),
function));
#elif __linux__
return
reinterpret_cast< T >(
dlsym(
module,
function));
#else
#error "Define for this platform!"
#endif
}
template < size_t OFFSET, typename T >
T GetBitmapData(
const FT_Face::pointer ft_face ) noexcept
{
#if _WIN32
#if _M_IX86
const size_t glyph_offset { 84 };
const size_t bitmap_offset { 76 };
#elif _M_X64
const size_t glyph_offset { 120 };
const size_t bitmap_offset { 104 };
#else
#define "Define for this platform type!"
#endif // _M_IX86
#elif __linux__
#if __i386__
const size_t glyph_offset { 84 };
const size_t bitmap_offset { 76 };
#elif __x86_64__
const size_t glyph_offset { 152 };
const size_t bitmap_offset { 152 };
#else
#define "Define for this platform type!"
#endif // __i386__
#else
#error "Define for this platform type!"
#endif // _WIN32
const uint8_t * const glyph =
reinterpret_cast< const uint8_t * >(
*reinterpret_cast< const size_t * >(
reinterpret_cast< const uint8_t * >(
ft_face) + glyph_offset));
return
*reinterpret_cast< const T * >(
glyph + bitmap_offset + OFFSET);
}
template < size_t OFFSET, typename T >
T GetGlyphData(
const FT_Face::pointer ft_face ) noexcept
{
#if _WIN32
#if _M_IX86
const size_t glyph_offset { 84 };
#elif _M_X64
const size_t glyph_offset { 120 };
#else
#error "Define for this platform type!"
#endif // _M_IX86
#elif __linux__
#if __i386__
const size_t glyph_offset { 84 };
#elif __x86_64__
const size_t glyph_offset { 152 };
#else
#error "Define for this platform type!"
#endif // __i386__
#else
#error "Define for this platform type!"
#endif // _WIN32
const uint8_t * const glyph =
reinterpret_cast< const uint8_t * >(
*reinterpret_cast< const size_t * >(
reinterpret_cast< const uint8_t * >(
ft_face) + glyph_offset));
return
*reinterpret_cast< const T * >(
glyph + OFFSET);
}
template < size_t OFFSET, typename T >
T GetFaceData(
const FT_Face::pointer ft_face ) noexcept
{
const uint8_t * const face =
reinterpret_cast< const uint8_t * >(
ft_face);
return
*reinterpret_cast< const T * >(
face + OFFSET);
}
std::shared_ptr< FreeType >
FreeType::Create( ) noexcept
{
std::shared_ptr< FreeType >
instance;
#if _WIN32 || __linux__
const char * const module_name =
#if _WIN32
#ifdef NDEBUG
"freetype.dll";
#else
"freetyped.dll";
#endif
const auto module =
LoadLibrary(
module_name);
#elif __linux__
#ifdef NDEBUG
"libfreetype.so.6";
#else
"libfreetype.so.6";
#endif
const auto module =
dlopen(
module_name,
RTLD_NOW);
#endif
try
{
if (!module)
{
throw
std::runtime_error {
"Unable to open freetype library " +
std::string { module_name } };
}
else
{
instance.reset(
new FreeType {
FT_Module {
module,
[ ] (
void * const module )
{
#if _WIN32
FreeLibrary(
static_cast< HMODULE >(
module));
#elif __linux__
dlclose(
module);
#endif
}
}});
}
}
catch (const std::exception & e)
{
ReportError(
e.what());
}
#else
#error "Define for this platform!"
#endif // _WIN32
return
instance;
}
#if __linux__
std::string ConstructFontPath(
const std::string & font_filename ) noexcept
{
std::string font_abs_path;
const auto home_dir =
std::getenv(
"HOME");
const std::string root_dirs[] {
home_dir ?
std::string { home_dir } + "/.fonts" :
std::string { },
"/usr/local/share/fonts",
"/usr/share/fonts"
};
for (const auto root_dir : root_dirs)
{
try
{
for (const auto & dir_entry :
std::filesystem::recursive_directory_iterator(
root_dir))
{
if (dir_entry.is_regular_file() &&
dir_entry.path().filename() == font_filename)
{
font_abs_path =
dir_entry.path();
break;
}
}
}
catch (const std::exception & e)
{
ReportError(
e.what());
}
}
return font_abs_path;
}
#endif // __linux__
bool FreeType::SetFont(
const std::string & font_filename ) noexcept
{
bool set { false };
#if _WIN32
const std::string font_abs_path =
"c:/windows/fonts/" +
font_filename;
#elif __linux__
const std::string font_abs_path =
ConstructFontPath(
font_filename);
#else
#error "Define for this platform!"
#endif // _WIN32
FT_Face::pointer face_ptr { nullptr };
const auto face_created =
new_face_(
instance_.get(),
font_abs_path.c_str(),
0,
&face_ptr);
if (face_created == 0)
{
FT_Face face {
face_ptr,
face_.get_deleter()
};
if (SetSize(face.get(), size_))
{
face_.reset(
face.release());
glyphs_.clear();
font_filename_ = font_filename;
set = true;
}
}
return set;
}
const std::string & FreeType::GetFont( ) const noexcept
{
return
font_filename_;
}
bool FreeType::SetSize(
const uint32_t size ) noexcept
{
bool set { false };
if (face_)
{
set =
SetSize(
face_.get(),
size);
if (set)
{
size_ = size;
glyphs_.clear();
}
}
return set;
}
uint32_t FreeType::GetSize( ) const noexcept
{
return size_;
}
const FreeType::Glyph * FreeType::GetGlyph(
const uint32_t character ) noexcept
{
const Glyph * glyph_ptr { nullptr };
if (face_)
{
decltype(glyphs_)::const_iterator glyph_it =
glyphs_.find(
character);
if (glyph_it != glyphs_.cend())
{
glyph_ptr =
&glyph_it->second;
}
else
{
const int32_t FT_LOAD_RENDER { 1 << 2 };
const bool loaded =
load_char_(
face_.get(),
character,
FT_LOAD_RENDER) == 0;
if (loaded)
{
const auto bitmap_width =
GetBitmapWidth(face_.get());
const auto bitmap_height =
GetBitmapHeight(face_.get());
Glyph glyph {
bitmap_width,
bitmap_height,
GetGlyphTop(face_.get()),
GetGlyphLeft(face_.get()),
GetGlyphAdvance(face_.get()),
std::vector< uint8_t > (
bitmap_width * bitmap_height )
};
if (const auto data =
GetBitmapData(face_.get()))
{
std::copy(
data,
data + glyph.bitmap.size(),
glyph.bitmap.data());
}
const auto inserted =
glyphs_.emplace(
character,
std::move(glyph));
if (inserted.second)
{
glyph_ptr =
&inserted.first->second;
}
}
}
}
return glyph_ptr;
}
double FreeType::GetGlobalGlyphHeight( ) const noexcept
{
double global_glyph_height { 0.0 };
if (face_)
{
const auto units_per_em =
GetFaceUnitsPerEM(face_.get());
if (units_per_em)
{
const auto ascender =
GetFaceAscender(face_.get());
const auto descender =
GetFaceDescender(face_.get());
global_glyph_height =
static_cast< double >(ascender - descender) *
GetSize() / units_per_em;
}
}
return
global_glyph_height;
}
FreeType::FreeType(
FT_Module module ) :
init_ { GetFuncAddress("FT_Init_FreeType", module.get(), init_) },
uninit_ { GetFuncAddress("FT_Done_FreeType", module.get(), uninit_) },
version_ { GetFuncAddress("FT_Library_Version", module.get(), version_) },
new_face_ { GetFuncAddress("FT_New_Face", module.get(), new_face_) },
delete_face_ { GetFuncAddress("FT_Done_Face", module.get(), delete_face_) },
set_pixel_sizes_ { GetFuncAddress("FT_Set_Pixel_Sizes", module.get(), set_pixel_sizes_) },
load_char_ { GetFuncAddress("FT_Load_Char", module.get(), load_char_) },
size_ { 48 },
glyphs_ { 128 },
module_ { std::move(module) },
instance_ { nullptr, uninit_ },
face_ { nullptr, delete_face_ }
{
if (!init_ || !uninit_ || !version_ ||
!new_face_ || !delete_face_ ||
!set_pixel_sizes_ || !load_char_)
{
throw
std::runtime_error {
"Required FreeType functions not found!"
};
}
FT_Instance::pointer instance { nullptr };
if (init_(&instance) != 0)
{
throw
std::runtime_error {
"Unable to initialize a FT instnace!"
};
}
instance_.reset(
instance);
int32_t version_mmp[3] { };
version_(
instance,
version_mmp + 0,
version_mmp + 1,
version_mmp + 2);
const uint32_t version {
static_cast< uint32_t >(version_mmp[0] << 16) |
static_cast< uint32_t >(version_mmp[1] << 8) |
static_cast< uint32_t >(version_mmp[2]) };
// assume that versions greater than the one
// specified below are compatible with this impl
if (version < 0x00020A00)
{
throw
std::runtime_error {
"FreeType version must be 2.10.4 or greater!"
};
}
else if (version >= 0x00030000)
{
throw
std::runtime_error {
"FreeType version validated with 2.x.x of the library! "
"A major version upgrade may no longer be compatible!"
};
}
}
bool FreeType::SetSize(
const FT_Face::pointer face,
const uint32_t size ) noexcept
{
bool set { false };
if (face)
{
set =
set_pixel_sizes_(
face,
0,
size) == 0;
}
return set;
}
uint32_t FreeType::GetBitmapWidth(
const FT_Face::pointer face ) const noexcept
{
#if _WIN32
#if _M_IX86
const size_t BITMAP_WIDTH_OFFSET { 4 };
#elif _M_X64
const size_t BITMAP_WIDTH_OFFSET { 4 };
#else
#error "Define for this platform type!"
#endif // _M_IX86
#elif __linux__
#if __i386__
const size_t BITMAP_WIDTH_OFFSET { 4 };
#elif __x86_64__
const size_t BITMAP_WIDTH_OFFSET { 4 };
#else
#error "Define for this platform type!"
#endif // __i386__
#else
#error "Define for this platform type!"
#endif // _WIN32
return
face ?
opengl::GetBitmapData<
BITMAP_WIDTH_OFFSET,
uint32_t >(
face) :
0ul;
}
uint32_t FreeType::GetBitmapHeight(
const FT_Face::pointer face ) const noexcept
{
#if _WIN32
#if _M_IX86
const size_t BITMAP_HEIGHT_OFFSET { 0 };
#elif _M_X64
const size_t BITMAP_HEIGHT_OFFSET { 0 };
#else
#error "Define for this platform type!"
#endif // _M_IX86
#elif __linux__
#if __i386__
const size_t BITMAP_HEIGHT_OFFSET { 0 };
#elif __x86_64__
const size_t BITMAP_HEIGHT_OFFSET { 0 };
#else
#error "Define for this platform type!"
#endif // __i386__
#else
#error "Define for this platform type!"
#endif // _WIN32
return
face ?
opengl::GetBitmapData<
BITMAP_HEIGHT_OFFSET,
uint32_t >(
face) :
0ul;
}
const uint8_t * FreeType::GetBitmapData(
const FT_Face::pointer face ) const noexcept
{
#if _WIN32
#if _M_IX86
const size_t BITMAP_DATA_OFFSET { 12 };
#elif _M_X64
const size_t BITMAP_DATA_OFFSET { 16 };
#else
#error "Define for this platform type!"
#endif // _M_IX86
#elif __linux__
#if __i386__
const size_t BITMAP_DATA_OFFSET { 12 };
#elif __x86_64__
const size_t BITMAP_DATA_OFFSET { 16 };
#else
#error "Define for this platform type!"
#endif // __i386__
#else
#error "Define for this platform type!"
#endif // _WIN32
return
face ?
opengl::GetBitmapData<
BITMAP_DATA_OFFSET,
const uint8_t * >(
face) :
nullptr;
}
int32_t FreeType::GetGlyphTop(
const FT_Face::pointer face ) const noexcept
{
#if _WIN32
#if _M_IX86
const size_t GLYPH_TOP_OFFSET { 104 };
#elif _M_X64
const size_t GLYPH_TOP_OFFSET { 148 };
#else
#error "Define for this platform type!"
#endif // _M_IX86
#elif __linux__
#if __i386__
const size_t GLYPH_TOP_OFFSET { 104 };
#elif __x86_64__
const size_t GLYPH_TOP_OFFSET { 196 };
#else
#error "Define for this platform type!"
#endif // __i386__
#else
#error "Define for this platform type!"
#endif // _WIN32
return
face ?
opengl::GetGlyphData<
GLYPH_TOP_OFFSET,
int32_t >(
face) :
0;
}
int32_t FreeType::GetGlyphLeft(
const FT_Face::pointer face ) const noexcept
{
#if _WIN32
#if _M_IX86
const size_t GLYPH_LEFT_OFFSET { 100 };
#elif _M_X64
const size_t GLYPH_LEFT_OFFSET { 144 };
#else
#error "Define for this platform type!"
#endif // _M_IX86
#elif __linux__
#if __i386__
const size_t GLYPH_LEFT_OFFSET { 100 };
#elif __x86_64__
const size_t GLYPH_LEFT_OFFSET { 192 };
#else
#error "Define for this platform type!"
#endif // __i386__
#else
#error "Define for this platform type!"
#endif // _WIN32
return
face ?
opengl::GetGlyphData<
GLYPH_LEFT_OFFSET,
int32_t >(
face) :
0;
}
double FreeType::GetGlyphAdvance(
const FT_Face::pointer face ) const noexcept
{
#if _WIN32
#if _M_IX86
const size_t GLYPH_ADVANCE_OFFSET { 64 };
#elif _M_X64
const size_t GLYPH_ADVANCE_OFFSET { 88 };
#else
#error "Define for this platform type!"
#endif // _M_IX86
#elif __linux__
#if __i386__
const size_t GLYPH_ADVANCE_OFFSET { 64 };
#elif __x86_64__
const size_t GLYPH_ADVANCE_OFFSET { 128 };
#else
#error "Define for this platform type!"
#endif // __i386__
#else
#error "Define for this platform type!"
#endif // _WIN32
return
face ?
opengl::GetGlyphData<
GLYPH_ADVANCE_OFFSET,
int32_t >(
face) / 64.0 :
0.0;
}
uint16_t FreeType::GetFaceUnitsPerEM(
const FT_Face::pointer face ) const noexcept
{
#if _WIN32
#if _M_IX86
const size_t FACE_UNITS_PER_EM_OFFSET { 68 };
#elif _M_X64
const size_t FACE_UNITS_PER_EM_OFFSET { 104 };
#else
#error "Define for this platform type!"
#endif // _M_IX86
#elif __linux__
#if __i386__
const size_t FACE_UNITS_PER_EM_OFFSET { 68 };
#elif __x86_64__
const size_t FACE_UNITS_PER_EM_OFFSET { 136 };
#else
#error "Define for this platform type!"
#endif // __i386__
#else
#error "Define for this platform type!"
#endif // _WIN32
return
face ?
opengl::GetFaceData<
FACE_UNITS_PER_EM_OFFSET,
uint16_t >(
face) :
0;
}
int16_t FreeType::GetFaceAscender(
const FT_Face::pointer face ) const noexcept
{
#if _WIN32
#if _M_IX86
const size_t FACE_ASCENDER_OFFSET { 70 };
#elif _M_X64
const size_t FACE_ASCENDER_OFFSET { 106 };
#else
#error "Define for this platform type!"
#endif // _M_IX86
#elif __linux__
#if __i386__
const size_t FACE_ASCENDER_OFFSET { 70 };
#elif __x86_64__
const size_t FACE_ASCENDER_OFFSET { 138 };
#else
#error "Define for this platform type!"
#endif // __i386__
#else
#error "Define for this platform type!"
#endif // _WIN32
return
face ?
opengl::GetFaceData<
FACE_ASCENDER_OFFSET,
int16_t >(
face) :
0;
}
int16_t FreeType::GetFaceDescender(
const FT_Face::pointer face ) const noexcept
{
#if _WIN32
#if _M_IX86
const size_t FACE_DESCENDER_OFFSET { 72 };
#elif _M_X64
const size_t FACE_DESCENDER_OFFSET { 108 };
#else
#error "Define for this platform type!"
#endif // _M_IX86
#elif __linux__
#if __i386__
const size_t FACE_DESCENDER_OFFSET { 72 };
#elif __x86_64__
const size_t FACE_DESCENDER_OFFSET { 140 };
#else
#error "Define for this platform type!"
#endif // __i386__
#else
#error "Define for this platform type!"
#endif // _WIN32
return
face ?
opengl::GetFaceData<
FACE_DESCENDER_OFFSET,
int16_t >(
face) :
0;
}
} // namespace opengl
| 20.771462 | 91 | 0.569171 | Deception666 |
d86271b0f08f0d5601052f4675e6e7657ab7cf56 | 576 | tpp | C++ | rb_tree/includes/btree_level_count.tpp | paulahemsi/ft_containers | c7d6c878c25bf4faeb60f86f977639c8a7006776 | [
"MIT"
] | 1 | 2022-03-02T15:14:16.000Z | 2022-03-02T15:14:16.000Z | rb_tree/includes/btree_level_count.tpp | paulahemsi/ft_containers | c7d6c878c25bf4faeb60f86f977639c8a7006776 | [
"MIT"
] | 73 | 2021-12-11T18:54:53.000Z | 2022-03-28T01:32:52.000Z | rb_tree/includes/btree_level_count.tpp | paulahemsi/ft_containers | c7d6c878c25bf4faeb60f86f977639c8a7006776 | [
"MIT"
] | null | null | null |
#ifndef BTREE_LEVEL_COUNT_TPP
#define BTREE_LEVEL_COUNT_TPP
#include "btree.tpp"
template <class T>
size_t max_depth(size_t left_depth, size_t right_depth, ft::btree<T> *root)
{
root++;
root--;
if (left_depth > right_depth)
return (left_depth);
return (right_depth);
}
template <class T>
size_t btree_level_count(ft::btree<T> *root)
{
if (!root || (!root->left && !root->right))
return (0);
size_t left_level = btree_level_count(root->left);
size_t right_level = btree_level_count(root->right);
return (1 + max_depth(left_level, right_level, root));
}
#endif
| 20.571429 | 75 | 0.722222 | paulahemsi |
d86274ba27915117d292cc9a571897383778152b | 1,295 | cpp | C++ | Fw/Log/test/ut/LogTest.cpp | AlperenCetin0/fprime | 7e20febd34019c730da1358567e7a512592de4d8 | [
"Apache-2.0"
] | 9,182 | 2017-07-06T15:51:35.000Z | 2022-03-30T11:20:33.000Z | Fw/Log/test/ut/LogTest.cpp | AlperenCetin0/fprime | 7e20febd34019c730da1358567e7a512592de4d8 | [
"Apache-2.0"
] | 719 | 2017-07-14T17:56:01.000Z | 2022-03-31T02:41:35.000Z | Fw/Log/test/ut/LogTest.cpp | AlperenCetin0/fprime | 7e20febd34019c730da1358567e7a512592de4d8 | [
"Apache-2.0"
] | 1,216 | 2017-07-12T15:41:08.000Z | 2022-03-31T21:44:37.000Z | #include <gtest/gtest.h>
#include <Fw/Log/LogPacket.hpp>
#include <Fw/Com/ComBuffer.hpp>
#include <Fw/Log/LogString.hpp>
TEST(FwLogTest,LogPacketSerialize) {
// Serialize data
Fw::LogPacket pktIn;
Fw::LogBuffer buffIn;
ASSERT_EQ(Fw::FW_SERIALIZE_OK,buffIn.serialize(static_cast<U32>(12)));
Fw::Time timeIn(TB_WORKSTATION_TIME,10,11);
pktIn.setId(10);
pktIn.setTimeTag(timeIn);
pktIn.setLogBuffer(buffIn);
Fw::ComBuffer comBuff;
ASSERT_EQ(Fw::FW_SERIALIZE_OK,comBuff.serialize(pktIn));
// Deserialize data
Fw::LogPacket pktOut;
Fw::LogBuffer buffOut;
Fw::Time timeOut(TB_WORKSTATION_TIME,10,11);
ASSERT_EQ(Fw::FW_SERIALIZE_OK,comBuff.deserialize(pktOut));
ASSERT_EQ(pktOut.getId(),10u);
ASSERT_EQ(pktOut.getTimeTag(),timeOut);
U32 valOut = 0;
buffOut = pktOut.getLogBuffer();
buffOut.resetDeser();
ASSERT_EQ(Fw::FW_SERIALIZE_OK,buffOut.deserialize(valOut));
ASSERT_EQ(valOut,12u);
// serialize string
Fw::LogStringArg str1;
Fw::LogStringArg str2;
str1 = "Foo";
buffOut.resetSer();
str1.serialize(buffOut);
str2.deserialize(buffOut);
ASSERT_EQ(str1,str2);
}
int main(int argc, char* argv[]) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 25.392157 | 74 | 0.689575 | AlperenCetin0 |
d866d581aab7118ca1f78c0f9c33c451a948e370 | 780 | cpp | C++ | CtCI/chapter20/20.5.cpp | wqw547243068/DS_Algorithm | 6d4a9baeb3650a8f93308c7405c9483bac59e98b | [
"RSA-MD"
] | 2 | 2021-12-29T14:42:51.000Z | 2021-12-29T14:46:45.000Z | CtCI/chapter20/20.5.cpp | wqw547243068/DS_Algorithm | 6d4a9baeb3650a8f93308c7405c9483bac59e98b | [
"RSA-MD"
] | null | null | null | CtCI/chapter20/20.5.cpp | wqw547243068/DS_Algorithm | 6d4a9baeb3650a8f93308c7405c9483bac59e98b | [
"RSA-MD"
] | null | null | null | #include <iostream>
using namespace std;
const int kMaxInt = ~(1<<31);
int ShortestDist(string text[], int n, string word1, string word2){
int min = kMaxInt / 2;
int pos1 = -min;
int pos2 = -min;
for(int pos=0; pos<n; ++pos){
if(text[pos] == word1){
pos1 = pos;
int dist = pos1 - pos2;
if(dist < min)
min = dist;
}
else if(text[pos] == word2){
pos2 = pos;
int dist = pos2 - pos1;
if(dist < min)
min = dist;
}
}
return min;
}
int main(){
string text[] = {
"What","is","your","name","My","name","is","Hawstein"
};
int len = 8;
cout<<ShortestDist(text, len, "is", "name")<<endl;
return 0;
}
| 21.666667 | 67 | 0.465385 | wqw547243068 |
d867313f72aa79a829de0e99bb03d1657692db2e | 3,923 | hpp | C++ | include/h3api/H3Creatures/H3CreatureInformation.hpp | Patrulek/H3API | 91f10de37c6b86f3160706c1fdf4792f927e9952 | [
"MIT"
] | 14 | 2020-09-07T21:49:26.000Z | 2021-11-29T18:09:41.000Z | include/h3api/H3Creatures/H3CreatureInformation.hpp | Day-of-Reckoning/H3API | a82d3069ec7d5127b13528608d5350d2b80d57be | [
"MIT"
] | 2 | 2021-02-12T15:52:31.000Z | 2021-02-12T16:21:24.000Z | include/h3api/H3Creatures/H3CreatureInformation.hpp | Day-of-Reckoning/H3API | a82d3069ec7d5127b13528608d5350d2b80d57be | [
"MIT"
] | 8 | 2021-02-12T15:52:41.000Z | 2022-01-31T15:28:10.000Z | //////////////////////////////////////////////////////////////////////
// //
// Created by RoseKavalier: //
// rosekavalierhc@gmail.com //
// Created or last updated on: 2021-02-02 //
// ***You may use or distribute these files freely //
// so long as this notice remains present.*** //
// //
//////////////////////////////////////////////////////////////////////
#pragma once
#include "h3api/H3Base.hpp"
#include "h3api/H3GameData/H3Resources.hpp"
#include "h3api/H3Constants/H3CstCreatures.hpp"
namespace h3
{
_H3API_DECLARE_(CreatureInformation);
#pragma pack(push, 4)
// * hardcoded creature information in heroes3.exe
struct H3CreatureInformation
{
_H3API_SIZE_(0x74);
_H3API_GET_INFO_(0x6747B0, H3CreatureInformation);
/** @brief [0] */
// -1 means neutral
INT32 town;
/** @brief [4] */
// 0 ~ 6
INT32 level;
/** @brief [8] */
LPCSTR soundName;
/** @brief [C] */
LPCSTR defName;
/** @brief [10] */
union
{
struct
{
unsigned doubleWide : 1; // 1
unsigned flyer : 1; // 2
unsigned shooter : 1; // 4
unsigned extendedAttack : 1; // 8 ~ aka dragon breath
unsigned alive : 1; // 10
unsigned destroyWalls : 1; // 20
unsigned siegeWeapon : 1; // 40
unsigned king1 : 1; // 80 ~ all creatures of 7th level and neutral dragons that do not belong to the KING2 or KING3
unsigned king2 : 1; // 100
unsigned king3 : 1; // 200
unsigned mindImmunity : 1; // 400
unsigned shootsRay : 1; // 800 WoG incorrectly refers to this as 'no obstacle penalty' instead it's a flag used to draw a straight line when shooting - see 0x43F23D
unsigned noMeleePenalty : 1; // 1000
unsigned unk2000 : 1; // 2000
unsigned fireImmunity : 1; // 4000
unsigned doubleAttack : 1; // 8000
unsigned noRetaliation : 1; // 10000
unsigned noMorale : 1; // 20000
unsigned undead : 1; // 40000
unsigned attackAllAround : 1; // 80000
unsigned fireballAttack : 1; // 100000
unsigned cannotMove : 1; // 200000 ~21
unsigned summon : 1; // 400000
unsigned clone : 1; // 800000
unsigned morale : 1; // 1000000
unsigned waiting : 1; // 2000000 ~25
unsigned done : 1; // 4000000
unsigned defending : 1; // 8000000
unsigned sacrificed : 1; // 10000000
unsigned noColoring : 1; // 20000000
unsigned gray : 1; // 40000000
unsigned dragon : 1; // 80000000
};
UINT32 flags;
};
/** @brief [14] */
LPCSTR nameSingular;
/** @brief [18] */
LPCSTR namePlural;
/** @brief [1C] */
LPCSTR description;
/** @brief [20] */
H3Resources cost;
/** @brief [3C] */
INT32 fightValue;
/** @brief [40] */
INT32 aiValue;
/** @brief [44] */
INT32 grow;
/** @brief [48] */
INT32 hGrow;
/** @brief [4C] */
INT32 hitPoints;
/** @brief [50] */
INT32 speed;
/** @brief [54] */
INT32 attack;
/** @brief [58] */
INT32 defence;
/** @brief [5C] */
INT32 damageLow;
/** @brief [60] */
INT32 damageHigh;
/** @brief [64] */
INT32 numberShots;
/** @brief [68] */
INT32 spellCharges;
/** @brief [6C] */
INT32 advMapLow;
/** @brief [70] */
INT32 advMapHigh;
_H3API_ LPCSTR GetCreatureName(INT32 count) const;
_H3API_ H3Resources UpgradeCost(H3CreatureInformation* upg, INT32 count) const;
};
_H3API_ASSERT_SIZE_(H3CreatureInformation);
#pragma pack(pop) /* align-4 */
} /* namespace h3 */
| 31.637097 | 176 | 0.513638 | Patrulek |
d86a61337af4391883603fdbccf97280c7f70321 | 309 | cpp | C++ | Graphics/Graphics/main.cpp | functard/Graphics-Framework | 90ed2e1d4631c6dce5c1aad5003e5a462966be87 | [
"MIT"
] | 1 | 2022-02-22T13:42:43.000Z | 2022-02-22T13:42:43.000Z | Graphics/Graphics/main.cpp | functard/Graphics-Framework | 90ed2e1d4631c6dce5c1aad5003e5a462966be87 | [
"MIT"
] | null | null | null | Graphics/Graphics/main.cpp | functard/Graphics-Framework | 90ed2e1d4631c6dce5c1aad5003e5a462966be87 | [
"MIT"
] | null | null | null | #include "PCH.h"
#include "Engine.h"
int CALLBACK wWinMain(HINSTANCE _hInstance, HINSTANCE _hPrevInstance, PWSTR _cmdLineArgs, int _cmdShow)
{
int value = CEngine::Get()->Init(_hInstance);
if (FAILED(value))
{
return value;
}
value = CEngine::Get()->Run();
CEngine::Get()->Finish();
return value;
} | 20.6 | 103 | 0.695793 | functard |
d87a2ac121c97d7ca6e8bf9bca530107ccb1b789 | 1,845 | hpp | C++ | oanda_v20/include/oanda/v20/json/exception/OutOfRange.hpp | CodeRancher/offcenter_oanda | c7817299b2c7199508307b2379179923e3f60fdc | [
"Apache-2.0"
] | null | null | null | oanda_v20/include/oanda/v20/json/exception/OutOfRange.hpp | CodeRancher/offcenter_oanda | c7817299b2c7199508307b2379179923e3f60fdc | [
"Apache-2.0"
] | null | null | null | oanda_v20/include/oanda/v20/json/exception/OutOfRange.hpp | CodeRancher/offcenter_oanda | c7817299b2c7199508307b2379179923e3f60fdc | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2020 Scott Brauer
*
* 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 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.
*/
/*
* @file OutOfRange.hpp
* @author Scott Brauer
* @date 12-11-2020
*/
#ifndef OANDA_V20_JSON_EXCEPTION_OUTOFRANGE_HPP_
#define OANDA_V20_JSON_EXCEPTION_OUTOFRANGE_HPP_
#include <string>
#include <stdexcept>
#include <sstream>
#include <nlohmann/json.hpp>
namespace oanda {
namespace v20 {
namespace json {
namespace exception {
class OutOfRange : public std::out_of_range
{
public:
explicit OutOfRange(const std::string& what_arg):
std::out_of_range(what_arg) {}
explicit OutOfRange(const char* what_arg):
std::out_of_range(what_arg) {}
explicit OutOfRange(nlohmann::json::exception& e,
const std::string& file = "",
int line = 0,
const std::string& function = ""):
std::out_of_range(OutOfRange::join({
e.what(), ":id(", std::to_string(e.id), ") ",
"File(", file, ") ",
"Line(", std::to_string(line), ") ",
"Function(", function, ") "
})) {}
virtual ~OutOfRange() = default;
static std::string join(std::initializer_list<std::string> elements)
{
std::ostringstream ss;
for (auto element : elements)
ss << element;
return ss.str();
}
};
} /* namespace exception */
} /* namespace json */
} /* namespace rest */
} /* namespace oanda */
#endif /* OANDA_V20_JSON_EXCEPTION_OUTOFRANGE_HPP_ */
| 24.6 | 75 | 0.695935 | CodeRancher |
d87b83b50d9c023e4201347db2a271f190fd69c7 | 1,461 | cpp | C++ | MyGUIWrapper/Src/EventComboChangePositionTranslator.cpp | AnomalousMedical/Engine | a19e21f597bd277e4ca17e0e5f3f89577f2307bb | [
"MIT"
] | null | null | null | MyGUIWrapper/Src/EventComboChangePositionTranslator.cpp | AnomalousMedical/Engine | a19e21f597bd277e4ca17e0e5f3f89577f2307bb | [
"MIT"
] | null | null | null | MyGUIWrapper/Src/EventComboChangePositionTranslator.cpp | AnomalousMedical/Engine | a19e21f597bd277e4ca17e0e5f3f89577f2307bb | [
"MIT"
] | null | null | null | #include "StdAfx.h"
#include "../Include/MyGUIEventTranslator.h"
class EventComboChangePositionTranslator : public MyGUIEventTranslator
{
public:
typedef void (*NativeEventDelegate)(MyGUI::ComboBox* sender, size_t index HANDLE_ARG);
private:
MyGUI::ComboBox* widget;
NativeEventDelegate nativeEvent;
HANDLE_INSTANCE
#ifdef FULL_AOT_COMPILE
void fireEvent(MyGUI::ComboBox* sender, size_t index)
{
nativeEvent(sender, index PASS_HANDLE_ARG);
}
#endif
public:
EventComboChangePositionTranslator(MyGUI::ComboBox* widget, EventComboChangePositionTranslator::NativeEventDelegate nativeEventCallback HANDLE_ARG)
:widget(widget),
nativeEvent(nativeEventCallback)
ASSIGN_HANDLE_INITIALIZER
{
}
virtual ~EventComboChangePositionTranslator()
{
}
virtual void bindEvent()
{
#ifdef FULL_AOT_COMPILE
widget->eventComboChangePosition = MyGUI::newDelegate(this, &EventComboChangePositionTranslator::fireEvent);
#else
widget->eventComboChangePosition = MyGUI::newDelegate(nativeEvent);
#endif
}
virtual void unbindEvent()
{
widget->eventComboChangePosition = NULL;
}
};
extern "C" _AnomalousExport EventComboChangePositionTranslator* EventComboChangePositionTranslator_Create(MyGUI::ComboBox* widget, EventComboChangePositionTranslator::NativeEventDelegate nativeEventCallback HANDLE_ARG)
{
return new EventComboChangePositionTranslator(widget, nativeEventCallback PASS_HANDLE_ARG);
} | 28.096154 | 219 | 0.78987 | AnomalousMedical |
f221521881832649aec7153ab6d320a15c241b49 | 599 | cpp | C++ | src/cpp/uml/literalSpecification.cpp | nemears/uml-cpp | d72c8b5506f391f2b6a5696972ff8da7ec10bd21 | [
"MIT"
] | null | null | null | src/cpp/uml/literalSpecification.cpp | nemears/uml-cpp | d72c8b5506f391f2b6a5696972ff8da7ec10bd21 | [
"MIT"
] | 1 | 2022-02-25T18:14:21.000Z | 2022-03-10T08:59:55.000Z | src/cpp/uml/literalSpecification.cpp | nemears/uml-cpp | d72c8b5506f391f2b6a5696972ff8da7ec10bd21 | [
"MIT"
] | null | null | null | #include "uml/literalSpecification.h"
#include "uml/package.h"
#include "uml/stereotype.h"
#include "uml/behavior.h"
#include "uml/dataType.h"
#include "uml/association.h"
#include "uml/association.h"
#include "uml/interface.h"
#include "uml/deployment.h"
using namespace UML;
LiteralSpecification::LiteralSpecification() : Element(ElementType::LITERAL_SPECIFICATION) {
}
bool LiteralSpecification::isSubClassOf(ElementType eType) const {
bool ret = ValueSpecification::isSubClassOf(eType);
if (!ret) {
ret = eType == ElementType::LITERAL_SPECIFICATION;
}
return ret;
} | 23.96 | 92 | 0.737896 | nemears |
f2226373e98348a11d1b6efc7573ac53fe048d6c | 2,114 | cpp | C++ | modules/task_2/kren_p_grid_torus_topology/main.cpp | RachinIA/pp_2020_autumn_engineer | 23f7df688a77cad9496b9d95bbe2645e0528f106 | [
"BSD-3-Clause"
] | 1 | 2020-10-30T13:49:58.000Z | 2020-10-30T13:49:58.000Z | modules/task_2/kren_p_grid_torus_topology/main.cpp | RachinIA/pp_2020_autumn_engineer | 23f7df688a77cad9496b9d95bbe2645e0528f106 | [
"BSD-3-Clause"
] | 1 | 2020-11-01T18:53:35.000Z | 2020-11-01T18:53:35.000Z | modules/task_2/kren_p_grid_torus_topology/main.cpp | RachinIA/pp_2020_autumn_engineer | 23f7df688a77cad9496b9d95bbe2645e0528f106 | [
"BSD-3-Clause"
] | 1 | 2021-03-14T18:08:22.000Z | 2021-03-14T18:08:22.000Z | // Copyright 2020 Kren Polina
#include <gtest-mpi-listener.hpp>
#include <gtest/gtest.h>
#include <mpi.h>
#include "./grid_torus_topology.h"
TEST(Grid_Torus_Topology, can_create_grid_torus) {
MPI_Comm comm_torus = getCommTorus(MPI_COMM_WORLD);
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
ASSERT_TRUE(testGridTorus(comm_torus));
}
}
TEST(Grid_Torus_Topology, not_cart_comm_has_no_torus_topology) {
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
ASSERT_FALSE(testGridTorus(MPI_COMM_WORLD));
}
}
TEST(Grid_Torus_Topology, none_period_comm_has_no_torus_topology) {
MPI_Comm main_comm;
int rank;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
int size;
MPI_Comm_size(MPI_COMM_WORLD, &size);
int dims[] = { 0, 0 };
int period[] = { 1, 0 };
MPI_Dims_create(size, 2, dims);
MPI_Cart_create(MPI_COMM_WORLD, 2, dims, period, 1, &main_comm);
if (rank == 0) {
ASSERT_FALSE(testGridTorus(main_comm));
}
}
TEST(Grid_Torus_Topology, cant_create_with_wrong_size) {
int rank;
int size;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm main_comm = getCommTorus(MPI_COMM_WORLD, size + 1);
if (rank == 0) {
ASSERT_EQ(main_comm, MPI_COMM_NULL);
}
}
TEST(Grid_Torus_Topology, shift_works_correctly) {
MPI_Comm comm_torus = getCommTorus(MPI_COMM_WORLD);
int rank;
MPI_Comm_rank(comm_torus, &rank);
bool flag = testRelation(comm_torus);
if (rank == 0) {
ASSERT_TRUE(flag);
}
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
::testing::AddGlobalTestEnvironment(new GTestMPIListener::MPIEnvironment);
::testing::TestEventListeners& listeners =
::testing::UnitTest::GetInstance()->listeners();
listeners.Release(listeners.default_result_printer());
listeners.Release(listeners.default_xml_generator());
listeners.Append(new GTestMPIListener::MPIMinimalistPrinter);
return RUN_ALL_TESTS();
}
| 24.581395 | 78 | 0.688269 | RachinIA |
f2227b20dba0d7ab0fdef547be23b785d97d7b5e | 1,340 | hpp | C++ | module07/ex01/iter.hpp | selysse/CPP-Piscine | 72884c60ac5007d34874b006e37dad7a04e846bb | [
"MIT"
] | 1 | 2021-09-17T13:25:47.000Z | 2021-09-17T13:25:47.000Z | module07/ex01/iter.hpp | selysse/CPP-Piscine | 72884c60ac5007d34874b006e37dad7a04e846bb | [
"MIT"
] | null | null | null | module07/ex01/iter.hpp | selysse/CPP-Piscine | 72884c60ac5007d34874b006e37dad7a04e846bb | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* iter.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: gselyse <gselyse@student.21-school.ru> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/03/12 13:56:13 by gselyse #+# #+# */
/* Updated: 2021/03/17 01:30:15 by gselyse ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef ITER_HPP
# define ITER_HPP
# include <iostream>
# include <string>
template<typename T>
void decrement(T const &input)
{
T num;
num = input;
num--;
std::cout << num << " ";
}
template<typename T>
void increment(T const &input)
{
T num;
num = input;
num++;
std::cout << num << " ";
}
template <typename T>
void iter(const T *array, size_t size, void (*f)(const T &p)) {
for (size_t i = 0; i < size; i++)
f(array[i]);
}
#endif | 31.162791 | 80 | 0.281343 | selysse |
f224794ac91fd4286b36c860fd316f0f4eadf478 | 756 | cpp | C++ | Year3Game/PitchRegion.cpp | EvanCGriffin/soccergame | 8056b39a4c7adfab3aa47333237474fc8250e7ac | [
"MIT"
] | 1 | 2021-09-29T14:27:07.000Z | 2021-09-29T14:27:07.000Z | Year3Game/PitchRegion.cpp | EvanCGriffin/soccergame | 8056b39a4c7adfab3aa47333237474fc8250e7ac | [
"MIT"
] | null | null | null | Year3Game/PitchRegion.cpp | EvanCGriffin/soccergame | 8056b39a4c7adfab3aa47333237474fc8250e7ac | [
"MIT"
] | null | null | null | #include "PitchRegion.h"
#include <Year3Engine\Utils.h>
PitchRegion::PitchRegion(double x, double y, double width, double height, int id)
:id(id)
{
rect = SDL_Rect();
rect.x = x;
rect.y = y;
rect.w = width;
rect.h = height;
center = b2Vec2(x + (width * 0.5), y + (height * 0.5));
color = b2Color(0, 0, 0);
}
PitchRegion::~PitchRegion(void)
{
}
void PitchRegion::Draw(DebugDraw* debugDraw)
{
b2AABB aabb;
aabb.lowerBound = b2Vec2(rect.x, rect.y + rect.h);
aabb.upperBound = b2Vec2(rect.x + rect.w, rect.y);
debugDraw->DrawCircle(center, 10, color);
debugDraw->DrawAABB(&aabb, color);
}
inline b2Vec2 PitchRegion::GetRandomPosition()
{
return b2Vec2(RandInRange(rect.x, (rect.x + rect.w)),
RandInRange(rect.y, (rect.y + rect.h)));
}
| 19.384615 | 81 | 0.667989 | EvanCGriffin |
f229c54432c3bf2ab8a1dd4e7adfa72a77cb1bd0 | 120 | hxx | C++ | src/Providers/UNIXProviders/ElementAsUser/UNIX_ElementAsUser_AIX.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | 1 | 2020-10-12T09:00:09.000Z | 2020-10-12T09:00:09.000Z | src/Providers/UNIXProviders/ElementAsUser/UNIX_ElementAsUser_AIX.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | src/Providers/UNIXProviders/ElementAsUser/UNIX_ElementAsUser_AIX.hxx | brunolauze/openpegasus-providers-old | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | [
"MIT"
] | null | null | null | #ifdef PEGASUS_OS_AIX
#ifndef __UNIX_ELEMENTASUSER_PRIVATE_H
#define __UNIX_ELEMENTASUSER_PRIVATE_H
#endif
#endif
| 10 | 38 | 0.841667 | brunolauze |
f22e7e2e6c5533baf6f8f2c9e1481b7571bd7cef | 587 | hxx | C++ | src/Tools/Algo/Predicate_ite.hxx | WilliamMajor/aff3ct | 4e71ab99f33a040ec06336d3e1d50bd2c0d6a579 | [
"MIT"
] | 1 | 2022-02-17T08:47:47.000Z | 2022-02-17T08:47:47.000Z | src/Tools/Algo/Predicate_ite.hxx | WilliamMajor/aff3ct | 4e71ab99f33a040ec06336d3e1d50bd2c0d6a579 | [
"MIT"
] | null | null | null | src/Tools/Algo/Predicate_ite.hxx | WilliamMajor/aff3ct | 4e71ab99f33a040ec06336d3e1d50bd2c0d6a579 | [
"MIT"
] | 1 | 2021-11-24T01:54:41.000Z | 2021-11-24T01:54:41.000Z | #include <sstream>
#include "Tools/Exception/exception.hpp"
#include "Tools/Algo/Predicate_ite.hpp"
namespace aff3ct
{
namespace tools
{
Predicate_ite::Predicate_ite(const int n_ite)
: n_ite(n_ite), cur_ite(0)
{
if (n_ite <= 0)
{
std::stringstream message;
message << "'n_ite' has to be equal or greater than 0 ('n_ite' = " << n_ite << ").";
throw invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
}
bool Predicate_ite::operator()()
{
const bool predicate = cur_ite >= n_ite;
cur_ite++;
return predicate;
}
void Predicate_ite::reset()
{
cur_ite = 0;
}
}
} | 17.787879 | 86 | 0.689949 | WilliamMajor |
f233a4d50426273586dd94dd8cd0ec33e1c131af | 309 | cpp | C++ | URI/1175/1175.cpp | IrineuAlmeidaJr/C | e04e818be1e8b302cc5d542f4b0ba9c6e07d9b15 | [
"MIT"
] | null | null | null | URI/1175/1175.cpp | IrineuAlmeidaJr/C | e04e818be1e8b302cc5d542f4b0ba9c6e07d9b15 | [
"MIT"
] | null | null | null | URI/1175/1175.cpp | IrineuAlmeidaJr/C | e04e818be1e8b302cc5d542f4b0ba9c6e07d9b15 | [
"MIT"
] | null | null | null | #include<stdio.h>
#define TF 20
int main()
{
int vet[TF], i, aux1, aux2;
for (i=0; i<TF; i++)
scanf("%d", &vet[i]);
i=0;
while (i<TF/2)
{
aux1=vet[TF-1-i];
aux2=vet[i];
vet[i]=aux1;
vet[TF-1-i]=aux2;
i++;
}
for (i=0; i<TF; i++)
printf("N[%d] = %d\n", i, vet[i]);
return 0;
}
| 11.035714 | 36 | 0.475728 | IrineuAlmeidaJr |
f238ee98b99c834ac94915d167f36ecddee11a3a | 3,982 | cpp | C++ | sources/main.cpp | BiarnGamer/pommeDePin | 21f525e728614c31d08d8b90821d37b74e481203 | [
"Apache-2.0"
] | null | null | null | sources/main.cpp | BiarnGamer/pommeDePin | 21f525e728614c31d08d8b90821d37b74e481203 | [
"Apache-2.0"
] | null | null | null | sources/main.cpp | BiarnGamer/pommeDePin | 21f525e728614c31d08d8b90821d37b74e481203 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
#include "../entetes/animal.h"
//Déja inclut dans menu.h
//#include "../entetes/enclos.h"
#include "../entetes/set.h"
#include "../entetes/parc.h"
#include "../entetes/menu.h"
#include "../entetes/affichage.h"
// Pas besoin de utilisateur.h car il est inclut dans menu.h
//#include "../entetes/utilisateur.h"
using namespace std;
void chargerJeuTest(Parc & Parc1) {
/* *************************** */
/* CRÉATION D'ANIMAUX */
/* *************************** */
Tigre Helico(105, 654, "Diego", 1);
Tigre Paul(241, 3321, "Pau'Pol", 2);
Tigre Paul2(541, 12, "Chicos", 2);
Basque Xabi(125, 63, 1, 9999, "Xabi", 3);
Basque Ninicolas(12, 125, 14, 4419, "Nicolas Belloir", 4);
Basque Antoine(36, 4512, 124, 874, "Antoine Lefier", 4);
Marmotte Miam(95, 6544, "Shakira", 5);
Marmotte Tekitoi(245, 20, "Rihanna", 6);
Marmotte pipicaca(42, 874, "Roberta", 6);
Elephant Pikachu(1021, 365, 102, "Valentin", 74);
Elephant PHP(412, 35, 212, "C++", 744);
Elephant Elephanto(874, 384, 784, "Chabal", 744);
Aigle Piafabec(95, 6544, "Poussin", 51);
Aigle Roucarnage(652, 474, "Pousse pousse", 11);
Aigle Nirondelle(412, 24, "Envole Moi", 11);
Lapin Valou(64, "Rouge", "Mimie Matti", 26);
Lapin Tuture(205, "Blanche", "GTi", 205);
Lapin Lapine(412, "Invisible", "Nom temporaire en attendant d'avoir des parents inspirés", 205);
Tortue Toto(35, 1201, "Arc-end-ciel", "Speedy Gonzalez", 7);
Tortue Toutou(135, 11, "La même que toi", "Faut pas pousser mes mail dans les ordis !", 17);
Tortue TordreTue(42, 8751, "Transparent", "Wall-E", 17);
Crocodile GrosseDent(3045, 124, "Mange de l'herbe", 8);
Crocodile MoiJaiFaim(212345, 542, "Trotro Rigolo !", 84);
Crocodile Grr(4577, 697, "RRRrrrr", 84);
Girafe PetiteB(120, 5412, "Gigi", 9);
Girafe QuiVeutDesTalons(21, 6854, "Tour Eiffel", 19);
Girafe Torticoli(784, 124, "TeCognePas!", 19);
Loutre loulou(12,14,"Moi j'ai des amis !", 110);
Loutre PasDeSequelles(1,4,"Gnééé !", 150);
Loutre Gneeee(174,474,"Gogo Gadgeto !", 150);
/* *************************** */
/* CRÉATION D'ENCLOS */
/* *************************** */
Parc1.creerEnclos("Attrapez-les tous !",1,23);
Parc1.creerEnclos("Zone 51",3,2);
Parc1.creerEnclos("Fac Informatique",2,53);
Parc1.creerEnclos("La planète des singes",3,5);
Parc1.creerEnclos("Qwerty",1,21);
Parc1.creerEnclos("Cours Structure de Donnée",3,4);
Parc1.creerEnclos("La pension",2,85);
Parc1.creerEnclos("Pikachu Island",2,3);
Parc1.creerEnclos("Enclos R2D2",1,42);
Parc1.creerEnclos("Coin des développeurs",1,64);
/* *************************** */
/* AJOUT D'ANIMAUX */
/* *************************** */
/* Répartition des animaux : aléatoire, en respectant ces quotas :
3 et 5 : vides
1:4
2:3
4:5
6:2
7:1
8:6
9:4
10:5
*/
Parc1.creerAnimal(&Helico,1);
Parc1.creerAnimal(&Paul,1);
Parc1.creerAnimal(&Paul2,4);
Parc1.creerAnimal(&Xabi,6);
Parc1.creerAnimal(&Ninicolas,2);
Parc1.creerAnimal(&Antoine,4);
Parc1.creerAnimal(&Miam,7);
Parc1.creerAnimal(&Tekitoi,9);
Parc1.creerAnimal(&pipicaca,6);
Parc1.creerAnimal(&Piafabec,10);
Parc1.creerAnimal(&Roucarnage,8);
Parc1.creerAnimal(&Nirondelle,10);
Parc1.creerAnimal(&Valou,4);
Parc1.creerAnimal(&Tuture,1);
Parc1.creerAnimal(&Lapine,8);
Parc1.creerAnimal(&Toto,8);
Parc1.creerAnimal(&Toutou,10);
Parc1.creerAnimal(&TordreTue,9);
Parc1.creerAnimal(&GrosseDent,8);
Parc1.creerAnimal(&MoiJaiFaim,1);
Parc1.creerAnimal(&Grr,10);
Parc1.creerAnimal(&PetiteB,10);
Parc1.creerAnimal(&Torticoli,9);
Parc1.creerAnimal(&QuiVeutDesTalons,8);
Parc1.creerAnimal(&loulou,2);
Parc1.creerAnimal(&PasDeSequelles,2);
Parc1.creerAnimal(&Gneeee,9);
Parc1.creerAnimal(&Pikachu,4);
Parc1.creerAnimal(&PHP,4);
Parc1.creerAnimal(&Elephanto,8);
}
int main() {
/** POUR DE L'ALÉATOIRE **/
srand(time(NULL));
Parc Parc1;
chargerJeuTest(Parc1);
menuPrincipal(Parc1);
return 0;
}
| 27.088435 | 97 | 0.650929 | BiarnGamer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.