blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
9b6846a7ead7d206dd9edd39628d3031447014bc | 153f2036e4858364946eb4698608bb9ac464dbc8 | /AnimalRace/Character.cpp | d9bf661e7cc25416e96d287c38864496ddf793db | [] | no_license | KobayashiMasakado/Animal_Race | dc7d03d0a3071825a20bb8ffe43a4032ba8bfc40 | 058f909599a19fb646bdcd07e95d3371a3e840b4 | refs/heads/master | 2020-09-23T22:23:06.233780 | 2019-12-09T08:34:56 | 2019-12-09T08:34:56 | 225,602,318 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 977 | cpp | Character.cpp | #include "pch.h"
#include "Character.h"
#include "ItemEffect.h"
Character::Character()
{
m_itemEffect = nullptr;
for (int i = 0; i < GOAL_NUM; i++)
{
m_charaCheckFlag[i] = false;
}
}
Character::~Character()
{
if (m_itemEffect != nullptr)
{
delete m_itemEffect;
m_itemEffect = nullptr;
}
}
bool Character::Update(const DX::StepTimer & stepTimer)
{
if (m_itemEffect != nullptr)
{
m_itemEffect->Update(stepTimer, this);
}
return true;
}
void Character::RenderEffect(bool selectFlag)
{
if (m_itemEffect != nullptr)
{
m_itemEffect->Render(selectFlag);
}
}
void Character::Finalize()
{
delete m_itemEffect;
}
//キャラがゴールしたら
bool Character::CharaGoal()
{
for (int i = 0; i < GOAL_NUM; i++)
{
if (m_charaCheckFlag[i] == false)
{
return false;
}
}
return true;
}
//ゴールのチェックポイント
void Character::CheckPoint(int num)
{
if (num < 0) return;
if (num > GOAL_NUM) return;
m_charaCheckFlag[num] = true;
}
|
00992dd12276d627d5cc13cde7784b766569f120 | 7904d6a8086fb9a0faa1b41b9363c7c19a93fe62 | /src/switch.cpp | 21364b0973972c151ac97ecbab738d289f3435a4 | [] | no_license | jam3st/muxev | e9f015cd7b5d65398b4166ed8a97812e346fbeea | 4caccbe00e3b118bb3dd52a39882f15e067e64f9 | refs/heads/master | 2021-06-24T13:55:35.968573 | 2021-05-03T05:45:28 | 2021-05-03T05:45:28 | 226,775,953 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,861 | cpp | switch.cpp | #include <sys/timerfd.h>
#include <unistd.h>
#include <fcntl.h>
#include <csignal>
#include <iostream>
#include <functional>
#include "switch.h"
#include "exception.h"
#include "misc.h"
static std::function<void()> sigHandler = nullptr;
extern "C" {
static void signalHandler(int const num) {
std::cerr << "Exiting on signal " << num << std::endl;
sigHandler();
}
}
Switch::Switch() : running(false) {
throwIf(sigHandler != nullptr, StringException("Too many instances"));
throwIf(0 > ::sem_init(&sem, 0, 0), StringException("sem_init"));
ePollFd = ::epoll_create1(EPOLL_CLOEXEC);
throwIf(0 > ePollFd, StringException("Epoll"));
timerFd = ::timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
throwIf(0 > timerFd, StringException("Monotoc Timer"));
epoll_event event = {EPOLLIN | EPOLLONESHOT | EPOLLET, {.u64 = 0ull}};
throwIf(::epoll_ctl(ePollFd, EPOLL_CTL_ADD, timerFd, &event), StringException("Timer Epoll"));;
enableTimer();
}
void Switch::startThreads() {
//int const nt = std::thread::hardware_concurrency();
int nt = 1;
for(int i = 0; i < nt; ++i) {
threads.push_back(new Thread(this, Switch::thRun));
}
}
void Switch::thRun(Switch* sw, Thread* th) {
sw->runThread(*th);
}
void Switch::enableTimer() {
epoll_event event = {EPOLLIN | EPOLLONESHOT | EPOLLET, {.u64 = 0ull}};
throwIf(::epoll_ctl(ePollFd, EPOLL_CTL_MOD, timerFd, &event), StringException("Timer CTL MOD"));
itimerspec oldTimer = {};
itimerspec newTimer = {.it_interval = {0, 0}, .it_value = {static_cast<decltype(newTimer.it_value.tv_sec)>(1),
static_cast<decltype(newTimer.it_value.tv_nsec)>(0)}};
throwIf(::timerfd_settime(timerFd, 0, &newTimer, &oldTimer), StringException("Recoonect timer settime"));
}
void Switch::timerConnectCheck() {
bool allConnected = true;
for(auto const& it: pollables) {
if(0 > it.first) {
allConnected = false;
it.second->tryConnect(*this);
}
}
if(!allConnected) {
enableTimer();
}
}
void Switch::runThread(Thread &th) {
try {
while(running) {
::sem_wait(&sem);
epoll_event ev;
std::shared_ptr<Pollable> pb;
{
std::lock_guard<std::mutex> sync(lock);
ev = events.front();
events.pop_front();
if(0ull == ev.data.fd) {
timerConnectCheck();
continue;
} else {
auto const it = pollables.find(ev.data.fd);
if(pollables.end() == it) {
std::cerr << "Event for deleted device " << ev.data.fd << std::endl;
return;
}
pb = it->second;
}
}
if((ev.events & EPOLLRDHUP) != 0 || (ev.events & EPOLLERR) != 0) {
pb->error(*this);
} else {
if ((ev.events & EPOLLOUT) != 0) {
pb->write(*this);
}
if ((ev.events & (EPOLLIN)) != 0) {
pb->read(*this);
}
}
}
} catch(StringException const& ex) {
std::cerr << "Exception " << ex.why() << std::endl;
stop();
} catch(...) {
std::cerr << "EXE" << std::endl;
stop();
}
th.exited = true;
}
std::weak_ptr<Pollable> Switch::getFromPtr(Pollable const* io) {
auto res = pollables.equal_range(io->getFd());
auto it = res.first;
for( ; it != res.second; ++it) {
if(io == it->second.get()) {
break;
}
}
throwIf(io != it->second.get(), StringException("Can't find it"));
return it->second;
}
void Switch::add(std::weak_ptr<Pollable> const& io, bool const hasInput) {
auto sp = io.lock();
throwIf(!sp, StringException("Unable to lock"));
auto ioPtr = sp.get();
pollables.insert(std::pair<int, std::shared_ptr<Pollable>>(ioPtr->getFd(), sp));
if(0 > ioPtr->getFd()) {
return;
}
throwIf(0 > ::fcntl(ioPtr->getFd(), F_SETFL, O_NONBLOCK), StringException("Need nonblocking io"));
epoll_event event = { (hasInput ? EPOLLIN : 0u ) | EPOLLERR | EPOLLRDHUP | EPOLLET | EPOLLWAKEUP, {.fd = ioPtr->getFd()}};
throwIf(0 > ::epoll_ctl(ePollFd, EPOLL_CTL_ADD, ioPtr->getFd(), &event), StringException("Epoll Add"));
}
void Switch::remove(const std::weak_ptr<Pollable> &io) {
auto sp = io.lock();
throwIf(!sp, StringException("Unable to lock"));
auto ioPtr = sp.get();
auto res = pollables.equal_range(ioPtr->getFd());
auto it = res.first;
for( ; it != res.second; ++it) {
if(sp == it->second) {
break;
}
}
throwIf(sp != it->second, StringException("Can't find it"));
pollables.erase(it);
if(0 > ioPtr->getFd()) {
return;
}
throwIf(0 > ::epoll_ctl(ePollFd, EPOLL_CTL_DEL, ioPtr->getFd(), nullptr), StringException("Epoll Del"));
}
void Switch::main() {
throwIf(running, StringException("Only run once"));
throwIf(0 == pollables.size(), StringException("Need to add something first"));
sigHandler = std::bind(&Switch::signaled, this);
std::signal(SIGPIPE, signalHandler);
for(int i = SIGHUP; i < _NSIG; ++i) {
std::signal(i, SIG_IGN);
}
std::signal(SIGQUIT, signalHandler);
std::signal(SIGINT, signalHandler);
std::signal(SIGTERM, signalHandler);
std::signal(SIGUSR1, signalHandler);
running = true;
startThreads();
try {
while(running) {
epoll_event epEvents[MAX_EPOLL_EVENTS];
int num = ::epoll_wait(ePollFd, &epEvents[0], sizeof(epEvents)/sizeof(epEvents[0]), -1);
if(!running) {
break;
}
if(num > 0) {
std::lock_guard<std::mutex> sync(lock);
for(auto i = 0u; i < num; ++i) {
events.push_back(epEvents[i]);
::sem_post(&sem);
}
} else if(num == -1 && (errno == EINTR || errno == EAGAIN)) {
continue;
} else {
throw StringException("EPOLL");
}
}
} catch(...) {
stop();
}
for(int i = SIGHUP; i < _NSIG; ++i) {
std::signal(i, SIG_DFL);
}
}
void Switch::stop() {
if(running) {
running = false;
}
exit(1);
}
void Switch::signaled() {
running = false;
}
Switch::~Switch() {
std::signal(SIGQUIT, SIG_DFL);
std::signal(SIGINT, SIG_DFL);
std::signal(SIGTERM, SIG_DFL);
std::signal(SIGUSR1, SIG_DFL);
sigHandler = nullptr;
::sem_close(&sem);
::close(timerFd);
::close(ePollFd);
}
|
56577032b9d8e4d46cde3c093e389145089ac2fa | 0179c590885fdcb61bc128f43b6400ecde323158 | /common/MetadataGenerator.cpp | 2fbdceaac3d404b1d855844e5111ac5759a32931 | [
"Apache-2.0"
] | permissive | grejppi/bitrot | b0ede30dd8476915f2d12db483a3827a76b82e99 | 06a72cd6cbe99b469e57a662cfb34e1cfe75e070 | refs/heads/main | 2023-07-22T13:59:12.449430 | 2023-07-12T22:42:23 | 2023-07-12T22:42:23 | 116,572,356 | 40 | 6 | Apache-2.0 | 2022-02-02T18:51:05 | 2018-01-07T14:33:05 | C++ | UTF-8 | C++ | false | false | 5,512 | cpp | MetadataGenerator.cpp | #include <clocale>
#include <deque>
#include <iostream>
#include <utility>
#include "DistrhoPlugin.hpp"
#include "src/DistrhoPluginInternal.hpp"
#include "DistrhoPluginInfo.h"
START_NAMESPACE_DISTRHO
Plugin* createPlugin();
END_NAMESPACE_DISTRHO
#define BOOL(WHOMST) Syntax().keyword((WHOMST) ? "true" : "false")
enum Token {
Colon,
Comma,
PopArray,
PopObject,
PushArray,
PushObject,
Whatever,
};
class Syntax {
public:
std::deque<Token> tokens;
std::deque<std::string> strings;
Syntax() {}
Syntax(const Syntax&) = delete;
virtual ~Syntax() {}
void output() {
while (tokens.size() != 0) {
Token token = tokens.front();
switch (token) {
case Colon: std::cout << ":"; break;
case Comma: std::cout << ","; break;
case PopArray: std::cout << "]"; break;
case PopObject: std::cout << "}"; break;
case PushArray: std::cout << "["; break;
case PushObject: std::cout << "{"; break;
case Whatever: std::cout << strings.front(); strings.pop_front(); break;
}
tokens.pop_front();
}
}
Syntax& merge(const Syntax& other) {
tokens.insert(tokens.end(), other.tokens.begin(), other.tokens.end());
strings.insert(strings.end(), other.strings.begin(), other.strings.end());
return *this;
}
Syntax& object(class Object& object);
Syntax& array(class Array& array);
Syntax& string(std::string string);
Syntax& number(double number);
Syntax& keyword(std::string keyword);
};
class Array : public Syntax {
public:
Array() {}
Array(const Array&) = delete;
virtual ~Array() {}
Array& item(Syntax& item) {
if (tokens.size() != 0) {
tokens.push_back(Comma);
}
merge(item);
return *this;
}
};
class Object : public Syntax {
public:
Object() {}
Object(const Object&) = delete;
virtual ~Object() {}
Object& item(std::string key, Syntax& item) {
if (tokens.size() != 0) {
tokens.push_back(Comma);
}
merge(Syntax().string(key));
tokens.push_back(Colon);
merge(item);
return *this;
}
};
Syntax& Syntax::object(Object& object) {
tokens.push_back(PushObject);
merge(object);
tokens.push_back(PopObject);
return *this;
}
Syntax& Syntax::array(Array& array) {
tokens.push_back(PushArray);
merge(array);
tokens.push_back(PopArray);
return *this;
}
Syntax& Syntax::string(std::string string) {
tokens.push_back(Whatever);
strings.push_back(std::string("\"") + string + std::string("\""));
return *this;
}
Syntax& Syntax::number(double number) {
tokens.push_back(Whatever);
strings.push_back(std::to_string(number));
return *this;
}
Syntax& Syntax::keyword(std::string keyword) {
tokens.push_back(Whatever);
strings.push_back(keyword);
return *this;
}
int main(int argc, char** argv) {
std::setlocale(LC_ALL, "C");
d_lastBufferSize = 256;
d_lastSampleRate = 44100.0;
PluginExporter plugin;
Object obj;
obj.item("uri", Syntax().string(DISTRHO_PLUGIN_URI));
obj.item("name", Syntax().string(DISTRHO_PLUGIN_NAME));
obj.item("dllname", Syntax().string(BITROT_BINARY_NAME));
obj.item("ttlname", Syntax().string(BITROT_TTL_NAME));
#if defined(DISTRHO_PLUGIN_REPLACED_URI)
obj.item("replaced_uri", Syntax().string(DISTRHO_PLUGIN_REPLACED_URI));
#else
obj.item("replaced_uri", Syntax().keyword("null"));
#endif
obj.item("description", Syntax().string(plugin.getDescription()));
obj.item("license", Syntax().string(plugin.getLicense()));
obj.item("maker", Syntax().string(plugin.getMaker()));
obj.item("is_rt_safe", BOOL(DISTRHO_PLUGIN_IS_RT_SAFE));
Object version;
version.item("major", Syntax().number(BITROT_VERSION_MAJOR));
version.item("minor", Syntax().number(BITROT_VERSION_MINOR));
version.item("micro", Syntax().number(BITROT_VERSION_MICRO));
obj.item("version", Syntax().object(version));
Array params;
for (uint32_t i = 0; i < plugin.getParameterCount(); ++i) {
Object param;
param.item(
"direction",
Syntax().string(
plugin.isParameterOutput(i) ? "output" : "input"
)
);
param.item("symbol", Syntax().string(
plugin.getParameterSymbol(i).buffer()));
param.item("name", Syntax().string(
plugin.getParameterName(i).buffer()));
const ParameterRanges& ranges(plugin.getParameterRanges(i));
param.item("minimum", Syntax().number(ranges.min));
param.item("maximum", Syntax().number(ranges.max));
param.item("default", Syntax().number(ranges.def));
const uint32_t hints(plugin.getParameterHints(i));
param.item("trigger", BOOL(
(hints & kParameterIsTrigger) == kParameterIsTrigger));
param.item("toggled", BOOL(hints & kParameterIsBoolean));
param.item("integer", BOOL(hints & kParameterIsInteger));
param.item("logarithmic", BOOL(hints & kParameterIsLogarithmic));
param.item("automatable", BOOL(hints & kParameterIsAutomatable));
params.item(Syntax().object(param));
}
obj.item("params", Syntax().array(params));
Syntax().object(obj).output();
std::cout << std::endl;
return EXIT_SUCCESS;
}
|
7e9591d980679810d51df8da5ceb55f85419078e | 946e1a482a7e43670049562b9080001faa2f79ab | /tgcviewer-cpp/tgcviewer-cpp/TgcViewer/Window/TgcWindowHandler.h | cd80dc983c37416e814e2fee7c6333a810a6e6d2 | [] | no_license | xyzr0482/TgcViewer-cpp | 8a7f369dacddb25d4396afd5b9e4f01b9f7fe8ca | 76d3cec308362c2ab114cb4145df51a792f8e833 | refs/heads/master | 2021-01-18T01:57:53.096388 | 2014-12-10T13:07:35 | 2014-12-10T13:07:35 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,189 | h | TgcWindowHandler.h | /////////////////////////////////////////////////////////////////////////////////
// TgcViewer-cpp
//
// Author: Matias Leone
//
/////////////////////////////////////////////////////////////////////////////////
#pragma once
//General Includes:
#include <string>
using namespace std;
//Project Includes:
#include "TgcViewer/globals.h"
#include "TgcViewer/GuiControllerConfig.h"
#include "TgcViewer/Input/TgcInput.h"
#include "TgcViewer/Math/Vector2.h"
//Forward declaration for "TgcViewer/GuiController.h"
namespace TgcViewer {class GuiController;};
namespace TgcViewer
{
/**
* An abstract Window Handler to interact with the platform-dependent
* window system, the input system, high resolution time and filesystem.
* Each specific platform must extend this class.
*/
class TgcWindowHandler
{
public:
TgcWindowHandler();
TgcWindowHandler(const TgcWindowHandler&);
~TgcWindowHandler();
/**
* Create a new window
*/
virtual void initializeWindow(GuiControllerConfig config) = 0;
/**
* Run events and starts the main loop.
* It must invoke GuiController::Instance->render() and feed
* GuiController::Instance->input with the input data.
*/
virtual void run() = 0;
/**
* Stops the main loop
*/
virtual void stop() = 0;
/**
* Close the window and free resources
*/
virtual void closeWindow() = 0;
/**
* Reset the values of the timer for frameTime and fps
*/
virtual void resetTimer() = 0;
/**
* Compute timer values for frameTime and fps
*/
virtual void updateTimer() = 0;
/**
* Returns the directory of the application's executable file
*/
virtual string getCurrentDir() = 0;
/**
* Shows an alert box with an error
*/
virtual void showErrorMessageBox(string title, string text) = 0;
/**
* Window size
*/
inline Vector2 size() const {return Vector2((float)screenWidth, (float)screenHeight);}
private:
public:
/**
* Screen width
*/
int screenWidth;
/**
* Screen height
*/
int screenHeight;
/**
* True if the windows is running in full-screen mode
*/
bool fullScreen;
/**
* The time elapsed between frames (in seconds)
*/
float frameTime;
/**
* Frames per second
*/
int fps;
private:
};
}
|
cb708ae450a1f8e9a8642d644951a6ba38877242 | bebf05455518256d3b977876502d56b7d0277098 | /Scheduler.cpp | 3c1ef7d205635a679b33ca6c72df6f55d45b335c | [] | no_license | LeBertrand/event-scheduler | 18b462c4e5887be40dcdb1c8b6d3121ea14661c5 | d5c26052d536dd12737ce6ecb366b8fc51ce2584 | refs/heads/master | 2021-05-04T15:25:50.361777 | 2018-02-11T23:39:04 | 2018-02-11T23:39:04 | 120,227,667 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,386 | cpp | Scheduler.cpp | /*
* Main file for Discrete Event simulator project.
* Shmuel Jacobs at Temple University, Spring 2018.
* Initialization has all been placed inside main function.
* New serial numbers represent entirely new jobs entering the system
(as opposed to the event created when a job moves from one component to
another), and only occur in the place_new_event function. This doesn't
complicate logging, because the log will look for the matching completion of
every job that opens, so future openings are no problem.
* Main logic of a single pass is in one_round_get_exe, which gets the next
event and handles it.
*/
#include "Component.cpp"
#include "EventQueue.h"
#include "EventQueue.cpp"
#include "Event.c"
#include "config.h"
#include <time.h>
int ranged_rand(int, int);
bool decide_quit();
void place_new_event(Component*);
void one_round_get_exe(EventQueue*, Component*,Component*,Component*);
int global_time;
int serial_stamp;
int main()
{
/* Dont bother seperating into a setup function.
Setup consists entirely of setting variables, which would have to be
declared here and passed by location anyway. */
// Create Event queue.
EventQueue event_queue;
// Create Components.
Component cpu;
Component disk_one;
Component disk_two;
// Set clock to zero.
global_time = 0;
// Seed random numbers.
srand(time(NULL));
// Create stamp to give events their serial numbers. Start is arbitrary.
serial_stamp = 1000;
// Setup Complete.
one_round_get_exe(&event_queue, &cpu, &disk_one, &disk_two);
return 0;
}
/*
* Main loop. Four major steps in each pass:
* Generate new CPU arrival.
* Find next job and advance time keeping.
* Handle event.
* Check if simulation over.
*/
/* Generally, I've tried to use member methods because I consider it easier to
code without passing pointers to member objects. However, Object Oriented
Scheduler class seemed more trouble than it was worth, so Scheduler does
pass pointers to its own fields. */
void one_round_get_exe(EventQueue* eq, Component* cpu, Component* disk_one, Component* disk_two)
{
// Generate CPU arrival
place_new_event(cpu);
// Find next job and advance time keeping.
Event* next = eq->getNext();
int job_length
// Handle job.
switch(next->jobtype){
// TODO: Standardized logging step in all cases.
case JOB_ARRIVE_CPU:
// TODO: All logic relies on current_wait being 0 when the queue is
// empty. Can I totally factor out the idle flag?
if(cpu->Getidle()){
// CPU idle so job doesn't wait. Set idle false.
cpu->Setidle(false);
} else {
// Put job into component queue.
cpu->pushJob(next->serial);
}
// Calculate job length - calculate now only for calculating true
// end time - EventQueue doesn't know the wait time, only queue lengths.
job_length = ranged_rand(CPU_MIN, CPU_MAX);
next->timestamp = global_time + job_length + cpu->getTime();
// Make event a cpu completion.
next->jobtype = JOB_FINISH_CPU;
// Put completion into event heap.
eq->pushJob(next);
break;
case JOB_FINISH_CPU:
// TODO: For stats log, we're counting the job as done, because we're interested in throughput. If not, I can change this part.
// Log completion
// Record if CPU just went idle.
if(cpu->Getjobs_waiting()==0){
cpu->Setidle(true);
}
// Pop CPU queue to preserve length.
cpu->nextJob();
// Decide where the job goes
if(!decide_quit()){
// Job goes to disk. Choose one.
if(disk_one->Getjobs_waiting() <= disk_two->Getjobs_waiting()){
// Make event a disk 1 arrival
next->jobtype = JOB_ARRIVE_D1;
// Calculate job length - see similar comment above
job_length = ranged_rand(D1_MIN, D1_MAX);
} else {
// Make event a disk 2 arrival
next->jobtype = JOB_ARRIVE_D2;
// Calculate job length - see similar comment above
job_length = ranged_rand(D2_MIN, D2_MAX);
}
// Job arrival at disk ready to go. Time stays the same.
eq->insert(next);
}
else {
// Log completion or something?
// TODO: Figure out if anything needs to happen here.
}
break;
case JOB_ARRIVE_D1:
// TODO: See above thoughts on refactoring in first case.
if(disk_one->Getidle()){
// Disk idle so job doesn't wait. Set idle false.
disk_one->Setidle(false);
} else {
// Put job into component queue.
disk_one->pushJob(next->serial);
}
// Calculate job length - calculate now only for calculating true
// end time - EventQueue doesn't know the wait time, only queue lengths.
job_length = ranged_rand(D1_MIN, D1_MAX);
next->timestamp = global_time + job_length + disk_one->getTime();
// Make event a disk completion.
next->jobtype = JOB_FINISH_D1;
// Put completion into event heap.
eq->pushJob(next);
break;
case JOB_ARRIVE_D2:
// TODO: See above thoughts on refactoring in first case.
if(disk_two->Getidle()){
// Disk idle so job doesn't wait. Set idle false.
disk_two->Setidle(false);
} else {
// Put job into component queue.
disk_two->pushJob(next->serial);
}
// Calculate job length - calculate now only for calculating true
// end time - EventQueue doesn't know the wait time, only queue lengths.
job_length = ranged_rand(D2_MIN, D2_MAX);
next->timestamp = global_time + job_length + disk_two->getTime();
// Make event a disk completion.
next->jobtype = JOB_FINISH_D2;
// Put completion into event heap.
eq->pushJob(next);
break;
case JOB_FINISH_D1:
// Record if Disk just went idle.
if(disk_one->Getjobs_waiting()==0){
disk_one->Setidle(true);
}
// Pop disk queue to preserve length.
disk_one->nextJob();
break;
case JOB_FINISH_D2:
// Record if Disk just went idle.
if(disk_two->Getjobs_waiting()==0){
disk_two->Setidle(true);
}
// Pop disk queue to preserve length.
disk_two->nextJob();
break;
}
return;
}
/*
* Function creates new event and places in event queue.
* Takes pointer to cpu to allow insertion into queue.
* TODO: This is a bad way to distribute events. Can't I just fill the queue\
during initialization, and then stop generating events?
*/
void place_new_event(Component* cpu)
{
Event* ev = (Event*) malloc(sizeof(Event));
// Give event next serial number available.
ev->serial = serial_stamp++;
// Record event as occuring
ev->timestamp = global_time + ranged_rand(ARRIVAL_MIN, ARRIVAL_MAX);
// Record job as a CPU arrival.
ev->jobtype = JOB_ARRIVE_CPU;
}
/*
* Return random int in range [min,max).
*/
int ranged_rand(int min, int max)
{
return (rand()%(max-min)) + min;
}
/*
* Randomly decide whether job is done.
Get random number in [1,100]. If higher than QUIT_PROB then quit.
*/
bool decide_quit()
{
int roll = ranged_rand(0,101);
return (roll > QUIT_PROB*100);
}
|
c027cbf49adb4f19155616885163057fb5bbbe5c | 84d6fab9b8bfcaec43dc05b78c2baab38c0f75df | /Engine2Lib/src/Instrumentation.h | ba2194f047e9e7d7c4c09e0662353cbaed9cde12 | [] | no_license | Dalelit/Engine2 | d9d40cb19e75c4da5c15e25fb04a09976c077eca | 121c20e0764914243489427a74a8614b76acf530 | refs/heads/master | 2021-10-25T02:22:27.336047 | 2021-09-26T10:46:00 | 2021-09-26T10:46:00 | 248,733,512 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,419 | h | Instrumentation.h | #pragma once
#define E2_STATS_VERTEXDRAW(x) { Instrumentation::Drawing::drawCount++; Instrumentation::Drawing::vertexCount += x; }
#define E2_STATS_INDEXDRAW(x) { Instrumentation::Drawing::drawCount++; Instrumentation::Drawing::indexCount += x; }
#define E2_STATS_INSTANCEDRAW(inst) { Instrumentation::Drawing::drawCount++; Instrumentation::Drawing::instanceCount += inst; }
#define E2_STATS_INDEXINSTANCEDRAW(indx, inst) { Instrumentation::Drawing::drawCount++; Instrumentation::Drawing::indexCount += indx; Instrumentation::Drawing::instanceCount += inst; }
#define E2_STATS_VSCB_BIND { Instrumentation::Drawing::vsConstBufferCount++; }
#define E2_STATS_PSCB_BIND { Instrumentation::Drawing::psConstBufferCount++; }
#define E2_STATS_GSCB_BIND { Instrumentation::Drawing::gsConstBufferCount++; }
#include <map>
namespace Engine2
{
namespace Instrumentation
{
void FrameReset();
class Memory
{
public:
static void ImguiWindow(bool* pOpen);
static unsigned long long allocated;
static unsigned long long freed;
};
class Drawing
{
public:
static void ImguiWindow(bool* pOpen);
static unsigned long long drawCount;
static unsigned long long vertexCount;
static unsigned long long indexCount;
static unsigned long long instanceCount;
static unsigned long long vsConstBufferCount;
static unsigned long long psConstBufferCount;
static unsigned long long gsConstBufferCount;
};
template <typename T, unsigned int SIZE>
class AverageTracker
{
public:
void Log(T value)
{
current++; // next
if (current >= SIZE) current = 0; // loop around array
data[current] = value; // set the value
}
float Average()
{
T amt = 0;
for (auto v : data)
{
amt += v;
}
return (float)amt / (float)SIZE;
}
unsigned int current = 0;
unsigned int size = SIZE;
T data[SIZE] = {};
};
class Timer
{
public:
Timer() { startTime = clock(); }
inline void Set() { startTime = clock(); }
inline void Tick() {
clock_t current = clock();
times.Log((float)(current - startTime));
startTime = current;
}
inline float Average() { return times.Average(); }
void OnImgui();
protected:
clock_t startTime;
AverageTracker<float, 60> times;
};
// Use to capture a timer at the beginning, then tick when it goes out of scope at the end.
class TimerResource
{
public:
TimerResource(Timer& t) : timer(t) { timer.Set(); };
~TimerResource() { timer.Tick(); }
protected:
Timer& timer;
};
class TimerCollection
{
public:
TimerResource ScopeTimer(const char* name) { return TimerResource(timers[name]); }
void OnImgui();
protected:
// Using const char* as the key, as this is what __FUNCTION__ macro is. Saves memory allocations for creating std::strings
std::map<const char*, Timer> timers;
};
class MemoryTracker
{
public:
MemoryTracker() { Set(); }
void Set() { allocated = Memory::allocated; freed = Memory::freed; }
void Tick() {
allocations.Log(Memory::allocated - allocated);
freeds.Log(Memory::freed - freed);
Set();
}
AverageTracker<unsigned long long, 60> allocations;
AverageTracker<unsigned long long, 60> freeds;
protected:
unsigned long long allocated;
unsigned long long freed;
};
}
}
|
49f36cec36e2617c4f7d3603818e854af73b1ea1 | aeae9a59fb57b672429c75693140ac9afb3e500e | /Gruppuppgift3/BoxNode.h | 2e2c96fa531f79ae3131b72ccf600cd5f0dd11a5 | [] | no_license | GameProject/Tower | 8d31a1cb70c76f461222a07abfb67cb03d806da8 | 91501df975f3d3dd1dd252ed78b6206f8fff5e24 | refs/heads/master | 2021-01-21T02:30:54.781582 | 2011-05-11T02:00:23 | 2011-05-11T02:00:23 | 1,728,394 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 196 | h | BoxNode.h | #ifndef BOXNODE_H
#define BOXNODE_H
#include <d3dx10.h>
#include <vector>
struct BoxNode
{
D3DXVECTOR3 minB;
D3DXVECTOR3 maxB;
std::vector<int> id;
std::vector<BoxNode> ChildNode;
};
#endif |
4afccf4db15748085f9711599375d2d5c3278f3b | 6d473c1828f0e67ac8c7b9cf5cdd12a91d9b9552 | /repo.h | 0d0dbbdfa636a18a47cbf0fb0cbe4ab725ee98a2 | [] | no_license | amulrichsen/CPSC362Project1 | 88bb6ec014bc7ea6e298b4f9d9c1451bed5f5905 | 681cd6071fd7eafe396a6f014613673eb856cf28 | refs/heads/master | 2020-03-28T21:47:05.003796 | 2018-12-15T09:38:06 | 2018-12-15T09:38:06 | 149,182,409 | 0 | 0 | null | 2018-09-24T05:55:24 | 2018-09-17T20:14:47 | C++ | UTF-8 | C++ | false | false | 1,486 | h | repo.h | /* Repo Class
Creates a repository using a given source tree path and target folder path
Replicates Files and Folders
Authors:
Anette Ulrichsen
amulrichsen@csu.fullerton.edu
John Margis
margisj@csu.fullerton.edu
*/
#pragma once
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <experimental/filesystem>
#include "leaf.h"
#include "manifest.h"
using namespace std;
class Repo
{
public:
string sPath; //source path
string tPath; //target path
string manPath = ""; //manifest path
Leaf *head; //Root folder
Manifest* manifest; //Manifest File
public:
void create(string sPath, string tPath); //creates a repo using a given source tree
string checkIn(string sPath, string tPath); //updates an existing project tree
void checkOut(string sPath, string tPath, string manifest); //creates a repo using a given manifest
void merge(string rPath, string tManifest, string rManifest, string tPath); //merges new changes from a repo into a project tree
void checkInLog(string ptPath, string mPath); //creates a textfile logging the manifests created for each check in from a project tree
void dotFile(string rPath, string mPath, string pPath, string act);
string ancestor(string fName, string checksum, string repoPath, string mPath);
};
//Required Prototypes
char getSlash(string path);
string searchLabels(string sPath, string oldLabel);
bool checkExists(string rManifest, string tManifest);
|
8b5642b5ac66108d4a572b0f473cc1af29f2d46d | e4d60bddba951b92ef586a5d8d5caf2985e991c3 | /백준13458 시험 감독.cpp | 9e8e5e941c6433f7efce68241d4eb8a2d2ec1806 | [] | no_license | Hong-kee/gitforHong | 6ec74bd94b16fd5f38977eb8952325922bf50f0f | e56fd441f720ae4bcd44cfad30f261aab8ecc036 | refs/heads/master | 2023-02-21T00:43:49.970438 | 2021-01-13T09:27:52 | 2021-01-13T09:27:52 | 285,011,113 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 912 | cpp | 백준13458 시험 감독.cpp | #include <iostream>
using namespace std;
long long N, grandmaster, master;
long long ans = 0;
int classroom[1000001];
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
cin >> N;
for (int i = 1; i <= N; i++) {
cin >> classroom[i];
}
cin >> grandmaster >> master;
for (int i = 1; i <= N; i++) {
if (classroom[i] - grandmaster <= 0) {
classroom[i] = 0;
}
else {
classroom[i] -= grandmaster;
}
ans++;
}
for (int i = 1; i <= N; i++) {
if (classroom[i] == 0) {
continue;
}
else if (classroom[i] != 0 && classroom[i] / master >= 1
&& classroom[i] % master != 0) {
ans += (classroom[i] / master) + 1;
}
else if (classroom[i] != 0 && classroom[i] / master >= 1
&& classroom[i] % master == 0) {
ans += classroom[i] / master;
}
else if (classroom[i] != 0 && classroom[i] / master < 1){
ans += 1;
}
}
cout << ans << '\n';
return 0;
}
|
f6359ddaf11bd4109a27cd2bb49022bb1c647482 | a13c1994f21db8a33023dad78790a75d15967a48 | /1BITL/IVS/black_box_tests.cpp | be7ee81542c7f153b7b67cd4af05da52927ce21a | [] | no_license | MasterPK/VUT_FIT | 9d1c128d197d9bc02b70ead26ed32dc94e003fbe | 508e982c3721171d9548dee390e33708031de35b | refs/heads/master | 2020-09-26T16:50:14.917826 | 2020-02-12T19:13:14 | 2020-02-12T19:13:14 | 226,295,850 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,648 | cpp | black_box_tests.cpp | //======== Copyright (c) 2017, FIT VUT Brno, All rights reserved. ============//
//
// Purpose: Red-Black Tree - public interface tests
//
// $NoKeywords: $ivs_project_1 $black_box_tests.cpp
// $Author: JMENO PRIJMENI <xlogin00@stud.fit.vutbr.cz>
// $Date: $2017-01-04
//============================================================================//
/**
* @file black_box_tests.cpp
* @author JMENO PRIJMENI
*
* @brief Implementace testu binarniho stromu.
*/
#include <vector>
#include "gtest/gtest.h"
#include "red_black_tree.h"
//============================================================================//
// ** ZDE DOPLNTE TESTY **
//
// Zde doplnte testy Red-Black Tree, testujte nasledujici:
// 1. Verejne rozhrani stromu
// - InsertNode/DeleteNode a FindNode
// - Chovani techto metod testuje pro prazdny i neprazdny strom.
// 2. Axiomy (tedy vzdy platne vlastnosti) Red-Black Tree:
// - Vsechny listove uzly stromu jsou *VZDY* cerne.
// - Kazdy cerveny uzel muze mit *POUZE* cerne potomky.
// - Vsechny cesty od kazdeho listoveho uzlu ke koreni stromu obsahuji
// *STEJNY* pocet cernych uzlu.
//============================================================================//
class EmptyTree:public ::testing::Test{
protected:
BinaryTree x;
};
class NonEmptyTree:public ::testing::Test{
protected:
BinaryTree x;
virtual void SetUp(){
for(int i=0;i<5;i++){
x.InsertNode(i);
}
}
};
class TreeAxioms:public ::testing::Test{
protected:
BinaryTree x;
virtual void SetUp(){
for(int i=0;i<=2;i++){
x.InsertNode(i);
}
}
};
TEST_F(EmptyTree,DeleteNode){
EXPECT_FALSE(x.DeleteNode(1));
}
TEST_F(EmptyTree,InsertNode){
std::pair<bool, BinaryTree::Node_t *> y;
//1
int cislo =1;
y=x.InsertNode(cislo);
EXPECT_TRUE(y.first);
EXPECT_EQ(y.second->key, cislo);
ASSERT_TRUE(y.second != NULL);
EXPECT_EQ(y.second->color, BLACK);
ASSERT_TRUE(y.second->pParent == NULL);
ASSERT_TRUE(y.second->pLeft != NULL);
ASSERT_TRUE(y.second->pRight != NULL);
//Pleft
ASSERT_TRUE(y.second->pLeft->pParent != NULL);
EXPECT_EQ(y.second->pLeft->color, BLACK);
EXPECT_EQ(y.second->pLeft->pParent->key, cislo);
EXPECT_TRUE(y.second->pLeft->pLeft == NULL);
EXPECT_TRUE(y.second->pLeft->pRight == NULL);
//Pright
ASSERT_TRUE(y.second->pRight->pParent != NULL);
EXPECT_EQ(y.second->pRight->color, BLACK);
EXPECT_EQ(y.second->pRight->pParent->key, cislo);
EXPECT_TRUE(y.second->pRight->pLeft == NULL);
EXPECT_TRUE(y.second->pRight->pRight == NULL);
//1 znovu
y=x.InsertNode(1);
ASSERT_FALSE(y.first);
//2
cislo =2;
y=x.InsertNode(cislo);
EXPECT_TRUE(y.first);
EXPECT_EQ(y.second->key, cislo);
ASSERT_TRUE(y.second != NULL);
EXPECT_EQ(y.second->color, RED);
ASSERT_TRUE(y.second->pParent != NULL);
ASSERT_TRUE(y.second->pLeft != NULL);
ASSERT_TRUE(y.second->pRight != NULL);
//Pleft
ASSERT_TRUE(y.second->pLeft->pParent != NULL);
EXPECT_EQ(y.second->pLeft->color, BLACK);
EXPECT_EQ(y.second->pLeft->pParent->key, cislo);
EXPECT_TRUE(y.second->pLeft->pLeft == NULL);
EXPECT_TRUE(y.second->pLeft->pRight == NULL);
//Pright
ASSERT_TRUE(y.second->pRight->pParent != NULL);
EXPECT_EQ(y.second->pRight->color, BLACK);
EXPECT_EQ(y.second->pRight->pParent->key, cislo);
EXPECT_TRUE(y.second->pRight->pLeft == NULL);
EXPECT_TRUE(y.second->pRight->pRight == NULL);
}
TEST_F(EmptyTree,FindNode){
EXPECT_TRUE(x.FindNode(1) == NULL);
EXPECT_TRUE(x.FindNode(-42) == NULL);
}
TEST_F(NonEmptyTree,DeleteNode){
for(int i=0;i<5;i++){
EXPECT_TRUE(x.DeleteNode(i));
}
EXPECT_FALSE(x.DeleteNode(100));
}
TEST_F(NonEmptyTree,InsertNode){
std::pair<bool, BinaryTree::Node_t *> y;
//1
int cislo =5;
y=x.InsertNode(cislo);
EXPECT_TRUE(y.first);
EXPECT_EQ(y.second->key, cislo);
ASSERT_TRUE(y.second != NULL);
EXPECT_EQ(y.second->color, RED);
ASSERT_TRUE(y.second->pParent != NULL);
ASSERT_TRUE(y.second->pLeft != NULL);
ASSERT_TRUE(y.second->pRight != NULL);
//Pleft
ASSERT_TRUE(y.second->pLeft->pParent != NULL);
EXPECT_EQ(y.second->pLeft->color, BLACK);
EXPECT_EQ(y.second->pLeft->pParent->key, cislo);
EXPECT_TRUE(y.second->pLeft->pLeft == NULL);
EXPECT_TRUE(y.second->pLeft->pRight == NULL);
//Pright
ASSERT_TRUE(y.second->pRight->pParent != NULL);
EXPECT_EQ(y.second->pRight->color, BLACK);
EXPECT_EQ(y.second->pRight->pParent->key, cislo);
EXPECT_TRUE(y.second->pRight->pLeft == NULL);
EXPECT_TRUE(y.second->pRight->pRight == NULL);
//1 znovu
y=x.InsertNode(1);
ASSERT_FALSE(y.first);
//2
cislo =6;
y=x.InsertNode(cislo);
EXPECT_TRUE(y.first);
EXPECT_EQ(y.second->key, cislo);
ASSERT_TRUE(y.second != NULL);
EXPECT_EQ(y.second->color, RED);
ASSERT_TRUE(y.second->pParent != NULL);
ASSERT_TRUE(y.second->pLeft != NULL);
ASSERT_TRUE(y.second->pRight != NULL);
//Pleft
ASSERT_TRUE(y.second->pLeft->pParent != NULL);
EXPECT_EQ(y.second->pLeft->color, BLACK);
EXPECT_EQ(y.second->pLeft->pParent->key, cislo);
EXPECT_TRUE(y.second->pLeft->pLeft == NULL);
EXPECT_TRUE(y.second->pLeft->pRight == NULL);
//Pright
ASSERT_TRUE(y.second->pRight->pParent != NULL);
EXPECT_EQ(y.second->pRight->color, BLACK);
EXPECT_EQ(y.second->pRight->pParent->key, cislo);
EXPECT_TRUE(y.second->pRight->pLeft == NULL);
EXPECT_TRUE(y.second->pRight->pRight == NULL);
}
TEST_F(NonEmptyTree,FindNode){
EXPECT_TRUE(x.FindNode(1) != NULL);
EXPECT_TRUE(x.FindNode(100) == NULL);
EXPECT_TRUE(x.FindNode(-42) == NULL);
}
//axiomy
TEST_F(TreeAxioms,Axiom1){
std::vector<BinaryTree::Node_t *> uzly;
x.GetLeafNodes(uzly);
for(int i=0;i<uzly.size();i++){
EXPECT_EQ(uzly[i]->color, BLACK);
}
}
/*** Konec souboru black_box_tests.cpp ***/
|
b4d08e3810e01ed79669309d8eb2723884a3c9a7 | 9d17289c97ca943856afd96375e458884d27848a | /pracprog2.cpp | 126dac05947515a5aab556abecc1415a0a47e4ac | [] | no_license | pratik-a/DSA | 0b3022638443de8925005abb3c75ea8012e89649 | 94fdf4c11b77421ec7c355a56f799cff9b775ec6 | refs/heads/main | 2023-08-22T00:43:24.773070 | 2021-10-28T18:19:39 | 2021-10-28T18:19:39 | 340,961,805 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,046 | cpp | pracprog2.cpp | #include<iostream>
#include<conio.h>
using namespace std;
void kmin(int arr[],int n,int k)
{
int temp;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(arr[i]>arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
cout<<"\nkth minimum element\t"<<arr[k-1];
}
void kmax(int arr[],int n,int k)
{
int temp;
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(arr[i]<arr[j])
{
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
cout<<"\nkth maximum element\t"<<arr[k-1];
}
void enter()
{
int arr[10],n,k;
cout<<"\nenter numbers of element\t";
cin>>n;
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"\nenter the k for min and max\t";
cin>>k;
kmin(arr,n,k);
kmax(arr,n,k);
}
int main()
{
enter();
getch();
return 0;
}
|
18b2cb9e9365d0019fa9e4f472c5a08bea229330 | aae79375bee5bbcaff765fc319a799f843b75bac | /tco_2019/EllysSki.cpp | 51a721248adbc1027c271916bebd8d110168ee25 | [] | no_license | firewood/topcoder | b50b6a709ea0f5d521c2c8870012940f7adc6b19 | 4ad02fc500bd63bc4b29750f97d4642eeab36079 | refs/heads/master | 2023-08-17T18:50:01.575463 | 2023-08-11T10:28:59 | 2023-08-11T10:28:59 | 1,628,606 | 21 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 5,089 | cpp | EllysSki.cpp | // BEGIN CUT HERE
/*
TCO19 R1B Easy (250)
PROBLEM STATEMENT
Elly hates the cold, but for some weird reason she likes skiing. Now she has started organizing a new ski adventure on a mountain ridge she hasn't visited before.
Elly has a map of the mountain ridge: the vector <int> height.
The mountain (when viewed from a side) has the shape of a polyline that goes through the points (0, height[0]), (1, height[1]), (2, height[2]), and so on.
For example, suppose height = {3, 4, 11, 6, 2, 2, 2, 5, 7, 7, 10, 8, 5, 8, 1, 4}.
If you walk along this mountain from the left to the right, you start at altitude 3, go up to altitude 4, then up some more to altitude 11. From there it goes down the hill to altitudes 6, 2, and so on.
Elly can hire a helicopter to bring her up to any point on the mountain.
She can then pick a direction (either left or right) and start skiing.
There are only two restrictions:
She cannot ski uphill.
While skiing, she cannot change direction. (If she started skiing left, she cannot turn around and ski right, or vice versa.)
For example, suppose Elly starts at index 2 (altitude 11) and chooses to go right. In this case the longest possible ski run consists of five points: {11, 6, 2, 2, 2}. She cannot continue farther because the next segment of the mountain goes uphill.
Should she start at the same place and go left instead, she would only visit three points (altitudes 11, 4, and 3, in this order).
Find the longest section of the mountain Elly can ski in a single run, and return the number of points that form the section.
DEFINITION
Class:EllysSki
Method:getMax
Parameters:vector <int>
Returns:int
Method signature:int getMax(vector <int> height)
CONSTRAINTS
-height will contain between 1 and 50 elements, inclusive.
-Each element of height will be between 1 and 1000, inclusive.
EXAMPLES
0)
{3, 4, 11, 6, 2, 2, 2, 5, 7, 7, 10, 8, 5, 8, 1, 4}
Returns: 7
The example from the problem statement.
The optimal solution is to start at index 10 (altitude 10) and ski left. The points visited, in order in which Elly skis through them, have altitudes {10, 7, 7, 5, 2, 2, 2}.
1)
{42, 42, 42}
Returns: 3
This mountain is quite flat, but okay for skiing, according to Elly. She should start at either end and ski towards the other end.
2)
{543, 230, 421, 415, 271, 962, 677, 373, 951, 114, 379, 15, 211, 955, 66, 573, 982, 296, 730, 591}
Returns: 3
3)
{50, 77, 24, 86, 98, 84, 42, 70, 88, 78, 73, 17, 76, 68, 64, 65, 40, 77, 33, 87, 11, 23, 78, 20, 8, 74, 44, 95, 94, 78, 27, 88, 71, 40, 11, 98, 82, 85, 79, 89, 31, 67, 41, 61, 71, 62, 74, 77, 86, 36}
Returns: 4
*/
// END CUT HERE
#include <algorithm>
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <cstring>
using namespace std;
class EllysSki {
int count(vector <int> height) {
int prev = 1 << 30, cnt = 0, m = 0;
for (int h : height) {
if (h > prev) {
cnt = 0;
}
++cnt;
prev = h;
m = max(m, cnt);
}
return m;
}
public:
int getMax(vector <int> height) {
int ans = count(height);
reverse(height.begin(), height.end());
ans = max(ans, count(height));
return ans;
}
// BEGIN CUT HERE
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
public:
void run_test(int Case) {
int n = 0;
// test_case_0
if ((Case == -1) || (Case == n)){
int Arr0[] = {3, 4, 11, 6, 2, 2, 2, 5, 7, 7, 10, 8, 5, 8, 1, 4};
int Arg1 = 7;
vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0])));
verify_case(n, Arg1, getMax(Arg0));
}
n++;
// test_case_1
if ((Case == -1) || (Case == n)){
int Arr0[] = {42, 42, 42};
int Arg1 = 3;
vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0])));
verify_case(n, Arg1, getMax(Arg0));
}
n++;
// test_case_2
if ((Case == -1) || (Case == n)){
int Arr0[] = {543, 230, 421, 415, 271, 962, 677, 373, 951, 114, 379, 15, 211, 955, 66, 573, 982, 296, 730, 591};
int Arg1 = 3;
vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0])));
verify_case(n, Arg1, getMax(Arg0));
}
n++;
// test_case_3
if ((Case == -1) || (Case == n)){
int Arr0[] = {50, 77, 24, 86, 98, 84, 42, 70, 88, 78, 73, 17, 76, 68, 64, 65, 40, 77, 33, 87, 11, 23, 78, 20, 8, 74, 44, 95, 94, 78, 27, 88, 71, 40, 11, 98, 82, 85, 79, 89, 31, 67, 41, 61, 71, 62, 74, 77, 86, 36};
int Arg1 = 4;
vector <int> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0])));
verify_case(n, Arg1, getMax(Arg0));
}
n++;
}
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
EllysSki ___test;
___test.run_test(-1);
}
// END CUT HERE
|
6762fe031b1f019b24b1c1255fb6f9f4af624929 | 5ca152075444853230a735af9896134cece59a06 | /submissions/U201614898_潘翔_软件工程实验/HUST_SoftwareEngineering_Labs_src/chooseseat_dialog.cpp | 4d49d694e44b5bd5b0578827909e50e487b86395 | [] | no_license | Xiang-Pan/HUST_SoftwareEngineering_Labs | c9f13faffa0396a2ea9859f4573583f25023fdfe | 31c81dc98fcc50a5dfe4740fd51ddf481f7b73a1 | refs/heads/master | 2021-10-10T06:26:21.442377 | 2019-01-07T14:47:30 | 2019-01-07T14:47:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,156 | cpp | chooseseat_dialog.cpp | /* FileName:chooseseat_dialog.cpp
* Author:Hover
* E-Mail:hover@hust.edu.cn
* GitHub:HoverWings
* Description:The implementation of chooseseat module
*/
#include "chooseseat_dialog.h"
#include "ui_chooseseat_dialog.h"
chooseSeat_Dialog::chooseSeat_Dialog(class MainWindow *parent,int FID) :
QDialog(parent),
ui(new Ui::chooseSeat_Dialog)
{
ui->setupUi(this);
this->FID=FID;
qDebug()<<this->FID;
setWindowTitle(tr("请选择座位!"));
setStyleSheet("background-color:white;"
"QPushButton{"
"background-color:white;"
"color:black;"
"text-align:center;"
"border-radius: 8px;"
"border: 2px groove gray;"
"border-style: outset;"
"}");
setButtonGroup(FID);
setImage();
queryFSTATUS(FID);
mw=parent;
// //set qss
// QFile qssfile(":/test.qss");
// qssfile.open(QFile::ReadOnly);
// QString qss;
// qss = qssfile.readAll();
// this->setStyleSheet(qss);
//setAttribute(Qt::WA_DeleteOnClose);
// set focus
}
//RESIZE!
void chooseSeat_Dialog::setImage()
{
QString str = "select * from FMODELinfo where FMODEL= (select FMODEL FROM FLIGHTinfo where FID= "+QString::number(FID,10)+" )";
QSqlQuery query;
query.exec(str);
QPixmap photo;
if(query.next())
{
auto *PicLabel = new QLabel();
photo.loadFromData(query.value(1).toByteArray(), "JPG"); //从数据库中读出图片为二进制数据,图片格式为JPG,然后显示到QLabel里
//photo.scaledToHeight(ui->graphicsView->maximumHeight());
//photo.scaledToWidth(ui->graphicsView->maximumWidth());
photo.scaled(ui->graphicsView->maximumSize());
PicLabel->setPixmap(photo);
PicLabel->setScaledContents(true);
}
auto *scene = new QGraphicsScene;
scene->addPixmap(photo);
ui->graphicsView->setScene(scene);
ui->graphicsView->resize(photo.width()*0.5 + 10, photo.height()*0.5 + 10);
ui->graphicsView->show();
}
void chooseSeat_Dialog::setButtonGroup(int FID)
{
// set button group
int totalNum=0;
int usableNum=0;
QGridLayout *layout = ui->gridLayout_0;
QSqlQuery query;
QString opName="FLIGHTinfo";
QString showItem="FLIGHT";
QString str="select * from FSTATUSinfo where FID ="+QString::number(FID, 10);
query.prepare(str);
bool isOk = query.exec();
if(!isOk)
{
qDebug()<<"set seat button fail!";
return;
}
;
QPushButton* pushbutton=nullptr;
int rowBefore=1;
int row=1;
int col=-1;
int len=0;
int usable=-1;
while (query.next()) // when .next() then go to the next
{
totalNum+=1;
//qDebug()<<query.value(2).toString();
usable=query.value(2).toString().toInt();
len=query.value(1).toString().length();
//qDebug()<<query.value(1).toString();
row=query.value(1).toString().midRef(0,len-1).toInt();
if(row!=rowBefore)
{
col=0;
rowBefore=row;
}
else
{
col+=1;
}
pushbutton = new QPushButton();
pushbutton->setText(query.value(1).toString());
pushButtonMap[query.value(1).toString()]=pushbutton;
layout->addWidget(pushbutton,row,col,1,1);
if(usable)
{
usableNum+=1;
pushbutton->setCheckable(true);
pushbutton->setAutoExclusive(true);
}
else
{
pushbutton->setCheckable(false);
pushbutton->setStyleSheet("background-color: rgb(170, 0, 255);"); //set the background color
}
}
qDebug()<<"totalNum"<<totalNum;
qDebug()<<"usableNum"<<usableNum;
ui->label_totalSeatNum->setText(QString::number(totalNum,10));
ui->label_usableSeatNum->setText(QString::number(usableNum,10));
float fnum=((float)totalNum-usableNum)/totalNum*100;
ui->label_fullRate->setText(QString("%1").arg(fnum)+"%");
}
chooseSeat_Dialog::~chooseSeat_Dialog()
{
delete ui;
}
//query the choosable seat
void chooseSeat_Dialog::queryFSTATUS(int FID)
{
StatusModel=new MySqlQueryModel(this);
StatusModel->opTable=2;
StatusModel->set_op();
QString str="select * from "+StatusModel->opName+" where FID ="+QString::number(FID, 10)+" AND USABLE = 1";
//qDebug()<<str;
StatusModel->setQuery(str);
StatusModel->query().bindValue(":FID",FID);
StatusModel->query().exec();
if(StatusModel->query().next())
{
qDebug()<<StatusModel->query().value(0).toString();
}
else
{
qDebug()<<"No Search Result!";
}
for(int i=0;i<StatusModel->opTitle.size();i++)
{
StatusModel->setHeaderData(i, Qt::Horizontal, StatusModel->opTitle[i]);
}
ui->FSTATUS_tableView->setModel(StatusModel);
ui->FSTATUS_tableView->setSelectionBehavior(QAbstractItemView::SelectRows);
}
void chooseSeat_Dialog::on_chooseSteat_pushButton_clicked()
{
QMapIterator<QString,QPushButton*> i(pushButtonMap);
seatName="";
while (i.hasNext())
{
// qDebug() <<i.next().key()<<i.next().value();
if(i.next().value()->isChecked())
{
seatName=i.key();
break;
}
}
if(seatName=="")
{
QModelIndex selIndex=ui->FSTATUS_tableView->currentIndex();
int selRow=selIndex.row();
//int selCol=selIndex.column();
qDebug()<<selRow;
QModelIndex index= StatusModel->index(selRow,1);
QVariant data = StatusModel->data(index);
qDebug()<<data.toString();
seatName=data.toString();
}
QMessageBox::StandardButton rb = QMessageBox::question(nullptr, "请确认座位", "您选择的座位为:"+seatName, QMessageBox::Yes | QMessageBox::No, QMessageBox::Yes);
if(rb == QMessageBox::Yes)
{
mw->seatName=seatName;
this->close();
}
if(rb == QMessageBox::No)
{
return;
}
//rb = information(NULL, "Show Qt", "Do you want to show Qt dialog?", QMessageBox::Yes QMessageBox::No, QMessageBox::Yes);
}
|
0f1c320c4e1cf690085de1aca43509826478040e | 63a45e299937aee8e9bcd1260c87f50d690563ae | /program.cpp | e067d7167b9853e7152bcac0939318e323f06492 | [
"MIT"
] | permissive | samiullahsaleem/pattern | 464a2c14b0f7b450a10e80539e61c2ca48c4a798 | dc32b398ff4ee5c7d229037e3bf18ae94c6727b2 | refs/heads/main | 2023-05-23T22:20:49.201644 | 2021-06-13T05:54:37 | 2021-06-13T05:54:37 | 376,452,883 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 611 | cpp | program.cpp | #include <iostream>
using namespace std;
int main()
{
int min = 0;
int max = 10;
int counter1 = min;
char symbol = '+' ;
cout << "Pattern A: " << endl;
while(counter1 < max)
{
while(min <= counter1)
{
cout << symbol;
min++;
}
min = 0;
cout << endl;
counter1++;
}
cout << "Pattern B: " << endl;
while(min < max)
{
while(max > min)
{
cout<< symbol;
max--;
}
max = 10;
min++;
cout << endl;
}
return 0;
}
|
c77013b46a5bb51d68ce542e97ab896042dbca30 | 7154a4132b8c55c0bb15794b8829fafa351bc092 | /src/user_interface/user_interface.cpp | d722eca9af4c178059a44d5ffe41cdb822899d48 | [] | no_license | FongYoong/data-logger-esp32 | 22d49e7a4e684833453cf9968c96c6eaba885ba6 | b6e67b3e2dbde7092a37ab8a17cb3ce2a797ad3f | refs/heads/master | 2023-08-04T05:32:30.294902 | 2021-09-11T17:20:50 | 2021-09-11T17:20:50 | 403,499,355 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,742 | cpp | user_interface.cpp | #include "user_interface.h"
#include "fonts/roboto_bold_8.h"
#include "fonts/roboto_bold_10.h"
#include "../pins/pins.h"
#include "../firebase/firebase.h"
#include "../unix_time/unix_time.h"
UserAction currentUserAction = UserAction::UA_NONE; // Current user action state
UIPage currentUIPage = UIPage::P_HOME; // Current UI page state
HomeOption currentHomeOption = HomeOption::HO_ENABLE_LOGGING; // Current home option state
unsigned long logIntervalTemp = 1000; // Milliseconds // Store temporary value
float temperatureLimitTemp = 25; // Celcius // Store temporary value
void userInterfaceSetup()
{
oledDisplay.init(); // Initialize OLED
oledDisplay.clear();
oledDisplay.drawString(0, 0, "Wait ah...");
oledDisplay.display();
}
void processInputs()
{
// Checks each button and sets the current user action
if (digitalRead(button_enter) == LOW)
{
currentUserAction = UserAction::UA_ENTER;
Serial.println("User Action: ENTER");
}
else if (digitalRead(button_back) == LOW)
{
currentUserAction = UserAction::UA_BACK;
Serial.println("User Action: BACK");
}
else if (digitalRead(button_left) == LOW)
{
currentUserAction = UserAction::UA_LEFT;
Serial.println("User Action: LEFT");
}
else if (digitalRead(button_right) == LOW)
{
currentUserAction = UserAction::UA_RIGHT;
Serial.println("User Action: RIGHT");
}
}
void renderUI()
{
if (currentUIPage == UIPage::P_HOME)
{
if (currentUserAction == UserAction::UA_ENTER)
{
if (currentHomeOption == HomeOption::HO_ENABLE_LOGGING)
{
enableLogging = !enableLogging;
updateConfigFirebase(); // Update Firebase
}
else if (currentHomeOption == HomeOption::HO_EDIT_LOG_INTERVAL)
{
currentUIPage = UIPage::P_EDIT_LOG_INTERVAL; // Change page
logIntervalTemp = logInterval; // Initial temporary value
displayEditLogInterval(); // Display on OLED
}
else if (currentHomeOption == HomeOption::HO_EDIT_TEMPERATURE_LIMIT)
{
currentUIPage = UIPage::P_EDIT_TEMPERATURE_LIMIT; // Change page
temperatureLimitTemp = temperatureLimit; // Initial temporary value
displayEditTemperatureLimit(); // Display on OLED
}
}
else
{
const char index= static_cast<char>(currentHomeOption); // Current Home option index
if (currentUserAction == UserAction::UA_LEFT)
{
if (index == 0) {
currentHomeOption = HomeOption::HO_EDIT_TEMPERATURE_LIMIT; // Change Home option
}
else {
currentHomeOption = static_cast<HomeOption>(index - 1); // Change to left Home option
}
}
else if (currentUserAction == UserAction::UA_RIGHT)
{
currentHomeOption = static_cast<HomeOption>((index + 1) % 3); // Change to right Home option.
// Modulo 3 because there's 3 options
}
displayHome(); // Display on OLED
}
}
else if (currentUIPage == UIPage::P_EDIT_LOG_INTERVAL)
{
if (currentUserAction == UserAction::UA_BACK)
{
currentUIPage = UIPage::P_HOME; // Cancel and go back to Home page
displayHome(); // Display on OLED
}
else
{
if (currentUserAction == UserAction::UA_LEFT)
{
// Decrement by step but ensure it is not lower than minimum
logIntervalTemp = max(logIntervalTemp - logIntervalStep, (unsigned long) minLogInterval);
}
else if (currentUserAction == UserAction::UA_RIGHT)
{
logIntervalTemp += logIntervalStep; // Increment by step
}
else if (currentUserAction == UserAction::UA_ENTER)
{
logInterval = logIntervalTemp; // Update to new value
updateConfigFirebase(); // Update Firebase
}
displayEditLogInterval(); // Display on OLED
}
}
else if (currentUIPage == UIPage::P_EDIT_TEMPERATURE_LIMIT)
{
if (currentUserAction == UserAction::UA_BACK)
{
currentUIPage = UIPage::P_HOME; // Cancel and go back to Home page
displayHome(); // Display on OLED
}
else
{
if (currentUserAction == UserAction::UA_LEFT)
{
// Decrement by step but ensure it is not lower than minimum
temperatureLimitTemp = max(temperatureLimitTemp - temperatureLimitStep, minTemperatureLimit);
}
else if (currentUserAction == UserAction::UA_RIGHT)
{
temperatureLimitTemp += temperatureLimitStep; // Increment by step
}
else if (currentUserAction == UserAction::UA_ENTER)
{
temperatureLimit = temperatureLimitTemp; // Update to new value
updateConfigFirebase(); // Update Firebase
}
displayEditTemperatureLimit(); // Display on OLED
}
}
currentUserAction = UA_NONE; // Reset user action
}
// (128 x 64), (width x height)
void displayHome()
{
// 3 selectable options at the top
// temperatureValue and warning at the middle-left
// Wi-Fi connectivity at the middle-right
// Current time at the bottom-right
oledDisplay.clear();
oledDisplay.setFont(Roboto_Bold_8);
// enableLogging option
oledDisplay.setTextAlignment(TEXT_ALIGN_LEFT);
oledDisplay.drawStringMaxWidth(0, 0, 40, enableLogging?"Disable Log":"Enable Log");
if (currentHomeOption == HomeOption::HO_ENABLE_LOGGING) {
oledDisplay.drawRect(0, 0, 30, 22);
}
// Edit logInterval option
oledDisplay.setTextAlignment(TEXT_ALIGN_CENTER);
oledDisplay.drawStringMaxWidth(64, 0, 40, "Log Interval");
if (currentHomeOption == HomeOption::HO_EDIT_LOG_INTERVAL) {
oledDisplay.drawRect(50, 0, 30, 22);
}
// Edit temperatureLimit option
oledDisplay.setTextAlignment(TEXT_ALIGN_RIGHT);
oledDisplay.drawStringMaxWidth(128, 0, 40, "Temp. Limit");
if (currentHomeOption == HomeOption::HO_EDIT_TEMPERATURE_LIMIT) {
oledDisplay.drawRect(98, 0, 30, 22);
}
// Display temperatureValue
oledDisplay.setFont(Roboto_Bold_10);
oledDisplay.setTextAlignment(TEXT_ALIGN_CENTER);
oledDisplay.drawString(32, 28, String(temperatureValue) + "*C");
if (temperatureValue > temperatureLimit)
{
// Display warning if exceed temperatureLimit
oledDisplay.setFont(Roboto_Bold_8);
oledDisplay.setTextAlignment(TEXT_ALIGN_CENTER);
oledDisplay.drawString(32, 44, "Exceeding limit!");
}
// Display Wi-Fi connectivity
oledDisplay.setFont(Roboto_Bold_8);
oledDisplay.setTextAlignment(TEXT_ALIGN_RIGHT);
oledDisplay.drawString(128, 28, WiFi.status() == WL_CONNECTED ? "Online" : "Offline");
// Display current time
struct tm timeinfo;
if (!getLocalTime(&timeinfo)) {
Serial.println("Failed to obtain time");
}
else {
char timeString[10];
strftime(timeString, 10, "%H:%M:%S", &timeinfo);
oledDisplay.setFont(Roboto_Bold_8);
oledDisplay.setTextAlignment(TEXT_ALIGN_RIGHT);
oledDisplay.drawString(128, 50, timeString);
oledDisplay.display();
}
}
void displayEditLogInterval()
{
oledDisplay.clear();
oledDisplay.setFont(Roboto_Bold_10);
// Display title
oledDisplay.setTextAlignment(TEXT_ALIGN_CENTER);
oledDisplay.drawString(64, 5, "Log Interval");
oledDisplay.display();
// Display temporary logInterval
oledDisplay.setTextAlignment(TEXT_ALIGN_CENTER);
oledDisplay.drawString(64, 30, String(logIntervalTemp / 1000.0));
oledDisplay.display();
}
void displayEditTemperatureLimit()
{
oledDisplay.clear();
oledDisplay.setFont(Roboto_Bold_10);
// Display title
oledDisplay.setTextAlignment(TEXT_ALIGN_CENTER);
oledDisplay.drawString(64, 5, "Temperature Limit");
oledDisplay.display();
// Display temporary temperatureLimit
oledDisplay.setTextAlignment(TEXT_ALIGN_CENTER);
oledDisplay.drawString(64, 30, String(temperatureLimitTemp));
oledDisplay.display();
} |
34b40c96a6281690952a65b3dd884aea909455af | 308cf11178f8034c1e64e9692d633dbf94d9edda | /tests/src/test/cpp/crypto/JsonWebKeyTest.cpp | 04666413bc27b9e3457934e80c8578b97e21dff1 | [
"Apache-2.0"
] | permissive | firmangel8/msl | 9abd151c5b31254fba9ce4ea5a61939c7d262da7 | 78dfd67165533d97051ea6d828063eacc92de77a | refs/heads/master | 2020-12-20T06:34:56.344898 | 2019-10-28T20:00:19 | 2019-10-28T20:00:19 | 235,989,131 | 1 | 0 | Apache-2.0 | 2020-01-24T11:18:03 | 2020-01-24T11:18:03 | null | UTF-8 | C++ | false | false | 42,211 | cpp | JsonWebKeyTest.cpp | /**
* Copyright (c) 2016-2017 Netflix, Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <gtest/gtest.h>
#include <crypto/JcaAlgorithm.h>
#include <crypto/JsonWebKey.h>
#include <crypto/OpenSslLib.h>
#include <crypto/Random.h>
#include <crypto/OpenSslLib.h>
#include <io/MslArray.h>
#include <util/MockMslContext.h>
#include <util/ScopedDisposer.h>
#include <io/MslEncoderUtils.h>
#include <MslCryptoException.h>
#include <MslEncodingException.h>
#include <openssl/x509.h>
#include <openssl/bn.h>
#include <memory>
#include <set>
#include <string>
#include "../util/MslTestUtils.h"
using namespace std;
using namespace netflix::msl;
using namespace netflix::msl::entityauth;
using namespace netflix::msl::io;
using namespace netflix::msl::util;
namespace netflix {
namespace msl {
namespace crypto {
namespace {
/** JSON key key type. */
const string KEY_TYPE = "kty";
/** JSON key usage. */
const string KEY_USAGE = "use";
/** JSON key key operations. */
const string KEY_KEY_OPS = "key_ops";
/** JSON key algorithm. */
const string KEY_ALGORITHM = "alg";
/** JSON key extractable. */
const string KEY_EXTRACTABLE = "extractable";
/** JSON key key ID. */
const string KEY_KEY_ID = "kid";
// RSA keys.
/** JSON key modulus. */
const string KEY_MODULUS = "n";
/** JSON key public exponent. */
const string KEY_PUBLIC_EXPONENT = "e";
/** JSON key private exponent. */
const string KEY_PRIVATE_EXPONENT = "d";
// Symmetric keys.
/** JSON key key. */
const string KEY_KEY = "k";
const string KEY_ID = "kid";
#define RSA_KEY_SIZE_BITS (1024)
#define RSA_PUB_EXP (65537ull)
shared_ptr<ByteArray> BigNumToByteArray(const BIGNUM *bn)
{
shared_ptr<ByteArray> buf = make_shared<ByteArray>(BN_num_bytes(bn));
unsigned char * const pBuf = &(*buf)[0];
BN_bn2bin(bn, pBuf);
return buf;
}
class RsaKey
{
public:
RsaKey() {}
bool init()
{
bool keygenSuccess = false;
uint32_t retryCount = 0;
const uint32_t MAX_RETRIES=4;
while (!keygenSuccess && (retryCount < MAX_RETRIES))
{
rsa.reset(RSA_generate_key(RSA_KEY_SIZE_BITS, RSA_PUB_EXP, 0, 0));
if (rsa.get())
keygenSuccess = (RSA_check_key(rsa.get()) == 1);
retryCount++;
}
return keygenSuccess;
}
shared_ptr<ByteArray> getPublicKeySpki() const
{
if (!rsa.get())
throw MslInternalException("RsaKey not initialized");
int outLen = i2d_RSA_PUBKEY(rsa.get(), NULL);
shared_ptr<ByteArray> spki = make_shared<ByteArray>(outLen);
unsigned char * buf = &(*spki)[0];
i2d_RSA_PUBKEY(rsa.get(), &buf);
return spki;
}
shared_ptr<ByteArray> getPrivateKeyPkcs8() const
{
if (!rsa.get())
throw MslInternalException("RsaKey not initialized");
ScopedDisposer<EVP_PKEY, void, EVP_PKEY_free> pkey(EVP_PKEY_new());
if (!pkey.get())
throw MslInternalException("EVP_PKEY_new() failed");
int ret = EVP_PKEY_set1_RSA(pkey.get(), rsa.get());
if (!ret)
throw MslInternalException("EVP_PKEY_set1_RSA() failed");
ScopedDisposer<PKCS8_PRIV_KEY_INFO, void, PKCS8_PRIV_KEY_INFO_free> p8inf(EVP_PKEY2PKCS8(pkey.get()));
if (!p8inf.get())
throw MslInternalException("EVP_PKEY2PKCS8() failed");
int outLen = i2d_PKCS8_PRIV_KEY_INFO(p8inf.get(), NULL);
if (outLen <= 0)
throw MslInternalException("i2d_PKCS8_PRIV_KEY_INFO() returned bad length");
shared_ptr<ByteArray> pkcs8 = make_shared<ByteArray>(outLen);
unsigned char * buf = &(*pkcs8)[0];
ret = i2d_PKCS8_PRIV_KEY_INFO(p8inf.get(), &buf);
if (!ret)
throw MslInternalException("i2d_PKCS8_PRIV_KEY_INFO() failed");
return pkcs8;
}
shared_ptr<ByteArray> getPublicExponent() const
{
return BigNumToByteArray(rsa.get()->e);
}
shared_ptr<ByteArray> getPrivateExponent() const
{
return BigNumToByteArray(rsa.get()->d);
}
shared_ptr<ByteArray> getModulus() const
{
return BigNumToByteArray(rsa.get()->n);
}
private:
ScopedDisposer<RSA, void, RSA_free> rsa;
};
class MyRsaPublicKey : public PublicKey
{
public:
MyRsaPublicKey(shared_ptr<ByteArray> spki)
: PublicKey(spki, "RSA")
{
shared_ptr<RsaEvpKey> rsaEvpKey = RsaEvpKey::fromSpki(spki);
shared_ptr<ByteArray> ignore;
rsaEvpKey->toRaw(publicModulus, publicExponent, ignore);
}
shared_ptr<ByteArray> getModulus() const { return publicModulus; }
shared_ptr<ByteArray> getPublicExponent() const { return publicExponent; }
private:
shared_ptr<ByteArray> publicModulus;
shared_ptr<ByteArray> publicExponent;
};
class MyRsaPrivateKey : public PrivateKey
{
public:
MyRsaPrivateKey(shared_ptr<ByteArray> pkcs8)
: PrivateKey(pkcs8, "RSA")
{
shared_ptr<RsaEvpKey> rsaEvpKey = RsaEvpKey::fromPkcs8(pkcs8);
rsaEvpKey->toRaw(publicModulus, publicExponent, privateExponent);
}
shared_ptr<ByteArray> getModulus() const { return publicModulus; }
shared_ptr<ByteArray> getPublicExponent() const { return publicExponent; }
shared_ptr<ByteArray> getPrivateExponent() const { return privateExponent; }
private:
shared_ptr<ByteArray> publicModulus;
shared_ptr<ByteArray> publicExponent;
shared_ptr<ByteArray> privateExponent;
};
// poor-man's singleton to make sure we only do keygen once for all tests
shared_ptr<RsaKey> getRsaKey()
{
static shared_ptr<RsaKey> rsaKey;
if (!rsaKey) {
rsaKey = make_shared<RsaKey>();
rsaKey->init();
}
return rsaKey;
}
RSA * getRsaKeyFromSpki(shared_ptr<PublicKey> key)
{
assert(key->getFormat() == "SPKI");
shared_ptr<ByteArray> spki = key->getEncoded();
const unsigned char * buf = &(*spki)[0];
ScopedDisposer<RSA, void, RSA_free> rsa(d2i_RSA_PUBKEY(NULL, &buf, (long)spki->size()));
assert(rsa);
return rsa.release();
}
shared_ptr<ByteArray> getModulus(shared_ptr<PublicKey> key)
{
ScopedDisposer<RSA, void, RSA_free> rsa(getRsaKeyFromSpki(key));
assert(rsa);
return BigNumToByteArray(rsa.get()->n);
}
shared_ptr<ByteArray> getPublicExponent(shared_ptr<PublicKey> key)
{
ScopedDisposer<RSA, void, RSA_free> rsa(getRsaKeyFromSpki(key));
assert(rsa);
return BigNumToByteArray(rsa.get()->e);
}
EVP_PKEY * getEvpPkeyFromPkcs8(shared_ptr<PrivateKey> key)
{
assert(key->getFormat() == "PKCS8");
shared_ptr<ByteArray> pkcs8 = key->getEncoded();
// OpenSSL does not make it easy to import a private key in PKCS#8 format.
// make a mem BIO pointing to the incoming PKCS#8 data
char* const data = reinterpret_cast<char*>(&(*pkcs8)[0]);
ScopedDisposer<BIO, void, BIO_free_all> bio(BIO_new_mem_buf(data, (int)pkcs8->size()));
assert(bio.get());
// get a PKCS8_PRIV_KEY_INFO struct from the BIO
ScopedDisposer<PKCS8_PRIV_KEY_INFO, void, PKCS8_PRIV_KEY_INFO_free> p8inf(
d2i_PKCS8_PRIV_KEY_INFO_bio(bio.get(), NULL));
assert(p8inf.get());
// create a EVP_PKEY from the PKCS8_PRIV_KEY_INFO
ScopedDisposer<EVP_PKEY, void, EVP_PKEY_free> pkey(EVP_PKCS82PKEY(p8inf.get()));
assert(pkey.get());
return pkey.release();
}
shared_ptr<ByteArray> getModulus(shared_ptr<PrivateKey> key)
{
ScopedDisposer<EVP_PKEY, void, EVP_PKEY_free> pkey(getEvpPkeyFromPkcs8(key));
assert(pkey.get());
// get the RSA struct from the EVP_PKEY
const RSA * const rsa = EVP_PKEY_get1_RSA(pkey.get());
assert(rsa);
return BigNumToByteArray(rsa->n);
}
shared_ptr<ByteArray> getPublicExponent(shared_ptr<PrivateKey> key)
{
ScopedDisposer<EVP_PKEY, void, EVP_PKEY_free> pkey(getEvpPkeyFromPkcs8(key));
assert(pkey.get());
// get the RSA struct from the EVP_PKEY
const RSA * const rsa = EVP_PKEY_get1_RSA(pkey.get());
assert(rsa);
return BigNumToByteArray(rsa->e);
}
shared_ptr<ByteArray> getPrivateExponent(shared_ptr<PrivateKey> key)
{
ScopedDisposer<EVP_PKEY, void, EVP_PKEY_free> pkey(getEvpPkeyFromPkcs8(key));
assert(pkey.get());
// get the RSA struct from the EVP_PKEY
const RSA * const rsa = EVP_PKEY_get1_RSA(pkey.get());
assert(rsa);
return BigNumToByteArray(rsa->d);
}
} // namespace anonymous
/**
* JSON web key unit tests.
*/
class JsonWebKeyTest : public ::testing::Test
{
public:
JsonWebKeyTest()
: NULL_USAGE(JsonWebKey::Usage::invalid)
, EXTRACTABLE(true)
, KEY_ID("kid")
, ctx(make_shared<MockMslContext>(EntityAuthenticationScheme::PSK, false))
, random(ctx->getRandom())
, encoder(ctx->getMslEncoderFactory())
, ENCODER_FORMAT(MslEncoderFormat::JSON)
{
ENCRYPT_DECRYPT.insert(JsonWebKey::KeyOp::encrypt);
ENCRYPT_DECRYPT.insert(JsonWebKey::KeyOp::decrypt);
WRAP_UNWRAP.insert(JsonWebKey::KeyOp::wrapKey);
WRAP_UNWRAP.insert(JsonWebKey::KeyOp::unwrapKey);
SIGN_VERIFY.insert(JsonWebKey::KeyOp::sign);
SIGN_VERIFY.insert(JsonWebKey::KeyOp::verify);
MA_SIGN_VERIFY = make_shared<MslArray>();
MA_SIGN_VERIFY->put(-1, JsonWebKey::KeyOp::sign.name());
MA_SIGN_VERIFY->put(-1, JsonWebKey::KeyOp::verify.name());
MA_ENCRYPT_DECRYPT = make_shared<MslArray>();
MA_ENCRYPT_DECRYPT->put(-1, JsonWebKey::KeyOp::encrypt.name());
MA_ENCRYPT_DECRYPT->put(-1, JsonWebKey::KeyOp::decrypt.name());
MA_WRAP_UNWRAP = make_shared<MslArray>();
MA_WRAP_UNWRAP->put(-1, JsonWebKey::KeyOp::wrapKey.name());
MA_WRAP_UNWRAP->put(-1, JsonWebKey::KeyOp::unwrapKey.name());
shared_ptr<RsaKey> rsaKey = getRsaKey();
PUBLIC_KEY = make_shared<MyRsaPublicKey>(rsaKey->getPublicKeySpki());
PRIVATE_KEY = make_shared<MyRsaPrivateKey>(rsaKey->getPrivateKeyPkcs8());
shared_ptr<ByteArray> keydata = make_shared<ByteArray>(16);
random->nextBytes(*keydata);
SECRET_KEY = make_shared<SecretKey>(keydata, JcaAlgorithm::AES);
}
protected:
// Key operations.
/** Encrypt/decrypt key operations. */
set<JsonWebKey::KeyOp> ENCRYPT_DECRYPT;
/** Wrap/unwrap key operations. */
set<JsonWebKey::KeyOp> WRAP_UNWRAP;
/** Sign/verify key operations. */
set<JsonWebKey::KeyOp> SIGN_VERIFY;
// Expected key operations MSL arrays.
/** Sign/verify. */
shared_ptr<MslArray> MA_SIGN_VERIFY;
/** Encrypt/decrypt. */
shared_ptr<MslArray> MA_ENCRYPT_DECRYPT;
/** Wrap/unwrap. */
shared_ptr<MslArray> MA_WRAP_UNWRAP;
/** Null usage. */
JsonWebKey::Usage NULL_USAGE;
/** Null key operations. */
set<JsonWebKey::KeyOp> NULL_KEYOPS;
const bool EXTRACTABLE = true;
const string KEY_ID;
shared_ptr<PublicKey> PUBLIC_KEY;
shared_ptr<PrivateKey> PRIVATE_KEY;
shared_ptr<SecretKey> SECRET_KEY;
shared_ptr<MslContext> ctx;
shared_ptr<IRandom> random;
/** MSL encoder factory. */
shared_ptr<MslEncoderFactory> encoder;
/** Encoder format. */
const MslEncoderFormat ENCODER_FORMAT;
};
TEST_F(JsonWebKeyTest, evpKey)
{
shared_ptr<RsaEvpKey> evpKey1 = RsaEvpKey::fromPkcs8(PRIVATE_KEY->getEncoded());
shared_ptr<ByteArray> pubMod, pubExp, privExp;
evpKey1->toRaw(pubMod, pubExp, privExp);
shared_ptr<RsaEvpKey> evpKey2 = RsaEvpKey::fromRaw(pubMod, pubExp, privExp);
shared_ptr<ByteArray> pkcs8 = evpKey2->toPkcs8();
EXPECT_EQ(*PRIVATE_KEY->getEncoded(), *pkcs8);
shared_ptr<RsaEvpKey> evpKey3 = RsaEvpKey::fromPkcs8(pkcs8);
shared_ptr<ByteArray> n, e, d;
evpKey3->toRaw(n, e, d);
EXPECT_EQ(*getPrivateExponent(PRIVATE_KEY), *d);
}
TEST_F(JsonWebKeyTest, rsaUsageCtor)
{
const JsonWebKey jwk(JsonWebKey::Usage::sig, JsonWebKey::Algorithm::RSA1_5, EXTRACTABLE, KEY_ID, PUBLIC_KEY, PRIVATE_KEY);
EXPECT_EQ(EXTRACTABLE, jwk.isExtractable());
EXPECT_EQ(JsonWebKey::Algorithm::RSA1_5, jwk.getAlgorithm());
EXPECT_EQ(KEY_ID, *jwk.getId());
shared_ptr<KeyPair> keypair = jwk.getRsaKeyPair();
EXPECT_TRUE(keypair);
EXPECT_EQ(*PUBLIC_KEY, *keypair->publicKey);
EXPECT_EQ(*PRIVATE_KEY, *keypair->privateKey);
EXPECT_FALSE(jwk.getSecretKey());
EXPECT_EQ(JsonWebKey::Type::rsa, jwk.getType());
EXPECT_EQ(JsonWebKey::Usage::sig, jwk.getUsage());
EXPECT_EQ(0u, jwk.getKeyOps().size());
shared_ptr<ByteArray> encode = jwk.toMslEncoding(encoder, ENCODER_FORMAT);
EXPECT_TRUE(encode);
const JsonWebKey moJwk(encoder->parseObject(encode));
EXPECT_EQ(jwk.isExtractable(), moJwk.isExtractable());
EXPECT_EQ(jwk.getAlgorithm(), moJwk.getAlgorithm());
EXPECT_EQ(*jwk.getId(), *moJwk.getId());
shared_ptr<KeyPair> moKeypair = moJwk.getRsaKeyPair();
EXPECT_TRUE(moKeypair);
EXPECT_EQ(*keypair->publicKey, *moKeypair->publicKey);
EXPECT_EQ(*getPrivateExponent(keypair->privateKey), *getPrivateExponent(moKeypair->privateKey));
EXPECT_EQ(*keypair->privateKey, *moKeypair->privateKey);
EXPECT_FALSE(moJwk.getSecretKey());
EXPECT_EQ(jwk.getType(), moJwk.getType());
EXPECT_EQ(jwk.getUsage(), moJwk.getUsage());
EXPECT_EQ(jwk.getKeyOps(), moJwk.getKeyOps());
shared_ptr<ByteArray> moEncode = moJwk.toMslEncoding(encoder, ENCODER_FORMAT);
EXPECT_TRUE(moEncode);
EXPECT_EQ(*encode, *moEncode);
}
TEST_F(JsonWebKeyTest, rsaKeyOpsCtor)
{
const JsonWebKey jwk(SIGN_VERIFY, JsonWebKey::Algorithm::RSA1_5, EXTRACTABLE, KEY_ID, PUBLIC_KEY, PRIVATE_KEY);
EXPECT_EQ(EXTRACTABLE, jwk.isExtractable());
EXPECT_EQ(JsonWebKey::Algorithm::RSA1_5, jwk.getAlgorithm());
EXPECT_EQ(KEY_ID, *jwk.getId());
shared_ptr<KeyPair> keypair = jwk.getRsaKeyPair();
EXPECT_TRUE(keypair);
EXPECT_EQ(*PUBLIC_KEY, *keypair->publicKey);
EXPECT_EQ(*PRIVATE_KEY, *keypair->privateKey);
EXPECT_FALSE(jwk.getSecretKey());
EXPECT_EQ(JsonWebKey::Type::rsa, jwk.getType());
EXPECT_EQ(JsonWebKey::Usage::invalid, jwk.getUsage());
EXPECT_EQ(SIGN_VERIFY, jwk.getKeyOps());
shared_ptr<ByteArray> encode = jwk.toMslEncoding(encoder, ENCODER_FORMAT);
EXPECT_TRUE(encode);
const JsonWebKey moJwk(encoder->parseObject(encode));
EXPECT_EQ(jwk.isExtractable(), moJwk.isExtractable());
EXPECT_EQ(jwk.getAlgorithm(), moJwk.getAlgorithm());
EXPECT_EQ(*jwk.getId(), *moJwk.getId());
shared_ptr<KeyPair> moKeypair = moJwk.getRsaKeyPair();
EXPECT_TRUE(moKeypair);
EXPECT_EQ(*keypair->publicKey, *keypair->publicKey);
EXPECT_EQ(*keypair->privateKey, *keypair->privateKey);
EXPECT_FALSE(moJwk.getSecretKey());
EXPECT_EQ(jwk.getType(), moJwk.getType());
EXPECT_EQ(jwk.getUsage(), moJwk.getUsage());
EXPECT_EQ(jwk.getKeyOps(), moJwk.getKeyOps());
shared_ptr<ByteArray> moEncode = moJwk.toMslEncoding(encoder, ENCODER_FORMAT);
EXPECT_TRUE(moEncode);
EXPECT_EQ(*encode, *moEncode);
}
TEST_F(JsonWebKeyTest, rsaUsageJson)
{
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(JsonWebKey::Usage::sig, JsonWebKey::Algorithm::RSA1_5, EXTRACTABLE, KEY_ID, PUBLIC_KEY, PRIVATE_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
EXPECT_EQ(EXTRACTABLE, mo->optBoolean(KEY_EXTRACTABLE));
EXPECT_EQ(JsonWebKey::Algorithm::RSA1_5.name(), mo->getString(KEY_ALGORITHM));
EXPECT_EQ(KEY_ID, mo->getString(KEY_KEY_ID));
EXPECT_EQ(JsonWebKey::Type::rsa.name(), mo->getString(KEY_TYPE));
EXPECT_EQ(JsonWebKey::Usage::sig.name(), mo->getString(KEY_USAGE));
EXPECT_FALSE(mo->has(KEY_KEY_OPS));
shared_ptr<string> modulus = MslEncoderUtils::b64urlEncode(getModulus(PUBLIC_KEY));
shared_ptr<string> pubexp = MslEncoderUtils::b64urlEncode(getPublicExponent(PUBLIC_KEY));
shared_ptr<string> privexp = MslEncoderUtils::b64urlEncode(getPrivateExponent(PRIVATE_KEY));
EXPECT_EQ(*modulus, mo->getString(KEY_MODULUS));
EXPECT_EQ(*pubexp, mo->getString(KEY_PUBLIC_EXPONENT));
EXPECT_EQ(*privexp, mo->getString(KEY_PRIVATE_EXPONENT));
EXPECT_FALSE(mo->has(KEY_KEY));
}
TEST_F(JsonWebKeyTest, rsaKeyOpsJson)
{
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(SIGN_VERIFY, JsonWebKey::Algorithm::RSA1_5, EXTRACTABLE, KEY_ID, PUBLIC_KEY, PRIVATE_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
EXPECT_EQ(EXTRACTABLE, mo->optBoolean(KEY_EXTRACTABLE));
EXPECT_EQ(JsonWebKey::Algorithm::RSA1_5.name(), mo->getString(KEY_ALGORITHM));
EXPECT_EQ(KEY_ID, mo->getString(KEY_KEY_ID));
EXPECT_EQ(JsonWebKey::Type::rsa.name(), mo->getString(KEY_TYPE));
EXPECT_FALSE(mo->has(KEY_USAGE));
EXPECT_EQ(MA_SIGN_VERIFY, mo->getMslArray(KEY_KEY_OPS));
shared_ptr<string> modulus = MslEncoderUtils::b64urlEncode(getModulus(PUBLIC_KEY));
shared_ptr<string> pubexp = MslEncoderUtils::b64urlEncode(getPublicExponent(PUBLIC_KEY));
shared_ptr<string> privexp = MslEncoderUtils::b64urlEncode(getPrivateExponent(PRIVATE_KEY));
EXPECT_EQ(*modulus, mo->getString(KEY_MODULUS));
EXPECT_EQ(*pubexp, mo->getString(KEY_PUBLIC_EXPONENT));
EXPECT_EQ(*privexp, mo->getString(KEY_PRIVATE_EXPONENT));
//EXPECT_EQ(key, mo->getString(KEY_KEY)); FIXME whatfor?
}
TEST_F(JsonWebKeyTest, rsaNullCtorPublic)
{
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", PUBLIC_KEY, shared_ptr<PrivateKey>());
EXPECT_FALSE(jwk->isExtractable());
EXPECT_EQ(JsonWebKey::Algorithm::INVALID, jwk->getAlgorithm());
EXPECT_EQ("", *jwk->getId());
std::shared_ptr<KeyPair> keypair = jwk->getRsaKeyPair();
EXPECT_TRUE(keypair.get());
EXPECT_EQ(*getModulus(PUBLIC_KEY), *getModulus(keypair->publicKey));
EXPECT_EQ(*getPublicExponent(PUBLIC_KEY), *getPublicExponent(keypair->publicKey));
EXPECT_FALSE(keypair->privateKey);
EXPECT_FALSE(jwk->getSecretKey());
EXPECT_EQ(JsonWebKey::Type::rsa, jwk->getType());
EXPECT_EQ(NULL_USAGE, jwk->getUsage());
EXPECT_EQ(0u, jwk->getKeyOps().size());
shared_ptr<ByteArray> encode = jwk->toMslEncoding(encoder, ENCODER_FORMAT);
EXPECT_TRUE(encode);
const JsonWebKey moJwk(encoder->parseObject(encode));
EXPECT_EQ(jwk->isExtractable(), moJwk.isExtractable());
EXPECT_EQ(jwk->getAlgorithm(), moJwk.getAlgorithm());
EXPECT_EQ(*jwk->getId(), *moJwk.getId());
std::shared_ptr<KeyPair> moKeypair = moJwk.getRsaKeyPair();
EXPECT_TRUE(moKeypair);
EXPECT_EQ(*getModulus(keypair->publicKey), *getModulus(moKeypair->publicKey));
EXPECT_EQ(*getPublicExponent(keypair->publicKey), *getPublicExponent(moKeypair->publicKey));
EXPECT_FALSE(moKeypair->privateKey);
EXPECT_FALSE(moJwk.getSecretKey());
EXPECT_EQ(jwk->getType(), moJwk.getType());
EXPECT_EQ(jwk->getUsage(), moJwk.getUsage());
EXPECT_EQ(jwk->getKeyOps(), moJwk.getKeyOps());
shared_ptr<ByteArray> moEncode = moJwk.toMslEncoding(encoder, ENCODER_FORMAT);
EXPECT_TRUE(moEncode);
EXPECT_EQ(*encode, *moEncode);
}
TEST_F(JsonWebKeyTest, rsaNullCtorPrivate)
{
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", shared_ptr<PublicKey>(), PRIVATE_KEY);
EXPECT_FALSE(jwk->isExtractable());
EXPECT_EQ(JsonWebKey::Algorithm::INVALID, jwk->getAlgorithm());
EXPECT_EQ(JsonWebKey::Algorithm::INVALID, jwk->getAlgorithm());
std::shared_ptr<KeyPair> keypair = jwk->getRsaKeyPair();
EXPECT_TRUE(keypair.get());
EXPECT_FALSE(keypair->publicKey);
EXPECT_EQ(*getModulus(PRIVATE_KEY), *getModulus(keypair->privateKey));
EXPECT_EQ(*getPublicExponent(PRIVATE_KEY), *getPublicExponent(keypair->privateKey));
EXPECT_FALSE(jwk->getSecretKey());
EXPECT_EQ(JsonWebKey::Type::rsa, jwk->getType());
EXPECT_EQ(NULL_USAGE, jwk->getUsage());
EXPECT_EQ(0u, jwk->getKeyOps().size());
shared_ptr<ByteArray> encode = jwk->toMslEncoding(encoder, ENCODER_FORMAT);
EXPECT_TRUE(encode);
shared_ptr<JsonWebKey> moJwk = make_shared<JsonWebKey>(encoder->parseObject(encode));
EXPECT_EQ(jwk->isExtractable(), moJwk->isExtractable());
EXPECT_EQ(jwk->getAlgorithm(), moJwk->getAlgorithm());
EXPECT_EQ(*jwk->getId(), *moJwk->getId());
std::shared_ptr<KeyPair> moKeypair = moJwk->getRsaKeyPair();
EXPECT_TRUE(moKeypair);
EXPECT_FALSE(moKeypair->publicKey);
EXPECT_TRUE(moKeypair->privateKey);
EXPECT_EQ(*getModulus(keypair->privateKey), *getModulus(moKeypair->privateKey));
EXPECT_EQ(*getPrivateExponent(keypair->privateKey), *getPrivateExponent(moKeypair->privateKey));
EXPECT_FALSE(moJwk->getSecretKey());
EXPECT_EQ(jwk->getType(), moJwk->getType());
EXPECT_EQ(jwk->getUsage(), moJwk->getUsage());
EXPECT_EQ(jwk->getKeyOps(), moJwk->getKeyOps());
shared_ptr<ByteArray> moEncode = moJwk->toMslEncoding(encoder, ENCODER_FORMAT);
EXPECT_TRUE(moEncode);
EXPECT_EQ(*encode, *moEncode);
}
TEST_F(JsonWebKeyTest, rsaNullJsonPublic)
{
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", PUBLIC_KEY, shared_ptr<PrivateKey>());
shared_ptr<ByteArray> encode = jwk->toMslEncoding(encoder, ENCODER_FORMAT);
shared_ptr<MslObject> mo = encoder->parseObject(encode);
EXPECT_FALSE(mo->getBoolean(KEY_EXTRACTABLE));
EXPECT_FALSE(mo->has(KEY_ALGORITHM));
EXPECT_EQ("", mo->getString(KEY_KEY_ID));
EXPECT_EQ(JsonWebKey::Type::rsa.name(), mo->getString(KEY_TYPE));
EXPECT_FALSE(mo->has(KEY_USAGE));
EXPECT_FALSE(mo->has(KEY_KEY_OPS));
shared_ptr<string> modulus = MslEncoderUtils::b64urlEncode(getModulus(PUBLIC_KEY));
shared_ptr<string> pubexp = MslEncoderUtils::b64urlEncode(getPublicExponent(PUBLIC_KEY));
EXPECT_EQ(*modulus, mo->getString(KEY_MODULUS));
EXPECT_EQ(*pubexp, mo->getString(KEY_PUBLIC_EXPONENT));
EXPECT_FALSE(mo->has(KEY_PRIVATE_EXPONENT));
EXPECT_FALSE(mo->has(KEY_KEY));
}
TEST_F(JsonWebKeyTest, rsaNullJsonPrivate)
{
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", shared_ptr<PublicKey>(), PRIVATE_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
EXPECT_FALSE(mo->getBoolean(KEY_EXTRACTABLE));
EXPECT_FALSE(mo->has(KEY_ALGORITHM));
EXPECT_EQ("", mo->getString(KEY_KEY_ID));
EXPECT_EQ(JsonWebKey::Type::rsa.name(), mo->getString(KEY_TYPE));
EXPECT_FALSE(mo->has(KEY_USAGE));
EXPECT_FALSE(mo->has(KEY_KEY_OPS));
shared_ptr<string> modulus = MslEncoderUtils::b64urlEncode(getModulus(PUBLIC_KEY));
shared_ptr<string> privexp = MslEncoderUtils::b64urlEncode(getPrivateExponent(PRIVATE_KEY));
EXPECT_EQ(*modulus, mo->getString(KEY_MODULUS));
EXPECT_FALSE(mo->has(KEY_PUBLIC_EXPONENT));
EXPECT_EQ(*privexp, mo->getString(KEY_PRIVATE_EXPONENT));
EXPECT_FALSE(mo->has(KEY_KEY));
}
//@Test(expected = MslInternalException.class)
TEST_F(JsonWebKeyTest, rsaCtorNullKeys)
{
EXPECT_THROW(new JsonWebKey(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", shared_ptr<PublicKey>(), shared_ptr<PrivateKey>()), MslInternalException);
}
//@Test(expected = MslInternalException.class)
TEST_F(JsonWebKeyTest, rsaCtorMismatchedAlgorithm)
{
EXPECT_THROW(new JsonWebKey(NULL_USAGE, JsonWebKey::Algorithm::A128CBC, false, "", PUBLIC_KEY, PRIVATE_KEY), MslInternalException);
}
TEST_F(JsonWebKeyTest, octUsageCtor)
{
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(JsonWebKey::Usage::enc, JsonWebKey::Algorithm::A128CBC, EXTRACTABLE, KEY_ID, SECRET_KEY);
EXPECT_EQ(EXTRACTABLE, jwk->isExtractable());
EXPECT_EQ(JsonWebKey::Algorithm::A128CBC, jwk->getAlgorithm());
EXPECT_EQ(KEY_ID, *jwk->getId());
EXPECT_FALSE(jwk->getRsaKeyPair());
EXPECT_EQ(SECRET_KEY->getEncoded(), jwk->getSecretKey()->getEncoded());
EXPECT_EQ(JsonWebKey::Type::oct, jwk->getType());
EXPECT_EQ(JsonWebKey::Usage::enc, jwk->getUsage());
EXPECT_EQ(0u, jwk->getKeyOps().size());
shared_ptr<ByteArray> encode = jwk->toMslEncoding(encoder, ENCODER_FORMAT);
EXPECT_TRUE(encode);
shared_ptr<JsonWebKey> moJwk = make_shared<JsonWebKey>(encoder->parseObject(encode));
EXPECT_EQ(jwk->isExtractable(), moJwk->isExtractable());
EXPECT_EQ(jwk->getAlgorithm(), moJwk->getAlgorithm());
EXPECT_EQ(*jwk->getId(), *moJwk->getId());
EXPECT_FALSE(moJwk->getRsaKeyPair());
EXPECT_EQ(*jwk->getSecretKey()->getEncoded(), *moJwk->getSecretKey()->getEncoded());
EXPECT_EQ(jwk->getType(), moJwk->getType());
EXPECT_EQ(jwk->getUsage(), moJwk->getUsage());
EXPECT_EQ(jwk->getKeyOps(), moJwk->getKeyOps());
shared_ptr<ByteArray> moEncode = moJwk->toMslEncoding(encoder, ENCODER_FORMAT);
EXPECT_TRUE(moEncode);
EXPECT_EQ(*encode, *moEncode);
}
TEST_F(JsonWebKeyTest, octKeyOpsCtor)
{
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(ENCRYPT_DECRYPT, JsonWebKey::Algorithm::A128CBC, EXTRACTABLE, KEY_ID, SECRET_KEY);
EXPECT_EQ(EXTRACTABLE, jwk->isExtractable());
EXPECT_EQ(JsonWebKey::Algorithm::A128CBC, jwk->getAlgorithm());
EXPECT_EQ(KEY_ID, *jwk->getId());
EXPECT_FALSE(jwk->getRsaKeyPair());
EXPECT_EQ(SECRET_KEY->getEncoded(), jwk->getSecretKey()->getEncoded());
EXPECT_EQ(JsonWebKey::Type::oct, jwk->getType());
EXPECT_EQ(JsonWebKey::Usage::invalid, jwk->getUsage());
EXPECT_EQ(ENCRYPT_DECRYPT, jwk->getKeyOps());
shared_ptr<ByteArray> encode = jwk->toMslEncoding(encoder, ENCODER_FORMAT);
EXPECT_TRUE(encode);
shared_ptr<JsonWebKey> moJwk = make_shared<JsonWebKey>(encoder->parseObject(encode));
EXPECT_EQ(jwk->isExtractable(), moJwk->isExtractable());
EXPECT_EQ(jwk->getAlgorithm(), moJwk->getAlgorithm());
EXPECT_EQ(*jwk->getId(), *moJwk->getId());
EXPECT_FALSE(moJwk->getRsaKeyPair());
EXPECT_EQ(*jwk->getSecretKey()->getEncoded(), *moJwk->getSecretKey()->getEncoded());
EXPECT_EQ(jwk->getType(), moJwk->getType());
EXPECT_EQ(jwk->getUsage(), moJwk->getUsage());
EXPECT_EQ(jwk->getKeyOps(), moJwk->getKeyOps());
shared_ptr<ByteArray> moEncode = moJwk->toMslEncoding(encoder, ENCODER_FORMAT);
EXPECT_TRUE(moEncode);
EXPECT_EQ(*encode, *moEncode);
}
TEST_F(JsonWebKeyTest, octUsageJson)
{
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(JsonWebKey::Usage::wrap, JsonWebKey::Algorithm::A128KW, EXTRACTABLE, KEY_ID, SECRET_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
EXPECT_EQ(EXTRACTABLE, mo->optBoolean(KEY_EXTRACTABLE));
EXPECT_EQ(JsonWebKey::Algorithm::A128KW.name(), mo->getString(KEY_ALGORITHM));
EXPECT_EQ(KEY_ID, mo->getString(KEY_KEY_ID));
EXPECT_EQ(JsonWebKey::Type::oct.name(), mo->getString(KEY_TYPE));
EXPECT_EQ(JsonWebKey::Usage::wrap.name(), mo->getString(KEY_USAGE));
EXPECT_FALSE(mo->has(KEY_KEY_OPS));
EXPECT_FALSE(mo->has(KEY_MODULUS));
EXPECT_FALSE(mo->has(KEY_PUBLIC_EXPONENT));
EXPECT_FALSE(mo->has(KEY_PRIVATE_EXPONENT));
shared_ptr<string> key = MslEncoderUtils::b64urlEncode(SECRET_KEY->getEncoded());
EXPECT_EQ(*key, mo->getString(KEY_KEY));
}
TEST_F(JsonWebKeyTest, octKeyOpsJson)
{
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(WRAP_UNWRAP, JsonWebKey::Algorithm::A128KW, EXTRACTABLE, KEY_ID, SECRET_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
EXPECT_EQ(EXTRACTABLE, mo->optBoolean(KEY_EXTRACTABLE));
EXPECT_EQ(JsonWebKey::Algorithm::A128KW.name(), mo->getString(KEY_ALGORITHM));
EXPECT_EQ(KEY_ID, mo->getString(KEY_KEY_ID));
EXPECT_EQ(JsonWebKey::Type::oct.name(), mo->getString(KEY_TYPE));
EXPECT_FALSE(mo->has(KEY_USAGE));
EXPECT_EQ(MA_WRAP_UNWRAP, mo->getMslArray(KEY_KEY_OPS));
EXPECT_FALSE(mo->has(KEY_MODULUS));
EXPECT_FALSE(mo->has(KEY_PUBLIC_EXPONENT));
EXPECT_FALSE(mo->has(KEY_PRIVATE_EXPONENT));
shared_ptr<string> key = MslEncoderUtils::b64urlEncode(SECRET_KEY->getEncoded());
EXPECT_EQ(*key, mo->getString(KEY_KEY));
}
TEST_F(JsonWebKeyTest, octNullCtor)
{
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", SECRET_KEY);
EXPECT_FALSE(jwk->isExtractable());
EXPECT_EQ(JsonWebKey::Algorithm::INVALID, jwk->getAlgorithm());
EXPECT_EQ("", *jwk->getId());
EXPECT_FALSE(jwk->getRsaKeyPair());
EXPECT_EQ(SECRET_KEY->getEncoded(), jwk->getSecretKey()->getEncoded());
EXPECT_EQ(JsonWebKey::Type::oct, jwk->getType());
EXPECT_EQ(NULL_USAGE, jwk->getUsage());
EXPECT_EQ(0u, jwk->getKeyOps().size());
shared_ptr<ByteArray> encode = jwk->toMslEncoding(encoder, ENCODER_FORMAT);
EXPECT_TRUE(encode);
shared_ptr<JsonWebKey> moJwk = make_shared<JsonWebKey>(encoder->parseObject(encode));
EXPECT_EQ(jwk->isExtractable(), moJwk->isExtractable());
EXPECT_EQ(jwk->getAlgorithm(), moJwk->getAlgorithm());
EXPECT_EQ(*jwk->getId(), *moJwk->getId());
EXPECT_FALSE(moJwk->getRsaKeyPair());
EXPECT_EQ(*jwk->getSecretKey(SECRET_KEY->getAlgorithm())->getEncoded(), *moJwk->getSecretKey(SECRET_KEY->getAlgorithm())->getEncoded());
EXPECT_EQ(jwk->getType(), moJwk->getType());
EXPECT_EQ(jwk->getUsage(), moJwk->getUsage());
EXPECT_EQ(jwk->getKeyOps(), moJwk->getKeyOps());
shared_ptr<ByteArray> moEncode = moJwk->toMslEncoding(encoder, ENCODER_FORMAT);
EXPECT_TRUE(moEncode);
EXPECT_EQ(*encode, *moEncode);
}
TEST_F(JsonWebKeyTest, octNullJson)
{
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", SECRET_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
EXPECT_FALSE(mo->getBoolean(KEY_EXTRACTABLE));
EXPECT_FALSE(mo->has(KEY_ALGORITHM));
EXPECT_EQ("", *jwk->getId());
EXPECT_EQ(JsonWebKey::Type::oct.name(), mo->getString(KEY_TYPE));
EXPECT_EQ(NULL_USAGE, jwk->getUsage());
EXPECT_EQ(0u, jwk->getKeyOps().size());
EXPECT_FALSE(mo->has(KEY_MODULUS));
EXPECT_FALSE(mo->has(KEY_PUBLIC_EXPONENT));
EXPECT_FALSE(mo->has(KEY_PRIVATE_EXPONENT));
shared_ptr<string> key = MslEncoderUtils::b64urlEncode(SECRET_KEY->getEncoded());
EXPECT_EQ(*key, mo->getString(KEY_KEY));
}
TEST_F(JsonWebKeyTest, usageOnly)
{
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", SECRET_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
mo->put(KEY_USAGE, JsonWebKey::Usage::enc.name());
shared_ptr<JsonWebKey> moJwk = make_shared<JsonWebKey>(mo);
EXPECT_EQ(JsonWebKey::Usage::enc, moJwk->getUsage());
EXPECT_EQ(0u, moJwk->getKeyOps().size());
}
TEST_F(JsonWebKeyTest, keyOpsOnly)
{
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", SECRET_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
mo->put(KEY_KEY_OPS, MA_ENCRYPT_DECRYPT);
shared_ptr<JsonWebKey> moJwk = make_shared<JsonWebKey>(mo);
EXPECT_EQ(NULL_USAGE, moJwk->getUsage());
set<JsonWebKey::KeyOp> keyOps;
keyOps.insert(JsonWebKey::KeyOp::encrypt);
keyOps.insert(JsonWebKey::KeyOp::decrypt);
EXPECT_EQ(keyOps, moJwk->getKeyOps());
}
TEST_F(JsonWebKeyTest, octCtorMismatchedAlgo)
{
//@Test(expected = MslInternalException.class)
EXPECT_THROW(JsonWebKey(NULL_USAGE, JsonWebKey::Algorithm::RSA1_5, false, "", SECRET_KEY), MslInternalException);
}
TEST_F(JsonWebKeyTest, missingType)
{
// thrown.expect(MslEncodingException.class);
// thrown.expectMslError(MslError.MSL_PARSE_ERROR);
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", SECRET_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
mo->remove(KEY_TYPE);
try {
new JsonWebKey(mo);
ADD_FAILURE() << "Should have thrown";
}
catch (const MslEncodingException& e) {
EXPECT_EQ(MslError::MSL_PARSE_ERROR, e.getError());
}
}
TEST_F(JsonWebKeyTest, invalidType)
{
// thrown.expect(MslCryptoException.class);
// thrown.expectMslError(MslError.UNIDENTIFIED_JWK_TYPE);
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", SECRET_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
mo->put<string>(KEY_TYPE, "x");
try {
new JsonWebKey(mo);
ADD_FAILURE() << "Should have thrown";
}
catch (const MslCryptoException& e) {
EXPECT_EQ(MslError::UNIDENTIFIED_JWK_TYPE, e.getError());
}
}
TEST_F(JsonWebKeyTest, invalidUsage)
{
// thrown.expect(MslCryptoException.class);
// thrown.expectMslError(MslError.UNIDENTIFIED_JWK_USAGE);
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", SECRET_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
mo->put<string>(KEY_USAGE, "x");
try {
new JsonWebKey(mo);
ADD_FAILURE() << "Should have thrown";
}
catch (const MslCryptoException& e) {
EXPECT_EQ(MslError::UNIDENTIFIED_JWK_USAGE, e.getError());
}
}
TEST_F(JsonWebKeyTest, invalidKeyOp)
{
// thrown.expect(MslCryptoException.class);
// thrown.expectMslError(MslError.UNIDENTIFIED_JWK_KEYOP);
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", SECRET_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
shared_ptr<MslArray> keyOps = make_shared<MslArray>();
keyOps->put(-1, JsonWebKey::KeyOp::encrypt.name());
keyOps->put<string>(-1, "x");
keyOps->put(-1, JsonWebKey::KeyOp::decrypt.name());
mo->put(KEY_KEY_OPS, keyOps);
try {
new JsonWebKey(mo);
ADD_FAILURE() << "Should have thrown";
}
catch (const MslCryptoException& e) {
EXPECT_EQ(MslError::UNIDENTIFIED_JWK_KEYOP, e.getError());
}
}
TEST_F(JsonWebKeyTest, invalidAlgorithm)
{
// thrown.expect(MslCryptoException.class);
// thrown.expectMslError(MslError.UNIDENTIFIED_JWK_ALGORITHM);
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", SECRET_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
mo->put<string>(KEY_ALGORITHM, "x");
try {
new JsonWebKey(mo);
ADD_FAILURE() << "Should have thrown";
}
catch (const MslCryptoException& e) {
EXPECT_EQ(MslError::UNIDENTIFIED_JWK_ALGORITHM, e.getError());
}
}
TEST_F(JsonWebKeyTest, missingExtractable)
{
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", SECRET_KEY);
shared_ptr<ByteArray> encode = jwk->toMslEncoding(encoder, ENCODER_FORMAT);
shared_ptr<MslObject> mo = encoder->parseObject(encode);
EXPECT_FALSE(mo->remove(KEY_EXTRACTABLE).isNull());
shared_ptr<JsonWebKey> moJwk = make_shared<JsonWebKey>(mo);
EXPECT_EQ(jwk->isExtractable(), moJwk->isExtractable());
EXPECT_EQ(jwk->getAlgorithm(), moJwk->getAlgorithm());
EXPECT_EQ(*jwk->getId(), *moJwk->getId());
EXPECT_FALSE(moJwk->getRsaKeyPair());
EXPECT_EQ(*jwk->getSecretKey(SECRET_KEY->getAlgorithm())->getEncoded(), *moJwk->getSecretKey(SECRET_KEY->getAlgorithm())->getEncoded());
EXPECT_EQ(jwk->getType(), moJwk->getType());
EXPECT_EQ(jwk->getUsage(), moJwk->getUsage());
shared_ptr<ByteArray> moEncode = moJwk->toMslEncoding(encoder, ENCODER_FORMAT);
EXPECT_TRUE(moEncode);
EXPECT_EQ(*encode, *moEncode);
}
TEST_F(JsonWebKeyTest, invalidExtractable)
{
// thrown.expect(MslEncodingException.class);
// thrown.expectMslError(MslError.MSL_PARSE_ERROR);
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", SECRET_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
mo->put<string>(KEY_EXTRACTABLE, "x");
try {
new JsonWebKey(mo);
ADD_FAILURE() << "Should have thrown";
}
catch (const MslEncodingException& e) {
EXPECT_EQ(MslError::MSL_PARSE_ERROR, e.getError());
}
}
TEST_F(JsonWebKeyTest, missingKey)
{
// thrown.expect(MslEncodingException.class);
// thrown.expectMslError(MslError.MSL_PARSE_ERROR);
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", SECRET_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
mo->remove(KEY_KEY);
try {
new JsonWebKey(mo);
ADD_FAILURE() << "Should have thrown";
}
catch (const MslEncodingException& e) {
EXPECT_EQ(MslError::MSL_PARSE_ERROR, e.getError());
}
}
TEST_F(JsonWebKeyTest, emptyKey)
{
// thrown.expect(MslCryptoException.class);
// thrown.expectMslError(MslError.INVALID_JWK_KEYDATA);
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", SECRET_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
mo->put<string>(KEY_KEY, "");
try {
new JsonWebKey(mo);
ADD_FAILURE() << "Should have thrown";
}
catch (const MslCryptoException& e) {
EXPECT_EQ(MslError::INVALID_JWK_KEYDATA, e.getError());
}
}
TEST_F(JsonWebKeyTest, missingModulus)
{
// thrown.expect(MslEncodingException.class);
// thrown.expectMslError(MslError.MSL_PARSE_ERROR);
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", PUBLIC_KEY, PRIVATE_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
mo->remove(KEY_MODULUS);
try {
new JsonWebKey(mo);
ADD_FAILURE() << "Should have thrown";
}
catch (const MslEncodingException& e) {
EXPECT_EQ(MslError::MSL_PARSE_ERROR, e.getError());
}
}
TEST_F(JsonWebKeyTest, emptyModulus)
{
// thrown.expect(MslCryptoException.class);
// thrown.expectMslError(MslError.INVALID_JWK_KEYDATA);
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", PUBLIC_KEY, PRIVATE_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
mo->put<string>(KEY_MODULUS, "");
try {
new JsonWebKey(mo);
ADD_FAILURE() << "Should have thrown";
}
catch (const MslCryptoException& e) {
EXPECT_EQ(MslError::INVALID_JWK_KEYDATA, e.getError());
}
}
TEST_F(JsonWebKeyTest, missingExponents)
{
// thrown.expect(MslEncodingException.class);
// thrown.expectMslError(MslError.MSL_PARSE_ERROR);
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", PUBLIC_KEY, PRIVATE_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
mo->remove(KEY_PUBLIC_EXPONENT);
mo->remove(KEY_PRIVATE_EXPONENT);
try {
new JsonWebKey(mo);
ADD_FAILURE() << "Should have thrown";
}
catch (const MslEncodingException& e) {
EXPECT_EQ(MslError::MSL_PARSE_ERROR, e.getError());
}
}
TEST_F(JsonWebKeyTest, emptyPublicExponent)
{
// thrown.expect(MslCryptoException.class);
// thrown.expectMslError(MslError.INVALID_JWK_KEYDATA);
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", PUBLIC_KEY, PRIVATE_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
mo->put<string>(KEY_PUBLIC_EXPONENT, "");
try {
new JsonWebKey(mo);
ADD_FAILURE() << "Should have thrown";
}
catch (const MslCryptoException& e) {
EXPECT_EQ(MslError::INVALID_JWK_KEYDATA, e.getError());
}
}
TEST_F(JsonWebKeyTest, invalidPublicExpontent)
{
// thrown.expect(MslCryptoException.class);
// thrown.expectMslError(MslError.INVALID_JWK_KEYDATA);
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", PUBLIC_KEY, PRIVATE_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
mo->put<string>(KEY_PUBLIC_EXPONENT, "x");
try {
new JsonWebKey(mo);
ADD_FAILURE() << "Should have thrown";
}
catch (const MslCryptoException& e) {
EXPECT_EQ(MslError::INVALID_JWK_KEYDATA, e.getError());
}
}
TEST_F(JsonWebKeyTest, emptyPrivateExponent)
{
// thrown.expect(MslCryptoException.class);
// thrown.expectMslError(MslError.INVALID_JWK_KEYDATA);
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", PUBLIC_KEY, PRIVATE_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
mo->put<string>(KEY_PRIVATE_EXPONENT, "");
try {
new JsonWebKey(mo);
ADD_FAILURE() << "Should have thrown";
}
catch (const MslCryptoException& e) {
EXPECT_EQ(MslError::INVALID_JWK_KEYDATA, e.getError());
}
}
TEST_F(JsonWebKeyTest, invalidPrivateExponent)
{
// thrown.expect(MslCryptoException.class);
// thrown.expectMslError(MslError.INVALID_JWK_KEYDATA);
shared_ptr<JsonWebKey> jwk = make_shared<JsonWebKey>(NULL_USAGE, JsonWebKey::Algorithm::INVALID, false, "", PUBLIC_KEY, PRIVATE_KEY);
shared_ptr<MslObject> mo = MslTestUtils::toMslObject(encoder, jwk);
mo->put<string>(KEY_PRIVATE_EXPONENT, "x");
try {
new JsonWebKey(mo);
ADD_FAILURE() << "Should have thrown";
}
catch (const MslCryptoException& e) {
EXPECT_EQ(MslError::INVALID_JWK_KEYDATA, e.getError());
}
}
}}} // namespace netflix::msl::crypto
|
182549fc2fdc56010688efb49af0426a1a675852 | 94312e2cb2d8a70d21871315c1e0d65f7d71faf5 | /labs/lab08/lab08_functions.cpp | b645f2e8286b35692f86e74ae8ec6d4936c98665 | [] | no_license | trainesb/CSE232-CPP | 9ade69f24bdc4bec355044f9aa10fe845ee63266 | 93d621ccca50920fffab9670b0b463aed19008e5 | refs/heads/master | 2020-07-21T15:30:29.014786 | 2019-09-07T03:22:13 | 2019-09-07T03:22:13 | 206,909,396 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 889 | cpp | lab08_functions.cpp | #include<string>
using std::string;
#include "lab08_functions.h"
/*
input is a positive (1 or greater) integer
returns the next collatz number
if number is 0 or less, throws range_error;
*/
long collatz_next(long n){
int next;
if(n%2==0){
next = n/2;
}
else{
next = (3*n)+1;
}
if(n<=0){
throw 0;
}
return next;
}
/*
input is a Collatz pair (pair<long, vector<long > >)
output is a string of the format
number: sequence (comma separated) ending in 1
no trailing comma
*/
string Collatz_to_string(const Collatz &p){
string k, v, s;
k=p.first;
v=p.second;
s=k+","+v;
return s;
}
/*
input is a collatz map (map<long, vector<long> >)and a long
if the number exists as a key in the map
returns the Collatz_to_string of that pair
otw returns an empty string
*/
string sequence_in_map_to_string(map<long, vector<long> > &m, long number){
}
|
288697b598eb8fe905da205dc471fe51825a46ed | ab6b28042e36ce34304c2d187279d199247994a6 | /src/buffer.hpp | 1fc7e8006d04df4004751cb02b62c5fcf00a53ef | [
"MIT"
] | permissive | asztal/eos | 7ed94d2eed70aec8049953af76cd96147d714ae1 | 2791e63f37c66f3a86b10a19183cf0f400cf8941 | refs/heads/master | 2021-01-24T06:38:00.917977 | 2015-06-14T13:31:42 | 2015-06-14T13:31:42 | 16,421,447 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,042 | hpp | buffer.hpp | #include "eos.hpp"
namespace Eos {
namespace Buffers {
bool Allocate(
SQLLEN length,
SQLPOINTER& buffer,
Handle<Object>& handle);
template<class T>
bool AllocatePrimitive(const T& value, SQLPOINTER& buffer, Handle<Object>& handle) {
if (!Allocate(sizeof(T), buffer, handle))
return false;
*reinterpret_cast<T*>(buffer) = value;
return true;
}
SQLLEN GetDesiredBufferLength(
SQLSMALLINT cType);
SQLLEN FillInputBuffer(
SQLSMALLINT cType,
Handle<Value> jsValue,
SQLPOINTER buffer, SQLLEN length);
bool AllocateBoundInputParameter(
SQLSMALLINT cType,
Handle<Value> jsValue,
SQLPOINTER& buffer, SQLLEN& length,
Handle<Object>& handle);
bool AllocateOutputBuffer(
SQLSMALLINT cType,
SQLPOINTER& buffer, SQLLEN& length,
Handle<Object>& handle);
}
} |
aef7ed4f2ceceb4e45c7166d8a5428510e9dc16c | 286bf5d8afa9692fdef36ae2171da90d418a0889 | /Broker.cpp | 4e1ee195ed66165d045e2341ca530243ca13d833 | [] | no_license | kanglicheng/CompetitiveProgramming | 6863702712e3c902f1e3b1344b9a17bf611e141d | 80a0fa8a5bf3793a1300ec15b3c4529e66b157cc | refs/heads/master | 2020-07-07T05:46:01.437467 | 2018-02-17T15:26:13 | 2018-02-17T15:26:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 809 | cpp | Broker.cpp | #define ll long long
#define pb push_back
#define N 400000
#define ms(a,b) memset(a, b, sizeof a)
#include<bits/stdc++.h>
using namespace std;
vector<int> adj[N];
ll a[N], p[N], par[N];
bool used[N];
int n, m;
bool kuhn(int x){
used[x] = 1;
for(auto v : adj[x]){
if(!par[v]){
par[v] = x;
return 1;
}
if(used[par[v]]) continue;
if(kuhn(par[v])){
par[v] = x;
return 1;
}
}
return 0;
}
void solve(){
cin >> n >> m;
for(int i = 1; i <= n; i++){
cin >> a[i] >> p[i];
}
for(int j = 1; j <= m; j++){
ll x, y; cin >> x >> y;
for(int i = 1; i <= n; i++){
if(x > a[i] && y <= p[i]){
adj[i].pb(n + 1 + j);
adj[n + 1 + j].pb(i);
}
}
}
ll ans = 0;
for(int i = 1; i <= n; i++){
ms(used, 0);
if(kuhn(i)) ans++;
}
cout << ans;
}
int main(){
solve();
return 0;
}
|
eed12ad2c1eb52f77697e2c46c1f9fb656481558 | 5db218901dc34c891b211d7db311f3669b86cd67 | /lib/Scoring/Process.cpp | a1bee9707b0536ed130d2134f556c6f82c331854 | [] | no_license | ibaiGilabert/AsiyaGPU | f9deaea6634c5359fecd4e64c61d3c6deb16e409 | c34128d1deb733937094d2955cd7334ffe8e1c69 | refs/heads/master | 2020-12-30T10:36:48.181868 | 2015-04-21T23:13:08 | 2015-04-21T23:13:08 | 20,775,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,533 | cpp | Process.cpp | #include "../include/Process.hpp"
#include "../include/TB_FORMAT.hpp"
#include "../include/TESTBED.hpp"
#include "../Config.hpp"
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <set>
#include <boost/filesystem.hpp>
#include <boost/algorithm/string.hpp>
string Process::exec(const char* cmd) {
FILE* pipe = popen(cmd, "r");
if (!pipe) return "ERROR";
char buffer[128];
string result = "";
while(!feof(pipe)) {
if(fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
pclose(pipe);
return result;
}
bool Process::end(string id) {
// check whether id job is already ended
bool ended = true;
string out = exec("qstat");
istringstream bufo(out);
int i = 0;
for (string token; getline(bufo, token, '\n'); ++i) {
string job_aux;
istringstream aux(token);
getline(aux, job_aux, ' ');
if (job_aux == id) ended = false;
/*if (atoi(job_aux.c_str()) > 0)
cout << "job_ID: " << atoi(job_aux.c_str()) << endl;*/
}
return ended;
}
void Process::get_s_time(string id, double &time) {
// get the ru_ru_wallclock of a <id> job
//string qacct = "/usr/local/sge/bin/linux-x64/qacct -j "+id;
string qacct = "qacct -j "+id;
//fprintf(stderr, "[Pr] to execute: |%s|\n", qacct.c_str());
string qacct_r = exec(qacct.c_str());
//fprintf(stderr, "[Pr]: qacct_r: |%s|\n", qacct_r.c_str());
if (qacct_r == "") get_s_time(id, time);
boost::algorithm::trim(qacct_r);
istringstream buf(qacct_r);
for (string token; getline(buf, token, '\n'); ) {
string ru_time;
istringstream sru(token);
getline(sru, ru_time, ' ');
//cout << "\tru_time: |" << ru_time << "|" << endl;
if (ru_time == "ru_wallclock") {
vector<string> strs;
boost::split(strs, token, boost::is_any_of("\t "));
time = atof(strs[1].c_str());
//return atof(strs[5].c_str()); (s_time)
}
}
}
double Process::get_time(string e_file) {
// get the total execution time from error file
string exe_cat = "cat " + e_file + " | grep TOTAL";
string time_out = exec(exe_cat.c_str());
vector<string> strs;
boost::split(strs, time_out, boost::is_any_of("\t "));
if (strs.size() == 0) { fprintf(stderr, "[ERROR] Could not parse total time of split execution <%s>\n", e_file.c_str()); exit(1); }
return atof(strs[strs.size()-1].c_str());
}
string Process::getJobID(string cmd) {
// get the id job from qsub's return value
boost::algorithm::trim(cmd);
//printf("return qsub: |%s|\n", job.c_str());
vector<string> v;
istringstream buf(cmd);
for (string token; getline(buf, token, ' '); ) v.push_back(token);
/*for (int j = 0; j < v.size(); ++j) cout << "v[" << j << "]: " << v[j] << "\t";
cout << endl;*/
return v[2];
}
string Process::run_job(string run_file, string metric) {
/*char qsub[] = "/usr/local/sge/bin/linux-x64/qsub ";
strcat(qsub, run_file);
strcat(qsub, " ");
strcat(qsub, metric);*/
//string qsub = "/usr/local/sge/bin/linux-x64/qsub -q \\!gpu " + run_file + " " + metric;
string qsub = "qsub -q \\!gpu " + run_file + " " + metric;
string qsub_r = exec(qsub.c_str());
return getJobID(qsub_r);
}
string Process::run_job_dep(string run_file, string metric, string dep) {
/*char qsub[] = "/usr/local/sge/bin/linux-x64/qsub -hold_jid ";
strcat(qsub, dep);
strcat(qsub, " ");
strcat(qsub, run_file);
strcat(qsub, " ");
strcat(qsub, metric);*/
//string qsub = "/usr/local/sge/bin/linux-x64/qsub -q \\!gpu -hold_jid " + dep + " " + run_file + " " + metric;
string qsub = "qsub -q \\!gpu -hold_jid " + dep + " " + run_file + " " + metric;
string qsub_r = exec(qsub.c_str());
return getJobID(qsub_r);
}
string Process::make_config_file(string TGT, string REF, string metric_set, int thread) {
// build config file for one thread
// return: config_file name
//char buffer[100];
//sprintf(buffer, "%s.%.3d.%s", TESTBED::Hsystems[SYS].c_str(), thread, Common::TXTEXT.c_str()); // get the system split
string source_txt = TB_FORMAT::get_split(TESTBED::src, Common::TXTEXT, thread);
string reference_txt = TB_FORMAT::get_split(TESTBED::Hrefs[REF], Common::TXTEXT, thread);
string syst_txt = TB_FORMAT::get_split(TESTBED::Hsystems[TGT], Common::TXTEXT, thread);
string source_tgt_txt = TESTBED::replace_extension(source_txt, TGT)+"."+Common::TXTEXT;
string reference_tgt_txt = TESTBED::replace_extension(reference_txt, TGT)+"."+Common::TXTEXT;
// idx
string source_idx = TB_FORMAT::get_split(TESTBED::src, Common::IDXEXT, thread);
string reference_idx = TB_FORMAT::get_split(TESTBED::Hrefs[REF], Common::IDXEXT, thread);
string source_tgt_idx = TESTBED::replace_extension(source_idx, TGT)+"."+Common::IDXEXT;
string reference_tgt_idx = TESTBED::replace_extension(reference_idx, TGT)+"."+Common::IDXEXT;
// copy txt files
string cmd, err;
cmd = "cp "+reference_txt+" "+reference_tgt_txt; err = "[ERROR] could not copy <"+reference_txt+"> into <"+reference_tgt_txt+">";
Common::execute_or_die(cmd, err);
cmd = "cp "+source_txt+" "+source_tgt_txt; err = "[ERROR] could not copy <"+source_txt+"> into <"+source_tgt_txt+">";
Common::execute_or_die(cmd, err);
// copy idx files
cmd = "cp "+reference_idx+" "+reference_tgt_idx; err = "[ERROR] could not copy <"+reference_idx+"> into <"+reference_tgt_idx+">";
Common::execute_or_die(cmd, err);
cmd = "cp "+source_idx+" "+source_tgt_idx; err = "[ERROR] could not copy <"+source_idx+"> into <"+source_tgt_idx+">";
Common::execute_or_die(cmd, err);
char config_name[150];
sprintf(config_name, "Asiya_%s_%s_%s_%.3d.config", metric_set.c_str(), TGT.c_str(), REF.c_str(), thread);
ofstream config_file(config_name);
if (config_file) {
config_file << "input=raw" << endl << endl;
config_file << "srclang=" << Config::SRCLANG << endl;
config_file << "srccase=" << Config::SRCCASE << endl;
config_file << "trglang=" << Config::LANG << endl;
config_file << "trgcase=" << Config::CASE << endl << endl;;
config_file << "src=" << source_tgt_txt << endl;
config_file << "ref=" << reference_tgt_txt << endl;
config_file << "sys=" << syst_txt << endl << endl;
config_file << "metrics_" << metric_set << "=";
for(set<string>::const_iterator it = Config::metrics.begin(); it != Config::metrics.end(); ++it)
config_file << *it << " ";
config_file << endl << endl;
config_file.close();
} else { fprintf(stderr, "[ERROR] Could not build config file <%s>\n", config_name); exit(1); }
return string(config_name);
}
string Process::make_run_file(string config_file, string TGT, string REF, int thread, string metric) {
// build run script file
// return: script file name
char run_buffer[150], report_buffer[150];
sprintf(run_buffer, "run_%s_%s_%s_%.3d.sh", metric.c_str(), TGT.c_str(), REF.c_str(), thread); // get the system split
sprintf(report_buffer, "run_%s_%s_%s_%.3d.report", metric.c_str(), TGT.c_str(), REF.c_str(), thread); // get the system split
ofstream run_file(run_buffer);
if (run_file) {
run_file << "#$ -S /bin/bash" << endl;
run_file << "#$ -V" << endl;
run_file << "#$ -cwd" << endl;
//run_file << "#$ -m eas" << endl;
//run_file << "#$ -M gilabert@cs.upc.edu" << endl;
run_file << "#$ -l h_vmem=10G" << endl; //LA MEMORIA QUE CADA METRICA DEMANI
//run_file << endl << "DATAPATH=" << Common::DATA_PATH << endl;
run_file << endl;
//run_file << "#$ -q short@node115,short@node116,short@node117,short@node315,short@node316" << endl << endl;
//run_file << endl << ". /home/soft/asiya/ASIYA12.04.PATH" << endl;
stringstream s_cmd;
s_cmd << "./Asiya " << config_file << " -serialize " << (thread-1)*TB_FORMAT::chunk + 1 << " -time -g seg -eval single -metric_set metrics_" << metric << " -data_path=" << Common::DATA_PATH << " > " << string(report_buffer);
string cmd = s_cmd.str();
if (Config::verbose) fprintf(stderr, "[EXEC] %s\n", cmd.c_str());
run_file << "echo " << cmd << endl;
run_file << cmd << endl;
run_file.close();
} else { fprintf(stderr, "[ERROR] Could not build config file <%s>\n", run_buffer); exit(1); }
return string(run_buffer);
}
|
826a9163c1b4acd031c3546560920ee7af8e0796 | aeb9add98587935f8b3cb52d8597c9349c47bcdf | /untitled1/myqtosgwidget.cpp | 93c005221d4f811f0c655adadc2831561984a0ce | [] | no_license | jnmaloney/MATH7232-Past-Exam-Solutions | 5bd118ff0e2871b04581864441088ddfc901d890 | 72d91a111cf2c9163f38fb3eb186fde81e55b0d2 | refs/heads/master | 2020-06-01T22:48:39.719325 | 2017-11-04T11:36:03 | 2017-11-04T11:36:03 | 94,085,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 64 | cpp | myqtosgwidget.cpp | #include "myqtosgwidget.h"
MyQtOSGWidget::MyQtOSGWidget()
{
}
|
fdaeadaad1c3aaa22a475a971c5fd726cf9c547a | 81b131f4963934e9a7e6a6f960430924f69f3005 | /c++Project/c++Project/interface.cpp | c16ac13750b0ba48caaa6597340c533dc4d50d87 | [] | no_license | cccv203/simulink-using-svm-rf-by-dll-c- | a099ee238dea4704227391d3e47d387a980ef27b | 7b66487fae5494bcb8b266494b3774ea4684623c | refs/heads/master | 2020-04-06T10:26:58.308243 | 2018-11-14T05:10:39 | 2018-11-14T05:10:39 | 157,380,651 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,337 | cpp | interface.cpp | #include "stdafx.h"
////
//#include "interface.h"
//#include "getData.h"
//#include "model.h"
//#include "svmModel.h"
//#include "randomForest.h"
//#include <iostream>
////
//
//
//static vector<Ptr<ml::SVM>> svmVec;
//static vector<Ptr<ml::RTrees>> randomForestVec;
//
//void train_process(Model* model, string dirPath) {
// model->train(dirPath);
// delete model;
//}
//
//
//
//void predict_process(INPUTDATA& data, int dataLong, char* initFile) {
// ifstream init(initFile);
// vector<float>nVec(2 * dataLong, 0.0);
// for (int i = 0; i < dataLong * 2; ++i)
// init >> nVec[i];
// init.close();
// data.d1 = (data.d1 - nVec[0]) / nVec[0 + dataLong];
// data.d2 = (data.d2 - nVec[1]) / nVec[1 + dataLong];
// data.d3 = (data.d3 - nVec[2]) / nVec[2 + dataLong];
// data.d4 = (data.d4 - nVec[3]) / nVec[3 + dataLong];
// data.d5 = (data.d5 - nVec[4]) / nVec[4 + dataLong];
//
//}
//
//int train(char* dirPath, char* logPath, double* dataRange, int ndR, double* labelRange, int nlR, double* parameters, int nP) {
// getData data(dirPath, logPath, dataRange, ndR, labelRange, nlR, parameters, nP);
// if (data.dataPath.size() == 0)
// return 1;
// data.mainProcess(true, true);
// if (parameters[0] == 0) {
// Model* model = new RandomForestModel(data.floatData, data.dataIndex.size(), data.labelIndex.size(), data.getLogPath());
// train_process(model, dirPath);
// }
// else if (parameters[0] == 1) {
// Model* model = new SvmModel(data.floatData, data.dataIndex.size(), data.labelIndex.size(), data.getLogPath());
// train_process(model, dirPath);
// }
// return 0;
//}
//
//void loadModel(char* modelPath, int whichModel) {
// vector<cv::String>temp;
// glob(modelPath, temp, false);
// for (int i = 0; i < temp.size(); ++i) {
// if (temp[i].find_last_of(".xml") == (temp[i].size() - 1)) {
// if (whichModel == 1 && temp[i].find("SVM") != -1) {
// Ptr<ml::SVM> svmTemp = ml::SVM::create();
// svmTemp = ml::SVM::load(temp[i]);
// svmVec.push_back(svmTemp);
// }
// else if (whichModel == 0 && temp[i].find("RandomForest") != -1) {
// Ptr<ml::RTrees> randomForestTemp = ml::RTrees::create();
// randomForestTemp = ml::RTrees::load(temp[i]);
// randomForestVec.push_back(randomForestTemp);
// }
// }
// }
//}
//
//void predict(INPUTDATA data, int dataLong, char* initPath, OUTPUTDATA& output) {
// //ofstream file;
// //file << data.d1;
// predict_process(data, dataLong, initPath);
//
// //file.open("E:\\solve\\frameWork\\frameWork\\data\\12.txt", ios::app);
// Mat sample = Mat::zeros(1, dataLong, CV_32FC1);
//
// sample.at<float>(0, 0) = data.d1;
// sample.at<float>(0, 1) = data.d2;
// sample.at<float>(0, 2) = data.d3;
// sample.at<float>(0, 3) = data.d4;
// sample.at<float>(0, 4) = data.d5;
//
// if (svmVec.size() != 0) {
// output.t1 = svmVec[0]->predict(sample);
// output.t2 = svmVec[1]->predict(sample);
// output.t3 = svmVec[2]->predict(sample);
// }
// else {
// output.t1 = randomForestVec[0]->predict(sample);
// output.t2 = randomForestVec[1]->predict(sample);
// output.t3 = randomForestVec[2]->predict(sample);
// }
//
// //for (int i = 0; i < svmVec.size(); ++i) {
// // file << svmVec[i]->predict(sample) << '\t';
// //}
// //file<<sample<<endl;
// //file.close();
//
//} |
938a05f88b32cf8d68760883d91c536999ec3f23 | 9f05d15a3f6d98711416d42e1ac3b385d9caa03a | /sem3/da/labs/4/var_3_1.cpp | 86c14f72ac9ac239f73a9f817575b2b3aabda665 | [] | no_license | dtbinh/MAI | abbad3bef790ea231a1dc36233851a080ea53225 | a5c0b7ce0be0f5b5a1d5f193e228c685977a2f93 | refs/heads/master | 2020-06-16T06:45:58.595779 | 2016-08-21T15:37:10 | 2016-08-21T15:37:10 | 75,237,279 | 1 | 0 | null | 2016-11-30T23:45:58 | 2016-11-30T23:45:58 | null | UTF-8 | C++ | false | false | 4,308 | cpp | var_3_1.cpp | #include <exception>
#include <new>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "vector.h"
#include "queue.h"
struct TPos
{
int row;
int col;
};
int ToLower(int ch);
void PreBmBc(char* x, int m, int* bmBc, int size);
void Suffixes(char* x, int m, int* suff);
void PreBmGs(char* x, int m, int* bmGs, int* suff);
void AG(const TVector<char>& pat);
int Max(int a, int b);
int main()
{
int ch;
TVector<char> pattern;
VectorInit<char>(pattern);
while ((ch = getchar()) != '\n')
{
ch = ToLower(ch);
if (ch == ' ')
{
ch = '{';
}
VectorPushBack<char>(pattern, ch);
}
AG(pattern);
VectorDestroy<char>(pattern);
return 0;
}
int ToLower(int ch)
{
return ch >= 'A' && ch <= 'Z' ? ch + 'a' - 'A' : ch;
}
void PreBmBc(char* x, int m, int* bmBc, int size)
{
for (int i = 0; i < size; ++i)
{
bmBc[i] = m;
}
for (int i = 0; i < m - 1; ++i)
{
bmBc[x[i] - 'a'] = m - i - 1;
}
}
void Suffixes(char* x, int m, int* suff)
{
int f = 0;
int g;
int i;
suff[m - 1] = m;
g = m - 1;
for (i = m - 2; i >= 0; --i)
{
if (i > g && suff[i + m - 1 - f] < i - g)
{
suff[i] = suff[i + m - 1 - f];
}
else
{
if (i < g)
{
g = i;
}
f = i;
while (g >= 0 && x[g] == x[g + m - 1 - f])
{
--g;
}
suff[i] = f - g;
}
}
}
void PreBmGs(char* x, int m, int* bmGs, int* suff)
{
int i, j;
Suffixes(x, m, suff);
for (i = 0; i < m; ++i)
{
bmGs[i] = m;
}
j = 0;
for (i = m - 1; i >= -1; --i)
{
if (i == -1 || suff[i] == i + 1)
{
for (; j < m - 1 - i; ++j)
{
if (bmGs[j] == m)
{
bmGs[j] = m - 1 - i;
}
}
}
}
for (i = 0; i < m - 1; ++i)
{
bmGs[m - 1 - suff[i]] = m - 1 - i;
}
}
void AG(const TVector<char>& pat)
{
const int A_SIZE = '{' - 'a' + 1;
int i;
int k;
int s;
int shift;
int ch;
int* bmBc = NULL;
int* bmGs = NULL;
int* skip = NULL;
int* suff = NULL;
TQueue<char> text;
TQueue<TPos> pos;
TPos tmpPos;
try
{
bmBc = new int[A_SIZE];
bmGs = new int[pat.size];
skip = new int[pat.size];
suff = new int[pat.size];
}
catch (const std::bad_alloc& e)
{
printf("ERROR: No memory\n");
std::exit(0);
}
tmpPos.row = 1;
tmpPos.col = 1;
QueueInit<char>(text, pat.size);
QueueInit<TPos>(pos, pat.size);
PreBmGs(pat.begin, pat.size, bmGs, suff);
PreBmBc(pat.begin, pat.size, bmBc, A_SIZE);
memset(skip, 0, pat.size * sizeof(int));
bool isWordFound = false;
while (true)
{
while (text.size < pat.size && (ch = getchar()) != EOF)
{
if (ch == ' ' || ch == '\t')
{
if (isWordFound)
{
QueuePush<char>(text, '{');
isWordFound = false;
++tmpPos.col;
}
}
else if (ch == '\n')
{
if (isWordFound)
{
QueuePush<char>(text, '{');
isWordFound = false;
}
++tmpPos.row;
tmpPos.col = 1;
}
else
{
if (!isWordFound)
{
QueuePush<TPos>(pos, tmpPos);
}
QueuePush<char>(text, ToLower(ch));
isWordFound = true;
}
}
if (text.size < pat.size)
{
break;
}
i = pat.size - 1;
while (i >= 0)
{
k = skip[i];
s = suff[i];
if (k > 0)
{
if (k > s)
{
if (i + 1 == s)
{
i = -1;
}
else
{
i -= s;
}
break;
}
else
{
i -= k;
if (k < s)
{
break;
}
}
}
else
{
if (pat.begin[i] == text.begin[(i + text.offset) % pat.size])
{
--i;
}
else
{
break;
}
}
}
if (i < 0)
{
TPos wp = pos.begin[pos.offset];
printf("%d, %d\n", wp.row, wp.col);
skip[pat.size - 1] = pat.size;
shift = bmGs[0];
}
else
{
int ind = text.begin[(i + text.offset) % pat.size] - 'a';
skip[pat.size - 1] = pat.size - 1 - i;
shift = Max(bmGs[i], bmBc[ind] - pat.size + 1 + i);
}
int offset = text.offset;
for (size_t z = 0; z < shift; ++z)
{
QueuePop<char>(text);
if (text.begin[(offset + z) % pat.size] == '{')
{
QueuePop<TPos>(pos);
}
}
memcpy(skip, skip + shift, (pat.size - shift) * sizeof(int));
memset(skip + pat.size - shift, 0, shift * sizeof(int));
}
QueueDestroy<char>(text);
QueueDestroy<TPos>(pos);
delete[] bmBc;
delete[] bmGs;
delete[] skip;
delete[] suff;
}
int Max(int a, int b)
{
return a > b ? a : b;
}
|
f11dfe14eef565e3a7b4c9479b1043806628e02c | 55fc1fbb64178cdf09255d2b2ab348d605188d7c | /MFilePlayer/MFilePlayer/MediaFileCtrl.h | 0248f52e434b536525a40772510f81157195fd9a | [] | no_license | noahliaoavlink/ms_src_1.2.8 | 679f86b39b958985df363ffe3a7071e2ff39717e | 96a5a0f20f2b2e6f72ce248682051e02668feb72 | refs/heads/master | 2021-01-16T16:16:41.972937 | 2020-07-20T03:31:56 | 2020-07-20T03:31:56 | 243,179,822 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 461 | h | MediaFileCtrl.h | #pragma once
#ifndef _MediaFileCtrl_H
#define _MediaFileCtrl_H
#include "FFMediaFileDll.h"
#include "..\\..\\Include\\SQList.h"
class MediaFileCtrl
{
SQList* m_pFFMediaFileList;
FFMediaFileDll* m_pCurSelObj;
public:
MediaFileCtrl();
~MediaFileCtrl();
void CloseAllFiles();
int SearchFileName(char* szFileName);
int Open(char* szFileName);
void Close();
FFMediaFileDll* GetCurSelObj();
int CreateNewObj();
void SetTarget(int iIndex);
};
#endif
|
748480eeb4967ed519e3c546d2552032a944bf75 | d680d37bc92ad510107ed74a7df3f0aae576259c | /order.cpp | 15569a1848472a19418063b9dc65b887737bde6c | [] | no_license | dleung25/C---Factory-Simulation | 8f404a3f2779aeba426043b8f020765d1e20ae50 | 1f01e32de9b4f4a0d036758c37ee307ab936b8d4 | refs/heads/master | 2021-01-09T06:24:16.276702 | 2017-02-05T09:08:05 | 2017-02-05T09:08:05 | 80,981,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,551 | cpp | order.cpp | //need to fix
#include "util.h"
#include "order.h"
using namespace std;
bool Order::validCustomerName(std::string name)
{
if (name.size() > 0 && isalpha(name[0]))
return true;
return false;
}
bool Order::validProductName(std::string name)
{
if (name.size() > 0 && isalpha(name[0]))
return true;
return false;
}
Order::Order(std::vector<std::string>& row){
if (row.size() < 3){
throw std::string("Expected 2 or more fields, found --> ") + to_string(row.size());
}
if (validCustomerName(row[0])){
customerName = row[0];
}
else{
throw std::string("Expected a customer name, found --> ") + row[0] + " <--";
}
if (validProductName(row[1])){
productName = row[1];
}
else{
throw std::string("Expected a product name, found --> ") + row[1] + " <--";
}
for (size_t item = 2; item < row.size(); item++){
if (validateItemName(row[item]))
itemList.push_back(row[item]);
}
}
void Order::print(){
std::cout << "customer name, product name, [items] = "
<< customerName << " , "
<< productName;
static int number = 1;
for (auto e : itemList)
cout << " , " << e;
cout << "\n";
number++;
}
void Order::graph(std::ofstream& of){
for (auto e : itemList)
of << '"' << customerName << '"' << "->" << '"' << " Item " << e << '"' << " [color=green];\n";
of << "\n";
}
OrderManager::OrderManager(std::vector<std::vector<string>> csvData){
int rowCount = 0;
for (auto row : csvData){
try{
rowCount++;
OrderList.push_back(Order(row));
}
catch (std::string& e){
std::cerr << "Problem with row " << rowCount << " : " << e << std::endl;
}
}
}
void OrderManager::print(){
for (auto e : OrderList)
e.print();
}
void OrderManager::graph(std::string& filename){
std::ofstream of(filename);
if (of.is_open()){
of << "Digraph myGraph {\n";
for (auto t : OrderList)
t.graph(of);
of << "}\n";
of.close();
}
std::string cmd = "dot -Tpng " + filename + " > " + filename + ".png";
std::cout << std::endl << cmd << std::endl;
system(cmd.c_str());
}
/*
using namespace std;
int main(int argc, char* argv[]){
if (argc != 3){
cerr << "Usage : " << argv[0] << "csv-file csv-seperator\n";
return 1;
}
string filename = argv[1];
char seperator = argv[2][0];
try{
vector<vector<string>> csvData;
csvread(filename, seperator, csvData);
OrderManager tm(csvData);
tm.print();
string f = filename + string(".gv");
tm.graph(f);
}
catch (string& e){
cerr << e << "\n";
}
return 0;
}
*/ |
d7bb7b19415cc934395d756259b5a402e46087cc | 52ca17dca8c628bbabb0f04504332c8fdac8e7ea | /boost/accumulators/statistics/weighted_density.hpp | a4ca9bf88cc7f21700805eb2bb3872746ff61d4b | [] | no_license | qinzuoyan/thirdparty | f610d43fe57133c832579e65ca46e71f1454f5c4 | bba9e68347ad0dbffb6fa350948672babc0fcb50 | refs/heads/master | 2021-01-16T17:47:57.121882 | 2015-04-21T06:59:19 | 2015-04-21T06:59:19 | 33,612,579 | 0 | 0 | null | 2015-04-08T14:39:51 | 2015-04-08T14:39:51 | null | UTF-8 | C++ | false | false | 86 | hpp | weighted_density.hpp | #include "thirdparty/boost_1_58_0/boost/accumulators/statistics/weighted_density.hpp"
|
bc590f2517b661c24f6d385ebbd6ee823f260a03 | f4b844363d692373d80d1340ddd98ced9a6cd47d | /LineUp.cpp | 9c6187fd2eb84fa940d0b6de8f375494e3988054 | [] | no_license | bpoore/162_Fantasy_Game | e7024861835fed3c010e7cc9bfeb20bf211106e1 | 35008665f2861860e355b147ac2fb50685a593b9 | refs/heads/master | 2020-12-24T19:28:24.208863 | 2016-04-29T06:13:50 | 2016-04-29T06:13:50 | 57,358,387 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,518 | cpp | LineUp.cpp | /*********************************************************************
** Author: Elizabeth Poore
** Date: May 23, 2015
** createLineup Function
** Description: This function allows the user to select how many creatures will
** be fighting on each team, then allows the players to select which kinds of creatures to
** create as well as provide it them wiht names to identify them from other creatures.
** Parameters: A pointer to character and two linked lists representing the queues for
** the two players are input parameters. The function doesn't return anything.
** Pre-Conditions: A valid pointer to character object as well as valid FIFO class
** objects to pass to the function.
** Post-Conditions: After executing the function, the FIFO class objects will be added to.
*********************************************************************/
#include <iostream>
#include "LineUp.hpp"
void createLineup(Character *characPtr, FIFO &player1, FIFO &player2)
{
int teamSize;
std::cout << "How many characters are there to be on each team?" << std::endl;
std::cin >> teamSize;
for (int x=1; x <=2; x++)
{
std::cout << "\n\nPlayer " << x << ", select your lineup of characters in order: \n\n" << std::endl;
for(int i=0; i < teamSize; i++)
{
std::cout << "Select character #" << (i+1) << " for your team from the following character types:" << std::endl;
std::cout << "1. Goblin" << std::endl;
std::cout << "2. Barbarian" << std::endl;
std::cout << "3. Reptile People" << std::endl;
std::cout << "4. Blue Men" << std::endl;
std::cout << "5. The Shadow" << std::endl;
int selection;
std::cin >> selection;
while (selection < 1 || selection > 5)
{
std::cout << "Invalid selection. Please make a selection from 1-5." << std::endl;
std::cin >> selection;
}
std::string name;
std::cout << "Select a unique name for this creature: " << std::endl;
std::cin >> name;
FIFO *player;
std::string team;
if (x == 1)
{
player = &player1;
team = "Team 1";
}
else
{
player = &player2;
team = "Team 2";
}
switch(selection)
{
case 1:
characPtr = new Goblin(name);
break;
case 2:
characPtr = new Barbarian(name);
break;
case 3:
characPtr = new Reptile(name);
break;
case 4:
characPtr = new BlueMen(name);
break;
case 5:
characPtr = new Shadow(name);
break;
}
characPtr->setPlayer(team);
player->add(characPtr);
}
}
}
|
edba345f72742a665c27d08aa310be821668ce4e | 6221c88e3d55aea2d96ea38e6508d6f3ef4c18e4 | /main.cpp | 90ebc97a1c3c3f5243c014e48de0e22a994f08dd | [] | no_license | sergiosanzllamas/navidades | 30a341d90906b3c44faf4c0312a0565af78304e1 | ad634e658c5c0d99014e94ba51db2b68cb40a462 | refs/heads/master | 2021-09-12T20:01:14.244668 | 2018-04-20T12:13:55 | 2018-04-20T12:13:55 | 115,423,083 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 404 | cpp | main.cpp | #include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(){
int x;
int seg1 = 5;
seg1=(int)clock()/CLOCKS_PER_SEC;
srand(time(NULL));
for(int as=0; as<3; as++){
x = rand()%36;
printf("El numero es %i\n", x);
if(x == 10 %2 || x == 10%3)
printf("has ganado\n");
else
printf("has perdido\n");
}
return EXIT_SUCCESS;
}
|
b215009a23591d5fa61bd3f8467d16a62636fa52 | 96be739909a2d5315b93137f95aec28cc755db2e | /PUNT1.CPP | dfaa16f140beb6d7089992f9e5f385c3dd5bf6bc | [] | no_license | NightRoadIx/Curso-C | e4b1c30bd745b6c86aa5483f490d59b8650706f8 | 44d40331b0d6cbf9340759dbebc034e2d4ed839f | refs/heads/master | 2021-06-14T00:15:09.962894 | 2021-02-16T20:28:52 | 2021-02-16T20:28:52 | 133,899,956 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,461 | cpp | PUNT1.CPP | /*
Curso de Programaci¢n de C
Punteros 1
*/
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
/*
Cuando una variable se declara existen tres atributos fundamentales:
->su tipo (int, float, char) [Da el tamaño que tiene que asignarse]
->su nombre [Como se llama la variable, la forma en que se referencia a ella]
->su dirección en memoria (0XFFFF p.e.) [El "lugar" en donde se coloca la variable]
*/
//VARIABLE GLOBAL
char c;
int main()
{
/*
Apuntador a caracter
Para declarar un apuntador:
tipo_variable *nombre_variable; (no importa si se coloca * nombre_variable)
*/
char *pc;
/*
Se asigna la dirección de la variable c al apuntador pc, esto es
que con esta sentencia el apuntador pc apunta al espacio en memoria
de la variable c
Operador dirección &
(Asignación estática de memoria o inicializacion de punteros)
*/
pc = &c;
//Ahora se recorre la variable c desde A hasta Z
for(c = 'A'; c <= 'Z'; c++)
/*
Lo que se hace es mostrar el contenido de lo que apunta pc
mediante *pc
Operador indirección *
*/
printf(" %c ", *pc);
getch();
printf("\n\nAhora un entero:\n");
int entero=30;
int *p = &entero;
printf("entero = %d , &entero = 0x%X \n",entero,&entero);
printf("p = 0x%X , *p = %d , &p = 0x%X",p,*p,&p);
printf("");
getch();
}
|
cf6452f3f9eb9ed7202156c129703356c6e1f7d4 | b678666d9a56165e56c39f99d569f3a5630452dc | /Phanso/Phanso/Phanso/Phanso.cpp | 69be24b5f739a2da817a6c28291d71eff8abafbd | [] | no_license | JustKidding2K/OOP_Tuan5 | 6184f85497b87684ccf844b611dc206abd6c68bf | af01536a9cf5e9ae8f8bf56f5e2950c323319c33 | refs/heads/master | 2020-08-17T16:41:53.637247 | 2019-10-17T02:44:01 | 2019-10-17T02:44:01 | 215,688,461 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,852 | cpp | Phanso.cpp |
#include"Header.h"
#include "Phanso.h"
int main()
{
//Phanso a(1, 2);
//Phanso b(3, 4);
//Phanso c = a + b;
//cout << c.pGetTu() << "/" << c.pGetMau();
//system("pause");
string input;
cin >> input;
Process(input);
system("pause");
}
Phanso::Phanso()
{
mTu = 0;
mMau = 1;
}
Phanso::~Phanso()
{
}
Phanso::Phanso(int a) {
mTu = a;
mMau=1;
}
Phanso::Phanso(int a, int b) {
mTu = a;
if (b != 0)
mMau = b;
else mMau = 1;
}
void Phanso::pSetTu(int a) {
mTu = a;
}
void Phanso::pSetMau(int b) {
if (b == 0)mMau = 1;
else mMau = b;
}
int Phanso::pGetTu() {
return mTu;
}
int Phanso::pGetMau() {
return mMau;
}
void swap(int& a,int& b) {
int temp = a;
a = b;
b = temp;
}
int Phanso::UCLN(int a,int b) {
int x;
int y;
int temp;
x =a;
y =b;
if (x < y)swap(x, y);
while (y != 0) {
temp = x%y;
x = y;
y = temp;
}
return x;
}
Phanso& Phanso::pQuyDong(Phanso& a) {
//euclid
int k = this->mMau * a.mMau / UCLN(this->mMau, a.mMau);
this->mTu = this->mTu * k / this->mMau;
this->mMau = k;
a.mTu = a.mTu * k / a.mMau;
a.mMau = k;
return *this;
}
Phanso Phanso::operator+(const Phanso& a) {
Phanso temp = a;
this->pQuyDong(temp);
this->mTu = this->mTu + temp.mTu;
return *this;
}
Phanso Phanso::operator-(const Phanso& a) {
Phanso temp = a;
this->pQuyDong(temp);
this->mTu = this->mTu - temp.mTu;
return *this;
}
Phanso Phanso::operator*(const Phanso& a) {
this->mTu = this->mTu * a.mTu;
this->mMau = this->mMau * a.mMau;
return *this;
}
Phanso Phanso::operator/(const Phanso& a) {
this->mTu = this->mTu * a.mMau;
this->mMau = this->mMau * a.mTu;
return *this;
}
Phanso& Phanso::pRutgon() {
int k = UCLN(mTu, mMau);
mTu = mTu / k;
mMau = mMau / k;
return *this;
}
|
71d67cf004c678c1133e007b7ce060e33e720974 | b4af26ef6994f4cbb738cdfd182e0a992d2e5baa | /source/leetcode/2293/신입.cpp | 3daec4023a10eaaa526f7dddb842a077b153af82 | [] | no_license | wisest30/AlgoStudy | 6819b193c8e9245104fc52df5852cd487ae7a26e | 112de912fc10933445c2ad36ce30fd404c493ddf | refs/heads/master | 2023-08-08T17:01:12.324470 | 2023-08-06T11:54:15 | 2023-08-06T11:54:15 | 246,302,438 | 10 | 17 | null | 2021-09-26T13:52:18 | 2020-03-10T13:02:56 | C++ | UTF-8 | C++ | false | false | 383 | cpp | 신입.cpp | class Solution {
public:
int minMaxGame(vector<int>& nums) {
if(nums.size() == 1) return nums[0];
vector<int> newNums;
for(int i=0;i<nums.size()/2;i++)
{
if(i%2 == 0) newNums.push_back(min(nums[2*i], nums[2*i+1]));
else newNums.push_back(max(nums[2*i], nums[2*i+1]));
}
return minMaxGame(newNums);
}
};
|
8c9a293d64b81beb6b03fcffc70ed9734a3fd8c6 | 1ca947273d2739e25e3e9d96c839dfa4562bfaf9 | /src/ViewFrustum.cpp | fb84a1992a33ecea83c5b5c93fa4539e4f4e86e6 | [] | no_license | jpaterso/fire-engine | 8cf40af27098c94df388714fb3a339f6fae16b37 | b6389539fe6901971bb2ff696aba1c2f55a3df55 | refs/heads/master | 2021-01-01T18:54:41.699488 | 2010-04-28T05:07:09 | 2010-04-28T05:07:09 | 32,113,283 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,402 | cpp | ViewFrustum.cpp | /**
* FILE: ViewFrustum.cpp
* AUTHOR: Joseph Paterson ( joseph dot paterson at gmail dot com )
* RCS ID: $Id: ViewFrustum.cpp 105 2007-09-11 05:08:21Z jpaterso $
* PURPOSE: A view frustum, defining a visible volume in 3-dimensional space.
**/
#include "ViewFrustum.h"
#include "Math.h"
namespace fire_engine
{
ViewFrustum::ViewFrustum()
{
}
ViewFrustum::ViewFrustum(const plane3f& near, const plane3f& far, const plane3f& top,
const plane3f& bottom, const plane3f& left, const plane3f& right)
{
mPlanes[EFP_NEAR] = near;
mPlanes[EFP_FAR] = far;
mPlanes[EFP_TOP] = top;
mPlanes[EFP_BOTTOM] = bottom;
mPlanes[EFP_LEFT] = left;
mPlanes[EFP_RIGHT] = right;
}
ViewFrustum::ViewFrustum(const plane3f * planes)
{
for (s32 i = 0; i < EFP_PLANECOUNT; i++)
mPlanes[i] = planes[i];
}
ViewFrustum::~ViewFrustum()
{
}
EFRUSTUM_INTERSECTION_TYPE ViewFrustum::calculateIntersection(const aabboxf& box) const
{
s32 totalInCount = 0;
s32 inCount, allPointsIn;
vector3f points[8];
box.getCorners(points);
for (s32 i = 0; i < EFP_PLANECOUNT; i++)
{
inCount = 8;
allPointsIn = 1;
for (s32 j = 0; j < 8; j++)
{
if (mPlanes[i].getSideOfPlane(points[j]) != ESOP_ABOVE)
{
allPointsIn = 0;
inCount--;
}
}
if (inCount == 0)
return EFIT_OUTSIDE;
totalInCount += allPointsIn;
}
if (totalInCount == EFP_PLANECOUNT)
return EFIT_INSIDE;
return EFIT_INTERSECT;
}
}
|
de5f912295f5d197a4015cf2f5b6260d1d9f2c3d | 91e0031b55d93eabb36e8a29234b3ce58e97cbe1 | /rules/str/51/c0.cpp | 80d758ed757ba4308f19c1f687ccaea4fd7be6c2 | [] | no_license | yesmar/sei-cert-cppcs-samples | d76c2f13fc21d01a04ae544118f272abce2b57b1 | 88f9bd1d9f4769f518b1348690bfc02e1647d16a | refs/heads/main | 2023-02-16T19:29:53.066649 | 2021-01-17T22:22:53 | 2021-01-17T22:22:53 | 313,092,118 | 4 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 215 | cpp | c0.cpp | // STR51-CPP: Compliant Solution
#include <cstdlib>
#include <string>
void f() {
const char *tmpPtrVal = std::getenv("TMP");
std::string tmp(tmpPtrVal ? tmpPtrVal : "");
if (!tmp.empty()) {
// ...
}
}
|
9002dae85195a576ca69e01364e0689c15c00f90 | 01f6db15d5fe059e3a45966008b93568bea691f5 | /Classes/Bullet.cpp | 3c2f407901b02c8bd6b61fc4ba468b43440fd3df | [
"MIT"
] | permissive | meer07/new_stg_sample | 61c80a77d6d8b4e840849e86e661b068a4fcd5d8 | d17d9e4eef7ad1216cb6a24c6eb34d6dbcb07b1d | refs/heads/master | 2020-05-16T23:50:08.419491 | 2015-02-06T09:30:23 | 2015-02-06T09:30:23 | 28,857,250 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,001 | cpp | Bullet.cpp | #include "Bullet.h"
#include "TaskManager.h"
#include "GameData.h"
// {speed,speedRate,angle}
Bullet* Bullet::create(const float param[], std::string fileName)
{
Bullet *bullet = new Bullet();
bullet->speed = param[0];
bullet->speedRate = param[1];
bullet->angle = param[2];
bullet->isAlive = true;
bullet->setTag(3);
bullet->setName("Bullet");
if (bullet && bullet->initWithSpriteFrameName(fileName))
{
bullet->autorelease();
bullet->retain();
return bullet;
}
CC_SAFE_DELETE(bullet);
return NULL;
}
void Bullet::Move()
{
MoveBase();
Collision();
}
void Bullet::Collision()
{
cocos2d::Rect bulletrect = this->boundingBox();
cocos2d::Rect playerrect = TaskManager::player->boundingBox();
if(bulletrect.intersectsRect(playerrect) && TaskManager::player->isAlive)
{
TaskManager::player->Destroy();
this->isAlive = false;
}
} |
d37cd88b801158b96d07b07ab432bb210098355a | ae11eda73ad0a61f8f7f894314bd9aa40798b50a | /HiggsAnalysis/GBRLikelihoodEGTools/src/EGEnergyCorrectorTraditional.cc | 31d445c49d7131b58456f109af04fafc1373db05 | [] | no_license | hbakhshi/NTupleProducer | 087a7286f7352e9f6c517d257d7f195280db058d | eec377339008d2139128059d7127f9a2184c080c | refs/heads/master | 2021-01-22T14:32:44.891691 | 2014-06-10T12:48:12 | 2014-06-10T12:48:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,150 | cc | EGEnergyCorrectorTraditional.cc | #include <TFile.h>
#include "../interface/EGEnergyCorrectorTraditional.h"
#include "CondFormats/EgammaObjects/interface/GBRForest.h"
#include "CondFormats/DataRecord/interface/GBRWrapperRcd.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "DataFormats/EgammaCandidates/interface/Photon.h"
#include "DataFormats/EgammaCandidates/interface/GsfElectron.h"
#include "DataFormats/Math/interface/deltaPhi.h"
#include "RecoEcal/EgammaCoreTools/interface/EcalClusterLazyTools.h"
#include "DataFormats/EcalDetId/interface/EcalSubdetector.h"
#include "DataFormats/VertexReco/interface/Vertex.h"
using namespace reco;
//--------------------------------------------------------------------------------------------------
EGEnergyCorrectorTraditional::EGEnergyCorrectorTraditional() :
_foresteb(0),
//_forestee(0),
_isInitialized(kFALSE)
{
// Constructor.
}
//--------------------------------------------------------------------------------------------------
EGEnergyCorrectorTraditional::~EGEnergyCorrectorTraditional()
{
if (_isInitialized) {
delete _foresteb;
//delete _forestee;
}
}
//--------------------------------------------------------------------------------------------------
void EGEnergyCorrectorTraditional::Initialize(std::string regweights) {
_isInitialized = kTRUE;
//initialize eval vector
_vals.resize(37);
//load forests from file
TFile *fgbr = TFile::Open(regweights.c_str(),"READ");
fgbr->GetObject("EBCorrection", _foresteb);
//fgbr->GetObject("EGRegressionForest_EE", _forestee);
fgbr->Close();
}
//--------------------------------------------------------------------------------------------------
void EGEnergyCorrectorTraditional::CorrectedEnergyWithErrorV4Traditional(const reco::Photon &p, const reco::VertexCollection& vtxcol, double rho, EcalClusterLazyTools &clustertools, const edm::EventSetup &es, double &ecor, double &cbsigma) {
//not implemented at the moment
cbsigma = 0.;
const SuperClusterRef s = p.superCluster();
const CaloClusterPtr b = s->seed(); //seed basic cluster
Bool_t isbarrel = b->hitsAndFractions().at(0).first.subdetId()==EcalBarrel;
if (!isbarrel) {
ecor = s->rawEnergy() + s->preshowerEnergy();
return;
}
// //basic supercluster variables
_vals[0] = s->rawEnergy();
_vals[1] = s->eta();
_vals[2] = s->phi();
_vals[3] = p.r9();
_vals[4] = s->etaWidth();
_vals[5] = s->phiWidth();
_vals[6] = double(s->clustersSize());
_vals[7] = p.hadTowOverEm();
_vals[8] = rho;
_vals[9] = double(vtxcol.size());
//seed basic cluster variables
double bemax = clustertools.eMax(*b);
double be2nd = clustertools.e2nd(*b);
double betop = clustertools.eTop(*b);
double bebottom = clustertools.eBottom(*b);
double beleft = clustertools.eLeft(*b);
double beright = clustertools.eRight(*b);
double be2x5max = clustertools.e2x5Max(*b);
double be2x5top = clustertools.e2x5Top(*b);
double be2x5bottom = clustertools.e2x5Bottom(*b);
double be2x5left = clustertools.e2x5Left(*b);
double be2x5right = clustertools.e2x5Right(*b);
double be5x5 = clustertools.e5x5(*b);
_vals[10] = b->eta()-s->eta();
_vals[11] = reco::deltaPhi(b->phi(),s->phi());
_vals[12] = b->energy()/s->rawEnergy();
_vals[13] = clustertools.e3x3(*b)/be5x5;
_vals[14] = sqrt(clustertools.localCovariances(*b)[0]); //sigietaieta
_vals[15] = sqrt(clustertools.localCovariances(*b)[2]); //sigiphiiphi
_vals[16] = clustertools.localCovariances(*b)[1]; //sigietaiphi
_vals[17] = bemax/be5x5; //crystal energy ratio gap variables
_vals[18] = be2nd/be5x5;
_vals[19] = betop/be5x5;
_vals[20] = bebottom/be5x5;
_vals[21] = beleft/be5x5;
_vals[22] = beright/be5x5;
_vals[23] = be2x5max/be5x5; //crystal energy ratio gap variables
_vals[24] = be2x5top/be5x5;
_vals[25] = be2x5bottom/be5x5;
_vals[26] = be2x5left/be5x5;
_vals[27] = be2x5right/be5x5;
if (isbarrel) {
//additional energy ratio (always ~1 for endcap, therefore only included for barrel)
_vals[28] = be5x5/b->energy();
//local coordinates and crystal indices (barrel only)
//seed cluster
float betacry, bphicry, bthetatilt, bphitilt;
int bieta, biphi;
_ecalLocal.localCoordsEB(*b,es,betacry,bphicry,bieta,biphi,bthetatilt,bphitilt);
_vals[29] = bieta; //crystal ieta
_vals[30] = biphi; //crystal iphi
_vals[31] = bieta%5; //submodule boundary eta symmetry
_vals[32] = biphi%2; //submodule boundary phi symmetry
_vals[33] = (TMath::Abs(bieta)<=25)*(bieta%25) + (TMath::Abs(bieta)>25)*((bieta-25*TMath::Abs(bieta)/bieta)%20); //module boundary eta approximate symmetry
_vals[34] = biphi%20; //module boundary phi symmetry
_vals[35] = betacry; //local coordinates with respect to closest crystal center at nominal shower depth
_vals[36] = bphicry;
}
else {
//preshower energy ratio (endcap only)
_vals[28] = s->preshowerEnergy()/s->rawEnergy();
}
double den = s->rawEnergy();
GBRForest *forest = _foresteb;
// if (isbarrel) {
// den = s->rawEnergy();
// forest = _foresteb;
// }
// else {
// den = s->rawEnergy() + s->preshowerEnergy();
// forest = _forestee;
// }
ecor = den*forest->GetResponse(&_vals[0]);
return;
}
//--------------------------------------------------------------------------------------------------
void EGEnergyCorrectorTraditional::CorrectedEnergyWithErrorV4Traditional(const reco::GsfElectron &e, const reco::VertexCollection& vtxcol, double rho, EcalClusterLazyTools &clustertools, const edm::EventSetup &es, double &ecor, double &cbsigma) {
//not implemented at the moment
cbsigma = 0.;
const SuperClusterRef s = e.superCluster();
const CaloClusterPtr b = s->seed(); //seed basic cluster
Bool_t isbarrel = b->hitsAndFractions().at(0).first.subdetId()==EcalBarrel;
if (!isbarrel) {
ecor = s->rawEnergy() + s->preshowerEnergy();
return;
}
// //basic supercluster variables
_vals[0] = s->rawEnergy();
_vals[1] = s->eta();
_vals[2] = s->phi();
_vals[3] = e.r9();
_vals[4] = s->etaWidth();
_vals[5] = s->phiWidth();
_vals[6] = double(s->clustersSize());
_vals[7] = e.hcalOverEcalBc();
_vals[8] = rho;
_vals[9] = double(vtxcol.size());
//seed basic cluster variables
double bemax = clustertools.eMax(*b);
double be2nd = clustertools.e2nd(*b);
double betop = clustertools.eTop(*b);
double bebottom = clustertools.eBottom(*b);
double beleft = clustertools.eLeft(*b);
double beright = clustertools.eRight(*b);
double be2x5max = clustertools.e2x5Max(*b);
double be2x5top = clustertools.e2x5Top(*b);
double be2x5bottom = clustertools.e2x5Bottom(*b);
double be2x5left = clustertools.e2x5Left(*b);
double be2x5right = clustertools.e2x5Right(*b);
double be5x5 = clustertools.e5x5(*b);
_vals[10] = b->eta()-s->eta();
_vals[11] = reco::deltaPhi(b->phi(),s->phi());
_vals[12] = b->energy()/s->rawEnergy();
_vals[13] = clustertools.e3x3(*b)/be5x5;
_vals[14] = sqrt(clustertools.localCovariances(*b)[0]); //sigietaieta
_vals[15] = sqrt(clustertools.localCovariances(*b)[2]); //sigiphiiphi
_vals[16] = clustertools.localCovariances(*b)[1]; //sigietaiphi
_vals[17] = bemax/be5x5; //crystal energy ratio gap variables
_vals[18] = be2nd/be5x5;
_vals[19] = betop/be5x5;
_vals[20] = bebottom/be5x5;
_vals[21] = beleft/be5x5;
_vals[22] = beright/be5x5;
_vals[23] = be2x5max/be5x5; //crystal energy ratio gap variables
_vals[24] = be2x5top/be5x5;
_vals[25] = be2x5bottom/be5x5;
_vals[26] = be2x5left/be5x5;
_vals[27] = be2x5right/be5x5;
if (isbarrel) {
//additional energy ratio (always ~1 for endcap, therefore only included for barrel)
_vals[28] = be5x5/b->energy();
//local coordinates and crystal indices (barrel only)
//seed cluster
float betacry, bphicry, bthetatilt, bphitilt;
int bieta, biphi;
_ecalLocal.localCoordsEB(*b,es,betacry,bphicry,bieta,biphi,bthetatilt,bphitilt);
_vals[29] = bieta; //crystal ieta
_vals[30] = biphi; //crystal iphi
_vals[31] = bieta%5; //submodule boundary eta symmetry
_vals[32] = biphi%2; //submodule boundary phi symmetry
_vals[33] = (TMath::Abs(bieta)<=25)*(bieta%25) + (TMath::Abs(bieta)>25)*((bieta-25*TMath::Abs(bieta)/bieta)%20); //module boundary eta approximate symmetry
_vals[34] = biphi%20; //module boundary phi symmetry
_vals[35] = betacry; //local coordinates with respect to closest crystal center at nominal shower depth
_vals[36] = bphicry;
}
else {
//preshower energy ratio (endcap only)
_vals[28] = s->preshowerEnergy()/s->rawEnergy();
}
double den = s->rawEnergy();
GBRForest *forest = _foresteb;
// if (isbarrel) {
// den = s->rawEnergy();
// forest = _foresteb;
// }
// else {
// den = s->rawEnergy() + s->preshowerEnergy();
// forest = _forestee;
// }
ecor = den*forest->GetResponse(&_vals[0]);
return;
}
|
284c8eae3fddc0d639c7ec3696838f33466a446f | 155e63c2cb0b214338a08b03f59e97f568582740 | /lab1/7.cc | b1aa66771c2856ff939f45f88428b6c825bde99f | [] | no_license | macabrus/asp | f5d259dbe8069b83fba9aacf4b7ff4d192f193b3 | 88ca813bb8a5e044a5091caed31df47820e1caf8 | refs/heads/master | 2020-08-24T10:46:41.340778 | 2020-01-10T20:04:35 | 2020-01-10T20:04:35 | 216,812,003 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | cc | 7.cc | #include <iostream>
#include <algorithm>
#include <ctime>
#include "../util.h"
using namespace std;
int* getSquaredArr(int* arr, int size) {
for(int i = 0; i < size; i++)
*(arr + i) = *(arr + i) * *(arr + i);
random_shuffle(arr, arr + size);
return arr;
}
int main () {
srand(time(0));
int n;
cin >> n;
int* arr = new int[n];
for(int i = 0; i < n; i++)
cin >> *(arr + i);
printArr(arr, n);
printArr(getSquaredArr(arr, n), n);
}
|
9b1848052a8d9247b94620f3e0938ad5c36d8bc6 | 1d9bc0bd79442d521f92e1328ff0ffa35adb13b7 | /riglib/plexon/plexon/docs/PlexNetClient.cpp | 0434028f2d64681617b778e8ab908ccb84863b4e | [
"Apache-2.0"
] | permissive | carmenalab/brain-python-interface | 07cf7e1ee1a75070cfbcabc7d2df9111e539e36c | a0e296aa663b49e767c9ebb274defb54b301eb12 | refs/heads/develop | 2023-02-21T14:43:26.659430 | 2022-12-18T21:54:56 | 2022-12-18T21:54:56 | 36,104,349 | 9 | 5 | NOASSERTION | 2023-02-08T00:01:39 | 2015-05-23T02:44:47 | Python | UTF-8 | C++ | false | false | 10,548 | cpp | PlexNetClient.cpp | //
// PlexNetClient.cpp
//
// Implements the PlexNetClient class. See RawSocket.cpp
// for a console mode application that demonstrates the use
// of PlexNetClient to receive PlexNet data from an OmniPlex
// or MAP system. For questions or support, please contact
// support@plexon.com.
//
// Author: Alex Kirillov
// (c) 1998-2014 Plexon Inc (www.plexon.com)
//
#include "PlexNetClient.h"
#include <stdexcept>
#ifdef WIN32
// this line will ensure linking with ws2_32.lib
#pragma comment( lib, "ws2_32.lib" )
#endif
using namespace std;
PlexNetClient::PlexNetClient( const char* hostAddress, int port, PlexNetClient::Protocol theProtocol )
: m_HostAddress( hostAddress )
, m_HostPort( port )
, m_Protocol( theProtocol )
, m_Socket( INVALID_SOCKET )
, m_SupportsSelectContChannels( false )
, m_SupportsSelectSpikeChannels( false )
, m_NumSpikeChannels( 0 )
, m_NumContinuousChannels( 0 )
{
m_SendBuffer.resize( PACKETSIZE );
m_SendBufferIntPointer = ( int* )( &m_SendBuffer[0] );
m_ReceiveBuffer.resize( PACKETSIZE );
m_ReceiveBufferIntPointer = ( int* )( &m_ReceiveBuffer[0] );
}
PlexNetClient::~PlexNetClient( void )
{
if ( m_Socket != INVALID_SOCKET ) {
// closesocket( m_Socket );
close( m_Socket );
}
#ifdef WIN32
WSACleanup();
#endif
}
void PlexNetClient::InitSocketLibrary()
{
#ifdef WIN32
WSADATA wsaData;
WORD wVersionRequested = MAKEWORD( 2, 2 );
if ( WSAStartup( wVersionRequested, &wsaData ) != 0 ) {
throw runtime_error( "Unable to init Windows sockets" );
}
#else
// do nothing in non-Windows OS
#endif
}
void PlexNetClient::CreateSocket()
{
m_Socket = socket( AF_INET, ( m_Protocol == ProtocolTCPIP ) ? SOCK_STREAM : SOCK_DGRAM, 0 );
if ( m_Socket == INVALID_SOCKET ) {
throw runtime_error( "Unable to create socket" );
}
}
void PlexNetClient::ConnectSocket()
{
// get IP address of the PlexNetLocal server
memset( &m_SocketAddressIn, 0, sizeof( SOCKADDR_IN ) );
hostent* he = gethostbyname( m_HostAddress.c_str() );
memcpy( &m_SocketAddressIn.sin_addr, he->h_addr_list[0], he->h_length );
m_SocketAddressIn.sin_family = AF_INET;
// port is configurable. look up port number
// at the top of PlexNetLocal dialog
m_SocketAddressIn.sin_port = htons( m_HostPort );
// address of the PlexNetLocal server
// needs to be in SOCKADDR structure instead of SOCKADDR_IN
// we simply copy contents of socketAddress into this struct
memset( &m_SocketAddress, 0, sizeof( m_SocketAddress ) );
memcpy( &m_SocketAddress, &m_SocketAddressIn, sizeof( m_SocketAddress ) );
if ( m_Protocol == ProtocolTCPIP ) {
if ( connect( m_Socket, &m_SocketAddress, sizeof( SOCKADDR ) ) != 0 ) {
throw runtime_error( "Unable to connect" );
}
}
}
void PlexNetClient::SendCommandConnectClient()
{
// send command to connect the client and set the data transfer mode
memset( &m_SendBuffer[0], 0, PACKETSIZE );
m_SendBufferIntPointer[0] = PLEXNET_COMMAND_FROM_CLIENT_TO_SERVER_CONNECT_CLIENT;
// this command specifies general data transfer options: what data types we want to transfer
// we will need to send additional commands later to specify details of data transfer
// here we specify that we want everything.
// we will send other commands later where we will specify what data we want from what channels
m_SendBufferIntPointer[1] = 1; // want timestamps
m_SendBufferIntPointer[2] = 1; // want spike waveforms
m_SendBufferIntPointer[3] = 1; // want analog data
m_SendBufferIntPointer[4] = 1; // spike channel from
m_SendBufferIntPointer[5] = 128; // spike channel to
SendPacket();
}
void PlexNetClient::SendPacket()
{
int bytesSentInSingleSend = 0;
int totalBytesSent = 0;
int attempt = 0;
// send may transmit fewer bytes than PACKETSIZE
// try several sends
while ( totalBytesSent < PACKETSIZE && attempt < 1000 ) {
attempt++;
if ( m_Protocol == ProtocolTCPIP ) {
bytesSentInSingleSend = send( m_Socket, &m_SendBuffer[0] + totalBytesSent, PACKETSIZE - totalBytesSent, 0 );
// if ( bytesSentInSingleSend == SOCKET_ERROR ) {
if ( bytesSentInSingleSend == -1 ) {
throw runtime_error( "Unable to send: send error" );
}
} else { // UDP
bytesSentInSingleSend = sendto( m_Socket, &m_SendBuffer[0] + totalBytesSent, PACKETSIZE - totalBytesSent, 0, ( SOCKADDR* )&m_SocketAddress, sizeof( m_SocketAddress ) );
// if ( bytesSentInSingleSend == SOCKET_ERROR ) {
if ( bytesSentInSingleSend == -1 ) {
throw runtime_error( "Unable to send: send error" );
}
}
totalBytesSent += bytesSentInSingleSend;
}
if ( totalBytesSent != PACKETSIZE ) {
throw runtime_error( "Unable to send: Cannot send all the bytes of the packet" );
}
}
void PlexNetClient::ReceivePacket()
{
SOCKADDR_IN SenderAddr; // for UDP recvfrom only
socklen_t SenderAddrSize = sizeof( SenderAddr );
int bytesReceivedInSingleRecv = 0;
int totalBytesReceived = 0;
int attempt = 0;
while ( totalBytesReceived < PACKETSIZE && attempt < 1000 ) {
attempt++;
if ( m_Protocol == ProtocolTCPIP ) {
bytesReceivedInSingleRecv = recv( m_Socket, &m_ReceiveBuffer[0] + totalBytesReceived, PACKETSIZE - totalBytesReceived, 0 );
// if ( bytesReceivedInSingleRecv == SOCKET_ERROR ) {
if ( bytesReceivedInSingleRecv == -1 ) {
throw runtime_error( "Unable to receive: receive error" );
}
} else { // UDP
bytesReceivedInSingleRecv = recvfrom( m_Socket, &m_ReceiveBuffer[0] + totalBytesReceived, PACKETSIZE - totalBytesReceived, 0, ( SOCKADDR* )&SenderAddr, &SenderAddrSize );
// if ( bytesReceivedInSingleRecv == SOCKET_ERROR ) {
if ( bytesReceivedInSingleRecv == -1 ) {
throw runtime_error( "Unable to receive: receive error" );
}
}
totalBytesReceived += bytesReceivedInSingleRecv;
}
if ( totalBytesReceived != PACKETSIZE ) {
throw runtime_error( "Unable to receive: Cannot receive all the bytes of the packet" );
}
}
void PlexNetClient::ProcessMmfSizesMessage()
{
// m_ReceiveBufferIntPointer[3] contains the number of supported commands
int numCommands = m_ReceiveBufferIntPointer[3];
if ( numCommands > 0 && numCommands < 32 ) {
for ( int i = 0; i < numCommands; i++ ) {
if ( m_ReceiveBufferIntPointer[4 + i] == PLEXNET_COMMAND_FROM_CLIENT_TO_SERVER_SELECT_SPIKE_CHANNELS ) {
m_SupportsSelectSpikeChannels = true;
}
if ( m_ReceiveBufferIntPointer[4 + i] == PLEXNET_COMMAND_FROM_CLIENT_TO_SERVER_SELECT_CONTINUOUS_CHANNELS ) {
m_SupportsSelectContChannels = true;
}
}
}
}
void PlexNetClient::GetPlexNetInfo()
{
ReceivePacket();
if ( m_ReceiveBufferIntPointer[0] != PLEXNET_COMMAND_FROM_SERVER_TO_CLIENT_MMF_SIZES ) {
throw runtime_error( "Unable to get PlexNet Info: wrong packet type" );
}
ProcessMmfSizesMessage();
if ( m_SupportsSelectSpikeChannels && m_SupportsSelectContChannels ) {
RequestParameterMMF();
GetNumbersOfChannels();
}
}
void PlexNetClient::RequestParameterMMF()
{
memset( &m_SendBuffer[0], 0, PACKETSIZE );
m_SendBufferIntPointer[0] = PLEXNET_COMMAND_FROM_CLIENT_TO_SERVER_GET_PARAMETERS_MMF;
SendPacket();
}
void PlexNetClient::GetNumbersOfChannels()
{
// read parameters until we get PLEXNET_COMMAND_FROM_SERVER_TO_CLIENT_SENDING_SERVER_AREA
bool gotServerArea = false;
while ( !gotServerArea ) {
ReceivePacket();
if ( m_ReceiveBufferIntPointer[0] == PLEXNET_COMMAND_FROM_SERVER_TO_CLIENT_SENDING_SERVER_AREA ) {
m_NumSpikeChannels = m_ReceiveBufferIntPointer[15];
m_NumContinuousChannels = m_ReceiveBufferIntPointer[17];
gotServerArea = true;
}
}
}
void PlexNetClient::SelectSpikeChannels( const std::vector<unsigned char>& channelSelection )
{
if ( channelSelection.size() > 0 ) {
SendLongBuffer( PLEXNET_COMMAND_FROM_CLIENT_TO_SERVER_SELECT_SPIKE_CHANNELS, &channelSelection[0], channelSelection.size() );
}
}
void PlexNetClient::SendLongBuffer( int command, const unsigned char* buffer, int length )
{
// we have PlexNetMultiMessageTransmissionHeader and the rest is bufLength that we can use for data
int buflength = PACKETSIZE - sizeof( PlexNetMultiMessageTransmissionHeader );
int numberOfMessages = length / buflength;
if ( length % buflength ) {
numberOfMessages++;
}
int positionOfFirstByte = 0;
for ( int i = 0; i < numberOfMessages; i++ ) {
memset( &m_SendBuffer[0], 0, PACKETSIZE );
int numBytesInThisMessage = buflength;
if ( length % buflength && i == numberOfMessages - 1 ) {
numBytesInThisMessage = length % buflength;
}
int headerSize = sizeof( PlexNetMultiMessageTransmissionHeader );
PlexNetMultiMessageTransmissionHeader* header = ( PlexNetMultiMessageTransmissionHeader* ) &m_SendBuffer[0];
header->CommandCode = command;
header->MessageIndex = i;
header->NumberOfMessages = numberOfMessages;
header->NumberOfBytesInThisMessage = numBytesInThisMessage;
header->PositionOfTheFirstByte = positionOfFirstByte;
memcpy( &m_SendBuffer[0] + headerSize, buffer + positionOfFirstByte, numBytesInThisMessage );
positionOfFirstByte += numBytesInThisMessage;
SendPacket();
}
}
void PlexNetClient::SelectContinuousChannels( const std::vector<unsigned char>& channelSelection )
{
if ( channelSelection.size() > 0 ) {
SendLongBuffer( PLEXNET_COMMAND_FROM_CLIENT_TO_SERVER_SELECT_CONTINUOUS_CHANNELS, &channelSelection[0], channelSelection.size() );
}
}
void PlexNetClient::StartDataPump()
{
memset( &m_SendBuffer[0], 0, PACKETSIZE );
m_SendBufferIntPointer[0] = PLEXNET_COMMAND_FROM_CLIENT_TO_SERVER_START_DATA_PUMP;
SendPacket();
}
|
621785f2d62d61b7291dde338a5cc003d9af12dd | bd9e6cfa10d1967b50cd699727631594f374b5f8 | /OpenMC/Src/Scenes/BuildingHelper.h | ded5965e1663088ee4767ee074bc747c6b038ad2 | [] | no_license | UnknownBuild/OpenMC | 20218202efb8678f0a6f594066e5c962ebd1711a | 7496e2b243a8e2efcff88df907139a276a676738 | refs/heads/master | 2020-05-21T07:12:06.683397 | 2019-07-19T15:55:50 | 2019-07-19T15:55:50 | 185,952,676 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 318 | h | BuildingHelper.h | #pragma once
#include "../Camera/Camera.h"
#include "../SpriteRenderer/SpriteRenderer.h"
#include "../World/World.h"
#include "Scene.h"
class BuildingHelper {
public:
BuildingHelper();
void buildTree(glm::vec3 pos, int height);
void buildHouse(glm::vec3 pos);
private:
SpriteRenderer* renderer;
};
|
5ea8b52e7761879603a55b7d8cb48d3961a5ca7a | 594c967c169872d19e5b3971f389aa5185a90c21 | /task9Aug2021B.cpp | 46ad588abd02d0d3589f71c746452ca3d3b8baeb | [] | no_license | mahmoudalfawair/task9Aug2021 | 7f342fd1ee5b8d2858f4afcdce153a8d7666116c | 0a951ae1795eb36c770b6f1975f103f8d6407231 | refs/heads/main | 2023-07-07T21:21:04.328152 | 2021-08-09T07:37:04 | 2021-08-09T07:37:04 | 394,195,713 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 221 | cpp | task9Aug2021B.cpp | #include <iostream>
using namespace std;
int main()
{
int counter=0;
for(int i =65; i < 91; i++)
cout << static_cast<char>(i)<< endl;
for(int j = 97; j<123; j++)
cout << static_cast<char>(j)<< endl;
return 0;
} |
8226afbd7cf243aaff5c374538c750c58fa7660d | 320dba9142f1bf18e042172bc6598b6cf6510a2c | /25_성적표ver3/MyException.h | 549ea274c3d52096f27ff740508e30a0c502191d | [] | no_license | Jeonghwan-Yoo/brain_cpp | a6a7be1f3d5e2288f5c93b437bd13530b600d7f7 | aa9f279dccb36705f308e4d8495cbcae9a7e6c9a | refs/heads/master | 2020-07-26T23:27:45.117750 | 2019-09-16T12:50:39 | 2019-09-16T12:50:39 | 208,797,126 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 777 | h | MyException.h | #ifndef MYEXCEPTION_H
#define MYEXCEPTION_H
#include <string>
#include <exception> //상속 받기 위해
using namespace std;
//이 프로젝트 사용할 예외
class MyException : public exception {
public:
//생성자
//msg:예외를 설명하는 문자열
//예외를 설명할 문자열을 인자로 받아 멤버 변수 _Str에 보관한다.
MyException(const string& msg) : _Str(msg) {
}
//소멸자
virtual ~MyException() {
}
//예외 설명 문자열을 반환한다.
//반환 값 : 문자열
//what()함수를 오버라이드한다. 예외에 대한 설명 문자열을 반환하는 함수.
//생성자에서 입력 받은 문자열을 반환한다.
virtual const char *what() const {
return _Str.c_str();
}
protected:
string _Str;
};
#endif |
ff2fe5c862f49ef6c6e76352d2ca4e6ae67ff54b | f8036dae49bfc19f21d52b80313e1539fc92d284 | /behavioral/observer/course_website.h | 70f97747b9b2b7937bcde5ea4c3d27e13b8bbfd3 | [] | no_license | EazyReal/design-pattern | c24f32e641cf1572c8f9e26644a613f204a0653f | 57d9cfa4d5e0349fa9e0091e802fd6997f742ebd | refs/heads/master | 2023-01-16T03:41:36.510849 | 2020-11-27T20:02:38 | 2020-11-27T20:02:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 601 | h | course_website.h | #ifndef COURSE_WEBSITE_H_
#define COURSE_WEBSITE_H_
#include "observable.h"
#include "observer.h"
#include <functional>
#include <string>
#include <vector>
class CourseWebsite : public Obserable<CourseWebsite> {
public:
// The caller is responsible for maintaining the life of an observer longer
// than course website.
void AddObserver(Observer<CourseWebsite> &observer) override;
void PutAnnoucement(std::string annoucement);
std::string GetAnnoucement() const;
private:
std::string annoucement_;
std::vector<std::reference_wrapper<Observer<CourseWebsite>>> observers_;
};
#endif
|
9231d29d9e77b1526931728b5fd83ee06a4291a0 | f0d5be072772928dfc3dbaf9134b8a51727a49cd | /SDLGame/PlayState.cpp | f12c3913467dc3285706ed0074d4204f81ca23ec | [] | no_license | KyryloBR/SDLEngine | 85cc17546395334c927ec10b58ae938b372cc347 | e4304927eee5992a0b0c68d38d8e52c06245cd67 | refs/heads/master | 2020-12-24T20:24:21.564478 | 2016-05-21T22:01:51 | 2016-05-21T22:01:51 | 59,379,157 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,751 | cpp | PlayState.cpp | #include "PlayState.h"
#include "Log.h"
#include "Game.h"
#include "InputHandler.h"
#include "PauseState.h"
#include "GameOverState.h"
#include "StateParser.h"
#include "LevelParser.h"
#include "AnimationParser.h"
#include "CollisionManager.h"
#include "AnimationHandler.h"
const std::string PlayState::s_playID = "PLAY";
void PlayState::render()
{
m_pLevel->render();
for (int i = 0; i < m_gameObjects.size(); ++i)
{
m_gameObjects[i]->draw();
}
}
void PlayState::update()
{
if (InputHandler::Instance()->isKeyDown(SDL_SCANCODE_ESCAPE))
{
Game::Instance()->getStateMachine()->push_back(new PauseState());
}
m_pLevel->update();
//if (m_pLevel->getPlayer()->getPosition()->getX() + m_pLevel->getPlayer()->getWidth() >= 635)
//{
// for (int i = 0; i < m_pLevel->getLayers()->size(); ++i)
// {
// TileLayer * pTile = dynamic_cast<TileLayer*>(m_pLevel->getLayers()->at(i));
// if (pTile)
// {
// pTile->setColumns(20);
// m_pLevel->getPlayer()->setPosition(Vector2D(30, 330));
// }
// }
//}
for (int i = 0; i < m_gameObjects.size(); ++i)
{
m_gameObjects[i]->update();
}
}
bool PlayState::onEnter()
{
LevelParser levelParser;
m_pLevel = levelParser.parseLevel("../assets/1.tmx");
TextureManager::Instance()->load("Underground2", "../assets/Underground2.png", Game::Instance()->getRenderer());
m_pLevel->getPlayer()->setEarthBorder(320);
//AnimationHandler::Instance()->load("D:/program/SDL/SDLGame/Data/animation.xml");
return true;
}
bool PlayState::onExit()
{
for (int i = 0; i < m_gameObjects.size(); ++i)
{
m_gameObjects[i]->clean();
}
m_gameObjects.clear();
for (int i = 0; i < m_textureIDs.size(); ++i)
{
TextureManager::Instance()->clearFromTextureMap(m_textureIDs[i]);
}
return true;
} |
b2d8a094701633f11e513f37fff43d83590d3714 | 78bffca13fb22f10a1453bf39e561cc1102f5033 | /TQueue Class/Tqueue.cpp | e4a17af88f1255d6e10f97448d03d5ffd638fa04 | [] | no_license | EnzoW1997/Music-Player | 563f68ff924ec76db51a8239a8e636cc50cf54b2 | c467e55a5d94f2fa7d501988cbbcc90e8cff7556 | refs/heads/master | 2020-03-21T19:35:44.136147 | 2018-06-28T03:21:14 | 2018-06-28T03:21:14 | 138,944,926 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,805 | cpp | Tqueue.cpp | #ifndef TQUEUE_H
#define TQUEUE_H
/********************************
** File: Tqueue.cpp
** Project: CMSC 202 Project 5, Fall 2017
** Author: Enzo Walker
** Date: 11/27/2017
** Section: 1093, Discussion: 1095
** Email: enzow1@umbc.edu
**
** This class is a templated Queue that takes Type Pramaters of T
** which are then implemented in a First-In-First-Out Queue system.
** In our case, Song objects will be queued.
**
**
********************************/
#include <iostream>
#include <cstdlib>
using namespace std;
template <class T, int N>
class Tqueue {
public:
//Name: Tqueue - Default Constructor
//Precondition: None (Must be templated)
//Postcondition: Creates a queue using dynamic array
Tqueue(); //Default Constructor
//Name: Copy Constructor
//Precondition: Existing Tqueue
//Postcondition: Copies an existing Tqueue
Tqueue( const Tqueue<T,N>& x ); //Copy Constructor
//Name: Destructor
//Precondition: Existing Tqueue
//Postcondition: Destructs existing Tqueue
~Tqueue(); //Destructor
//Name: enqueue
//Precondition: Existing Tqueue
//Postcondition: Adds item to back of queue
void enqueue(T data); //Adds item to queue (to back)
//Name: dequeue
//Precondition: Existing Tqueue
//Postcondition: Removes item from front of queue
void dequeue(T &); //Removes item from queue (from front)
//Name: queueFront
//Precondition: Existing Tqueue
//Postcondition: Retrieve front (does not remove it)
void queueFront(T &); // Retrieve front (does not remove it)
//Name: isEmpty
//Precondition: Existing Tqueue
//Postcondition: Returns 1 if queue is empty else 0
int isEmpty(); //Returns 1 if queue is empty else 0
//Name: isFull
//Precondition: Existing Tqueue
//Postcondition: Returns 1 if queue is full else 0
int isFull(); //Returns 1 if queue is full else 0
//Name: size
//Precondition: Existing Tqueue
//Postcondition: Returns size of queue
int size(); //Returns size of queue
//Name: Overloaded assignment operator
//Precondition: Existing Tqueue
//Postcondition: Sets one Tqueue to same as a second Tqueue using =
Tqueue<T,N>& operator=( Tqueue<T,N> y); //Overloaded assignment operator for queue
//Name: Overloaded [] operator
//Precondition: Existing Tqueue
//Postcondition: Returns object from Tqueue using []
T& operator[] (int x);//Overloaded [] operator to pull data from queue
private:
T* m_data; //Data of the queue (Must be dynamically allocated array)
int m_front; //Front of the queue
int m_back; //Back of the queue
};
//**** Add class definition below ****
//Tqueue()
//Default constructor for a Templated Queue
template <class T, int N>
Tqueue<T,N>::Tqueue(){
m_data = new T[N];
m_front = 0;
m_back = 0;
}
//Tqueue( const Tqueue<T,N>& x)
//Copy constructor for a Tqueue
template <class T, int N>
Tqueue<T,N>::Tqueue( const Tqueue<T,N>& x ){
m_data = new T[N];
for(int i = 0; i < N; i++){
m_data[i] = x.m_data[i];
}
m_front = x.m_front;
m_back = x.m_back;
}
//~Tqueue()
//Destructor for Tqueue that deallocates each song in the queue
template <class T, int N>
Tqueue<T,N>::~Tqueue(){
delete [] m_data;
m_data = NULL;
}
//enqueue(T data)
//Adds item that is passed to the back of the queue
template <class T, int N>
void Tqueue<T,N>::enqueue(T data){
//Enqueue's if the queue is not full
if(!isFull()){
m_data[m_back] = data;
m_back++;
}else{
cout << "You have reached the max amount of songs allowed" << endl;
}
}
//dequeue(T& data)
//Removes an item from the queue
template <class T, int N>
void Tqueue<T,N>::dequeue(T& data){
if(!isEmpty())
m_front++;
}
//queueFront(T& data)
//Retrieves front of the queue but does not remove it
template <class T, int N>
void Tqueue<T,N>::queueFront(T& data){
}
//isEmpty();
//Returns 1 if queue is empty, and 0 if it's not empty
template <class T, int N>
int Tqueue<T,N>::isEmpty(){
if(size() == 0)
return 1;
else
return 0;
}
//isFull()
//Returns 1 if queue is full, and 0 if it's not full
template <class T, int N>
int Tqueue<T,N>::isFull(){
if(size() == N)
return 1;
else
return 0;
}
//size()
//Returns the size of the queue
template <class T, int N>
int Tqueue<T,N>::size(){
return abs((m_back - m_front));
}
//Overloaded assignment operator
//Assigns one Tqueue to another using the "=" operator
template <class T, int N>
Tqueue<T,N>& Tqueue<T,N>::operator=( Tqueue<T,N> y){
delete [] m_data;
m_data = new T[N];
for(int i = 0; i < N; i++){
m_data[i] = y.m_data[i];
}
m_front = y.m_front;
m_back = y.m_back;
return *this;
}
//Overloaded [] operator
//Properly returns a reference to an object of type T
template <class T, int N>
T& Tqueue<T,N>::operator[] (int x){
return m_data[x+m_front];
}
#endif
|
5ba6404ace3ec52fa4d951d99fdd945010eb2e06 | 58dbd83bc3142b23d7f6b20212a592ded62f49fa | /Algorithm/Baekjoon/1325.cpp | 0d1b565f26ad7eb49d6ff1787d469c6d40d29a32 | [] | no_license | kkminseok/Git_Tutorial | 56cbaededfed52dc093cdf343ace98f59ba57b18 | 1be681f240de067f9aee17a08620e04f9fc49441 | refs/heads/master | 2022-08-13T13:24:32.886304 | 2022-07-24T09:20:56 | 2022-07-24T09:20:56 | 204,464,357 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 919 | cpp | 1325.cpp | #include<iostream>
#include<vector>
#include<cstring>
#include<queue>
using namespace std;
int N, M;
int counting[10001] = { 0, };
int maxz = -1;
bool v[100001] = { false };
void bfs(int start,vector<int> graph[])
{
queue<int> q;
q.push(start);
v[start] = true;
while (!q.empty())
{
int tmp = q.front();
q.pop();
for (int i = 0; i < graph[tmp].size(); ++i)
{
if (v[graph[tmp][i]] == false)
{
q.push(graph[tmp][i]);
++counting[start];
}
}
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N >> M;
int a,b;
vector<int>* graph = new vector<int>[N + 1];
for (int i = 0; i < M; ++i)
{
cin >> a >> b;
graph[b].push_back(a);
}
for (int i = 1; i <= N; ++i)
{
memset(v, false, sizeof(v));
bfs(i,graph);
if (maxz < counting[i])
maxz = counting[i];
}
for (int i = 1; i <= N; ++i)
{
if (maxz == counting[i])
cout << i<<" ";
}
} |
f265fd2325b2ffae260487b8ce5a75641ec37ef5 | c31ee8136a57a96649196081e1cfde0676c2a481 | /larcv/app/ImageMod/MultiPartSegFromCluster2dParticle.h | 89a5903742e451a464425cd7e61a41f2d2c9d90d | [
"MIT"
] | permissive | DeepLearnPhysics/larcv2 | b12b46168e5c6795c70461c9495e29b427cd88b5 | 31863c9b094a09db2a0286cfbb63ccd2f161e14d | refs/heads/develop | 2023-06-11T03:15:51.679864 | 2023-05-30T17:51:19 | 2023-05-30T17:51:19 | 107,551,725 | 16 | 19 | MIT | 2023-04-10T10:15:13 | 2017-10-19T13:42:39 | C++ | UTF-8 | C++ | false | false | 2,214 | h | MultiPartSegFromCluster2dParticle.h | /**
* \file MultiPartSegFromCluster2dParticle.h
*
* \ingroup ImageMod
*
* \brief Class def header for a class MultiPartSegFromCluster2dParticle
*
* @author cadams
*/
/** \addtogroup ImageMod
@{*/
#ifndef __MULTIPARTSEGFROMCLUSTER2DPARTICLE_H__
#define __MULTIPARTSEGFROMCLUSTER2DPARTICLE_H__
#include "larcv/core/Processor/ProcessBase.h"
#include "larcv/core/Processor/ProcessFactory.h"
#include "larcv/core/DataFormat/Image2D.h"
#include "larcv/core/DataFormat/Particle.h"
#include "larcv/core/DataFormat/Voxel2D.h"
namespace larcv {
/**
\class ProcessBase
User defined class MultiPartSegFromCluster2dParticle ... these comments are
used to generate
doxygen documentation!
*/
class MultiPartSegFromCluster2dParticle : public ProcessBase {
public:
/// Default constructor
MultiPartSegFromCluster2dParticle(
const std::string name = "MultiPartSegFromCluster2dParticle");
/// Default destructor
~MultiPartSegFromCluster2dParticle() {}
void configure(const PSet&);
void initialize();
bool process(IOManager& mgr);
void finalize();
Image2D seg_image_creator(const std::vector<Particle> & particles,
const ClusterPixel2D & clusters,
const ImageMeta & meta);
private:
void configure_labels(const PSet&);
std::string _image2d_producer;
std::string _cluster2d_producer;
std::string _output_producer;
std::string _particle_producer;
std::vector<int> _pdg_list;
std::vector<int> _label_list;
};
/**
\class larcv::MultiPartSegFromCluster2dParticleFactory
\brief A concrete factory class for larcv::MultiPartSegFromCluster2dParticle
*/
class MultiPartSegFromCluster2dParticleProcessFactory
: public ProcessFactoryBase {
public:
/// ctor
MultiPartSegFromCluster2dParticleProcessFactory() {
ProcessFactory::get().add_factory("MultiPartSegFromCluster2dParticle",
this);
}
/// dtor
~MultiPartSegFromCluster2dParticleProcessFactory() {}
/// creation method
ProcessBase* create(const std::string instance_name) {
return new MultiPartSegFromCluster2dParticle(instance_name);
}
};
}
#endif
/** @} */ // end of doxygen group
|
eeb53f3e92ce9e0dd8485149f06d0270da71c072 | b7f7a7f5b4dfa3f249822eb312ac92b0c4d2d840 | /HWPrograms/forHW1/HW1P2/vectorClient1.cpp | 31fb14bc492e10c65b6a382a66bd8f20fe6932dd | [] | no_license | elDavidGarcia/CSUSM_CS311 | 46571c5235aa03f5cea1f8c41e9f0f71ba16047b | 5d0d59487dbd6a12c50b563744d0a65907f6c90e | refs/heads/master | 2020-04-27T16:12:04.956702 | 2019-03-08T05:41:55 | 2019-03-08T05:41:55 | 174,476,072 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,601 | cpp | vectorClient1.cpp | //=========================================================
//HW#: HW1P2 vector stack
//Your name: David Garcia
//Complier: g++
//File type: client program for vector stack
//===========================================================
using namespace std;
#include <cstdlib>
#include <iostream>
#include <string>
#include "vstack.h"
//Purpose of the program: Uses a vector stack to make an integer postfix expression
// calculator that can add, subtract, and muliply.
//Algorithm: Asks the user for an expression which it stores into a string variable,
// named expression. Using the string class it breaks down the string into
// an array of chracters ending with the NULL charcter ('\0'). The while
// loop keeps going until it reaches the NULL charcter, adding operands to
// the stack and poping them when there is a operator. It pops the result
// and displays it. Then checks for incomplete expressions.
int main()
{
stack postfixstack; // integer vector stack
string expression, close; // user entered expression
cout << "Type a postfix expression: ";
cin >> expression; //Get input from user
int i = 0; // character position within expression
char item; // one character out of the expression
int box1, box2; // receive things from pop
//While it doesn't reach the end of expression
while (expression[i] != '\0')
{
try
{
item = expression[i]; // current character from expression
//2. if it is an operand (number),
// push it.
// subtract 48 to turn char into correct int
if(isdigit(item)) postfixstack.push(item - 48);
//3. else if it is an operator,
// pop the two operands (you might get Underflow exception), and
// apply the operator to the two operands, and
// push the result.
else if ( (item == '+') || (item == '-') || (item == '*'))
{
postfixstack.pop(box1); //Pop 1st operand, store in box1
postfixstack.pop(box2); //Pop 2nd operand, store in box2
//cases for different operators follow:
switch(item) //Switch case uses current iteam being checked
{
//check what operator is in item and push the
//result of the first operand operator operand
case '+': postfixstack.push(box2 + box1); break;
case '-': postfixstack.push(box2 - box1); break;
case '*': postfixstack.push(box2 * box1); break;
}
}
//If it's neither a number or valid operator throw invalid item
else throw "Invalid item entered";
} // this closes try
// Catch exceptions and report problems and quit the program now.
// Error messages describe what is wrong with the expression.
catch (stack::Underflow) // for too few operands
{
cout << "Error: Not enough numbers\n"; exit(1);
}
catch (char const* errorcode) // for invalid item
{
cout << "Error: " << errorcode << endl; exit(1);
}
i++; // go back to the loop after incrementing i
}// end of while
// After the loop successfully completes:
// The result will be at the top of the stack. Pop it and show it.
postfixstack.pop(box1);
// If anything is left on the stack, an incomplete expression was found.
// Inform the user.
try
{
//If there is something in the stack throw error code
if(!postfixstack.isEmpty()) throw "Incomplete expression was found";
}
catch(char const* errorcode)
{
cout << "Error: " << errorcode << endl; return 0;
}
cout << "Result: " << box1 << endl;
return 0;
}// end of the program
|
c6e82494a68d4d0ec33a9e61d452f6090e86ffe8 | 35250ed783653dabc3dfb7328a8a1b1d0fa7d295 | /Code/cxz/tfidfGenerator.cpp | 02768f89b19a052dd845008a9b0cd6338206f4d9 | [] | no_license | alpha7happy/kaggle-keyword | 780abaab8bd8bb2c9af9012ce6c7901236ed186a | 71c3c8adc9fd50b6e887ee02f3f285999aa74625 | refs/heads/master | 2020-05-28T10:29:18.177875 | 2013-12-04T19:08:13 | 2013-12-04T19:08:13 | 13,782,091 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,434 | cpp | tfidfGenerator.cpp | #include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cctype>
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <queue>
#include <set>
#include <map>
#include <sstream>
#include <cctype>
using namespace std;
#define lowbit(x) ((x)&(-(x)))
#define sqr(x) ((x)*(x))
#define PB push_back
#define MP make_pair
FILE* fout;
FILE* fin;
char s[1000000];
vector<double> idf;
void loadDict(char* filename){
FILE* fin=fopen(filename,"r");
double value;
int id;
for (;fscanf(fin,"%lf",&value)==1;)
idf.PB(value);
fclose(fin);
}
vector<pair<int,int> > parseFeature(char* s){
vector<pair<int,int> > res;
res.clear();
for (char* p=strtok(s," ");p;p=strtok(NULL," ")){
int id;
int value;
if (sscanf(p,"%d:%d",&id,&value)==2)
if (id!=-1)
res.PB(MP(id,value));
}
return res;
}
int main(int argc,char** argv){
if (argc!=4){
puts("Argument Error");
return 0;
}
loadDict(argv[1]);
puts("Dictionary Loaded");
fin=fopen(argv[2],"r");
fout=fopen(argv[3],"w");
int cnt=0;
for (;fgets(s,1000000,fin);){
cnt++;
if (cnt%10000==0){
printf("\rLoading, #Row = %.2fM",cnt/1000000.);
fflush(stdout);
}
vector<pair<int,int> > data=parseFeature(s);
for (int i=0;i<data.size();i++)
fprintf(fout,"%d:%.5f ",data[i].first,data[i].second*idf[data[i].first]);
fprintf(fout,"\n");
}
printf("\rLoading Finished\n");
fclose(fin);
fclose(fout);
} |
58c9bd98c64f35934903480737a81071da5df7c9 | c6e78a4c638d56dc9e444615873bfd593cca3fbb | /Mine-Sweeper-game/Mine-Sweeper-game/Game2D.cpp | 2089198bcd79b2d192473c6ac49d2e5e8311ed98 | [] | no_license | Yeram522/OPP-Mine-Sweeper-Game | aefb68e4d0276efae71658432f073bd333ada737 | 5207778ac1f8c41b28cf88291b3806bcc835cb1e | refs/heads/main | 2023-08-19T14:39:49.291003 | 2021-10-07T10:52:50 | 2021-10-07T10:52:50 | 408,292,629 | 0 | 0 | null | 2021-10-04T15:29:27 | 2021-09-20T02:52:59 | C++ | UHC | C++ | false | false | 3,677 | cpp | Game2D.cpp | #include "Game2D.h"
Input* Input::Instance = nullptr;
bool Game2D::isLooping=true;
WindowPos Input:: ClickedPos;
//-------------
//
//
//
//맨 상단 윗줄의 UI를 업데이트 한다.
void Game2D::Update_UI(const int _count)
{
Borland::gotoxy(0, 0);
printf("▤▤▤▤▤▤▤ ★ : %d ▤▤▤▤▤▤▤\n", _count);
printf("-------------------------------------------");
Borland::gotoxy(44, 2);
printf("How To Game\n");
Borland::gotoxy(44, 3);
printf("-------------\n");
Borland::gotoxy(44, 4);
printf("Click Mine → GameOver\n");
Borland::gotoxy(44, 5);
printf("LeftMouseClick → Open the button.\n");
Borland::gotoxy(44, 6);
printf("ESC → End the game\n");
}
//마이크로소프트 제공 함수----------------------------------(약간 수정한 것도 있다.)
void Input::ErrorExit(const char* lpszMessage)
{
fprintf(stderr, "%s\n", lpszMessage);
// Restore input mode on exit.
SetConsoleMode(hStdin, fdwSaveOldMode);
ExitProcess(0);
}
void Input::KeyEventProc(KEY_EVENT_RECORD ker)
{
Borland::gotoxy(0, 12);
printf("%s\r", blankChars);
switch (ker.wVirtualKeyCode) {
case VK_LBUTTON:
printf("left button ");
break;
case VK_BACK:
printf("back space");
break;
case VK_RETURN:
printf("enter key");
break;
case VK_ESCAPE:
printf("escape key");
Game2D::isLooping = false;
break;
case VK_UP:
printf("arrow up");
break;
default:
if (ker.wVirtualKeyCode >= 0x30 && ker.wVirtualKeyCode <= 0x39)
printf("Key event: %c ", ker.wVirtualKeyCode - 0x30 + '0');
else printf("Key event: %c ", ker.wVirtualKeyCode - 0x41 + 'A');
break;
}
Borland::gotoxy(0, 0);
}
void Input::MouseEventProc(MOUSE_EVENT_RECORD mer)
{
Borland::gotoxy(0, 12);
printf("%s\r", blankChars);
#ifndef MOUSE_HWHEELED
#define MOUSE_HWHEELED 0x0008
#endif
printf("Mouse event: ");
switch (mer.dwEventFlags)
{
case 0:
if (mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED)
{
printf("left button press %d %d\n", mer.dwMousePosition.X, mer.dwMousePosition.Y);
ClickedPos.x = mer.dwMousePosition.X;
ClickedPos.y = mer.dwMousePosition.Y;//전역변수에 입력받은 pos 넘겨줌.
}
else if (mer.dwButtonState == RIGHTMOST_BUTTON_PRESSED)
{
printf("right button press \n");
}
else
{
printf("button press\n");
}
break;
case DOUBLE_CLICK:
printf("double click\n");
break;
case MOUSE_HWHEELED:
printf("horizontal mouse wheel\n");
break;
case MOUSE_MOVED:
printf("mouse moved %d %d\n", mer.dwMousePosition.X, mer.dwMousePosition.Y);
break;
case MOUSE_WHEELED:
printf("vertical mouse wheel\n");
break;
default:
printf("unknown\n");
break;
}
Borland::gotoxy(0, 0);
}
void Input::ResizeEventProc(WINDOW_BUFFER_SIZE_RECORD wbsr)
{
Borland::gotoxy(0, 13);
printf("%s\r", blankChars);
printf("Resize event: ");
printf("Console screen buffer is %d columns by %d rows.\n", wbsr.dwSize.X, wbsr.dwSize.Y);
Borland::gotoxy(0, 0);
}
//---------------------------------------------------------
void Game2D::run()//자식게임클래스를 실행하는 함수이고 while문을 포함한다.
{
bool isClear = false;
//키 입력 변수-------------
Input* input = Input::GetInstance();
//input->Intialize();
//게임 루프 스타트!!
while (isLooping) {
if (gameclear())
{
Borland::gotoxy(44, 9);
printf("★★★CLEAR★★★");
isClear = true;
break;
}
clear();
input->ReadInput();
update();//자식클래스에서 이 함수를 오버라이드 하여 사용한다!
Sleep(100);
}
if (isClear) return;
Borland::gotoxy(44, 9);
printf("★Game-Over★");
return;
}
void Game2D::exit()
{
isLooping = false;
}
|
f8538bfca7c08add9580f3806eb4886b85182a0c | c553210bcfb3a9e9c89b05ea8cb0b661b8c7682b | /AOAPC_II/ch2/2-4.cpp | dceb48ac6eb91819900337968d41adca3d077d2d | [
"MIT"
] | permissive | y-wan/OJ | e9f387c2453471a3a48223461fcab9c6883ad02a | 5dea140dbaaec98e440ad4b1c10fa5072f1ceea7 | refs/heads/master | 2021-01-20T00:16:11.535977 | 2019-11-16T09:56:46 | 2019-11-16T09:56:46 | 101,275,100 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 232 | cpp | 2-4.cpp | #include <stdio.h>
int main() {
int kase = 0, a, b;
double sum;
while (scanf("%d %d", &a, &b) == 2 && a) {
sum = 0;
for (int i = a; i <= b; i++)
sum += 1.0 / i / i;
printf("Case %d: %.5f\n", ++kase, sum);
}
return 0;
} |
5162637e44f2e9a34317b8a73579b13a145da572 | 7bc94825dacf6aa90c25260441277baecac1d7a2 | /be/src/olap/memory/delta_index.h | 00b6728d4448f8a0bb4f5b9dee5b88b552db94ed | [
"Apache-2.0",
"PSF-2.0",
"bzip2-1.0.6",
"BSD-3-Clause",
"Zlib",
"dtoa",
"MIT",
"GPL-2.0-only",
"LicenseRef-scancode-public-domain"
] | permissive | EmmyMiao87/incubator-doris | 2330b55b21d8478365b0feec2a45776b62433fc8 | af06adb57fbaf306534971bae8cf11162d714404 | refs/heads/master | 2022-09-30T16:22:13.074082 | 2020-12-02T02:13:13 | 2020-12-02T02:13:13 | 155,680,801 | 3 | 3 | Apache-2.0 | 2018-11-01T07:52:59 | 2018-11-01T07:52:59 | null | UTF-8 | C++ | false | false | 2,521 | h | delta_index.h | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#pragma once
#include <vector>
#include "olap/memory/buffer.h"
#include "olap/memory/common.h"
namespace doris {
namespace memory {
// DeltaIndex store all the updated rows' id(rowids) for a ColumnDelta.
// Rowids are sorted and divided into blocks, each 64K rowid space is a
// block. Since each block only have 64K id space, it can be store as uint16_t
// rather than uint32_t to save memory.
class DeltaIndex : public RefCountedThreadSafe<DeltaIndex> {
public:
static const uint32_t npos = 0xffffffffu;
DeltaIndex() = default;
// get memory consumption
size_t memory() const;
// find rowid(rid) in the index,
// return index position if found, else return npos
uint32_t find_idx(uint32_t rid);
// get a block's index position range as [start, end)
void block_range(uint32_t bid, uint32_t* start, uint32_t* end) const {
if (bid < _block_ends.size()) {
*start = bid > 0 ? _block_ends[bid - 1] : 0;
*end = _block_ends[bid];
} else {
*start = 0;
*end = 0;
}
}
// Return true if this index has any rowid belonging to this block
bool contains_block(uint32_t bid) const {
if (bid < _block_ends.size()) {
return (bid > 0 ? _block_ends[bid - 1] : 0) < _block_ends[bid];
}
return false;
}
Buffer& data() { return _data; }
const Buffer& data() const { return _data; }
vector<uint32_t>& block_ends() { return _block_ends; }
const vector<uint32_t>& block_ends() const { return _block_ends; }
private:
vector<uint32_t> _block_ends;
Buffer _data;
DISALLOW_COPY_AND_ASSIGN(DeltaIndex);
};
} // namespace memory
} // namespace doris
|
4492d8da3d86e6e1311e6af0c8b59c90c936b94c | e43e57d3a56b053b9429130e75a112ec094fe06d | /algorithms/38_atoi.cpp | 16f3098d343a7a7667f24599b4b9b012bde316f8 | [] | no_license | zebra6/polecat | 6b1ba43e51652115edab316bcda6562d941a10ec | 2ae019ddbcd613de0571961e40c1b5d83cfd638d | refs/heads/master | 2021-06-15T08:50:35.123977 | 2017-04-10T02:11:58 | 2017-04-10T02:11:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,002 | cpp | 38_atoi.cpp | /*
implementation of atoi
*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
int is_num( char x );
int atoi1( char* str );
int atoi2( char* str );
/******************************************************************************
*****************************************************************************/
int main( int argc, char** argv )
{
char* in = argv[1];
printf( "a1: %i\na2: %i\n", atoi1( in ), atoi2( in ) );
printf( "\n\n" );
return 0;
}
/******************************************************************************
*****************************************************************************/
int atoi1( char* str )
{
int i = 0;
int j = strlen(str) - 1;
int retv = 0;
char tmp = '0';
/*reverse the string*/
for( ; i < j; i++, j-- )
{
tmp = str[i];
str[i] = str[j];
str[j] = tmp;
}
/*use i as an accumulator*/
for( i = 0; i < strlen(str); i++ )
{
if( str[i] >= '0' && str[i] <= '9' )
{
/*found a digit*/
tmp = str[i] - '0';
retv += tmp * pow( 10, i );
}
else if( str[i] == '-' )
{
/*negative sign*/
retv *= -1;
break;
}
else
/*non-digit*/
break;
}
return retv;
}
/******************************************************************************
*****************************************************************************/
int is_num(char x)
{
return ( x >= '0' && x <= '9' ) ? true : false;
}
/******************************************************************************
*****************************************************************************/
int atoi2( char *str )
{
int i = 0;
int retv = 0;
int sign = 1;
if ( !str ) return 0;
/*check for negative sign*/
if (str[0] == '-')
{
sign = -1;
i++;
}
/*iterate through the string*/
for( ; str[i] != '\0'; i++ )
{
/*check for errors*/
if( !is_num( str[i] ) ) return 0;
/*retv is raised to the nth power of 10 as we iterate*/
retv = ( retv * 10 ) + ( str[i] - '0' );
}
return retv * sign;
}
|
ab7c6cba1be6bf63155cf207dab537c61cd8e0ac | 2435868c60ecb911fd07cd11abfb0431cfe23d1f | /toolchain-extras/profile-clang-openat.cpp | 45c1acc5286998640983111a6b1025e4672d32ac | [] | no_license | jbeich/platform_system_extras | 5d4e47ae890bd067284daaf421cfe9d6b2367cb3 | 0f0aecc178b6f01223d14b06206a766b56aa55e1 | refs/heads/master | 2023-09-03T23:17:15.359272 | 2023-09-01T23:57:26 | 2023-09-01T23:57:26 | 37,218,268 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,607 | cpp | profile-clang-openat.cpp | /*
* Copyright (C) 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <fcntl.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
// This file provides a wrapper for open.
extern "C" {
int __real_open(const char* pathname, int flags, ...);
static bool needs_mode(int flags) {
return ((flags & O_CREAT) == O_CREAT) || ((flags & O_TMPFILE) == O_TMPFILE);
}
static const char* PROFRAW_START = "/data/misc/trace/";
static bool is_coverage_trace(const char* pathname) {
if (strncmp(pathname, PROFRAW_START, strlen(PROFRAW_START)) == 0) return true;
return false;
}
__attribute__((weak)) int __wrap_open(const char* pathname, int flags, ...) {
if (!needs_mode(flags)) {
return __real_open(pathname, flags);
}
va_list args;
va_start(args, flags);
mode_t mode = static_cast<mode_t>(va_arg(args, int));
va_end(args);
int ret = __real_open(pathname, flags, mode);
if (ret != -1 && is_coverage_trace(pathname)) fchmod(ret, mode);
return ret;
}
}
|
64abc60e6e41b9fdd71c2f6f02705cbeeabf260a | 75297fca92dfd49d958b83dd3103e762339c2366 | /tests/common.h | d9501155a503be4f454bc7e1e0a17ab54191c936 | [
"Apache-2.0"
] | permissive | Zondax/ledger-matrix | 3333af4a0799ca8780562b7a7243c9ed4de238ee | a5c4286caa618607d94029304eccf751bef00e56 | refs/heads/main | 2023-07-20T20:49:40.566415 | 2023-06-15T08:18:36 | 2023-07-11T18:01:14 | 186,560,818 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 1,911 | h | common.h | /*******************************************************************************
* (c) 2018 - 2023 Zondax AG
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
********************************************************************************/
#pragma once
#include <vector>
#include <string>
#include "parser_common.h"
typedef struct {
uint64_t index;
std::string name;
std::string blob;
std::vector<std::string> expected;
std::vector<std::string> expected_expert;
} testcase_t;
class JsonTests_Base : public ::testing::TestWithParam<testcase_t> {
public:
struct PrintToStringParamName {
template<class ParamType>
std::string operator()(const testing::TestParamInfo<ParamType> &info) const {
auto p = static_cast<testcase_t>(info.param);
std::stringstream ss;
ss << p.index << "_" << p.name;
return ss.str();
}
};
};
#define EXPECT_EQ_STR(_STR1, _STR2, _errorMessage) { if (_STR1 != nullptr & _STR2 != nullptr) \
EXPECT_TRUE(!strcmp(_STR1, _STR2)) << _errorMessage << ", expected: " << _STR2 << ", received: " << _STR1; \
else FAIL() << "One of the strings is null"; }
std::vector<std::string> dumpUI(parser_context_t *ctx, uint16_t maxKeyLen, uint16_t maxValueLen);
std::vector<testcase_t> GetJsonTestCases(const std::string &jsonFile);
void check_testcase(const testcase_t &tc, bool expert_mode);
|
bcdaffcbe0e13d237ee1bf4a34158fe5f2977559 | 67b645a97d18d12841a1ac70aaf3f4c87b5d96d6 | /framework/code/framework/light/ManagerLight.cpp | a8f7588aa28d9c3f50b1b68c0bc576a9c4d7c5e2 | [] | no_license | H405/MSProject | 051d8ac7dbc8e6e0a39d9b6abdcceece102267d0 | 07cb61afc4ed5caa2c6ee2a928a3f5c6d34ccdc3 | refs/heads/master | 2021-01-10T17:44:19.281382 | 2016-01-19T23:54:43 | 2016-01-19T23:54:43 | 44,644,877 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 9,684 | cpp | ManagerLight.cpp | //==============================================================================
//
// File : ManagerLight.cpp
// Brief : ライト管理クラス
// Author : Taiga Shirakawa
// Date : 2015/11/14 sat : Taiga Shirakawa : create
//
//==============================================================================
//******************************************************************************
// インクルード
//******************************************************************************
#include "ManagerLight.h"
#include "LightDirection.h"
#include "LightPoint.h"
#include "../develop/Debug.h"
//******************************************************************************
// ライブラリ
//******************************************************************************
//******************************************************************************
// マクロ定義
//******************************************************************************
//******************************************************************************
// 静的メンバ変数
//******************************************************************************
//==============================================================================
// Brief : コンストラクタ
// Return : :
// Arg : void : なし
//==============================================================================
ManagerLight::ManagerLight( void )
{
// クラス内の初期化処理
InitializeSelf();
}
//==============================================================================
// Brief : デストラクタ
// Return : :
// Arg : void : なし
//==============================================================================
ManagerLight::~ManagerLight( void )
{
// 終了処理
Finalize();
}
//==============================================================================
// Brief : 初期化処理
// Return : int : 実行結果
// Arg : int maximumDirection : 最大ディレクショナルライト数
// Arg : int maximumPoint : 最大ポイントライト数
//==============================================================================
int ManagerLight::Initialize( int maximumDirection, int maximumPoint )
{
// メンバ変数の設定
maximumDirection_ = maximumDirection;
maximumPoint_ = maximumPoint;
if( maximumDirection > 0 )
{
pLightDirection_ = new LightDirection[ maximumDirection ];
for( int counterItem = 0; counterItem < maximumDirection; ++counterItem )
{
pLightDirection_[ counterItem ].Initialize();
}
}
if( maximumPoint > 0 )
{
pLightPoint_ = new LightPoint[ maximumPoint ];
for( int counterItem = 0; counterItem < maximumPoint; ++counterItem )
{
pLightPoint_[ counterItem ].Initialize();
}
}
// 正常終了
return 0;
}
//==============================================================================
// Brief : 終了処理
// Return : int : 実行結果
// Arg : void : なし
//==============================================================================
int ManagerLight::Finalize( void )
{
// 格納領域の開放
delete[] pLightDirection_;
pLightDirection_ = nullptr;
delete[] pLightPoint_;
pLightPoint_ = nullptr;
// クラス内の初期化処理
InitializeSelf();
// 正常終了
return 0;
}
//==============================================================================
// Brief : 再初期化処理
// Return : int : 実行結果
// Arg : int maximumDirection : 最大ディレクショナルライト数
// Arg : int maximumPoint : 最大ポイントライト数
//==============================================================================
int ManagerLight::Reinitialize( int maximumDirection, int maximumPoint )
{
// 終了処理
int result; // 実行結果
result = Finalize();
if( result != 0 )
{
return result;
}
// 初期化処理
return Initialize( maximumDirection, maximumPoint );
}
//==============================================================================
// Brief : クラスのコピー
// Return : int : 実行結果
// Arg : ManagerLight* pOut : コピー先アドレス
//==============================================================================
int ManagerLight::Copy( ManagerLight* pOut ) const
{
// 正常終了
return 0;
}
//==============================================================================
// Brief : ディレクショナルライトの取得
// Return : LightDirection* : ディレクショナルライト
// Arg : void : なし
//==============================================================================
LightDirection* ManagerLight::GetLightDirection( void )
{
// 空いているライトを検索
for( int counterLight = 0; counterLight < maximumDirection_; ++counterLight )
{
if( !pLightDirection_[ counterLight ].IsUsed() )
{
pLightDirection_[ counterLight ].Reinitialize();
pLightDirection_[ counterLight ].Use();
return &pLightDirection_[ counterLight ];
}
}
// 見つからなかった
PrintDebugWnd( _T( "ディレクショナルライトの空きがありませんでした。\n" ) );
return nullptr;
}
//==============================================================================
// Brief : ポイントライトの取得
// Return : LightPoint* : ポイントライト
// Arg : void : なし
//==============================================================================
LightPoint* ManagerLight::GetLightPoint( void )
{
// 空いているライトを検索
for( int counterLight = 0; counterLight < maximumPoint_; ++counterLight )
{
if( !pLightPoint_[ counterLight ].IsUsed() )
{
pLightPoint_[ counterLight ].Reinitialize();
pLightPoint_[ counterLight ].Use();
return &pLightPoint_[ counterLight ];
}
}
// 見つからなかった
PrintDebugWnd( _T( "ポイントライトの空きがありませんでした。\n" ) );
return nullptr;
}
//==============================================================================
// Brief : ディレクショナルライト数の取得
// Return : int : ディレクショナルライト数
// Arg : void : なし
//==============================================================================
int ManagerLight::GetCountLightDirection( void )
{
// 使用しているライトを検索
int countLight; // ライトの数
countLight = 0;
for( int counterLight = 0; counterLight < maximumDirection_; ++counterLight )
{
if( pLightDirection_[ counterLight ].IsUsed() && pLightDirection_[ counterLight ].IsEnable() )
{
++countLight;
}
}
// 値の返却
return countLight;
}
//==============================================================================
// Brief : ポイントライト数の取得
// Return : int : ポイントライト数
// Arg : void : なし
//==============================================================================
int ManagerLight::GetCountLightPoint( void )
{
// 使用しているライトを検索
int countLight; // ライトの数
countLight = 0;
for( int counterLight = 0; counterLight < maximumPoint_; ++counterLight )
{
if( pLightPoint_[ counterLight ].IsUsed() && pLightPoint_[ counterLight ].IsEnable() )
{
++countLight;
}
}
// 値の返却
return countLight;
}
//==============================================================================
// Brief : 有効なディレクショナルライトの取得
// Return : LightDirection* : ディレクショナルライト
// Arg : int index : 番号
//==============================================================================
LightDirection* ManagerLight::GetLightDirectionEnable( int index )
{
// 使用しているライトを検索
int countLight; // ライトの個数
countLight = 0;
for( int counterLight = 0; counterLight < maximumDirection_; ++counterLight )
{
if( pLightDirection_[ counterLight ].IsUsed() && pLightDirection_[ counterLight ].IsEnable() )
{
if( countLight == index )
{
return &pLightDirection_[ counterLight ];
}
++countLight;
}
}
// 見つからなかった
PrintDebugWnd( _T( "有効なディレクショナルライトが見つかりませんでした。\n" ) );
return nullptr;
}
//==============================================================================
// Brief : 有効なポイントライトの取得
// Return : LightPoint* : ポイントライト
// Arg : int index : 番号
//==============================================================================
LightPoint* ManagerLight::GetLightPointEnable( int index )
{
// 使用しているライトを検索
int countLight; // ライトの個数
countLight = 0;
for( int counterLight = 0; counterLight < maximumPoint_; ++counterLight )
{
if( pLightPoint_[ counterLight ].IsUsed() && pLightPoint_[ counterLight ].IsEnable() )
{
if( countLight == index )
{
return &pLightPoint_[ counterLight ];
}
++countLight;
}
}
// 見つからなかった
PrintDebugWnd( _T( "有効なポイントライトが見つかりませんでした。\n" ) );
return nullptr;
}
//==============================================================================
// Brief : クラス内の初期化処理
// Return : void : なし
// Arg : void : なし
//==============================================================================
void ManagerLight::InitializeSelf( void )
{
// メンバ変数の初期化
maximumDirection_ = 0;
maximumPoint_ = 0;
pLightDirection_ = nullptr;
pLightPoint_ = nullptr;
}
|
20e4e7c07e52fff2504c568ff2ed49e9739b0e1d | 4cd0cbfb4f5b54ad8530ce06e218edb4b9a151ba | /QuadPrecision/precision_functions_test.cpp | ce2631b89e945b0dde76b70ae9f91b4749644ec7 | [] | no_license | ariana-bruno/ECE4960-PA1 | f97329f291eed8f639f002857dc3210785c2ce64 | 75d4ab893f7391aa926cef59075e9616226f2eaf | refs/heads/master | 2021-09-07T16:15:24.193487 | 2018-02-25T23:17:26 | 2018-02-25T23:17:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,168 | cpp | precision_functions_test.cpp | //
// precision_functions_test.cpp
// QuadPrecision
//
//
#include "precision_functions.hpp"
//Testing the addition of two double-precision values and returns "true" if the results match the
//given expected results, and returns "false" otherwise
bool test_addition(long double a, long double b, long double expected_result1, long double expected_result2){
//constructs the inputs to number structure
number num1 = construct_number(a);
number num2 = construct_number(b);
//calculates the addition result
result add = addition_precision(num1, num2);
//compares the addition result to expected values
if (comparison_error( expected_result1, add.most_significant.value) && comparison_error( expected_result2, add.least_significant.value)){
return true;
} else {
return false;
}
}
//Testing the subtraction of two double-precision values and returns "true" if the results match the
//given expected results, and returns "false" otherwise
bool test_subtraction(long double a, long double b, long double expected_result1, long double expected_result2){
//constructs the inputs to number structure
number num1 = construct_number(a);
number num2 = construct_number(b);
//calculates the addition result
result subtract = subtraction_precision(num1, num2);
//compares the addition result to expected values
if (comparison_error(expected_result1, subtract.most_significant.value) && comparison_error( expected_result2, subtract.least_significant.value)){
return true;
} else {
return false;
}
}
//Returns true or false is the expected value is equal to the result within 1e-16 precision error
bool comparison_error( long double expected_value, long double result ){
if ((expected_value == result) || (calculate_error( expected_value, result ) < 1e-16 )){
return true;
} else {
return false;
}
}
//Calculates the precision error between the expected and the result values
long double calculate_error( long double expected_value, long double result ){
return abs( expected_value - result )/expected_value;
}
|
14501391dba5ebaf5cabd23157dbaaf0d28542be | 3159d77c2fc0828025bd0fb6f5d95c91fcbf4cd5 | /cpp/memory_guard/test/main.cpp | a4092d236f0749203cd2c0718fd37581fe43a2a2 | [] | no_license | jcmana/playground | 50384f4489a23c3a3bb6083bc619e95bd20b17ea | 8cf9b9402d38184f1767c4683c6954ae63d818b8 | refs/heads/master | 2023-09-01T11:26:07.231711 | 2023-08-21T16:30:16 | 2023-08-21T16:30:16 | 152,144,627 | 1 | 0 | null | 2023-08-21T16:21:29 | 2018-10-08T20:47:39 | C++ | UTF-8 | C++ | false | false | 956 | cpp | main.cpp | #include <iostream>
#include <thread>
#include <mutex>
#include "../memory_guard/memory.hpp"
class threadsafe_provider
{
public:
auto size()
{
return m_value.get();
}
void increment()
{
m_value.get() = m_value.get() + 1;
}
void reset()
{
m_value.get() = 0;
}
private:
memory<int> m_value;
};
void main()
{
threadsafe_provider a;
a.reset();
std::cout << a.size() << std::endl;
auto thread_procedure = [&a]
{
for (unsigned int n = 0; n < 10; ++n)
{
a.increment();
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
};
std::thread thread(thread_procedure);
std::this_thread::sleep_for(std::chrono::milliseconds(300));
std::cout << a.size() << std::endl;
thread.join();
auto mga = a.size();
auto mgb = a.size();
threadsafe_provider a_moved;
a_moved = std::move(a);
}
|
be40f7a7cf0e8a836b39835556d7cf0aa2fb4d33 | 7d07d9669d9caaa77a2771ca3d43de10f8ccc794 | /lab6/lab65.cpp | ee420152d8e262a4c54a822d8f93a30b5187c653 | [] | no_license | divBaral/labsheet | ccecb1febd8d47ac9667b8ff1732d57e8d0a23fe | 95424f161e1857aba77e8eee21bd022ae2b4f2f9 | refs/heads/master | 2023-07-01T11:49:43.812344 | 2021-08-12T11:54:15 | 2021-08-12T11:54:15 | 376,901,081 | 0 | 1 | null | 2021-06-17T13:19:25 | 2021-06-14T17:14:15 | C | UTF-8 | C++ | false | false | 1,344 | cpp | lab65.cpp | /*Write a base class that asks the user to enter a complex number and make a derived class that adds the complex number of its own with the base. Finally, make a third class that is a friend of derived and calculate the difference of the base complex number and its own complex number.*/
#include <iostream>
using namespace std;
class complexSub;
class complex{
public:
float a;
float b;
void getData(){
cout << "Enter a complex number(a b): ";
cin >> a >> b;
}
void showData(){
cout << a << " + " << "(" << b << ")" << "j";
}
};
class complexAdd: public complex{
public:
void getData(){
complex::getData();
}
complex operator + (const complex c1){
complex temp;
temp.a = a + c1.a;
temp.b = b + c1.b;
return temp;
}
friend class complexSub;
};
class complexSub{
public:
static void getData(complexAdd& c1){
c1.getData();
}
static complex subtract(complexAdd c1, complex c2){
complex temp;
temp.a = c1.a - c2.a;
temp.b = c1.b - c2.b;
return temp;
}
};
int main(){
complex num1;
num1.getData();
complexAdd num2;
num2.getData();
cout << endl;
num2.showData(); cout << " + "; num1.showData();
cout << " = "; (num2 + num1).showData();
cout << endl;
num2.showData(); cout << " - "; num1.showData();
cout << " = "; complexSub::subtract(num2, num1).showData();
cout << endl;
return 0;
} |
0c3e6df6a873dc58bf219d5f7edc73d91ae95be1 | 4252011d891fad3a15864d3d141968d8e0c72251 | /derivada.cpp | 17d2e6f75acd7a64a7dd4f56f86150123a7deba0 | [] | no_license | giovannirosario/dim0404_calcnumerico | 19361c1143d6d7bbb229f5a90ef1e0e643524b7f | 57be8b17aa4457639a44d4155028fd844443a3f8 | refs/heads/master | 2020-04-23T21:19:51.551340 | 2019-03-21T02:50:49 | 2019-03-21T02:50:49 | 171,467,232 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 259 | cpp | derivada.cpp | #include <iostream>
#include <math.h>
#include <iomanip>
#define PI 3.14159265
double f (double x) {
return x * cos(x);
}
int main () {
for (double x = 2; x >= 1; x -= 0.01)
{
std::cout << std::fixed << std::setprecision(20) << f(x) << std::endl;
}
} |
8e7e8f71c9379f6ea971dde09d95f6035442482e | ca157d9be997af55dfa07796e41b7b8f5797f6d8 | /Binary Search/Infinite.cpp | 36b896ebdd214ad6aa5cf780e1413551c9ec012c | [] | permissive | abhishek2x/Algorithms | b47ef0e673f73dbdbb6910d5f665b59855dee144 | 0429a0284bce95b563e70c294fe1acf60da177a7 | refs/heads/master | 2022-03-20T17:05:46.711267 | 2022-02-27T06:16:33 | 2022-02-27T06:16:33 | 240,521,395 | 0 | 2 | MIT | 2020-10-31T13:15:58 | 2020-02-14T14:03:41 | C++ | UTF-8 | C++ | false | false | 699 | cpp | Infinite.cpp | /*!
* Copyright (c) 2020 Abhishek Srivastava
*/
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
int binaryPlay(vector<int> a, int l, int h, int key){
while(l<=h){
int mid = l + (h-l)/2;
if(a[mid] == key){
return mid;
} else if(a[mid] < key){
l = mid+1;
} else {
h = mid-1;
}
}
return -1;
}
int main(){
ios :: sync_with_stdio(false);
cin.tie(0);
vector<int> inf = {1, 2, 3, 4, 5, 6, 7 ,8 , 9, 10};
int key = 4;
int l = 0, h = 1, mid;
while(inf[h] < key){
h = h*2;
}
// cout << h << "\t";
cout << binaryPlay(inf, l, h, key);
return 0;
} |
0a8edb58521314e98b1f75442c6d077f9fa654b7 | 766b000c981a06ff263101161bbc63418bf609d0 | /include/model/encryption/encryption_rsa.hpp | 59428ceb50f22b9f9fdd06a31a6b494061f76c88 | [] | no_license | TransientTetra/safe_sender | 1b17903a7434f4ecd79dc7ef4e44ae9acca68f9a | 0ebd914875b8d2ad450c9612f5827ec871befbc0 | refs/heads/master | 2022-09-23T05:33:28.870995 | 2020-06-06T19:02:24 | 2020-06-06T19:02:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,106 | hpp | encryption_rsa.hpp | #ifndef SAFE_SENDER_ENCRYPTION_RSA_HPP
#define SAFE_SENDER_ENCRYPTION_RSA_HPP
#include "encryption.hpp"
#include <cryptopp/rsa.h>
#include <model/communication/communicator.hpp>
class EncryptionRSA : public Encryption
{
private:
CryptoPP::RSA::PrivateKey privateKey;
CryptoPP::RSA::PublicKey publicKey;
void saveKeysToFile(std::string privPath, std::string publPath);
void loadKeysFromFile(std::string privPath, std::string publPath);
protected:
public:
void encrypt(RawBytes &data) override;
void decrypt(RawBytes &data) override;
const CryptoPP::RSA::PrivateKey &getPrivateKey() const;
void setPrivateKey(const CryptoPP::RSA::PrivateKey &privateKey);
CryptoPP::RSA::PublicKey &getPublicKey();
void setPublicKey(const CryptoPP::RSA::PublicKey &publicKey);
void savePublicKey(std::string path);
void loadPublicKey(std::string path);
void encryptKeysToFile(std::string privPath, std::string publPath, EncryptionKey& key);
bool decryptKeysFromFile(std::string privPath, std::string publPath, EncryptionKey& key);
void generateKeyPair();
};
#endif //SAFE_SENDER_ENCRYPTION_RSA_HPP
|
3c0280505776d4caa316e46c3c446ff054cd6a43 | ea401c3e792a50364fe11f7cea0f35f99e8f4bde | /released_plugins/v3d_plugins/bigneuron_AmosSironi_PrzemyslawGlowacki_SQBTree_plugin/libs/boost_1_58_0/boost/detail/winapi/crypt.hpp | c9108f29bff7cc3a6e344b9bbebbf70bd644c879 | [
"MIT"
] | permissive | Vaa3D/vaa3d_tools | edb696aa3b9b59acaf83d6d27c6ae0a14bf75fe9 | e6974d5223ae70474efaa85e1253f5df1814fae8 | refs/heads/master | 2023-08-03T06:12:01.013752 | 2023-08-02T07:26:01 | 2023-08-02T07:26:01 | 50,527,925 | 107 | 86 | MIT | 2023-05-22T23:43:48 | 2016-01-27T18:19:17 | C++ | UTF-8 | C++ | false | false | 2,214 | hpp | crypt.hpp | // crypt.hpp --------------------------------------------------------------//
// Copyright 2014 Antony Polukhin
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
#ifndef BOOST_DETAIL_WINAPI_CRYPT_HPP
#define BOOST_DETAIL_WINAPI_CRYPT_HPP
#include <boost/detail/winapi/basic_types.hpp>
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
namespace boost
{
namespace detail
{
namespace winapi
{
#if defined( BOOST_USE_WINDOWS_H )
typedef HCRYPTPROV HCRYPTPROV_;
using ::CryptEnumProvidersA;
using ::CryptAcquireContextA;
using ::CryptGenRandom;
using ::CryptReleaseContext;
const DWORD_ PROV_RSA_FULL_ = PROV_RSA_FULL;
const DWORD_ CRYPT_VERIFYCONTEXT_ = CRYPT_VERIFYCONTEXT;
const DWORD_ CRYPT_NEWKEYSET_ = CRYPT_NEWKEYSET;
const DWORD_ CRYPT_DELETEKEYSET_ = CRYPT_DELETEKEYSET;
const DWORD_ CRYPT_MACHINE_KEYSET_ = CRYPT_MACHINE_KEYSET;
const DWORD_ CRYPT_SILENT_ = CRYPT_SILENT;
#else
extern "C" {
typedef ULONG_PTR_ HCRYPTPROV_;
__declspec(dllimport) BOOL_ __stdcall
CryptEnumProvidersA(
DWORD_ dwIndex,
DWORD_ *pdwReserved,
DWORD_ dwFlags,
DWORD_ *pdwProvType,
LPSTR_ szProvName,
DWORD_ *pcbProvName
);
__declspec(dllimport) BOOL_ __stdcall
CryptAcquireContextA(
HCRYPTPROV_ *phProv,
LPCSTR_ pszContainer,
LPCSTR_ pszProvider,
DWORD_ dwProvType,
DWORD_ dwFlags
);
__declspec(dllimport) BOOL_ __stdcall
CryptGenRandom(
HCRYPTPROV_ hProv,
DWORD_ dwLen,
BYTE_ *pbBuffer
);
__declspec(dllimport) BOOL_ __stdcall
CryptReleaseContext(
HCRYPTPROV_ hProv,
DWORD_ dwFlags
);
const DWORD_ PROV_RSA_FULL_ = 1;
const DWORD_ CRYPT_VERIFYCONTEXT_ = 0xF0000000;
const DWORD_ CRYPT_NEWKEYSET_ = 8;
const DWORD_ CRYPT_DELETEKEYSET_ = 16;
const DWORD_ CRYPT_MACHINE_KEYSET_ = 32;
const DWORD_ CRYPT_SILENT_ = 64;
}
#endif
}
}
}
#endif // BOOST_DETAIL_WINAPI_CRYPT_HPP
|
b809e37e4eac05c8b09575bb118edd3f82a2509b | 556861de6b08e4f26ba66d9a2b0801ae585f51f8 | /ListNode.hpp | 030802dc24faffcd415b69e7c0c9b820ce42bbbd | [] | no_license | darklam/syspro-hw2 | d2345f4d369637226ec1a260dd5724c0d641f7e1 | 9122835c499ca74e3263aa13cf300c63dc8f267b | refs/heads/master | 2020-05-03T00:04:37.612876 | 2019-04-09T21:35:38 | 2019-04-09T21:35:38 | 178,299,417 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 581 | hpp | ListNode.hpp | #ifndef LIST_NODE_H
#define LIST_NODE_H
#include <cstdlib>
template<class T>
class ListNode {
private:
T value;
ListNode<T>* next;
public:
ListNode<T>* getNext() {
return this->next;
}
void addNext(T value) {
this->next = new ListNode<T>(value);
}
void setNext(ListNode<T>* next) {
this->next = next;
}
ListNode(T value) {
this->next = NULL;
this->value = value;
}
T getValue() {
return this->value;
}
void setValue(T value) {
this->value = value;
}
};
#endif
|
19ad42396b1b4ae7ef2c875f973e8af8eee8c121 | 1eaf26e8cfc8a8eabe2e372f2e6c6a190cc8e85d | /lz/compiler/grammar_design.h | 7e8cd6605bbefb52512d167961bae3be8c2bf1b3 | [] | no_license | liuzhuocpp/algorithm | b31931fe034b24d9aeb8e119198341d91c70cce1 | 151d9ea55c214f6fff3c40629e48a1baae9c9ad7 | refs/heads/master | 2020-12-18T22:14:09.453723 | 2017-06-21T07:36:04 | 2017-06-21T07:36:04 | 28,743,281 | 14 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,524 | h | grammar_design.h | /*
* grammar_design.h
*
* Created on: 2017年2月28日
* Author: LZ
*/
#ifndef LZ_COMPILER_GRAMMAR_DESIGN_H_
#define LZ_COMPILER_GRAMMAR_DESIGN_H_
/*
*
包含了一些对文法重新设计、改造的算法,包括 计算first集、follow集,消除左递归,提取左公共因子
*/
#include <lz/compiler/grammar.h>
namespace lz {
using Set = std::set<SymbolDescriptor>;
template<typename InputIterator>
Set calculateRuleBodyFirstSet(InputIterator ruleBodyBegin, InputIterator ruleBodyEnd,
const std::vector<Set>& nonterminalsFirstSet);
template<typename Grammar>
std::vector<Set> calculateFirstSets(const Grammar& g)
{
std::vector<Set> ans(g.nonterminalsNumber());
while(true)
{
bool hasNew = 0;
for(auto rd: g.rules())
{
auto ruleSymbolRange = g.ruleSymbols(rd);
auto head = *ruleSymbolRange.first;
auto ruleBodyFirstSet = calculateRuleBodyFirstSet(++ruleSymbolRange.first, ruleSymbolRange.second, ans);
auto oldSize = ans[head].size();
ans[head].insert(ruleBodyFirstSet.begin(), ruleBodyFirstSet.end());
if(ans[head].size() > oldSize) hasNew = 1;
}
if(!hasNew) break;
}
return ans;
}
template<typename Iterator>
Set calculateRuleBodyFirstSet(
Iterator ruleBodyBegin,
Iterator ruleBodyEnd,
const std::vector<Set>& firstSets)
{
Set ans;
bool allHasEmptyString = 1;
for(auto s: lz::makeIteratorRange(ruleBodyBegin, ruleBodyEnd))
{
if(isNonterminal(s))
{
ans.insert(firstSets[s].begin(), firstSets[s].end());
if(!firstSets[s].count(EmptyStringSymbol))
{
allHasEmptyString = 0;
break;
}
else ans.erase(EmptyStringSymbol);
}
else if(isTerminal(s))
{
ans.insert(s);
allHasEmptyString = 0;
break;
}
else // error
{}
}
if(allHasEmptyString) ans.insert(EmptyStringSymbol);
return ans;
}
template<typename Grammar>
std::vector<Set> calculateFollowSets(
const Grammar& g,
const std::vector<Set>& firstSets,
SymbolDescriptor startSymbol = 0)
{
std::vector<Set> ans(g.nonterminalsNumber());
ans[startSymbol].insert(EndTagSymbol);
while(true)
{
bool hasNew = 0;
for(auto rd: g.rules())
{
auto ruleSymbolRange = g.ruleSymbols(rd);
auto head = *ruleSymbolRange.first ++;
for(auto it = ruleSymbolRange.first ; it != ruleSymbolRange.second; ++ it)
{
auto s = *it;
if(isNonterminal(s))
{
Set::size_type oldSize = ans[s].size();
auto nextIt = it;
auto backFirstSet = calculateRuleBodyFirstSet(++nextIt, ruleSymbolRange.second, firstSets);
ans[s].insert(backFirstSet.begin(), backFirstSet.end());
if(backFirstSet.count(EmptyStringSymbol))
{
ans[s].erase(EmptyStringSymbol);
ans[s].insert(ans[head].begin(), ans[head].end());
}
if(ans[s].size() > oldSize) hasNew = 1;
}
}
}
if(!hasNew) break;
}
return ans;
}
} // namespace lz
#endif /* LZ_COMPILER_GRAMMAR_DESIGN_H_ */
|
c6602a92e2e2bd976ec657a1cdb1adadb57b2bb3 | 4e8635a0c3f02237e80173c4b9a8b8b2f8b10570 | /Assignment-4/POPServerSession.hxx | 4656b30c182391147f1a3df756a1c2d8be9c5720 | [] | no_license | ravibansal/Networks-Lab-Assignments | 04c06ef8e65955ce7f183adb9290a82e18997efc | b2ed9aba9e99aadd2f67aee244a615097f799811 | refs/heads/master | 2020-06-14T06:35:17.589350 | 2016-11-30T20:20:54 | 2016-11-30T20:20:54 | 75,222,486 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,221 | hxx | POPServerSession.hxx | #ifndef __POPSERVERSESSIONHXX__
#define __POPSERVERSESIONHXX__
#include <string>
#include <iostream>
#include <vector>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <sys/socket.h> // For the socket (), bind () etc. functions.
#include <netinet/in.h> // For IPv4 data struct..
#include <arpa/inet.h> // For inet_pton (), inet_ntop ().
#include <errno.h>
#include "sql.h"
using namespace std;
#define AUTHORIZATION 1
#define TRANSACTION 2
#define UPDATE 3
#define ERR 0
#define OK 1
class POPServerSession
{
static const int BUFFSIZE = 512;
int socketfd;
int state;
string hostname;
string msg;
string username;
sql::Connection* conn;
int userid;
vector< pair<int,double> > msglist;
vector<int> to_delete;
set<int> read;
public:
POPServerSession(int socketfd,string hostname);
~POPServerSession();
int sendResponse(int type, string message="");
int processCMD(string buf);
protected:
int processUSER(string buf);
int processPASS(string buf);
int processLIST(string buf);
int processSTAT(string buf);
int processRETR(string buf);
int processQUIT(string buf);
int processDELE(string buf);
private:
int sendMessage(string msg, int status=-1);
};
#endif
|
bc40b8d24322cfeb7de80e60ad23a6e4db2b790c | 182adfdfa907d3efc0395e293dcdbc46898d88eb | /Temp/il2cppOutput/il2cppOutput/AssemblyU2DCSharpU2Dfirstpass_AN_DeviceCodeResult3529581718.h | e0b4e4ef8378cd8f05d8c36d4de65c7e085578f1 | [] | no_license | Launchable/1.1.3New | d1962418cd7fa184300c62ebfd377630a39bd785 | 625374fae90e8339cec0007d4d7202328bfa03d9 | refs/heads/master | 2021-01-19T07:40:29.930695 | 2017-09-15T17:20:45 | 2017-09-15T17:20:45 | 100,642,705 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,046 | h | AssemblyU2DCSharpU2Dfirstpass_AN_DeviceCodeResult3529581718.h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "AssemblyU2DCSharpU2Dfirstpass_SA_Common_Models_Res4287219743.h"
// System.String
struct String_t;
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// AN_DeviceCodeResult
struct AN_DeviceCodeResult_t3529581718 : public Result_t4287219743
{
public:
// System.String AN_DeviceCodeResult::_deviceCode
String_t* ____deviceCode_1;
// System.String AN_DeviceCodeResult::_userCode
String_t* ____userCode_2;
// System.String AN_DeviceCodeResult::_verificationUrl
String_t* ____verificationUrl_3;
// System.Int64 AN_DeviceCodeResult::_expiresIn
int64_t ____expiresIn_4;
// System.Int64 AN_DeviceCodeResult::_interval
int64_t ____interval_5;
public:
inline static int32_t get_offset_of__deviceCode_1() { return static_cast<int32_t>(offsetof(AN_DeviceCodeResult_t3529581718, ____deviceCode_1)); }
inline String_t* get__deviceCode_1() const { return ____deviceCode_1; }
inline String_t** get_address_of__deviceCode_1() { return &____deviceCode_1; }
inline void set__deviceCode_1(String_t* value)
{
____deviceCode_1 = value;
Il2CppCodeGenWriteBarrier(&____deviceCode_1, value);
}
inline static int32_t get_offset_of__userCode_2() { return static_cast<int32_t>(offsetof(AN_DeviceCodeResult_t3529581718, ____userCode_2)); }
inline String_t* get__userCode_2() const { return ____userCode_2; }
inline String_t** get_address_of__userCode_2() { return &____userCode_2; }
inline void set__userCode_2(String_t* value)
{
____userCode_2 = value;
Il2CppCodeGenWriteBarrier(&____userCode_2, value);
}
inline static int32_t get_offset_of__verificationUrl_3() { return static_cast<int32_t>(offsetof(AN_DeviceCodeResult_t3529581718, ____verificationUrl_3)); }
inline String_t* get__verificationUrl_3() const { return ____verificationUrl_3; }
inline String_t** get_address_of__verificationUrl_3() { return &____verificationUrl_3; }
inline void set__verificationUrl_3(String_t* value)
{
____verificationUrl_3 = value;
Il2CppCodeGenWriteBarrier(&____verificationUrl_3, value);
}
inline static int32_t get_offset_of__expiresIn_4() { return static_cast<int32_t>(offsetof(AN_DeviceCodeResult_t3529581718, ____expiresIn_4)); }
inline int64_t get__expiresIn_4() const { return ____expiresIn_4; }
inline int64_t* get_address_of__expiresIn_4() { return &____expiresIn_4; }
inline void set__expiresIn_4(int64_t value)
{
____expiresIn_4 = value;
}
inline static int32_t get_offset_of__interval_5() { return static_cast<int32_t>(offsetof(AN_DeviceCodeResult_t3529581718, ____interval_5)); }
inline int64_t get__interval_5() const { return ____interval_5; }
inline int64_t* get_address_of__interval_5() { return &____interval_5; }
inline void set__interval_5(int64_t value)
{
____interval_5 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
|
ddfb68652b7a694bbf91500615594cee8e882636 | c9ea4b7d00be3092b91bf157026117bf2c7a77d7 | /比赛/校内/NOIP模拟试题/201811080800(40)[NOILinux]/TEST/2.cpp | 29fd23a727302d592c425d1d18c9770fd33e24e9 | [] | no_license | Jerry-Terrasse/Programming | dc39db2259c028d45c58304e8f29b2116eef4bfd | a59a23259d34a14e38a7d4c8c4d6c2b87a91574c | refs/heads/master | 2020-04-12T08:31:48.429416 | 2019-04-20T00:32:55 | 2019-04-20T00:32:55 | 162,387,499 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 862 | cpp | 2.cpp | #include<iostream>
#include<cstdio>
#include<set>
using namespace std;
#define ri register int
#define rc register char
#define N 100100
set<int> S[N];
int n,m,d,g;
int a[N];
int ans[N];
inline int read(){
ri res=0;
rc c=getchar();
for(;c<'0' || c>'9';c=getchar());
for(;c>='0' && c<='9';c=getchar())
res=(res<<3)+(res<<1)+(c^'0');
return res;
}
void write(const int& x){
if(x>9)
write(x/10);
putchar(x%10^'0');
}
int main(){
n=read(),m=read();
for(ri i=1;i<n;i++)
a[i]=read();
for(ri i=1;i<=m;i++){
g=read(),d=read();
for(ri j=g;j;j=a[j])
if(!S[j].count(d)){
ans[j]++;
S[j].insert(d);
}
else
break;
if(!S[0].count(d)){
ans[0]++;
S[0].insert(d);
}
}
for(ri i=0;i<n;i++){
write(ans[i]);
puts("");
}
return 0;
}
/*
5 4
0
0
1
1
4 1
3 1
2 2
4 2
*/
|
800fa7b8520765d6d89d1ae7b53ef5649e580596 | d30bf8d4b67f903023756bf43bab8801653af1e8 | /include/win/windows_console_terminal.hpp | e15474471ef2d1d732002d9e4ad19ea7b8356b49 | [] | no_license | incoder1/cppcurses | 7c9deaef71b3f26e502d9c928c2817a0f33ca5ae | 0faa02c33e050a080dd748cf25e28f98eb540ffd | refs/heads/master | 2016-08-10T21:26:24.065610 | 2016-04-08T18:44:17 | 2016-04-08T18:44:54 | 50,059,008 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,593 | hpp | windows_console_terminal.hpp | #ifndef __WINDOWS_CONSOLE_TERMINAL_HPP_INCLUDED__
#define __WINDOWS_CONSOLE_TERMINAL_HPP_INCLUDED__
#if !defined(UNICODE) && !defined(_UNICODE)
# error Windows Implementation requares Unicode
#endif // unicode check
#include <assert.h>
#include <cstdlib>
#include <windows.h>
#include "../basic_terminal_spec.hpp"
namespace curses {
enum color: uint8_t {
BLACK = 0x0,
NAVY_BLUE = 0x1,
NAVY_GREEN = 0x2,
NAVY_AQUA = 0x3,
NAVY_RED = 0x4,
NAVY_PURPLE = 0x5,
NAVY_YELLOW = 0x6,
WHITE = 0x7,
GREY = 0x8,
LIGHT_BLUE = 0x9,
LIGHT_GREEN = 0xA,
LIGHT_AQUA = 0xB,
LIGHT_RED = 0xC,
LIGHT_PURPLE = 0xD,
LIGHT_YELLOW = 0xE,
BRIGHT_WHITE = 0xF
};
typedef basic_texel<::TCHAR,::WORD> texel;
typedef basic_text_color<uint8_t> text_color;
namespace win {
class terminal:public basic_terminal<texel, text_color, terminal>, public virtual object {
public:
explicit terminal():
hStdOut_(INVALID_HANDLE_VALUE),
hStdIn_(INVALID_HANDLE_VALUE),
hCons_(INVALID_HANDLE_VALUE)
{
hStdOut_ = ::GetStdHandle(STD_OUTPUT_HANDLE);
assert(INVALID_HANDLE_VALUE != hStdOut_);
hStdIn_ = ::GetStdHandle(STD_INPUT_HANDLE);
assert(INVALID_HANDLE_VALUE != hStdIn_);
::SetConsoleCP(1200); // UTF16LE
hCons_ = ::CreateConsoleScreenBuffer(
GENERIC_READ | GENERIC_WRITE,// read/write access
FILE_SHARE_READ | FILE_SHARE_WRITE,// shared
NULL,// default security attributes
CONSOLE_TEXTMODE_BUFFER, // must be TEXTMODE
NULL);
assert(INVALID_HANDLE_VALUE != hCons_);
::DWORD ec = ::SetConsoleActiveScreenBuffer(hCons_);
assert(ec);
assert(::SetConsoleMode(hStdIn_, ENABLE_WINDOW_INPUT | ENABLE_MOUSE_INPUT));
}
virtual ~terminal() CURSES_NOEXCEPT {
::DWORD ec = ::SetConsoleActiveScreenBuffer(hStdOut_);
assert(ec);
::CloseHandle(hCons_);
}
bounds get_bounds() const {
::CONSOLE_SCREEN_BUFFER_INFO info;
::GetConsoleScreenBufferInfo(hCons_,&info);
return bounds(info.srWindow.Right+1,info.srWindow.Bottom+1);
}
void set_size(uint8_t width, uint8_t height) const {
::SMALL_RECT sr;
sr.Left = 0;
sr.Top = 0;
sr.Right = width;
sr.Bottom = height;
::SetConsoleWindowInfo(hCons_,TRUE,&sr);
}
void putch(const position& pos,char_t ch) const
{
put_line(pos,ch,1);
}
void put_line(const position& pos,char_t ch, uint8_t count) const
{
::DWORD written = 0;
::COORD coord;
coord.X = pos.x;
coord.Y = pos.y;
::FillConsoleOutputCharacter(hCons_, ch, count, coord, &written);
assert(written);
attrs_t attrs = current_attributes();
::FillConsoleOutputAttribute(hCons_, attrs, count, coord, &written);
assert(written);
}
uint8_t put_text(const position& pos, const char_t* str) const {
char_t *it = const_cast<char_t*>(str);
position outp = pos;
uint8_t result = 0;
do {
putch(outp,*it);
++outp.x;
++it;
++result;
} while(*it != 0);
return result;
}
void fill_rectangle(const rectangle& r,char_t ch) const {
position pos = r.left_top();
bounds bds = r.get_bounds();
uint8_t count = bds.width;
uint8_t lines = r.left() + bds.height;
for(uint8_t y = r.top(); y < lines; y++ ) {
pos.y = y;
put_line(pos,ch,count);
}
}
attrs_t make_attrs(const text_color& color) const {
return (color.background << 4) | color.foreground;
}
void set_out_attrs(attrs_t attrs) const {
::SetConsoleTextAttribute(hCons_, attrs);
}
attrs_t current_attributes() const
{
::CONSOLE_SCREEN_BUFFER_INFO info;
::GetConsoleScreenBufferInfo(hCons_,&info);
return info.wAttributes;
}
void clipt_rect(const rectangle& rect,texel_type* buff) const
{
::COORD coordBufCoord;
coordBufCoord.X = 0;
coordBufCoord.Y = 0;
bounds bds = rect.get_bounds();
::COORD coordBufSize;
coordBufSize.X = bds.width;
coordBufSize.Y = bds.height;
::SMALL_RECT sr;
sr.Left = rect.left();
sr.Top = rect.top();
sr.Right = rect.right();
sr.Bottom = rect.bottom();
CHAR_INFO *chiBuffer = reinterpret_cast<CHAR_INFO*>(buff);
::BOOL fSuccess = ::ReadConsoleOutputW(
hCons_, // screen buffer to read from
chiBuffer, // buffer to copy into
coordBufSize, // col-row size of chiBuffer
coordBufCoord, // top left dest. cell in chiBuffer
&sr); // screen buffer source rectangle
assert(fSuccess);
}
void paste_rect(const rectangle& rect, texel_type* data) const
{
::COORD coordBufCoord;
coordBufCoord.X = 0;
coordBufCoord.Y = 0;
bounds bds = rect.get_bounds();
::COORD coordBufSize;
coordBufSize.X = bds.width;
coordBufSize.Y = bds.height;
::SMALL_RECT sr;
sr.Left = rect.left();
sr.Top = rect.top();
sr.Right = rect.right();
sr.Bottom = rect.bottom();
::CHAR_INFO *chiBuffer = reinterpret_cast<::CHAR_INFO*>(data);
::BOOL fSuccess = ::WriteConsoleOutputW(
hCons_, // screen buffer to write to
chiBuffer, // buffer to copy from
coordBufSize, // col-row size of chiBuffer
coordBufCoord, // top left src cell in chiBuffer
&sr); // dest. screen buffer rectangle
assert(fSuccess);
}
private:
::HANDLE hStdOut_;
::HANDLE hStdIn_;
::HANDLE hCons_;
};
} // namespace win
// define the texel and terminal types
typedef win::terminal terminal;
CURSES_DECLARE_SPTR(terminal);
} // namesapce curses
#endif // __WINDOWS_CONSOLE_TERMINAL_HPP_INCLUDED__
|
2ca4c0a2f13ac794d41e14c3ded60a719211bbf5 | 1e14ecf45543da3b02187d1414e613ac8f2ace20 | /array/smallest_subarray_sum_greaterthenx.cpp | b0951fba23a4d40535a226a581c945681edca04a | [] | no_license | nimit1jain/DSA-Questions | 7bdb32f7745858bba0d42d3cc9902236a68d802d | 748365d62c7c0032bc6f608ecbe4d23c5568ea67 | refs/heads/master | 2023-07-27T07:28:57.131907 | 2021-09-06T11:05:00 | 2021-09-06T11:05:00 | 384,985,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 489 | cpp | smallest_subarray_sum_greaterthenx.cpp | #include<iostream>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"enter the value of X ";
int x;
cin>>x;
int i=0;int j=0;
int mind=INT_MAX;
int sum=0;
while(i<=j&&j<n)
{
while(sum<=x&&j<n){
sum=sum+arr[j++];
}
while(sum>x&&i<j){
mind=min(mind,j-i);
sum=sum-arr[i];
i++;
}
}
cout<<mind<<endl;
return 0;
} |
4f2a5999295d600c76606fb9f3d3533784cc4c8e | 5e26f1899b7e9118e732209774626d8a3972dfd1 | /Driver.h | e5e39187e7ea8bfa0e1da29d9b19ef1368e3525e | [] | no_license | RDamman/SpeakerWorkshop | b33313c1fa51eb342922ecb4c837eb5a24790bd8 | 87a38d04197a07a9a7878b3f60d5e0706782163c | refs/heads/master | 2021-01-20T21:35:09.932108 | 2019-01-14T11:47:23 | 2019-01-14T11:47:23 | 101,771,745 | 15 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 4,548 | h | Driver.h | // Named.h : Named Components Class
//
/////////////////////////////////////////////////////////////////////////////
#ifndef CDRIVERH
#include "Xform.h"
typedef enum tagenResponse
{
rsResponse = 0, // response curve
rsImpedance = 1, // impedance
rsFreeAir = 2, // impedance in free air
rsSealed = 3, // sealed box impedance
rsAddMass = 4, // added mass method
rsTimeRes = 5, // time/pulse response (not required)
rsNearField = 6, // nearfield response
rsFreq30 = 7, // 30 degrees response
rsFreq60 = 8, // 60 degrees response
rsGated = 9, // gated
rsPort = 10 // port response
} enResponse;
typedef struct tagDriveparm
{
// ----------- calculated
float fFs; // Resonant frequency
float fLe; // inductance
float fQms; // mechanical Q
float fQes; // electrical Q
float fQts; // total Q
float fRe; // dc resistance
float fVas; // effective compliance
// ----------- provided
// float fDiameter; // diameter
float fPistonArea; // effective piston area
float fXmax; // maximum excursion
float fSensitivity; // sensitivity in w/m
float fVolume; // volume of sealed box
float fMass; // added mass
float fDCRes; // DC resistance???
BOOL bUseDC; // user has supplied DC resistance
BOOL bUseMass; // use added mass method
float fBL; // motor strength of driver
float fPe; // maximum power input
// ----------- now the datasets
DWORD dwResponse; // response curve
DWORD dwImpedance; // impedance
DWORD dwFreeAir; // impedance in free air
DWORD dwSealed; // sealed box impedance
DWORD dwAddMass; // added mass method
DWORD dwTimeRes; // time/pulse response (not required)
DWORD dwNearField; // nearfield response
DWORD dwFreq30; // 30 degrees response
DWORD dwFreq60; // 60 degrees response
DWORD dwGated; // gated frequency response
DWORD dwPort; // the port frequency response
} DRIVEPARM;
// driver equivalent circuit
// see speaker builder 5/94
// -Re-+-L1a--+-L1b--+--+--+
// |-R1---| | | |
// R2 L2 C2
// | | |
// ------------------+--+--+
typedef struct tagDriveequiv
{
double fRe;
double fL1a;
double fR1;
double fL1b;
double fR2;
double fL2;
double fC2;
} DRIVEEQUIV;
class CDriver : public CGraphed
{
protected: // create from serialization only
DECLARE_SERIAL(CDriver)
// Attributes
protected:
DRIVEPARM m_DP;
DRIVEEQUIV m_DEq;
// dialog info
// Operations
public:
CDriver();
virtual int EditProperties(CWnd *pWnd, CObject *cSubject = NULL); // bring up properties dbox
virtual BOOL CreateChart( CNamed *cBase = NULL); // build a new chart object to be graphed
const DRIVEPARM *GetDriverParameters() { return &m_DP; }
void SetDriverParameters( DRIVEPARM *pDP) { m_DP = *pDP; }
const DRIVEEQUIV *GetDriverEquiv() { return &m_DEq; }
void SetDriverEquiv( DRIVEEQUIV *pDP) { m_DEq = *pDP; }
DWORD GetImpedance() { return m_DP.dwImpedance; }
DWORD GetResponse() { return m_DP.dwResponse; }
DWORD GetResponse(int nWhich);
void SetResponse( int nWhich, DWORD dwNew);
int ValidateResponse( int nWhich); // make sure response is valid
void ValidateCurves(void ); // make sure all curves are valid
DWORD GetSealed() { return m_DP.dwSealed; }
DWORD GetAddMass() { return m_DP.dwAddMass; }
DWORD GetFreeAir() { return m_DP.dwFreeAir; }
DWORD GetTimeResponse() { return m_DP.dwTimeRes; }
int CalculateDriverParameters(CDataSet *cDest, bool bDoFree ); // calc thiele stuff and return .estimate
int CalculateDriverParameters(CDataSet *cDest, bool bDoFree , float fStart, float fEnd ); // windowed
void ConvertDQtoDP( DRIVEPARM &DP, DRIVEEQUIV &DQ);
int UseDriverEquiv(CDataSet *cDest, DRIVEEQUIV &DQ ); // calc thiele stuff and return .estimate
virtual int Import(CString sFile); // import some data
virtual int Export(CString sFile); // export some data
virtual void GetFilter(CString& csExt, CString& csFilter);
private:
// Implementation
public:
virtual ~CDriver();
virtual void Serialize(CArchive& ar); // overridden for Named i/o
virtual NAMETYPES GetType(void) const { return ntDriver; }
virtual CNamed *Duplicate(); // make a duplicate object (different id)
CNamed &operator=(const CNamed &cIn);
CDriver &operator=(const CDriver &cIn);
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
};
#define CDRIVERH
#endif
|
6b2919b758140ebfa1c665cd328fee8268188311 | 231b764548636ad7b05a1d4db85ce14e7a23dd87 | /AT-Task3-OpenGL/VoxelLevelLoader.h | f8ec8ca737413d6c1d924d65176fb830a60a654f | [
"MIT"
] | permissive | gualtyphone/AT-Task3-OpenGL | 7cf843b39573d8c83b4801935dd873be3a65f5ac | b14461f71b1766882082cd1481d21bd00f49cdb5 | refs/heads/master | 2021-04-29T17:41:28.810667 | 2018-04-10T00:09:58 | 2018-04-10T00:09:58 | 121,670,597 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,795 | h | VoxelLevelLoader.h | #pragma once
#include "GMath.h"
#include <vector>
#include "VoxelData.h"
#include "VoxelRenderer.h"
#include "Random.h"
#include "Transform.h"
#include "GameObject.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include "AntTweakBar\AntTweakBar.h"
#include "LevelExpander.h"
using namespace GMath;
class Pair
{
public:
Pair(Vector4 color, int block)
{
selectColor = color;
correspondingCube = block;
}
Vector4 selectColor;
int correspondingCube;
};
class VoxelLevelLoader : public GameObject
{
public:
VoxelLevelLoader(std::string filename, Shader* shader, Texture* text);
~VoxelLevelLoader();
virtual void Update() override;
virtual void Draw() override;
// Initialization
void Start(std::string filename, Shader* shader, Texture* text);
void LoadChunks();
void UpdateAllChunks();
// Simpler world creation
void CreateWorld(int width, int height);
void CreateBaseLayer(int width);
void OneStepSmoothing(int previousLayer, int width, int height, int direction);
// Utils
void setBlock(Vector3 pos, int blockType);
int getBlock(Vector3 pos);
int getFloorLevel(int x, int z);
inline void clearMesh()
{
for (int i = 0; i < chunks.size(); i++)
{
for (int x = 0; x < chunks[i]->width; x++)
{
for (int y = 0; y < chunks[i]->height; y++)
{
for (int z = 0; z < chunks[i]->depth; z++)
{
chunks[i]->SetCell(Vector3Int(x, y, z), 0);
}
}
}
}
}
public:
//TwBar * voxelBar;
unsigned char* pixels;
int texWidth;
int texHeight;
std::vector<Pair*> mapBlocks;
int depth = 10;
std::vector<VoxelData*> chunks;
std::vector<VoxelRender*> chunkRenderers;
int chunkWidth;
int chunkHeight;
int chunkDepth;
Texture* baseTex;
Shader* baseShader;
unsigned int seed;
LevelExpander* levelExpander;
}; |
8a7c86293a5326d31416d6ee667432b39e371993 | e154a67d426c97c328b0c97882572fbfc7d02010 | /SpiralMatrix.cpp | 3dd4925a0dda90244e2c58927742fe87ee6a9217 | [] | no_license | TopHK/LeetCode-Mine | 261a77aa850317d71d4763e5fdd095bc8824ca44 | aeae6012ac31440a1172019cbd2cf648cf68a9d5 | refs/heads/master | 2021-03-12T21:50:31.944604 | 2015-08-19T03:14:54 | 2015-08-19T03:14:54 | 41,009,431 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,486 | cpp | SpiralMatrix.cpp | /*************************************************************************
> File Name: SpiralMatrix.cpp
> Author:
> Mail:
> Created Time: 2015年07月04日 星期六 16时10分36秒
************************************************************************/
#include<iostream>
#include<vector>
using namespace std;
void spiralOrderCore(const vector<vector<int> >& matrix, int row, int col, const int& rows, const int& cols, vector<int>& result)
{
int leftTopX = row;
int leftTopY = col;
int rightTopX = row;
int rightTopY = cols-col-1;
int leftBottomX = rows-row-1;
int leftBottomY = col;
int rightBottomX = rows-row-1;
int rightBottomY = cols-col-1;
if(rightTopY > leftTopY)
{
// left to right in the top row
for(int j=leftTopY; j<=rightTopY; ++j)
result.push_back(matrix[leftTopX][j]);
if(rightTopX < rightBottomX)
{
for(int i=rightTopX+1; i<=rightBottomX; ++i)
result.push_back(matrix[i][rightTopY]);
for(int j=rightBottomY-1; j>=leftBottomY; --j)
result.push_back(matrix[leftBottomX][j]);
if(leftBottomX-leftTopX > 1)
{
for(int i=leftBottomX-1; i>=leftTopX+1; --i)
result.push_back(matrix[i][leftTopY]);
}
}
}
else
{
for(int i=leftTopX; i<=leftBottomX; ++i)
result.push_back(matrix[i][leftTopY]);
return;
}
}
vector<int> spiralOrder(vector<vector<int> >& matrix)
{
vector<int> result;
if(matrix.empty()) return result;
int rows = matrix.size();
int cols = matrix[0].size();
int row = 0;
int col = 0;
while(row<((rows+1)>>1) && col<((cols+1)>>1))
{
spiralOrderCore(matrix, row, col, rows, cols, result);
row++;
col++;
}
return result;
}
void print(const vector<int>& matrix)
{
for(int i=0; i<matrix.size(); ++i)
cout<<matrix[i]<<" ";
cout<<endl;
}
int main()
{
int arr1[] = {1, 2, 3};
vector<int> vec1(arr1, arr1+sizeof(arr1)/sizeof(int));
int arr2[] = {4, 5, 6};
vector<int> vec2(arr2, arr2+sizeof(arr2)/sizeof(int));
int arr3[] = {7, 8, 9};
vector<int> vec3(arr3, arr3+sizeof(arr3)/sizeof(int));
vector<vector<int> > matrix;
matrix.push_back(vec1);
matrix.push_back(vec2);
matrix.push_back(vec3);
vector<int> result = spiralOrder(matrix);
print(result);
return 0;
}
|
455c2c1dba8815f1a17106f55542270264a45e22 | f36a7c61f8334c3395eee541aa3b76a2e82549a6 | /image/format/JPEGimage.h | 8e39e450846ee850591b72908955845025eeba6c | [] | no_license | jeinne/ImageProcessing | 8004658942eb23a2adf2000255e1c2ecd707a6c4 | 9d7f698d248676f9d5d775e2633db80a308a2a0c | refs/heads/master | 2023-03-15T13:17:16.439492 | 2017-11-09T06:57:21 | 2017-11-09T06:57:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 725 | h | JPEGimage.h | #ifndef _JPEG_IMAGE_H_
#define _JPEG_IMAGE_H_
#include "../image.h"
#include "../imageRaster.h"
#include <stdio.h>
#include "jpeglib.h"
namespace IMAGE {
class JPEGimage : public Image {
private:
JPEGimage( const JPEGimage& );
JPEGimage& operator= ( const JPEGimage& ) { return *this; }
FILE* imageFile_m;
#ifdef DEBUG
static AutoCounter<JPEGimage> counter;
#endif
public:
JPEGimage() throw();
~JPEGimage() throw();
void open( const std::string& , const char ) throw( IMAGE::file_io_failed );
void close();
void readImageRaster() throw( IMAGE::bad_alloc , IMAGE::empty_image );
void writeRasterToImage() throw( IMAGE::empty_raster );
};//and of class JPEGimage
}//end of namespace IMAGE
#endif
|
bfca34cf0d6197a02814679344a63679fe9562a7 | f98553794c8deb0ffafbd89fed4fd460f26e9245 | /textBack.cpp | 648c2e7a215b2c477bd5e453521e5bf26185b887 | [] | no_license | Laowpetch/Programming_Fundamental | 4acee8c7383f4c9f5985d11871b1d1301c5a8a19 | 2919f68efc92ab42283e2045688e21c3c8303539 | refs/heads/master | 2023-06-21T11:25:31.444990 | 2021-08-11T16:20:55 | 2021-08-11T16:20:55 | 395,050,320 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 83 | cpp | textBack.cpp | #include<stdio.h>
#include<conio.h>
main () {
printf("text back to me plsss.");
}
|
8c3ce686c7f0d630dbceb1f24b8df57b25f3bf04 | 8fe9bc8be43d76db98c629bdb305a4e965e9c074 | /Software_Engineering_Robust_Principle_Axis_Detection/Mesh/NeighborMesh.h | e6e4c479d2900273015236b7d6db9bdb77a906dc | [] | no_license | ChaKon/Software_Engineering_Robust_Principle_Axis_Detection | 62b895cee3dd7f6069f7b473d5e75bc42f55aa5d | 7fd6d17a30fc73b86fddb896d00c9bc43fcf6029 | refs/heads/master | 2021-03-12T23:48:57.180437 | 2014-07-29T23:27:21 | 2014-07-29T23:27:21 | 22,398,847 | 1 | 0 | null | null | null | null | MacCentralEurope | C++ | false | false | 3,307 | h | NeighborMesh.h | /***************************************************************************
Mesh.h
-------------------
update : 2002-10-11
copyright : (C) 2002 by MichaŽl ROY
email : michaelroy@users.sourceforge.net
Edit Yohan Fougerolle
Warning : handle only triangular faces!
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifndef _NEIGHBORMESH_
#define _NEIGHBORMESH_
#include <Eigen/Core>
#include <Eigen/Geometry>
using namespace Eigen;
#include <cassert>
#include <cstring>
#include <vector>
#include <set>
#include <map>
using namespace std;
#include "Mesh.h"
class NeighborMesh : public Mesh
{
public:
//constructor and destructor
NeighborMesh();
virtual ~NeighborMesh();
//attributes
vector < set<int> > P2P_Neigh;
vector < set<int> > P2F_Neigh;
vector < set<int> > F2F_Neigh;
vector<double> Labels;
map < pair <int,int>, set<int> > Edges;
inline map < pair <int,int>, set<int> > :: iterator Get_Edge(int i1, int i2)
{
pair <int, int> mypair;
if (i1<i2) {mypair.first = i1; mypair.second = i2; return Edges.find(mypair);}
else {mypair.first = i2; mypair.second = i1; return Edges.find(mypair);}
}
//construction of the previous attributes once the file is loaded
bool Build_P2P_Neigh();
bool Build_P2F_Neigh();
bool Build_F2F_Neigh();
bool Build_Edges();
void BuildDistanceLabels(int A);
//rendering functions for verification
void DrawP2P_Neigh( int i );
void DrawP2F_Neigh( int i );
void DrawF2F_Neigh( int i );
void DrawEdge( int i);
void DrawEdge( map< pair<int,int>, set<int> > :: iterator it);
void DrawBoudaryEdges();
vector<int> ShortestPath(int, int, bool buildlabels=false);
void SetColorsFromLabels();
void SetColorsFromKean(double n = 5);
//compute extended neighborhoods
set<int> GetP2P_Neigh( int, int );
set<int> GetF2F_Neigh( int, int );
//drawing functions
void DrawPoints ( set <int> );
void DrawFaces ( set <int> );
void IllustratePointNeighbourhoodComputation(int,int);
void IllustrateFaceNeighbourhoodComputation(int,int);
void IllustrateEdges( int n);
void IllustrateP2P_Neigh( int n);
void IllustrateP2F_Neigh( int n );
void IllustrateF2F_Neigh( int n );
void IllustrateShortestPaths (int ngeod, int startpointindex);
int IsObtuse( int face_index);
};
#endif // _NEIGHBORMESH_
|
6eab49f6f4298989e74fb2100cae3174014eda50 | fcc136c9b903c33027da3c3e1604ec9325272bb2 | /367. Valid Perfect Square.cpp | 1f93c03b7008f30f5849f2b7fd0ba7c781361457 | [] | no_license | autumn192837465/LeetCode | 4c67105174f942ce861c99637e059abde5378f0e | d7c2ddb955adc826d01175a31747a12163f8d41d | refs/heads/master | 2021-07-20T06:59:39.267313 | 2020-05-26T05:06:06 | 2020-05-26T05:06:06 | 174,077,418 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 806 | cpp | 367. Valid Perfect Square.cpp | /*
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
Example 1:
Input: 16
Output: true
Example 2:
Input: 14
Output: false
*/
class Solution {
public:
bool isPerfectSquare(int num) {
unsigned int left = 0;
unsigned int right = num;
while(left <= right){
unsigned int mid = (left+right)/2;
if(mid == (float)num/mid){
return true;
}
else if(left == right){
return false;
}
if(mid > (float)num/mid){
right = mid-1;
}
else{
left = mid+1;
}
}
return false;
}
}; |
6e849340c0ac709c1f4697170cc4646317ebe809 | d6ccef84f1aad545243bf8519a725ea61789a5de | /Computer/calcComputer.cpp | 168ab4d4b491b4abfe03c0095baddf02a2d5b9bd | [] | no_license | devMal1/Calcpp | f12aa4c5c94344cfd4f3198e24331bfd224dd630 | 89fd966699b1fa33508502e1b9d835e05963e86e | refs/heads/master | 2021-01-22T21:32:37.540810 | 2017-05-05T21:28:26 | 2017-05-05T21:28:26 | 85,440,093 | 0 | 0 | null | 2017-05-05T21:28:26 | 2017-03-19T00:08:49 | C++ | UTF-8 | C++ | false | false | 1,283 | cpp | calcComputer.cpp | #include "calcComputer.h"
CalcComputer::CalcComputer() {}
CalcComputer::~CalcComputer() {}
int add(int a, int b) {
return (a + b);
}
int sub(int a, int b) {
return (a - b);
}
int mult(int a, int b) {
return (a * b);
}
int divi(int a, int b) {
if (b == 0) { throw CalcComputer::DIV_BY_ZERO; }
return (a / b);
}
int CalcComputer::reduce(const std::vector<int> &nums, int (*reducer)(int, int)) {
if (nums.size() == 1) { return nums[0]; }
int value{ (*reducer)(nums[0], nums[1]) };
for (unsigned int i = 2; i < nums.size(); i ++) {
value = (*reducer)(value, nums[i]);
}
return value;
}
int CalcComputer::compute(const CalcCommand &command) {
if (command.getArguments().size() < 1) { throw NOT_ENOUGH_ARGUMENTS; }
std::string op{ command.getOperation() };
if (op == "add") { return reduce(command.getArguments(), add); }
if (op == "sub") { return reduce(command.getArguments(), sub); }
if (op == "mult") { return reduce(command.getArguments(), mult); }
if (op == "div") { return reduce(command.getArguments(), divi); }
throw INVALID_OPERATION;
}
const int CalcComputer::NOT_ENOUGH_ARGUMENTS = -1000;
const int CalcComputer::INVALID_OPERATION = -2000;
const int CalcComputer::DIV_BY_ZERO = -3000; |
396118505960dc2151dfc1aadf7522c1e0f25f3a | bf32aa7664731320fd3ca9422623237a07112e72 | /spoj/hackerrank/pir_3/2.cpp | 14eeff50134e0203a7004d18ea5b39fd5f641c8a | [] | no_license | rohit-100/cppFiles | 69c2b2030f8c573d80c28001cc8e220e4001b601 | 1912b7d90600a92b18ea59f9fd44edd20969a67f | refs/heads/master | 2020-12-12T12:07:55.345431 | 2020-07-24T14:26:10 | 2020-07-24T14:26:10 | 234,124,535 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,085 | cpp | 2.cpp | #include<bits/stdc++.h>
using namespace std;
int main(){
int n,k;
cin>>n>>k;
long long arr[n+1][n+1];
memset(arr,0,sizeof(arr));
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
long long x;cin>>x;
x += arr[i][j-1];
x += arr[i-1][j];
x -= arr[i-1][j-1];
arr[i][j] =x;
}
}
// for(int i=0;i<=n;i++){
// for(int j=0;j<=n;j++)cout<<arr[i][j]<<" ";
// cout<<endl;
// }
int high = n;
int low = 1;
int ans = -1;
while(low <= high){
int mid = (low + high)>>1;
bool flag = false;
for(int i=1;i+mid-1<=n;i++){
for(int j=1;j+mid-1<=n;j++){
if(arr[i+mid-1][j+mid-1]-arr[i-1][j+mid-1]-arr[i+mid-1][j-1]+arr[i-1][j-1]>=k){
flag = true;
break;
}
}
}
if(flag){
ans = mid;
high = mid-1;
}
else{
low = mid+1;
}
}
cout<<ans<<endl;
}
|
5a0a28be4d8b045a90193fb745c40eca055a0ceb | e84a9d918231c9d4470d1aa61aefffd44f827878 | /src/Kiwi/Kiwi/HartreeFock/SimultaneousDiis/SimultaneousDiis.cpp | 7ec9debbdba08ebb1d853c14b7f88cb612a3dcba | [
"BSD-3-Clause"
] | permissive | qcscine/kiwi | 2f28b5e055e1a246555a9808acd18d3fb50ef5b2 | 0879aeeb5dea2454819b2599780d28393eacbe8b | refs/heads/master | 2023-04-10T08:04:56.038549 | 2023-01-25T18:36:11 | 2023-01-25T18:36:11 | 593,176,904 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,551 | cpp | SimultaneousDiis.cpp | /**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*/
#include <Kiwi/HartreeFock/SimultaneousDiis/SimultaneousDiis.h>
#include <Eigen/QR>
#include <algorithm>
#include <iostream>
namespace Scine {
namespace Kiwi {
SimultaneousDiis::SimultaneousDiis() {
setSubspaceSize(5);
}
void SimultaneousDiis::setSubspaceSize(int n) {
bool resizeNeeded = n != subspaceSize_;
subspaceSize_ = n;
if (resizeNeeded) {
resizeMembers();
}
}
void SimultaneousDiis::resizeMembers() {
fockMatrices.resize(subspaceSize_);
errorMatrices.resize(subspaceSize_);
B = Eigen::MatrixXd::Ones(subspaceSize_ + 1, subspaceSize_ + 1) * (-1);
B(0, 0) = 0;
rhs = Eigen::VectorXd::Zero(subspaceSize_ + 1);
rhs(0) = -1;
restart();
}
void SimultaneousDiis::restart() {
C = Eigen::VectorXd::Zero(subspaceSize_ + 1);
iterationNo_ = 0;
index_ = 0;
}
void SimultaneousDiis::addMatrices() {
iterationNo_++;
lastAdded_ = index_;
if (useOrthonormalBasis) {
fockMatrices[index_] = data_->hartreeFockData->F_OAO;
}
else {
fockMatrices[index_] = data_->hartreeFockData->F;
}
evalauteError(index_);
updateBMatrix();
index_ = (index_ + 1) % subspaceSize_;
}
void SimultaneousDiis::updateBMatrix() {
int activeSize = iterationNo_ > subspaceSize_ ? subspaceSize_ : iterationNo_;
// Bii element
B(lastAdded_ + 1, lastAdded_ + 1) = evalauteBMatrixElement(lastAdded_, lastAdded_);
// Bij elements
for (int i = 1; i < activeSize + 1; i++) {
if (i == lastAdded_ + 1) {
continue;
}
B(lastAdded_ + 1, i) = evalauteBMatrixElement(lastAdded_, i - 1);
B(i, lastAdded_ + 1) = B(lastAdded_ + 1, i);
}
}
auto SimultaneousDiis::getMixedFockMatrix() -> std::map<Utils::ElementType, Utils::SpinAdaptedMatrix> {
if (iterationNo_ > subspaceSize_) {
iterationNo_ = subspaceSize_;
}
// If we have only one Simultaneous matrix
if (iterationNo_ < 2) {
return fockMatrices[0];
}
C.head(iterationNo_ + 1) =
B.block(0, 0, iterationNo_ + 1, iterationNo_ + 1).colPivHouseholderQr().solve(rhs.head(iterationNo_ + 1));
return calculateLinearCombination();
}
Eigen::MatrixXd SimultaneousDiis::calculateErrorMatrixOrthonormal(const Eigen::MatrixXd& D, const Eigen::MatrixXd& F) {
Eigen::MatrixXd DF = D * F;
return DF - DF.transpose();
}
Eigen::MatrixXd SimultaneousDiis::calculateErrorMatrix(const Eigen::MatrixXd& D, const Eigen::MatrixXd& F,
const Eigen::MatrixXd& S) {
Eigen::MatrixXd SDF = S * D * F;
return SDF - SDF.transpose();
}
auto SimultaneousDiis::evalauteError(int idx) -> void {
for (const auto& elem : *molecule_) {
const auto type = elem.first;
if (elem.second.isRestricted) {
if (useOrthonormalBasis) {
errorMatrices[idx][type].restrictedMatrix() = calculateErrorMatrixOrthonormal(
data_->D_OAO[type].restrictedMatrix(), data_->hartreeFockData->F_OAO[type].restrictedMatrix());
}
else {
errorMatrices[idx][type].restrictedMatrix() = calculateErrorMatrix(
data_->D_OAO[type].restrictedMatrix(), data_->hartreeFockData->F_OAO[type].restrictedMatrix(), data_->S[type]);
}
}
else {
if (useOrthonormalBasis) {
errorMatrices[idx][type].alphaMatrix() = calculateErrorMatrixOrthonormal(
data_->D_OAO[type].alphaMatrix(), data_->hartreeFockData->F_OAO[type].alphaMatrix());
if (elem.second.msVector[1] > 0) {
errorMatrices[idx][type].betaMatrix() = calculateErrorMatrixOrthonormal(
data_->D_OAO[type].betaMatrix(), data_->hartreeFockData->F_OAO[type].betaMatrix());
}
}
else {
errorMatrices[idx][type].alphaMatrix() = calculateErrorMatrix(
data_->D_OAO[type].alphaMatrix(), data_->hartreeFockData->F_OAO[type].alphaMatrix(), data_->S[type]);
if (elem.second.msVector[1] > 0) {
errorMatrices[idx][type].betaMatrix() = calculateErrorMatrix(
data_->D_OAO[type].betaMatrix(), data_->hartreeFockData->F_OAO[type].betaMatrix(), data_->S[type]);
}
}
}
}
}
auto SimultaneousDiis::evalauteBMatrixElement(int i, int j) -> double {
double ret = 0;
for (const auto& elem : *molecule_) {
const auto type = elem.first;
if (elem.second.isRestricted) {
ret += errorMatrices[i][type].restrictedMatrix().cwiseProduct(errorMatrices[j][type].restrictedMatrix()).sum();
}
else {
ret += errorMatrices[i][type].alphaMatrix().cwiseProduct(errorMatrices[j][type].alphaMatrix()).sum();
if (elem.second.msVector[1] > 0) {
ret += errorMatrices[i][type].betaMatrix().cwiseProduct(errorMatrices[j][type].betaMatrix()).sum();
}
}
}
return ret;
}
Utils::SpinAdaptedMatrix SimultaneousDiis::calculateLinearCombination(const Utils::ElementType type) {
if (!molecule_->at(type).isRestricted) {
Eigen::MatrixXd F_alpha;
F_alpha.resizeLike(fockMatrices[0][type].alphaMatrix());
F_alpha.setZero();
Eigen::MatrixXd F_beta;
F_beta.resizeLike(fockMatrices[0][type].betaMatrix());
F_beta.setZero();
for (int i = 0; i < iterationNo_; i++) {
F_alpha += C(i + 1) * fockMatrices[i][type].alphaMatrix();
}
if (molecule_->at(type).msVector[1] > 0) {
for (int i = 0; i < iterationNo_; i++) {
F_beta += C(i + 1) * fockMatrices[i][type].betaMatrix();
}
}
return Utils::SpinAdaptedMatrix::createUnrestricted(std::move(F_alpha), std::move(F_beta));
}
Eigen::MatrixXd F_restricted;
F_restricted.resizeLike(fockMatrices[0][type].restrictedMatrix());
F_restricted.setZero();
for (int i = 0; i < iterationNo_; i++) {
F_restricted += C(i + 1) * fockMatrices[i][type].restrictedMatrix();
}
return Utils::SpinAdaptedMatrix::createRestricted(std::move(F_restricted));
}
auto SimultaneousDiis::calculateLinearCombination() -> std::map<Utils::ElementType, Utils::SpinAdaptedMatrix> {
std::map<Utils::ElementType, Utils::SpinAdaptedMatrix> ret;
for (const auto& elem : *molecule_) {
ret[elem.first] = calculateLinearCombination(elem.first);
}
return ret;
}
auto SimultaneousDiis::setMixedFockMatrix() -> void {
if (useOrthonormalBasis) {
data_->hartreeFockData->F_OAO = getMixedFockMatrix();
}
else {
data_->hartreeFockData->F = getMixedFockMatrix();
}
}
} // namespace Kiwi
} // namespace Scine
|
7fb87db6c4aad6ab494097ae7248d4de6c00eb00 | 1408c9b234d8d94f182c11c53f92dd0c8f80c16d | /Viewer/libViewer/src/UserMessage.hpp | b0f80e5c914eb7ffa15a34d2031c8569dd6771c1 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"MIT",
"BSL-1.0"
] | permissive | XiaoLinhong/ecflow | 8f324250d0a5308b3e39f3dd5bd7a297a2e49c90 | 57ba5b09a35b064026a10638a10b31d660587a75 | refs/heads/master | 2023-06-19T04:07:54.150363 | 2021-05-19T14:58:16 | 2021-05-19T14:58:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,168 | hpp | UserMessage.hpp | //============================================================================
// Copyright 2009-2020 ECMWF.
// This software is licensed under the terms of the Apache Licence version 2.0
// which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
// In applying this licence, ECMWF does not waive the privileges and immunities
// granted to it by virtue of its status as an intergovernmental organisation
// nor does it submit to any jurisdiction.
//============================================================================
#ifndef USER_MESSAGE_HPP_
#define USER_MESSAGE_HPP_
#include <QDebug>
#include <QString>
#include <string>
class UserMessage
{
//Q_OBJECT
public:
UserMessage();
enum MessageType {INFO, WARN, ERROR, DBG}; // note: cannot have DEBUG because of possible -DDEBUG in cpp!
static void setEchoToCout(bool toggle) {echoToCout_ = toggle;}
static void message(MessageType type, bool popup, const std::string& message);
static bool confirm(const std::string& message);
static void debug(const std::string& message);
static std::string toString(int);
private:
static bool echoToCout_;
};
#endif
|
ee63dc307e7ba9c3043e7c57de6cdf6a1e5076e5 | c5b7a81da80a90f30346f7f82f958aba1f71debd | /cpp_practise/matrix_vector_calc/main.cpp | 5b75b710f4d4ecd54a278db1b3768c3faa530994 | [] | no_license | atifkarim/problem_solving | f765be37970f4d55376a499daf0fcf6f596396bc | 141c96364524aeb40fff4e1ec75877f1ff8c416a | refs/heads/master | 2023-04-27T20:03:03.917053 | 2023-04-19T22:43:06 | 2023-04-19T22:43:06 | 201,545,905 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,484 | cpp | main.cpp | /*
#include <cstdlib>
#include <math.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
int a[3][3]={{ 2,4,3},{1,5,7},{0,2,3}};
int b[]={2,5,6};
int c[3];
for (int i=0;i<3;i++){
c[i]=0;
}
for (int i=0;i<3;i++){
for (int j=0;j<3;j++){
c[i]+=( a[i][j]*b[j]);
}
}
for (int i=0;i<3;i++){
cout<<c[i]<<" "<<endl;
}
// system("PAUSE");
// return EXIT_SUCCESS;
}
*/
/*
#include <iostream>
using namespace std;
int create_vector(int mat_col)
{
int vec_row, vec_col;
int my_vec[vec_row][vec_col];
if (mat_col!=1){
cout<<"It will be a column vector"<<endl;
vec_row = mat_col;
vec_col = 1;
// column vector, single column
}
else if (mat_col==1){
cout<<"It will be a row vector"<<endl;
vec_row=mat_col;
cout<<"put desired column for the vector as it is a row vector: ";
cin>>vec_col;
}
else{
cout<<"problem arises in declaring Matrix"<<endl;
}
cout<<"Printing vector: \n"<<endl;
for (int i=0;i<vec_row;i++)
{
for (int j=0;j<vec_col;j++)
{
cout << "A[" << i+1 << "][" << j+1 << "]=";
cin >> my_vec[i][j];
}
}
cout << "[[ ";
for (int i=0;i<vec_row;i++)
{
for (int j=0;j<vec_col;j++)
{
cout << my_vec[i][j] << " ";
}
if (i!=vec_row-1) //Just to make the output pretty
cout << "]\n [ ";
else
cout << "]]";
}
return 1;
//return my_vec;
}*/
/*
#include<iostream>
using namespace std;
std::vector<int> f() {
std::vector<int> my_vec;
int vec_row, vec_col;
// int my_vec[vec_row][vec_col];
if (mat_col!=1){
cout<<"It will be a column vector"<<endl;
vec_row = mat_col;
vec_col = 1;
// column vector, single column
}
else if (mat_col==1){
cout<<"It will be a row vector"<<endl;
vec_row=mat_col;
cout<<"put desired column for the vector as it is a row vector: ";
cin>>vec_col;
}
else{
cout<<"problem arises in declaring Matrix"<<endl;
}
cout<<"Printing vector: \n"<<endl;
for (int i=0;i<vec_row;i++)
{
for (int j=0;j<vec_col;j++)
{
cout << "A[" << i+1 << "][" << j+1 << "]=";
cin >> my_vec[i][j];
}
}
cout << "[[ ";
for (int i=0;i<vec_row;i++)
{
for (int j=0;j<vec_col;j++)
{
cout << my_vec[i][j] << " ";
}
if (i!=vec_row-1) //Just to make the output pretty
cout << "]\n [ ";
else
cout << "]]";
}
// ... populate the vector ...
return my_vec;
}
*/
/*
#include<iostream>
using namespace std;
int main()
{
int n,m;
cout << "A is an nxn matrix.\nn or row=";
cin >> n; //row
cout << "A is an nxn matrix.\nm or column=";
cin>>m; //column
int matrix[n][m];
for (int i=0;i<n;i++)
{
for (int j=0;j<m;j++)
{
cout << "A[" << i+1 << "][" << j+1 << "]=";
cin >> matrix[i][j];
}
}
cout << "[[ ";
for (int i=0;i<n;i++)
{
for (int j=0;j<m;j++)
{
cout << matrix[i][j] << " ";
}
if (i!=n-1) //Just to make the output pretty
cout << "]\n [ ";
else
cout << "]]";
}
cout<<"\n";
int b[]={2,5,6};
int h,k;
int c[h][k];
for (int h=0;h<n;h++){
for (int k=0;k<n;k++){
c[h][k]=0;
}
}
for (int i=0;i<n;i++){
for (int j=0;j<m;j++){
c[i][j]+=( matrix[i][j]*b[j]);
}
}
cout << "[[ ";
for (int i=0;i<n;i++)
{
for (int j=0;j<n;j++)
{
cout << c[i][j] << " ";
}
if (i!=n-1) //Just to make the output pretty
cout << "]\n [ ";
else
cout << "]]";
}
// create_vector(m);
// std::vector<int> myvec_1 = f();
}
*/
/*
#include <iostream>
#include <sstream>
#include <vector>
int main() {
std::string line;
int number;
std::vector<int> numbers;
std::cout << "Enter numbers separated by spaces: ";
std::getline(std::cin, line);
std::istringstream stream(line);
while (stream >> number)
numbers.push_back(number);
// write_vector(numbers);
}*/
#include <iostream>
#include <vector>
using namespace std;
typedef vector<int> Array; // a declaration of a 1D vactor whose name is Array
typedef vector<Array> Matrix; // A declaration of a 2D vector whose name is Matrix
int main(){
int vec_row;
cout<<"give row of vector: ";
cin>>vec_row;
Array vector_1(Array(3)); // A 1D vector named vector_1 is assigned with column size 3
Array res_col(Array(1));
// cout<<"vector_1 row or SIZE: "<<vector_1.size()<<endl;
// cout<<"vector_1 column is : "<<vector_1[1].size()<<endl;
int mat_row;
cout<<" give row of matrix: ";
cin>>mat_row;
Matrix Matrix_1(Matrix(mat_row,vector_1)); // A 2D vector named Matrix_1 is assigned with column size as same as vector_1
// and it's row is used as user input
// cout <<"Matrix_1 row or SIZE is: "<<Matrix_1.size()<<endl; // row number
// cout<<"Matrix_1 column is: "<<Matrix_1[1].size()<<endl;//column number
// int val_mat;
for (int i=0;i<3;i++){
for (int j=0;j<vector_1.size();j++){
cin>>Matrix_1[i][j];
// cin>>val_mat;
// Matrix_1[i][j].push_back(val_mat);
}
}
cout<<"\n 2D vector printing\n";
for (int i=0;i<3;i++){
for(int j=0;j<vector_1.size();j++){
cout<<Matrix_1[i][j]<<" ";
}
cout<<"\n";
}
cout <<"\n NOW 1D VECTOR\n";
for (int i=0;i<vector_1.size();i++){
cin>>vector_1[i];
}
cout<<"\n 1D vector printing\n";
for (int i=0;i<vector_1.size();i++){
cout<<vector_1[i];
}
Matrix Result_Matrix(Matrix(Matrix_1.size(),res_col));
// Matrix Result_Matrix(Matrix(3,1));
// for (int h=0;h<Result_Matrix.size();h++){
// for (int k=0;Result_Matrix[0].size()<1;k++){
// cout<<"I am here"<<endl;
// Result_Matrix[h][k]=0;
// }
// }
int val_here=0;
for (int i=0;i<Matrix_1.size();i++){
for (int j=0;j<Matrix_1[0].size();j++){
Result_Matrix[i][0]+=( Matrix_1[i][j]*vector_1[j]);
// val_here++;
}
// val_here=0;
}
cout<<"Resultant Matrix\n";
for (int i =0;i<Result_Matrix.size();i++){
for(int j =0;j <Result_Matrix[0].size();j++){
cout<<Result_Matrix[i][j]<<endl;
}
}
return 0;
}
|
dceb8092b043a753b25e6db1da60abcfbeb089f7 | ece3d852c9c23229081872b61a2f617bf0576b7e | /sarturis-curses/modules/misc-curses/bardrawer.cpp | 1b5ead8fef7efc37511ca50f8d89461905359630 | [] | no_license | meisenmann77/sarturis | 14ee6e7462ce84aa5dfc78b49190fb993e6051ec | bf8bcee735859667a1bdd1f67f2fa78ca938573b | refs/heads/master | 2021-01-19T14:56:56.033733 | 2020-11-30T16:57:38 | 2020-11-30T16:57:38 | 37,017,592 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,683 | cpp | bardrawer.cpp | /*******************************************************************************
*
* Sarturis is (C) Copyright 2006-2011 by Dresden University of Technology
*
* This software is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This software 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this software; if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
******************************************************************************/
#include <math.h>
#include <sarturis/common/str.h>
#include <sarturis/curses/color.h>
#include "include/bardrawer.h"
using namespace sarturis::curses;
#define EPS 1e-6
/******************************************************************************/
BarDrawer::BarDrawer(unsigned int X, unsigned int Y, unsigned int Width,
double Min, double Max, double Value, bool ShowValue):
Widget(X,Y,Width,1),
min(Min),
max(Max),
showvalue(ShowValue),
value(Value)
/******************************************************************************/
{
}
/******************************************************************************/
/******************************************************************************/
BarDrawer::~BarDrawer()
/******************************************************************************/
{
}
/******************************************************************************/
/******************************************************************************/
void BarDrawer::draw_content()
/******************************************************************************/
{
// Position
const unsigned int p=(unsigned int)((value-min)/(max-min)*(double)width+0.5);
// Zwei Teile des Bars
mvwhline(win,0,0,A_REVERSE | ' ',p); // "Gefuellter" Teil
mvwhline(win,0,p,' ',width-p); // Rest
// Wert
if (showvalue)
{
// Wert in String umwandeln - "0" und in Breite einpassen
std::string sval=str(value);
if (fabs(value)<EPS) sval="0";
if (sval.length()>width) sval=sval.substr(0,width);
// Start-Pos und End-Pos
const unsigned int cp=(width-sval.length())/2;
const unsigned int ce=cp+sval.length();
// Teil-Strings und Positionen
std::string sback; unsigned int back_pos=0;
std::string sfill; unsigned int fill_pos=0;
// Komplett auf Hintergrund
if (p<=cp)
{
sback=sval;
back_pos=cp;
}
// Komplett auf Fuellung
else if (p>=ce)
{
sfill=sval;
fill_pos=cp;
}
// cp < p < ce - Teilen
else
{
sfill=sval.substr(0,p-cp); // Linker Teil, auf Fuellung
fill_pos=cp;
sback=sval.substr(p-cp,ce-p); // Rechter Teil, auf Hintergrund
back_pos=p;
}
// Auf Hintergrund
if (sback!="") mvwprintw(win,0,back_pos,sback.c_str());
// Auf Fuellung (invertiert)
if (cp<p)
{
wattron(win,COLOR_PAIR(Color::Invert(color)));
mvwprintw(win,0,fill_pos,sfill.c_str());
wattroff(win,COLOR_PAIR(Color::Invert(color)));
}
}
}
/******************************************************************************/
|
a91dfdf54b356ba734647fd1bda2354d8245196d | c0f7f59c1f4b6bc378dfc7606304338de2b3346d | /labs/rec05/rec05/rec05/rec05.cpp | 2449e64c58541ca17091ac900d9b7a0b1344d6e8 | [] | no_license | VIJAYKALLEM/NYU_CS2124 | 39005fbee51b607af402b3cf50fc747d2d7be022 | a727316668b98d718630a921dab569d236d75bfa | refs/heads/master | 2022-03-22T09:14:07.442890 | 2019-12-16T19:09:19 | 2019-12-16T19:09:19 | 293,368,189 | 0 | 1 | null | 2020-09-06T21:57:58 | 2020-09-06T21:57:58 | null | UTF-8 | C++ | false | false | 7,409 | cpp | rec05.cpp | /*
Simran Soin (sks684)
4 October 2019
Recitation 5: Design interacting classes using
Association
Composition
Encapsulation and Data Hiding
Delegation
Copy control: destructor and copy constructor.
Output operator
Modeling the NYU Tandon CS lab Administration
*/
#include <iostream>
#include <string>
#include <vector>
using namespace std;
const int NUM_GRADES = 14;
class Section{
// OSTREAM << OPERATOR FOR SECTION
friend ostream& operator<<(ostream& os, const Section& rhs){
os << "Section: " << rhs.name << ", " << rhs.section_time << ", Students: " <<endl;
if (rhs.student_records.size() == 0){
os << "None";
}
else{
for (const Student* curr_student: rhs.student_records){
os << *curr_student;
}
}
return os;
}
public:
// CONSTRUCTOR
Section(const string& name, const string& day, int start_time): name(name),
section_time(TimeSlot(start_time, day)) {};
// COPY CONSTRUCTOR
Section(const Section& rhs) : section_time(rhs.section_time), name(rhs.name) {
vector<Student*> lhs_student_records;
for (const Student* curr_student: rhs.student_records){
Student* deep_copied_student_pointer = new Student(*curr_student);
lhs_student_records.push_back(deep_copied_student_pointer);
}
student_records = lhs_student_records;
};
// DESTRUCTOR
~Section(){
cout << "Section " << name << " is being deleted" << endl;
for (Student*& curr_student: student_records){
cout << "Deleting " << curr_student->getNameCopy() << endl;
delete curr_student;
curr_student = nullptr;
}
student_records.clear();
};
// CREATES STUDENT FROM NAME AND ADDS POINTER TO STUDENT_RECORDS
void addStudent(const string& name){
Student* curr_student = new Student(name);
student_records.push_back(curr_student);
}
// FINDS NAME IN STUDENT RECORDS
// TELLS STUDENT TO ADD A CERTAIN GRADE TO A CERTAIN WEEK
void addGrade(const string& name, int grade, int week){
for (Student*& curr_student: student_records){
if (curr_student->getNameCopy() == name){
curr_student->addGrade(grade, week);
break;
}
}
}
private:
// STUDENT IS EMBEDDED IN SECTION
class Student{
// OSTREAM << OPERATOR FOR STUDENT
friend ostream& operator<<(ostream& os,
const Student& rhs){
os << "Name: " << rhs.name << ", Grades: ";
for (size_t i = 0; i <= NUM_GRADES; ++i){
os << rhs.student_grades[i] << ", ";
}
os << endl;
return os;
}
public:
// CONSTRUCTOR (INTIALIZES ALL GRADES TO -1)
Student(const string& name): name(name) {
student_grades = vector<int>(NUM_GRADES, -1);
};
// GIVEN GRADE AND WEEK, ADDS TO GRADE VECTOR
void addGrade(int grade, int week){
student_grades[week-1] = grade;
}
// CONST FUNCTION RETURNS COPY OF NAME
string getNameCopy() const{
return name;
}
private:
string name;
vector<int> student_grades;
};
//TIMESLOT IS EMBEDDED IN SECTION
class TimeSlot{
// OSTREAM << OPERATOR FOR TIMESLOT
friend ostream& operator<<(ostream& os, const TimeSlot& rhs){
os << "Time slot: [Day: " << rhs.day <<", Start Time: ";
if (rhs.start_time <= 11){
os << rhs.start_time << "am";
}
else if (rhs.start_time == 12){
os << rhs.start_time << "pm";
}
else {
os << (rhs.start_time - 12) << "pm";
}
os << "]";
return os;
}
public:
// CONSTRUCTOR
TimeSlot(int start_time, const string& day): start_time(start_time), day(day) {};
private:
// HAS STRING DAY AND INT TIME (24 HR)
int start_time;
string day;
};
string name;
TimeSlot section_time;
// SECTION HAS A VECTOR OF STUDENT POINTERS (POINTS TO HEAP)
vector<Student*> student_records;
};
class LabWorker{
// OSTREAM << OPERATOR FOR LABWORKER
friend ostream& operator<<(ostream& os, const LabWorker& rhs){
os << rhs.name;
if (rhs.assigned_section == nullptr){
os << " does not have a section.";
}
else{
os << " has " << *rhs.assigned_section;
}
return os;
}
public:
// CONSTRUCTOR
LabWorker(const string& name): name(name), assigned_section(nullptr){};
// ASSIGNS AN EXISTING SECTION TO LABWORKER
void addSection(Section& section_name){
assigned_section = §ion_name;
}
// ADDING A GRADE --> DELEGATES TO THE SECTION
void addGrade(const string& student_name, int grade, int week){
assigned_section->addGrade(student_name, grade, week);
}
private:
string name;
// POINTER TO A SECTION.
// IF POINTER IS NULL, LABWORKER HASNT BEEN ASSIGNED SECTIOM
Section* assigned_section;
};
// Test code
void doNothing(Section sec) {
cout << sec << endl;;
}
int main() {
cout << "Test 1: Defining a section\n";
Section secA2("A2", "Tuesday", 16);
cout << secA2 << endl;
cout << "\nTest 2: Adding students to a section\n";
secA2.addStudent("John");
secA2.addStudent("George");
secA2.addStudent("Paul");
secA2.addStudent("Ringo");
cout << secA2 << endl;
cout << "\nTest 3: Defining a lab worker.\n";
LabWorker moe("Moe");
cout << moe << endl;
cout << "\nTest 4: Adding a section to a lab worker.\n";
moe.addSection(secA2);
cout << moe << endl;
cout << "\nTest 5: Adding a second section and lab worker.\n";
LabWorker jane( "Jane" );
Section secB3( "B3", "Thursday", 11 );
secB3.addStudent("Thorin");
secB3.addStudent("Dwalin");
secB3.addStudent("Balin");
secB3.addStudent("Kili");
secB3.addStudent("Fili");
secB3.addStudent("Dori");
secB3.addStudent("Nori");
secB3.addStudent("Ori");
secB3.addStudent("Oin");
secB3.addStudent("Gloin");
secB3.addStudent("Bifur");
secB3.addStudent("Bofur");
secB3.addStudent("Bombur");
jane.addSection(secB3);
cout << jane << endl;
cout << "\nTest 6: Adding some grades for week one\n";
moe.addGrade("John", 17, 1);
moe.addGrade("Paul", 19, 1);
moe.addGrade("George", 16, 1);
moe.addGrade("Ringo", 7, 1);
cout << moe << endl;
cout << "\nTest 7: Adding some grades for week three (skipping week 2)\n";
moe.addGrade("John", 15, 3);
moe.addGrade("Paul", 20, 3);
moe.addGrade("Ringo", 0, 3);
moe.addGrade("George", 16, 3);
cout << moe << endl;
cout << "\nTest 8: We're done (almost)! \nWhat should happen to all "
<< "those students (or rather their records?)\n";
cout << "\nTest 9: Oh, IF you have covered copy constructors in lecture, "
<< "then make sure the following call works properly, i.e. no memory leaks\n";
doNothing(secA2);
cout << "Back from doNothing\n\n";
} // main
|
792ef2c4276be6361f434105caffd794d45e8024 | c62e924a6ed420e3562bc5cac80d48d58bd51807 | /Arrays/TapeEquilibrium.cpp | 52a6bb09733a42d5609214affaf1c5d53cf67652 | [] | no_license | cyf1981/algoPrac | a0ecc6bbb748884dc889da5264485aa175dc8fd7 | 33992cbeba9a09b9887a8d07008035b8832544e7 | refs/heads/master | 2022-12-22T06:45:15.133172 | 2020-09-29T12:59:41 | 2020-09-29T12:59:41 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 556 | cpp | TapeEquilibrium.cpp | // you can use includes, for example:
// #include <algorithm>
#include <math.h>
#include <numeric>
// you can write to stdout for debugging purposes, e.g.
// cout << "this is a debug message" << endl;
int solution(vector<int> &A) {
int left = A[0];
int right = accumulate(A.begin()+1, A.end(), 0);
int minDiff = abs(left - right);
for (int i = 0; i < A.size() - 1; i++){
left += A[i];
right -= A[i];
if (abs(left - right) < minDiff){
minDiff = abs(left - right);
}
}
return minDiff;
}
|
bfa5ed46b05626880ff8f32b31a45904bd6134b0 | 07dde1571c3c7a3b102445f0f2881b5d8a5f04e1 | /ConcreteStructureDesign/AxiallyCompression/AxiallyCompression/AxiallyCompressionDlg.h | 8279949723a5fea43e741205240ea85a33170b29 | [] | no_license | mc-liyanliang/Structural-Design-Tool | d8ee124cf4bce769830759ef89c32189b716664a | d0c988767893694232a28760d555cdcbf8ffe419 | refs/heads/master | 2022-11-27T19:43:47.395376 | 2020-08-05T14:30:33 | 2020-08-05T14:31:32 | 284,239,977 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,430 | h | AxiallyCompressionDlg.h |
// AxiallyCompressionDlg.h : 头文件
//
#pragma once
#include "afxwin.h"
#include "Tool.h"
class CAxialCompressionData;
// CAxiallyCompressionDlg 对话框
class CAxiallyCompressionDlg : public CDialogEx
{
// 构造
public:
CAxiallyCompressionDlg(CWnd* pParent = NULL); // 标准构造函数
// 对话框数据
enum { IDD = IDD_AXIALLYCOMPRESSION_DIALOG };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
// 实现
protected:
HICON m_hIcon;
// 生成的消息映射函数
virtual BOOL OnInitDialog();
afx_msg void OnSysCommand(UINT nID, LPARAM lParam);
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnBnClickedButtonCalculate();
afx_msg void OnBnClickedButtonReset();
private:
void InitComboList();
void Data2Dlg();
BOOL Dlg2Data();
private:
CTool m_Tool;
CAxialCompressionData* m_pData;
private:
CComboBox m_ComboSecType;
CEdit m_EditHeight;
CEdit m_EditWidth;
CEdit m_EditLength;
CEdit m_EditDiameter;
CEdit m_EditAxialDisignValue;
CEdit m_EditStabilityFactor;
CComboBox m_ComboConcreteGrade;
CComboBox m_ComboMainbarGrade;
CButton m_CheckSpiralRebar;
CComboBox m_ComboSpiralStirrupDia;
CEdit m_EditSpiralStirrupSpace;
CComboBox m_ComboSpiralStirrupGrade;
CEdit m_EditCoreSecDia;
CEdit m_EditMainbarMake;
CEdit m_EditSpiralStrrupMake;
CEdit m_EditRealMainbarArea;
virtual void PostNcDestroy();
};
|
dd7178e7594f7fbbcb6adcbda885802465045b77 | a7491f10bd804de1b2633497901c33dd00495d7b | /CMD2Mesh.cpp | 32f174a6a416dca1ab19cb946163d63d6e04cfc5 | [] | no_license | zikr99/3D-visualization | bfa646440a1100f7ae7a7d2f7e857cdb44910f5e | 4f84500fb688f023c4ffd878c4933d4d1ca3f019 | refs/heads/master | 2020-12-11T00:48:36.948607 | 2020-04-26T12:45:43 | 2020-04-26T12:45:43 | 233,757,577 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,763 | cpp | CMD2Mesh.cpp | #include "CMD2Mesh.h"
#include "CSceneManager.h"
#include <stdio.h>
CMD2Mesh::CMD2Mesh(CSceneManager *mngr): CMesh(mngr), NumFrames(0), FrameSize(0),
NumVertices(0), NumSTs(0), NumTriangles(0), Vertices(NULL), STs(NULL),
Triangles(NULL)
{
m_meshtype = EMST_MD2;
}
CMD2Mesh::CMD2Mesh(CSceneManager *mngr, char *filename, char* skinfilename):
CMesh(mngr), NumFrames(0), FrameSize(0), NumVertices(0), NumSTs(0),
NumTriangles(0), Vertices(NULL), STs(NULL), Triangles(NULL)
{
m_meshtype = EMST_MD2;
if ((filename != NULL) && (skinfilename != NULL)) loadFile(filename, skinfilename);
}
bool CMD2Mesh::loadFile(char *filename, char *skinfilename)
{
FILE *filePtr;
int fileLen;
char *buffer;
modelHeader_t *modelHeader;
vector_t *vertexList;
frame_t *frame;
vector_t *vertexListPtr;
float tempv;
texCoord_t *st;
stIndex_t *stPtr;
mesh_t *bufIndexPtr;
mesh_t *triIndex;
int i, j, numread;
filePtr = fopen(filename, "rb");
if (filePtr == NULL)
return false;
fseek(filePtr, 0, SEEK_END); // find length of file
fileLen = ftell(filePtr);
fseek(filePtr, 0, SEEK_SET);
buffer = new char [fileLen + 1]; //(char*)malloc(fileLen + 1);
if (buffer == NULL)
{
fclose(filePtr);
return false;
}
numread = fread(buffer, sizeof(char), fileLen, filePtr);
if (numread < fileLen)
{
delete [] buffer;
fclose(filePtr);
return false;
}
modelHeader = (modelHeader_t*)buffer; // extract model file header from buffer
vertexList = new vector_t [modelHeader->numXYZ*modelHeader->numFrames];
if (vertexList == NULL)
{
delete [] buffer;
fclose(filePtr);
return false;
}
for (j = 0; j < modelHeader->numFrames; j++)
{
frame = (frame_t*)&buffer[modelHeader->offsetFrames + modelHeader->framesize*j];
vertexListPtr = (vector_t*)&vertexList[modelHeader->numXYZ*j];
for (i = 0; i < modelHeader->numXYZ; i++)
{
vertexListPtr[i].point[0] = frame->fp[i].v[0]*frame->scale[0] + frame->translate[0];
vertexListPtr[i].point[1] = frame->fp[i].v[1]*frame->scale[1] + frame->translate[1];
vertexListPtr[i].point[2] = frame->fp[i].v[2]*frame->scale[2] + frame->translate[2];
}
for (i = 0; i < modelHeader->numXYZ; i++)
{
tempv = vertexListPtr[i].point[1];
vertexListPtr[i].point[1] = vertexListPtr[i].point[2];
vertexListPtr[i].point[2] = -tempv;
}
}
st = new texCoord_t [modelHeader->numST];
if (st == NULL)
{
delete [] vertexList;
delete [] buffer;
fclose(filePtr);
return false;
}
stPtr = (stIndex_t*)&buffer[modelHeader->offsetST];
for (i = 0; i < modelHeader->numST; i++)
{
st[i].s = (float)stPtr[i].s/modelHeader->skinwidth;
st[i].t = (float)stPtr[i].t/modelHeader->skinheight;
}
triIndex = new mesh_t [modelHeader->numTris];
if (triIndex == NULL)
{
delete [] st;
delete [] vertexList;
delete [] buffer;
fclose(filePtr);
return false;
}
bufIndexPtr = (mesh_t*)&buffer[modelHeader->offsetTris];
for(i = 0; i < modelHeader->numTris; i++) // for all triangles in a frame
{
triIndex[i].meshIndex[0] = bufIndexPtr[i].meshIndex[0];
triIndex[i].meshIndex[1] = bufIndexPtr[i].meshIndex[1];
triIndex[i].meshIndex[2] = bufIndexPtr[i].meshIndex[2];
triIndex[i].stIndex[0] = bufIndexPtr[i].stIndex[0];
triIndex[i].stIndex[1] = bufIndexPtr[i].stIndex[1];
triIndex[i].stIndex[2] = bufIndexPtr[i].stIndex[2];
}
FreeBuffer();
CMesh::loadFile(filename);
NumFrames = modelHeader->numFrames;
FrameSize = modelHeader->framesize;
NumVertices = modelHeader->numXYZ;
Vertices = vertexList;
NumSTs = modelHeader->numST;
STs = st;
NumTriangles = modelHeader->numTris;
Triangles = triIndex;
aabbox BBox;
for (j = 0; j < NumFrames; j++)
{
vertexListPtr = (vector_t*)&Vertices[NumVertices*j];
BBox.reset(vertexListPtr[0].point[0], vertexListPtr[0].point[1],
vertexListPtr[0].point[2]);
for (i = 0; i < NumVertices; i++)
BBox.addInternalPoint(vertexListPtr[i].point[0], vertexListPtr[i].point[1],
vertexListPtr[i].point[2]);
BBoxes.push_back(BBox);
}
delete [] buffer;
fclose(filePtr);
loadSkin(skinfilename);
return true;
}
void CMD2Mesh::loadSkin(char *skinfilename)
{
CTexture *tx;
tx = new CTexture();
tx->buildTextureBMP24(skinfilename);
m_scenemanager->addTexture(tx);
Material.MaterialType = EMT_TEXTURE;
Material.Texture1 = tx;
}
void CMD2Mesh::FreeBuffer()
{
if (Vertices) delete [] Vertices;
if (STs) delete [] STs;
if (Triangles) delete [] Triangles;
BBoxes.clear();
}
|
8c3bf62a2260f58ac2bac30e14251c28181c3160 | 487d24ea70bf9aac666b75046d3c0d39ffdfc873 | /challenge6.cpp | c64f30efaa016621a4f6ac66adaacb35d596c5cf | [] | no_license | mitchellharvey/cryptopals | 03252a9380433592a5b70b72277e01de98fe6516 | 26b31cd5147993b44a611ad5e8c817ad85228622 | refs/heads/master | 2020-04-17T09:32:11.730613 | 2019-02-14T02:52:43 | 2019-02-14T02:52:43 | 67,108,415 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,337 | cpp | challenge6.cpp | #include "Utils.h"
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
int main(int argc, char** argv) {
if (argc < 2) {
std::cout << "Please specify the challenege6 file!" << std::endl;
return 1;
}
std::ifstream ifile(argv[1], std::ios_base::in);
if (!ifile.is_open()) {
std::cout << "Unable to open file: " << argv[1] << std::endl;
return 2;
}
// Load each line, base64 decode it and append it to the list of
// bytes to operate on
std::string bytes;
for(std::string line; std::getline(ifile, line); ) {
bytes += base64::decode(line);
}
ifile.close();
// Attempt to guess the repeating xor key size by comparing the edit distance
// between each key_size chunk of bytes and normalizing it (dividing the edit distance
// result by the current key_size). The key size with the smallest distance is most
// likey the correct size of the repeating xor key
size_t min_key_size = 2;
size_t max_key_size = 40;
using KEY_SIZE = std::pair<size_t, double>;
std::vector<KEY_SIZE> sorted_key_sizes;
for(size_t key_size = min_key_size; key_size <= max_key_size; ++key_size) {
size_t total_blocks = bytes.size() / key_size;
double normalized_distance = 0.0f;
for(size_t b = 0; b < total_blocks; b+=2) {
const char* b1_start = bytes.c_str() + (b * key_size);
const char* b2_start = bytes.c_str() + (b+1 * key_size);
std::string block1(b1_start, std::min(key_size, bytes.size()));
std::string block2(b2_start, std::min(key_size, bytes.size() - key_size));
normalized_distance += cipher::hamming_distance(block1, block2);
}
normalized_distance /= total_blocks;
sorted_key_sizes.push_back(KEY_SIZE(key_size, normalized_distance));
}
// Sort key sizes from lowest to highest
std::sort(sorted_key_sizes.begin(), sorted_key_sizes.end(),
[](const KEY_SIZE& p1, const KEY_SIZE& p2) {
return p1.second < p2.second;
}
);
// Starting with the most likley key size, break the bytes up into key_size number of blocks
// and for each block, fill it with all the bytes that would be encrypted with the
// same xor byte.
for(auto key_size : sorted_key_sizes) {
size_t cur_key_size = key_size.first;
std::vector<std::string> blocks(cur_key_size);
for(size_t i = 0; i < blocks.size(); ++i) {
const char* cur = bytes.c_str() + i;
const char* end = bytes.c_str() + bytes.size();
while(cur <= end) {
blocks[i] += *cur;
cur += cur_key_size;
}
}
// Now we have our blocks, guess the single xor char for each block
std::string repeating_xor_key;
for(auto block : blocks) {
repeating_xor_key += cipher::guess_xor_byte(block);
}
std::cout << "Key Size: " << cur_key_size << std::endl;
std::cout << "Score: " << key_size.second << std::endl;
std::cout << "Key: " << hex::encode(repeating_xor_key) << std::endl;
std::cout << cipher::repeating_xor(bytes, repeating_xor_key) << std::endl;
break;
}
return 0;
}
|
3cd34df392301f6120b9487e92282426a409629c | 8403304f3a79159e0a5e4cb03200d950f5359dc7 | /Day-13/50_power(x,n).cpp | cb3604a8e24dc18500558947845ed93dbd271049 | [] | no_license | pratham-0094/100DaysOfCode | c38be5bbf9332b91667e1730d87389de9f4f1879 | 19d35726e5418d77a0af410594c986c7abd2eea2 | refs/heads/main | 2023-09-05T15:55:07.564770 | 2021-11-19T17:57:36 | 2021-11-19T17:57:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 636 | cpp | 50_power(x,n).cpp | // https://leetcode.com/problems/powx-n/
#include <iostream>
using namespace std;
class Solution {
public:
double myPow(double x, int n) {
double ans=1.0;
long long num=n;
if(num<0){
num=-1*num;
}
while(num){
if(num%2){
ans=ans*x;
num=num-1;
}
else{
x=x*x;
num=num/2;
}
}
if(n<0){
ans=(double)(1.0)/(double)(ans);
}
return ans;
}
};
int main()
{
int n;
double x;
cin >>x>> n;
Solution pow;
cout << pow.myPow(x,n) << endl;
return 0;
} |
f098c8d4456454d770b4bd4f9ffc030f6ff05b18 | c7532c99dfe6fd27c6a12fdc9a98ce1fe67bc93d | /GameProject/Source/Game/Input/GameInput.cpp | 06e1f851ebb2f88243aa9845dbd871d13ff6f066 | [
"MIT"
] | permissive | lqq1985/OpenGL4.5-GameEngine | a7d3dcf408b06b59f5838290ad3a72ec51bfda1d | 79468b7807677372bbc0450ea49b48ad66bbbd41 | refs/heads/master | 2020-08-17T22:57:34.064047 | 2019-03-05T20:36:50 | 2019-03-05T20:36:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 141 | cpp | GameInput.cpp | #include <pch.h>
#include "GameInput.h"
#include <include/gl.h>
#include <Game/Game.h>
GameInput::GameInput(Game *game)
: game(game)
{
} |
25f6f62834b45dd13c98ad1ce84574f352c55db7 | 6d4726500b5b990589ed6a1ad4da0b5420ad59ca | /Assignment/chapter1/return_index_of_x_recursion.cpp | e2885fff12b0474862f0132a04d07ed146a7a141 | [] | no_license | Anandp332/Competative-Programming | d4423a85d79cea58981a599f412d277531fea96b | 6b4d64fe11e2517cbcb6f9fed9c325dec62fa22f | refs/heads/master | 2020-08-28T22:19:32.771390 | 2020-05-06T13:55:01 | 2020-05-06T13:55:01 | 217,834,756 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 634 | cpp | return_index_of_x_recursion.cpp | #include<iostream>
//#include "Solution.h"
using namespace std;
int myindex(int input[],int size,int x,int index){
if(size==0){
return -1;
}
else if(input[0]==x){
return index;
}
else{
index++;
return myindex(input+1,size-1,x,index);
}
}
int firstIndex(int input[], int size, int x) {
int index=0;
return myindex(input,size, x,index);
}
int main(){
int n;
cin >> n;
int *input = new int[n];
for(int i = 0; i < n; i++) {
cin >> input[i];
}
int x;
cin >> x;
cout << firstIndex(input, n, x) << endl;
}
|
7d7109ca492e03ff658e20ede62483282d634e5f | d9882df02f8e19fabfd9c7cadfea8e6b95a94387 | /src/utilities/setup.cpp | fee0ff12d149507b20698504e5589c0afdf53872 | [] | no_license | spenser-roark/CTSDLPort | 207b413fa69d5aeec2f6b82e6570df400e944afe | 364b773da2722b7843adcd305c2887f43a723c7a | refs/heads/master | 2020-05-20T18:42:49.252900 | 2017-12-23T13:46:57 | 2017-12-23T13:46:57 | 84,505,996 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 124 | cpp | setup.cpp | #include <iostream>
using namespace std;
#include "setup.h"
void setupPlayableCharacter(PlayableCharacter& character) {
} |
e642a8174d9f1cf6456c879831f972af93c1d162 | 7cfcc43d1eb330f56a75b9ecc76f1aa975f9a225 | /algorithmStudy/2631_lineUp.cpp | 982dfbb54a1f724394e4a16b8192eb1942ae05d2 | [] | no_license | enan501/Algorithm-study | e25f35ff6fedb7e46b154326e4145ce0948f4f5d | f8b6380b530ee08404e01b050543c81f2958169e | refs/heads/master | 2021-07-25T02:08:11.805891 | 2021-07-02T05:35:27 | 2021-07-02T05:35:27 | 162,815,602 | 0 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 382 | cpp | 2631_lineUp.cpp | #include <stdio.h>
int main(void) {
int n = 0, h=1;
int* arr = NULL, *dp = NULL;
scanf("%d", &n);
arr = new int[n];
dp = new int[n];
for(int i=0;i<n;i++)
scanf("%d", &arr[i]);
for(int i=0;i<n;i++){
dp[i] = 1;
for (int j = 0; j < i; j++) {
if (arr[j]<arr[i] && (dp[j]+1)>dp[i])
dp[i] = dp[j] + 1;
}
if (dp[i]>h) h = dp[i];
}
printf("%d", n-h);
return 0;
} |
dd1bcafefd26ce3b6aa45f2ad9388859b54a7ff7 | 91ff1a932edcfd1d2c67c6a569daa30c2bb3c0d7 | /inc/devices/can/canair.h | 83266cab2d3e0ec45511e36d688dc4fa015c47d8 | [] | no_license | spiralray/stm32f4discovery_dualshock3 | 5f08cdbd055795e951ddf3e55042629286a5dd2b | 30fe7f5474afa14e956395e2f50e6a7c5ae35fc6 | refs/heads/master | 2020-04-05T23:06:43.276315 | 2015-08-30T17:13:49 | 2015-08-30T17:13:49 | 41,635,785 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 951 | h | canair.h | /*
* led.h
*
* Created on: 2014/10/05
* Author: spiralray
*/
#pragma once
#include "config/stm32plus.h"
#include "hardware/canroot.h"
namespace stm32plus{
class CanAir {
private:
CanTxMsg TxMessage;
CanRoot *can;
public:
CanAir(CanRoot *_can){
can = _can;
TxMessage.StdId = 0x150;
TxMessage.ExtId = 0x01;
TxMessage.RTR = CAN_RTR_DATA;
TxMessage.IDE = CAN_ID_STD;
TxMessage.DLC = 1;
TxMessage.Data[0] = 0x00;
}
CanAir(CanRoot *_can, uint32_t stdid){
can = _can;
TxMessage.StdId = stdid;
TxMessage.ExtId = 0x01;
TxMessage.RTR = CAN_RTR_DATA;
TxMessage.IDE = CAN_ID_STD;
TxMessage.DLC = 1;
TxMessage.Data[0] = 0x00;
}
void Set(int ch){
TxMessage.Data[0] |= 0x01 << ch;
}
void Reset(int ch){
TxMessage.Data[0] &= ~(0x01 << ch);
}
void Update(){
can->Send(&TxMessage);
}
};
}
|
87bf5943b2579b95fac99f204468aa4d126f7aac | d1524d8828f573bd53a3be78a9451d1789c9dca7 | /NetEventService/Channel.cpp | 5bfb5851595f2a9c780e4676a8162485a344abb8 | [] | no_license | liunatural/NetEventServiceSolution | 750b2aa1f482b07f4de20e1280eaa46446baf3fa | 33e5dc785bcf6db21328d981a09d27d3502490ed | refs/heads/master | 2020-03-30T12:38:19.391476 | 2019-08-02T06:07:12 | 2019-08-02T06:07:12 | 151,232,745 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,953 | cpp | Channel.cpp | //**************************************************************************
// File......... : Channel.cpp
// Project...... : VR
// Author....... : Liu Zhi
// Date......... : 2018-09
// Description.. : Implementation file for class Channel used as user messages processing
// and user connection data managements.
//
// History...... : First created by Liu Zhi 2018-09
//**************************************************************************
#include "Channel.h"
#include "event2/buffer.h"
#include "event2/event.h"
#include "MessageQueue.h"
#include "NetEventServer.h"
#include "ChannelManager.h"
#include "protocol.h"
Channel::Channel(struct bufferevent *bev)
{
m_bev = bev;
m_bUsedFlag = false;
m_readBuffer = new DynamicBuffer();
}
Channel::~Channel()
{
if (m_fd != -1)
{
evutil_closesocket(m_fd);
//bufferevent_free(m_bev);
}
if (m_readBuffer)
{
delete m_readBuffer;
}
}
MessageQueueAB* Channel::GetMsgQueueAB()
{
return m_pMsgQAB;
}
void Channel::SetMsgQueueAB(MessageQueueAB* pMsgQAB)
{
m_pMsgQAB = pMsgQAB;
}
NetEventServer* Channel::GetNetEventServer()
{
return m_pNetEvtSvr;
}
void Channel::DoRead()
{
char data[1024 * 4] = {0};
int nbytes = 0;
int TotalBytes = 0;
if (m_bev == NULL)
{
return;
}
int len = (int)bufferevent_read(m_bev, data, sizeof(data));
m_readBuffer->Push(data, len);
ReadPackage();
}
void Channel::ReadPackage()
{
while (m_readBuffer->Size() >= MessagePackage::header_length)
{
int len = *(int*)m_readBuffer->Peek();
if (m_readBuffer->Size() < len + MessagePackage::header_length)
{
break;
}
char* data = m_readBuffer->Peek();
MessagePackage msgPack;
memcpy(msgPack.data(), data, len + MessagePackage::header_length);
msgPack.SetLinkID(m_channelID);//将数据包加上连接ID
m_pMsgQAB->Push(msgPack);
m_readBuffer->Pop(len + MessagePackage::header_length);
}
}
void Channel::CloseSocket()
{
if (m_fd != -1)
{
bufferevent_setfd(m_bev, -1);
evutil_closesocket(m_fd);
bufferevent_free(m_bev);
m_fd = -1;
m_bev = NULL;
m_bUsedFlag = false;
int cid = GetChannelID();
m_pNetEvtSvr->GetChannelManager()->ReleaseID(cid); //归还ChannelID
int dataLen = strlen(m_ip.c_str());
//将用户断开连接信息返回给上层应用
MessagePackage msgPack;
msgPack.WriteHeader(link_disconnected, 0);
msgPack.WriteBody((void*)m_ip.c_str(), dataLen);
msgPack.SetLinkID(m_channelID);
m_pMsgQAB->Push(msgPack);
}
}
int Channel::SendData(void* data, int len)
{
if (m_fd == -1)
{
return send_disconnected;
}
//当用户断开连接时, bufferevent_write函数会死锁在m_bev里不返回
//if (0 != bufferevent_write(m_bev, data, len))
//{
// printf("bufferevent_write error\n");
// return send_stat::send_buffer_full;
//}
int ret = send(m_fd, (const char*)data, len, 0);
return send_succeed;
}
|
e8b9ffa5b8a4b931259a82de78504b24570bdb10 | 6ceb8c2564498a0c2b5071408380999b13115432 | /session_manager.cpp | 429fba0f00acbcd7aee1ecbe1c6fc68d60421f5b | [] | no_license | mfzhang/TradeRunner | 7e210f03bc013ced45ec5eabe992ab6be2fdef28 | d1cfa45ae0dbbbb3b72a7dc1747586a2da8fb28a | refs/heads/master | 2022-12-05T03:41:50.484988 | 2020-08-20T13:12:47 | 2020-08-20T13:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 256 | cpp | session_manager.cpp | #include "session_manager.h"
session_manager::session_manager(boost::asio::io_service& io_srv, int expires_time)
:m_io_srv(io_srv),
m_check_tick(io_srv),
m_expires_time(expires_time),
m_next_session(0)
{
}
session_manager::~session_manager()
{
}
|
7de8efb9ab1badb7e77c3a7484b3cdb292153770 | 056f44f4693912c9436bce21f0eb1ad02d68b86f | /src/ofApp.h | 2c73b2fe67705dbe04a27fdfffabe6e62882583a | [] | no_license | DHaylock/WatershedAlgorithm | d67c294782637d5a4feeb738ce57572a5ecf714d | 1d92d8f03c61cd3b1a2cb7b67ee14d755e8829d8 | refs/heads/master | 2016-08-13T01:20:33.053838 | 2016-02-22T20:12:20 | 2016-02-22T20:12:20 | 52,302,152 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,265 | h | ofApp.h | #pragma once
#include "ofMain.h"
#include "ofxDatGui.h"
#include "Detection_Abstraction.h"
class ofApp : public ofBaseApp{
public:
void setup();
void update();
void draw();
void keyPressed(int key);
void keyReleased(int key);
void mouseMoved(int x, int y );
void mouseDragged(int x, int y, int button);
void mousePressed(int x, int y, int button);
void mouseReleased(int x, int y, int button);
void mouseEntered(int x, int y);
void mouseExited(int x, int y);
void windowResized(int w, int h);
void dragEvent(ofDragInfo dragInfo);
void gotMessage(ofMessage msg);
void personDetected(int &val);
void personLeft(int &val);
Detection_Abstraction detection;
vector<string> videosInDirectory;
vector<string> videoNames;
// GUI Objects
ofxDatGui * gui;
void onButtonEvent(ofxDatGuiButtonEvent e);
void onSliderEvent(ofxDatGuiSliderEvent e);
void onTextInputEvent(ofxDatGuiTextInputEvent e);
void on2dPadEvent(ofxDatGui2dPadEvent e);
void onDropdownEvent(ofxDatGuiDropdownEvent e);
void onColorPickerEvent(ofxDatGuiColorPickerEvent e);
void onMatrixEvent(ofxDatGuiMatrixEvent e);
void setupGUI();
};
|
f64e15fe34a90dea29fc74bcad5d0536eef4d999 | a848bf6b9e6c7284e8e480f7c925787b13be743e | /Fade LEDs/PR02_Fade_LEDs/PR02_Fade_LEDs.ino | 861eed6afb5660c3a10db968c94aedd5157e6d88 | [] | no_license | mouradelfilali2017/Fade_LEDs | eea3d5e7ef30a823f2e24fea955d2f215dbd3ab6 | aefde04b8999cb93febf4dda8a734e394714f445 | refs/heads/master | 2020-03-18T03:10:53.401258 | 2018-05-21T06:17:33 | 2018-05-21T06:17:33 | 134,226,570 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,443 | ino | PR02_Fade_LEDs.ino | /**********************************************************************************
** **
** Fade LEDs **
** **
** MOURAD EL FILALI TABBAI **
**********************************************************************************/
//********** Includes *************************************************************
//********** Variables ************************************************************
const int led0 = 3; // donar nom al pin 3 de l’Arduino
const int led1 = 5; // donar nom al pin 5 de l’Arduino
const int led2 = 6; // donar nom al pin 6 de l’Arduino
const int led3 = 9; // donar nom al pin 9 de l’Arduino
const int led4 = 10; // donar nom al pin 10 de l’Arduino
const int led5 = 11; // donar nom al pin 11 de l’Arduino
int velocitat = 1000; // velocitat de l'acció en ms
//********** Setup ****************************************************************
void setup()
{
pinMode(led0, OUTPUT); // definir el pin 3 com una sortida
pinMode(led1, OUTPUT); // definir el pin 5 com una sortida
pinMode(led2, OUTPUT); // definir el pin 6 com una sortida
pinMode(led3, OUTPUT); // definir el pin 9 com una sortida
pinMode(led4, OUTPUT); // definir el pin 10 com una sortida
pinMode(led5, OUTPUT); // definir el pin 11 com una sortida
}
//********** Loop *****************************************************************
void loop()
{
analogWrite(led0, 0); // posar PWM del pin 3 a 0
analogWrite(led1, 0); // posar PWM del pin 5 a 0
analogWrite(led2, 0); // posar PWM del pin 6 a 0
analogWrite(led3, 0); // posar PWM del pin 9 a 0
analogWrite(led4, 0); // posar PWM del pin 10 a 0
analogWrite(led5, 0); // posar PWM del pin 11 a 0
delay(velocitat); // es queden leds velocitat ms en aquest estat
analogWrite(led0, 4); // posar PWM del pin 3 a 4
analogWrite(led1, 0); // posar PWM del pin 5 a 0
analogWrite(led2, 0); // posar PWM del pin 6 a 0
analogWrite(led3, 0); // posar PWM del pin 9 a 0
analogWrite(led4, 0); // posar PWM del pin 10 a 0
analogWrite(led5, 0); // posar PWM del pin 11 a 0
delay(velocitat); // es queden leds velocitat ms en aquest estat
analogWrite(led0, 12); // posar PWM del pin 3 a 12
analogWrite(led1, 4); // posar PWM del pin 5 a 4
analogWrite(led2, 0); // posar PWM del pin 6 a 0
analogWrite(led3, 0); // posar PWM del pin 9 a 0
analogWrite(led4, 0); // posar PWM del pin 10 a 0
analogWrite(led5, 0); // posar PWM del pin 11 a 0
delay(velocitat); // es queden leds velocitat ms en aquest estat
analogWrite(led0, 27); // posar PWM del pin 3 a 27
analogWrite(led1, 12); // posar PWM del pin 5 a 12
analogWrite(led2, 4); // posar PWM del pin 6 a 4
analogWrite(led3, 0); // posar PWM del pin 9 a 0
analogWrite(led4, 0); // posar PWM del pin 10 a 0
analogWrite(led5, 0); // posar PWM del pin 11 a 0
delay(velocitat); // es queden leds velocitat ms en aquest estat
analogWrite(led0, 62); // posar PWM del pin 3 a 62
analogWrite(led1, 27); // posar PWM del pin 5 a 27
analogWrite(led2, 12); // posar PWM del pin 6 a 12
analogWrite(led3, 4); // posar PWM del pin 9 a 4
analogWrite(led4, 0); // posar PWM del pin 10 a 0
analogWrite(led5, 0); // posar PWM del pin 11 a 0
delay(velocitat); // es queden leds velocitat ms en aquest estat
analogWrite(led0, 255); // posar PWM del pin 3 a 255
analogWrite(led1, 62); // posar PWM del pin 5 a 62
analogWrite(led2, 27); // posar PWM del pin 6 a 27
analogWrite(led3, 12); // posar PWM del pin 9 a 12
analogWrite(led4, 4); // posar PWM del pin 10 a 4
analogWrite(led5, 0); // posar PWM del pin 11 a 0
delay(velocitat); // es queden leds velocitat ms en aquest estat
analogWrite(led0, 255); // posar PWM del pin 3 a 255
analogWrite(led1, 255); // posar PWM del pin 5 a 255
analogWrite(led2, 62); // posar PWM del pin 6 a 62
analogWrite(led3, 27); // posar PWM del pin 9 a 27
analogWrite(led4, 12); // posar PWM del pin 10 a 12
analogWrite(led5, 4); // posar PWM del pin 11 a 4
delay(velocitat); // es queden leds velocitat ms en aquest estat
analogWrite(led0, 255); // posar PWM del pin 3 a 255
analogWrite(led1, 255); // posar PWM del pin 5 a 255
analogWrite(led2, 255); // posar PWM del pin 6 a 255
analogWrite(led3, 62); // posar PWM del pin 9 a 62
analogWrite(led4, 27); // posar PWM del pin 10 a 27
analogWrite(led5, 12); // posar PWM del pin 11 a 12
delay(velocitat); // es queden leds velocitat ms en aquest estat
analogWrite(led0, 255); // posar PWM del pin 3 a 125
analogWrite(led1, 255); // posar PWM del pin 5 a 125
analogWrite(led2, 255); // posar PWM del pin 6 a 125
analogWrite(led3, 255); // posar PWM del pin 9 a 125
analogWrite(led4, 62); // posar PWM del pin 10 a 62
analogWrite(led5, 27); // posar PWM del pin 11 a 27
delay(velocitat); // es queden leds velocitat ms en aquest estat
analogWrite(led0, 255); // posar PWM del pin 3 a 255
analogWrite(led1, 255); // posar PWM del pin 5 a 255
analogWrite(led2, 255); // posar PWM del pin 6 a 255
analogWrite(led3, 255); // posar PWM del pin 9 a 255
analogWrite(led4, 225); // posar PWM del pin 10 a 255
analogWrite(led5, 62); // posar PWM del pin 11 a 62
delay(velocitat); // es queden leds velocitat ms en aquest estat
analogWrite(led0, 255); // posar PWM del pin 3 a 255
analogWrite(led1, 255); // posar PWM del pin 5 a 255
analogWrite(led2, 255); // posar PWM del pin 6 a 255
analogWrite(led3, 255); // posar PWM del pin 9 a 255
analogWrite(led4, 225); // posar PWM del pin 10 a 255
analogWrite(led5, 225); // posar PWM del pin 11 a 255
delay(velocitat); // es queden leds velocitat ms en aquest estat
}
//********** Funcions *************************************************************
|
77118c2f7bf0987762e8205b5a3d81ae64140ae1 | c8bc887dce587649a366772bbd78f6e630c395bf | /frontpropagate.cc | b67ac149d23c25a18dd75fd4399cd482f3f71082 | [] | no_license | DuyHuynhLe/StageAtEpitaCode | b53dbf4f74bf4145f7d2558d370403f56dcbdde9 | ad5c0d249b364ffdad4bcb7e7669870fb834d2ba | refs/heads/master | 2021-01-21T04:54:18.653478 | 2016-05-24T13:02:48 | 2016-05-24T13:02:48 | 39,623,484 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,486 | cc | frontpropagate.cc | /*
*Big change: normalisation the laplacian before continue
*Big change: Laplacian is float
*/
/*
* CODE1 Displace the laplacian of different value
*
*
*/
#include <iostream>
#include <mln/core/image/image2d.hh>
#include <mln/debug/println.hh>
#include <mln/io/pgm/load.hh>
#include <tos_src/immerse.hh>
#include <mln/win/rectangle2d.hh>
#include <mln/morpho/laplacian.hh>
#include <mln/morpho/gradient.hh>
#include <mln/arith/times.hh>
#include <vector>
#include <mln/data/fill.hh> //for debugging
#include <mln/util/timer.hh> //for timer
#include <mln/io/pgm/save.hh>
#include <mln/io/pbm/save.hh>
#include <mln/io/magick/load.hh>
#include <mln/io/magick/save.hh>
#include <mln/value/rgb8.hh>
#include <mln/fun/v2v/rgb_to_int_u.hh>
#include <mln/linear/gaussian.hh>
#include <mln/util/array.hh>
#include "frontpropagateOp.hh"
#include "display.hh"
#define color 1
#define black 0
#define gradi 0
/*
i=5;./StageAtEpitaCode/trunk/frontpropagate ~/Documents/ima/test_set/img_${i}.jpg 11 11 0Testoutput/lap${i}.ppm 0Testoutput/lab${i}.png 30 0Testoutput/bin${i}.pbm 0 0 1 1 0Testoutput/${i}.png 3.1 0Testoutput/Gau${i}.png 0Testoutput/gt.txt
*/
void help(char * argv[])
{
std::cerr << "usage: " << argv[0] << " input.ext Laplace_window gradian_window laplaceOutput.ext labelOutput.ext parenthoodOutput.ext gradian_threadholding.ext contour(1|0) elementBox(1|0) textBox(1|0) textBox_ori(1|0) textBox_ori.ext " << std::endl;
std::abort();
}
int main(int argc, char* argv[])
{
if (argc < 8)
help(argv);
using namespace std;
using namespace mln;
util::timer t1,t2,t4,t5;
t1.start();t2.start();t4.start();
//input
image2d<value::rgb8> inputrgb;
io::magick::load(inputrgb,argv[1]);
image2d<value::int_u8> input = tos::transformBnW(inputrgb);
border::thickness = 1;
std::cout <<" input and convert "<<t4.stop() * 1000. << " ms" << std::endl;
//image2d<value::int_u8> input_blur;
//blur out the image
//if(atof(argv[13]))
//input_blur = linear::gaussian(input, atof(argv[13]));
//input = input_blur;
//io::magick::save(input,argv[14]);
//io::magick::save(tos::immerse2(input),argv[14]);
//*---> Laplacian
//create structure element
t4.reset();
t4.start();
win::rectangle2d lapw( atoi(argv[2]),atoi(argv[2]));
win::rectangle2d gradw( atoi(argv[3]), atoi(argv[3]));
image2d<float> lap(input.domain());
//Calculate Laplacian
morpho::laplacian(input, lapw, lap);
//Calculate gradient
/*************************************
image2d<value::int_u8> input_blur = linear::gaussian(input, atof(argv[13]));
//***********************************/
image2d<value::int_u8> grad = morpho::gradient(input,gradw);
std::cout <<"lap and grad "<<t4.stop() * 1000. << " ms" << std::endl;
t4.reset();
t4.start();
//image2d<value::int_u8> grad = morpho::gradient(input_blur,gradw);
//arith::times_cst(lap,2,lap);//2*laplacian to make sure lap is pair
//arith::times_cst(grad,2,grad);//2*laplacian to make sure lap is pair
/*
* CODE1
*/
//image2d<float> lapB(input_blur.domain());
//morpho::laplacian(input_blur, lapw, lapB);
//lapB = tos::normalisation(tos::immerse2(lapB));
//image2d<value::int_u8> gradB = tos::immerse2(morpho::gradient(input_blur,gradw));
/*
**********************************************************
*/
display::laplacian_colorizationNotDependValue(lap,argv[5]);
lap = tos::immerse2(lap);
lap = tos::normalisation(lap); // BIGCHANGE
//save the laplacian
display::laplacian_colorizationNotDependValue(lap,argv[4]);
/*
//immerse the gradient
grad = tos::immerse2(grad);
//******************************************************************A TESTING LINE HERE
//io::magick::save(grad,"grad.png");
//******************************************************************A TESTING LINE HERE
//save the gradient
//arith::times_cst(input,2,input);//2*laplacian to make sure input is pair this input will be used for average gray level calculation
params::laplacianThreshold=atoi(argv[6]);
//image2d<unsigned int> output_4 = tos::labeling(tos::immerse2(input),lap,grad,30,treeOfShape);//replace 30 = atof(argv[6]) (gradThresHold)
//cout<<grad.offset_of_point(grad.domain().pmin())<<endl;
//cout<<lap.offset_of_point(lap.domain().pmin())<<endl;
//cout<<input.offset_of_point(input.domain().pmin())<<endl;
//cout<<"end of test 1"<<endl;
image2d<value::int_u8> inputImmersed =tos::immerse2(input);
std::cout <<"Immersed "<<t4.stop() * 1000. << " ms" << std::endl;
t5.start();
//init output value
tos::tos treeOfShape(lap.nrows()*lap.ncols());
util::timer t3;
t3.start();
image2d<unsigned int> output_4 = tos::labeling(inputImmersed,lap,grad,30,treeOfShape);//replace 30 = atof(argv[6]) (gradThresHold)
std::cout <<"outside labeling "<< t3.stop() * 1000. << " ms" << std::endl;
//get an output
std::cout<<"number of Labels: "<<treeOfShape.nLabels<<endl;
std::cout << t1.stop() * 1000. << " ms" << std::endl;
t1.start();
//get the bounding box
if(atoi(argv[10]))
{
treeOfShape.boundingBoxes = tos::distance::getRegions(output_4,treeOfShape);
}
//get the bounding box and display on original image
if(atoi(argv[10]) and atoi(argv[11]) )
{
//display::box_on_image(inputrgb,treeOfShape,argv[12]);
}
//displace the labels with different color with color labels
display::saveGT(treeOfShape,argv[15]);
#if color
//display::label_colorization(output_4,argv[5],treeOfShape,atoi(argv[8]),atoi(argv[9]),atoi(argv[10]));
#endif
#if gradi
//display::label_colorization(output_4,argv[5],treeOfShape,atoi(argv[8]),atoi(argv[9]),atoi(argv[10]),grad);
#endif
#if black
//display::label_colorizationref(output_4,argv[5],treeOfShape,atoi(argv[8]),atoi(argv[9]),atoi(argv[10]),lap);
#endif
//io::pbm::save(tos::binarization(output_4,treeOfShape,3),argv[7]);
//for(int i =0;i<treeOfShape.contourSize.size();i++)
// cout<<treeOfShape.boxes[i].center[1]<<" "<<treeOfShape.boxes[i].height<<" "<<treeOfShape.boxes[i].width<<endl;
// cout<<endl;
//cout<<treeOfShape.lambda.size()<<" "<<treeOfShape.nLabels<<" "<<treeOfShape.border.size()<<endl;
std::cout << t2.stop() * 1000. << " ms" << std::endl;
std::cout << t1.stop() * 1000. << " ms" << std::endl;
std::cout <<"labeling and grouping "<< t5.stop() * 1000. << " ms" << std::endl;
*/
}
//attention, the tree code lable from 1, but the vector starts from 0
|
c8e6e2226bf4cd36ff63e2df12ee997993b2dda8 | 12322278b3c0c26d91dbbd585d314c63e3ffedb4 | /test/graph/bipartite_test.cpp | 2879a4d65611a25d6a44f3a62141d5a500435089 | [
"BSL-1.0"
] | permissive | dieram3/competitive-programming-library | 3fe18b25ef0517230882f5b3dd100602966b1b00 | 29bd0204d00c08e56d1f7fedc5c6c3603c4e5121 | refs/heads/master | 2021-08-18T08:09:41.456258 | 2020-09-06T04:17:55 | 2020-09-06T04:19:04 | 34,582,884 | 27 | 5 | null | 2016-12-06T04:24:09 | 2015-04-25T19:30:09 | C++ | UTF-8 | C++ | false | false | 2,452 | cpp | bipartite_test.cpp | // Copyright Diego Ramirez 2015
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <cpl/graph/bipartite.hpp>
#include <gtest/gtest.h>
#include <cpl/graph/undirected_graph.hpp> // undirected_graph
#include <cstddef> // size_t
#include <vector> // vector
using cpl::is_bipartite;
using cpl::undirected_graph;
using std::size_t;
using std::vector;
static void check_colors(const undirected_graph& g, const vector<bool>& color) {
EXPECT_EQ(g.num_vertices(), color.size());
for (size_t e = 0; e != g.num_edges(); ++e) {
const size_t u = g.source(e);
const size_t v = g.target(e);
EXPECT_NE(color[u], color[v]) << "Neighbor vertices " << u << " and " << v
<< " should have different colors";
}
}
static void check_bipartite(const undirected_graph& g) {
vector<bool> color;
EXPECT_TRUE(is_bipartite(g, color));
check_colors(g, color);
}
TEST(IsBipartiteTest, EmptyGraphTest) {
undirected_graph g(0);
check_bipartite(g);
}
TEST(IsBipartiteTest, AloneVerticesTest) {
undirected_graph g(6);
check_bipartite(g);
}
TEST(IsBipartiteTest, ConnectedBipartiteGraphTest) {
undirected_graph g(7);
g.add_edge(0, 1);
g.add_edge(0, 4);
g.add_edge(1, 2);
g.add_edge(1, 5);
g.add_edge(2, 6);
g.add_edge(3, 6);
g.add_edge(4, 5);
ASSERT_EQ(7, g.num_edges());
check_bipartite(g);
}
TEST(IsBipartiteTest, DisconnectedBipartiteGraphTest) {
undirected_graph g(8);
g.add_edge(0, 1);
g.add_edge(0, 7);
g.add_edge(1, 6);
g.add_edge(2, 4);
g.add_edge(3, 4);
g.add_edge(6, 7);
ASSERT_EQ(6, g.num_edges());
check_bipartite(g);
}
TEST(IsBipartiteTest, ConnectedNonBipartiteGraphTest) {
undirected_graph g(6);
g.add_edge(0, 1);
g.add_edge(0, 2);
g.add_edge(1, 3);
g.add_edge(2, 3);
g.add_edge(2, 4);
g.add_edge(3, 4);
g.add_edge(4, 5);
ASSERT_EQ(7, g.num_edges());
vector<bool> color;
EXPECT_FALSE(is_bipartite(g, color));
}
TEST(IsBipartiteTest, DisconnectedNonBipartiteGraphTest) {
undirected_graph g(11);
g.add_edge(0, 1);
g.add_edge(0, 3);
g.add_edge(1, 2);
g.add_edge(2, 3);
g.add_edge(4, 7);
g.add_edge(5, 6);
g.add_edge(5, 8);
g.add_edge(6, 8);
ASSERT_EQ(8, g.num_edges());
vector<bool> color;
EXPECT_FALSE(is_bipartite(g, color));
}
|
b4133d1b4168f4b33cc58bdea50dad7597ea9fbf | 2d8f99055f2631f562153ff6b7b40101f5484ca8 | /rotatearray efficiet.cpp | c080e480b7fdbc64d0767201f243f85c3f23d9e4 | [] | no_license | priya139A/geeks-for-geeks-codes | 36b25761c74496b3efd6b041ead8b15a21881714 | 0c95df3cb8a6fe47abf8fd075ea5584b4a3914c0 | refs/heads/main | 2023-08-01T03:30:22.295014 | 2021-09-17T09:20:27 | 2021-09-17T09:20:27 | 373,760,560 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 341 | cpp | rotatearray efficiet.cpp | void rotate(vector<int>& nums, int k) {
int n=nums.size();
k=k%n;
reverse(nums.begin(),nums.end());
for(int i=0;i<k;i++)
nums.push_back(nums[i]);
reverse(nums.begin(),nums.end());
for(int i=0;i<k;i++)
nums.pop_back();
}
|
65dbde58ef22a4b0b60b54c876d04ae0ac5c7dc3 | c4372f2763e5ca9492d2d476c3ee0ce1dec54d35 | /SMEGen_BLUFOR.IslaDuala3/config/params.hpp | 6cf5df8c2d51a24b34443d92f21877ffa3ed1c0f | [] | no_license | TaskForce47/SME | eb9f9a5d3bfb53ee7b330f1e191b812d8d938346 | 1728f4316c529c009634cae022d80079e06d149f | refs/heads/master | 2021-01-11T21:27:53.934228 | 2016-09-19T19:29:44 | 2016-09-19T19:29:44 | 78,788,282 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,890 | hpp | params.hpp | /*
=======================================================================================================================
SME.Gen - Small Military Encounter Genenerator
File: params.hpp
Author: T-800a
E-Mail: t-800a@gmx.net
=======================================================================================================================
*/
class Params
{
class param_enemy {
title = "Enemy Faction";
values[] = { 0, 1, 2, 3, 4, 5, 6, 7, 200, 999 };
texts[] = { "CSAT", "CSAT Urban", "CSAT Guerilla", "AAF", "AAF - Guerilla", "CUP - Takistan Army", "CUP - Takistan Locals", "CUP - NAPA", "OPFOR RHS EMR", "DEFAUL - CSAT Urban" };
default = 999;
};
class param_reward {
title = "Player Faction";
values[] = { 0, 2, 200, 999 };
texts[] = { "BLUFOR", "CUP USMC", "RHS USArmy", "DEFAULT - BLUFOR" };
default = 999;
};
class param_sites {
title = "Simultaneous Mission Sites";
values[] = { 0, 1, 2, 3, 999 };
texts[] = { "1 Site", "2 Sites", "3 Sites", "4 Sites", "DEFAULT - 2 Sites" };
default = 999;
};
class param_skill {
title = "AI Skill";
values[] = { 0, 1, 2, 999 };
texts[] = { "Militia", "Army", "Special Forces", "DEFAULT - Militia" };
default = 999;
};
class param_loadout {
title = "Keep Loadout After Respawn";
values[] = { 0, 1, 999 };
texts[] = { "YES", "NO", "DEFAULT - Yes" };
default = 999;
};
class param_vehiclepatrols {
title = "Allow Vehicle Patrols";
values[] = { 0, 1, 999 };
texts[] = { "ENABLED", "DISABLED", "DEFAULT - ENABLED" };
default = 999;
};
class param_radio_system {
title = "Radio System";
values[] = {2, 999};
texts[] = {"ACRE 2", "DEFAULT - ACRE 2"};
default = 999;
};
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.