hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
01d27102bfa6e032fdf184a2f54d22e580f06ec2
5,824
cc
C++
trabalhos/atividadePratica2/talvez_correto/lib/Task.cc
paladini/UFSC-so1-2015-01
891696fd555fa0f31270d87b31ffe00f724da748
[ "MIT" ]
null
null
null
trabalhos/atividadePratica2/talvez_correto/lib/Task.cc
paladini/UFSC-so1-2015-01
891696fd555fa0f31270d87b31ffe00f724da748
[ "MIT" ]
null
null
null
trabalhos/atividadePratica2/talvez_correto/lib/Task.cc
paladini/UFSC-so1-2015-01
891696fd555fa0f31270d87b31ffe00f724da748
[ "MIT" ]
null
null
null
/* * Task.cc * * Created on: Feb 27, 2014 * Author: arliones */ #include "Task.h" #include "Scheduler.h" #include "BOOOS.h" #include <stdio.h> #include <ucontext.h> #include <stdlib.h> #include <iostream> #include <time.h> #define STACKSIZE 32768 /* tamanho de pilha das threads */ using namespace std; namespace BOOOS { volatile Task * Task::__running; Task * Task::tMain; Queue Task::__ready; Queue Task::__sleep; volatile int Task::__tid_counter = 0; // This method initializes Task's global attributes void Task::init() { tMain = new Task(0, 0, (char*) "\tMain"); tMain->_response = Timer::time(); __running = tMain; __running->_activations = 1; } // This constructor creates a task. // - entry_point: pointer to a function that implements the behavior of the task // - nargs: number of arguments sent to the entry_point function // - arg: vector with the arguments for the entry_point function Task::Task(void (*entry_point)(void *), int nargs, void * arg) { getcontext(&this->ctask); char * stack; stack = (char *) malloc(STACKSIZE); if (stack) { this->_cputime = 0; this->_cpuaux = 0; this->_coxilo = 0; this->_codeExit = 0; this->_activations = 0; this->_response = Timer::time(); this->ctask.uc_stack.ss_sp = stack; this->ctask.uc_stack.ss_size = STACKSIZE; this->ctask.uc_stack.ss_flags = 0; this->ctask.uc_link = 0; this->_tid = __tid_counter++; if (nargs > 0) { this->_state = READY; insert_in_ready(this); } else { this->_state = RUNNING; } } else { perror("Erro na criação da pilha: "); exit(1); } if (nargs > 0) { makecontext(&(this->ctask), (void(*)(void))entry_point, nargs, arg); } //inicializar timer do cputime //inicializar timer do TR } // This destructor destroys/frees any resources allocated in the constructor Task::~Task() { __tid_counter--; } // This method transfers the execution flow from the current task to the Task 't'. // - t: pointer to the task that will assume the CPU. // - s: state that the current task will assume void Task::pass_to(Task * t, State s) { Task * aux = this->self(); if (__running->_state != SCHEDULER) { __running->_cputime = Timer::time() + __running->_cputime - __running->_cpuaux; __running->_state = s; } if (t->_state != SCHEDULER) { t->_state = RUNNING; t->_cpuaux = Timer::time(); } //t->_activations++; __running = t; if (__running->_state == RUNNING) { __running->_activations++; } if (aux->_state == READY) { insert_in_ready(aux); } swapcontext(&(aux->ctask), &(t->ctask)); } void Task::insert_in_ready(Task * task) { if (BOOOS_Configuration::SCHEDULER_TYPE == Scheduler::SCHED_FCFS) { __ready.insert(task); } if (BOOOS_Configuration::SCHEDULER_TYPE == Scheduler::SCHED_PRIORITY) { __ready.insert_ordered(task); } } void Task::yield() { pass_to(Scheduler::self()); } // This method finalizes a task // - code: exit/error code. void Task::exit(int code) { __tid_counter--; Task * aux; this->_codeExit = code; while (this->_sleepQueue.length() != 0) { aux = (Task *) this->_sleepQueue.remove(); aux->_state = READY; insert_in_ready(aux); } if (this->state() != SCHEDULER) { this->_response = Timer::time() - this->_response; cout << "Task " << this->_tid << " exit: response time " << this->_response / 1000 << " ms, CPU time " << this->_cputime / 1000 << " ms, " << this->_activations << " activations" << endl; pass_to(Scheduler::self(), FINISHING); } else { pass_to(tMain, FINISHING); } } int Task::count() { return __tid_counter; } int Task::join(Task * b) { if (b == 0) return -1; if (b->_state == FINISHING) { return b->_codeExit; } else { if (b == this) return 0; //__ready.removeItem(Task::self()); Task::self()->_state = WAITING; b->_sleepQueue.insert(Task::self()); this->pass_to(Scheduler::self(), WAITING); return b->_codeExit; } } void Task::requestWakeup() { int aux = Timer::time(); int cont = 0; Task * task; if(__sleep.length() == 0) cout << "nada no sleep" << endl; while (cont != __sleep.length() + 1) { task = (Task *) __sleep.getItem(cont); if (task != 0) { if (aux >= task->coxilo()) { task->_state = READY; cout << "Acordei" << endl; __sleep.removeItem(task); this->insert_in_ready(task); } else { cont++; } } } return; } void Task::sleep(int t) { int aux = 0; if (t != 0) { //__ready.removeItem(this); this->_state = WAITING; __sleep.insert(self()); aux = Timer::time(); //start this->coxilo(aux + t); pass_to(Scheduler::__dispatcher); } else { return; } return; } } /* namespace BOOOS */
28
199
0.5091
[ "vector" ]
01d461371f68340ea8d1be08571a473274153a84
4,966
cc
C++
chrome/browser/bookmark_bar_context_menu_controller_test.cc
bluebellzhy/chromium
008c4fef2676506869a0404239da31e83fd6ccc7
[ "BSD-3-Clause" ]
1
2016-05-08T15:35:17.000Z
2016-05-08T15:35:17.000Z
chrome/browser/bookmark_bar_context_menu_controller_test.cc
bluebellzhy/chromium
008c4fef2676506869a0404239da31e83fd6ccc7
[ "BSD-3-Clause" ]
null
null
null
chrome/browser/bookmark_bar_context_menu_controller_test.cc
bluebellzhy/chromium
008c4fef2676506869a0404239da31e83fd6ccc7
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/bookmark_bar_context_menu_controller.h" #include "chrome/browser/bookmarks/bookmark_model.h" #include "chrome/browser/profile.h" #include "chrome/browser/views/bookmark_bar_view.h" #include "chrome/common/pref_names.h" #include "chrome/common/pref_service.h" #include "chrome/browser/page_navigator.h" #include "chrome/test/testing_profile.h" #include "testing/gtest/include/gtest/gtest.h" #include "generated_resources.h" namespace { // PageNavigator implementation that records the URL. class TestingPageNavigator : public PageNavigator { public: virtual void OpenURL(const GURL& url, WindowOpenDisposition disposition, PageTransition::Type transition) { urls_.push_back(url); } std::vector<GURL> urls_; }; } // namespace class BookmarkBarContextMenuControllerTest : public testing::Test { public: BookmarkBarContextMenuControllerTest() : bb_view_(NULL), model_(NULL) { } virtual void SetUp() { BookmarkBarView::testing_ = true; profile_.reset(new TestingProfile()); profile_->set_has_history_service(true); profile_->CreateBookmarkModel(true); model_ = profile_->GetBookmarkModel(); bb_view_.reset(new BookmarkBarView(profile_.get(), NULL)); bb_view_->SetPageNavigator(&navigator_); AddTestData(); } virtual void TearDown() { BookmarkBarView::testing_ = false; // Flush the message loop to make Purify happy. message_loop_.RunAllPending(); } protected: MessageLoopForUI message_loop_; scoped_ptr<TestingProfile> profile_; BookmarkModel* model_; scoped_ptr<BookmarkBarView> bb_view_; TestingPageNavigator navigator_; private: // Creates the following structure: // a // F1 // f1a // F11 // f11a // F2 void AddTestData() { std::string test_base = "file:///c:/tmp/"; model_->AddURL(model_->GetBookmarkBarNode(), 0, L"a", GURL(test_base + "a")); BookmarkNode* f1 = model_->AddGroup(model_->GetBookmarkBarNode(), 1, L"F1"); model_->AddURL(f1, 0, L"f1a", GURL(test_base + "f1a")); BookmarkNode* f11 = model_->AddGroup(f1, 1, L"F11"); model_->AddURL(f11, 0, L"f11a", GURL(test_base + "f11a")); model_->AddGroup(model_->GetBookmarkBarNode(), 2, L"F2"); } }; // Tests Deleting from the menu. TEST_F(BookmarkBarContextMenuControllerTest, DeleteURL) { BookmarkBarContextMenuController controller( bb_view_.get(), model_->GetBookmarkBarNode()->GetChild(0)); GURL url = model_->GetBookmarkBarNode()->GetChild(0)->GetURL(); ASSERT_TRUE(controller.IsCommandEnabled(IDS_BOOKMARK_BAR_REMOVE)); // Delete the URL. controller.ExecuteCommand(IDS_BOOKMARK_BAR_REMOVE); // Model shouldn't have URL anymore. ASSERT_FALSE(model_->IsBookmarked(url)); } // Tests open all on a folder with a couple of bookmarks. TEST_F(BookmarkBarContextMenuControllerTest, OpenAll) { BookmarkNode* folder = model_->GetBookmarkBarNode()->GetChild(1); BookmarkBarContextMenuController controller(bb_view_.get(), folder); ASSERT_TRUE(controller.IsCommandEnabled(IDS_BOOMARK_BAR_OPEN_ALL)); ASSERT_TRUE(controller.IsCommandEnabled(IDS_BOOMARK_BAR_OPEN_ALL_INCOGNITO)); ASSERT_TRUE(controller.IsCommandEnabled(IDS_BOOMARK_BAR_OPEN_ALL_NEW_WINDOW)); // Open it. controller.ExecuteCommand(IDS_BOOMARK_BAR_OPEN_ALL); // Should have navigated to F1's children. ASSERT_EQ(2, navigator_.urls_.size()); ASSERT_TRUE(folder->GetChild(0)->GetURL() == navigator_.urls_[0]); ASSERT_TRUE(folder->GetChild(1)->GetChild(0)->GetURL() == navigator_.urls_[1]); // Make sure incognito is disabled when OTR. profile_->set_off_the_record(true); ASSERT_TRUE(controller.IsCommandEnabled(IDS_BOOMARK_BAR_OPEN_ALL)); ASSERT_FALSE(controller.IsCommandEnabled(IDS_BOOMARK_BAR_OPEN_ALL_INCOGNITO)); ASSERT_TRUE( controller.IsCommandEnabled(IDS_BOOMARK_BAR_OPEN_ALL_NEW_WINDOW)); } // Tests that menus are appropriately disabled for empty folders. TEST_F(BookmarkBarContextMenuControllerTest, DisableForEmptyFolder) { BookmarkNode* folder = model_->GetBookmarkBarNode()->GetChild(2); BookmarkBarContextMenuController controller(bb_view_.get(), folder); EXPECT_FALSE(controller.IsCommandEnabled(IDS_BOOMARK_BAR_OPEN_ALL)); EXPECT_FALSE( controller.IsCommandEnabled(IDS_BOOMARK_BAR_OPEN_ALL_NEW_WINDOW)); } // Tests the enabled state of open incognito. TEST_F(BookmarkBarContextMenuControllerTest, DisableIncognito) { BookmarkBarContextMenuController controller( bb_view_.get(), model_->GetBookmarkBarNode()->GetChild(0)); EXPECT_TRUE(controller.IsCommandEnabled(IDS_BOOMARK_BAR_OPEN_INCOGNITO)); profile_->set_off_the_record(true); EXPECT_FALSE(controller.IsCommandEnabled(IDS_BOOMARK_BAR_OPEN_INCOGNITO)); }
34.971831
80
0.747684
[ "vector", "model" ]
01d7eeb05f5e435729336562e075bb2cb1eaf69c
4,174
cpp
C++
C++/CensusBureau/CensusBureau/CensusBureau.cpp
MuscleNrd/Student-Self-Completed
87c20c4cbd561554eb112047660b698d58711cdc
[ "MIT" ]
null
null
null
C++/CensusBureau/CensusBureau/CensusBureau.cpp
MuscleNrd/Student-Self-Completed
87c20c4cbd561554eb112047660b698d58711cdc
[ "MIT" ]
null
null
null
C++/CensusBureau/CensusBureau/CensusBureau.cpp
MuscleNrd/Student-Self-Completed
87c20c4cbd561554eb112047660b698d58711cdc
[ "MIT" ]
null
null
null
// CensusBureau.cpp : Defines the entry point for the console application. // #include "stdafx.h" using namespace std; const int INFANT = 18; const int YOUNG = 29; const int MIDDLEAGED = 50; const int OLD = 69; const int REALLYOLD = 70; map<int, int> organizeValues(int ages[], int size); map<string, int> organizeStats(std::map<int, int> ageSet); inline int findAverage(int numbers[], int size); int* findMode(map<int, int> numbers); double calculateStandardDeviation(int numbers[], int size); void printMyCrap(map<int, int> ageSet, map<string, int> statistics, int ages[], int size); int main() { int ages[] = { 4, 15 ,79, 52, 56, 19, 21, 22, 3, 12, 30, 33, 81, 99, 85, 28, 24, 25, 24, 26, 27, 20, 41, 32, 35, 24, 39, 43, 41, 46, 56, 62, 22, 20, 22, 18, }; map<int, int> ageSet = organizeValues(ages , sizeof(ages) / sizeof(int)); // Age :: number of people of that age map<string, int> statistics = organizeStats(ageSet); printMyCrap(ageSet, statistics, ages, sizeof(ages) / sizeof(int)); cout << "//////////////////////////////////////////////// End Professor's Test" << endl; cout << "//////////////////////////////////////////////// Begin user input" << endl; int input = 0; vector<int> userInput; cout << "Enter in ages, enter -1 to stop." << endl; while ( input != -1) { cin >> input; if (input == -1) break; userInput.push_back(input); } ageSet = organizeValues(&userInput[0], userInput.size()); statistics = organizeStats(ageSet); printMyCrap(ageSet, statistics, &userInput[0], userInput.size()); system("Pause"); return 0; } void printMyCrap(map<int,int> ageSet , map<string,int> statistics, int ages[], int size) { for (map<string, int>::iterator it = statistics.begin(); it != statistics.end(); it++) cout << "Amount of " << it->first << " -> " << it->second << endl; cout << "Printing Mode(s): "; for (int x = 0; x < findMode(ageSet)[0]; x++) cout << findMode(ageSet)[x + 1] << " "; cout << endl; cout << "Average: "; cout << findAverage(ages, size); cout << endl; cout << "Standard Deviation: "; cout << calculateStandardDeviation(ages, size); cout << endl; cout << endl; } map<int,int> organizeValues(int ages[], int size) { map<int, int> ageSet; for (int x = 0; x < size ; x++) { if (ageSet.find(ages[x]) == ageSet.end()) ageSet[ages[x]] = 1; else if (ageSet.find(ages[x]) != ageSet.end()) ageSet[ages[x]]++; } return ageSet; } map<string,int> organizeStats(std::map<int,int> ageSet) { map<string, int> stats; stats["INFANT"] = 0; stats["YOUNG"] = 0; stats["MIDDLEAGED"] = 0; stats["OLD"] = 0; stats["REALLYOLD"] = 0; map<int, int>::iterator it; for (it = ageSet.begin(); it != ageSet.end(); ++it) { if (it->first > 0 && it->first < INFANT) stats["INFANT"] += it->second; else if (it->first > INFANT && it->first < YOUNG) stats["YOUNG"] += it->second; else if (it->first > YOUNG && it->first < MIDDLEAGED) stats["MIDDLEAGED"] += it->second; else if (it->first > MIDDLEAGED && it->first < REALLYOLD) stats["OLD"] += it->second; else if (it->first >= REALLYOLD) stats["REALLYOLD"] += it->second; } return stats; } inline int findAverage(int numbers[], int size) { int a = 0; for (int x = 0; x < size; x++) a += numbers[x]; return a / size; } int* findMode(map<int,int> numbers) { int amountSame = 0; int mostCommon = 0; for (map<int, int>::iterator it = numbers.begin(); it != numbers.end(); ++it) { if (it->second > mostCommon) mostCommon = it->second; } for (map<int, int>::iterator it = numbers.begin(); it != numbers.end(); ++it) { if (it->second == mostCommon) amountSame++; } int * modes = new int[amountSame + 1]; modes[0] = amountSame; int counter = 1; for (map<int, int>::iterator it = numbers.begin(); it != numbers.end(); ++it) { if (it->second == mostCommon) { modes[counter] = it->first; counter++; } } return modes; } double calculateStandardDeviation(int numbers[], int size) { int average = findAverage(numbers, size); double y = 0; for (int x = 0; x < size; x++) y += (pow(numbers[x] - average, 2)); y /= size; y = sqrt(y); return y; }
21.626943
160
0.600383
[ "vector" ]
01d8f00b20a2a647b0f288e07e66be86b3255ea2
2,288
hpp
C++
libs/OGLPlus/include/oglplus/config/object.hpp
Clairezsh/PCISPH
9f0974c9c0bd73f52509445f976e4c4634dfd740
[ "WTFPL" ]
24
2015-01-31T15:30:49.000Z
2022-01-29T08:36:42.000Z
libs/OGLPlus/include/oglplus/config/object.hpp
Clairezsh/PCISPH
9f0974c9c0bd73f52509445f976e4c4634dfd740
[ "WTFPL" ]
4
2015-08-21T02:29:15.000Z
2020-05-02T13:50:36.000Z
libs/OGLPlus/include/oglplus/config/object.hpp
Clairezsh/PCISPH
9f0974c9c0bd73f52509445f976e4c4634dfd740
[ "WTFPL" ]
9
2015-06-08T22:04:15.000Z
2021-08-16T03:52:11.000Z
/** * @file oglplus/config/object.hpp * @brief Object-related compile-time configuration options * * @author Matus Chochlik * * Copyright 2010-2014 Matus Chochlik. 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) */ #pragma once #ifndef OGLPLUS_CONFIG_OBJECT_1107121519_HPP #define OGLPLUS_CONFIG_OBJECT_1107121519_HPP #include <oglplus/config/basic.hpp> #if OGLPLUS_DOCUMENTATION_ONLY /// Compile-time switch disabling the testing of object type on construction /** Setting this preprocessor option to a non-zero integer value * disables the additional checking of the type of object * returned by OpenGL's @c glGen*(...) functions during the construction * of an Object. Setting it to zero enables the check. * * By default this option is set to 1, i.e. object type tests are disabled. * * @ingroup compile_time_config */ #define OGLPLUS_DONT_TEST_OBJECT_TYPE #else # ifndef OGLPLUS_DONT_TEST_OBJECT_TYPE # define OGLPLUS_DONT_TEST_OBJECT_TYPE 1 # endif #endif #if OGLPLUS_DOCUMENTATION_ONLY /// Compile-time switch disabling textual object descriptions /** Setting this preprocessor option to a non-zero integer value * disables the @ref oglplus_object_description attached to * various specializations of @c Object (like Program, Shader, * Texture, etc.) during construction by the means of the ObjectDesc * parameter in constructor of Object. * * By default this option is set to the same value as #OGLPLUS_LOW_PROFILE, * i.e. objects descriptions are enabled, when not in low-profile mode * and disabled otherwise. * * @note Object descriptions use statically initialized data which * may cause problems if the final executable is built together from * several different object files. Because of this, if object descriptions * are enabled it is recommended that OGLplus applications are built with * #OGLPLUS_LINK_LIBRARY set to non-zero or are built as a single translation * unit. * * @see OGLPLUS_LINK_LIBRARY * * @ingroup compile_time_config */ #define OGLPLUS_NO_OBJECT_DESC #else # ifndef OGLPLUS_NO_OBJECT_DESC # define OGLPLUS_NO_OBJECT_DESC OGLPLUS_LOW_PROFILE # endif #endif #endif // include guard
33.647059
78
0.772727
[ "object" ]
01dae0f9426b4395b257fd12ac5eb659d8f8f6bf
1,152
cpp
C++
lintcode2/reversepairs.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2016-01-20T08:26:34.000Z
2016-01-20T08:26:34.000Z
lintcode2/reversepairs.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2015-10-21T05:38:17.000Z
2015-11-02T07:42:55.000Z
lintcode2/reversepairs.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
null
null
null
class Solution { public: /** * @param A an array * @return total of reverse pairs */ long long res=0; long long reversePairs(vector<int>& A) { // Write your code here int n=A.size(); vector<int> t(n,0); helper(A,0,n,t); return res; } void helper(vector<int> &A, int x, int y, vector<int>& t){ if(y-x>1){ int m=x+((y-x)>>1); helper(A,x,m,t); helper(A,m,y,t); //merge int p=x,i=x,q=m; while(p<m || q<y){ if(q>=y || (p<m && A[p]<=A[q])){ t[i++]=A[p++]; }else{ // when use a right element to fill in the t, // the A[q] is smaller than all the A[x] where x is [p,m) // so in terms of A[q], there is m-p reverse pairs res+=(m-p); t[i++]=A[q++]; } } for(int i=x; i<y; i++){ A[i]=t[i]; } } } };
25.043478
77
0.342014
[ "vector" ]
01e057d6519ba00ea42acbca22e9c2a0fb3c09ee
14,932
cpp
C++
project/ms3d/src/ms3dWriter.cpp
floitsch/gpexport
8b348f3dfe9f155e092fd9f456b6e9d0f138ec52
[ "MIT" ]
2
2017-05-26T07:15:46.000Z
2021-03-11T08:10:12.000Z
project/ms3d/src/ms3dWriter.cpp
floitsch/gpexport
8b348f3dfe9f155e092fd9f456b6e9d0f138ec52
[ "MIT" ]
null
null
null
project/ms3d/src/ms3dWriter.cpp
floitsch/gpexport
8b348f3dfe9f155e092fd9f456b6e9d0f138ec52
[ "MIT" ]
1
2016-03-31T04:52:24.000Z
2016-03-31T04:52:24.000Z
/* * Exports to MS3D-format. * * I never needed the ms3d-format, and this file is only * here as an example. I tested the exported file using * the IrrLicht-engine: http://irrlicht.sourceforge.net * and it worked fine. * My examples were pretty small though, and I'm not * guaranteeing anything. * * The MS3D-format is documented in their SDK: * http://www.swissquake.ch/chumbalum-soft/ms3d/download.html * * the ms3d.h-file is nearly a copy-paste of one of their files. (I * hope I don't break any copyright...) */ #include "ms3dWriter.hpp" #include <stdio.h> #include <string.h> #include <maya/MEulerRotation.h> #include <maya/MVector.h> #include "ms3d.h" namespace MS3DTranslation { void MS3DWriter::writeHeader() { std::cout << " Writing Header" << std::endl; ms3d_header_t header; strncpy(header.id, "MS3D000000", 10); header.version = 4; fwrite(header); } int MS3DWriter::nbVertices(const Scene& scene) { int sum = 0; for (unsigned int i = 0; i < scene.meshes.size(); ++i) sum += scene.meshes[i].positions.size(); return sum; } // MS3D refers to joints by index, and not by name. // using this method, we calculate the index, the joints will // have, when we extract them: nameVector[i] contains the joint with index i. void MS3DWriter::fillJointNameVector(const JointNode& node, std::vector<std::string>* nameVector) { nameVector->push_back(node.name); for (uint32 i = 0; i < node.children.size(); ++i) fillJointNameVector(node.children[i], nameVector); } // maps a joint to the index it will have, when we extract it. const std::map<std::string, uint32> MS3DWriter::getNameIndexMap(const Scene& scene) { std::vector<std::string> nameVector; const Skeleton& skel = scene.skeleton; for (uint32 i = 0; i < skel.rootNodes.size(); ++i) fillJointNameVector(skel.rootNodes[i], &nameVector); // transform it into a map (easier to access) std::map<std::string, uint32> result; for (uint32 i = 0; i < nameVector.size(); ++i) result[nameVector[i]] = i; return result; } // let's face it: MS3D is just not sophisticated enough. // A vertex can only be influenced by at most one bone. (this is certainly not true // for Maya, or other engines/file-formats). // Going to find the bone, that influences the most the given vertex. char MS3DWriter::getBoneIndex(uint32 vertexIndex, const Mesh& mesh, const std::map<std::string, uint32> nameIndexMap) // maps the jointName to the index it will have later on. { const uint32 weightIndex = mesh.vertices[vertexIndex].positionIndex; const SkinningData& skinning = mesh.skinningData; if (skinning.influences.size() == 0) return -1; // doesn't have weights const Influences& influences= skinning.influences[weightIndex]; if (influences.size() == 0) return -1; float maxWeight = 0; char jointIndex = -1; for (uint32 i = 0; i < influences.size(); ++i) { if (influences[i].weight > maxWeight) { maxWeight = influences[i].weight; const std::string& jointName = skinning.jointNames[influences[i].boneIndex]; // so we got the name. translate the correct index. std::map<std::string, uint32>::const_iterator it = nameIndexMap.find(jointName); if (it != nameIndexMap.end()) jointIndex = (char) it->second; else jointIndex = -1; // should not happen. } } return jointIndex; } // just dumps the vertices of the given mesh. (MS3D needs reference counts, // but this isn't really an issue). void MS3DWriter::writeVertices(const Mesh& meshToWrite, const std::map<std::string, uint32> nameIndexMap) { unsigned int nbVertices = meshToWrite.vertices.size(); //int referenceCounts[nbVertices]; std::vector<int> referenceCounts; referenceCounts.resize(nbVertices); for (unsigned int i = 0; i < nbVertices; ++i) referenceCounts[i] = 0; for (unsigned int i = 0; i < meshToWrite.indices.size(); ++i) for (unsigned int j = 0; j < 3; ++j) referenceCounts[meshToWrite.indices[i].i[j]]++; for (unsigned int i = 0; i < meshToWrite.vertices.size(); ++i) { const Vertex& vertex = meshToWrite.vertices[i]; const MPoint& position = meshToWrite.positions[vertex.positionIndex]; ms3d_vertex_t ms3dVertex; ms3dVertex.flags = 0; for (unsigned int j = 0; j < 3; ++j) ms3dVertex.vertex[j] = (float)position[j]; ms3dVertex.boneId = getBoneIndex(i, meshToWrite, nameIndexMap); ms3dVertex.referenceCount = referenceCounts[i]; fwrite(ms3dVertex); } } // dumps all the vertices. // as the vertices are referring to bone-indices, we need // to create the jointName2index-map first. void MS3DWriter::writeVertices(const Scene& sceneToWrite) { // write number vertices first (sum of all vertices). unsigned int nbTotalVertices = 0; for (unsigned int i = 0; i < sceneToWrite.meshes.size(); ++i) nbTotalVertices += sceneToWrite.meshes[i].vertices.size(); fwrite((word)nbTotalVertices); // in order to do get the correct joint-index we need a mapping // from joint-name to index. std::map<std::string, uint32> nameIndexMap = getNameIndexMap(sceneToWrite); // now write the vertices for (unsigned int i = 0; i < sceneToWrite.meshes.size(); ++i) writeVertices(sceneToWrite.meshes[i], nameIndexMap); } // just dumps all the vertices of the mesh. // note, that we associated the normals to the vertices during extraction. // MS3D associates them to the triangles. Therefore the extracted mesh is // clearly not optimal, as two vertices with the same position, will be // exported twice (which is not necessary in MS3D). unsigned int MS3DWriter::writeTriangles(const Mesh& meshToWrite, unsigned int indexOffset, byte groupIndex) { for (unsigned int i = 0; i < meshToWrite.indices.size(); ++i) { const Int3& indices = meshToWrite.indices[i]; ms3d_triangle_t ms3dTriangle; ms3dTriangle.flags = 0; for (unsigned int j = 0; j < 3; ++j) { const int vertexIndex = indices.i[j]; const Vertex& vertex = meshToWrite.vertices[vertexIndex]; ms3dTriangle.vertexIndices[j] = (word)(vertexIndex + indexOffset); int32 normalIndex = vertex.normalIndex; for (unsigned int k = 0; k < 3; ++k) ms3dTriangle.vertexNormals[j][k] = (float)meshToWrite.normals[normalIndex][k]; int32 uvIndex = vertex.uvIndex; // only get the first UV-set. ms3dTriangle.s[j] = meshToWrite.uvs[0][uvIndex].s; ms3dTriangle.t[j] = meshToWrite.uvs[0][uvIndex].t; } ms3dTriangle.smoothingGroup = 0; ms3dTriangle.groupIndex = groupIndex; fwrite(ms3dTriangle); } return meshToWrite.vertices.size(); } // dumps all triangles. void MS3DWriter::writeTriangles(const Scene& sceneToWrite) { /* * first get the total number of indices. */ unsigned int nbTotalIndices = 0; for (unsigned int i = 0; i < sceneToWrite.meshes.size(); ++i) nbTotalIndices += sceneToWrite.meshes[i].indices.size(); fwrite<word>((word)nbTotalIndices); /* * now write the indices */ // the we "merge" the meshes, so we need to adjust the indices. unsigned int indexOffset = 0; // every mesh is a group byte groupIndex = 0; for (unsigned int i = 0; i < sceneToWrite.meshes.size(); ++i) { indexOffset += writeTriangles(sceneToWrite.meshes[i], indexOffset, groupIndex++); } } // every Maya-mesh becomes a MS3D-group. void MS3DWriter::writeGroups(const Scene& sceneToWrite) { unsigned int nbMeshes = sceneToWrite.meshes.size(); fwrite((word)nbMeshes); unsigned int triangleCounter = 0; for (unsigned int i = 0; i < nbMeshes; ++i) { const Mesh& mesh = sceneToWrite.meshes[i]; fwrite<byte>(0); // flags char name[32]; strncpy(name, mesh.name.c_str(), 32); name[31] = '\0'; // strncpy doesn't necessarily terminate the string. fwrite<char>(name, 32); unsigned int nbIndices = mesh.indices.size(); fwrite<word>((word)nbIndices); for (unsigned int j = 0; j < nbIndices; ++j) fwrite<word>((word)triangleCounter++); fwrite<char>(-1); } } // TODO. void MS3DWriter::writeMaterials(const Scene& sceneToWrite) { std::cout << " Writing Materials" << std::endl; fwrite((word)0); // currently nothing. } // dumps the rotation-part of the matrix, decomposed in x, y, z rotations. void MS3DWriter::writeRotation(const MMatrix& matrix) { const MTransformationMatrix transformationMatrix(matrix); const MEulerRotation rotation = transformationMatrix.eulerRotation(); fwrite<float>((float)rotation.x); fwrite<float>((float)rotation.y); fwrite<float>((float)rotation.z); } // dumps the translation-part of the matrix. void MS3DWriter::writePosition(const MMatrix& matrix) { const MTransformationMatrix transformationMatrix(matrix); const MVector translation = transformationMatrix.translation(MSpace::kTransform); fwrite<float>((float)translation.x); fwrite<float>((float)translation.y); fwrite<float>((float)translation.z); } // dumps the rotational part of the keyframe. // note, that maya crashed quite often in this function. I have no idea why! A reproducable // way of crashing Maya was: load the plugin. export. unload. reload. export and crash when // accessing the keyFrame-time. // If you know why, drop me a mail... void MS3DWriter::writeKeyFrameRotation(const KeyFrame& keyFrame, const MMatrix& inverse) { fwrite<float>((float)keyFrame.time.as(MTime::kSeconds)); writeRotation(inverse * keyFrame.transformation); } // dumps the translational part of the keyframe. void MS3DWriter::writeKeyFramePosition(const KeyFrame& keyFrame, const MMatrix& inverse) { fwrite<float>((float)keyFrame.time.as(MTime::kSeconds)); writePosition(inverse * keyFrame.transformation); } // dumps all the keyframes. // as we just extracted the transformation-matrix of each joint, we don't know, if it was a rotation // or translation. Hence we write both. This isn't really optimal, but shouldn't harm. void MS3DWriter::writeTrack(const Track& track, const JointNode& node, const MTime& start, const MTime& end) { uint32 nbKeyFrames = track.size(); if (nbKeyFrames == 0) { fwrite<word>(0); // nbRotationFrames fwrite<word>(0); // nbTranslationFrames return; } // Maya uses the first keyframe for everything before the first time. // MS3D uses the original transformation (which is not necessarely the same). // so just copy the first keyframe to the start of the animation, so the // behaviour is same. KeyFrame firstFrame = track[0]; firstFrame.time = start; // same is true for last frame. KeyFrame lastFrame = track[track.size() - 1]; lastFrame.time = end; bool newStart = (track[0].time != start); bool newEnd = (track[nbKeyFrames - 1].time != end); char additionalFrames = 0; if (newStart) additionalFrames++; if (newEnd) additionalFrames++; fwrite<word>((word)(nbKeyFrames + additionalFrames)); // nbRotationFrames fwrite<word>((word)(nbKeyFrames + additionalFrames)); // nbTranslationFrames MMatrix inverseTransformation = node.localTransform.inverse(); // rotation if (newStart) writeKeyFrameRotation(firstFrame, inverseTransformation); for (uint32 i = 0; i < track.size(); ++i) writeKeyFrameRotation(track[i], inverseTransformation); if (newEnd) writeKeyFrameRotation(lastFrame, inverseTransformation); // position if (newStart) writeKeyFramePosition(firstFrame, inverseTransformation); for (uint32 i = 0; i < track.size(); ++i) writeKeyFramePosition(track[i], inverseTransformation); if (newEnd) writeKeyFramePosition(lastFrame, inverseTransformation); } // recursively counts the nb of joints. uint32 MS3DWriter::countJoints(const JointNode& node) { uint32 childrenNodesCount = 0; for (uint32 i = 0; i < node.children.size(); ++i) childrenNodesCount += countJoints(node.children[i]); return childrenNodesCount + 1; // don't forget the current node } // dumps the joint and its children. // note, that the animations are written here too. void MS3DWriter::writeJoints(const JointNode& node, const std::string& parentName, const Scene& scene) { fwrite<byte>(0); // flags char buffer[32]; // IMPORTANT: if the name's longer than 32 chars, // this could pose big troubles. (as unicity is // not guaranteed anymore. strncpy(buffer, node.name.c_str(), 32); buffer[31] = '\0'; fwrite<char>(buffer, 32); strncpy(buffer, parentName.c_str(), 32); buffer[31] = '\0'; fwrite<char>(buffer, 32); writeRotation(node.localTransform); writePosition(node.localTransform); // wanted to write scene.animation.tracks[node.name] in the next // line. but due to const-issues, this isn't possible. const Animation& anim = scene.animation; StringTrackMap::const_iterator it = anim.tracks.find(node.name); writeTrack(it->second, node, anim.start, anim.end); for (uint32 i = 0; i < node.children.size(); ++i) writeJoints(node.children[i], node.name, scene); } // writes all joints. void MS3DWriter::writeJoints(const Scene& sceneToWrite) { const Skeleton& skel = sceneToWrite.skeleton; uint32 nbJoints = 0; for (uint32 i = 0; i < skel.rootNodes.size(); ++i) nbJoints += countJoints(skel.rootNodes[i]); // don't count the root-nodes fwrite<word>((word)nbJoints); for (uint32 i = 0; i < skel.rootNodes.size(); ++i) writeJoints(skel.rootNodes[i], "", sceneToWrite); } // nothing special here. void MS3DWriter::writeAnimation(const Scene& sceneToWrite) { std::cout << " Writing Animation" << std::endl; const Animation& anim = sceneToWrite.animation; uint32 fps = anim.fps; fwrite<float>((float)fps); fwrite<float>((float)anim.start.as(MTime::kSeconds)); // currentTime (we take starttime) MTime length = anim.end - anim.start; fwrite<int>((int)(length.as(MTime::kSeconds)*fps)); // totalframes writeJoints(sceneToWrite); } // write the meshes, split into vertices, triangles, and groups. void MS3DWriter::writeMeshes(const Scene& sceneToWrite) { std::cout << " Writing Meshes" << std::endl; writeVertices(sceneToWrite); writeTriangles(sceneToWrite); writeGroups(sceneToWrite); } void MS3DWriter::WriteScene(const Scene& sceneToWrite ) { std::cout << "Writing ms3d to " << m_config->getOutFile() << std::endl; FileWriter::WriteScene(sceneToWrite, m_config->getOutFile()); } void MS3DWriter::doWriteScene(const Scene& sceneToWrite) { writeHeader(); writeMeshes(sceneToWrite); writeMaterials(sceneToWrite); writeAnimation(sceneToWrite); } } // namespace GPTranslation
31.770213
115
0.682025
[ "mesh", "vector", "transform" ]
01e2a7f4710ff8e4cb997dcefbeaadd5a4f3eb68
6,635
cpp
C++
source/modules/problem/optimization/optimization.cpp
JonathanLehner/korali
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
[ "MIT" ]
43
2018-07-26T07:20:42.000Z
2022-03-02T10:23:12.000Z
source/modules/problem/optimization/optimization.cpp
JonathanLehner/korali
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
[ "MIT" ]
212
2018-09-21T10:44:07.000Z
2022-03-22T14:33:05.000Z
source/modules/problem/optimization/optimization.cpp
JonathanLehner/korali
90f97d8e2fed2311f988f39cfe014f23ba7dd6cf
[ "MIT" ]
16
2018-07-25T15:00:36.000Z
2022-03-22T14:19:46.000Z
#include "modules/problem/optimization/optimization.hpp" #include "sample/sample.hpp" namespace korali { namespace problem { ; void Optimization::initialize() { if (_k->_variables.size() == 0) KORALI_LOG_ERROR("Optimization Evaluation problems require at least one variable.\n"); } void Optimization::evaluateConstraints(Sample &sample) { for (size_t i = 0; i < _constraints.size(); i++) { sample.run(_constraints[i]); auto evaluation = KORALI_GET(double, sample, "F(x)"); if (std::isfinite(evaluation) == false) KORALI_LOG_ERROR("Non finite value of constraint evaluation %lu detected: %f\n", i, evaluation); sample["Constraint Evaluations"][i] = evaluation; } } void Optimization::evaluate(Sample &sample) { sample.run(_objectiveFunction); auto evaluation = KORALI_GET(double, sample, "F(x)"); if (std::isfinite(evaluation) == false) KORALI_LOG_ERROR("Non finite value of function evaluation detected: %f\n", evaluation); } void Optimization::evaluateMultiple(Sample &sample) { sample.run(_objectiveFunction); auto evaluation = KORALI_GET(std::vector<double>, sample, "F(x)"); for (size_t i = 0; i < evaluation.size(); i++) if (std::isfinite(evaluation[i]) == false) KORALI_LOG_ERROR("Non finite value of function evaluation detected for variable %lu: %f\n", i, evaluation[i]); } void Optimization::evaluateWithGradients(Sample &sample) { sample.run(_objectiveFunction); auto evaluation = KORALI_GET(double, sample, "F(x)"); auto gradient = KORALI_GET(std::vector<double>, sample, "Gradient"); if (gradient.size() != _k->_variables.size()) KORALI_LOG_ERROR("Size of sample's gradient evaluations vector (%lu) is different from the number of problem variables defined (%lu).\n", gradient.size(), _k->_variables.size()); if (std::isfinite(evaluation) == false) KORALI_LOG_ERROR("Non finite value of function evaluation detected: %f\n", evaluation); for (size_t i = 0; i < gradient.size(); i++) if (std::isfinite(gradient[i]) == false) KORALI_LOG_ERROR("Non finite value of gradient evaluation detected for variable %lu: %f\n", i, gradient[i]); } void Optimization::setConfiguration(knlohmann::json& js) { if (isDefined(js, "Results")) eraseValue(js, "Results"); if (isDefined(js, "Has Discrete Variables")) { try { _hasDiscreteVariables = js["Has Discrete Variables"].get<int>(); } catch (const std::exception& e) { KORALI_LOG_ERROR(" + Object: [ optimization ] \n + Key: ['Has Discrete Variables']\n%s", e.what()); } eraseValue(js, "Has Discrete Variables"); } if (isDefined(js, "Num Objectives")) { try { _numObjectives = js["Num Objectives"].get<size_t>(); } catch (const std::exception& e) { KORALI_LOG_ERROR(" + Object: [ optimization ] \n + Key: ['Num Objectives']\n%s", e.what()); } eraseValue(js, "Num Objectives"); } else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Num Objectives'] required by optimization.\n"); if (isDefined(js, "Objective Function")) { try { _objectiveFunction = js["Objective Function"].get<std::uint64_t>(); } catch (const std::exception& e) { KORALI_LOG_ERROR(" + Object: [ optimization ] \n + Key: ['Objective Function']\n%s", e.what()); } eraseValue(js, "Objective Function"); } else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Objective Function'] required by optimization.\n"); if (isDefined(js, "Constraints")) { try { _constraints = js["Constraints"].get<std::vector<std::uint64_t>>(); } catch (const std::exception& e) { KORALI_LOG_ERROR(" + Object: [ optimization ] \n + Key: ['Constraints']\n%s", e.what()); } eraseValue(js, "Constraints"); } else KORALI_LOG_ERROR(" + No value provided for mandatory setting: ['Constraints'] required by optimization.\n"); if (isDefined(_k->_js.getJson(), "Variables")) for (size_t i = 0; i < _k->_js["Variables"].size(); i++) { } bool detectedCompatibleSolver = false; std::string solverName = toLower(_k->_js["Solver"]["Type"]); std::string candidateSolverName; solverName.erase(remove_if(solverName.begin(), solverName.end(), isspace), solverName.end()); candidateSolverName = toLower("Optimizer"); candidateSolverName.erase(remove_if(candidateSolverName.begin(), candidateSolverName.end(), isspace), candidateSolverName.end()); if (solverName.rfind(candidateSolverName, 0) == 0) detectedCompatibleSolver = true; if (detectedCompatibleSolver == false) KORALI_LOG_ERROR(" + Specified solver (%s) is not compatible with problem of type: optimization\n", _k->_js["Solver"]["Type"].dump(1).c_str()); Problem::setConfiguration(js); _type = "optimization"; if(isDefined(js, "Type")) eraseValue(js, "Type"); if(isEmpty(js) == false) KORALI_LOG_ERROR(" + Unrecognized settings for Korali module: optimization: \n%s\n", js.dump(2).c_str()); } void Optimization::getConfiguration(knlohmann::json& js) { js["Type"] = _type; js["Num Objectives"] = _numObjectives; js["Objective Function"] = _objectiveFunction; js["Constraints"] = _constraints; js["Has Discrete Variables"] = _hasDiscreteVariables; for (size_t i = 0; i < _k->_variables.size(); i++) { } Problem::getConfiguration(js); } void Optimization::applyModuleDefaults(knlohmann::json& js) { std::string defaultString = "{\"Num Objectives\": 1, \"Has Discrete Variables\": false, \"Constraints\": []}"; knlohmann::json defaultJs = knlohmann::json::parse(defaultString); mergeJson(js, defaultJs); Problem::applyModuleDefaults(js); } void Optimization::applyVariableDefaults() { std::string defaultString = "{}"; knlohmann::json defaultJs = knlohmann::json::parse(defaultString); if (isDefined(_k->_js.getJson(), "Variables")) for (size_t i = 0; i < _k->_js["Variables"].size(); i++) mergeJson(_k->_js["Variables"][i], defaultJs); Problem::applyVariableDefaults(); } bool Optimization::runOperation(std::string operation, korali::Sample& sample) { bool operationDetected = false; if (operation == "Evaluate") { evaluate(sample); return true; } if (operation == "Evaluate Multiple") { evaluateMultiple(sample); return true; } if (operation == "Evaluate With Gradients") { evaluateWithGradients(sample); return true; } if (operation == "Evaluate Constraints") { evaluateConstraints(sample); return true; } operationDetected = operationDetected || Problem::runOperation(operation, sample); if (operationDetected == false) KORALI_LOG_ERROR(" + Operation %s not recognized for problem Optimization.\n", operation.c_str()); return operationDetected; } ; } //problem } //korali ;
33.680203
186
0.694951
[ "object", "vector" ]
01e658aa0254d7e550d5eb96e259ea74a6c445b7
811
hpp
C++
3SST/Libraries/graph.hpp
AVAtarMod/University-C
e516aac99eabbcbe14d897239f08acf6c8e146af
[ "BSD-3-Clause" ]
1
2021-07-31T06:55:08.000Z
2021-07-31T06:55:08.000Z
3SST/Libraries/graph.hpp
AVAtarMod/University-C
e516aac99eabbcbe14d897239f08acf6c8e146af
[ "BSD-3-Clause" ]
null
null
null
3SST/Libraries/graph.hpp
AVAtarMod/University-C
e516aac99eabbcbe14d897239f08acf6c8e146af
[ "BSD-3-Clause" ]
null
null
null
#ifndef GRAPH_LIB #define GRAPH_LIB #include <vector> #include "list.hpp" #include "tree.hpp" using matrix_t = std::vector<std::vector<int>>; class Graph { private: uint size = 0; List1D<List1D<int>> adjacencyList = nullptr; public: enum Method { BY_DEPTH, BY_WIDTH }; Graph(); Graph(const matrix_t& adjacencyMatrix); Graph(const List1D<List1D<int>> adjacencyList); void operator=(const Graph& graph); List1D<List1D<int>> getAdjacencyList() const; const matrix_t getAdjacencyMatrix() const; IntTree getSpanningTree(Method m) const; void print() const; void validate() const; friend std::istream& operator>>(std::istream& input, Graph& number); ~Graph(); }; std::istream& operator>>(std::istream& input, Graph& number); #endif // GRAPH_LIB
20.794872
72
0.679408
[ "vector" ]
5438476c69c1ac107b2723ba3b1573f1095026fd
3,187
cpp
C++
src/protocolreader_sougou.cpp
hejianglin/QNetworkTranslator
82a36ca0528f1a9082005374f72e64a799c349d7
[ "MIT" ]
null
null
null
src/protocolreader_sougou.cpp
hejianglin/QNetworkTranslator
82a36ca0528f1a9082005374f72e64a799c349d7
[ "MIT" ]
null
null
null
src/protocolreader_sougou.cpp
hejianglin/QNetworkTranslator
82a36ca0528f1a9082005374f72e64a799c349d7
[ "MIT" ]
null
null
null
//Qt #include <QtCore/QMap> #include <QtCore/QObject> #include <QtCore/QJsonDocument> #include <QtCore/QJsonObject> #include <QtCore/QJsonArray> //QNetworkTranslator #include "protocolreader_sougou.h" NETWORKTRANSLATOR_NAMESPACE_BEGIN class ProtocolReaderPrivate_Sougou : public QSharedData { public: ProtocolReaderPrivate_Sougou() : m_iError(0) , m_eSourceLanguage(LanguageType_eNone) , m_eTargetLanguage(LanguageType_eNone) { //detail:http://deepi.sogou.com/docs/fanyiDoc m_mapError[1001] = QObject::tr("Unsupported language type"); m_mapError[1002] = QObject::tr("Text too long"); m_mapError[1003] = QObject::tr("Invalid PID"); m_mapError[1004] = QObject::tr("Trial PID limit reached"); m_mapError[1005] = QObject::tr("PID traffic too high"); m_mapError[1006] = QObject::tr("Insufficient balance"); m_mapError[1007] = QObject::tr("Random number does not exist"); m_mapError[1008] = QObject::tr("Signature does not exist"); m_mapError[1009] = QObject::tr("The signature is incorrect"); m_mapError[10010] = QObject::tr("Text does not exist"); m_mapError[1050] = QObject::tr("Internal server error"); } ~ProtocolReaderPrivate_Sougou() { } void read(const QByteArray &data) { if(data.isEmpty()){ m_iError = 999; m_sErrorString = QObject::tr("empty respone"); return ; } QJsonObject dataObj = QJsonDocument::fromJson(data).object(); if(dataObj["errorCode"].toString().toInt(0,10) != 0){ m_iError = dataObj["errorCode"].toString().toInt(0,10); m_sErrorString = m_mapError.value(m_iError); return ; } m_sSource.append(dataObj["query"].toString()); m_sTarget.append(dataObj["translation"].toString()); } int m_iError; QString m_sErrorString; LanguageType m_eSourceLanguage; LanguageType m_eTargetLanguage; QString m_sSource; QString m_sTarget; LanguageMap *m_cLanguageMap; QMap<int,QString> m_mapError; }; ProtocolReader_Sougou::ProtocolReader_Sougou() :d(new ProtocolReaderPrivate_Sougou) { } ProtocolReader_Sougou::~ProtocolReader_Sougou() { d = 0; } void ProtocolReader_Sougou::setLanguageMap(LanguageMap *map) { d->m_cLanguageMap = map; } LanguageMap *ProtocolReader_Sougou::languageMap() const { return d->m_cLanguageMap; } void ProtocolReader_Sougou::read(const QByteArray &data) { return d->read(data); } void ProtocolReader_Sougou::read(const QString &data) { return read(data.toUtf8()); } LanguageType ProtocolReader_Sougou::sourceLanguage() const { return d->m_eSourceLanguage; } LanguageType ProtocolReader_Sougou::targetLanguage() const { return d->m_eTargetLanguage; } QString ProtocolReader_Sougou::source() const { return d->m_sSource; } QString ProtocolReader_Sougou::target() const { return d->m_sTarget; } int ProtocolReader_Sougou::error() const { return d->m_iError; } QString ProtocolReader_Sougou::errorString() const { return d->m_sErrorString; } NETWORKTRANSLATOR_NAMESPACE_END
23.962406
71
0.682146
[ "object" ]
5445459040adcc59b5229490bb4e571a4a7b728f
2,395
cc
C++
third_party_builtin/slivr/slivr/Ray.cc
ahota/visit_ospray
d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9
[ "BSD-3-Clause" ]
null
null
null
third_party_builtin/slivr/slivr/Ray.cc
ahota/visit_ospray
d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9
[ "BSD-3-Clause" ]
null
null
null
third_party_builtin/slivr/slivr/Ray.cc
ahota/visit_ospray
d80b2e18ff5654d04bfb56ae4d6f42e45f87c9b9
[ "BSD-3-Clause" ]
null
null
null
/* For more information, please see: http://software.sci.utah.edu The MIT License Copyright (c) 2008 Scientific Computing and Imaging Institute, University of Utah. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* * Ray.cc: The Ray datatype * * Written by: * Steven G. Parker * Department of Computer Science * University of Utah * December 1994 * */ #include <slivr/Ray.h> namespace SLIVR { Ray::Ray(const Point& o, const Vector& d) : o_(o), d_(d) { } Ray::Ray(const Ray& copy) : o_(copy.o_), d_(copy.d_) { } Ray::~Ray() { } Ray& Ray::operator=(const Ray& copy) { o_=copy.o_; d_=copy.d_; return *this; } Point Ray::parameter(double t) const { return o_ + d_*t; } bool Ray::planeIntersectParameter(const Vector& N, const Point& P, double& t) const { //! Computes the ray parameter t at which the ray R will //! point P /* Dot(N, ((O + t0*V) - P)) = 0 solve for t0 */ Point O(o_); Vector V(d_); double D = -(N.x()*P.x() + N.y()*P.y() + N.z()*P.z()); double NO = (N.x()*O.x() + N.y()*O.y() + N.z()*O.z()); double NV = Dot(N,V); if (NV == 0) // ray is parallel to plane return false; else { t = -(D + NO)/NV; return true; } } void Ray::normalize() { d_.normalize(); } void Ray::direction(const Vector& newdir) { d_=newdir; } } // End namespace SLIVR
21.772727
78
0.664718
[ "vector" ]
54454f518c813883e9ccb82ea9c51090fee2b439
4,200
hpp
C++
state.hpp
5cript/automata
28750528c528dcb297906e73e52a5b21d2f53d9e
[ "MIT" ]
null
null
null
state.hpp
5cript/automata
28750528c528dcb297906e73e52a5b21d2f53d9e
[ "MIT" ]
null
null
null
state.hpp
5cript/automata
28750528c528dcb297906e73e52a5b21d2f53d9e
[ "MIT" ]
null
null
null
#pragma once #include "automata_fwd.hpp" #include "trigger.hpp" #include <functional> #include <string> #include <vector> #include <boost/optional.hpp> namespace MiniAutomata { //##################################################################################################################### // declaration class State; //##################################################################################################################### class ProtoState { public: struct StateBindingElement { boost::optional <std::string> name; boost::optional <int> id; Trigger trig; StateBindingElement(std::string const& name) : name{name} , id{boost::none} , trig{} {} StateBindingElement(int id) : name{boost::none} , id{id} , trig{} {} StateBindingElement(std::string const& name, std::function <bool()> trig) : name{name} , id{boost::none} , trig{trig} {} StateBindingElement(int id, std::function <bool()> trig) : name{boost::none} , id{id} , trig{trig} {} }; using StateBinding = std::vector <StateBindingElement>; public: friend Transition; public: ProtoState(const char* name /* null determinated */); ProtoState(unsigned long long int id); State operator()(int id); State operator()() &&; /** * Binds states together for transitions. */ friend StateBinding operator||(ProtoState&& lhs, std::string&& name); /** * Binds states together for transitions. */ friend StateBinding operator||(ProtoState&& lhs, ProtoState&& rhs); /** * Binds states together for transitions. */ friend StateBinding operator||(ProtoState&& lhs, int id); /** * Binds states together for transitions. */ friend StateBinding operator||(StateBinding&& lhs, std::string&& name); /** * Binds states together for transitions. */ friend StateBinding operator||(StateBinding&& lhs, ProtoState&& rhs); /** * Binds states together for transitions. */ friend StateBinding operator||(StateBinding&& lhs, StateBinding&& rhs); /** * Binds states together for transitions. */ friend StateBinding operator||(StateBinding&& lhs, int id); /** * Add triggers to protos */ friend StateBinding operator<(ProtoState&& proto, std::function <bool()> trig); private: boost::optional <int> id_; std::string name_; }; //##################################################################################################################### class State { public: State(std::string&& name); State(int id, std::string&& name); /** * Get state name. */ std::string getName() const; /** * Get state id (if assigned). */ boost::optional <int> getId() const; /** * Adds an action to the state. The action is called when this state is entered. * * @param A functor called on state activation. */ void bindAction(std::function <void()> const& action); /** * Calls action_, if assigned. */ void operator()(); private: boost::optional <int> id_; std::string name_; std::function <void()> action_; }; //##################################################################################################################### ProtoState operator "" _as(const char* name, std::size_t); ProtoState operator "" _as(unsigned long long int id); }
28.767123
120
0.440476
[ "vector" ]
5446f9a7c62f58b735d1499edb7599d8eb233ca2
20,817
cpp
C++
Sankore-3.1/src/gui/UBKeyboardPalette.cpp
eaglezzb/rsdc
cce881f6542ff206bf286cf798c8ec8da3b51d50
[ "MIT" ]
null
null
null
Sankore-3.1/src/gui/UBKeyboardPalette.cpp
eaglezzb/rsdc
cce881f6542ff206bf286cf798c8ec8da3b51d50
[ "MIT" ]
null
null
null
Sankore-3.1/src/gui/UBKeyboardPalette.cpp
eaglezzb/rsdc
cce881f6542ff206bf286cf798c8ec8da3b51d50
[ "MIT" ]
null
null
null
/* * Copyright (C) 2010-2013 Groupement d'Intérêt Public pour l'Education Numérique en Afrique (GIP ENA) * * This file is part of Open-Sankoré. * * Open-Sankoré is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, version 3 of the License, * with a specific linking exception for the OpenSSL project's * "OpenSSL" library (or with modified versions of it that use the * same license as the "OpenSSL" library). * * Open-Sankoré is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Open-Sankoré. If not, see <http://www.gnu.org/licenses/>. */ #include <QtGui> #include <QList> #include <QSize> #include "UBKeyboardPalette.h" #include "core/UBSettings.h" #include "core/UBApplication.h" #include "gui/UBMainWindow.h" #include "core/memcheck.h" /* UBKeyboardPalette */ UBKeyboardPalette::UBKeyboardPalette(QWidget *parent) : UBActionPalette(Qt::TopRightCorner, parent) { // setWindowFlags(/*Qt::CustomizeWindowHint|*/Qt::WindowStaysOnTopHint|Qt::FramelessWindowHint); setCustomCloseProcessing(true); setCustomPosition(true); setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum); setFocusPolicy(Qt::NoFocus); setClosable(true); setGrip(false); capsLock = false; shift = false; languagePopupActive = false; keyboardActive = false; nSpecialModifierIndex = 0; specialModifier = 0; btnWidth = btnHeight = 16; strSize = "16x16"; currBtnImages = new BTNImages("16", btnWidth, btnHeight); storage = NULL; buttons = new UBKeyButton*[47]; for (int i=0; i<47; i++) { buttons[i] = new UBKeyButton(this); } locales = UBPlatformUtils::getKeyboardLayouts(this->nLocalesCount); createCtrlButtons(); nCurrentLocale = UBSettings::settings()->KeyboardLocale->get().toInt(); if (nCurrentLocale < 0 || nCurrentLocale >= nLocalesCount) nCurrentLocale = 0; if (locales!=NULL) setInput(locales[nCurrentLocale]); setContentsMargins( 22, 22, 22, 22 ); init(); } //QList<UBKeyboardPalette*> UBKeyboardPalette::instances; void UBKeyboardPalette::init() { m_isVisible = false; setVisible(false); setKeyButtonSize(UBSettings::settings()->boardKeyboardPaletteKeyBtnSize->get().toString()); connect(this, SIGNAL(keyboardActivated(bool)), this, SLOT(onActivated(bool))); connect(UBSettings::settings()->boardKeyboardPaletteKeyBtnSize, SIGNAL(changed(QVariant)), this, SLOT(keyboardPaletteButtonSizeChanged(QVariant))); connect(UBApplication::mainWindow->actionVirtualKeyboard, SIGNAL(triggered(bool)), this, SLOT(showKeyboard(bool))); connect(this, SIGNAL(closed()), this, SLOT(hideKeyboard())); //------------------------------// UBPlatformUtils::setWindowNonActivableFlag(this, true); } void UBKeyboardPalette::showKeyboard(bool show) { m_isVisible = show; } void UBKeyboardPalette::hideKeyboard() { UBApplication::mainWindow->actionVirtualKeyboard->activate(QAction::Trigger); } void UBKeyboardPalette::syncPosition(const QPoint & pos) { m_pos = pos; move(pos); } void UBKeyboardPalette::syncLocale(int nLocale) { nCurrentLocale = nLocale; setInput(locales[nCurrentLocale]); } void UBKeyboardPalette::keyboardPaletteButtonSizeChanged(QVariant size) { setKeyButtonSize(size.toString()); } void UBKeyboardPalette::setInput(const UBKeyboardLocale* locale) { if (locale!=NULL) { for (int i=0; i<47; i++) buttons[i]->setKeyBt((*locale)[i]); } else { this->hide(); } } UBKeyboardPalette::~UBKeyboardPalette() { //for (int i=0; i<47; i++) // delete buttons[i]; delete [] buttons; //for (int i=0; i<8; i++) // delete ctrlButtons[i]; delete [] ctrlButtons; //if (locales!=NULL) //{ // for (int i=0; i<nLocalesCount; i++) // delete locales[i]; // delete [] locales; //} if(currBtnImages != NULL) { delete currBtnImages; currBtnImages = NULL; } onActivated(false); } QSize UBKeyboardPalette::sizeHint () const { int w = contentsMargins().left() + 15 * btnWidth + contentsMargins().right(); int h = contentsMargins().top() + 5 * btnHeight + contentsMargins().bottom(); return QSize(w, h); } const QString* UBKeyboardPalette::getLocaleName() { return locales == NULL ? NULL : &(locales[nCurrentLocale]->name); } void UBKeyboardPalette::setLocale(int nLocale) { if (locales != NULL) { nCurrentLocale = nLocale; setInput(locales[nCurrentLocale]); onLocaleChanged(locales[nCurrentLocale]); update(); UBSettings::settings()->KeyboardLocale->set(nCurrentLocale); } emit localeChanged(nLocale); } void UBKeyboardPalette::setKeyButtonSize(const QString& _strSize) { QStringList strs = _strSize.split('x'); if (strs.size()==2) { strSize = _strSize; btnWidth = strs[0].toInt(); btnHeight = strs[1].toInt(); if(currBtnImages != NULL) delete currBtnImages; currBtnImages = new BTNImages(strs[1], btnWidth, btnHeight); adjustSizeAndPosition(); } } void UBKeyboardPalette::enterEvent ( QEvent * ) { if (keyboardActive) return; keyboardActive = true; //adjustSizeAndPosition(); emit keyboardActivated(true); } void UBKeyboardPalette::leaveEvent ( QEvent * ) { if (languagePopupActive || !keyboardActive || mIsMoving) return; keyboardActive = false; //adjustSizeAndPosition(); emit keyboardActivated(false); } void UBKeyboardPalette::moveEvent ( QMoveEvent * event ) { UBActionPalette::moveEvent(event); emit moved(event->pos()); } void UBKeyboardPalette::adjustSizeAndPosition(bool pUp) { QSize rSize = sizeHint(); if (rSize != size()) { int dx = (rSize.width() - size().width()) /2; int dy = rSize.height() - size().height(); this->move(x()-dx, y() - dy); this->resize(rSize.width(), rSize.height()); } UBActionPalette::adjustSizeAndPosition(pUp); } void UBKeyboardPalette::paintEvent( QPaintEvent* event) { checkLayout(); UBActionPalette::paintEvent(event); QRect r = this->geometry(); int lleft, ltop, lright, lbottom; getContentsMargins ( &lleft, &ltop, &lright, &lbottom ) ; //------------------------------------------------ // calculate start offset from left, and from top int ctrlButtonsId = 0; lleft = ( r.width() - btnWidth * 15 ) / 2; ltop = ( r.height() - btnHeight * 5 ) / 2; //------------------------------------------------ // set geometry (position) for row 1 int offX = lleft; int offY = ltop; //------------------- // buttons [`]..[+] for (int i = 0; i<13; i++) { buttons[i]->setGeometry(offX, offY, btnWidth, btnHeight); offX += btnWidth; } // button Backspace ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth * 2, btnHeight); offX += btnWidth * 2; //------------------------------------------------ // set geometry (position) for row 2 offX = lleft; offY += btnHeight; offX += btnWidth / 2; //------------------- // button Tab ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth * 2, btnHeight); offX += btnWidth * 2; // buttons [q]..[]] for (int i = 0; i<12; i++) { buttons[i + 13]->setGeometry(offX, offY, btnWidth, btnHeight); offX += btnWidth; } // // Row 2 Stub // ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth * 1.5, btnHeight); // offX += btnWidth * 1.5; //------------------------------------------------ // set geometry (position) for row 3 offX = lleft; offY += btnHeight; //------------------- // // Row 3 Stub // button Enter ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth * 1, btnHeight); offX += btnWidth*1; // buttons [a]..[\] for (int i = 0; i < 12; i++) { buttons[i + 12 + 13]->setGeometry(offX, offY, btnWidth, btnHeight); offX += btnWidth; } // button Enter ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth * 2, btnHeight); offX += btnWidth*2; //------------------------------------------------ // set geometry (position) for row 4 offX = lleft; offY += btnHeight; //------------------- // button LCapsLock ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth*2.5, btnHeight); offX += btnWidth*2.5; for (int i = 0; i < 10; i++) { buttons[i + 12 + 12 + 13]->setGeometry(offX, offY, btnWidth, btnHeight); offX += btnWidth; } // button RCapsLock ctrlButtons[ctrlButtonsId++]->setGeometry(offX, offY, btnWidth*2.5, btnHeight); offX += btnWidth*2.5; //------------------------------------------------ // set geometry (position) for row 5 offX = lleft; offY += btnHeight; //------------------- ctrlButtons[ctrlButtonsId++]->setGeometry(offX + btnWidth * 1 , offY, btnWidth * 2, btnHeight); ctrlButtons[ctrlButtonsId++]->setGeometry(offX + btnWidth * 3 , offY, btnWidth * 9, btnHeight); ctrlButtons[ctrlButtonsId++]->setGeometry(offX + btnWidth * 12, offY, btnWidth * 2, btnHeight); //------------------------------------------------ } void UBKeyboardPalette::onDeactivated() { onActivated(false); } //-----------------------------------------------------------------------// // BTNImages Class //-----------------------------------------------------------------------// BTNImages::BTNImages(QString strHeight, int width, int height) { m_strHeight = strHeight; m_width = width; m_height = height; m_strLeftPassive = ":/images/virtual.keyboard/" + strHeight + "/left-passive.png"; m_strCenterPassive = ":/images/virtual.keyboard/" + strHeight + "/centre-passive.png"; m_strRightPassive = ":/images/virtual.keyboard/" + strHeight + "/right-passive.png"; m_strLeftActive = ":/images/virtual.keyboard/" + strHeight + "/left-active.png"; m_strCenterActive = ":/images/virtual.keyboard/" + strHeight + "/centre-active.png"; m_strRightActive = ":/images/virtual.keyboard/" + strHeight + "/right-active.png"; m_btnLeftPassive = QImage(m_strLeftPassive); m_btnCenterPassive = QImage(m_strCenterPassive); m_btnRightPassive = QImage(m_strRightPassive); m_btnLeftActive = QImage(m_strLeftActive); m_btnCenterActive = QImage(m_strCenterActive); m_btnRightActive = QImage(m_strRightActive); } ContentImage::ContentImage(QString strHeight, int height, QString strContentName) { m_strHeight = strHeight; m_height = height; m_strContent = ":/images/virtual.keyboard/" + strHeight + "/" + strContentName + ".png"; m_btnContent = QImage(m_strContent); } //-----------------------------------------------------------------------// // UBKeyboardButton Class //-----------------------------------------------------------------------// UBKeyboardButton::UBKeyboardButton(UBKeyboardPalette* parent, QString contentImagePath = "") :QWidget(parent), keyboard(parent), bFocused(false), bPressed(false) { m_parent = parent; m_contentImagePath = contentImagePath; imgContent = NULL; setCursor(Qt::PointingHandCursor); } UBKeyboardButton::~UBKeyboardButton() { if(imgContent != NULL) { delete imgContent; imgContent = NULL; } } bool UBKeyboardButton::isPressed() { return bPressed; } void UBKeyboardButton::paintEvent(QPaintEvent*) { QPainter painter(this); //-------------------------- if(imgContent != NULL) { if(imgContent->m_height != m_parent->currBtnImages->m_height) { delete imgContent; if(!m_contentImagePath.isEmpty()) imgContent = new ContentImage(m_parent->currBtnImages->m_strHeight, m_parent->currBtnImages->m_height, m_contentImagePath); } } else if(!m_contentImagePath.isEmpty()) imgContent = new ContentImage(m_parent->currBtnImages->m_strHeight, m_parent->currBtnImages->m_height, m_contentImagePath); //-------------------------- if (isPressed()) { painter.drawImage( 0,0, m_parent->currBtnImages->m_btnLeftActive, 0,0, m_parent->currBtnImages->m_btnLeftActive.width(), m_parent->currBtnImages->m_btnLeftActive.height() ); painter.drawImage( QRect(m_parent->currBtnImages->m_btnLeftActive.width(), 0, width() - m_parent->currBtnImages->m_btnLeftActive.width() - m_parent->currBtnImages->m_btnRightActive.width(), height()), m_parent->currBtnImages->m_btnCenterActive ); painter.drawImage( width() - m_parent->currBtnImages->m_btnRightActive.width(), 0, m_parent->currBtnImages->m_btnRightActive, 0,0, m_parent->currBtnImages->m_btnRightActive.width(), m_parent->currBtnImages->m_btnRightActive.height() ); } else { painter.drawImage( 0,0, m_parent->currBtnImages->m_btnLeftPassive, 0,0, m_parent->currBtnImages->m_btnLeftPassive.width(), m_parent->currBtnImages->m_btnLeftPassive.height() ); painter.drawImage( QRect(m_parent->currBtnImages->m_btnLeftPassive.width(), 0, width() - m_parent->currBtnImages->m_btnLeftPassive.width() - m_parent->currBtnImages->m_btnRightPassive.width(), height()), m_parent->currBtnImages->m_btnCenterPassive ); painter.drawImage( width() - m_parent->currBtnImages->m_btnRightPassive.width(), 0, m_parent->currBtnImages->m_btnRightPassive, 0,0, m_parent->currBtnImages->m_btnRightPassive.width(), m_parent->currBtnImages->m_btnRightPassive.height() ); } //-------------------------- this->paintContent(painter); //-------------------------- } void UBKeyboardButton::enterEvent ( QEvent*) { bFocused = true; update(); } void UBKeyboardButton::leaveEvent ( QEvent*) { bFocused = false; update(); } void UBKeyboardButton::mousePressEvent ( QMouseEvent * event) { event->accept(); bPressed = true; update(); this->onPress(); } void UBKeyboardButton::mouseReleaseEvent ( QMouseEvent * ) { bPressed = false; update(); this->onRelease(); } UBKeyButton::UBKeyButton(UBKeyboardPalette* parent) :UBKeyboardButton(parent), keybt(0) {} UBKeyButton::~UBKeyButton() {} bool UBKeyButton::shifted() { #if defined(Q_WS_MACX) return keyboard->shift; #else bool b = keyboard->shift; if (keybt->capsLockSwitch && keyboard->capsLock) b = !b; return b; #endif } bool UBKeyButton::capsed() { return keyboard->capsLock; } void UBKeyButton::onPress() { if (keybt!=NULL) { #if defined(Q_WS_MACX) int codeIndex = keyboard->nSpecialModifierIndex + (shifted())?1:(capsed() ? 2 : 0); #else int codeIndex = keyboard->nSpecialModifierIndex * 2 + shifted(); #endif if (keyboard->nSpecialModifierIndex) { if (keybt->codes[codeIndex].empty()) { sendUnicodeSymbol(keyboard->specialModifier); sendUnicodeSymbol(keybt->codes[shifted()]); } else { sendUnicodeSymbol(keybt->codes[codeIndex]); } keyboard->nSpecialModifierIndex = 0; } else { #if defined(Q_WS_MACX) int nSpecialModifierIndex; if (shifted()) nSpecialModifierIndex = keybt->modifierShift; else if(capsed()) nSpecialModifierIndex = keybt->modifierCaps; else nSpecialModifierIndex = keybt->modifierNo; #else int nSpecialModifierIndex = shifted()? keybt->modifierShift : keybt->modifierNo; #endif if (nSpecialModifierIndex) { keyboard->nSpecialModifierIndex = nSpecialModifierIndex; keyboard->specialModifier = keybt->codes[codeIndex]; } else { sendUnicodeSymbol(keybt->codes[codeIndex]); } } } if (keyboard->shift) { keyboard->shift = false; keyboard->update(); } } void UBKeyButton::onRelease() {} void UBKeyButton::paintContent(QPainter& painter) { if (keybt) { #if defined(Q_WS_MACX) QString text(QChar(shifted() ? keybt->shiftedSymbol : (capsed() ? keybt->capsedSymbol : keybt->simpleSymbol))); #else QString text(QChar(shifted() ? keybt->shiftedSymbol : keybt->simpleSymbol)); #endif QRect textRect(rect().x()+2, rect().y()+2, rect().width()-4, rect().height()-4); painter.drawText(textRect, Qt::AlignCenter, text); } } UBCntrlButton::UBCntrlButton(UBKeyboardPalette* parent, int _code, const QString& _contentImagePath ) :UBKeyboardButton(parent, _contentImagePath), label(""), code(_code) {} UBCntrlButton::UBCntrlButton(UBKeyboardPalette* parent, const QString& _label, int _code ) :UBKeyboardButton(parent), label(_label), code(_code) {} UBCntrlButton::~UBCntrlButton() {} void UBCntrlButton::onPress() { sendControlSymbol(code); } void UBCntrlButton::onRelease() {} void UBCntrlButton::paintContent(QPainter& painter) { if(!label.isEmpty()) { painter.drawText(rect(), Qt::AlignCenter, label); } else if(imgContent != NULL) { painter.drawImage(( rect().width() - imgContent->m_btnContent.width() ) / 2, ( rect().height() - imgContent->m_btnContent.height() ) / 2, imgContent->m_btnContent, 0,0, imgContent->m_btnContent.width(), imgContent->m_btnContent.height()); } } UBCapsLockButton::UBCapsLockButton(UBKeyboardPalette* parent, const QString _contentImagePath) :UBKeyboardButton(parent, _contentImagePath) {} UBCapsLockButton::~UBCapsLockButton() {} void UBCapsLockButton::onPress() { keyboard->capsLock = !keyboard->capsLock; keyboard->update(); } void UBCapsLockButton::onRelease() {} bool UBCapsLockButton::isPressed() { return keyboard->capsLock; } void UBCapsLockButton::paintContent(QPainter& painter) { if(imgContent != NULL) { painter.drawImage(( rect().width() - imgContent->m_btnContent.width() ) / 2, ( rect().height() - imgContent->m_btnContent.height() ) / 2, imgContent->m_btnContent, 0,0, imgContent->m_btnContent.width(), imgContent->m_btnContent.height()); } else painter.drawText(rect(), Qt::AlignCenter, "^"); } UBShiftButton::UBShiftButton(UBKeyboardPalette* parent, const QString _contentImagePath) :UBKeyboardButton(parent, _contentImagePath) {} UBShiftButton::~UBShiftButton() {} void UBShiftButton::onPress() { keyboard->shift = !keyboard->shift; keyboard->update(); } void UBShiftButton::onRelease() {} bool UBShiftButton::isPressed() { return keyboard->shift; } void UBShiftButton::paintContent(QPainter& painter) { if(imgContent != NULL) { painter.drawImage(( rect().width() - imgContent->m_btnContent.width() ) / 2, ( rect().height() - imgContent->m_btnContent.height() ) / 2, imgContent->m_btnContent, 0,0, imgContent->m_btnContent.width(), imgContent->m_btnContent.height()); } else painter.drawText(rect(), Qt::AlignCenter, "^"); } UBLocaleButton::UBLocaleButton(UBKeyboardPalette* parent) :UBKeyboardButton(parent) { localeMenu = new QMenu(this); for (int i=0; i<parent->nLocalesCount; i++) { QAction* action = (parent->locales[i]->icon!=NULL) ? localeMenu->addAction(*parent->locales[i]->icon, parent->locales[i]->fullName) : localeMenu->addAction(parent->locales[i]->fullName); action->setData(QVariant(i)); } } UBLocaleButton::~UBLocaleButton() { delete localeMenu; } void UBLocaleButton::onPress() { } void UBLocaleButton::onRelease() { keyboard->languagePopupActive = true; QAction* action = localeMenu->exec(mapToGlobal(QPoint(0,0))); keyboard->languagePopupActive = false; if (action!=NULL) { int nLocale = action->data().toInt(); keyboard->setLocale(nLocale); } } void UBLocaleButton::paintContent(QPainter& painter) { const QString* localeName = keyboard->getLocaleName(); if (localeName!=NULL) painter.drawText(rect(), Qt::AlignCenter, *localeName); }
26.895349
258
0.620695
[ "geometry" ]
544ab5a185603336cb3fb678833d12c335eb5fc1
17,610
cpp
C++
npplugin_demo_frmwk/npfdemo/npfrmwk_entry.cpp
bluedump/BHO
4ffead78823c4d655f05b0bc84cdb3c71ff4a1b2
[ "Apache-2.0" ]
1
2020-11-10T04:01:03.000Z
2020-11-10T04:01:03.000Z
npplugin_demo_frmwk/npfdemo/npfrmwk_entry.cpp
bluedump/BHO
4ffead78823c4d655f05b0bc84cdb3c71ff4a1b2
[ "Apache-2.0" ]
null
null
null
npplugin_demo_frmwk/npfdemo/npfrmwk_entry.cpp
bluedump/BHO
4ffead78823c4d655f05b0bc84cdb3c71ff4a1b2
[ "Apache-2.0" ]
null
null
null
#include "npfrmwkbase.h" // // npapi plugin functions // NPNetscapeFuncs* nsPluginInstanceBase::NPNFuncs = NULL; #ifdef XP_UNIX NP_EXPORT(char*) NP_GetPluginVersion() { return nsPluginInstanceBase::GetPluginVersion(); } #endif #if defined(XP_UNIX) NP_EXPORT(const char*) NP_GetMIMEDescription() #elif defined(XP_WIN) || defined(XP_OS2) const char* NP_GetMIMEDescription() #endif { return nsPluginInstanceBase::GetMIMEDescription(); } #ifdef XP_UNIX NP_EXPORT(NPError) NP_GetValue(void* future, NPPVariable aVariable, void* aValue) { return nsPluginInstanceBase::GetValue(aVariable,aValue); } #endif static NPError fillPluginFunctionTable(NPPluginFuncs* aNPPFuncs) { if (!aNPPFuncs) return NPERR_INVALID_FUNCTABLE_ERROR; // Set up the plugin function table that Netscape will use to call us. aNPPFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR; aNPPFuncs->newp = NPP_New; aNPPFuncs->destroy = NPP_Destroy; aNPPFuncs->setwindow = NPP_SetWindow; aNPPFuncs->newstream = NPP_NewStream; aNPPFuncs->destroystream = NPP_DestroyStream; aNPPFuncs->asfile = NPP_StreamAsFile; aNPPFuncs->writeready = NPP_WriteReady; aNPPFuncs->write = NPP_Write; aNPPFuncs->print = NPP_Print; aNPPFuncs->event = NPP_HandleEvent; aNPPFuncs->urlnotify = NPP_URLNotify; aNPPFuncs->getvalue = NPP_GetValue; aNPPFuncs->setvalue = NPP_SetValue; return NPERR_NO_ERROR; } #if defined(XP_MACOSX) NP_EXPORT(NPError) NP_Initialize(NPNetscapeFuncs* aNPNFuncs) #elif defined(XP_WIN) || defined(XP_OS2) NPError OSCALL NP_Initialize(NPNetscapeFuncs* aNPNFuncs) #elif defined(XP_UNIX) NP_EXPORT(NPError) NP_Initialize(NPNetscapeFuncs* aNPNFuncs, NPPluginFuncs* pFuncs) #endif { nsPluginInstanceBase::NPNFuncs = aNPNFuncs; #if defined(XP_UNIX) && !defined(XP_MACOSX) if (!fillPluginFunctionTable(pFuncs)) { return NPERR_INVALID_FUNCTABLE_ERROR; } #endif return nsPluginInstanceBase::PluginInitialize(); } #if defined(XP_MACOSX) NP_EXPORT(NPError) NP_GetEntryPoints(NPPluginFuncs* pFuncs) #elif defined(XP_WIN) || defined(XP_OS2) NPError OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs) #endif #if defined(XP_MACOSX) || defined(XP_WIN) || defined(XP_OS2) { return fillPluginFunctionTable(pFuncs); } #endif #if defined(XP_UNIX) NP_EXPORT(NPError) NP_Shutdown() #elif defined(XP_WIN) || defined(XP_OS2) NPError OSCALL NP_Shutdown() #endif { nsPluginInstanceBase::PluginShutdown(); return NPERR_NO_ERROR; } //npp_functions #ifdef XP_UNIX char* NPP_GetMIMEDescription(void) { return NS_GetMIMEDescription(); } #endif NPError NPP_New(NPMIMEType pluginType, NPP instance, uint16_t mode, int16_t argc, char* argn[], char* argv[], NPSavedData* saved) { if (!instance) return NPERR_INVALID_INSTANCE_ERROR; // create a new plugin instance object // initialization will be done when the associated window is ready nsPluginCreateData ds; ds.instance = instance; ds.type = pluginType; ds.mode = mode; ds.argc = argc; ds.argn = argn; ds.argv = argv; ds.saved = saved; nsPluginInstanceBase * plugin = nsPluginInstanceBase::NewPluginInstance(&ds); if (!plugin) return NPERR_OUT_OF_MEMORY_ERROR; // associate the plugin instance object with NPP instance instance->pdata = (void *)plugin; return NPERR_NO_ERROR; } NPError NPP_Destroy (NPP instance, NPSavedData** save) { if (!instance) return NPERR_INVALID_INSTANCE_ERROR; nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; if (plugin) { plugin->shut(); nsPluginInstanceBase::DestroyPluginInstance(plugin); } return NPERR_NO_ERROR; } NPError NPP_SetWindow (NPP instance, NPWindow* pNPWindow) { if (!instance) return NPERR_INVALID_INSTANCE_ERROR; if (!pNPWindow) return NPERR_GENERIC_ERROR; nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; if (!plugin) return NPERR_GENERIC_ERROR; // window just created if (!plugin->isInitialized() && pNPWindow->window) { if (!plugin->init(pNPWindow)) { nsPluginInstanceBase::DestroyPluginInstance(plugin); return NPERR_MODULE_LOAD_FAILED_ERROR; } } // window goes away if (!pNPWindow->window && plugin->isInitialized()) return plugin->SetWindow(pNPWindow); // window resized? if (plugin->isInitialized() && pNPWindow->window) return plugin->SetWindow(pNPWindow); // this should not happen, nothing to do if (!pNPWindow->window && !plugin->isInitialized()) return plugin->SetWindow(pNPWindow); return NPERR_NO_ERROR; } NPError NPP_NewStream(NPP instance, NPMIMEType type, NPStream* stream, NPBool seekable, uint16_t* stype) { if (!instance) return NPERR_INVALID_INSTANCE_ERROR; nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; if (!plugin) return NPERR_GENERIC_ERROR; return plugin->NewStream(type, stream, seekable, stype); } int32_t NPP_WriteReady (NPP instance, NPStream *stream) { if (!instance) return 0x0fffffff; nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; if (!plugin) return 0x0fffffff; return plugin->WriteReady(stream); } int32_t NPP_Write (NPP instance, NPStream *stream, int32_t offset, int32_t len, void *buffer) { if (!instance) return len; nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; if (!plugin) return len; return plugin->Write(stream, offset, len, buffer); } NPError NPP_DestroyStream (NPP instance, NPStream *stream, NPError reason) { if (!instance) return NPERR_INVALID_INSTANCE_ERROR; nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; if (!plugin) return NPERR_GENERIC_ERROR; return plugin->DestroyStream(stream, reason); } void NPP_StreamAsFile (NPP instance, NPStream* stream, const char* fname) { if (!instance) return; nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; if (!plugin) return; plugin->StreamAsFile(stream, fname); } void NPP_Print (NPP instance, NPPrint* printInfo) { if (!instance) return; nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; if (!plugin) return; plugin->Print(printInfo); } void NPP_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData) { if (!instance) return; nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; if (!plugin) return; plugin->URLNotify(url, reason, notifyData); } NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value) { if (!instance) return NPERR_INVALID_INSTANCE_ERROR; nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; if (!plugin) return NPERR_GENERIC_ERROR; return plugin->SetValue(variable, value); } int16_t NPP_HandleEvent(NPP instance, void* event) { if (!instance) return 0; nsPluginInstanceBase * plugin = (nsPluginInstanceBase *)instance->pdata; if (!plugin) return 0; return plugin->HandleEvent(event); } NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value) { if(instance == NULL) return NPERR_INVALID_INSTANCE_ERROR; NPError rv = NPERR_NO_ERROR; nsPluginInstanceBase* plugin = (nsPluginInstanceBase*)instance->pdata; if(plugin == NULL) return NPERR_GENERIC_ERROR; if (variable==NPPVpluginScriptableNPObject) { *(NPObject **)value = plugin->GetScriptableObject(); } else rv=plugin->GetValue(variable,value); return rv; } //npn_functions bool NPN_SetProperty(NPP instance, NPObject* obj, NPIdentifier propertyName, const NPVariant* value) { return nsPluginInstanceBase::NPNFuncs->setproperty(instance, obj, propertyName, value); } NPIdentifier NPN_GetIntIdentifier(int32_t intid) { return nsPluginInstanceBase::NPNFuncs->getintidentifier(intid); } NPIdentifier NPN_GetStringIdentifier(const NPUTF8* name) { return nsPluginInstanceBase::NPNFuncs->getstringidentifier(name); } void NPN_GetStringIdentifiers(const NPUTF8 **names, int32_t nameCount, NPIdentifier *identifiers) { return nsPluginInstanceBase::NPNFuncs->getstringidentifiers(names, nameCount, identifiers); } bool NPN_IdentifierIsString(NPIdentifier identifier) { return nsPluginInstanceBase::NPNFuncs->identifierisstring(identifier); } NPUTF8* NPN_UTF8FromIdentifier(NPIdentifier identifier) { return nsPluginInstanceBase::NPNFuncs->utf8fromidentifier(identifier); } int32_t NPN_IntFromIdentifier(NPIdentifier identifier) { return nsPluginInstanceBase::NPNFuncs->intfromidentifier(identifier); } NPError NPN_GetValue(NPP instance, NPNVariable variable, void* value) { return nsPluginInstanceBase::NPNFuncs->getvalue(instance, variable, value); } NPError NPN_SetValue(NPP instance, NPPVariable variable, void* value) { return nsPluginInstanceBase::NPNFuncs->setvalue(instance, variable, value); } void NPN_InvalidateRect(NPP instance, NPRect* rect) { nsPluginInstanceBase::NPNFuncs->invalidaterect(instance, rect); } bool NPN_HasProperty(NPP instance, NPObject* obj, NPIdentifier propertyName) { return nsPluginInstanceBase::NPNFuncs->hasproperty(instance, obj, propertyName); } NPObject* NPN_CreateObject(NPP instance, NPClass* aClass) { return nsPluginInstanceBase::NPNFuncs->createobject(instance, aClass); } bool NPN_Invoke(NPP npp, NPObject* obj, NPIdentifier methodName, const NPVariant *args, uint32_t argCount, NPVariant *result) { return nsPluginInstanceBase::NPNFuncs->invoke(npp, obj, methodName, args, argCount, result); } bool NPN_InvokeDefault(NPP npp, NPObject* obj, const NPVariant *args, uint32_t argCount, NPVariant *result) { return nsPluginInstanceBase::NPNFuncs->invokeDefault(npp, obj, args, argCount, result); } bool NPN_Construct(NPP npp, NPObject* npobj, const NPVariant* args, uint32_t argCount, NPVariant* result) { return nsPluginInstanceBase::NPNFuncs->construct(npp, npobj, args, argCount, result); } const char* NPN_UserAgent(NPP instance) { return nsPluginInstanceBase::NPNFuncs->uagent(instance); } NPObject* NPN_RetainObject(NPObject* obj) { return nsPluginInstanceBase::NPNFuncs->retainobject(obj); } void NPN_ReleaseObject(NPObject* obj) { return nsPluginInstanceBase::NPNFuncs->releaseobject(obj); } void* NPN_MemAlloc(uint32_t size) { return nsPluginInstanceBase::NPNFuncs->memalloc(size); } char* NPN_StrDup(const char* str) { return strcpy((char*)nsPluginInstanceBase::NPNFuncs->memalloc(strlen(str) + 1), str); } void NPN_MemFree(void* ptr) { return nsPluginInstanceBase::NPNFuncs->memfree(ptr); } uint32_t NPN_ScheduleTimer(NPP instance, uint32_t interval, NPBool repeat, void (*timerFunc)(NPP npp, uint32_t timerID)) { return nsPluginInstanceBase::NPNFuncs->scheduletimer(instance, interval, repeat, timerFunc); } void NPN_UnscheduleTimer(NPP instance, uint32_t timerID) { return nsPluginInstanceBase::NPNFuncs->unscheduletimer(instance, timerID); } void NPN_ReleaseVariantValue(NPVariant *variant) { return nsPluginInstanceBase::NPNFuncs->releasevariantvalue(variant); } NPError NPN_GetURLNotify(NPP instance, const char* url, const char* target, void* notifyData) { return nsPluginInstanceBase::NPNFuncs->geturlnotify(instance, url, target, notifyData); } NPError NPN_GetURL(NPP instance, const char* url, const char* target) { return nsPluginInstanceBase::NPNFuncs->geturl(instance, url, target); } NPError NPN_RequestRead(NPStream* stream, NPByteRange* rangeList) { return nsPluginInstanceBase::NPNFuncs->requestread(stream, rangeList); } NPError NPN_PostURLNotify(NPP instance, const char* url, const char* target, uint32_t len, const char* buf, NPBool file, void* notifyData) { return nsPluginInstanceBase::NPNFuncs->posturlnotify(instance, url, target, len, buf, file, notifyData); } NPError NPN_PostURL(NPP instance, const char *url, const char *target, uint32_t len, const char *buf, NPBool file) { return nsPluginInstanceBase::NPNFuncs->posturl(instance, url, target, len, buf, file); } NPError NPN_DestroyStream(NPP instance, NPStream* stream, NPError reason) { return nsPluginInstanceBase::NPNFuncs->destroystream(instance, stream, reason); } NPError NPN_NewStream(NPP instance, NPMIMEType type, const char* target, NPStream** stream) { return nsPluginInstanceBase::NPNFuncs->newstream(instance, type, target, stream); } int32_t NPN_Write(NPP instance, NPStream* stream, int32_t len, void* buf) { return nsPluginInstanceBase::NPNFuncs->write(instance, stream, len, buf); } bool NPN_Enumerate(NPP instance, NPObject *npobj, NPIdentifier **identifiers, uint32_t *identifierCount) { return nsPluginInstanceBase::NPNFuncs->enumerate(instance, npobj, identifiers, identifierCount); } bool NPN_GetProperty(NPP instance, NPObject *npobj, NPIdentifier propertyName, NPVariant *result) { return nsPluginInstanceBase::NPNFuncs->getproperty(instance, npobj, propertyName, result); } bool NPN_Evaluate(NPP instance, NPObject *npobj, NPString *script, NPVariant *result) { return nsPluginInstanceBase::NPNFuncs->evaluate(instance, npobj, script, result); } void NPN_SetException(NPObject *npobj, const NPUTF8 *message) { return nsPluginInstanceBase::NPNFuncs->setexception(npobj, message); } NPBool NPN_ConvertPoint(NPP instance, double sourceX, double sourceY, NPCoordinateSpace sourceSpace, double *destX, double *destY, NPCoordinateSpace destSpace) { return nsPluginInstanceBase::NPNFuncs->convertpoint(instance, sourceX, sourceY, sourceSpace, destX, destY, destSpace); } NPError NPN_SetValueForURL(NPP instance, NPNURLVariable variable, const char *url, const char *value, uint32_t len) { return nsPluginInstanceBase::NPNFuncs->setvalueforurl(instance, variable, url, value, len); } NPError NPN_GetValueForURL(NPP instance, NPNURLVariable variable, const char *url, char **value, uint32_t *len) { return nsPluginInstanceBase::NPNFuncs->getvalueforurl(instance, variable, url, value, len); } NPError NPN_GetAuthenticationInfo(NPP instance, const char *protocol, const char *host, int32_t port, const char *scheme, const char *realm, char **username, uint32_t *ulen, char **password, uint32_t *plen) { return nsPluginInstanceBase::NPNFuncs->getauthenticationinfo(instance, protocol, host, port, scheme, realm, username, ulen, password, plen); } void NPN_PluginThreadAsyncCall(NPP plugin, void (*func)(void*), void* userdata) { return nsPluginInstanceBase::NPNFuncs->pluginthreadasynccall(plugin, func, userdata); } void NPN_URLRedirectResponse(NPP instance, void* notifyData, NPBool allow) { return nsPluginInstanceBase::NPNFuncs->urlredirectresponse(instance, notifyData, allow); } #ifdef ENABLE_SCRIPT_OBJECT /****************************************************************************\ These are the static functions given to the browser in the NPClass struct. You might look at these as the "entry points" for the nsScriptObjectBase \****************************************************************************/ NPObject* nsScriptObjectBase::_Allocate(NPP npp, NPClass *aClass) { return nsScriptObjectBase::AllocateScriptPluginObject(npp,aClass); } void nsScriptObjectBase::_Deallocate(NPObject *npobj) { //delete static_cast<nsScriptObjectBase *>(npobj); delete (nsScriptObjectBase*)npobj; } void nsScriptObjectBase::_Invalidate(NPObject *npobj) { return ((nsScriptObjectBase*)npobj)->Invalidate(); } bool nsScriptObjectBase::_HasMethod(NPObject *npobj, NPIdentifier name) { return ((nsScriptObjectBase*)npobj)->HasMethod(name); } bool nsScriptObjectBase::_Invoke(NPObject *npobj, NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) { return ((nsScriptObjectBase*)npobj)->Invoke(name,args,argCount,result); } bool nsScriptObjectBase::_InvokeDefault(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { return ((nsScriptObjectBase*)npobj)->InvokeDefault(args,argCount,result); } bool nsScriptObjectBase::_HasProperty(NPObject *npobj, NPIdentifier name) { return ((nsScriptObjectBase*)npobj)->HasProperty(name); } bool nsScriptObjectBase::_GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) { return ((nsScriptObjectBase*)npobj)->GetProperty(name,result); } bool nsScriptObjectBase::_SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) { return ((nsScriptObjectBase*)npobj)->SetProperty(name, value); } bool nsScriptObjectBase::_RemoveProperty(NPObject *npobj, NPIdentifier name) { return ((nsScriptObjectBase*)npobj)->RemoveProperty(name); } bool nsScriptObjectBase::_Enumerate(NPObject *npobj, NPIdentifier **value, uint32_t *count) { return ((nsScriptObjectBase*)npobj)->Enumerate(value, count); } bool nsScriptObjectBase::_Construct(NPObject *npobj, const NPVariant *args, uint32_t argCount, NPVariant *result) { return ((nsScriptObjectBase*)npobj)->Construct(args, argCount, result); } // This defines the "entry points"; it's how the browser knows how to create the object // when you call NPN_CreateObject, and how it knows how to call functions on it NPClass nsScriptObjectBase::nsScriptObjectClass = { NP_CLASS_STRUCT_VERSION_CTOR, nsScriptObjectBase::_Allocate, nsScriptObjectBase::_Deallocate, nsScriptObjectBase::_Invalidate, nsScriptObjectBase::_HasMethod, nsScriptObjectBase::_Invoke, nsScriptObjectBase::_InvokeDefault, nsScriptObjectBase::_HasProperty, nsScriptObjectBase::_GetProperty, nsScriptObjectBase::_SetProperty, nsScriptObjectBase::_RemoveProperty, nsScriptObjectBase::_Enumerate, nsScriptObjectBase::_Construct }; #endif
28.868852
160
0.757297
[ "object" ]
5451f6f13788cf313cafbf8493f49491b212a57c
851
hpp
C++
src/json.hpp
DavidPfander-UniStuttgart/jsoncpp
cc4d04328f47c4f89898eda03e6460e01106252e
[ "BSD-3-Clause" ]
null
null
null
src/json.hpp
DavidPfander-UniStuttgart/jsoncpp
cc4d04328f47c4f89898eda03e6460e01106252e
[ "BSD-3-Clause" ]
1
2017-07-26T16:39:10.000Z
2018-07-26T19:31:23.000Z
src/json.hpp
DavidPfander-UniStuttgart/jsoncpp
cc4d04328f47c4f89898eda03e6460e01106252e
[ "BSD-3-Clause" ]
null
null
null
// Copyright (C) 2008-today The SG++ project // This file is part of the SG++ project. For conditions of distribution and // use, please see the copyright notice provided with SG++ or at // sgpp.sparsegrids.org #pragma once #include "dict_node.hpp" #include "token.hpp" #include <iostream> #include <map> #include <memory> #include <string> #include <vector> namespace json { class json : public dict_node { private: std::string fileName; std::vector<token> tokenize(const std::string &input); public: explicit json(const std::string &fileName); json(); json(const json &original); virtual json *clone(); void clear(); void serialize(const std::string &outFileName); void deserialize(std::string content); void deserializeFromString(const std::string &content); using dict_node::serialize; }; } // namespace json
18.5
76
0.712103
[ "vector" ]
54563a924c24d34bfa3ca4797b31f99271ecac89
2,553
cpp
C++
libcxx/test/libcxx/algorithms/sort_stability.pass.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
libcxx/test/libcxx/algorithms/sort_stability.pass.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
libcxx/test/libcxx/algorithms/sort_stability.pass.cpp
lxbndr/llvm-project
2b715b15f5f4c6dd60f05d1b62f9c404e8b56e34
[ "Apache-2.0" ]
null
null
null
//===----------------------------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // <algorithm> // Test std::sort stability randomization // UNSUPPORTED: libcxx-no-debug-mode, c++03, windows // ADDITIONAL_COMPILE_FLAGS: -D_LIBCPP_DEBUG=1 #include <algorithm> #include <array> #include <cassert> #include <iterator> #include <vector> #include "test_macros.h" struct EqualType { int value = 0; constexpr bool operator<(const EqualType&) const { return false; } }; std::vector<EqualType> deterministic() { static constexpr int kSize = 100; std::vector<EqualType> v; v.resize(kSize); for (int i = 0; i < kSize; ++i) { v[i].value = kSize / 2 - i * (i % 2 ? -1 : 1); } std::__sort(v.begin(), v.end(), std::less<EqualType>()); return v; } void test_randomization() { static constexpr int kSize = 100; std::vector<EqualType> v; v.resize(kSize); for (int i = 0; i < kSize; ++i) { v[i].value = kSize / 2 - i * (i % 2 ? -1 : 1); } auto deterministic_v = deterministic(); std::sort(v.begin(), v.end()); bool all_equal = true; for (int i = 0; i < kSize; ++i) { if (v[i].value != deterministic_v[i].value) { all_equal = false; } } assert(!all_equal); } void test_same() { static constexpr int kSize = 100; std::vector<EqualType> v; v.resize(kSize); for (int i = 0; i < kSize; ++i) { v[i].value = kSize / 2 - i * (i % 2 ? -1 : 1); } auto snapshot_v = v; auto snapshot_custom_v = v; std::sort(v.begin(), v.end()); std::sort(snapshot_v.begin(), snapshot_v.end()); std::sort(snapshot_custom_v.begin(), snapshot_custom_v.end(), [](const EqualType&, const EqualType&) { return false; }); bool all_equal = true; for (int i = 0; i < kSize; ++i) { if (v[i].value != snapshot_v[i].value || v[i].value != snapshot_custom_v[i].value) { all_equal = false; } } assert(all_equal); } #if TEST_STD_VER > 17 constexpr bool test_constexpr() { std::array<EqualType, 10> v; for (int i = 9; i >= 0; --i) { v[9 - i].value = i; } std::sort(v.begin(), v.end()); return std::is_sorted(v.begin(), v.end()); } #endif int main(int, char**) { test_randomization(); test_same(); #if TEST_STD_VER > 17 static_assert(test_constexpr(), ""); #endif return 0; }
25.787879
88
0.578535
[ "vector" ]
545b76fdd418d62ac2a59e7908d18b077d471d84
3,430
cpp
C++
ConvNN/OpenCL.cpp
SergiosKar/Convolutional-Neural-Network
b206c03daf5287778a4b7aa769f870f8c592cd09
[ "Apache-2.0" ]
16
2019-04-22T14:02:44.000Z
2022-03-15T13:07:47.000Z
ConvNN/OpenCL.cpp
SergiosKar/Convolutional-Neural-Network
b206c03daf5287778a4b7aa769f870f8c592cd09
[ "Apache-2.0" ]
null
null
null
ConvNN/OpenCL.cpp
SergiosKar/Convolutional-Neural-Network
b206c03daf5287778a4b7aa769f870f8c592cd09
[ "Apache-2.0" ]
3
2019-02-18T13:15:03.000Z
2019-12-30T20:08:50.000Z
#include "OpenCL.h" #include "util.h" cl::Program OpenCL::clprogram; cl::Context OpenCL::clcontext; cl::CommandQueue OpenCL::clqueue; void OpenCL::initialize_OpenCL() { // get all platforms (drivers), e.g. NVIDIA std::vector<cl::Platform> all_platforms; cl::Platform::get(&all_platforms); if (all_platforms.size() == 0) { std::cout << " No platforms found. Check OpenCL installation!\n"; exit(1); } cl::Platform default_platform = all_platforms[0]; std::cout << "Using platform: " << default_platform.getInfo<CL_PLATFORM_NAME>() << "\n"; // get default device (CPUs, GPUs) of the default platform std::vector<cl::Device> all_devices; default_platform.getDevices(CL_DEVICE_TYPE_ALL, &all_devices); if (all_devices.size() == 0) { std::cout << " No devices found. Check OpenCL installation!\n"; exit(1); } cl::Device default_device = all_devices[0]; std::cout << "Using device: " << default_device.getInfo<CL_DEVICE_NAME>() << "\n"; /*//////////////////////////////////////////////////// std::cout << "\t-------------------------" << std::endl; std::string s; default_device.getInfo(CL_DEVICE_NAME, &s); std::cout << "\t\tName: " << s << std::endl; //default_device.getInfo(CL_DEVICE_OPENCL_C_VERSION, &s); //std::cout << "\t\tVersion: " << s << std::endl; int i; default_device.getInfo(CL_DEVICE_MAX_COMPUTE_UNITS, &i); std::cout << "\t\tMax. Compute Units: " << i << std::endl; size_t size; default_device.getInfo(CL_DEVICE_LOCAL_MEM_SIZE, &size); std::cout << "\t\tLocal Memory Size: " << size / 1024 << " KB" << std::endl; default_device.getInfo(CL_DEVICE_GLOBAL_MEM_SIZE, &size); std::cout << "\t\tGlobal Memory Size: " << size / (1024 * 1024) << " MB" << std::endl; default_device.getInfo(CL_DEVICE_MAX_MEM_ALLOC_SIZE, &size); std::cout << "\t\tMax Alloc Size: " << size / (1024 * 1024) << " MB" << std::endl; default_device.getInfo(CL_DEVICE_MAX_WORK_GROUP_SIZE, &size); std::cout << "\t\tMax Work-group Total Size: " << size << std::endl; std::vector<size_t> d; default_device.getInfo(CL_DEVICE_MAX_WORK_ITEM_SIZES, &d); std::cout << "\t\tMax Work-group Dims: ("; for (std::vector<size_t>::iterator st = d.begin(); st != d.end(); st++) std::cout << *st << " "; std::cout << "\x08)" << std::endl; std::cout << "\t-------------------------" << std::endl; ////////////////////////////////////////////////////////////*/ // a context is like a "runtime link" to the device and platform; // i.e. communication is possible OpenCL::clcontext=cl::Context({ default_device }); // create the program that we want to execute on the device cl::Program::Sources sources; std::string src,src2,src3; src = util::loadProgram("kernelheader.cl"); src2 = util::loadProgram("fcnn_kernels.cl"); src3 = util::loadProgram("conv_kernels.cl"); src = src + src2+src3; sources.push_back({ src.c_str(), src.length() }); OpenCL::clprogram=cl::Program(OpenCL::clcontext, sources); try { OpenCL::clprogram.build({ default_device }); } catch (...) { cl_int buildErr = CL_SUCCESS; auto buildInfo = OpenCL::clprogram.getBuildInfo<CL_PROGRAM_BUILD_LOG>(&buildErr); for (auto &pair : buildInfo) { std::cerr << pair.second << std::endl << std::endl; } } OpenCL::clqueue=cl::CommandQueue(OpenCL::clcontext, default_device); }
30.087719
90
0.61312
[ "vector" ]
545f7b63b0659b23f9972df9e765a39ece977d67
1,335
cpp
C++
Dataset/Leetcode/valid/48/340.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/valid/48/340.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
Dataset/Leetcode/valid/48/340.cpp
kkcookies99/UAST
fff81885aa07901786141a71e5600a08d7cb4868
[ "MIT" ]
null
null
null
class Solution { public: void XXX(vector<vector<int>>& matrix) { int rows = matrix.size(); int cols = rows; if(rows == 1) return; int convert_row1, convert_row2, convert_row3, convert_row4; int convert_col1, convert_col2, convert_col3, convert_col4; int temp1, temp2, temp3, temp4; for(int row = 0; row < rows / 2; row++) { int new_cols = cols - row - 1; for(int col = row; col < new_cols; col++) { // 每次转换4次 convert_row1 = row, convert_col1 = col; convert_row2 = convert_col1, convert_col2 = cols - convert_row1 - 1; convert_row3 = convert_col2, convert_col3 = cols - convert_row2 - 1; convert_row4 = convert_col3, convert_col4 = cols - convert_row3 - 1; temp1 = matrix[convert_row1][convert_col1]; temp2 = matrix[convert_row2][convert_col2]; temp3 = matrix[convert_row3][convert_col3]; temp4 = matrix[convert_row4][convert_col4]; matrix[convert_row1][convert_col1] = temp4; matrix[convert_row2][convert_col2] = temp1; matrix[convert_row3][convert_col3] = temp2; matrix[convert_row4][convert_col4] = temp3; } } } };
41.71875
84
0.564794
[ "vector" ]
546da392707e2d5514f4a3cab09a355a44a9d800
7,111
cpp
C++
fp_core/src/main/src/PythonBindings/Graphics.cpp
submain/fruitpunch
31773128238830d3d335c1915877dc0db56836cd
[ "MIT" ]
null
null
null
fp_core/src/main/src/PythonBindings/Graphics.cpp
submain/fruitpunch
31773128238830d3d335c1915877dc0db56836cd
[ "MIT" ]
null
null
null
fp_core/src/main/src/PythonBindings/Graphics.cpp
submain/fruitpunch
31773128238830d3d335c1915877dc0db56836cd
[ "MIT" ]
1
2020-08-14T02:51:47.000Z
2020-08-14T02:51:47.000Z
/* * Common.cpp * * Created on: Oct 26, 2012 * Author: leo */ #include <boost/python/detail/prefix.hpp> #include <boost/python.hpp> #include <fruitpunch/PythonBindings/Graphics.h> #include <string> // --------------------------------------------------------------------------- // Fp core includes // --------------------------------------------------------------------------- #include <fruitpunch/Common/Observable.h> #include <fruitpunch/Elements/Element.h> #include <fruitpunch/Elements/Scene.h> #include <fruitpunch/Graphics/Vertex.h> #include <fruitpunch/Graphics/Primitive.h> #include <fruitpunch/Graphics/Sprite.h> #include <fruitpunch/Graphics/Color.h> #include <fruitpunch/Graphics/Group.h> #include <fruitpunch/Graphics/Image.h> #include <fruitpunch/Graphics/Transformable.h> // --------------------------------------------------------------------------- // Imports // --------------------------------------------------------------------------- using namespace fp_core::common; using namespace boost::python; using namespace std; namespace fp_core { namespace python { // --------------------------------------------------------------------------- // Methods // --------------------------------------------------------------------------- // ____________________________________________________________________________ void Graphics::declareClasses() { class_<Element, bases<Observable>, boost::shared_ptr<Element> >("Element") .def("add", &Element::add) .def("add_orphan", &Element::addOrphan) .def("remove", &Element::remove) .def("destroy", &Element::destroy) .def("render_frame", &Element::renderFrame) .def("tick", &Element::tick) .def("get_scene", &Element::getScene) .def("set_scene", &Element::setScene) .def("get_children", &Element::getChildren) .def("get_parent", &Element::getParent) .def("set_parent", &Element::setParent); class_<point>("Point") .def_readwrite("x", &point::x) .def_readwrite("y", &point::y); class_<Vertex>("Vertex", init<point>()) .def("get_position", &Vertex::getPosition) .def("get_uvmap", &Vertex::getUvmap) .def("set_position", &Vertex::setPosition) .def("set_uvmap", &Vertex::setUvmap); class_<Primitive, bases<Element>, boost::shared_ptr<Primitive> >("Primitive") .def("add_vertex", &Primitive::addVertex) .def("point_vector", &Primitive::pointVector) .def("uv_point_vector", &Primitive::uvPointVector) .def("bounding_box", &Primitive::boundingBox) .def("boundaries", &Primitive::boundaries) .def("transformed_bounds", &Primitive::transformedBounds) .def("contains", &Primitive::contains) .def("vertices_center", &Primitive::verticesCenter) .def("move", &Primitive::move) .def("rotate", &Primitive::rotate) .def("scale", &Primitive::scale) .def("get_center", &Primitive::getCenter) .def("get_width", &Primitive::getWidth) .def("get_height", &Primitive::getHeight) .def("get_x", &Primitive::getX) .def("get_y", &Primitive::getY) .def("get_top", &Primitive::getTop) .def("get_left", &Primitive::getLeft) .def("get_tex_center", &Primitive::getTexCenter) .def("get_tex_position", &Primitive::getTexPosition) .def("get_tex_scale", &Primitive::getTexScale) .def("get_tex_rotation", &Primitive::getTexRotation) .def("get_tex_x", &Primitive::getTexX) .def("get_tex_y", &Primitive::getTexY) .def("get_position", &Primitive::getPosition) .def("get_rotation", &Primitive::getRotation) .def("get_scale", &Primitive::getScale) .def("get_vertices", &Primitive::getVertices) .def("is_stick", &Primitive::isStick) .def("get_image", &Primitive::getImage) .def("get_alpha", &Primitive::getAlpha) .def("set_center", &Primitive::setCenter) .def("set_width", &Primitive::setWidth) .def("set_height", &Primitive::setHeight) .def("set_x", &Primitive::setX) .def("set_y", &Primitive::setY) .def("set_top", &Primitive::setTop) .def("set_left", &Primitive::setLeft) .def("set_alpha", &Primitive::setAlpha) .def("set_position", &Primitive::setPosition) .def("set_rotation", &Primitive::setRotation) .def("set_scale", &Primitive::setScale) .def("set_window", &Primitive::setWindow) .def("set_stick", &Primitive::setStick) .def("set_image", &Primitive::setImage) .def("set_tex_center", &Primitive::setTexCenter) .def("set_tex_position", &Primitive::setTexPosition) .def("set_tex_scale", &Primitive::setTexScale) .def("set_tex_rotation", &Primitive::setTexRotation) .def("set_tex_x", &Primitive::setTexX) .def("set_tex_y", &Primitive::setTexY); class_<Sprite, bases<Primitive>, boost::shared_ptr<Sprite> >("Sprite") .def("__init__", make_constructor(&construct_simple<string,Sprite>)) .def("__init__", make_constructor(&construct<Image,Sprite>)) .def("crop", &Sprite::crop); class_<Window, bases<Observable>, boost::shared_ptr<Window> >("Window") .def("add_primitive", &Window::addPrimitive) .def("remove_primitive", &Window::removePrimitive) .def("get_primitives", &Window::getPrimitives) .def("get_window_height", &Window::getWindowHeight) .def("get_window_width", &Window::getWindowWidth) .def("get_pointer", &Window::getPointer) .def("get_fps", &Window::getFps) .def("set_fps", &Window::setFps) .def("set_pointer", &Window::setPointer) .def("set_pointer_x", &Window::setPointerX) .def("set_pointer_y", &Window::setPointerY); class_<Color, bases<Object>, boost::shared_ptr<Color> >("Color", init<unsigned long>()) .def("from_long", &Color::fromLong) .def("to_long", &Color::toLong) .def("set_red", &Color::setRed) .def("set_green", &Color::setGreen) .def("set_blue", &Color::setBlue) .def("set_alpha", &Color::setAlpha) .def("get_red", &Color::getRed) .def("get_green", &Color::getGreen) .def("get_blue", &Color::getBlue) .def("get_alpha", &Color::getAlpha); class_<Group, bases<Object>, boost::shared_ptr<Group> >("Group")// Transformable is essentially an interface...I don't believe I need to extend it for python? .def("add", &Group::add) .def("group_center", &Group::groupCenter) .def("boundaries", &Group::boundaries) .def("set_position", &Group::setPosition) .def("get_position", &Group::getPosition) .def("set_rotation", &Group::setRotation) .def("get_rotation", &Group::getRotation) .def("set_scale", &Group::setScale) .def("get_scale", &Group::getScale); class_<Image, bases<Object>, boost::shared_ptr<Image> >("Image", init<string>()) .def("pixel_at", &Image::pixelAt) .def("fill", &Image::fill) .def("set_pixel", &Image::setPixel) .def("copy_to", &Image::copyTo) .def("apply_alpha", &Image::applyAlpha) .def("get_bytes_per_pixel", &Image::getBytesPerPixel) .def("flip_y", &Image::flipY) .def("get_height", &Image::getHeight) .def("get_width", &Image::getWidth) .def("get_image_id", &Image::getImageId) .def("get_format", &Image::getFormat); } } /* namespace python */ } /* namespace fp_core */
39.287293
160
0.635213
[ "object" ]
546f38d97a010c74f07ee180c10494de499956a3
1,695
cc
C++
Calibration/EcalCalibAlgos/src/L3CalibBlock.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
Calibration/EcalCalibAlgos/src/L3CalibBlock.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
Calibration/EcalCalibAlgos/src/L3CalibBlock.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
/** */ #include "Calibration/EcalCalibAlgos/interface/L3CalibBlock.h" #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "TH1F.h" #include "TFile.h" // ----------------------------------------------------- L3CalibBlock::L3CalibBlock(const int numberOfElements, const int keventweight) : VEcalCalibBlock(numberOfElements), m_L3AlgoUniv(new MinL3AlgoUniv<unsigned int>(keventweight)) { reset(); } // ----------------------------------------------------- L3CalibBlock::~L3CalibBlock() { delete m_L3AlgoUniv; } // ----------------------------------------------------- void L3CalibBlock::Fill(std::map<int, double>::const_iterator MapBegin, std::map<int, double>::const_iterator MapEnd, double pTk, double pSubtract, double sigma) { // to feed the L3 algo std::vector<float> energy; std::vector<unsigned int> position; // loop over the energies map for (std::map<int, double>::const_iterator itMap = MapBegin; itMap != MapEnd; ++itMap) { // translation into vectors for the L3 algo position.push_back(itMap->first); energy.push_back(itMap->second); } // loop over the energies map m_L3AlgoUniv->addEvent(energy, position, pTk - pSubtract); return; } // ------------------------------------------------------------ int L3CalibBlock::solve(int usingBlockSolver, double min, double max) { m_coefficients = m_L3AlgoUniv->getSolution(); return 0; } // ------------------------------------------------------------ void L3CalibBlock::reset() { //PG FIXME could it be it is not wanted to be reset? m_L3AlgoUniv->resetSolution(); return; }
30.818182
102
0.560472
[ "vector" ]
5476d352d5c165f5526f6f0e9e42165d7d859b1f
14,813
cpp
C++
CppCollection/EXITJWV1.15.cpp
huoyongkai/Wireless360
20b458809b16aa05316cbbe98d2aebc10b4ba19f
[ "MIT" ]
1
2020-06-25T05:36:23.000Z
2020-06-25T05:36:23.000Z
CppCollection/EXITJWV1.15.cpp
huoyongkai/Wireless360
20b458809b16aa05316cbbe98d2aebc10b4ba19f
[ "MIT" ]
null
null
null
CppCollection/EXITJWV1.15.cpp
huoyongkai/Wireless360
20b458809b16aa05316cbbe98d2aebc10b4ba19f
[ "MIT" ]
null
null
null
/*! * \file * exit.cpp * \brief * Exit chart generation utilities * \note * Refer to exit.h for usage advice. * * Rob Maunder * rm02r@ecs.soton.ac.uk * October 2004 * * Revised by: $Author: jw02r $ (Jin Wang) * $Revision: 1.1.1.1 $ * $Date: 2006/11/17 18:04:56 $ * $Id: exit.cpp,v 1.1.1.1 2006/11/17 18:04:56 jw02r Exp $ * * Revised by Yongkai Huo. For better efficiency. June 21, 2010 */ #include "Headers.h" #include EXITJW_H #include <cmath> #include FileOper_H using namespace std; namespace comms_soton { /* const vec EXIT::default_sigma_A = "0 0.771376 1.1321 1.44287 1.74044 2.04354 \ 2.36894 2.73956 3.19956 3.87751 \ 3.97185 4.07508 4.18947 4.31828 4.46647 \ 4.64224 4.86067 5.15474 5.62597 10.35"; const vec EXIT::default_I_A = "0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 \ 0.91 0.92 0.93 0.94 0.95 0.96 0.97 0.98 0.99 1.0"; */ /* Joerg's original sigma vector "0.1, 0.2, 0.3, 0.4, 0.5, 0.7714, 1.1321, 1.4429, \ 1.7404,2.0435,2.3689, 2.7400, 3.1995, 3.8773, 4.5, 5.2, 6, 7, 8, 9, 10" */ /* // define static class members const vec EXIT::default_sigma_A = "0 0.1 0.3 0.5 0.771376 0.962142 1.1321 1.29066 \ 1.44287 1.59198 1.74044 1.89029 2.04354 2.20227 2.36894 2.54664 \ 2.73956 2.95389 3.19956 3.49451 3.87751 4.18947 4.46647 \ 4.64224 4.86067 5.15474 5.5 6 10.35"; const vec EXIT::default_I_A = "0 0.00180112 0.0160504 0.04373 0.1 0.15 0.2 0.25 \ 0.3 0.35 0.4 0.45 0.5 0.55 0.6 0.65 \ 0.7 0.75 0.8 0.85 0.9 0.93 0.95 \ 0.96 0.97 0.98 0.987901 0.994447 1"; */ const vec EXITJW::default_sigma_A = "0 0.1 0.5 0.771376 0.962142 1.1321 1.29066 \ 1.44287 1.59198 1.74044 1.89029 2.04354 2.20227 2.36894 2.54664 \ 2.73956 2.95389 3.19956 3.49451 3.87751 4.18947 4.46647 \ 4.64224 4.86067 5.15474 6 10.35"; const vec EXITJW::default_I_A = "0 0.00180112 0.04373 0.1 0.15 0.2 0.25 \ 0.3 0.35 0.4 0.45 0.5 0.55 0.6 0.65 \ 0.7 0.75 0.8 0.85 0.9 0.93 0.95 \ 0.96 0.97 0.98 0.994447 1"; const unsigned int EXITJW::extrinsic_xi_count = 10000; const double EXITJW::extrinsic_xi_lower = -500.0; const double EXITJW::extrinsic_xi_upper = 500.0; const unsigned int EXITJW::apriori_xi_count = 10000; EXITJW::EXITJW() { histograms[0].set_size(extrinsic_xi_count); histograms[1].set_size(extrinsic_xi_count); reset_histograms(); } EXITJW::~EXITJW() { } void EXITJW::reset_histograms(void) { histograms[0].zeros(); histograms[1].zeros(); } /* double EXIT::to_I_A(double sigma_A) { char function_name[] = "double EXIT::get_I_A(double sigma_A)"; double I_A; double xi; double xi_lower; double xi_upper; double xi_inter; unsigned int xi_index; if(sigma_A < 0){ cerr << "Error!" << endl; cerr << function_name << endl; cerr << "sigma_A{" << sigma_A << "} < 0.0" << endl; exit(1); } if(sigma_A == 0) return 0; if(sigma_A > 10.35) return 1.0; xi_lower = -10.0*sigma_A; xi_upper = 10.0*sigma_A; xi_inter = (xi_upper-xi_lower)/double(apriori_xi_count-1); I_A = 1.0; for(xi_index = 0; xi_index < apriori_xi_count; xi_index++){ xi = double(xi_index)*xi_inter + xi_lower; I_A -= (exp(-(sqr(xi-sqr(sigma_A)/2.0)/(2.0*sqr(sigma_A))))/(sqrt(2.0*pi)*sigma_A))* itpp::log2(1.0+exp(-xi))*xi_inter; } return I_A; } double EXIT::to_sigma_A(double I_A) { const double d_sigma_A = 0.00000005; const double threshold = 0.00000005; double sigma_A = 2.04354; // ==> I_A = 0.5 double I_A_1; double I_A_2; do{ I_A_1 = to_I_A(sigma_A-d_sigma_A/2.0); I_A_2 = to_I_A(sigma_A+d_sigma_A/2.0); sigma_A += (sqr(I_A_1) + 2.0*I_A*(I_A_2 - I_A_1) - sqr(I_A_2))/d_sigma_A; } while((I_A_1+I_A_2)/2.0 - I_A > threshold || I_A - (I_A_1+I_A_2)/2.0 > threshold); return sigma_A; } */ vec EXITJW::generate_apriori_LLRs(const bvec& data, double sigma_A) { return randn(data.size())*sigma_A - (to_vec(data)-0.5)*sqr(sigma_A); } void EXITJW::accumulate_histograms(const bvec& data,const vec& extrinsic_LLRs) { char function_name[] = "void EXIT::accumulate_histograms(data, extrinsic_LLRs)"; double xi_inter; int bit_index; unsigned int xi_index; unsigned int lower_xi_index; unsigned int upper_xi_index; if (data.size() != extrinsic_LLRs.size()) { cerr << "Error!" << endl; cerr << function_name << endl; cerr << "data.size(){" << data.size() << "} != extrinsic_LLRs.size(){"; cerr<< extrinsic_LLRs.size() << "}" << endl; exit(1); } xi_inter = (extrinsic_xi_upper-extrinsic_xi_lower)/double(extrinsic_xi_count-1); for (bit_index = 0; bit_index < extrinsic_LLRs.size(); bit_index++) { lower_xi_index = 0; upper_xi_index = extrinsic_xi_count-1; xi_index = (lower_xi_index+upper_xi_index)/2; double LLR = clip(extrinsic_LLRs[bit_index]); if (LLR < (double(xi_index)+0.5)*xi_inter + extrinsic_xi_lower) { upper_xi_index = xi_index; while (upper_xi_index != lower_xi_index) { xi_index = (lower_xi_index+upper_xi_index)/2; if (LLR < (double(xi_index)+0.5)*xi_inter + extrinsic_xi_lower) { upper_xi_index = xi_index; } else { lower_xi_index = xi_index+1; } } } else { lower_xi_index = xi_index+1; while (upper_xi_index != lower_xi_index) { xi_index = (lower_xi_index+upper_xi_index+1)/2; if (LLR >= (double(xi_index)-0.5)*xi_inter + extrinsic_xi_lower) { lower_xi_index = xi_index; } else { upper_xi_index = xi_index-1; } } } histograms[(int)data[bit_index]][upper_xi_index]++; } } void EXITJW::output_histograms(const char* filename0,const char* filename1) { char function_name[] = "void EXIT::output_histograms(char* filename0, char* filename1)"; double xi_inter; unsigned int bit_value; unsigned int xi_index; double xi; fstream fout[2]; vec d_histograms[2]; for (bit_value = 0; bit_value < 2; bit_value++) { if (sum(histograms[bit_value]) == 0) { cerr << "Error!" << endl; cerr << function_name << endl; cerr << "sum(histograms[" << bit_value << "]) == 0" << endl; exit(1); } } fout[0].open(filename0, ios::out | ios::trunc); fout[1].open(filename1, ios::out | ios::trunc); xi_inter = (extrinsic_xi_upper-extrinsic_xi_lower)/double(extrinsic_xi_count-1); for (bit_value = 0; bit_value < 2; bit_value++) { d_histograms[bit_value] = to_vec(histograms[bit_value])/(double(sum(histograms[bit_value]))*xi_inter); } for (bit_value = 0; bit_value < 2; bit_value++) { for (xi_index = 0; xi_index < extrinsic_xi_count; xi_index++) { xi = double(xi_index)*xi_inter + extrinsic_xi_lower; fout[bit_value] << xi << '\t' << d_histograms[bit_value][xi_index] << endl; } fout[bit_value].close(); } } double EXITJW::calculate_I_E(void) { char function_name[] = "double EXIT::get_I_E(void)"; double I_E; unsigned int bit_value; unsigned int xi_index; double xi_inter; vec d_histograms[2]; for (bit_value = 0; bit_value < 2; bit_value++) { if (sum(histograms[bit_value]) == 0) { cerr << "Error!" << endl; cerr << function_name << endl; cerr << "sum(histograms[" << bit_value << "]) == 0" << endl; //exit(1); throw("EXIT::calculate_I_E(void): error of histogram!"); } } xi_inter = (extrinsic_xi_upper-extrinsic_xi_lower)/double(extrinsic_xi_count-1); for (bit_value = 0; bit_value < 2; bit_value++) { d_histograms[bit_value] = to_vec(histograms[bit_value])/ (double(sum(histograms[bit_value]))*xi_inter); } I_E = 0.0; for (bit_value = 0; bit_value < 2; bit_value++) { for (xi_index = 0; xi_index < extrinsic_xi_count; xi_index++) { if (d_histograms[bit_value][xi_index] > 0.0) { I_E += d_histograms[bit_value][xi_index]* log2(2.0*d_histograms[bit_value][xi_index]/ (d_histograms[0][xi_index] + d_histograms[1][xi_index])) *xi_inter/2.0; } } } if (I_E>1.0) I_E=1.0; if (I_E<0) I_E=0; return I_E; } double EXITJW::calculate_I_E(const vec& extrinsic_LLRs) { int bit_index; double I_E; I_E = 0.0; for (bit_index = 0; bit_index < extrinsic_LLRs.size(); bit_index++) { double LLR = clip(extrinsic_LLRs[bit_index]); //make it more efficient here double tempExp=exp(LLR); I_E += (log2(2.0/(1.0+tempExp))/ (1.0+tempExp) + log2(2.0/(1.0+1/tempExp))/ (1.0+1/tempExp))/double(extrinsic_LLRs.size()); } if (I_E>1.0) I_E=1.0; if (I_E<0) I_E=0; return I_E; } // add correction term for non-uniform input (NI) double EXITJW::calculate_I_E_NI(const vec& extrinsic_LLRs, double H_b) { double I_E = calculate_I_E(extrinsic_LLRs) - (1.0-H_b); if (I_E>1.0) I_E=1.0; if (I_E<0) I_E=0; return I_E; } double EXITJW::calculate_coding_rate(const vec& I_A,const vec& I_E) { return (1.0-calculate_area(I_A, I_E)); } double EXITJW::calculate_area(const vec& I_A,const vec& I_E) { double area=0.0; for (int i=0; i<I_A.size()-1;i++) { area += (I_E(i)+I_E(i+1))*(I_A(i+1)-I_A(i))/2.0; } return area; } double EXITJW::clip(double x) { if (x>extrinsic_xi_upper) return extrinsic_xi_upper; else if (x<extrinsic_xi_lower) return extrinsic_xi_lower; else return x; } double EXITJW::predict_BER(double R, double EbN0, double I_A, double I_E) { return erfc(std::sqrt(8*R*EbN0 + std::pow(to_sigma_A(I_A), 2.0) + std::pow(to_sigma_A(I_E), 2.0))/(2*std::sqrt(2.0)))/2; } double EXITJW::J_Fredrick(double sigma) { double I; if (sigma>=10.0) return 1.0; else I=std::pow(1.0-std::pow(2.0, -0.3037*std::pow(sigma, 2*0.8935)), 1.1064); if (I>1.0) I=1.0; if (I<0) I=0; return I; } vec EXITJW::J_Fredrick(const vec& sigma) { vec I(sigma.size()); for (int i=0; i<sigma.size(); ++i) { I(i) = J_Fredrick(sigma(i)); } return I; } double EXITJW::J_inv_Fredrick(double I) { if (I>=1.0) // I should not be greater than 1.0 return 10.0; // INF, theoretically else return std::pow(-1.0/0.3037*std::log(1.0-std::pow(I, 1.0/1.1064))/std::log(2.0), 1.0/(2.0*0.8935)); } vec EXITJW::J_inv_Fredrick(const itpp::vec& I) { vec sigma(I.size()); for (int i=0; i<I.size(); ++i) { sigma[i] = J_inv_Fredrick(I(i)); } return sigma; } double EXITJW::SumMI(double _MI1, double _MI2) { return J_Fredrick(sqrt( pow(J_inv_Fredrick(_MI1),2)+pow(J_inv_Fredrick(_MI2),2))); } double EXITJW::BoxplusMI(double _MI1, double _MI2,const string& _LUTFile) { static bool inited=false; static mat table; static vec MIs("0:0.01:1"); if (!inited) { if (!p_fIO.Exist(_LUTFile)) throw("EXITJW::BoxplusMI: LUT file not found!"); mat tmp; ScanTable (_LUTFile.c_str(),1,tmp ); int len=itpp::round(sqrt(tmp.rows())); MIs=tmp.get_col(1)(0,len-1); p_cvt.Vec2Mat_rowise<double>(tmp.get_col(2),table,MIs.length(),MIs.length()); inited=true; } int s_1,e_1; BiSearch<double> ( MIs,_MI1,&s_1,&e_1 ); int s_2,e_2; BiSearch<double> ( MIs,_MI2,&s_2,&e_2 ); double finalMI; if ( s_1!=e_1&&s_2!=e_2 ) { //twp step linear-interpolation for two dimensional interpolation double mi_s=LinearInterpolate ( MIs ( s_1 ),table ( s_1,s_2 ), MIs ( e_1 ),table ( e_1,s_2 ), _MI1 ); double mi_e=LinearInterpolate ( MIs ( s_1 ),table ( s_1,e_2 ), MIs ( e_1 ),table ( e_1,e_2 ), _MI1); finalMI=LinearInterpolate ( MIs ( s_2 ),mi_s, MIs ( e_2 ),mi_e, _MI2 ); } else if ( s_1!=e_1 ) { finalMI=LinearInterpolate ( MIs ( s_1 ),table ( s_1,s_2 ), MIs ( e_1 ),table ( e_1,s_2 ), _MI1 ); } else if ( s_2!=e_2 ) { finalMI=LinearInterpolate ( MIs ( s_2 ),table ( s_1,s_2 ), MIs ( e_2 ),table ( s_1,s_2 ), _MI2 ); } else finalMI=table ( s_1,s_2 ); return finalMI; // return _MI1*_MI2;//worse than the lookup table } double EXITJW::MixLLRs(double _MI1, double _MI2, double _Percent_MI1) { double sigma1=to_sigma_A(_MI1); double C1=_Percent_MI1; double sigma2=to_sigma_A(_MI2); double C2=1-_Percent_MI1; double sigma3=sqrt(1.0/(C1/pow(sigma1,2)+C2/pow(sigma2,2))); return to_I_A(sigma3); } double EXITJW::J_Brink(double sigma) { double I; if (sigma>=10.0) return 1.0; else if (sigma>1.6363) { double tmp=0.00181491*pow(sigma,3)-0.142675*pow(sigma,2)-0.0822054*sigma+0.0549608; I=1-exp(tmp); } else I=-0.0421061*pow(sigma,3)+0.209252*pow(sigma,2)-0.00640081*sigma; if (I>1.0) I=1.0; if (I<0) I=0; return I; } double EXITJW::J_inv_Brink(double I) { double sigma; if (I>=1.0) // I should not be greater than 1.0 return 10.0; // INF, theoretically else if (I>0.3646) sigma=-0.706692*log(0.386013*(1-I))+1.75017*I; else sigma=1.09542*pow(I,2)+0.214217*I+2.33727*sqrt(I); // return std::pow(-1.0/0.3037*std::log(1.0-std::pow(I, 1.0/1.1064))/std::log(2.0), 1.0/(2.0*0.8935)); return sigma; } } // namespace comms_soton
30.668737
110
0.552218
[ "vector" ]
5488400048adec95fc9978676005b0e21405f101
1,148
hpp
C++
tests/unit_tests/framework/node_types_are.hpp
cpp-niel/mfl
d22d698b112b95d102150d5f3a5f35d8eb7fb0f3
[ "MIT" ]
4
2021-04-02T02:52:05.000Z
2021-12-11T00:42:35.000Z
tests/unit_tests/framework/node_types_are.hpp
cpp-niel/mfl
d22d698b112b95d102150d5f3a5f35d8eb7fb0f3
[ "MIT" ]
null
null
null
tests/unit_tests/framework/node_types_are.hpp
cpp-niel/mfl
d22d698b112b95d102150d5f3a5f35d8eb7fb0f3
[ "MIT" ]
null
null
null
#pragma once #include "node/node.hpp" #include <vector> namespace mfl { namespace detail { template <typename NodeTuple, size_t Index, typename N> bool node_type_is(const NodeTuple&, const std::vector<N>& nodes) { using type = std::tuple_element_t<Index, NodeTuple>; using expected_type = std::conditional_t<std::is_same_v<type, box>, wrapped_box, type>; return std::holds_alternative<expected_type>(nodes[Index]); } template <typename NodeTuple, size_t... Indices, typename N> bool node_types_are(const NodeTuple& t, const std::vector<N>& nodes, const std::index_sequence<Indices...>) { return (node_type_is<NodeTuple, Indices>(t, nodes) && ...); } } template <typename... NodeTypes, typename N> bool node_types_are(const std::vector<N>& nodes) { constexpr auto expected_num_nodes = sizeof...(NodeTypes); if (nodes.size() != expected_num_nodes) return false; return detail::node_types_are(std::tuple<NodeTypes...>{}, nodes, std::make_index_sequence<expected_num_nodes>()); } }
32.8
121
0.641115
[ "vector" ]
548b79278fdfcddc2abd2f2c23182310956ee5a0
5,857
cc
C++
asylo/util/status_helpers_test.cc
qinkunbao/asylo
6c6c4a185a1ee927996b43a060d924a49548d999
[ "Apache-2.0" ]
null
null
null
asylo/util/status_helpers_test.cc
qinkunbao/asylo
6c6c4a185a1ee927996b43a060d924a49548d999
[ "Apache-2.0" ]
null
null
null
asylo/util/status_helpers_test.cc
qinkunbao/asylo
6c6c4a185a1ee927996b43a060d924a49548d999
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2021 Asylo authors * * 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 "asylo/util/status_helpers.h" #include <string> #include <tuple> #include <utility> #include <vector> #include <google/protobuf/stubs/status.h> #include <gmock/gmock.h> #include <gtest/gtest.h> #include "absl/status/status.h" #include "absl/strings/string_view.h" #include "asylo/platform/primitives/sgx/sgx_error_space.h" #include "asylo/util/error_codes.h" #include "asylo/util/status.h" #include "include/grpcpp/support/status.h" #include "include/sgx_error.h" namespace asylo { namespace { using ::testing::Eq; using ::testing::HasSubstr; using ::testing::Test; using ::testing::Types; // The canonical code and error message that all test statuses used in // ConvertStatus() tests must have. constexpr error::GoogleError kCanonicalCode = error::GoogleError::RESOURCE_EXHAUSTED; constexpr absl::string_view kErrorMessage = "test error message"; // Provides test data and method access for different status types for // ConvertStatus() tests. Each implementation must have the following memebers: // // // Returns the error code of |status| in the canonical error space. // static int GetCanonicalCode(const StatusT &status) { ... } // // // Returns the error message of |status|. // static std::string GetErrorMessage(const StatusT &status) { ... } // // // Returns a vector of statuses that have canonical code and error // // message equal to kCanonicalCode and kErrorMessage, respectively. // static std::vector<StatusT> TestData() { ... } template <typename StatusT> struct StatusInfo; template <> struct StatusInfo<Status> { static int GetCanonicalCode(const Status &status) { return status.CanonicalCode(); } static std::string GetErrorMessage(const Status &status) { return std::string(status.error_message()); } static std::vector<Status> TestData() { return {Status(kCanonicalCode, kErrorMessage), Status(SGX_ERROR_OUT_OF_MEMORY, kErrorMessage)}; } }; template <> struct StatusInfo<absl::Status> { static int GetCanonicalCode(const absl::Status &status) { return static_cast<int>(status.code()); } static std::string GetErrorMessage(const absl::Status &status) { return std::string(status.message()); } static std::vector<absl::Status> TestData() { return {absl::ResourceExhaustedError(kErrorMessage)}; } }; template <> struct StatusInfo<grpc::Status> { static int GetCanonicalCode(const grpc::Status &status) { return static_cast<int>(status.error_code()); } static std::string GetErrorMessage(const grpc::Status &status) { return status.error_message(); } static std::vector<grpc::Status> TestData() { return {grpc::Status(grpc::StatusCode::RESOURCE_EXHAUSTED, std::string(kErrorMessage))}; } }; template <> struct StatusInfo<google::protobuf::util::Status> { static int GetCanonicalCode(const google::protobuf::util::Status &status) { return status.error_code(); } static std::string GetErrorMessage( const google::protobuf::util::Status &status) { return std::string(status.error_message()); } static std::vector<google::protobuf::util::Status> TestData() { return {google::protobuf::util::Status( google::protobuf::util::error::RESOURCE_EXHAUSTED, std::string(kErrorMessage))}; } }; // A test fixture for ConvertStatus() tests. StatusPairT must be of the form // std::pair<ToStatusType, FromStatusType>. template <typename StatusPairT> class ConvertStatusTest : public Test {}; // Converts a std::tuple<Ts...> to a Types<Ts...>. template <typename TupleT> struct TupleToTypes; template <typename... Ts> struct TupleToTypes<std::tuple<Ts...>> { using Types_ = Types<Ts...>; }; // Concatenates any number of lists of types represented as std::tuple<...> // types. template <typename... TupleTs> using TupleCat = decltype(std::tuple_cat(std::declval<TupleTs>()...)); // Provides an alias for a std::tuple<...> of std::pair<T, U>s for each U in Us. template <typename T, typename... Us> struct TypeSquareRow { using Row = std::tuple<std::pair<T, Us>...>; }; // Provides an alias for a std::tuple<...> of a std::pair<T, U> for each // (ordered) pair of types T, U in Ts. template <typename... Ts> struct TypeSquare { using Square = TupleCat<typename TypeSquareRow<Ts, Ts...>::Row...>; }; using StatusTypesSquare = TupleToTypes< TypeSquare<Status, absl::Status, grpc::Status, google::protobuf::util::Status>::Square>::Types_; TYPED_TEST_SUITE(ConvertStatusTest, StatusTypesSquare); TYPED_TEST(ConvertStatusTest, HasCorrectPropertiesAfterConversion) { using ToStatus = typename TypeParam::first_type; using FromStatus = typename TypeParam::second_type; using ToInfo = StatusInfo<ToStatus>; using FromInfo = StatusInfo<FromStatus>; for (const auto &from_status : FromInfo::TestData()) { ToStatus to_status = ConvertStatus<ToStatus>(from_status); EXPECT_THAT(ToInfo::GetCanonicalCode(to_status), Eq(kCanonicalCode)); // Use HasSubstr() instead of Eq() because Status::ToCanonical() adds error // space information to the error message. EXPECT_THAT(ToInfo::GetErrorMessage(to_status), HasSubstr(kErrorMessage)); } } } // namespace } // namespace asylo
32.005464
80
0.711969
[ "vector" ]
548cb7651f855595c95829a6e7e94da41cf70559
1,682
cpp
C++
ThunderSurge-core/game/MenuState.cpp
carsonclarke570/ThunderSurgeEngine
4214b39044f9c434f3769aec945fea9a7d63c8ae
[ "Apache-2.0" ]
null
null
null
ThunderSurge-core/game/MenuState.cpp
carsonclarke570/ThunderSurgeEngine
4214b39044f9c434f3769aec945fea9a7d63c8ae
[ "Apache-2.0" ]
null
null
null
ThunderSurge-core/game/MenuState.cpp
carsonclarke570/ThunderSurgeEngine
4214b39044f9c434f3769aec945fea9a7d63c8ae
[ "Apache-2.0" ]
null
null
null
#include "MenuState.h" #include "../daybreak/components/MeshRenderer.h" #include "../daybreak/components/Camera.h" #include "../daybreak/components/FreeLook.h" #include "../daybreak/components/FreeMove.h" using namespace daybreak; using namespace core; using namespace components; Scene* m_scene; GameObject* m_cube; GameObject* m_camera; GameObject* m_sprite; MenuState::MenuState() : GameState() { } void MenuState::init() { m_scene = new Scene(); // CAMERA m_camera = new GameObject(); m_camera->addComponent(new Camera(mat4::perspective(90.0f, 16.0f / 9.0f, 0.1, 1000.0f))); m_camera->addComponent(new FreeLook(10.0f)); //m_camera->addComponent(new FreeMove(1.0f)); m_camera->getTransform()->translate(vec3(0, 0, 1)); m_scene->addGameObject(m_camera); // CUBE m_cube = new GameObject(); m_cube->addComponent(new MeshRenderer(new Mesh("C:/Users/birdi/source/repos/DaybreakGameEngine/ThunderSurge-core/game/res/models/cube.obj"), new Material(Texture("C:/Users/birdi/source/repos/DaybreakGameEngine/ThunderSurge-core/game/res/textures/crate.jpg")))); m_scene->addGameObject(m_cube); // SPRITE /*m_sprite = new GameObject(); m_sprite->addComponent(new Sprite()); */ // LIGHTING BaseLight light; light.ambient = vec3(0.05f, 0.05f, 0.05f); light.diffuse = vec3(0.4f, 0.4f, 0.4f); light.specular = vec3(0.5f, 0.5f, 0.5f); Light* dir = new DirectionalLight(light, vec3(-0.2f, -1.0f, -0.3f)); m_scene->addLight(dir); } void MenuState::dispose() { delete m_scene; } void MenuState::update(float delta) { m_scene->update(delta); m_cube->getTransform()->rotate(delta * 20.0f, vec3(0, 1, 0)); } void MenuState::render() { m_scene->render(); }
25.484848
262
0.712842
[ "mesh", "render" ]
5492e3e9936950194eff17d5f9295924c7349104
416
cpp
C++
src/start/main.cpp
TheJelmega/engine
39778e153a3214fb54d7c88295289a5128cd248f
[ "0BSD" ]
3
2021-09-04T20:36:23.000Z
2022-01-20T14:16:43.000Z
src/start/main.cpp
TheJelmega/engine
39778e153a3214fb54d7c88295289a5128cd248f
[ "0BSD" ]
1
2021-11-02T23:26:26.000Z
2021-11-02T23:26:26.000Z
src/start/main.cpp
TheJelmega/engine
39778e153a3214fb54d7c88295289a5128cd248f
[ "0BSD" ]
null
null
null
#include <iostream> #include <vector> #include "core/Core.h" auto main(int argc, char* argv[]) -> int { Core::Alloc::Mallocator mallocator; Core::Alloc::BuddyAllocator alloc{ &mallocator, 256, 4 }; /*for (usize i = 256; i < 1024; i += 256) { auto mem = alloc.Allocate<u8>(i); alloc.Deallocate(StdMove(mem)); }*/ auto mem0 = alloc.Allocate<u8>(256); alloc.Deallocate(StdMove(mem0)); }
21.894737
59
0.629808
[ "vector" ]
5494fd6c8622dd5512396b8be84ba524929f0309
2,758
cpp
C++
src/CwshBlock.cpp
colinw7/Cwsh
f39e93ca48e92b14a55c1dce8c85b37843cff81e
[ "MIT" ]
1
2021-12-23T02:22:56.000Z
2021-12-23T02:22:56.000Z
src/CwshBlock.cpp
colinw7/Cwsh
f39e93ca48e92b14a55c1dce8c85b37843cff81e
[ "MIT" ]
null
null
null
src/CwshBlock.cpp
colinw7/Cwsh
f39e93ca48e92b14a55c1dce8c85b37843cff81e
[ "MIT" ]
null
null
null
#include <CwshI.h> CwshBlockMgr:: CwshBlockMgr(Cwsh *cwsh) : cwsh_(cwsh) { } CwshBlockMgr:: ~CwshBlockMgr() { for (auto &block : block_stack_) delete block; } CwshBlock * CwshBlockMgr:: startBlock(CwshBlockType type, const CwshLineArray &lines) { if (inBlock()) { block_stack_.push_back(current_block_); current_block_.release(); } current_block_ = new CwshBlock(type, lines); goto_depth_ = 0; return current_block_; } void CwshBlockMgr:: endBlock() { if (! inBlock()) CWSH_THROW("Not in block"); if (! block_stack_.empty()) { current_block_ = block_stack_.back(); block_stack_.pop_back(); } else current_block_ = nullptr; if (goto_depth_ > 1) --goto_depth_; } bool CwshBlockMgr:: inBlock() const { return current_block_; } bool CwshBlockMgr:: eof() const { if (! inBlock()) CWSH_THROW("Not in block"); return current_block_->eof(); } CwshLine CwshBlockMgr:: readLine() const { if (! inBlock()) CWSH_THROW("Not in block"); return current_block_->readLine(); } CwshBlock * CwshBlockMgr:: find(CwshBlockType type) { if (! inBlock()) return nullptr; if (current_block_->getType() == type) return current_block_; int num_blocks = block_stack_.size(); for (int i = num_blocks - 1; i >= 0; --i) { CwshBlock *block = block_stack_[i]; if (block->getType() == type) return block; } return nullptr; } void CwshBlockMgr:: gotoLabel(const std::string &label) { if (! inBlock()) CWSH_THROW("goto: Not in block."); goto_depth_ = 0; int line_num = current_block_->getLabelLineNum(label); if (line_num != -1) { current_block_->setLineNum(line_num); return; } int num_blocks = block_stack_.size(); for (int i = num_blocks - 1; i >= 0; i--) { CwshBlock *block = block_stack_[i]; int lineNum1 = block->getLabelLineNum(label); if (lineNum1 != -1) { block->setLineNum(lineNum1); goto_depth_ = i + 1; return; } } CWSH_THROW("goto: Label " + label + "not found."); } //---------------- CwshBlock:: CwshBlock(CwshBlockType type, const CwshLineArray &lines) : type_(type), lines_(lines) { } CwshBlock:: ~CwshBlock() { } CwshLine CwshBlock:: readLine() { if (eof()) CWSH_THROW("Block EOF"); return lines_[line_num_++]; } bool CwshBlock:: eof() const { return (line_num_ >= (int) lines_.size()); } int CwshBlock:: getLabelLineNum(const std::string &label) const { int num_lines = lines_.size(); for (int i = 0; i < num_lines; i++) { const CwshLine &line = lines_[i]; std::vector<std::string> words; CwshString::addWords(line.line, words); if (words.size() == 2 && words[1] == ":" && words[0] == label) return i; } return -1; }
14.827957
66
0.630892
[ "vector" ]
5496841fe84de6b203a5d176a16e9adea94a9d3e
6,116
cpp
C++
PersonModel.cpp
jeisonsantiago/Person-Model-Qt
c02251090ef1276c38c7aaf5236335b1e6bf740f
[ "MIT" ]
1
2022-02-14T08:57:46.000Z
2022-02-14T08:57:46.000Z
PersonModel.cpp
jeisonsantiago/Person-Model-Qt
c02251090ef1276c38c7aaf5236335b1e6bf740f
[ "MIT" ]
null
null
null
PersonModel.cpp
jeisonsantiago/Person-Model-Qt
c02251090ef1276c38c7aaf5236335b1e6bf740f
[ "MIT" ]
null
null
null
/******************************************************************************* * Project: Person Model Qt * Purpose: QAbstractListModel example * Author: Jeison Santiago, jeison.santiago@gmail.com * Language: C++ ******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2020 Jeison Santiago * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ #include "PersonModel.h" PersonModel::PersonModel(QObject *parent) : QAbstractListModel(parent) { } void PersonModel::addPerson(Person *person) { const int index = m_persons.size(); person->setParent(this); beginInsertRows(QModelIndex(),index,index); m_persons.append(person); endInsertRows(); } void PersonModel::addPerson() { Person *person = new Person("Added Person",45,this); this->addPerson(person); } void PersonModel::addPerson(const QString &name, const int &age) { Person *person = new Person(name,age,this); this->addPerson(person); } void PersonModel::removePerson(QModelIndex index) { beginRemoveRows(QModelIndex(),index.row(),index.row()); delete m_persons.takeAt(index.row()); endRemoveRows(); } int PersonModel::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return m_persons.size(); } QVariant PersonModel::data(const QModelIndex &index, int role) const { if (index.row() < 0 || index.row() >= m_persons.count()) return QVariant(); Person * person = m_persons[index.row()]; if(role == Qt::DisplayRole){ return person->name(); } if(role == Qt::ToolTipRole){ return person->name() + " age:" + QString::number(person->age()); } return QVariant(); } bool PersonModel::setData(const QModelIndex &index, const QVariant &value, int role) { if(!index.isValid()) { return false; } bool somethingChanged = false; switch (role) { case Qt::DisplayRole: { m_persons[index.row()]->setValues(value); somethingChanged = true; break; } } if(somethingChanged){ emit dataChanged(index,index); return true; } return false; } Qt::ItemFlags PersonModel::flags(const QModelIndex &index) const { if (!index.isValid()) { return QAbstractItemModel::flags(index) | Qt::ItemIsDropEnabled; } return QAbstractItemModel::flags(index) | Qt::ItemIsDragEnabled; } bool PersonModel::canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const { Q_UNUSED(action); Q_UNUSED(row); Q_UNUSED(parent); if (!data->hasFormat("material_data")) return false; if (column > 0) return false; return true; } bool PersonModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) { // simple work around for the drop "out side" of the drop indicator zone if(row == -1) row = rowCount(); if(data->hasFormat("material_data")){ if(parent.isValid()){ //Replace data this->insertRows(rowCount(),1,QModelIndex()); this->setData(index(rowCount()-1),data->data("material_data"),Qt::DisplayRole); } else{ //Add new data this->insertRows(row,1,QModelIndex()); this->setData(index(row),data->data("material_data"),Qt::DisplayRole); } return true; } return QAbstractListModel::dropMimeData(data,action,row,column,parent); } Qt::DropActions PersonModel::supportedDropActions() const { return Qt::MoveAction | Qt::CopyAction; } Qt::DropActions PersonModel::supportedDragActions() const { return Qt::MoveAction; } QStringList PersonModel::mimeTypes() const { return QAbstractListModel::mimeTypes() << "material_data"; } QMimeData *PersonModel::mimeData(const QModelIndexList &indexes) const { QMimeData * mimeData = QAbstractListModel::mimeData(indexes); QByteArray encodedData; QDataStream stream(&encodedData,QIODevice::WriteOnly); for( const QModelIndex & index : indexes){ if(index.isValid()){ stream << m_persons[index.row()]->getValues(); } } mimeData->setData("material_data",encodedData); return mimeData; } bool PersonModel::insertRows(int row, int count = 0, const QModelIndex &parent = QModelIndex()) { qDebug() << "insertRows()"; Q_UNUSED(parent); beginInsertRows(QModelIndex(), row, row+count-1); for (int i = 0; i < count; ++i) { m_persons.insert(row,new Person(this)); } endInsertRows(); return true; } bool PersonModel::removeRows(int row, int count, const QModelIndex &parent) { qDebug() << "removeRows()"; Q_UNUSED(parent); beginRemoveRows(QModelIndex(), row, row+count-1); for (int i = 0; i < count; ++i) { delete m_persons.takeAt(row); } endRemoveRows(); return true; }
27.674208
124
0.63947
[ "model" ]
5496f59fbee5dd13a2fb6c01857fd1b294551d51
6,866
cc
C++
vm_tools/garcon/mime_types_parser.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
vm_tools/garcon/mime_types_parser.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
vm_tools/garcon/mime_types_parser.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2018 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <utility> #include <arpa/inet.h> #include <base/check.h> #include <base/files/file_path.h> #include <base/files/file_util.h> #include <base/logging.h> #include <base/strings/string_split.h> #include <base/strings/string_tokenizer.h> #include <base/strings/string_util.h> #include <base/strings/utf_string_conversion_utils.h> #include "vm_tools/garcon/mime_types_parser.h" namespace { // Ridiculously large size for a /usr/share/mime/mime.cache file. // Default file is about 100KB, we will allow up to 10MB. constexpr size_t kMaxMimeTypesFileSize = 10485760; // Maximum number of nodes to allow in reverse suffix tree. // Default file has ~3K nodes, we will allow up to 30K. constexpr size_t kMaxNodes = 30000; // Maximum file extension size. constexpr size_t kMaxExtSize = 100; // Header size in mime.cache file. constexpr size_t kHeaderSize = 40; // Largest valid unicode code point is U+10ffff. constexpr uint32_t kMaxUnicode = 0x10ffff; // Read 4 bytes from string |buf| at |offset| as network order uint32_t. // Returns false if |offset > buf.size() - 4| or |offset| is not aligned to a // 4-byte word boundary, or |*result| is not between |min_result| and // |max_result|. |field_name| is used in error message. bool ReadInt(std::string buf, uint32_t offset, std::string field_name, uint32_t min_result, uint32_t max_result, uint32_t* result) { if (offset > buf.size() - 4 || (offset & 0x3)) { LOG(ERROR) << "Invalid offset=" << offset << " for " << field_name << ", string size=" << buf.size(); return false; } *result = ntohl(*reinterpret_cast<const uint32_t*>(buf.c_str() + offset)); if (*result < min_result || *result > max_result) { LOG(ERROR) << "Invalid " << field_name << "=" << *result << " not between min_result=" << min_result << " and max_result=" << max_result; return false; } return true; } } // namespace namespace vm_tools { namespace garcon { bool ParseMimeTypes(const std::string& file_name, MimeTypeMap* out_mime_types) { CHECK(out_mime_types); base::FilePath file_path(file_name); if (!base::PathExists(file_path)) { VLOG(1) << "MIME types file does not exist at: " << file_name; return false; } // File format from // https://specifications.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-0.21.html#idm46070612075440 // Header: // 2 CARD16 MAJOR_VERSION 1 // 2 CARD16 MINOR_VERSION 2 // 4 CARD32 ALIAS_LIST_OFFSET // 4 CARD32 PARENT_LIST_OFFSET // 4 CARD32 LITERAL_LIST_OFFSET // 4 CARD32 REVERSE_SUFFIX_TREE_OFFSET // ... // ReverseSuffixTree: // 4 CARD32 N_ROOTS // 4 CARD32 FIRST_ROOT_OFFSET // ReverseSuffixTreeNode: // 4 CARD32 CHARACTER // 4 CARD32 N_CHILDREN // 4 CARD32 FIRST_CHILD_OFFSET // ReverseSuffixTreeLeafNode: // 4 CARD32 0 // 4 CARD32 MIME_TYPE_OFFSET // 4 CARD32 WEIGHT in lower 8 bits // FLAGS in rest: // 0x100 = case-sensitive std::string buf; if (!base::ReadFileToStringWithMaxSize(file_path, &buf, kMaxMimeTypesFileSize)) { LOG(ERROR) << "Failed reading in mime.cache file: " << file_name; return false; } if (buf.size() < kHeaderSize) { LOG(ERROR) << "Invalid mime.cache file size=" << buf.size(); return false; } // Validate file[ALIAS_LIST_OFFSET - 1] is null to ensure that any // null-terminated strings we dereference at addresses below ALIAS_LIST_OFFSET // will not overflow. uint32_t alias_list_offset = 0; if (!ReadInt(buf, 4, "ALIAS_LIST_OFFSET", kHeaderSize, buf.size(), &alias_list_offset)) { return false; } if (buf[alias_list_offset - 1] != 0) { LOG(ERROR) << "Invalid mime.cache file does not contain null prior to " "ALIAS_LIST_OFFSET=" << alias_list_offset; return false; } // Parse ReverseSuffixTree. We will read all nodes and place them on |stack|, // allowing max of kMaxNodes and max extension of kMaxExtSize. uint32_t tree_offset = 0; if (!ReadInt(buf, 16, "REVERSE_SUFFIX_TREE_OFFSET", kHeaderSize, buf.size(), &tree_offset)) { return false; } struct Node { std::string ext; uint32_t n_children; uint32_t first_child_offset; }; // Read root node and put it on the stack. Node root; if (!ReadInt(buf, tree_offset, "N_ROOTS", 0, kMaxUnicode, &root.n_children)) { return false; } if (!ReadInt(buf, tree_offset + 4, "FIRST_ROOT_OFFSET", tree_offset, buf.size(), &root.first_child_offset)) { return false; } std::vector<Node> stack; stack.push_back(std::move(root)); uint32_t num_nodes = 0; while (stack.size() > 0) { // Pop top node from the stack and process children. Node n = stack.back(); stack.pop_back(); uint32_t p = n.first_child_offset; for (uint32_t i = 0; i < n.n_children; i++) { uint32_t c = 0; if (!ReadInt(buf, p, "CHARACTER", 0, kMaxUnicode, &c)) { return false; } p += 4; // Leaf node, add mime type. if (c == 0) { uint32_t mime_type_offset = 0; if (!ReadInt(buf, p, "mime type offset", kHeaderSize, alias_list_offset - 1, &mime_type_offset)) { return false; } p += 8; if (n.ext.size() == 0 || n.ext[0] != '.') { LOG(INFO) << "Ignoring extension without leading dot " << n.ext; } else { (*out_mime_types)[n.ext.substr(1)] = std::string(buf.c_str() + mime_type_offset); } continue; } // Regular node, parse and add it to the stack. Node node; base::WriteUnicodeCharacter(c, &node.ext); node.ext += n.ext; if (!ReadInt(buf, p, "N_CHILDREN", 0, kMaxUnicode, &node.n_children)) { return false; } p += 4; if (!ReadInt(buf, p, "FIRST_CHILD_OFFSET", tree_offset, buf.size(), &node.first_child_offset)) { return false; } p += 4; // Check limits. if (++num_nodes > kMaxNodes) { LOG(ERROR) << "Exceeded maxium number of nodes=" << kMaxNodes; return false; } if (node.ext.size() > kMaxExtSize) { LOG(WARNING) << "Ignoring large extension exceeds size=" << kMaxExtSize << " ext=" << node.ext; } else { stack.push_back(std::move(node)); } } } return true; } } // namespace garcon } // namespace vm_tools
32.540284
115
0.614477
[ "vector" ]
54a8b866ded41899d4025dc852298a7dc2c01d19
7,111
cpp
C++
src/msix/pack/ZipObjectWriter.cpp
bfourie/msix-packaging
c30aa5218cc7e2f80b96e27ee60c4eca8e3c2f0a
[ "MIT" ]
486
2018-03-07T17:15:03.000Z
2019-05-06T20:05:44.000Z
src/msix/pack/ZipObjectWriter.cpp
bfourie/msix-packaging
c30aa5218cc7e2f80b96e27ee60c4eca8e3c2f0a
[ "MIT" ]
172
2019-05-14T18:56:36.000Z
2022-03-30T16:35:24.000Z
src/msix/pack/ZipObjectWriter.cpp
bfourie/msix-packaging
c30aa5218cc7e2f80b96e27ee60c4eca8e3c2f0a
[ "MIT" ]
83
2019-05-29T18:38:36.000Z
2022-03-17T07:34:16.000Z
// // Copyright (C) 2019 Microsoft. All rights reserved. // See LICENSE file in the project root for full license information. // #include "ZipObjectWriter.hpp" #include "ZipObject.hpp" #include "MsixErrors.hpp" #include "Exceptions.hpp" #include "ZipFileStream.hpp" #include "DeflateStream.hpp" #include "StreamHelper.hpp" #include "Encoding.hpp" namespace MSIX { // We only use this for writting. If we ever decide to validate it, it needs to move to // ZipObject and ZipObjectReader must validate it class DataDescriptor final : public Meta::StructuredObject< Meta::Field4Bytes, // 0 - data descriptor header signature 4 bytes(0x08074b50) Meta::Field4Bytes, // 1 - crc -32 4 bytes Meta::Field8Bytes, // 2 - compressed size 8 bytes(zip64) Meta::Field8Bytes // 3 - uncompressed size 8 bytes(zip64) > { public: DataDescriptor(std::uint32_t crc, std::uint64_t compressSize, std::uint64_t uncompressSize) { Field<0>() = static_cast<std::uint32_t>(Signatures::DataDescriptor); Field<1>() = crc; Field<2>() = compressSize; Field<3>() = uncompressSize; } }; ZipObjectWriter::ZipObjectWriter(const ComPtr<IStream>& stream) : ZipObject(stream) { } // This is used for editing a package (aka signing) ZipObjectWriter::ZipObjectWriter(const ComPtr<IStorageObject>& storageObject) : ZipObject(storageObject) { // The storage object provided should had already initialize all the data. ThrowErrorIfNot(Error::Zip64EOCDRecord, m_endCentralDirectoryRecord.GetIsZip64(), "Editing non zip64 packages not supported"); // Move the stream at the start of central directory record so we can start overwritting. // Central directory data in already in m_centralDirectories. LARGE_INTEGER pos = {0}; pos.QuadPart = m_zip64EndOfCentralDirectory.GetOffsetStartOfCD(); ThrowHrIfFailed(m_stream->Seek(pos, StreamBase::Reference::START, nullptr)); } // IStorage std::vector<std::string> ZipObjectWriter::GetFileNames(FileNameOptions options) { // TODO: implement NOTIMPLEMENTED; } ComPtr<IStream> ZipObjectWriter::GetFile(const std::string& fileName) { // TODO: implement NOTIMPLEMENTED; } // IZipWriter std::pair<std::uint32_t, ComPtr<IStream>> ZipObjectWriter::PrepareToAddFile(const std::string& name, bool isCompressed) { ThrowErrorIf(Error::InvalidState, m_state != ZipObjectWriter::State::ReadyForLfhOrClose, "Invalid zip writer state"); auto result = m_centralDirectories.find(name); if (result != m_centralDirectories.end()) { auto message = "Adding duplicated file " + Encoding::DecodeFileName(name) + "to package"; ThrowErrorAndLog(Error::DuplicateFile, message.c_str()); } // Get position were the lfh is going to be written ULARGE_INTEGER pos = {0}; ThrowHrIfFailed(m_stream->Seek({0}, StreamBase::Reference::CURRENT, &pos)); // Write lfh LocalFileHeader lfh; lfh.SetData(name, isCompressed); lfh.WriteTo(m_stream); m_lastLFH = std::make_pair(static_cast<std::uint64_t>(pos.QuadPart), std::move(lfh)); m_state = ZipObjectWriter::State::ReadyForFile; ComPtr<IStream> zipStream = ComPtr<IStream>::Make<ZipFileStream>(name, isCompressed, m_stream.Get()); if (isCompressed) { zipStream = ComPtr<IStream>::Make<DeflateStream>(zipStream); } return std::make_pair(static_cast<std::uint32_t>(m_lastLFH.second.Size()), std::move(zipStream)); } void ZipObjectWriter::EndFile(std::uint32_t crc, std::uint64_t compressedSize, std::uint64_t uncompressedSize, bool forceDataDescriptor) { ThrowErrorIf(Error::InvalidState, m_state != ZipObjectWriter::State::ReadyForFile, "Invalid zip writer state"); if (forceDataDescriptor || compressedSize > MaxSizeToNotUseDataDescriptor || uncompressedSize > MaxSizeToNotUseDataDescriptor) { // Create and write data descriptor DataDescriptor descriptor = DataDescriptor(crc, compressedSize, uncompressedSize); descriptor.WriteTo(m_stream); } else { // The sizes can fit in the LFH, rewrite it with the new data Helper::StreamPositionReset resetAfterLFHWrite{ m_stream.Get() }; LARGE_INTEGER lfhLocation; lfhLocation.QuadPart = static_cast<LONGLONG>(m_lastLFH.first); ThrowHrIfFailed(m_stream->Seek(lfhLocation, StreamBase::Reference::START, nullptr)); // We cannot change the size of the LFH, ensure that we don't accidentally size_t currentSize = m_lastLFH.second.Size(); m_lastLFH.second.SetData(crc, compressedSize, uncompressedSize); ThrowErrorIf(Error::Unexpected, currentSize != m_lastLFH.second.Size(), "Cannot change the LFH size when updating it"); m_lastLFH.second.WriteTo(m_stream); } // Create and add cdh to map CentralDirectoryFileHeader cdh; cdh.SetData(m_lastLFH.second.GetFileName(), crc, compressedSize, uncompressedSize, m_lastLFH.first, m_lastLFH.second.GetCompressionMethod(), forceDataDescriptor); m_centralDirectories.insert(std::make_pair(m_lastLFH.second.GetFileName(), std::move(cdh))); m_state = ZipObjectWriter::State::ReadyForLfhOrClose; } void ZipObjectWriter::Close() { ThrowErrorIf(Error::InvalidState, m_state != ZipObjectWriter::State::ReadyForLfhOrClose, "Invalid zip writer state"); // Write central directories ULARGE_INTEGER startOfCdh = {0}; ThrowHrIfFailed(m_stream->Seek({0}, StreamBase::Reference::CURRENT, &startOfCdh)); std::size_t cdhsSize = 0; for (auto& cdh : m_centralDirectories) { cdhsSize += cdh.second.Size(); cdh.second.WriteTo(m_stream); } // Write zip64 end of cds ULARGE_INTEGER startOfZip64EndOfCds = {0}; ThrowHrIfFailed(m_stream->Seek({0}, StreamBase::Reference::CURRENT, &startOfZip64EndOfCds)); m_zip64EndOfCentralDirectory.SetData(m_centralDirectories.size(), static_cast<std::uint64_t>(cdhsSize), static_cast<std::uint64_t>(startOfCdh.QuadPart)); m_zip64EndOfCentralDirectory.WriteTo(m_stream); // Write zip64 locator m_zip64Locator.SetData(static_cast<std::uint64_t>(startOfZip64EndOfCds.QuadPart)); m_zip64Locator.WriteTo(m_stream); // Because we only use zip64, EndCentralDirectoryRecord never changes m_endCentralDirectoryRecord.WriteTo(m_stream); m_state = ZipObjectWriter::State::Closed; } }
42.837349
171
0.648713
[ "object", "vector" ]
54ae11d6d1435c5c1a4c93fdbe5c2709e544c760
3,034
cpp
C++
PRIMER/RSA.cpp
sonaspy/PAT-PTA
dc7d7c64e66a844cc199bfe845bc2873d4435732
[ "Unlicense" ]
1
2018-11-28T09:38:23.000Z
2018-11-28T09:38:23.000Z
PRIMER/RSA.cpp
NewGuonx/PAT-PTA
dc7d7c64e66a844cc199bfe845bc2873d4435732
[ "Unlicense" ]
null
null
null
PRIMER/RSA.cpp
NewGuonx/PAT-PTA
dc7d7c64e66a844cc199bfe845bc2873d4435732
[ "Unlicense" ]
null
null
null
// author -sonaspy@outlook.com // coding - utf_8 #include <bits/stdc++.h> #define test() freopen("in", "r", stdin) using namespace std; class Primes { public: vector<uint64_t> prime_numbers; Primes() { prime_generate(); } private: inline bool __isprime(uint64_t num) { if (num < 2 || (num != 2 && num % 2 == 0)) return false; uint64_t s = sqrt(num); for (uint64_t i = 3; i <= s; i += 2) if (num % i == 0) return false; return true; } void prime_generate() { int n = 2; for (uint64_t i = 0; i < 10000; i++) { while (!__isprime(n)) n++; this->prime_numbers.push_back(n); n++; } } } global_primes; class RSA { public: RSA() { __perpration(); } uint64_t classify(uint64_t m) { uint64_t Cypher = uint64_t(pow(m, this->__public_key)) % __n; return Cypher; } uint64_t declassify(uint64_t Cypher) { uint64_t m = uint64_t(pow(Cypher, this->__private_key)) % __n; return m; } private: uint64_t __public_key, __private_key, __n, __Fn; vector<uint64_t> *prime_numbers; inline uint64_t __GCD(uint64_t m, uint64_t n) { uint64_t r; while (n > 0) { r = m % n; m = n; n = r; } return m; } void __perpration() { prime_numbers = &global_primes.prime_numbers; uint64_t p, q, Fn, pub_key, pri_key, bound, n, c; // p = this->prime_numbers[rand() % 3]; // while ((q = this->prime_numbers[rand() % 3]) == p) // ; p = 3, q = 11; Fn = (p - 1) * (q - 1); n = p * q; bound = lower_bound(this->prime_numbers->begin(), this->prime_numbers->end(), Fn) - this->prime_numbers->begin(); c = 0; while (c < bound && __GCD(Fn, pub_key = (*(this->prime_numbers))[c++]) != 1) ; pri_key = 1; while ((((++pri_key * pub_key) % Fn != 1)) || pri_key == pub_key) ; cout << "p: " << p << " q: " << q << endl << "Fn: " << Fn << " -> " << " n: " << n << endl << "Public Key: " << pub_key << endl << "Private Key: " << pri_key << endl; cout << (pri_key * pub_key) % Fn << endl; this->__public_key = pub_key; this->__private_key = pri_key; this->__n = n; this->__Fn = Fn; } }; int main(int argc, char const *argv[]) { /* code */ //test(); srand(time(NULL)); int n = 10, x = 10; RSA demo; bool valid = true; while (x--) { while (n--) { uint64_t m = rand() % 1000 + 1; uint64_t c = demo.classify(m); if (!(demo.declassify(c) == m)) goto end; } n = 10; } end: cout << (valid ? "Valid" : "Non-Valid") << endl; return 0; }
22.308824
121
0.457482
[ "vector" ]
54b2444d702c44db8d229bccbeb3b189717146f5
2,875
cpp
C++
CPU_Renderer/Source/Mesh/Mesh.cpp
Thundersoft-Tech/GarajEngine
633de17ad79577f4306ea432f56f052c168e7a18
[ "MIT" ]
3
2021-08-18T12:13:32.000Z
2022-02-16T22:17:59.000Z
CPU_Renderer/Source/Mesh/Mesh.cpp
Thundersoft-Tech/GarajEngine
633de17ad79577f4306ea432f56f052c168e7a18
[ "MIT" ]
null
null
null
CPU_Renderer/Source/Mesh/Mesh.cpp
Thundersoft-Tech/GarajEngine
633de17ad79577f4306ea432f56f052c168e7a18
[ "MIT" ]
null
null
null
#include "Mesh.h" vec3_t cube_vertices[N_CUBE_VERTICES] = { { -1, -1, -1 }, // 1 { -1, 1, -1 }, // 2 { 1, 1, -1 }, // 3 { 1, -1, -1 }, // 4 { 1, 1, 1 }, // 5 { 1, -1, 1 }, // 6 { -1, 1, 1 }, // 7 { -1, -1, 1 }, // 8 }; face_t cube_faces[N_CUBE_FACES] = { // front { 1, 2, 3, { 0, 1 }, { 0, 0 }, { 1, 0 }, WHITE }, { 1, 3, 4, { 0, 1 }, { 1, 0 }, { 1, 1 }, WHITE }, // right { 4, 3, 5, { 0, 1 }, { 0, 0 }, { 1, 0 }, WHITE }, { 4, 5, 6, { 0, 1 }, { 1, 0 }, { 1, 1 }, WHITE }, // back { 6, 5, 7, { 0, 1 }, { 0, 0 }, { 1, 0 }, WHITE }, { 6, 7, 8, { 0, 1 }, { 1, 0 }, { 1, 1 }, WHITE }, // left { 8, 7, 2, { 0, 1 }, { 0, 0 }, { 1, 0 }, WHITE }, { 8, 2, 1, { 0, 1 }, { 1, 0 }, { 1, 1 }, WHITE }, // top { 2, 7, 5, { 0, 1 }, { 0, 0 }, { 1, 0 }, WHITE }, { 2, 5, 3, { 0, 1 }, { 1, 0 }, { 1, 1 }, WHITE }, // bottom { 6, 8, 1, { 0, 1 }, { 0, 0 }, { 1, 0 }, WHITE }, { 6, 1, 4, { 0, 1 }, { 1, 0 }, { 1, 1 }, WHITE }, }; mesh_t mesh; void load_cube_mesh_data() { for (int i = 0; i < N_CUBE_VERTICES; i++) { mesh.vertices.push_back(cube_vertices[i]); } for (int i = 0; i < N_CUBE_FACES; i++) { mesh.faces.push_back(cube_faces[i]); } mesh.scale = { 1, 1, 1 }; } void destroy_mesh() { mesh.faces.clear(); mesh.vertices.clear(); } bool load_obj_file(std::string file_name) { FILE* file; fopen_s(&file, file_name.c_str(), "r"); char line[32768]; std::vector<tex2_t> texcoords; while (fgets(line, 32768, file)) { // Vertex information if (strncmp(line, "v ", 2) == 0) { vec3_t vertex; sscanf_s(line, "v %f %f %f", &vertex.x, &vertex.y, &vertex.z); mesh.vertices.push_back(vertex); } // Texture coordinate information if (strncmp(line, "vt ", 3) == 0) { tex2_t texcoord; sscanf_s(line, "vt %f %f", &texcoord.u, &texcoord.v); texcoords.push_back(texcoord); } // Face information if (strncmp(line, "f ", 2) == 0) { int vertex_indices[3]; int texture_indices[3]; int normal_indices[3]; sscanf_s( line, "f %d/%d/%d %d/%d/%d %d/%d/%d", &vertex_indices[0], &texture_indices[0], &normal_indices[0], &vertex_indices[1], &texture_indices[1], &normal_indices[1], &vertex_indices[2], &texture_indices[2], &normal_indices[2] ); face_t face; face.a = vertex_indices[0]; face.b = vertex_indices[1]; face.c = vertex_indices[2]; if (texcoords.size() > (texture_indices[0] - 1)) face.a_uv = texcoords[texture_indices[0] - 1]; if (texcoords.size() > (texture_indices[1] - 1)) face.b_uv = texcoords[texture_indices[1] - 1]; if (texcoords.size() > (texture_indices[2] - 1)) face.c_uv = texcoords[texture_indices[2] - 1]; face.color = WHITE; mesh.faces.push_back(face); } } mesh.scale = { 1, 1, 1 }; std::cout << "Faces = " << mesh.faces.size() << std::endl; std::cout << "Vertices = " << mesh.vertices.size() << std::endl; return true; }
27.644231
65
0.522783
[ "mesh", "vector" ]
2a67323c23dacea0667ba75576852770acefe048
1,153
cpp
C++
statistics/tests/cache.cpp
5r1gsOi1/other
16da2846da4f80cdbccf0232696301c50c10c005
[ "MIT" ]
null
null
null
statistics/tests/cache.cpp
5r1gsOi1/other
16da2846da4f80cdbccf0232696301c50c10c005
[ "MIT" ]
null
null
null
statistics/tests/cache.cpp
5r1gsOi1/other
16da2846da4f80cdbccf0232696301c50c10c005
[ "MIT" ]
null
null
null
#include "statistics/cache.h" #include <vector> #include "common/simple_date.h" #include "common/tests.h" /* bool Test_CacheIndex_Simple() { const std::string file_name = "fake file name"; { volatile std::ofstream vvv(file_name); } CacheIndex<WikiPageDateTimestamp> index(file_name); index.Add(WikiPageDateTimestamp{"name", Date{2012, 10, 1}}); index.Add(WikiPageDateTimestamp{"name2", Date{2012, 10, 1}}); index.Add(WikiPageDateTimestamp{"name3", Date{2012, 10, 1}}); index.Add(WikiPageDateTimestamp{"name", Date{2012, 10, 1}}); index.Add(WikiPageDateTimestamp{"name5", Date{2012, 10, 1}}); index.Add(WikiPageDateTimestamp{"name5", Date{2012, 10, 1}}); index.Add(WikiPageDateTimestamp{"name", Date{2012, 10, 1}}); auto found = index.Get([](const WikiPageDateTimestamp& element) { return element.name == "name"; }); for (auto& i : found) { std::cout << i.name << " == " << i.date << std::endl; } return true; } bool Test_CacheIndex() { TEST_START; CALL_AND_PRINT(Test_CacheIndex_Simple); TEST_END; } */ bool Test_All() { TEST_START; //CALL_AND_PRINT(Test_CacheIndex); TEST_END; } MAIN_TEST(Test_All)
28.825
67
0.690373
[ "vector" ]
2a67c3bcb7a070d81208f4f90ab1e6dc267d6728
9,838
hpp
C++
include/geometry/polygon.hpp
waterben/LineExtraction
d247de45417a1512a3bf5d0ffcd630d40ffb8798
[ "MIT" ]
1
2020-06-12T13:30:56.000Z
2020-06-12T13:30:56.000Z
include/geometry/polygon.hpp
waterben/LineExtraction
d247de45417a1512a3bf5d0ffcd630d40ffb8798
[ "MIT" ]
null
null
null
include/geometry/polygon.hpp
waterben/LineExtraction
d247de45417a1512a3bf5d0ffcd630d40ffb8798
[ "MIT" ]
null
null
null
/*M/////////////////////////////////////////////////////////////////////////////////////// // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2008-2011, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // // C by Benjamin Wassermann //M*/ #ifndef _GEOMETRY_POLYGON_HPP_ #define _GEOMETRY_POLYGON_HPP_ #ifdef __cplusplus #include <vector> #include "line.hpp" #include <opencv2/imgproc/imgproc.hpp> namespace lsfm { //! Polygon object template<class FT, template<class> class PT = Vec2> class Polygon { PT<FT> piviot_; std::vector<PT<FT>> verticies_; public: typedef FT float_type; typedef PT<FT> point_type; typedef std::vector<point_type> VertexVector; Polygon(const point_type &piviot = point_type(0,0)) : piviot_(piviot) {} inline VertexVector& verticies() { return verticies_; } inline const VertexVector& verticies() const { return verticies_; } inline LineSegment2Vector<FT,PT> edges() const { LineSegment2Vector<FT, PT> ret; if (verticies_.size() == 2) ret.push_back(LineSegment2<FT, PT>(verticies_[0], verticies_[1])); else if (verticies_.size() > 2) { ret.reserve(verticies_.size()); size_t i = 0; for (; i != verticies_.size()-1; ++i) ret.push_back(LineSegment2<FT, PT>(verticies_[i], verticies_[i+1])); ret.push_back(LineSegment2<FT, PT>(verticies_[i], verticies_[0])); } return ret; } inline VertexVector wolrdVerticies() const { VertexVector ret; ret.reserve(verticies_.size()); for_each(verticies_.begin(), verticies_.end(), [&,this](point_type &p) { ret.push_back(p + this->piviot_); }); return ret; } inline LineSegment2Vector<FT, PT> worldEdges() const { LineSegment2Vector<FT, PT> ret; if (verticies_.size() == 2) ret.push_back(LineSegment2<FT, PT>(verticies_[0] + piviot_, verticies_[1] + piviot_)); else if (verticies_.size() > 2) { VertexVector tmp = wolrdVerticies(); ret.reserve(tmp.size()); size_t i = 0; for (; i != tmp.size() - 1; ++i) ret.push_back(LineSegment2<FT, PT>(tmp[i], tmp[i + 1])); ret.push_back(LineSegment2<FT, PT>(tmp[i], tmp[0])); } return ret; } inline void clear() const { verticies_.clear(); } inline void push_back(const point_type& vertex) { verticies_.push_back(vertex); } inline void push_back_world(const point_type& vertex) { verticies_.push_back(vertex - piviot_); } inline bool empty() const { verticies_.empty(); } inline size_t size() const { verticies_.size(); } //! translate polygon inline void translate(const point_type &t) { piviot_ += t; } //! rotate shape by angle (radian) around piviot inline void rotate(FT angle) { FT sa = sin(angle), ca = cos(angle); for_each(verticies_.begin(), verticies_.end(), [&](point_type &p) { set(p, getX(p) * ca - getY(p) * sa, getX(p) * sa + getY(p) * ca); }); } //! rotate shape by angle (radian) around o inline void rotate(FT angle, const point_type &o) { FT sa = sin(angle), ca = cos(angle); point_type t = piviot_ - o; for_each(verticies_.begin(), verticies_.end(), [&](point_type &p) { p += t; set(p, getX(p) * ca - getY(p) * sa, getX(p) * sa + getY(p) * ca); p -= t; }); } //! scale shape at piviot virtual void scale(FT s) { for_each(verticies_.begin(), verticies_.end(), [&,this](point_type &p) { p *= s; }); } //! scale shape at o virtual void scale(FT s, const point_type &o) { point_type t = piviot_ - o; for_each(verticies_.begin(), verticies_.end(), [&, this](point_type &p) { p += t; p *= s; p -= t; }); } inline point_type& piviot() { return piviot_; } inline const point_type& piviot() const { return piviot_; } //! translate polygon inline void translatePiviot(const point_type &t) { for_each(verticies_.begin(), verticies_.end(), [&](point_type &p) { p -= t; }); piviot_ += t; } inline void fill(cv::Mat& img, const cv::Scalar &color, int lineType = 8) const { std::vector<cv::Point> in; in.reserve(verticies_.size()); point_type tmp; for_each(verticies_.begin(), verticies_.end(), [&,this](const point_type &p) { tmp = p + this->piviot_; in.push_back(cv::Point(std::round(getX(tmp)), std::round(getY(tmp)))); }); cv::fillConvexPoly(img, in.data(), static_cast<int>(verticies_.size()), color, lineType); } inline void fillComplex(cv::Mat& img, const cv::Scalar &color, int lineType = 8) const { std::vector<cv::Point> in; in.reserve(verticies_.size()); point_type tmp; for_each(verticies_.begin(), verticies_.end(), [&,this](const point_type &p) { tmp = p + this->piviot_; in.push_back(cv::Point(std::round(getX(tmp)), std::round(getY(tmp)))); }); int np = static_cast<int>(verticies_.size()); const cv::Point *data = in.data(); cv::fillPoly(img, &data, &np, 1, color, lineType); } inline void draw(cv::Mat& img, const cv::Scalar &color, int thickness = 1, int lineType = 8) const { std::vector<cv::Point> in; in.reserve(verticies_.size()); point_type tmp; for_each(verticies_.begin(), verticies_.end(), [&,this](const point_type &p) { tmp = p + this->piviot_; in.push_back(cv::Point(std::round(getX(tmp)), std::round(getY(tmp)))); }); int np = static_cast<int>(verticies_.size()); const cv::Point *data = in.data(); cv::polylines(img, &data, &np, 1, true, color, thickness, lineType); } inline bool isConvex() const { if (verticies_.size() < 3) return false; point_type p1 = verticies_[0], p2 = verticies_[1], p3 = verticies_[2], d = p2-p1; size_t s = verticies_.size(); FT res = getX(p3) * getY(d) - getY(p3) * getX(d) + getX(d) * getY(p1) - getY(d) * getX(p1); for (size_t i = 1; i < s; ++i) { p1 = p2; p2 = p3; p3 = verticies_[(i + 2) % s]; d = p2-p1; FT newres = getX(p3) * getY(d) - getY(p3) * getX(d) + getX(d) * getY(p1) - getY(d) * getX(p1); if ((newres > 0 && res < 0) || (newres < 0 && res > 0)) return false; } return true; } }; template<class FT, template<class> class PT = Vec2> using PolygonVector = std::vector<Polygon<FT, PT>>; } #endif #endif
37.984556
111
0.534458
[ "object", "shape", "vector" ]
2a69f1c10398ae715c481eb5267832b2943b678b
27,363
cpp
C++
src/virtual_db_rocks.cpp
keenbo/wwsearch
5c5f5c5deac1820c6bc6ef96e8163c583cf57641
[ "CC-BY-3.0" ]
465
2019-11-18T07:00:58.000Z
2022-03-30T07:13:36.000Z
src/virtual_db_rocks.cpp
Jie-Yuan/wwsearch
5c5f5c5deac1820c6bc6ef96e8163c583cf57641
[ "CC-BY-3.0" ]
7
2019-11-20T03:53:00.000Z
2021-01-01T02:35:46.000Z
src/virtual_db_rocks.cpp
Jie-Yuan/wwsearch
5c5f5c5deac1820c6bc6ef96e8163c583cf57641
[ "CC-BY-3.0" ]
77
2019-11-18T07:05:52.000Z
2022-02-11T08:01:24.000Z
/* * Tencent is pleased to support the open source community by making wwsearch * available. * * Copyright (C) 2018-present Tencent. 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 * * https://opensource.org/licenses/Apache-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 OF ANY KIND, either express or implied. See the License for the * specific language governing permissions and limitations under the License. */ #include "virtual_db_rocks.h" #include "codec_doclist_impl.h" #include "index_config.h" #include "iterator_rocks.h" #include "logger.h" #include "write_buffer_rocks.h" #include <memory> #include "codec_doclist_impl.h" #include "rocksdb/db.h" #include "rocksdb/memtablerep.h" #include "rocksdb/options.h" #include "rocksdb/slice.h" #include "rocksdb/table.h" #include "rocksdb/utilities/db_ttl.h" namespace wwsearch { namespace merge { using namespace wwsearch; typedef struct HeapItem { DocList* ptr_; size_t left_size_; uint32_t priority_; inline void Set(DocList* ptr, size_t size, uint32_t priority) { // version update char* pc = (char*)ptr; pc += sizeof(DocListHeader); ptr_ = (DocList*)pc; left_size_ = size - sizeof(DocListHeader); priority_ = priority; } inline void Swap(HeapItem& o) { DocList* t2 = o.ptr_; o.ptr_ = ptr_; ptr_ = t2; left_size_ ^= o.left_size_; o.left_size_ ^= left_size_; left_size_ ^= o.left_size_; priority_ ^= o.priority_; o.priority_ ^= priority_; priority_ ^= o.priority_; } } HeapItem; #define MergeOperator_LOCKS_SIZE (1000) #define MergeOperator_HEAP_SIZE (1000) #define DOCID(a) ((a).left_size_ == 0 ? 0 : (a).ptr_->doc_id_) #define HeapItemGreater(a, b) \ ((DOCID(a) > DOCID(b)) || (DOCID(a) == DOCID(b) && a.priority_ > b.priority_)) class OptimizeMerger { public: std::atomic<std::uint64_t> seq_; std::mutex locks_[MergeOperator_LOCKS_SIZE]; merge::HeapItem* heaps_[MergeOperator_LOCKS_SIZE]; uint32_t max_doc_list_num_; public: OptimizeMerger(uint32_t max_doc_list_num) : max_doc_list_num_(max_doc_list_num) { assert(max_doc_list_num_ > 0); for (size_t i = 0; i < MergeOperator_LOCKS_SIZE; i++) { std::lock_guard<std::mutex> guard(locks_[i]); heaps_[i] = new merge::HeapItem[MergeOperator_HEAP_SIZE]; } } virtual ~OptimizeMerger() { for (size_t i = 0; i < MergeOperator_LOCKS_SIZE; i++) { std::lock_guard<std::mutex> guard(locks_[i]); if (heaps_[i] != nullptr) delete heaps_[i]; heaps_[i] = nullptr; } } inline void HeapShiftUp(HeapItem* items, size_t size, size_t pos) { while (pos != 0) { size_t parent = (pos - 1) / 2; if (HeapItemGreater(items[pos], items[parent])) { items[pos].Swap(items[parent]); pos = parent; } else { break; } } } inline void HeapShiftDown(HeapItem* items, size_t size, size_t pos) { for (;;) { size_t left = pos * 2 + 1; size_t right = pos * 2 + 2; if (right < size) { if (HeapItemGreater(items[left], items[right])) { // 1. left big if (HeapItemGreater(items[left], items[pos])) { // 1.1 left biggest items[left].Swap(items[pos]); pos = left; } else { break; } } else if (HeapItemGreater(items[right], items[pos])) { // 2. right biggest items[right].Swap(items[pos]); pos = right; } else { // 3. pos biggest break; } } else if (left < size) { // 1. left biggest if (HeapItemGreater(items[left], items[pos])) { items[left].Swap(items[pos]); pos = left; } else { // 2. pos biggest break; } } else { // 1. pos biggest,reach tail break; } } } inline bool OptimizeDocListMerge(Codec* codec, std::string* new_value, HeapItem* items, size_t queue_size, size_t approximate_size, bool purge_deletedoc) { #define ONE_DOCID_SIZE (9) assert(sizeof(DocList) == ONE_DOCID_SIZE); DocumentID doc_id; // build heap for (uint32_t j = 0; j < queue_size; j++) { HeapShiftUp(items, queue_size, j); } uint64_t match_doc_count = 0; uint64_t match_delete_doc_count = 0; DocListWriterCodec* writer = codec->NewOrderDocListWriterCodec(); // Attention: // Even if the total size of doc list reach max doc list count,we can not // delete tail's delete id in PartialMerge. But we can do that in FullMerge. while (DOCID(items[0]) != 0) { DocList* doc = items[0].ptr_; if (purge_deletedoc) { // full merge // if reach max ,just break if (items[0].ptr_->doc_state_ != kDocumentStateDelete) { writer->AddDocID(doc->doc_id_, doc->doc_state_); // new_value->append((const char*)items[0].ptr_, ONE_DOCID_SIZE); match_doc_count++; if (match_doc_count >= this->max_doc_list_num_) { SearchLogError("MatchDocCount reach max limit=%lu", this->max_doc_list_num_); break; } } } else { // partial merge // keep max num undelete doc id and all delete doc id if (items[0].ptr_->doc_state_ != kDocumentStateDelete) { if (match_doc_count < this->max_doc_list_num_) { writer->AddDocID(doc->doc_id_, doc->doc_state_); // new_value->append((const char*)items[0].ptr_, ONE_DOCID_SIZE); match_doc_count++; } } else { writer->AddDocID(doc->doc_id_, doc->doc_state_); // new_value->append((const char*)items[0].ptr_, ONE_DOCID_SIZE); match_delete_doc_count++; // protect our system? if (match_delete_doc_count > 10000000) { SearchLogError("too many delete doc id keep"); break; } } } doc_id = DOCID(items[0]); // skip same doc_id do { items[0].ptr_++; items[0].left_size_ -= ONE_DOCID_SIZE; HeapShiftDown(items, queue_size, 0); } while (DOCID(items[0]) == doc_id); } bool ret = writer->SerializeToBytes(*new_value, 0); codec->ReleaseOrderDocListWriterCodec(writer); SearchLogDebug("new_value len:%u", new_value->size()) return ret; } }; } // namespace merge static bool FastMerge(const rocksdb::Slice* existing_value, const std::deque<std::string>& operand_list, std::string* new_value) { if (existing_value != NULL && existing_value != nullptr) new_value->assign(existing_value->data(), existing_value->size()); for (size_t i = 0; i < operand_list.size(); i++) { new_value->append(operand_list[i]); } if (new_value->size() > 10000000) { new_value->resize(10000000); } return true; } DocListMergeOperator::~DocListMergeOperator() { if (nullptr != merger_) delete merger_; merger_ = nullptr; } // merger's life cycle manage by DocListMergeOperator // DocListMergeOperator life cycle manage by outside shared_ptr DocListMergeOperator* DocListMergeOperator::NewInstance(VDBParams* params) { merge::OptimizeMerger* merger = new merge::OptimizeMerger(params->max_doc_list_num_); DocListMergeOperator* instance = new DocListMergeOperator(params->codec_, merger); return instance; } bool DocListMergeOperator::FullMergeV2( const rocksdb::MergeOperator::MergeOperationInput& merge_in, rocksdb::MergeOperator::MergeOperationOutput* merge_out) const { SearchLogDebug("new value size:%u", merge_out->new_value.size()); // collect buffer std::vector<std::pair<merge::DocList*, size_t>> doc_lists; std::vector<std::string> alloc_buffer; if (merge_in.existing_value) { doc_lists.push_back(DecodeDocList(alloc_buffer, merge_in.existing_value->data(), merge_in.existing_value->size())); } for (size_t i = 0, length = merge_in.operand_list.size(); i < length; i++) { doc_lists.push_back(DecodeDocList(alloc_buffer, merge_in.operand_list[i].data(), merge_in.operand_list[i].size())); SearchLogDebug("in doclist size:%u", merge_in.operand_list[i].size()) } // must clear the value. merge_out->new_value.clear(); // init head and merge bool ret = DoMerge(&(merge_out->new_value), doc_lists, true); SearchLogDebug("ret:%d size:%u", ret, alloc_buffer.size()); return ret; } bool DocListMergeOperator::PartialMergeMulti( const rocksdb::Slice& key, const std::deque<rocksdb::Slice>& operand_list, std::string* new_value, rocksdb::Logger* logger) const { SearchLogDebug("new value size:%u", new_value->size()); // assert(new_value->size() == 0); new_value->clear(); // collect buffer std::vector<std::pair<merge::DocList*, size_t>> doc_lists; std::vector<std::string> alloc_buffer; for (size_t i = 0, length = operand_list.size(); i < length; i++) { doc_lists.push_back(DecodeDocList(alloc_buffer, operand_list[i].data(), operand_list[i].size())); SearchLogDebug("in doclist size:%u", operand_list[i].size()) } // init head and merge bool ret = DoMerge(new_value, doc_lists, false); SearchLogDebug("ret:%d size:%u", ret, alloc_buffer.size()); return ret; } // Decode [data] to FixDocList,If alloc string,string will store to // alloc_buffer. std::pair<merge::DocList*, size_t> DocListMergeOperator::DecodeDocList( std::vector<std::string>& alloc_buffer, const char* data, size_t data_len) const { assert(data_len < (static_cast<uint32_t>(1) << 31)); bool ret; bool use_buffer; std::string buffer; ret = codec_->DecodeDocListToFixBytes(data, data_len, use_buffer, buffer); if (!ret) { SearchLogError("DecodeDocList fail,Data Broken or Bug ?"); assert(false); } std::pair<merge::DocList*, size_t> one_list; if (use_buffer) { alloc_buffer.push_back(std::move(buffer)); one_list.first = (merge::DocList*)alloc_buffer.back().c_str(); one_list.second = alloc_buffer.back().size(); } else { one_list.first = (merge::DocList*)data; one_list.second = data_len; } return one_list; } bool DocListMergeOperator::DoMerge( std::string* new_value, std::vector<std::pair<merge::DocList*, size_t>>& doc_lists, bool full_merge) const { size_t list_size = doc_lists.size(); size_t approximate_size = 0; bool ret; if (list_size < MergeOperator_HEAP_SIZE) { std::uint64_t pos = merger_->seq_.fetch_add(1, std::memory_order_relaxed) % MergeOperator_LOCKS_SIZE; std::lock_guard<std::mutex> lock_guard(merger_->locks_[pos]); merge::HeapItem* heap = merger_->heaps_[pos]; for (size_t i = 0; i < list_size; i++) { heap[i].Set((merge::DocList*)doc_lists[i].first, doc_lists[i].second, i); SearchLogDebug("in doclist size:%u", doc_lists[i].second); approximate_size += doc_lists[i].second; } // 1/3 compression ? approximate_size /= 3; ret = merger_->OptimizeDocListMerge(codec_, new_value, heap, list_size, approximate_size, full_merge); } else { // WTF,why so big SearchLogError("too many list to merge:%u", list_size); merge::HeapItem* heap = new merge::HeapItem[list_size]; for (size_t i = 0; i < list_size; i++) { heap[i].Set((merge::DocList*)doc_lists[i].first, doc_lists[i].second, i); SearchLogDebug("in doclist size:%u", doc_lists[i].second); approximate_size += doc_lists[i].second; } // 1/3 compression ? approximate_size /= 3; ret = merger_->OptimizeDocListMerge(codec_, new_value, heap, list_size, approximate_size, full_merge); delete heap; } return ret; } bool DocListMergeOperator::FullMerge( const rocksdb::Slice& key, const rocksdb::Slice* existing_value, const std::deque<std::string>& operand_list, std::string* new_value, rocksdb::Logger* logger) const { // deprecated assert(false); #ifdef BENCHMARK return FastMerge(existing_value, operand_list, new_value); #else SearchLogDebug(""); std::vector<DocListReaderCodec*> priority_queue; for (size_t i = 0; i < operand_list.size(); i++) { const std::string& value = operand_list[i]; DocListReaderCodec* item = codec_->NewDocListReaderCodec(value.c_str(), value.size()); item->SetPriority(i); priority_queue.push_back(item); } bool ok = DocListMerge(priority_queue, new_value, logger, true); if (!ok) { SearchLogError("DocListMerge fail"); assert(false); } for (auto item : priority_queue) { codec_->ReleaseDocListReaderCodec(item); } return true; #endif } bool DocListMergeOperator::PartialMerge(const rocksdb::Slice& key, const rocksdb::Slice& left_operand, const rocksdb::Slice& right_operand, std::string* new_value, rocksdb::Logger* logger) const { // deprecated assert(false); #ifdef BENCHMARK new_value->append(left_operand.data(), left_operand.size()); new_value->append(right_operand.data(), right_operand.size()); if (new_value->size() > 10000000) { new_value->resize(10000000); } return true; #else SearchLogDebug(""); // Optimize, only do partial merge while operand is big. std::vector<DocListReaderCodec*> priority_queue; { DocListReaderCodec* item = codec_->NewDocListReaderCodec(left_operand.data(), left_operand.size()); item->SetPriority(0); priority_queue.push_back(item); } { DocListReaderCodec* item = codec_->NewDocListReaderCodec( right_operand.data(), right_operand.size()); item->SetPriority(1); priority_queue.push_back(item); } bool ok = DocListMerge(priority_queue, new_value, logger, false); if (!ok) { SearchLogError("DocListMerge fail"); assert(false); } for (auto item : priority_queue) { codec_->ReleaseDocListReaderCodec(item); } return true; #endif } bool DocListMergeOperator::DocListMerge(std::vector<DocListReaderCodec*>& items, std::string* new_value, rocksdb::Logger* logger, bool purge_deleted) const { SearchLogDebug(""); assert(false); DocListWriterCodec* writer = codec_->NewOrderDocListWriterCodec(); // DocListOrderWriterCodecImpl writer(new_value); std::make_heap(items.begin(), items.end(), codec_->GetGreaterComparator()); for (;;) { std::pop_heap(items.begin(), items.end(), codec_->GetGreaterComparator()); DocListReaderCodec* back = items.back(); DocumentID last_document_id = back->DocID(); if (last_document_id == DocIdSetIterator::NO_MORE_DOCS) break; if (back->State() == kDocumentStateDelete && purge_deleted) { // delete doc SearchLogDebug("delete doc[%lu]", last_document_id); } else { writer->AddDocID(back->DocID(), back->State()); SearchLogDebug("merge doc[%lu]", last_document_id); } items.back()->NextDoc(); // skip same doc for (;;) { std::push_heap(items.begin(), items.end(), codec_->GetGreaterComparator()); if (items.back()->DocID() == last_document_id) { std::pop_heap(items.begin(), items.end(), codec_->GetGreaterComparator()); items.back()->NextDoc(); SearchLogDebug("skip same doc[%lu]", last_document_id); } else { break; } } } assert(writer->SerializeToBytes(*new_value, 0)); codec_->ReleaseOrderDocListWriterCodec(writer); return true; } // rocksdb must have default column. So: // default -> kStoredFieldColumn static std::string column_family_mapping[kMaxColumn] = {"default", "kInvertedIndexColumn", "kDocValueColumn", "kMetaColumn", "kDictionaryColumn", "kPaxosLogColumn", "kPaxosDataMetaColumn", "kPaxosLogMetaColumn"}; VirtualDBRocksImpl::VirtualDBRocksImpl( VDBParams* params, const std::shared_ptr<DbRocksWriteQueue>& write_queue) : params_(params), db_(nullptr), merger_(nullptr), write_queue_(write_queue) {} VirtualDBRocksImpl::~VirtualDBRocksImpl() { Clear(); } bool VirtualDBRocksImpl::Open() { if (nullptr != this->db_) { SearchLogError("DB had opened"); this->SetState("DB had opened!"); return false; } InitDBOptions(); std::vector<int32_t> ttls; column_families_.clear(); // Couldn't use HashSkipListRepFactory for some unknown bug if (options_.allow_concurrent_memtable_write == false) { options_.prefix_extractor.reset(rocksdb::NewFixedPrefixTransform(9)); options_.memtable_factory.reset(rocksdb::NewHashSkipListRepFactory()); } // options_.disable_auto_compactions = true; for (int i = 0; i < kMaxColumn; i++) { rocksdb::ColumnFamilyOptions cf_options = NewColumnFamilyOptions(options_, (StorageColumnType)i); column_families_.push_back( rocksdb::ColumnFamilyDescriptor(column_family_mapping[i], cf_options)); /* if (i == kPaxosLogColumn) { ttls.push_back(this->params_->plog_ttl_seconds_); // in seconds. } else { ttls.push_back(-1); // infinite seconds. } */ } rocksdb::Status s = rocksdb::DB::Open(this->options_, this->params_->path, column_families_, &(this->column_famil_handles_), &this->db_); // ttl open // auto s = rocksdb::DBWithTTL::Open( // this->options_, this->params_->path, column_families, // &(this->column_famil_handles_), &this->db_, ttls, false); if (!s.ok()) { SearchLogError("DB open failed %s", s.getState()); this->SetState(s.getState()); return false; } return true; } std::vector<rocksdb::ColumnFamilyHandle*>& VirtualDBRocksImpl::ColumnFamilyHandle() { return this->column_famil_handles_; } VirtualDBSnapshot* VirtualDBRocksImpl::NewSnapshot() { const rocksdb::Snapshot* snapshot = this->db_->GetSnapshot(); assert(snapshot != nullptr); return new VirtualDBRocksSnapshot(snapshot); } void VirtualDBRocksImpl::ReleaseSnapshot(VirtualDBSnapshot* snapshot) { VirtualDBRocksSnapshot* real_snapshot = reinterpret_cast<VirtualDBRocksSnapshot*>(snapshot); this->db_->ReleaseSnapshot(real_snapshot->GetSnapshot()); delete snapshot; } SearchStatus VirtualDBRocksImpl::FlushBuffer(WriteBuffer* write_buffer) { SearchStatus status; if (!write_queue_) { WriteBufferRocksImpl* buffer = reinterpret_cast<WriteBufferRocksImpl*>(write_buffer); auto s = this->db_->Write(rocksdb::WriteOptions(), buffer->write_batch_); if (!s.ok()) { status.SetStatus(kRocksDBErrorStatus, s.getState()); } } else { VirtualDBRocksWriteOption write_options; status = write_queue_->Write(this, &write_options, write_buffer); } return status; } WriteBuffer* VirtualDBRocksImpl::NewWriteBuffer( const std::string* write_buffer) { return new WriteBufferRocksImpl(&column_famil_handles_, NULL, write_buffer); } void VirtualDBRocksImpl::ReleaseWriteBuffer(WriteBuffer* buffer) { delete buffer; } SearchStatus VirtualDBRocksImpl::Get(StorageColumnType column, const std::string& key, std::string& value, VirtualDBSnapshot* snapshot) { rocksdb::Status ss; rocksdb::ReadOptions read_option; if (nullptr != snapshot) { VirtualDBRocksSnapshot* real_snapshot = reinterpret_cast<VirtualDBRocksSnapshot*>(snapshot); read_option.snapshot = real_snapshot->GetSnapshot(); } ss = this->db_->Get(read_option, this->column_famil_handles_[column], key, &value); SearchStatus status; if (ss.ok()) { status.SetStatus(kOK, ""); } else if (ss.IsNotFound()) { status.SetStatus(kDocumentNotExistStatus, ""); } else { status.SetStatus(kRocksDBErrorStatus, ss.getState()); } return status; } void VirtualDBRocksImpl::MultiGet(std::vector<StorageColumnType> columns, std::vector<std::string>& keys, std::vector<std::string>& values, std::vector<SearchStatus>& status, VirtualDBSnapshot* snapshot) { std::vector<rocksdb::ColumnFamilyHandle*> handles; std::vector<rocksdb::Slice> slice_keys; assert(keys.size() == columns.size()); for (size_t i = 0; i < columns.size(); i++) { handles.push_back(this->column_famil_handles_[columns[i]]); slice_keys.push_back(keys[i]); } std::vector<rocksdb::Status> ss; rocksdb::ReadOptions read_option; if (nullptr != snapshot) { VirtualDBRocksSnapshot* real_snapshot = reinterpret_cast<VirtualDBRocksSnapshot*>(snapshot); read_option.snapshot = real_snapshot->GetSnapshot(); } ss = this->db_->MultiGet(read_option, handles, slice_keys, &values); assert(ss.size() == keys.size()); for (rocksdb::Status s : ss) { SearchLogDebug("rocksdb status[%s]", s.getState()); SearchStatus temp; if (s.ok()) { temp.SetStatus(kOK, ""); } else if (s.IsNotFound()) { temp.SetStatus(kDocumentNotExistStatus, ""); } else { temp.SetStatus(kRocksDBErrorStatus, s.getState()); } status.push_back(temp); } } void VirtualDBRocksImpl::InitDBOptions() { // options_.IncreaseParallelism(); options_.OptimizeLevelStyleCompaction(); options_.create_if_missing = true; options_.create_missing_column_families = true; // file size options_.max_subcompactions = params_->rocks_max_subcompactions; // If use HashSkipListMemtable wouldn't support concurrent_memtable_write options_.allow_concurrent_memtable_write = params_->rocks_allow_concurrent_memtable_write; // log settings options_.max_log_file_size = params_->rocks_max_log_file_size; // 50MB options_.log_file_time_to_roll = params_->rocks_log_file_time_to_roll; // one hours options_.keep_log_file_num = params_->rocks_keep_log_file_num; // 10 days // manifest options_.max_manifest_file_size = params_->rocks_max_manifest_file_size; // 50MB // write options_.level0_file_num_compaction_trigger = params_->rocks_level0_file_num_compaction_trigger; options_.level0_slowdown_writes_trigger = params_->rocks_level0_slowdown_writes_trigger; options_.level0_stop_writes_trigger = params_->rocks_level0_stop_writes_trigger; options_.num_levels = params_->rocks_num_levels; options_.write_buffer_size = params_->rocks_write_buffer_size; options_.max_write_buffer_number = params_->rocks_max_write_buffer_number; // 3 write buffer options_.max_total_wal_size = params_->rocks_max_total_wal_size; // 200 MB options_.db_write_buffer_size = params_->rocks_db_write_buffer_size; // 200 MB options_.max_bytes_for_level_base = params_->rocks_max_bytes_for_level_base; // options_.max_bytes_for_level_multiplier = 10; // *10 // options_.wal_bytes_per_sync = params_->rocks_20 << 20; // 2MB sync once ? // options_.bytes_per_sync = 20 << 20; // Doesn't need anymore if use write_queue for colib // options_.enable_write_thread_adaptive_yield = false; // options_.write_thread_max_yield_usec = 0; // options_.write_thread_slow_yield_usec = 0; options_.max_background_jobs = params_->rocks_max_background_jobs_; // table cache block cache { rocksdb::BlockBasedTableOptions table_options; if (params_->rocks_db_block_cache_bytes != 0) { table_options.block_cache = rocksdb::NewLRUCache(params_->rocks_db_block_cache_bytes); } table_options.cache_index_and_filter_blocks = params_->rocks_db_cache_index_and_filter_blocks; if (params_->rocks_db_max_open_files != 0) { options_.max_open_files = params_->rocks_db_max_open_files; } options_.table_factory.reset(NewBlockBasedTableFactory(table_options)); } // compression options_.compression = params_->rocks_compression; // Open all staticstic info for DB options_.statistics = rocksdb::CreateDBStatistics(); } rocksdb::ColumnFamilyOptions VirtualDBRocksImpl::NewColumnFamilyOptions( const rocksdb::Options& options, StorageColumnType column) { rocksdb::ColumnFamilyOptions cf_options(options); switch (column) { case kInvertedIndexColumn: assert(merger_ == nullptr); merger_ = DocListMergeOperator::NewInstance(this->params_); cf_options.merge_operator.reset(merger_); break; default: break; } auto it = this->params_->columns_compactionfilter.find(column); if (it != this->params_->columns_compactionfilter.end()) { cf_options.compaction_filter = it->second; } return cf_options; } Iterator* VirtualDBRocksImpl::NewIterator(StorageColumnType column, VirtualDBReadOption* options) { VirtualDBRocksSnapshot* snapshot = (VirtualDBRocksSnapshot*)options->snapshot_; rocksdb::ReadOptions rocks_options; if (nullptr != snapshot) { rocks_options.snapshot = snapshot->GetSnapshot(); } if (column >= this->column_famil_handles_.size()) return nullptr; auto rocks_iterator = this->db_->NewIterator( rocks_options, this->column_famil_handles_[column]); if (nullptr == rocks_iterator) return nullptr; return new IteratorRocks(rocks_iterator); } SearchStatus VirtualDBRocksImpl::CompactRange(StorageColumnType column, const std::string& begin, const std::string& end) { SearchStatus status; rocksdb::ColumnFamilyHandle* cf_handle = this->column_famil_handles_[column]; rocksdb::CompactRangeOptions options; rocksdb::Slice begin_slice(begin); rocksdb::Slice end_slice(end); rocksdb::Status rocksdb_s = this->db_->CompactRange(options, cf_handle, &begin_slice, &end_slice); if (!rocksdb_s.ok()) { status.SetStatus(kRocksDBErrorStatus, rocksdb_s.getState()); } return status; } SearchStatus VirtualDBRocksImpl::DropDB() { Clear(); SearchStatus status; // auto ret = this->db_->DropColumnFamilies(this->column_famil_handles_); // status.SetStatus(ret.code(), ret.getState()); auto ss = rocksdb::DestroyDB(this->params_->path, this->options_); status.SetStatus(ss.code(), ""); return status; } } // namespace wwsearch
33.991304
80
0.649563
[ "vector" ]
2a6ee201d2c4777a4bdbce8dc91e42e7054b925a
4,685
cpp
C++
ofSketchApp/src/AddonManager.cpp
brannondorsey/ofSketch
304f4a6eec010a1f479d64c8bf7f78e7ee5f4769
[ "MIT" ]
1
2015-06-09T12:10:44.000Z
2015-06-09T12:10:44.000Z
ofSketchApp/src/AddonManager.cpp
brannondorsey/ofSketch
304f4a6eec010a1f479d64c8bf7f78e7ee5f4769
[ "MIT" ]
null
null
null
ofSketchApp/src/AddonManager.cpp
brannondorsey/ofSketch
304f4a6eec010a1f479d64c8bf7f78e7ee5f4769
[ "MIT" ]
null
null
null
// ============================================================================= // // Copyright (c) 2013 Christopher Baker <http://christopherbaker.net> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // // ============================================================================= #include "AddonManager.h" namespace of { namespace Sketch { const std::string AddonManager::DEFAULT_ADDON_PATH = "addons/"; AddonManager::AddonManager(const std::string& path): _path(path) { Poco::Path fullPath(ofToDataPath(_path, true)); Poco::File file(fullPath); if (!file.exists()) { Poco::FileNotFoundException exc(fullPath.toString()); throw exc; } std::vector<Poco::File> files; ofx::IO::DirectoryUtils::list(file, files, true, &_directoryFilter); std::vector<Poco::File>::iterator iter = files.begin(); while (iter != files.end()) { std::string addonPath = (*iter).path(); std::string addonName = Poco::Path(addonPath).getBaseName(); Poco::RegularExpression addonExpression("ofx.+$", Poco::RegularExpression::RE_ANCHORED); if (addonExpression.match(addonName)) { _addons[addonName] = Addon::SharedPtr(new Addon(addonName, addonPath)); } ++iter; } _addonWatcher.registerAllEvents(this); _addonWatcher.addPath(fullPath.toString(), false, true, &_directoryFilter); } AddonManager::~AddonManager() { _addonWatcher.unregisterAllEvents(this); } void AddonManager::onDirectoryWatcherItemAdded(const ofx::DirectoryWatcher::DirectoryEvent& evt) { ofLogNotice("AddonManager::onDirectoryWatcherItemAdded") << evt.event << " " << evt.item.path(); std::string path = evt.item.path(); std::string name = Poco::Path(path).getBaseName(); _addons[name] = Addon::SharedPtr(new Addon(name, path)); } void AddonManager::onDirectoryWatcherItemRemoved(const ofx::DirectoryWatcher::DirectoryEvent& evt) { ofLogNotice("AddonManager::onDirectoryWatcherItemRemoved") << evt.event << " " << evt.item.path(); std::string path = evt.item.path(); std::string name = Poco::Path(path).getBaseName(); std::map<std::string, Addon::SharedPtr>::iterator iter = _addons.find(name); if (iter != _addons.end()) { _addons.erase(iter); } else { ofLogError("AddonManager::onDirectoryWatcherItemRemoved") << "Unable to find " << path; } } void AddonManager::onDirectoryWatcherItemModified(const ofx::DirectoryWatcher::DirectoryEvent& evt) { ofLogNotice("AddonManager::onDirectoryWatcherItemModified") << evt.event << " " << evt.item.path(); } void AddonManager::onDirectoryWatcherItemMovedFrom(const ofx::DirectoryWatcher::DirectoryEvent& evt) { ofLogNotice("AddonManager::onDirectoryWatcherItemMovedFrom") << evt.event << " " << evt.item.path(); } void AddonManager::onDirectoryWatcherItemMovedTo(const ofx::DirectoryWatcher::DirectoryEvent& evt) { ofLogNotice("AddonManager::onDirectoryWatcherItemMovedTo") << evt.event << " " << evt.item.path(); } void AddonManager::onDirectoryWatcherError(const Poco::Exception& exc) { ofLogError("AddonManager::onDirectoryWatcherError") << exc.displayText(); } std::vector<Addon::SharedPtr> AddonManager::getAddons() const { std::vector<Addon::SharedPtr> addons; std::map<std::string, Addon::SharedPtr>::const_iterator iter = _addons.begin(); while (iter != _addons.end()) { addons.push_back(iter->second); ++iter; } return addons; } } } // namespace of::Sketch
29.840764
104
0.662967
[ "vector" ]
2a6fd3ec35cb7892c1fd2cd83f7f65276356c97f
589
cpp
C++
c++/leetcode/0049-Group_Anagrams-M.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
1
2020-03-02T10:56:22.000Z
2020-03-02T10:56:22.000Z
c++/leetcode/0049-Group_Anagrams-M.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
null
null
null
c++/leetcode/0049-Group_Anagrams-M.cpp
levendlee/leetcode
35e274cb4046f6ec7112cd56babd8fb7d437b844
[ "Apache-2.0" ]
null
null
null
// 49 Group Anagrams // https://leetcode.com/problems/group-anagrams // version: 1; create time: 2020-01-04 17:05:56; class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { unordered_map<string, vector<string>> groups; for (const auto& str : strs) { auto tmp = str; std::sort(tmp.begin(), tmp.end()); groups[tmp].push_back(str); } vector<vector<string>> res; for (const auto& p : groups) { res.push_back(std::move(p.second)); } return res; } };
28.047619
64
0.565365
[ "vector" ]
2a7128b56a26f95ab60471d575c1e4477eff7845
8,183
cc
C++
test/ParserNargs.cc
m-mizutani/argparse-cpp
585c0d89e8448c09f290048f80e442d512015d57
[ "BSD-2-Clause" ]
3
2017-07-09T20:23:29.000Z
2020-06-09T08:57:04.000Z
test/ParserNargs.cc
m-mizutani/argparse-cpp
585c0d89e8448c09f290048f80e442d512015d57
[ "BSD-2-Clause" ]
2
2016-05-07T03:16:04.000Z
2018-04-10T20:52:36.000Z
test/ParserNargs.cc
m-mizutani/argparse-cpp
585c0d89e8448c09f290048f80e442d512015d57
[ "BSD-2-Clause" ]
2
2018-04-10T20:49:05.000Z
2020-02-08T04:14:39.000Z
/* * Copyright 2016, Masayoshi Mizutani, mizutani@sfc.wide.ad.jp * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <vector> #include <string> #include "./gtest.h" #include "../argparse.hpp" class ParserNargsNumber : public ::testing::Test { public: argparse::Parser *psr; argparse::Argument *arg; virtual void SetUp() { psr = new argparse::Parser("test"); arg = &(psr->add_argument("-a").nargs(2)); psr->add_argument("-b"); } virtual void TearDown() { delete psr; } }; TEST_F(ParserNargsNumber, ok1) { argparse::Argv seq = {"./test", "-a", "v1", "v2"}; argparse::Values val = psr->parse_args(seq); EXPECT_TRUE(val.is_set("a")); EXPECT_EQ(2, val.size("a")); EXPECT_EQ("v1", val.get("a", 0)); EXPECT_EQ("v2", val.get("a", 1)); } TEST_F(ParserNargsNumber, ng1_too_many_arg) { argparse::Argv seq = {"./test", "-a", "v1", "v2", "v3"}; EXPECT_THROW(psr->parse_args(seq), argparse::exception::ParseError); } TEST_F(ParserNargsNumber, ng2_not_enough_arg) { argparse::Argv seq = {"./test", "-a", "v1"}; EXPECT_THROW(psr->parse_args(seq), argparse::exception::ParseError); } class ParserNargsAsterisk : public ::testing::Test { public: argparse::Parser *psr; argparse::Argument *arg; virtual void SetUp() { psr = new argparse::Parser("test"); arg = &(psr->add_argument("-a").nargs("*")); psr->add_argument("-b"); } virtual void TearDown() { delete psr; } }; TEST_F(ParserNargsAsterisk, no_option) { argparse::Argv ok1 = {"./test"}; argparse::Values v1 = psr->parse_args(ok1); EXPECT_FALSE(v1.is_set("a")); } TEST_F(ParserNargsAsterisk, ok1) { argparse::Argv ok1 = {"./test", "-a", "v1", "v2"}; argparse::Values v1 = psr->parse_args(ok1); EXPECT_EQ(2, v1.size("a")); EXPECT_EQ("v1", v1.get("a", 0)); EXPECT_EQ("v2", v1.get("a", 1)); } TEST_F(ParserNargsAsterisk, ok2) { // Stop parsing by an other option. argparse::Argv ok2 = {"./test", "-a", "v1", "v2", "-b", "r1"}; argparse::Values v2 = psr->parse_args(ok2); EXPECT_EQ(2, v2.size("a")); EXPECT_EQ("v1", v2.get("a", 0)); EXPECT_EQ("v2", v2.get("a", 1)); EXPECT_EQ(1, v2.size("b")); EXPECT_EQ("r1", v2.get("b")); } TEST_F(ParserNargsAsterisk, ok3) { // No option value. argparse::Argv ok3 = {"./test", "-a", "-b", "r1"}; argparse::Values v3 = psr->parse_args(ok3); EXPECT_EQ(0, v3.size("a")); EXPECT_TRUE(v3.is_set("a")); EXPECT_EQ(1, v3.size("b")); EXPECT_EQ("r1", v3.get("b")); } class ParserNargsQuestion : public ::testing::Test { public: argparse::Parser *psr; argparse::Argument *arg; virtual void SetUp() { psr = new argparse::Parser("test"); arg = &(psr->add_argument("-a").nargs("?")); // 0 or 1 value psr->add_argument("-b"); } virtual void TearDown() { delete psr; } }; TEST_F(ParserNargsQuestion, ok0) { argparse::Argv seq = {"./test"}; argparse::Values v = psr->parse_args(seq); EXPECT_FALSE(v.is_set("a")); EXPECT_EQ(0, v.size("a")); EXPECT_FALSE(v.is_set("b")); } TEST_F(ParserNargsQuestion, ok1) { argparse::Argv seq = {"./test", "-a"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); EXPECT_FALSE(v.is_set("b")); } TEST_F(ParserNargsQuestion, ok2) { argparse::Argv seq = {"./test", "-a", "v1"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); EXPECT_EQ("v1", v["a"]); EXPECT_FALSE(v.is_set("b")); } TEST_F(ParserNargsQuestion, ok3) { argparse::Argv seq = {"./test", "-a", "v1", "-b", "r1"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); EXPECT_EQ("v1", v["a"]); EXPECT_TRUE(v.is_set("b")); } TEST_F(ParserNargsQuestion, with_default1) { arg->set_default("d"); argparse::Argv seq = {"./test", "-a"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); } TEST_F(ParserNargsQuestion, with_default2) { arg->set_default("d"); argparse::Argv seq = {"./test"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); EXPECT_EQ("d", v["a"]); } TEST_F(ParserNargsQuestion, with_const) { arg->set_const("c"); argparse::Argv seq = {"./test", "-a"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); EXPECT_EQ("c", v["a"]); } TEST_F(ParserNargsQuestion, with_default_and_const) { arg->set_const("c").set_default("d"); argparse::Argv seq = {"./test", "-a"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); // 'const' has priority over 'default' EXPECT_EQ("c", v["a"]); } class ParserNargsPlus : public ::testing::Test { public: argparse::Parser *psr; argparse::Argument *arg; virtual void SetUp() { psr = new argparse::Parser("test"); arg = &(psr->add_argument("-a").nargs("+")); // 0 or 1 value psr->add_argument("-b"); } virtual void TearDown() { delete psr; } }; TEST_F(ParserNargsPlus, ok0) { argparse::Argv seq = {"./test"}; argparse::Values v = psr->parse_args(seq); EXPECT_FALSE(v.is_set("a")); EXPECT_EQ(0, v.size("a")); EXPECT_FALSE(v.is_set("b")); } TEST_F(ParserNargsPlus, ok1) { argparse::Argv seq = {"./test", "-a", "v1"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(1, v.size("a")); EXPECT_EQ("v1", v.get("a", 0)); EXPECT_FALSE(v.is_set("b")); } TEST_F(ParserNargsPlus, ok2) { argparse::Argv seq = {"./test", "-a", "v1", "v2"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(2, v.size("a")); EXPECT_EQ("v1", v.get("a", 0)); EXPECT_EQ("v2", v.get("a", 1)); EXPECT_FALSE(v.is_set("b")); } TEST_F(ParserNargsPlus, ok3) { argparse::Argv seq = {"./test", "-a", "v1", "v2", "v3", "-b", "r1"}; argparse::Values v = psr->parse_args(seq); EXPECT_TRUE(v.is_set("a")); EXPECT_EQ(3, v.size("a")); EXPECT_EQ("v1", v.get("a", 0)); EXPECT_EQ("v2", v.get("a", 1)); EXPECT_EQ("v3", v.get("a", 2)); EXPECT_TRUE(v.is_set("b")); } TEST_F(ParserNargsPlus, ng_no_argument1) { argparse::Argv seq = {"./test", "-a"}; EXPECT_THROW(psr->parse_args(seq), argparse::exception::ParseError); } TEST_F(ParserNargsPlus, ng_no_argument2) { argparse::Argv seq = {"./test", "-a", "-b", "r1"}; EXPECT_THROW(psr->parse_args(seq), argparse::exception::ParseError); } TEST_F(ParserNargsPlus, with_default1) { arg->set_default("d"); argparse::Argv seq = {"./test", "-a", "v1", "-b", "r1"}; argparse::Values v = psr->parse_args(seq); EXPECT_EQ(1, v.size("a")); EXPECT_EQ("v1", v["a"]); } TEST_F(ParserNargsPlus, with_default2) { arg->set_default("d"); argparse::Argv seq = {"./test", "-b", "r1"}; argparse::Values v = psr->parse_args(seq); EXPECT_EQ(1, v.size("a")); EXPECT_EQ("d", v["a"]); }
28.915194
73
0.640596
[ "vector" ]
2a73d98f8aea1efc05baf2e21eecc39bacda8b8c
14,051
cpp
C++
DSP/extensions-inactive/AudioUnit/TTAudioUnit.cpp
avilleret/JamomaCore
b09cfb684527980f30845f664e1f922005c24e60
[ "BSD-3-Clause" ]
31
2015-02-28T23:51:10.000Z
2021-12-25T04:16:01.000Z
DSP/extensions-inactive/AudioUnit/TTAudioUnit.cpp
avilleret/JamomaCore
b09cfb684527980f30845f664e1f922005c24e60
[ "BSD-3-Clause" ]
126
2015-01-01T13:42:05.000Z
2021-07-13T14:11:42.000Z
DSP/extensions-inactive/AudioUnit/TTAudioUnit.cpp
avilleret/JamomaCore
b09cfb684527980f30845f664e1f922005c24e60
[ "BSD-3-Clause" ]
14
2015-02-10T15:08:32.000Z
2019-09-17T01:21:25.000Z
/* * TTAudioUnit -- AudioUnit plug-in host * Extension Class for Jamoma DSP * Copyright © 2008, Timothy Place * * License: This code is licensed under the terms of the "New BSD License" * http://creativecommons.org/licenses/BSD/ */ #include "TTDSP.h" #ifdef uint #undef uint #endif #include <CoreServices/CoreServices.h> #include <AudioToolbox/AudioToolBox.h> #include <AudioUnit/AudioUnit.h> #define thisTTClass TTAudioUnit /** An AudioUnit render callback. The AudioUnit will get its audio input by calling this function. */ OSStatus TTAudioUnitGetInputSamples(void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData); /** Host AudioUnit plug-ins. */ class TTAudioUnit : public TTAudioObjectBase { public: TTSymbol mPlugin; ///< Attribute: the name of the current plugin AudioUnit mAudioUnit; ///< the actual plugin AudioBufferList* mInputBufferList; AudioBufferList* mOutputBufferList; AudioTimeStamp mTimeStamp; TTHashPtr mParameterNames; ///< parameter names -> parameter ids TTUInt32 mInputCount; TTUInt32 mOutputCount; /** Constructor. */ TTAudioUnit(TTValue& arguments) : TTAudioObjectBase(arguments), mAudioUnit(NULL), mInputBufferList(NULL), mOutputBufferList(NULL), mInputCount(0), mOutputCount(0) { addAttributeWithSetter(Plugin, kTypeSymbol); addAttributeWithSetter(InputCount, kTypeUInt32); addAttributeWithSetter(OutputCount, kTypeUInt32); addMessageWithArguments(getPluginNames); addMessageWithArguments(getParameterNames); addMessageWithArguments(getPresetNames); addMessageWithArguments(setParameter); addMessageWithArguments(getParameter); addMessageWithArguments(recallPreset); addUpdates(MaxNumChannels); mParameterNames = new TTHash; mTimeStamp.mSampleTime = 0; mTimeStamp.mFlags = kAudioTimeStampSampleTimeValid; setAttributeValue(TT("inputCount"), 1); setAttributeValue(TT("outputCount"), 1); setAttributeValue(TT("plugin"), TT("AULowpass")); setProcessMethod(processAudio); } /** Destructor. */ ~TTAudioUnit() { if (mAudioUnit) { AudioUnitUninitialize(mAudioUnit); CloseComponent(mAudioUnit); mAudioUnit = NULL; } free(mInputBufferList); free(mOutputBufferList); delete mParameterNames; } TTErr updateMaxNumChannels(TTValueConstRef oldMaxNumChannels, TTValueRef) { if (mInputBufferList) free(mInputBufferList); if (mOutputBufferList) free(mOutputBufferList); // inputBufferList = (AudioBufferList*)malloc(offsetof(AudioBufferList, mBuffers[maxNumChannels])); // outputBufferList = (AudioBufferList*)malloc(offsetof(AudioBufferList, mBuffers[maxNumChannels])); mInputBufferList = (AudioBufferList*)malloc(offsetof(AudioBufferList, mBuffers) + (mMaxNumChannels * sizeof(AudioBuffer))); mOutputBufferList = (AudioBufferList*)malloc(offsetof(AudioBufferList, mBuffers) + (mMaxNumChannels * sizeof(AudioBuffer))); for (TTUInt16 channel=0; channel<mMaxNumChannels; channel++) { mInputBufferList->mBuffers[channel].mNumberChannels = 1; mInputBufferList->mBuffers[channel].mData = NULL; // We will set this pointer in the process method mInputBufferList->mBuffers[channel].mDataByteSize = 0; mOutputBufferList->mBuffers[channel].mNumberChannels = 1; mOutputBufferList->mBuffers[channel].mData = NULL; // Tell the AU to deal with the memory mOutputBufferList->mBuffers[channel].mDataByteSize = 0; } return kTTErrNone; } TTErr setInputCount(TTValueConstRef aValue, TTValueRef) { TTUInt32 newInputCount = aValue; if (newInputCount != mInputCount) { mInputCount = newInputCount; // TODO: NEED TO RE-INIT PLUGIN HERE! } return kTTErrNone; } TTErr setOutputCount(TTValueConstRef aValue, TTValueRef) { TTUInt32 newOutputCount = aValue; if (newOutputCount != mOutputCount) { mOutputCount = newOutputCount; // TODO: NEED TO RE-INIT PLUGIN HERE! } return kTTErrNone; } TTErr getPluginNames(TTValueConstRef, TTValueRef pluginNames) { ComponentDescription searchDesc; Component comp = NULL; ComponentDescription compDesc; Handle compName; char* compNameStr; int compNameLen; pluginNames.clear(); searchDesc.componentType = kAudioUnitType_Effect; // TODO: support other types searchDesc.componentSubType = 0; // kAudioUnitSubType_DefaultOutput; searchDesc.componentManufacturer = 0; //kAudioUnitManufacturer_Apple; searchDesc.componentFlags = 0; searchDesc.componentFlagsMask = 0; while (comp = FindNextComponent(comp, &searchDesc)) { compName = NewHandle(0); GetComponentInfo(comp, &compDesc, compName, NULL, NULL); HLock(compName); compNameStr = *compName; compNameLen = *compNameStr++; compNameStr[compNameLen] = 0; compNameStr = strchr(compNameStr, ':'); compNameStr++; compNameStr++; pluginNames.append(TT(compNameStr)); HUnlock(compName); DisposeHandle(compName); } return kTTErrNone; } TTErr setPlugin(TTValue& newPluginName) { ComponentDescription searchDesc; Component comp = NULL; ComponentDescription compDesc; Handle compName; char* compNameStr; int compNameLen; TTSymbol pluginName = newPluginName; TTUInt32 dataSizeDontCare; AudioStreamBasicDescription audioStreamBasicDescription; OSStatus result; if (mAudioUnit) { AudioUnitUninitialize(mAudioUnit); CloseComponent(mAudioUnit); mAudioUnit = NULL; } searchDesc.componentType = kAudioUnitType_Effect; // TODO: support other types searchDesc.componentSubType = 0; // kAudioUnitSubType_DefaultOutput; searchDesc.componentManufacturer = 0; //kAudioUnitManufacturer_Apple; searchDesc.componentFlags = 0; searchDesc.componentFlagsMask = 0; while (comp = FindNextComponent(comp, &searchDesc)) { compName = NewHandle(0); GetComponentInfo(comp, &compDesc, compName, NULL, NULL); HLock(compName); compNameStr = *compName; compNameLen = *compNameStr++; compNameStr[compNameLen] = 0; compNameStr = strchr(compNameStr, ':'); compNameStr++; compNameStr++; if (!strcmp(compNameStr, pluginName)) { AURenderCallbackStruct callbackStruct; mAudioUnit = OpenComponent(comp); mPlugin = pluginName; stuffParameterNamesIntoHash(); HUnlock(compName); DisposeHandle(compName); // plugin is loaded, now activate it callbackStruct.inputProc = &TTAudioUnitGetInputSamples; callbackStruct.inputProcRefCon = this; AudioUnitSetProperty(mAudioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &callbackStruct, sizeof(AURenderCallbackStruct)); AudioUnitSetProperty(mAudioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Global, 0, &sr, sizeof(sr)); // configure for channels in and out dataSizeDontCare = sizeof(audioStreamBasicDescription); result = AudioUnitGetProperty(mAudioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &audioStreamBasicDescription, &dataSizeDontCare); if (!result) { audioStreamBasicDescription.mChannelsPerFrame = mInputCount; result = AudioUnitSetProperty(mAudioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &audioStreamBasicDescription, sizeof(audioStreamBasicDescription)); } dataSizeDontCare = sizeof(audioStreamBasicDescription); result = AudioUnitGetProperty(mAudioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &audioStreamBasicDescription, &dataSizeDontCare); if (!result) { audioStreamBasicDescription.mChannelsPerFrame = mOutputCount; result = AudioUnitSetProperty(mAudioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 0, &audioStreamBasicDescription, sizeof(audioStreamBasicDescription)); } // AudioUnitInitialize(mAudioUnit); return kTTErrNone; } HUnlock(compName); DisposeHandle(compName); } return kTTErrGeneric; } void stuffParameterNamesIntoHash() { UInt32 size = 0; Boolean writable = false; OSStatus err = noErr; AudioUnitParameterID* parameterArray = NULL; mParameterNames->clear(); err = AudioUnitGetPropertyInfo(mAudioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global, 0, &size, &writable); if (err || size == 0) return; parameterArray = (AudioUnitParameterID*)malloc(size); err = AudioUnitGetProperty(mAudioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global, 0, parameterArray, &size); if (err) goto out; for (UInt32 paramNumber = 0; paramNumber < size/sizeof(AudioUnitParameterID); paramNumber++) { AudioUnitParameterInfo info; UInt32 infoSize = sizeof(AudioUnitParameterInfo); char parameterName[256]; err = AudioUnitGetProperty(mAudioUnit, kAudioUnitProperty_ParameterInfo, kAudioUnitScope_Global, parameterArray[paramNumber], &info, &infoSize); if (!err) { CFStringGetCString(info.cfNameString, parameterName, 256, kCFStringEncodingUTF8); mParameterNames->append(TT(parameterName), paramNumber); } } out: free(parameterArray); } TTErr getParameterNames(TTValueConstRef, TTValueRef returnedParameterNames) { return mParameterNames->getKeys(returnedParameterNames); } TTErr setParameter(TTValueConstRef nameAndValue, TTValueRef) { TTSymbol parameterName; TTFloat32 parameterValue; TTValue v; TTErr err; if (nameAndValue.getSize() != 2) { logError("Bad arguments for setParameter()"); return kTTErrGeneric; } nameAndValue.get(0, parameterName); nameAndValue.get(1, parameterValue); err = mParameterNames->lookup(parameterName, v); if (!err) AudioUnitSetParameter(mAudioUnit, v, kAudioUnitScope_Global, 0, parameterValue, 0); return err; } TTErr getParameter(TTValueConstRef nameIn, TTValueRef valueOut) { TTSymbol parameterName = nameIn; TTValue v; TTErr err; long parameterID = -1; Float32 parameterValue = 0.0; err = mParameterNames->lookup(parameterName, v); if (!err) { parameterID = v; AudioUnitGetParameter(mAudioUnit, parameterID, kAudioUnitScope_Global, 0, &parameterValue); valueOut = parameterValue; } return err; } TTErr getPresetNames(TTValueConstRef, TTValueRef returnedPresetNames) { CFArrayRef factoryPresets = NULL; UInt32 size = sizeof(CFArrayRef); OSStatus err = noErr; CFIndex count; returnedPresetNames.clear(); err = AudioUnitGetProperty(mAudioUnit, kAudioUnitProperty_FactoryPresets, kAudioUnitScope_Global, 0, &factoryPresets, &size); if (err) return kTTErrGeneric; count = CFArrayGetCount(factoryPresets); for (int i=0; i<count; i++) { const AUPreset* preset = (const AUPreset*)CFArrayGetValueAtIndex(factoryPresets, i); char presetName[256]; CFStringGetCString(preset->presetName, presetName, 256, kCFStringEncodingUTF8); returnedPresetNames.append(TT(presetName)); } CFRelease(factoryPresets); return kTTErrNone; } // We could also keep a hash of factory presets and allow a symbol to set the preset by name at some point... TTErr recallPreset(TTValueConstRef presetNumber, TTValueRef) { AUPreset presetInfo; OSStatus err = noErr; presetInfo.presetNumber = presetNumber; err = AudioUnitSetProperty(mAudioUnit, kAudioUnitProperty_CurrentPreset, kAudioUnitScope_Global, 0, &presetInfo, sizeof(AUPreset)); return TTErr(err); } /** Audio Processing Method */ TTErr processAudio(TTAudioSignalArrayPtr inputs, TTAudioSignalArrayPtr outputs) { TTAudioSignal& in = inputs->getSignal(0); TTAudioSignal& out = outputs->getSignal(0); TTUInt16 vs = in.getVectorSizeAsInt(); TTUInt16 numInputChannels = in.getNumChannelsAsInt(); TTUInt16 numOutputChannels = out.getNumChannelsAsInt(); // TTFloat32* auInput[numInputChannels]; TTFloat32* auOutput;//[numOutputChannels]; AudioUnitRenderActionFlags ioActionFlags = 0; // prepare the input for (TTUInt16 channel=0; channel<numInputChannels; channel++) { TTUInt32 dataByteSize = sizeof(TTFloat32) * vs; if (mInputBufferList->mBuffers[channel].mDataByteSize != dataByteSize) { if (mInputBufferList->mBuffers[channel].mDataByteSize) TTFree16(mInputBufferList->mBuffers[channel].mData); mInputBufferList->mBuffers[channel].mData = TTMalloc16(dataByteSize); mInputBufferList->mBuffers[channel].mDataByteSize = dataByteSize; } in.getVector(channel, vs, (TTFloat32*)mInputBufferList->mBuffers[channel].mData); // mInputBufferList->mBuffers[channel].mDataByteSize = sizeof(TTFloat32) * vs; mOutputBufferList->mBuffers[channel].mDataByteSize = sizeof(TTFloat32) * vs; } mInputBufferList->mNumberBuffers = numInputChannels; mOutputBufferList->mNumberBuffers = numOutputChannels; // render the output using the plugin AudioUnitRender(mAudioUnit, &ioActionFlags, &mTimeStamp, 0, vs, mOutputBufferList); // handle the output numOutputChannels = mOutputBufferList->mNumberBuffers; for (TTUInt16 channel=0; channel<numOutputChannels; channel++) { auOutput = (TTFloat32*)mOutputBufferList->mBuffers[channel].mData; out.setVector(channel, vs, auOutput); } mTimeStamp.mSampleTime += vs; return kTTErrNone; } }; // Implemention of the AU render callback. OSStatus TTAudioUnitGetInputSamples(void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData) { TTAudioUnit* ttAudioUnit = (TTAudioUnit*)inRefCon; for (TTUInt16 channel=0; channel < ioData->mNumberBuffers; channel++) memcpy(ioData->mBuffers[channel].mData, ttAudioUnit->mInputBufferList->mBuffers[channel].mData, sizeof(TTFloat32) * inNumberFrames); return noErr; } TT_AUDIO_CLASS_SETUP("audiounit", "audio, processor", TTAudioUnit);
31.504484
174
0.740446
[ "render" ]
2a7a225352f385aa87446cb4bc14f3d02c3ddf68
855
cpp
C++
src/listeners/RequestSet.cpp
valmat/RocksServer
e00436ec9147641731c60da7d4643ecfb61217ac
[ "BSD-3-Clause" ]
24
2015-02-03T08:48:52.000Z
2021-10-03T23:57:13.000Z
src/listeners/RequestSet.cpp
valmat/RocksServer
e00436ec9147641731c60da7d4643ecfb61217ac
[ "BSD-3-Clause" ]
null
null
null
src/listeners/RequestSet.cpp
valmat/RocksServer
e00436ec9147641731c60da7d4643ecfb61217ac
[ "BSD-3-Clause" ]
5
2015-07-10T15:40:53.000Z
2019-12-06T11:57:35.000Z
/** * RequestSet.cpp * * Request listener for command "set" * * @author valmat <ufabiz@gmail.com> * @github https://github.com/valmat/rocksserver */ #include "RocksServer.h" namespace RocksServer { /** * Runs request listener * @param protocol in object * @param protocol out object */ void RequestSet::run(const ProtocolInPost &in, const ProtocolOut &out) noexcept { // Detect if current method is correct POST if( !in.check(out) ) { return; } // Get key-value pair from the POST data auto pair = in.pair(); // Set key-value pair to the DB if(db.set(pair.first, pair.second)) { out.ok(); } else { out.fail(); EvLogger::writeLog(db.getStatus().data()); } } }
21.923077
83
0.539181
[ "object" ]
2a850c99e5078a9230099602a5ed2ad1dff79779
442
cpp
C++
10610.cpp
jaemin2682/BAEKJOON_ONLINE_JUDGE
0d5c6907baee61e1fabdbcd96ea473079a9475ed
[ "MIT" ]
null
null
null
10610.cpp
jaemin2682/BAEKJOON_ONLINE_JUDGE
0d5c6907baee61e1fabdbcd96ea473079a9475ed
[ "MIT" ]
null
null
null
10610.cpp
jaemin2682/BAEKJOON_ONLINE_JUDGE
0d5c6907baee61e1fabdbcd96ea473079a9475ed
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <algorithm> #include <vector> using namespace std; int main() { string s; cin >> s; vector<int> v; int sum = 0; for (int i = 0; i < s.length(); i++) { v.push_back(s[i]); sum += s[i] - 48; } sort(v.begin(), v.end(), greater<int>()); if (v.back()-48 != 0 || sum<3) cout << -1; else if (sum % 3 == 0) { for (int i = 0; i < s.length(); i++) cout << v[i]-48; } else cout << -1; }
18.416667
55
0.527149
[ "vector" ]
2a8710a4857c71b74965b9cc64e97b2a58049730
15,854
cpp
C++
rdkPlugins/Networking/source/NetworkingPlugin.cpp
jignatius/Dobby
1de36b7e4442b3c10bccb881907fd07368dd463f
[ "Apache-2.0" ]
null
null
null
rdkPlugins/Networking/source/NetworkingPlugin.cpp
jignatius/Dobby
1de36b7e4442b3c10bccb881907fd07368dd463f
[ "Apache-2.0" ]
null
null
null
rdkPlugins/Networking/source/NetworkingPlugin.cpp
jignatius/Dobby
1de36b7e4442b3c10bccb881907fd07368dd463f
[ "Apache-2.0" ]
null
null
null
/* * If not stated otherwise in this file or this component's LICENSE file the * following copyright and licenses apply: * * Copyright 2020 Sky UK * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "NetworkingPlugin.h" #include "DnsmasqSetup.h" #include "PortForwarding.h" #include "MulticastForwarder.h" #include "NetworkSetup.h" #include "Netlink.h" #include "IPAllocator.h" #include <fcntl.h> #include <unistd.h> #include <dirent.h> #include <sys/stat.h> #include <algorithm> REGISTER_RDK_PLUGIN(NetworkingPlugin); NetworkingPlugin::NetworkingPlugin(std::shared_ptr<rt_dobby_schema> &cfg, const std::shared_ptr<DobbyRdkPluginUtils> &utils, const std::string &rootfsPath) : mName("Networking"), mNetworkType(NetworkType::None), mContainerConfig(cfg), mUtils(utils), mRootfsPath(rootfsPath), mNetfilter(std::make_shared<Netfilter>()) { AI_LOG_FN_ENTRY(); if (!mContainerConfig || !cfg->rdk_plugins->networking || !cfg->rdk_plugins->networking->data) { mValid = false; } else { mPluginData = cfg->rdk_plugins->networking->data; mHelper = std::make_shared<NetworkingHelper>(mPluginData->ipv4, mPluginData->ipv6); std::string networkType = mPluginData->type; if (networkType == "nat") { mNetworkType = NetworkType::Nat; } else if (networkType == "none") { mNetworkType = NetworkType::None; } else if (networkType == "open") { mNetworkType = NetworkType::Open; } else { AI_LOG_WARN("Unexpected network type '%s', defaulting to 'none'", networkType.c_str()); mNetworkType = NetworkType::None; } mValid = true; } AI_LOG_FN_EXIT(); } NetworkingPlugin::~NetworkingPlugin() { AI_LOG_FN_ENTRY(); AI_LOG_FN_EXIT(); } /** * @brief Set the bit flags for which hooks we're going to use * * This plugin uses all the hooks so set all the flags */ unsigned NetworkingPlugin::hookHints() const { return ( IDobbyRdkPlugin::HintFlags::PostInstallationFlag | IDobbyRdkPlugin::HintFlags::CreateRuntimeFlag | IDobbyRdkPlugin::HintFlags::PostStopFlag | IDobbyRdkPlugin::HintFlags::PostHaltFlag ); } // Begin Hook Methods /** * @brief Dobby Hook - run in host namespace *once* when container bundle is downloaded */ bool NetworkingPlugin::postInstallation() { AI_LOG_FN_ENTRY(); if (!mValid) { AI_LOG_ERROR_EXIT("invalid config file"); return false; } // if the network type is not 'open', enable network namespacing in OCI config if (mNetworkType != NetworkType::Open) { // add /etc/resolv.conf mount if not using dnsmasq. If dnsmasq is enabled, // a new /etc/resolv.conf is created rather than mounting the host's if (!mPluginData->dnsmasq) { NetworkSetup::addResolvMount(mUtils, mContainerConfig); } // add network namespacing to the OCI config NetworkSetup::addNetworkNamespace(mContainerConfig); } AI_LOG_FN_EXIT(); return true; } /** * @brief OCI Hook - Run in host namespace */ bool NetworkingPlugin::createRuntime() { AI_LOG_FN_ENTRY(); if (!mValid) { AI_LOG_ERROR_EXIT("invalid config file"); return false; } // nothing to do for containers configured for an open network if (mNetworkType == NetworkType::Open) { AI_LOG_FN_EXIT(); return true; } // get available external interfaces const std::vector<std::string> extIfaces = GetAvailableExternalInterfaces(); if (extIfaces.empty()) { AI_LOG_ERROR_EXIT("No network interfaces available"); return false; } // check if another container has already initialised the bridge device for us std::shared_ptr<Netlink> netlink = std::make_shared<Netlink>(); bool bridgeExists = netlink->ifaceExists(std::string(BRIDGE_NAME)); if (!bridgeExists) { AI_LOG_DEBUG("Dobby network bridge not found, setting it up"); // setup the bridge device if (!NetworkSetup::setupBridgeDevice(mUtils, mNetfilter, extIfaces)) { AI_LOG_ERROR_EXIT("failed to setup Dobby bridge device"); return false; } } // setup veth, ip address and iptables rules for container if (!NetworkSetup::setupVeth(mUtils, mNetfilter, mHelper, mRootfsPath, mUtils->getContainerId(), mNetworkType)) { AI_LOG_ERROR_EXIT("failed to setup virtual ethernet device"); return false; } // setup dnsmasq rules if enabled if (mNetworkType != NetworkType::None && mPluginData->dnsmasq) { if (!DnsmasqSetup::set(mUtils, mNetfilter, mHelper, mRootfsPath, mUtils->getContainerId(), mNetworkType)) { AI_LOG_ERROR_EXIT("failed to setup container for dnsmasq use"); return false; } } // add port forwards if any have been configured if (mPluginData->port_forwarding != nullptr) { if (!PortForwarding::addPortForwards(mNetfilter, mHelper, mUtils->getContainerId(), mPluginData->port_forwarding)) { AI_LOG_ERROR_EXIT("failed to add port forwards"); return false; } // Add localhost masquerade if enabled (run in container network namespace) if (mPluginData->port_forwarding->localhost_masquerade_present && mPluginData->port_forwarding->localhost_masquerade) { // Ideally this would be done in the createContainer hook, but that fails // on some platforms with permissions issues (works fine on VM...) if (!mUtils->callInNamespace(mUtils->getContainerPid(), CLONE_NEWNET, &PortForwarding::addLocalhostMasquerading, mHelper, mUtils, mPluginData->port_forwarding)) { AI_LOG_ERROR_EXIT("Failed to add localhost masquerade iptables rules inside container"); return false; } } } // enable multicast forwarding if (mPluginData->multicast_forwarding != nullptr) { if (!MulticastForwarder::set(mNetfilter, mPluginData, mHelper->vethName(), mUtils->getContainerId(), extIfaces)) { AI_LOG_ERROR_EXIT("failed to add multicast forwards"); return false; } } // apply iptables changes if (!mNetfilter->applyRules(AF_INET) || !mNetfilter->applyRules(AF_INET6)) { AI_LOG_ERROR_EXIT("failed to apply iptables rules"); return false; } AI_LOG_FN_EXIT(); return true; } /** * @brief OCI Hook - Run in host namespace */ bool NetworkingPlugin::postStop() { AI_LOG_FN_ENTRY(); // In some scenarios, the PostHalt hook might not run (e.g. if we're cleaning up // old containers at boot). // Make sure we clean up after ourselves const std::string containerId = mUtils->getContainerId(); const std::string addressFilePath = ADDRESS_FILE_DIR + containerId; if (access(addressFilePath.c_str(), F_OK) == 0) { IPAllocator ipAllocator(mUtils); ipAllocator.deallocateIpAddress(containerId); } AI_LOG_FN_EXIT(); return true; } /** * @brief Dobby Hook - Run in host namespace when container terminates */ bool NetworkingPlugin::postHalt() { AI_LOG_FN_ENTRY(); bool success = true; if (!mValid) { AI_LOG_ERROR_EXIT("invalid config file"); return false; } // nothing to do for containers configured for an open network if (mNetworkType == NetworkType::Open) { AI_LOG_FN_EXIT(); return true; } // Get container veth/ip ContainerNetworkInfo networkInfo; IPAllocator ipAllocator(mUtils); if (!ipAllocator.getContainerNetworkInfo(mUtils->getContainerId(), networkInfo)) { AI_LOG_WARN("Failed to get container network info"); success = false; } else { // Update instance of network helper mHelper->storeContainerInterface(networkInfo.ipAddressRaw, networkInfo.vethName); // delete the veth pair for the container if (!NetworkSetup::removeVethPair(mNetfilter, mHelper, networkInfo.vethName, mNetworkType, mUtils->getContainerId())) { AI_LOG_WARN("failed to remove veth pair %s", networkInfo.vethName.c_str()); success = false; } } // Release the IP from the pool ipAllocator.deallocateIpAddress(mUtils->getContainerId()); // get external interfaces const std::vector<std::string> extIfaces = GetAvailableExternalInterfaces(); if (extIfaces.empty()) { AI_LOG_WARN("couldn't find external network interfaces in settings," "unable to remove bridge device"); success = false; } else { // if there are no containers using the bridge device left, remove bridge device std::shared_ptr<Netlink> netlink = std::make_shared<Netlink>(); auto bridgeConnections = netlink->getAttachedIfaces(BRIDGE_NAME); // Ignore the tap0 device as that may or may not be present, doesn't matter for this check if (bridgeConnections.size() == 0 || (bridgeConnections.size() == 1 && strcmp(bridgeConnections.front().name, "dobby_tap0") == 0)) { if (!NetworkSetup::removeBridgeDevice(mNetfilter, extIfaces)) { success = false; } } } // if dnsmasq iptables rules were set up for container, "uninstall" them if (mNetworkType != NetworkType::None && mPluginData->dnsmasq) { if (!DnsmasqSetup::removeRules(mNetfilter, mHelper, mUtils->getContainerId())) { success = false; } } // remove port forwards if any have been configured // no need to remove the localhost masquerade rules as these were only // applied inside the container namespace if (mPluginData->port_forwarding != nullptr) { if (!PortForwarding::removePortForwards(mNetfilter, mHelper, mUtils->getContainerId(), mPluginData->port_forwarding)) { success = false; } } // remove multicast forwarding rules if configured if (mPluginData->multicast_forwarding != nullptr) { if (!MulticastForwarder::removeRules(mNetfilter, mPluginData, mHelper->vethName(), mUtils->getContainerId(), extIfaces)) { AI_LOG_ERROR_EXIT("failed to remove multicast forwards"); return false; } } // apply iptables changes if (!mNetfilter->applyRules(AF_INET) || !mNetfilter->applyRules(AF_INET6)) { AI_LOG_ERROR_EXIT("failed to apply iptables rules"); return false; } AI_LOG_FN_EXIT(); return success; } // End hook methods /** * @brief Should return the names of the plugins this plugin depends on. * * This can be used to determine the order in which the plugins should be * processed when running hooks. * * @return Names of the plugins this plugin depends on. */ std::vector<std::string> NetworkingPlugin::getDependencies() const { std::vector<std::string> dependencies; const rt_defs_plugins_networking* pluginConfig = mContainerConfig->rdk_plugins->networking; for (size_t i = 0; i < pluginConfig->depends_on_len; i++) { dependencies.push_back(pluginConfig->depends_on[i]); } return dependencies; } // Begin private methods /** * @brief Gets the external interfaces that are actually available. Looks in the * settings for the interfaces Dobby should use, then checks if the device * actually has those interfaces available. Will return empty vector if none of * the ifaces in the settings file are available * * @return Available external interfaces from the ones defined in dobby * settings */ std::vector<std::string> NetworkingPlugin::GetAvailableExternalInterfaces() const { std::vector<std::string> externalIfaces = GetExternalInterfacesFromSettings(); if (externalIfaces.size() == 0) { AI_LOG_WARN("No external network interfaces defined in settings file"); return {}; } // Look in the /sys/class/net for available interfaces struct dirent *dir; DIR *d = opendir("/sys/class/net"); if (!d) { AI_LOG_SYS_ERROR(errno, "Could not check for available interfaces"); return std::vector<std::string>(); } std::vector<std::string> availableIfaces = {}; while ((dir = readdir(d)) != nullptr) { if (dir->d_name[0] != '.') { availableIfaces.emplace_back(dir->d_name); } } closedir(d); // We know what interfaces we want, and what we've got. See if we're missing // any auto it = externalIfaces.cbegin(); while (it != externalIfaces.cend()) { if (std::find(availableIfaces.begin(), availableIfaces.end(), it->c_str()) == availableIfaces.end()) { AI_LOG_WARN("Interface '%s' from settings file not available", it->c_str()); it = externalIfaces.erase(it); } else { ++it; } } // If no interfaces are available, something is very wrong if (externalIfaces.size() == 0) { AI_LOG_ERROR("None of the external interfaces defined in the settings file are available"); } return externalIfaces; } /** * @brief Gets the external interfaces defined in the dobby settings file, regardless * of whether they actually exist on the platform or not * * @return All external interfaces from dobby settings file */ std::vector<std::string> NetworkingPlugin::GetExternalInterfacesFromSettings() const { // We don't have jsoncpp here, so use yajl from libocispec std::vector<std::string> ifacesFromSettings = {}; std::string settingsFile = mUtils->readTextFile("/etc/dobby.json"); if (settingsFile.empty()) { AI_LOG_ERROR("Could not read settings file @ '/etc/dobby.json'"); return {}; } yajl_val tree; char errbuf[1024]; // Parse the settings file tree = yajl_tree_parse (settingsFile.c_str(), errbuf, sizeof (errbuf)); if (!tree || strlen(errbuf) > 0) { yajl_tree_free(tree); AI_LOG_ERROR_EXIT("Failed to parse Dobby settings file, err '%s'", errbuf); return {}; } // Read the external interfaces array const char* path[] = {"network", "externalInterfaces", (const char *) 0}; yajl_val extInterfaces = yajl_tree_get(tree, path, yajl_t_array); if (extInterfaces && YAJL_GET_ARRAY (extInterfaces) && YAJL_GET_ARRAY (extInterfaces)->len > 0) { size_t i; size_t len = YAJL_GET_ARRAY (extInterfaces)->len; yajl_val *values = YAJL_GET_ARRAY (extInterfaces)->values; for (i = 0; i < len; i++) { ifacesFromSettings.push_back(YAJL_GET_STRING(values[i])); } } yajl_tree_free(tree); return ifacesFromSettings; }
30.488462
138
0.637379
[ "vector" ]
2a88f795879ef922b95f89222441ecce7bbc4d60
969
cpp
C++
problems/066.Plus_One/AC_simulation_n.cpp
subramp-prep/leetcode
d125201d9021ab9b1eea5e5393c2db4edd84e740
[ "Unlicense" ]
null
null
null
problems/066.Plus_One/AC_simulation_n.cpp
subramp-prep/leetcode
d125201d9021ab9b1eea5e5393c2db4edd84e740
[ "Unlicense" ]
null
null
null
problems/066.Plus_One/AC_simulation_n.cpp
subramp-prep/leetcode
d125201d9021ab9b1eea5e5393c2db4edd84e740
[ "Unlicense" ]
null
null
null
/* * Author: illuz <iilluzen[at]gmail.com> * File: AC_simulation_n.cpp * Create Date: 2014-12-20 10:07:27 * Descripton: */ #include <bits/stdc++.h> using namespace std; const int N = 0; class Solution { public: vector<int> plusOne(vector<int> &digits) { int len = digits.size(); bool carry = true; for (int i = len - 1; i >= 0; i--) { carry = ((digits[i] + 1) % 10 == 0); if (carry) { digits[i] = 0; } else { digits[i]++; return digits; } } vector<int> res(len + 1, 0); res[0] = 1; return res; } }; int main() { vector<int> v; Solution s; string str; while (cin >> str) { v.clear(); for (char i : str) v.push_back(i - '0'); v = s.plusOne(v); for (int i : v) cout << i; cout << endl; } return 0; }
19.77551
48
0.432405
[ "vector" ]
2a8b483c7a010290a2ea8dde6c96caf89cb5732d
1,792
cpp
C++
Leet Code/Sliding Window Maximum.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
51
2020-02-24T11:14:00.000Z
2022-03-24T09:32:18.000Z
Leet Code/Sliding Window Maximum.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
3
2020-10-02T08:16:09.000Z
2021-04-17T16:32:38.000Z
Leet Code/Sliding Window Maximum.cpp
Shubhrmcf07/Competitive-Coding-and-Interview-Problems
7281ea3163c0cf6938a3af7b54a8a14f97c97c0e
[ "MIT" ]
18
2020-04-24T15:33:36.000Z
2022-03-24T09:32:20.000Z
/* Leet Code */ /* Title - Sliding Window Maximum */ /* Created By - Akash Modak */ /* Date - 23/09/2020 */ // You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. // Return the max sliding window. // Example 1: // Input: nums = [1,3,-1,-3,5,3,6,7], k = 3 // Output: [3,3,5,5,6,7] // Explanation: // Window position Max // --------------- ----- // [1 3 -1] -3 5 3 6 7 3 // 1 [3 -1 -3] 5 3 6 7 3 // 1 3 [-1 -3 5] 3 6 7 5 // 1 3 -1 [-3 5 3] 6 7 5 // 1 3 -1 -3 [5 3 6] 7 6 // 1 3 -1 -3 5 [3 6 7] 7 // Example 2: // Input: nums = [1], k = 1 // Output: [1] // Example 3: // Input: nums = [1,-1], k = 1 // Output: [1,-1] // Example 4: // Input: nums = [9,11], k = 2 // Output: [11] // Example 5: // Input: nums = [4,-2], k = 2 // Output: [4] class Solution { public: vector<int> maxSlidingWindow(vector<int>& nums, int k) { deque<int> dq; vector<int> res; int i=0; for(;i<k;i++){ while(!dq.empty() and nums[dq.back()]<=nums[i]) dq.pop_back(); dq.push_back(i); } for(;i<nums.size();i++){ res.push_back(nums[dq.front()]); while(!dq.empty() and dq.front()<=i-k) dq.pop_front(); while(!dq.empty() and nums[i]>=nums[dq.back()]) dq.pop_back(); dq.push_back(i); } res.push_back(nums[dq.front()]); return res; } };
26.352941
251
0.457031
[ "vector" ]
2a8bc018088398c056c7f4f6ea0cc21a21f63a4c
3,126
hpp
C++
headers/GameWorld.hpp
eubrunomiguel/garuna
e18d54213b561fbc7075eaf2acb131b2084a6434
[ "MIT" ]
57
2018-05-16T17:04:01.000Z
2022-03-22T00:18:42.000Z
headers/GameWorld.hpp
eubrunomiguel/garuna
e18d54213b561fbc7075eaf2acb131b2084a6434
[ "MIT" ]
null
null
null
headers/GameWorld.hpp
eubrunomiguel/garuna
e18d54213b561fbc7075eaf2acb131b2084a6434
[ "MIT" ]
17
2019-01-25T04:04:59.000Z
2022-03-13T11:54:08.000Z
// // GameWorld.hpp // server // // Created by Bruno Macedo Miguel on 12/11/16. // Copyright © 2016 d2server. All rights reserved. // #ifndef GameWorld_hpp #define GameWorld_hpp #include <cstdlib> #include <cassert> #include <map> #include <queue> #include <iostream> #include "DynamicPool.hpp" #include "GameLevel.hpp" #include "Consts.hpp" #include "Item.hpp" class Factory; class Player; class GameWorld{ public: GameWorld() { assert(numinstantiated < MAXWORLDS); numinstantiated++; } void loadFactory(Factory* fac) {_factory = fac;} void update(); void addAction(DataBus* action) { _incomingactions.push(action);} GameLevel* isInGame(const Body* body); const std::map <uint32_t, GameLevel*>& getGames(){return _games;} void broadcastGameStatus (uint32_t to, GameMessage message, const GameLevel& game, uint32_t who, std::string who_name); void broadcastGameStatus (uint32_t to, GameMessage message, const GameLevel& game, uint32_t who); void broadcastBodyCoordinate (const uint32_t& to, const Body*, const Vector3&, const bool&); void broadcastBodyCardinal (const uint32_t& to, const Body*, const MovementDirection&); void broadcastBodyAttacker (const uint32_t& to, const Body* attacker, const Body* target); void broadcastBodyLife (const uint32_t& to, const Body*, const Body* responsible, const uint16_t&, const bool&); void broadcastShoot (const uint32_t& to, const Body* shooter, const Vector3& target); void broadcastCreatureDead (uint32_t to, uint32_t who, uint32_t by); void broadcastNewItem (const uint32_t& to, const Item* item); void broadcastDespawn (const uint32_t& to, const Body* body); void broadcastWarningMessage (const uint32_t& tp, const MessageOutput&); void broadcastExperience (const uint32_t& to, const ExperienceData&); void broadcastSpawn (const uint32_t& to, Body* body); // Non-Const since we send a copy pointer to ActionData static uint32_t getUniqueID() {return ++entityid;} const Factory* getFactory() const {return _factory;} void registerPlayer(Player&); void unregisterPlayer(Player&); void forceSave(uint32_t playerguid); void leaveGame(Body*); private: void gameManager(Body*, const void*); void startGame(Body*); void joinGame(const uint32_t&, Body*); void newGame(Body*); void endGame(const uint32_t&); void processInput(); void updateGame(); Factory* _factory; std::vector<GameLevel*> _gamestodestroy; std::map <uint32_t, GameLevel*> _games; DynamicPool<GameLevel> _gamePool; // to process actions std::queue<DataBus*> _incomingactions; // Keep track of our bodies in the world std::map <uint32_t, Player*> _players; // Unique Entity ID static uint32_t entityid; // Control number instanciated static uint8_t numinstantiated; }; #endif /* GameWorld_hpp */
30.950495
124
0.665707
[ "vector" ]
2a8c459d1a24ab285eeb885556be6a27bec34aae
11,760
cpp
C++
Homework 2 The Fruit Rage!/homework11.cpp
dweeptrivedi/CSCI561-Artificial-Intelligence-Assignments
15840d0a6fff02db6563ada0be10d4b45d44216d
[ "MIT" ]
null
null
null
Homework 2 The Fruit Rage!/homework11.cpp
dweeptrivedi/CSCI561-Artificial-Intelligence-Assignments
15840d0a6fff02db6563ada0be10d4b45d44216d
[ "MIT" ]
null
null
null
Homework 2 The Fruit Rage!/homework11.cpp
dweeptrivedi/CSCI561-Artificial-Intelligence-Assignments
15840d0a6fff02db6563ada0be10d4b45d44216d
[ "MIT" ]
1
2019-11-25T11:21:40.000Z
2019-11-25T11:21:40.000Z
#include <iostream> #include <functional> #include <fstream> #include <string> #include <stdlib.h> #include <sys/types.h> #include <stdint.h> #include <stdbool.h> #include <string> #include <string.h> #include <map> #include <vector> #include <array> #include <algorithm> #include <assert.h> #include <unistd.h> #include <cmath> using namespace std; uint32_t maxDepth = 3; uint64_t count1 = 0, prune = 0, saved = 0, savedIlands = 0, leaves = 0, star = 0; uint32_t n = 0; uint32_t p = 0; double t = 0; uint32_t bestState[2]={0,0}; uint32_t bestSize=0; uint32_t min_row,max_row,min_col,max_col; hash<string> str_hash; hash<string> score_hash; map<size_t, vector <array<uint32_t,3>>> m1; map<size_t, int64_t> m3; bool goalState(string board) { uint32_t data = n*n; for (int i=0;i<data;i++){ if (board[i]!='*') return false; } return true; } uint32_t exploreIland2(string &board, uint32_t row, uint32_t col, char fruit){ uint32_t index = row*n+col; if (board[index] != fruit) return 0; board[index] = '*'; if (col < n-1){ max_col = (max_col>col+1)?max_col:col+1; exploreIland2(board, row, col+1, fruit); } if (col > 0){ min_col = (min_col<col-1)?min_col:col-1; exploreIland2(board, row, col-1, fruit); } if (row < n-1){ max_row = (max_row>row+1)?max_row:row+1; exploreIland2(board, row+1, col, fruit); } if (row > 0){ min_row = (min_row<row-1)?min_row:row-1; exploreIland2(board, row-1, col, fruit); } return 0; } uint32_t exploreIland3(string &board, uint32_t row, uint32_t col, char fruit, uint32_t islanSize){ uint32_t index = row*n+col; if (board[index] != fruit) return 0; board[index] = '*'; uint32_t islandSize = 1; if (col < n-1){ max_col = (max_col>col+1)?max_col:col+1; islandSize += exploreIland3(board, row, col+1, fruit, islandSize); } if (col > 0){ min_col = (min_col<col-1)?min_col:col-1; islandSize += exploreIland3(board, row, col-1, fruit, islandSize); } if (row < n-1){ max_row = (max_row>row+1)?max_row:row+1; islandSize += exploreIland3(board, row+1, col, fruit, islandSize); } if (row > 0){ min_row = (min_row<row-1)?min_row:row-1; islandSize += exploreIland3(board, row-1, col, fruit, islandSize); } return islandSize; } void applyGravity(string &board){ uint32_t Rmax = max_row+1; int32_t j, last, lastStar; for (int i=min_col;i<=max_col;i++){ j = min_row; while (j<Rmax){ while(j<Rmax && board[j*n+i]=='*') j++; while(j<Rmax && board[j*n+i]!='*') j++; if(j<Rmax){ last = j-1; while(j<Rmax && board[j*n+i]=='*'){ lastStar = j; j++; } while(last>=0){ board[lastStar*n+i] = board[last*n+i]; lastStar--; last--; } while(lastStar>=0){ board[lastStar*n+i] = '*'; lastStar--; } } } } return; } bool sortFunc(array<uint32_t,3>&a, array<uint32_t,3>&b){ return (a[0]>b[0]); } bool sortFunc2(array<double,3>&a, array<double,3>&b){ return (a[1]>b[1]); } void getChildren(string &board,vector <array<uint32_t,3>> &childIlands,uint32_t *childIlandsSize){ uint32_t k =0; uint32_t index,size; size_t boardhash = str_hash(board); if(m1.find(boardhash)!=m1.end()){ savedIlands++; childIlands = m1[boardhash]; return; } string visited(board); for(uint32_t i=0;i<n;i++){ for(uint32_t j=0;j<n;j++){ index= i*n+j; if (visited[index]!='*'){ size = exploreIland3(visited, i, j, visited[index], 0); array<uint32_t,3> island {size, i, j}; childIlands.push_back(island); k++; } } } sort(childIlands.begin(),childIlands.begin()+k, sortFunc); //This will create a new copy at global level, change it to pointer reference if taking too much memory m1[boardhash] = childIlands; *childIlandsSize=k; } void getChild(string &board, string &child, array <uint32_t,3>&childIland){ uint32_t r = childIland[1]; uint32_t c = childIland[2]; min_row = r; max_row = r; min_col = c; max_col = c; exploreIland2(child, r, c, child[r*n+c]); applyGravity(child); return; } int64_t playGame(string &board, bool player, uint64_t maximus, uint64_t minimus, uint32_t depth, int64_t alpha, int64_t beta){ int64_t va, vb; int64_t temp; uint32_t childIlandIdx=0; int64_t score = maximus-minimus; count1++; if (goalState(board)){ return 0; } if (player){va=-123456;}else{vb=123456;} bool gotit = false; size_t boardhash = score_hash(board+to_string(maxDepth-depth)+to_string(player)+to_string(alpha)+to_string(beta)); if (depth < maxDepth && m3.find(boardhash)!=m3.end()){ saved++; temp = m3[boardhash]; return temp; } vector <array<uint32_t,3>>childIlands = vector<array<uint32_t,3>>(); uint32_t childIlandsSize=0; getChildren(board,childIlands,&childIlandsSize); childIlandsSize = childIlands.size(); for (int i=0;i<childIlandsSize;i++){ score = maximus-minimus; string child(board); getChild(board, child, childIlands[i]); uint32_t squaredSize = childIlands[i][0]*childIlands[i][0]; (player)?maximus+=squaredSize:minimus+=squaredSize; if(depth+1<=maxDepth) { temp = playGame(child,!player, maximus, minimus, depth+1, alpha, beta); } else { temp = 0; leaves++; } if (player){ maximus -= squaredSize; score += squaredSize+temp; if (va < score){ va=score; if (depth==1){ bestSize = childIlands[i][0]; bestState[0] = childIlands[i][1]; bestState[1] = childIlands[i][2]; } } if (va >= beta){ prune++; return va-maximus+minimus; } alpha = alpha>va?alpha:va; } else { minimus -= squaredSize; score += temp-squaredSize; if (vb > score){ vb = score; } if (vb <= alpha){ prune++; return vb-maximus+minimus; } beta = beta<vb?beta:vb; } } if (player) { if (depth<maxDepth) m3[boardhash] = va-maximus+minimus; return va-maximus+minimus; } else { if (depth<maxDepth) m3[boardhash] = vb-maximus+minimus; return vb-maximus+minimus; } } void initGame(string &board){ if (goalState(board)){ return; } uint64_t maximus = 0; uint64_t minimus = 0; uint64_t score; score = playGame(board, true, maximus, minimus, 1, -123456, 123456); bool* visited = (bool*)calloc(sizeof(bool)*n*n,false); min_row = bestState[0]; max_row = bestState[0]; min_col = bestState[1]; max_col = bestState[1]; exploreIland2(board, bestState[0], bestState[1], board[bestState[0]*n+bestState[1]]); applyGravity(board); } long long totalNodes(uint64_t (&arrayTotal)[677] ,uint32_t num, uint32_t depth, uint32_t maxD){ if (num==2 || num==1 || (depth == maxD)){ return 1; } if (arrayTotal[num]!=0){ return arrayTotal[num]; } arrayTotal[num] = 1+num+(num*(num-1)*totalNodes(arrayTotal, num-2, depth+1,maxD)); return arrayTotal[num]; } void setDepth(uint32_t numIslands){ int maxN=0, maxK=0, numSamples=0; int i=0; bool notFound = false; double read[3]={0}; vector <array<double,3>> v = vector<array<double,3>>(); if(t-(t/15)<=0.05 && n>=15){ maxDepth=2; return; } ifstream calibrate; calibrate.open("calibration.txt"); if(!calibrate.is_open()){ if (numIslands<=n*n/2) { if (n<=10) maxDepth = 6; else if (n<=14) maxDepth = 5; else if (n<=17) maxDepth = 4; } else { maxDepth = 4; } if (n>=18){ if(numIslands<=n*n/4) maxDepth = 4; else maxDepth = 3; } return; } calibrate>>maxN>>maxK>>numSamples; for (i=0;i<n-1 && i+1<=maxN;i++){ for (int j=0;j<numSamples;j++){ for(int k=0;k<maxK;k++){ calibrate>>read[k]; } } } if(read[0]+1!=n){ if (n<=19 || numIslands<=1.125*n*n/3){ maxDepth = 4; }else{ maxDepth = 3; } return; } for (int j=0;j<numSamples;j++){ array<double, 3> arr; for(int k=0;k<maxK;k++){ calibrate>>arr[k]; } v.push_back(arr); } sort(v.begin(),v.end(),sortFunc2); int id=0; while(numIslands<v[id][1] && id<numSamples) id++; int idx1 = id-1; int idx2 = id; double m = (v[idx2][2]-v[idx1][1])/(v[idx2][1]-v[idx1][1]); double c = v[idx2][2]-(m*v[idx2][1]); // y = nodes/sec double y = ((m*numIslands)+c); for (int d=3;d<=n*n;d++){ uint64_t arrayTotal[677]={0}; //total nodes for depth , for branching factor=b totalNodes(arrayTotal, numIslands,1,d); uint64_t nodeCount[677]={0}; uint64_t sum = 0; for (int i=0;i<=numIslands;i++){ if (arrayTotal[i]!=0){ if((sum >= (1LL<<63))&&(arrayTotal[i] >= (1LL<<63))){ maxDepth=max(d-1,3); if((time_t)t<=(time_t)0.5 && n>=20){ maxDepth = 2; } return; } sum += arrayTotal[i]; nodeCount[i] = sum; } } uint64_t totalTnodes = (t-(t/15)) * y; //check this equals sign maxDepth = d-1; if(totalTnodes<=(sqrt(nodeCount[numIslands]))){ break; } } } int main(){ char *x = (char*)malloc(sizeof(char)*26*26); ifstream input; input.open("input.txt"); input>>n; input>>p; input>>t; string board; for (int i=0;i<n;i++){ input >> x; for (int j=0;j<n;j++){ board += x[j]; if (x[j]=='*') star++; } } input.close(); vector <array<uint32_t,3>> childIlands = vector<array<uint32_t,3>>(); uint32_t childIlandsSize = 0; getChildren(board, childIlands,&childIlandsSize); setDepth(childIlandsSize); initGame(board); ofstream output; output.open("output.txt"); ofstream output1; output1.open("score.txt"); output1<<bestSize<<endl; output1.close(); output<<char('A'+bestState[1])<<bestState[0]+1<<endl; for (int i=0;i<n;i++){ for (int j=0;j<n;j++){ output <<board[i*n+j]; } output<<endl; } output.close(); ofstream temp; temp.open("temp.txt"); temp<<n<<endl; temp<<childIlandsSize<<endl; temp<<maxDepth<<endl; temp<<count1<<endl; temp<<leaves<<endl; temp<<saved<<endl; temp<<savedIlands<<endl; temp<<prune<<endl; temp.close(); return 0; }
25.733042
118
0.519303
[ "vector" ]
2a90371429cfb613f7a13414665d7256d2c47fc9
13,784
cpp
C++
source/ConeTraceState.cpp
RobertBeckebans/CVCT_Vulkan
edd8e9865f126ffbdf474a6e419d46efc4c7f267
[ "MIT" ]
null
null
null
source/ConeTraceState.cpp
RobertBeckebans/CVCT_Vulkan
edd8e9865f126ffbdf474a6e419d46efc4c7f267
[ "MIT" ]
null
null
null
source/ConeTraceState.cpp
RobertBeckebans/CVCT_Vulkan
edd8e9865f126ffbdf474a6e419d46efc4c7f267
[ "MIT" ]
1
2021-04-09T09:20:20.000Z
2021-04-09T09:20:20.000Z
#include "PipelineStates.h" #include "VCTPipelineDefines.h" #include "SwapChain.h" #include "VulkanCore.h" #include "Shader.h" #include "DataTypes.h" #include "AnisotropicVoxelTexture.h" struct Parameter { SwapChain* swapchain; }; void BuildCommandBufferConeTracerState( RenderState* renderstate, VkCommandPool commandpool, VulkanCore* core, uint32_t framebufferCount, VkFramebuffer* framebuffers, BYTE* parameters) { uint32_t width = core->GetSwapChain()->m_width; uint32_t height = core->GetSwapChain()->m_height; RenderState* renderState = renderstate; VkDevice device = core->GetViewDevice(); //////////////////////////////////////////////////////////////////////////////// // Rebuild the parameters //////////////////////////////////////////////////////////////////////////////// SwapChain* swapchain = ((Parameter*)parameters)->swapchain; //////////////////////////////////////////////////////////////////////////////// // Rebuild the command buffers //////////////////////////////////////////////////////////////////////////////// renderState->m_commandBufferCount = framebufferCount; renderState->m_commandBuffers = (VkCommandBuffer*)malloc(sizeof(VkCommandBuffer)*renderState->m_commandBufferCount); for (uint32_t i = 0; i < renderState->m_commandBufferCount; i++) renderState->m_commandBuffers[i] = VKTools::Initializers::CreateCommandBuffer(commandpool, device, VK_COMMAND_BUFFER_LEVEL_PRIMARY, false); //////////////////////////////////////////////////////////////////////////////// // Record command buffer //////////////////////////////////////////////////////////////////////////////// VkCommandBufferBeginInfo cmdBufInfo = {}; cmdBufInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; cmdBufInfo.pNext = NULL; VkImageSubresourceRange srRange = {}; srRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; srRange.baseMipLevel = 0; srRange.levelCount = 1; srRange.baseArrayLayer = 0; srRange.layerCount = 1; for (uint32_t i = 0; i < renderState->m_commandBufferCount; i++) { VK_CHECK_RESULT(vkBeginCommandBuffer(renderState->m_commandBuffers[i], &cmdBufInfo)); vkCmdResetQueryPool(renderState->m_commandBuffers[i], renderState->m_queryPool, 0, 4); vkCmdWriteTimestamp(renderState->m_commandBuffers[i], VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, renderState->m_queryPool, 0); // Set image layout to write VKTools::SetImageLayout( renderState->m_commandBuffers[i], swapchain->m_images[i], VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, srRange); vkCmdBindPipeline(renderState->m_commandBuffers[i], VK_PIPELINE_BIND_POINT_COMPUTE, renderState->m_pipelines[0]); vkCmdBindDescriptorSets(renderState->m_commandBuffers[i], VK_PIPELINE_BIND_POINT_COMPUTE, renderState->m_pipelineLayout, 0, 1, &renderState->m_descriptorSets[i], 0, 0); uint32_t dispatchX = (uint32_t)glm::ceil((float)swapchain->m_width / 32.0f); uint32_t dispatchY = (uint32_t)glm::ceil((float)swapchain->m_height / 32.0f); vkCmdDispatch(renderState->m_commandBuffers[i], dispatchX, dispatchY, 1); // Set image layout to read VKTools::SetImageLayout( renderState->m_commandBuffers[i], swapchain->m_images[i], VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_PRESENT_SRC_KHR, srRange); vkCmdWriteTimestamp(renderState->m_commandBuffers[i], VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, renderState->m_queryPool, 1); vkEndCommandBuffer(renderState->m_commandBuffers[i]); } } void CreateConeTraceState( RenderState& renderState, uint32_t framebufferCount, VulkanCore* core, VkCommandPool commandPool, SwapChain* swapchain, AnisotropicVoxelTexture* avts ) { uint32_t width = swapchain->m_width; uint32_t height = swapchain->m_height; VkDevice device = core->GetViewDevice(); //////////////////////////////////////////////////////////////////////////////// // Create queries //////////////////////////////////////////////////////////////////////////////// renderState.m_queryCount = 4; renderState.m_queryResults = (uint64_t*)malloc(sizeof(uint64_t)*renderState.m_queryCount); memset(renderState.m_queryResults, 0, sizeof(uint64_t)*renderState.m_queryCount); // Create query pool VkQueryPoolCreateInfo queryPoolInfo = {}; queryPoolInfo.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO; queryPoolInfo.queryType = VK_QUERY_TYPE_TIMESTAMP; queryPoolInfo.queryCount = renderState.m_queryCount; VK_CHECK_RESULT(vkCreateQueryPool(device, &queryPoolInfo, NULL, &renderState.m_queryPool)); //////////////////////////////////////////////////////////////////////////////// // Create the pipelineCache //////////////////////////////////////////////////////////////////////////////// if (renderState.m_pipelineCache == VK_NULL_HANDLE) { // create a default pipelinecache VkPipelineCacheCreateInfo pipelineCacheCreateInfo = {}; pipelineCacheCreateInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO; VK_CHECK_RESULT(vkCreatePipelineCache(device, &pipelineCacheCreateInfo, NULL, &renderState.m_pipelineCache)); } //////////////////////////////////////////////////////////////////////////////// // set framebuffers //////////////////////////////////////////////////////////////////////////////// renderState.m_framebufferCount = 0; renderState.m_framebuffers = NULL; //////////////////////////////////////////////////////////////////////////////// // Create semaphores //////////////////////////////////////////////////////////////////////////////// if (!renderState.m_semaphores) { renderState.m_semaphoreCount = 1; renderState.m_semaphores = (VkSemaphore*)malloc(sizeof(VkSemaphore)*renderState.m_semaphoreCount); VkSemaphoreCreateInfo semInfo = VKTools::Initializers::SemaphoreCreateInfo(); for (uint32_t i = 0; i < renderState.m_semaphoreCount; i++) vkCreateSemaphore(device, &semInfo, NULL, &renderState.m_semaphores[i]); } //////////////////////////////////////////////////////////////////////////////// // Create the Uniform Data //////////////////////////////////////////////////////////////////////////////// if (!renderState.m_uniformData) { renderState.m_uniformDataCount = 1; renderState.m_uniformData = (UniformData*)malloc(sizeof(UniformData) * renderState.m_uniformDataCount); VKTools::CreateBuffer(core, device, VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, sizeof(ConeTracerUBOComp), NULL, &renderState.m_uniformData[0].m_buffer, &renderState.m_uniformData[0].m_memory, &renderState.m_uniformData[0].m_descriptor); } //////////////////////////////////////////////////////////////////////////////// // Create the descriptorlayout //////////////////////////////////////////////////////////////////////////////// if (!renderState.m_descriptorLayouts) { renderState.m_descriptorLayoutCount = 1; renderState.m_descriptorLayouts = (VkDescriptorSetLayout*)malloc(sizeof(VkDescriptorSetLayout)*renderState.m_descriptorLayoutCount); //dynamic descriptorset VkDescriptorSetLayoutBinding layoutBinding[FORWARDRENDER_DESCRIPTOR_COUNT]; // Binding 0 : diffuse texture sampled image layoutBinding[CONETRACER_DESCRIPTOR_VOXELGRID] = { CONETRACER_DESCRIPTOR_VOXELGRID, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL }; // Binding 1 : uniform buffer layoutBinding[CONETRACER_DESCRIPTOR_BUFFER_COMP] = { CONETRACER_DESCRIPTOR_BUFFER_COMP, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL }; // Binding 2 : framebuffer image to write layoutBinding[CONETRACER_DESCRIPTOR_FRAMEBUFFER] = { CONETRACER_DESCRIPTOR_FRAMEBUFFER, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_COMPUTE_BIT, NULL }; // set the createinfo VkDescriptorSetLayoutCreateInfo descriptorLayout = VKTools::Initializers::DescriptorSetLayoutCreateInfo(0, CONETRACER_DESCRIPTOR_COUNT, layoutBinding); VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, NULL, &renderState.m_descriptorLayouts[0])); } //////////////////////////////////////////////////////////////////////////////// // Create pipeline layout //////////////////////////////////////////////////////////////////////////////// if (!renderState.m_pipelineLayout) { VkPipelineLayoutCreateInfo pipelineLayoutCreateInfo = VKTools::Initializers::PipelineLayoutCreateInfo(0, 1, &renderState.m_descriptorLayouts[0]); VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pipelineLayoutCreateInfo, NULL, &renderState.m_pipelineLayout)); } //////////////////////////////////////////////////////////////////////////////// // Create descriptor pool //////////////////////////////////////////////////////////////////////////////// if (!renderState.m_descriptorPool) { VkDescriptorPoolSize poolSize[CONETRACER_DESCRIPTOR_COUNT]; poolSize[MIPMAPPER_DESCRIPTOR_VOXELGRID] = { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1 * framebufferCount }; poolSize[MIPMAPPER_DESCRIPTOR_IMAGE_VOXELGRID] = { VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 1 * framebufferCount }; poolSize[CONETRACER_DESCRIPTOR_FRAMEBUFFER] = { VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1 * framebufferCount }; VkDescriptorPoolCreateInfo descriptorPoolCreateInfo = VKTools::Initializers::DescriptorPoolCreateInfo(0, framebufferCount, CONETRACER_DESCRIPTOR_COUNT, poolSize); //create the descriptorPool VK_CHECK_RESULT(vkCreateDescriptorPool(device, &descriptorPoolCreateInfo, NULL, &renderState.m_descriptorPool)); } //////////////////////////////////////////////////////////////////////////////// // Create the descriptor set //////////////////////////////////////////////////////////////////////////////// if (!renderState.m_descriptorSets) { renderState.m_descriptorSetCount = framebufferCount; renderState.m_descriptorSets = (VkDescriptorSet*)malloc(renderState.m_descriptorSetCount * sizeof(VkDescriptorSet)); VkDescriptorSetAllocateInfo descriptorSetAllocateInfo = VKTools::Initializers::DescriptorSetAllocateInfo(renderState.m_descriptorPool, 1, &renderState.m_descriptorLayouts[0]); for(uint32_t i = 0; i < framebufferCount;i++) VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &descriptorSetAllocateInfo, &renderState.m_descriptorSets[i])); /////////////////////////////////////////////////////// ///// Set/Update the image and uniform buffer descriptorsets /////////////////////////////////////////////////////// VkDescriptorImageInfo descriptors[1]; //for (uint32_t i = 0; i < VoxelDirections::NUM_DIRECTIONS; i++) { descriptors[0].imageLayout = avts[0].m_imageLayout; descriptors[0].imageView = avts[0].m_descriptor[0].imageView; descriptors[0].sampler = avts[0].m_conetraceSampler; } for (uint32_t i = 0; i < framebufferCount; i++) { // Bind the 3D voxel textures { VkWriteDescriptorSet wds = {}; wds.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; wds.pNext = NULL; wds.dstSet = renderState.m_descriptorSets[i]; wds.dstBinding = CONETRACER_DESCRIPTOR_VOXELGRID; wds.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER; wds.descriptorCount = 1; wds.dstArrayElement = 0; wds.pImageInfo = descriptors; //update the descriptorset vkUpdateDescriptorSets(device, 1, &wds, 0, NULL); } // Bind the Uniform buffer { VkWriteDescriptorSet wds = {}; wds.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; wds.pNext = NULL; wds.dstSet = renderState.m_descriptorSets[i]; wds.dstBinding = CONETRACER_DESCRIPTOR_BUFFER_COMP; wds.dstArrayElement = 0; wds.descriptorCount = 1; wds.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER; wds.pImageInfo = NULL; wds.pBufferInfo = &renderState.m_uniformData[0].m_descriptor; wds.pTexelBufferView = NULL; vkUpdateDescriptorSets(device, 1, &wds, 0, NULL); } // Bind framebuffer image { VkWriteDescriptorSet wds = {}; wds.sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET; wds.pNext = NULL; wds.dstSet = renderState.m_descriptorSets[i]; wds.dstBinding = CONETRACER_DESCRIPTOR_FRAMEBUFFER; wds.descriptorType = VK_DESCRIPTOR_TYPE_STORAGE_IMAGE; wds.descriptorCount = 1; wds.dstArrayElement = 0; wds.pImageInfo = &swapchain->m_descriptors[i]; //update the descriptorset vkUpdateDescriptorSets(device, 1, &wds, 0, NULL); } } } /////////////////////////////////////////////////////// ///// Create the compute pipeline /////////////////////////////////////////////////////// if (!renderState.m_pipelines) { renderState.m_pipelineCount = 1; renderState.m_pipelines = (VkPipeline*)malloc(renderState.m_pipelineCount * sizeof(VkPipeline)); // Create pipeline VkComputePipelineCreateInfo computePipelineCreateInfo = VKTools::Initializers::ComputePipelineCreateInfo(renderState.m_pipelineLayout, VK_FLAGS_NONE); // Shaders are loaded from the SPIR-V format, which can be generated from glsl Shader shaderStage; shaderStage = VKTools::LoadShader("shaders/conetrace.comp.spv", "main", device, VK_SHADER_STAGE_COMPUTE_BIT); computePipelineCreateInfo.stage = shaderStage.m_shaderStage; VK_CHECK_RESULT(vkCreateComputePipelines(device, renderState.m_pipelineCache, 1, &computePipelineCreateInfo, NULL, &renderState.m_pipelines[0])); } //////////////////////////////////////////////////////////////////////////////// // Build command buffers //////////////////////////////////////////////////////////////////////////////// Parameter* parameter; parameter = (Parameter*)malloc(sizeof(Parameter)); parameter->swapchain = swapchain; renderState.m_cmdBufferParameters = (BYTE*)parameter; renderState.m_CreateCommandBufferFunc = &BuildCommandBufferConeTracerState; renderState.m_CreateCommandBufferFunc(&renderState, commandPool, core, framebufferCount, NULL, renderState.m_cmdBufferParameters); }
44.753247
177
0.653439
[ "3d" ]
2a91d610eba66aac81dedc767e4e0400eba4dc34
40,616
cpp
C++
amd_tressfx_vulkan/src/TressFXShortCutVulkan.cpp
vlj/TressFX
83678bf6a946ecbdd9643965e79ed20b35039f77
[ "MIT" ]
1
2018-08-06T22:31:28.000Z
2018-08-06T22:31:28.000Z
amd_tressfx_vulkan/src/TressFXShortCutVulkan.cpp
0x6E745C/TressFX
83678bf6a946ecbdd9643965e79ed20b35039f77
[ "MIT" ]
null
null
null
amd_tressfx_vulkan/src/TressFXShortCutVulkan.cpp
0x6E745C/TressFX
83678bf6a946ecbdd9643965e79ed20b35039f77
[ "MIT" ]
1
2019-03-16T11:40:23.000Z
2019-03-16T11:40:23.000Z
//-------------------------------------------------------------------------------------- // File: TressFXShortCut.cpp // // TressFX ShortCut method. // // // Copyright (c) 2016 Advanced Micro Devices, Inc. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // //-------------------------------------------------------------------------------------- #include "TressFXShortCutVulkan.h" #include "AMD_Types.h" #include "TressFXPrecompiledShadersVulkan.h" #include "UtilVulkan.h" #include <vector> // unreferenced formal parameter #pragma warning(disable : 4100) // Constants must match in TressFXRender.hlsl // Clear value for depths resource #define SHORTCUT_INITIAL_DEPTH 0x3f800000 // Number of depth layers to use. 2 or 3 supported. #define SHORTCUT_NUM_DEPTHS 3 // Compute source color as weighted average of front fragments, vs blending in order. #define SHORTCUT_WEIGHTED_AVERAGE 1 // Output color deterministically when fragments have the same depth. Requires additional // clear of colors resource. #define SHORTCUT_DETERMINISTIC 1 namespace AMD { VkResult GPUOnlyStructuredBuffer::Create(VkDevice pvkDevice, uint32_t structSize, uint32_t structCount) { VkResult vr; // Per-pixel Linked List (PPLL) buffer VkBufferCreateInfo BufferDesc{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; BufferDesc.size = structCount * structSize; BufferDesc.usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; AMD_CHECKED_VULKAN_CALL(vkCreateBuffer(pvkDevice, &BufferDesc, NULL, &m_pBuffer)); m_pvkDevice = pvkDevice; return VK_SUCCESS; } void GPUOnlyStructuredBuffer::Destroy() { if (m_pBuffer) vkDestroyBuffer(m_pvkDevice, m_pBuffer, nullptr); } VkResult TressFXShortCut::CreateScreenSizedItems(VkDevice pvkDevice, int winWidth, int winHeight, VkPhysicalDeviceMemoryProperties memProperties) { m_pvkDevice = pvkDevice; VkResult vr; { VkImageCreateInfo accumInvAlphaInfo = getImageCreateInfo( VK_FORMAT_R16_SFLOAT, winWidth, winHeight, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT); AMD_CHECKED_VULKAN_CALL(vkCreateImage(pvkDevice, &accumInvAlphaInfo, nullptr, &m_pAccumInvAlphaTexture)); m_pAccumInvAlphaMemory = allocImageMemory(pvkDevice, m_pAccumInvAlphaTexture, memProperties); VkImageViewCreateInfo srDesc{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; srDesc.format = VK_FORMAT_R16_SFLOAT; srDesc.viewType = VK_IMAGE_VIEW_TYPE_2D; srDesc.subresourceRange.levelCount = 1; srDesc.subresourceRange.layerCount = 1; srDesc.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; srDesc.image = m_pAccumInvAlphaTexture; AMD_CHECKED_VULKAN_CALL( vkCreateImageView(pvkDevice, &srDesc, nullptr, &m_pAccumInvAlphaView)); } { VkImageCreateInfo fragmentDepthInfo = getImageCreateInfo(VK_FORMAT_R32_UINT, winWidth, winHeight, VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT, SHORTCUT_NUM_DEPTHS); AMD_CHECKED_VULKAN_CALL(vkCreateImage(pvkDevice, &fragmentDepthInfo, nullptr, &m_pFragmentDepthsTexture)); m_pFragmentDepthsMemory = allocImageMemory(pvkDevice, m_pFragmentDepthsTexture, memProperties); VkImageViewCreateInfo srDesc{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; srDesc.format = VK_FORMAT_R32_UINT; srDesc.viewType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; srDesc.subresourceRange.levelCount = 1; srDesc.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; srDesc.subresourceRange.layerCount = SHORTCUT_NUM_DEPTHS; srDesc.image = m_pFragmentDepthsTexture; AMD_CHECKED_VULKAN_CALL( vkCreateImageView(pvkDevice, &srDesc, nullptr, &m_pFragmentDepthsView)); } #if SHORTCUT_DETERMINISTIC && SHORTCUT_WEIGHTED_AVERAGE { VkImageCreateInfo fragmentColorInfo = getImageCreateInfo( VK_FORMAT_R16G16B16A16_SFLOAT, winWidth, winHeight, VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_INPUT_ATTACHMENT_BIT); AMD_CHECKED_VULKAN_CALL(vkCreateImage(pvkDevice, &fragmentColorInfo, nullptr, &m_pFragmentColorsTexture)); m_pFragmentColorsMemory = allocImageMemory(pvkDevice, m_pFragmentColorsTexture, memProperties); VkImageViewCreateInfo srDesc{VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; srDesc.format = VK_FORMAT_R16G16B16A16_SFLOAT; srDesc.viewType = VK_IMAGE_VIEW_TYPE_2D; srDesc.subresourceRange.levelCount = 1; srDesc.subresourceRange.layerCount = 1; srDesc.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; srDesc.image = m_pFragmentColorsTexture; AMD_CHECKED_VULKAN_CALL( vkCreateImageView(pvkDevice, &srDesc, nullptr, &m_pFragmentColorsView)); } #else m_FragmentColors.Create(pd3dDevice, 4 * SHORTCUT_NUM_DEPTHS, winWidth * winHeight); #endif return VK_SUCCESS; } void TressFXShortCut::DestroyScreenSizedItems() { AMD_SAFE_RELEASE(m_pFBRenderHair, vkDestroyFramebuffer, m_pvkDevice); AMD_SAFE_RELEASE(m_pFragmentColorsView, vkDestroyImageView, m_pvkDevice); AMD_SAFE_RELEASE(m_pFragmentDepthsView, vkDestroyImageView, m_pvkDevice); AMD_SAFE_RELEASE(m_pAccumInvAlphaView, vkDestroyImageView, m_pvkDevice); AMD_SAFE_RELEASE(m_pFragmentColorsMemory, vkFreeMemory, m_pvkDevice); AMD_SAFE_RELEASE(m_pFragmentDepthsMemory, vkFreeMemory, m_pvkDevice); AMD_SAFE_RELEASE(m_pAccumInvAlphaMemory, vkFreeMemory, m_pvkDevice); AMD_SAFE_RELEASE(m_pFragmentColorsTexture, vkDestroyImage, m_pvkDevice); AMD_SAFE_RELEASE(m_pFragmentDepthsTexture, vkDestroyImage, m_pvkDevice); AMD_SAFE_RELEASE(m_pAccumInvAlphaTexture, vkDestroyImage, m_pvkDevice); m_FragmentColors.Destroy(); } namespace { VkAttachmentDescription getAttachmentDescription( VkFormat format, VkAttachmentLoadOp loadOp, VkAttachmentStoreOp storeOp, VkImageLayout inoutLayout, VkAttachmentLoadOp stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE, VkAttachmentStoreOp stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE) { return {0, format, VK_SAMPLE_COUNT_1_BIT, loadOp, storeOp, stencilLoadOp, stencilStoreOp, inoutLayout, inoutLayout}; } VkRenderPass createRenderPass(VkDevice pvkDevice, VkFormat depthStencilFormat, VkFormat colorFormat) { VkRenderPassCreateInfo info{VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO}; const VkAttachmentDescription attachments[] = { // DS getAttachmentDescription(depthStencilFormat, VK_ATTACHMENT_LOAD_OP_LOAD, VK_ATTACHMENT_STORE_OP_STORE, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_DONT_CARE), // accumInvAlpha getAttachmentDescription(VK_FORMAT_R16_SFLOAT, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_DONT_CARE, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL), #if SHORTCUT_DETERMINISTIC && SHORTCUT_WEIGHTED_AVERAGE // FragmentColor getAttachmentDescription( VK_FORMAT_R16G16B16A16_SFLOAT, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_DONT_CARE, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL), #else // TODO #endif // Result getAttachmentDescription(colorFormat, VK_ATTACHMENT_LOAD_OP_LOAD, VK_ATTACHMENT_STORE_OP_STORE, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL), }; VkAttachmentReference depthStencil{0, VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL}; VkAttachmentReference accumInvAlpha{1, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; #if SHORTCUT_DETERMINISTIC && SHORTCUT_WEIGHTED_AVERAGE VkAttachmentReference FragmentColor{2, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; #else // TODO #endif VkAttachmentReference colorAttachment{3, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL}; VkAttachmentReference colorResolveInputAttachments[] = {{1, VK_IMAGE_LAYOUT_GENERAL}, {2, VK_IMAGE_LAYOUT_GENERAL}}; uint32_t untouchedAttachmentDepthResolve[] = {1}; uint32_t untouchedAttachmentColorFill[] = {1}; const VkSubpassDescription subpasses[] = { // Depth alpha {0, VK_PIPELINE_BIND_POINT_GRAPHICS, 0, nullptr, 1, &accumInvAlpha, nullptr, &depthStencil, 0, nullptr}, // Depth resolve {0, VK_PIPELINE_BIND_POINT_GRAPHICS, 0, nullptr, 0, nullptr, nullptr, &depthStencil, AMD_ARRAY_SIZE(untouchedAttachmentDepthResolve), untouchedAttachmentDepthResolve}, // Color fill {0, VK_PIPELINE_BIND_POINT_GRAPHICS, 0, nullptr, 1, &FragmentColor, nullptr, &depthStencil, AMD_ARRAY_SIZE(untouchedAttachmentColorFill), untouchedAttachmentColorFill}, // Color resolve {0, VK_PIPELINE_BIND_POINT_GRAPHICS, AMD_ARRAY_SIZE(colorResolveInputAttachments), colorResolveInputAttachments, 1, &colorAttachment, nullptr, &depthStencil, 0, nullptr}, }; const VkSubpassDependency dependencies[] = { // Depth alpha modifies fragment depth image while depth resolve reads it {0, 1, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_SHADER_WRITE_BIT | VK_ACCESS_SHADER_READ_BIT, VK_ACCESS_SHADER_READ_BIT, VK_DEPENDENCY_BY_REGION_BIT}, {0, 2, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, VK_DEPENDENCY_BY_REGION_BIT}, {0, 3, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT, VK_ACCESS_INPUT_ATTACHMENT_READ_BIT, VK_DEPENDENCY_BY_REGION_BIT}, // Depth resolve update depth attachement while color fill reads it {1, 2, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT, VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_READ_BIT, VK_DEPENDENCY_BY_REGION_BIT}, {1, 3, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, VK_DEPENDENCY_BY_REGION_BIT}, // color resolve consumes output from color fill {2, 3, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT | VK_ACCESS_COLOR_ATTACHMENT_READ_BIT, VK_ACCESS_INPUT_ATTACHMENT_READ_BIT, VK_DEPENDENCY_BY_REGION_BIT}, }; info.attachmentCount = AMD_ARRAY_SIZE(attachments); info.pAttachments = attachments; info.subpassCount = AMD_ARRAY_SIZE(subpasses); info.pSubpasses = subpasses; info.dependencyCount = AMD_ARRAY_SIZE(dependencies); info.pDependencies = dependencies; VkRenderPass result; vkCreateRenderPass(pvkDevice, &info, nullptr, &result); return result; } } //-------------------------------------------------------------------------------------- // // CreateRenderStateObjects // // Creates the pipelines for hair rendering // //-------------------------------------------------------------------------------------- VkResult TressFXShortCut::CreateRenderStateObjects(VkDevice pvkDevice, VkFormat depthStencilFormat, VkFormat colorFormat) { m_pRPRenderHair = createRenderPass(pvkDevice, depthStencilFormat, colorFormat); ShaderModule m_pPSDepthsAlpha(pvkDevice, depth_hair_data); ShaderModule m_pPSFillColors(pvkDevice, fillcolors_hair_data); ShaderModule render_hair_aa_strand_copiesModule(pvkDevice, render_hair_aa_strand_copies_vertex); const VkPipelineShaderStageCreateInfo renderHairAAStrandCopiesDepthsAlphaStage[2] = { getShaderStageCreateInfo(render_hair_aa_strand_copiesModule.m_shaderModule, VK_SHADER_STAGE_VERTEX_BIT, "main"), getShaderStageCreateInfo(m_pPSDepthsAlpha.m_shaderModule, VK_SHADER_STAGE_FRAGMENT_BIT, "main"), }; const VkGraphicsPipelineCreateInfo renderHairAAStrandCopiesDepthsAlphaDesc = CommonPipelineState::getBasePipelineCreateInfo( &CommonPipelineState::m_pLayoutHair, &CommonPipelineState::DepthTestEnabledNoDepthWritesStencilWriteIncrementDesc, &CommonPipelineState::m_pDepthWritesToColor_BS, &CommonPipelineState::inputAssemblyTriangle, renderHairAAStrandCopiesDepthsAlphaStage, m_depthPassPipelineLayout, m_pRPRenderHair, 0); const VkPipelineShaderStageCreateInfo renderHairAAStrandCopiesFillColorsStage[2] = { getShaderStageCreateInfo(render_hair_aa_strand_copiesModule.m_shaderModule, VK_SHADER_STAGE_VERTEX_BIT, "main"), getShaderStageCreateInfo(m_pPSFillColors.m_shaderModule, VK_SHADER_STAGE_FRAGMENT_BIT, "main"), }; const VkGraphicsPipelineCreateInfo renderHairAAStrandCopiesFillColorsDesc = CommonPipelineState::getBasePipelineCreateInfo( &CommonPipelineState::m_pLayoutHair, #if SHORTCUT_DETERMINISTIC && SHORTCUT_WEIGHTED_AVERAGE &CommonPipelineState::DepthTestEnabledNoDepthWritesStencilWriteIncrementDesc, &CommonPipelineState::m_pSum_BS, #else &m_pDepthTestEnabledNoDepthWritesStencilWriteIncrement_DSS, &m_pNoWrites_BS, #endif &CommonPipelineState::inputAssemblyTriangle, renderHairAAStrandCopiesFillColorsStage, m_colorPassPipelineLayout, m_pRPRenderHair, 2); ShaderModule RenderHairAAVertexShader(pvkDevice, render_hair_aa_vertex); const VkPipelineShaderStageCreateInfo renderHairAADepthsAlphaStage[2] = { getShaderStageCreateInfo(RenderHairAAVertexShader.m_shaderModule, VK_SHADER_STAGE_VERTEX_BIT, "main"), getShaderStageCreateInfo(m_pPSDepthsAlpha.m_shaderModule, VK_SHADER_STAGE_FRAGMENT_BIT, "main"), }; const VkGraphicsPipelineCreateInfo renderHairAADepthsAlphaDesc = CommonPipelineState::getBasePipelineCreateInfo( &CommonPipelineState::m_pLayoutHair, &CommonPipelineState::DepthTestEnabledNoDepthWritesStencilWriteIncrementDesc, &CommonPipelineState::m_pDepthWritesToColor_BS, &CommonPipelineState::inputAssemblyTriangle, renderHairAADepthsAlphaStage, m_depthPassPipelineLayout, m_pRPRenderHair, 0); const VkPipelineShaderStageCreateInfo renderHairAAFillColorsStage[2] = { getShaderStageCreateInfo(RenderHairAAVertexShader.m_shaderModule, VK_SHADER_STAGE_VERTEX_BIT, "main"), getShaderStageCreateInfo(m_pPSFillColors.m_shaderModule, VK_SHADER_STAGE_FRAGMENT_BIT, "main"), }; const VkGraphicsPipelineCreateInfo renderHairAAFillColorsDesc = CommonPipelineState::getBasePipelineCreateInfo( &CommonPipelineState::m_pLayoutHair, #if SHORTCUT_DETERMINISTIC && SHORTCUT_WEIGHTED_AVERAGE &CommonPipelineState::DepthTestEnabledNoDepthWritesStencilWriteIncrementDesc, &CommonPipelineState::m_pSum_BS, #else &m_pDepthTestEnabledNoDepthWritesStencilWriteIncrement_DSS, &m_pNoWrites_BS, #endif &CommonPipelineState::inputAssemblyTriangle, renderHairAAFillColorsStage, m_colorPassPipelineLayout, m_pRPRenderHair, 2); ShaderModule renderHairStrandCopiesVertexModule(pvkDevice, render_hair_strand_copies_vertex); const VkPipelineShaderStageCreateInfo renderHairStrandCopiesDepthsAlphaStage[2] = { getShaderStageCreateInfo(renderHairStrandCopiesVertexModule.m_shaderModule, VK_SHADER_STAGE_VERTEX_BIT, "main"), getShaderStageCreateInfo(m_pPSDepthsAlpha.m_shaderModule, VK_SHADER_STAGE_FRAGMENT_BIT, "main"), }; const VkGraphicsPipelineCreateInfo renderHairStrandCopiesDepthsAlphaDesc = CommonPipelineState::getBasePipelineCreateInfo( &CommonPipelineState::m_pLayoutHair, &CommonPipelineState::DepthTestEnabledNoDepthWritesStencilWriteIncrementDesc, &CommonPipelineState::m_pDepthWritesToColor_BS, &CommonPipelineState::inputAssemblyTriangle, renderHairStrandCopiesDepthsAlphaStage, m_depthPassPipelineLayout, m_pRPRenderHair, 0); const VkPipelineShaderStageCreateInfo renderHairStrandCopiesFillColorsStage[2] = { getShaderStageCreateInfo(renderHairStrandCopiesVertexModule.m_shaderModule, VK_SHADER_STAGE_VERTEX_BIT, "main"), getShaderStageCreateInfo(m_pPSFillColors.m_shaderModule, VK_SHADER_STAGE_FRAGMENT_BIT, "main"), }; const VkGraphicsPipelineCreateInfo renderHairStrandCopiesFillColorsDesc = CommonPipelineState::getBasePipelineCreateInfo( &CommonPipelineState::m_pLayoutHair, #if SHORTCUT_DETERMINISTIC && SHORTCUT_WEIGHTED_AVERAGE &CommonPipelineState::DepthTestEnabledNoDepthWritesStencilWriteIncrementDesc, &CommonPipelineState::m_pSum_BS, #else &m_pDepthTestEnabledNoDepthWritesStencilWriteIncrement_DSS, &m_pNoWrites_BS, #endif &CommonPipelineState::inputAssemblyTriangle, renderHairStrandCopiesFillColorsStage, m_colorPassPipelineLayout, m_pRPRenderHair, 2); ShaderModule renderHairVertexModule(pvkDevice, render_hair_vertex); const VkPipelineShaderStageCreateInfo renderHairDepthsAlphaStage[2] = { getShaderStageCreateInfo(renderHairVertexModule.m_shaderModule, VK_SHADER_STAGE_VERTEX_BIT, "main"), getShaderStageCreateInfo(m_pPSDepthsAlpha.m_shaderModule, VK_SHADER_STAGE_FRAGMENT_BIT, "main"), }; const VkGraphicsPipelineCreateInfo renderHairDepthsAlphaDesc = CommonPipelineState::getBasePipelineCreateInfo( &CommonPipelineState::m_pLayoutHair, &CommonPipelineState::DepthTestEnabledNoDepthWritesStencilWriteIncrementDesc, &CommonPipelineState::m_pDepthWritesToColor_BS, &CommonPipelineState::inputAssemblyTriangle, renderHairDepthsAlphaStage, m_depthPassPipelineLayout, m_pRPRenderHair, 0); const VkPipelineShaderStageCreateInfo renderHairFillColorsStage[2] = { getShaderStageCreateInfo(renderHairVertexModule.m_shaderModule, VK_SHADER_STAGE_VERTEX_BIT, "main"), getShaderStageCreateInfo(m_pPSFillColors.m_shaderModule, VK_SHADER_STAGE_FRAGMENT_BIT, "main"), }; const VkGraphicsPipelineCreateInfo renderHairFillColorsDesc = CommonPipelineState::getBasePipelineCreateInfo( &CommonPipelineState::m_pLayoutHair, #if SHORTCUT_DETERMINISTIC && SHORTCUT_WEIGHTED_AVERAGE &CommonPipelineState::DepthTestEnabledNoDepthWritesStencilWriteIncrementDesc, &CommonPipelineState::m_pSum_BS, #else &m_pDepthTestEnabledNoDepthWritesStencilWriteIncrement_DSS, &m_pNoWrites_BS, #endif &CommonPipelineState::inputAssemblyTriangle, renderHairFillColorsStage, m_colorPassPipelineLayout, m_pRPRenderHair, 2); // Resolve depth ShaderModule renderQuadVS(pvkDevice, pass2_vertex); ShaderModule depth_resolve(pvkDevice, resolve_depth); const VkPipelineShaderStageCreateInfo depthResolveStage[2] = { getShaderStageCreateInfo(renderQuadVS.m_shaderModule, VK_SHADER_STAGE_VERTEX_BIT, "main"), getShaderStageCreateInfo(depth_resolve.m_shaderModule, VK_SHADER_STAGE_FRAGMENT_BIT, "main"), }; const VkGraphicsPipelineCreateInfo depthResolveDesc = CommonPipelineState::getBasePipelineCreateInfo( &CommonPipelineState::m_pLayoutQuad, &CommonPipelineState::m_pDepthWriteEnabledStencilTestLess_DSS, &CommonPipelineState::ColorWritesOff, &CommonPipelineState::inputAssemblyTriangle, depthResolveStage, m_depthPassPipelineLayout, m_pRPRenderHair, 1); // Resolve Color ShaderModule color_resolve(pvkDevice, resolvecolors); const VkPipelineShaderStageCreateInfo colorResolveStage[2] = { getShaderStageCreateInfo(renderQuadVS.m_shaderModule, VK_SHADER_STAGE_VERTEX_BIT, "main"), getShaderStageCreateInfo(color_resolve.m_shaderModule, VK_SHADER_STAGE_FRAGMENT_BIT, "main"), }; const VkGraphicsPipelineCreateInfo colorResolveDesc = CommonPipelineState::getBasePipelineCreateInfo( &CommonPipelineState::m_pLayoutQuad, &CommonPipelineState::DepthTestDisabledStencilTestLessDSS, &CommonPipelineState::m_pResolveColor_BS, &CommonPipelineState::inputAssemblyTriangle, colorResolveStage, m_colorPassPipelineLayout, m_pRPRenderHair, 3); VkGraphicsPipelineCreateInfo pipelinesDesc[] = { renderHairAAStrandCopiesDepthsAlphaDesc, renderHairAAStrandCopiesFillColorsDesc, renderHairAADepthsAlphaDesc, renderHairAAFillColorsDesc, renderHairStrandCopiesDepthsAlphaDesc, renderHairStrandCopiesFillColorsDesc, renderHairDepthsAlphaDesc, renderHairFillColorsDesc, depthResolveDesc, colorResolveDesc}; VkPipeline pipelines[AMD_ARRAY_SIZE(pipelinesDesc)]; VkResult vr; AMD_CHECKED_VULKAN_CALL(vkCreateGraphicsPipelines(pvkDevice, VK_NULL_HANDLE, AMD_ARRAY_SIZE(pipelinesDesc), pipelinesDesc, nullptr, pipelines)); m_pPLRenderHairAAStrandCopiesDepthsAlpha = pipelines[0]; m_pPLRenderHairAAStrandCopiesFillColors = pipelines[1]; m_pPLRenderHairAADepthsAlpha = pipelines[2]; m_pPLRenderHairAAFillColors = pipelines[3]; m_pPLRenderHairStrandCopiesDepthsAlpha = pipelines[4]; m_pPLRenderHairStrandCopiesFillColors = pipelines[5]; m_pPLRenderHairDepthsAlpha = pipelines[6]; m_pPLRenderHairFillColors = pipelines[7]; m_pPLDepthResolve = pipelines[8]; m_pPLColorResolve = pipelines[9]; return VK_SUCCESS; } //-------------------------------------------------------------------------------------- // // CreateLayouts // // Creates the descriptors set and pipeline layouts. // //-------------------------------------------------------------------------------------- VkResult TressFXShortCut::CreateLayouts(VkDevice pvkDevice, VkDescriptorSetLayout mesh_layout, VkSampler noiseSamplerRef, VkSampler shadowSamplerRef) { VkResult vr; { VkDescriptorSetLayoutCreateInfo info{ VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; VkDescriptorSetLayoutBinding bindings[] = { // TressFX parameters {IDSRV_CONSTANTS_BUFFER, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT}, // Fragment depth {IDSRV_HAIR_FRAGMENT_DEPTHS, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_FRAGMENT_BIT}, // Sampler for noise texture in VS {IDSRV_NOISE_SAMPLER, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_VERTEX_BIT, &noiseSamplerRef}, // Noise texture {IDSRV_NOISEMAP, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1, VK_SHADER_STAGE_VERTEX_BIT}, }; info.bindingCount = AMD_ARRAY_SIZE(bindings); info.pBindings = bindings; AMD_CHECKED_VULKAN_CALL( vkCreateDescriptorSetLayout(pvkDevice, &info, nullptr, &m_pSLDepthAlpha)); } { VkDescriptorSetLayoutCreateInfo info{ VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO}; VkDescriptorSetLayoutBinding bindings[] = { // TressFX parameters {IDSRV_CONSTANTS_BUFFER, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 1, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT}, // Fragment depth {IDSRV_HAIR_FRAGMENT_DEPTHS, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, VK_SHADER_STAGE_FRAGMENT_BIT}, // Sampler for noise texture in VS {IDSRV_NOISE_SAMPLER, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_VERTEX_BIT, &noiseSamplerRef}, // Noise texture {IDSRV_NOISEMAP, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1, VK_SHADER_STAGE_VERTEX_BIT}, // Hair shadow {IDSRV_HAIRSM, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 1, VK_SHADER_STAGE_FRAGMENT_BIT}, // Hair shadow sampler {IDSRV_SHADOW_SAMPLER, VK_DESCRIPTOR_TYPE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, &shadowSamplerRef}, // Fragment color #if SHORTCUT_DETERMINISTIC && SHORTCUT_WEIGHTED_AVERAGE {IDSRV_HAIR_FRAGMENT_COLORS, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1, VK_SHADER_STAGE_FRAGMENT_BIT}, #else // TODO #endif // inv alpha accum {IDSRV_HAIR_ACCUM_INV_ALPHA, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 1, VK_SHADER_STAGE_FRAGMENT_BIT}, }; info.bindingCount = AMD_ARRAY_SIZE(bindings); info.pBindings = bindings; AMD_CHECKED_VULKAN_CALL( vkCreateDescriptorSetLayout(pvkDevice, &info, nullptr, &m_pSLColors)); } { VkPipelineLayoutCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; VkDescriptorSetLayout set_layout[] = {m_pSLDepthAlpha, mesh_layout}; info.setLayoutCount = AMD_ARRAY_SIZE(set_layout); info.pSetLayouts = set_layout; AMD_CHECKED_VULKAN_CALL(vkCreatePipelineLayout(pvkDevice, &info, nullptr, &m_depthPassPipelineLayout)); } { VkPipelineLayoutCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; VkDescriptorSetLayout set_layout[] = {m_pSLColors, mesh_layout}; info.setLayoutCount = AMD_ARRAY_SIZE(set_layout); info.pSetLayouts = set_layout; AMD_CHECKED_VULKAN_CALL(vkCreatePipelineLayout(pvkDevice, &info, nullptr, &m_colorPassPipelineLayout)); } return VK_SUCCESS; } //-------------------------------------------------------------------------------------- // // CreateFramebuffer // // Creates the framebuffer for every pass of the shortcut algorithm // //-------------------------------------------------------------------------------------- VkResult TressFXShortCut::CreateFramebuffer(VkDevice pvkDevice, VkImageView depthStencilView, VkImageView colorView, uint32_t width, uint32_t height) { VkResult vr; { VkFramebufferCreateInfo info{VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO}; info.renderPass = m_pRPRenderHair; info.height = height; info.width = width; info.layers = 1; #if SHORTCUT_DETERMINISTIC && SHORTCUT_WEIGHTED_AVERAGE VkImageView attachments[] = {depthStencilView, m_pAccumInvAlphaView, m_pFragmentColorsView, colorView}; info.attachmentCount = AMD_ARRAY_SIZE(attachments); info.pAttachments = attachments; #else // TODO #endif AMD_CHECKED_VULKAN_CALL(vkCreateFramebuffer(pvkDevice, &info, nullptr, &m_pFBRenderHair)); } return VK_SUCCESS; } //-------------------------------------------------------------------------------------- // // AllocateAndPopulateSets // // Allocate descriptor set and fills them // //-------------------------------------------------------------------------------------- VkResult TressFXShortCut::AllocateAndPopulateSets(VkDevice pvkDevice, VkBuffer configBuffer, uint64_t configBufferSize, VkImageView noiseMap, VkImageView hairShadowMap) { VkResult vr; { VkDescriptorPoolCreateInfo info{VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO}; VkDescriptorPoolSize sizes[] = {{VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, 2}, {VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 5}, {VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, 5}, {VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, 2}, {VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER, 1}, {VK_DESCRIPTOR_TYPE_SAMPLER, 5}}; info.maxSets = 2; info.poolSizeCount = AMD_ARRAY_SIZE(sizes); info.pPoolSizes = sizes; AMD_CHECKED_VULKAN_CALL( vkCreateDescriptorPool(pvkDevice, &info, nullptr, &m_pDPShortcutPool)); } { VkDescriptorSetLayout setLayout[] = {m_pSLDepthAlpha, m_pSLColors}; VkDescriptorSetAllocateInfo info{VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO}; info.descriptorPool = m_pDPShortcutPool; info.descriptorSetCount = AMD_ARRAY_SIZE(setLayout); info.pSetLayouts = setLayout; VkDescriptorSet sets[AMD_ARRAY_SIZE(setLayout)]; AMD_CHECKED_VULKAN_CALL(vkAllocateDescriptorSets(pvkDevice, &info, sets)); m_depthPassSet = sets[0]; m_colorPassSet = sets[1]; } VkDescriptorBufferInfo bufferdesc{configBuffer, 0, configBufferSize}; VkDescriptorImageInfo noise_descriptor{VK_NULL_HANDLE, noiseMap, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; VkDescriptorImageInfo hairSM_descriptor{VK_NULL_HANDLE, hairShadowMap, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; VkDescriptorImageInfo hairFragmentDepthsDescriptor{ VK_NULL_HANDLE, m_pFragmentDepthsView, VK_IMAGE_LAYOUT_GENERAL}; VkDescriptorImageInfo hairFragmentColorDescriptor{ VK_NULL_HANDLE, m_pFragmentColorsView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; VkDescriptorImageInfo hairAccumInvAlphaDescriptor{ VK_NULL_HANDLE, m_pAccumInvAlphaView, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL}; VkWriteDescriptorSet writes[] = { getWriteDescriptor(m_depthPassSet, IDSRV_CONSTANTS_BUFFER, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, &bufferdesc), getWriteDescriptor(m_depthPassSet, IDSRV_HAIR_FRAGMENT_DEPTHS, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &hairFragmentDepthsDescriptor), getWriteDescriptor(m_depthPassSet, IDSRV_NOISEMAP, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, &noise_descriptor), getWriteDescriptor(m_colorPassSet, IDSRV_CONSTANTS_BUFFER, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC, &bufferdesc), getWriteDescriptor(m_colorPassSet, IDSRV_HAIR_FRAGMENT_DEPTHS, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, &hairFragmentDepthsDescriptor), getWriteDescriptor(m_colorPassSet, IDSRV_NOISEMAP, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, &noise_descriptor), getWriteDescriptor(m_colorPassSet, IDSRV_HAIRSM, VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE, &hairSM_descriptor), getWriteDescriptor(m_colorPassSet, IDSRV_HAIR_FRAGMENT_COLORS, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, &hairFragmentColorDescriptor), getWriteDescriptor(m_colorPassSet, IDSRV_HAIR_ACCUM_INV_ALPHA, VK_DESCRIPTOR_TYPE_INPUT_ATTACHMENT, &hairAccumInvAlphaDescriptor), }; vkUpdateDescriptorSets(pvkDevice, AMD_ARRAY_SIZE(writes), writes, 0, nullptr); return VK_SUCCESS; } VkResult TressFXShortCut::OnCreateDevice( VkDevice pd3dDevice, int winWidth, int winHeight, VkDescriptorSetLayout mesh_layout, VkSampler noiseSamplerRef, VkSampler shadowSamplerRef, VkImageView depthStencilView, VkImageView colorView, VkBuffer configBuffer, uint64_t configBufferSize, VkImageView noiseMap, VkImageView hairShadowMap, VkPhysicalDeviceMemoryProperties memProperties, uint32_t width, uint32_t height, VkFormat depthStencilFormat, VkFormat colorFormat) { VkResult vr; AMD_CHECKED_VULKAN_CALL( CreateScreenSizedItems(pd3dDevice, winWidth, winHeight, memProperties)); AMD_CHECKED_VULKAN_CALL( CreateLayouts(pd3dDevice, mesh_layout, noiseSamplerRef, shadowSamplerRef)); AMD_CHECKED_VULKAN_CALL(CreateRenderStateObjects(pd3dDevice, depthStencilFormat, colorFormat)); AMD_CHECKED_VULKAN_CALL( CreateFramebuffer(pd3dDevice, depthStencilView, colorView, width, height)); AMD_CHECKED_VULKAN_CALL(AllocateAndPopulateSets(pd3dDevice, configBuffer, configBufferSize, noiseMap, hairShadowMap)) return VK_SUCCESS; } VkResult TressFXShortCut::OnResizedSwapChain(VkDevice pd3dDevice, int winWidth, int winHeight, VkPhysicalDeviceMemoryProperties memProperties) { DestroyScreenSizedItems(); VkResult vr; AMD_CHECKED_VULKAN_CALL( CreateScreenSizedItems(pd3dDevice, winWidth, winHeight, memProperties)); return VK_SUCCESS; } void TressFXShortCut::OnDestroy(bool destroyShaders) { DestroyScreenSizedItems(); if (destroyShaders) { AMD_SAFE_RELEASE(m_pPLRenderHairAAStrandCopiesDepthsAlpha, vkDestroyPipeline, m_pvkDevice); AMD_SAFE_RELEASE(m_pPLRenderHairAAStrandCopiesFillColors, vkDestroyPipeline, m_pvkDevice); AMD_SAFE_RELEASE(m_pPLRenderHairAADepthsAlpha, vkDestroyPipeline, m_pvkDevice); AMD_SAFE_RELEASE(m_pPLRenderHairAAFillColors, vkDestroyPipeline, m_pvkDevice); AMD_SAFE_RELEASE(m_pPLRenderHairStrandCopiesDepthsAlpha, vkDestroyPipeline, m_pvkDevice); AMD_SAFE_RELEASE(m_pPLRenderHairStrandCopiesFillColors, vkDestroyPipeline, m_pvkDevice); AMD_SAFE_RELEASE(m_pPLRenderHairDepthsAlpha, vkDestroyPipeline, m_pvkDevice); AMD_SAFE_RELEASE(m_pPLRenderHairFillColors, vkDestroyPipeline, m_pvkDevice); AMD_SAFE_RELEASE(m_pPLDepthResolve, vkDestroyPipeline, m_pvkDevice); AMD_SAFE_RELEASE(m_pPLColorResolve, vkDestroyPipeline, m_pvkDevice); AMD_SAFE_RELEASE(m_pRPRenderHair, vkDestroyRenderPass, m_pvkDevice); AMD_SAFE_RELEASE(m_depthPassPipelineLayout, vkDestroyPipelineLayout, m_pvkDevice); AMD_SAFE_RELEASE(m_colorPassPipelineLayout, vkDestroyPipelineLayout, m_pvkDevice); AMD_SAFE_RELEASE(m_pSLDepthAlpha, vkDestroyDescriptorSetLayout, m_pvkDevice); AMD_SAFE_RELEASE(m_pSLColors, vkDestroyDescriptorSetLayout, m_pvkDevice); } AMD_SAFE_RELEASE(m_pDPShortcutPool, vkDestroyDescriptorPool, m_pvkDevice); } void TressFXShortCut::SetupDepthPass(VkDevice pvkDevice, VkCommandBuffer commandBuffer, uint32_t width, uint32_t height) { VkClearColorValue dwDepthClearMax{}; dwDepthClearMax.uint32[0] = SHORTCUT_INITIAL_DEPTH; dwDepthClearMax.uint32[1] = SHORTCUT_INITIAL_DEPTH; dwDepthClearMax.uint32[2] = SHORTCUT_INITIAL_DEPTH; dwDepthClearMax.uint32[3] = SHORTCUT_INITIAL_DEPTH; VkImageSubresourceRange range{}; range.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; range.layerCount = SHORTCUT_NUM_DEPTHS; range.levelCount = 1; vkCmdClearColorImage(commandBuffer, m_pFragmentDepthsTexture, VK_IMAGE_LAYOUT_GENERAL, &dwDepthClearMax, 1, &range); { VkRenderPassBeginInfo info{VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO}; info.framebuffer = m_pFBRenderHair; info.renderPass = m_pRPRenderHair; info.renderArea.extent.height = height; info.renderArea.extent.width = width; VkClearValue clearValue[3]; clearValue[0].depthStencil.stencil = 0; // alpha clearValue[1].color.float32[0] = 1; clearValue[1].color.float32[1] = 1; clearValue[1].color.float32[2] = 1; clearValue[1].color.float32[3] = 1; // color clearValue[2].color.float32[0] = 0.; clearValue[2].color.float32[1] = 0.; clearValue[2].color.float32[2] = 0.; clearValue[2].color.float32[3] = 0.; info.clearValueCount = 3; info.pClearValues = clearValue; vkCmdBeginRenderPass(commandBuffer, &info, VK_SUBPASS_CONTENTS_INLINE); } } void TressFXShortCut::SetupResolveDepth(VkDevice pvkDevice, VkCommandBuffer commandBuffer, uint32_t width, uint32_t height) { vkCmdNextSubpass(commandBuffer, VK_SUBPASS_CONTENTS_INLINE); } void TressFXShortCut::SetupShadePass(VkDevice pvkDevice, VkCommandBuffer commandBuffer, uint32_t width, uint32_t height) { vkCmdNextSubpass(commandBuffer, VK_SUBPASS_CONTENTS_INLINE); } void TressFXShortCut::SetupResolveColor(VkDevice pvkDevice, VkCommandBuffer commandBuffer, uint32_t width, uint32_t height) { vkCmdNextSubpass(commandBuffer, VK_SUBPASS_CONTENTS_INLINE); } }
47.504094
122
0.673897
[ "vector" ]
2a99534629ed4aafab308b1f6ea6ac742e38ecd0
3,912
cpp
C++
thirdparty/liblsdj/lsdsng_import/main.cpp
fossabot/RetroPlug
5a39379bd10d2e2c0b13a0850380db4d5a58cdd3
[ "MIT" ]
186
2019-05-14T15:15:33.000Z
2022-03-21T22:27:10.000Z
thirdparty/liblsdj/lsdsng_import/main.cpp
fossabot/RetroPlug
5a39379bd10d2e2c0b13a0850380db4d5a58cdd3
[ "MIT" ]
70
2018-05-14T15:44:17.000Z
2020-04-18T14:34:02.000Z
thirdparty/liblsdj/lsdsng_import/main.cpp
fossabot/RetroPlug
5a39379bd10d2e2c0b13a0850380db4d5a58cdd3
[ "MIT" ]
9
2019-05-17T08:24:42.000Z
2021-11-14T12:00:11.000Z
/* This file is a part of liblsdj, a C library for managing everything that has to do with LSDJ, software for writing music (chiptune) with your gameboy. For more information, see: * https://github.com/stijnfrishert/liblsdj * http://www.littlesounddj.com -------------------------------------------------------------------------------- MIT License Copyright (c) 2018 - 2020 Stijn Frishert Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <iostream> #include <popl/popl.hpp> #include <lsdj/version.h> #include "../common/common.hpp" #include "importer.hpp" void printHelp(const popl::OptionParser& options) { std::cout << "lsdsng-import -o output.sav song1.lsgsng song2.lsdsng songs.sav...\n\n" << "Version: " << LSDJ_VERSION_STRING << "\n\n" << options << "\n"; std::cout << "LibLSDJ is open source and freely available to anyone.\nIf you'd like to show your appreciation, please consider\n - buying one of my albums (https://4ntler.bandcamp.com)\n - donating money through PayPal (https://paypal.me/4ntler).\n"; } std::string generateOutputFilename(const std::vector<std::string>& inputs) { // If we've got no output file and are only importing one folder, // we take that folder name as output. In case of multiple folders, if (inputs.size() == 1) { const auto path = ghc::filesystem::absolute(inputs.front()); return path.stem().filename().string() + ".sav"; } return "out.sav"; } int main(int argc, char* argv[]) { popl::OptionParser options("Options"); auto help = options.add<popl::Switch>("h", "help", "Show the help screen"); auto verbose = options.add<popl::Switch>("v", "verbose", "Verbose output during import"); auto output = options.add<popl::Value<std::string>>("o", "output", "The output file (.sav)"); auto wm = options.add<popl::Value<std::string>>("w", "working-memory", "The song to put in the working memory"); try { options.parse(argc, argv); const auto imports = options.non_option_args(); if (help->is_set()) { printHelp(options); return 0; } else if (!imports.empty()) { lsdj::Importer importer; importer.inputs = imports; if (wm->is_set()) importer.workingMemoryInput = wm->value(); importer.verbose = verbose->is_set(); importer.outputFile = output->is_set() ? output->value() : generateOutputFilename(importer.inputs); return importer.import(); } else { printHelp(options); return 0; } } catch (std::exception& e) { std::cerr << e.what() << std::endl; } catch (...) { std::cerr << "unknown error" << std::endl; } return 0; }
35.889908
256
0.632157
[ "vector" ]
2a9f769ff98ba6ab8f2a6281927f0927eaf93a08
2,481
cpp
C++
windows/pw6e.official/CPlusPlus/Chapter18/OrientationAndOrientation/OrientationAndOrientation/MainPage.xaml.cpp
nnaabbcc/exercise
255fd32b39473b3d0e7702d4b1a8a97bed2a68f8
[ "MIT" ]
1
2016-11-23T08:18:08.000Z
2016-11-23T08:18:08.000Z
windows/pw6e.official/CPlusPlus/Chapter18/OrientationAndOrientation/OrientationAndOrientation/MainPage.xaml.cpp
nnaabbcc/exercise
255fd32b39473b3d0e7702d4b1a8a97bed2a68f8
[ "MIT" ]
null
null
null
windows/pw6e.official/CPlusPlus/Chapter18/OrientationAndOrientation/OrientationAndOrientation/MainPage.xaml.cpp
nnaabbcc/exercise
255fd32b39473b3d0e7702d4b1a8a97bed2a68f8
[ "MIT" ]
1
2016-11-23T08:17:34.000Z
2016-11-23T08:17:34.000Z
// // MainPage.xaml.cpp // Implementation of the MainPage class. // #include "pch.h" #include "MainPage.xaml.h" using namespace OrientationAndOrientation; using namespace Platform; using namespace Windows::Devices::Sensors; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::Graphics::Display; using namespace Windows::UI::Core; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; MainPage::MainPage() { InitializeComponent(); simpleOrientationSensor = SimpleOrientationSensor::GetDefault(); // SimpleOrientationSensor initialization if (simpleOrientationSensor != nullptr) { SetOrientationSensorText(simpleOrientationSensor->GetCurrentOrientation()); simpleOrientationSensor->OrientationChanged += ref new TypedEventHandler<SimpleOrientationSensor^, SimpleOrientationSensorOrientationChangedEventArgs^>(this, &MainPage::OnSimpleOrientationChanged); } // DisplayProperties initialization SetDisplayOrientationText(DisplayProperties::CurrentOrientation); DisplayProperties::OrientationChanged += ref new DisplayPropertiesEventHandler(this, &MainPage::OnDisplayPropertiesOrientationChanged); } // SimpleOrientationSensor handler void MainPage::OnSimpleOrientationChanged(SimpleOrientationSensor^ sender, SimpleOrientationSensorOrientationChangedEventArgs^ args) { this->Dispatcher->RunAsync(CoreDispatcherPriority::Normal, ref new DispatchedHandler([this, args]() { SetOrientationSensorText(args->Orientation); })); } void MainPage::SetOrientationSensorText(SimpleOrientation simpleOrientation) { orientationSensorTextBlock->Text = simpleOrientation.ToString(); } // DisplayProperties handler void MainPage::OnDisplayPropertiesOrientationChanged(Object^ sender) { SetDisplayOrientationText(DisplayProperties::CurrentOrientation); } void MainPage::SetDisplayOrientationText(DisplayOrientations displayOrientation) { displayOrientationTextBlock->Text = displayOrientation.ToString(); }
34.943662
137
0.739218
[ "object" ]
2ab2e8d20188c4dd64f8665cf0e00e1188c0b3b0
21,944
cpp
C++
src/scenes/SelectionScene.cpp
rodri042/piugba
bb3aae80c3a74d87531a825eba35a032f45c42a3
[ "TU-Berlin-1.0", "MIT" ]
37
2020-03-29T03:55:17.000Z
2022-01-12T02:12:14.000Z
src/scenes/SelectionScene.cpp
rodri042/piugba
bb3aae80c3a74d87531a825eba35a032f45c42a3
[ "TU-Berlin-1.0", "MIT" ]
2
2020-06-27T16:49:33.000Z
2020-07-20T04:55:07.000Z
src/scenes/SelectionScene.cpp
rodri042/piugba
bb3aae80c3a74d87531a825eba35a032f45c42a3
[ "TU-Berlin-1.0", "MIT" ]
2
2021-05-31T00:39:38.000Z
2021-07-12T21:01:23.000Z
#include "SelectionScene.h" #include <libgba-sprite-engine/background/text_stream.h> #include <libgba-sprite-engine/effects/fade_out_scene.h> #include <libgba-sprite-engine/gba/tonc_bios.h> #include <tonc_input.h> #include "ModsScene.h" #include "MultiplayerLobbyScene.h" #include "SettingsScene.h" #include "assets.h" #include "data/content/_compiled_sprites/palette_selection.h" #include "gameplay/Key.h" #include "gameplay/Sequence.h" #include "gameplay/models/Song.h" #include "utils/SceneUtils.h" extern "C" { #include "player/player.h" #include "utils/gbfs/gbfs.h" } #define CONFIRM_MESSAGE "Press to start!" const u32 ID_HIGHLIGHTER = 1; const u32 ID_MAIN_BACKGROUND = 2; const u32 INIT_FRAME = 2; const u32 BANK_BACKGROUND_TILES = 0; const u32 BANK_BACKGROUND_MAP = 16; const u32 SELECTOR_MARGIN = 3; const u32 CENTER_X = 96; const u32 CENTER_Y = 110; const u32 TEXT_COLOR = 0x7FFF; const u32 TEXT_ROW = 13; const int TEXT_SCROLL_NORMAL = -6; const int TEXT_SCROLL_CONFIRMED = -10; const u32 PIXEL_BLINK_LEVEL = 4; const u32 CHANNEL_BADGE_X[] = {22, 82, 142, 202}; const u32 CHANNEL_BADGE_Y = 49; const u32 GRADE_BADGE_X[] = {43, 103, 163, 222}; const u32 GRADE_BADGE_Y = 84; const u32 LOCK_X[] = {22, 82, 142, 202}; const u32 LOCK_Y = 71; const u32 NUMERIC_LEVEL_BADGE_X = 104; const u32 NUMERIC_LEVEL_BADGE_Y = 19; const u32 NUMERIC_LEVEL_ROW = 3; const u32 NUMERIC_LEVEL_BADGE_OFFSET_Y = 43; const u32 NUMERIC_LEVEL_BADGE_OFFSET_ROW = 5; static std::unique_ptr<Highlighter> highlighter{ new Highlighter(ID_HIGHLIGHTER)}; SelectionScene::SelectionScene(std::shared_ptr<GBAEngine> engine, const GBFS_FILE* fs) : Scene(engine) { this->fs = fs; library = std::unique_ptr<Library>{new Library(fs)}; } std::vector<Background*> SelectionScene::backgrounds() { return {}; } std::vector<Sprite*> SelectionScene::sprites() { std::vector<Sprite*> sprites; for (auto& it : arrowSelectors) sprites.push_back(it->get()); for (auto& it : channelBadges) sprites.push_back(it->get()); for (auto& it : gradeBadges) sprites.push_back(it->get()); for (auto& it : locks) sprites.push_back(it->get()); difficulty->render(&sprites); sprites.push_back(multiplier->get()); progress->render(&sprites); if (!IS_STORY(SAVEFILE_getGameMode())) sprites.push_back(numericLevelBadge->get()); return sprites; } void SelectionScene::load() { if (ENV_ARCADE && IS_STORY(SAVEFILE_getGameMode())) BSOD("This version is ARCADE only."); if (isMultiplayer()) { syncer->clearTimeout(); syncer->$resetFlag = false; SAVEFILE_write8(SRAM->memory.numericLevel, 0); } SAVEFILE_write8(SRAM->state.isPlaying, 0); SCENE_init(); TextStream::instance().scroll(0, TEXT_SCROLL_NORMAL); TextStream::instance().setMosaic(true); pixelBlink = std::unique_ptr<PixelBlink>{new PixelBlink(PIXEL_BLINK_LEVEL)}; difficulty = std::unique_ptr<Difficulty>{new Difficulty()}; multiplier = std::unique_ptr<Multiplier>{ new Multiplier(SAVEFILE_read8(SRAM->mods.multiplier))}; progress = std::unique_ptr<NumericProgress>{new NumericProgress()}; settingsMenuInput = std::unique_ptr<InputHandler>{new InputHandler()}; if (IS_STORY(SAVEFILE_getGameMode())) { auto level = SAVEFILE_read8(SRAM->memory.difficultyLevel); difficulty->setValue(static_cast<DifficultyLevel>(level)); } else { numericLevelBadge = std::unique_ptr<Button>{ new Button(ButtonType::LEVEL_METER, NUMERIC_LEVEL_BADGE_X, NUMERIC_LEVEL_BADGE_Y, false)}; numericLevelBadge->get()->setPriority(ID_HIGHLIGHTER); difficulty->setValue(DifficultyLevel::NUMERIC); SPRITE_hide(multiplier->get()); } setUpSpritesPalette(); setUpArrows(); setUpChannelBadges(); setUpGradeBadges(); setUpLocks(); setUpPager(); } void SelectionScene::tick(u16 keys) { if (engine->isTransitioning()) return; if (SEQUENCE_isMultiplayerSessionDead()) { player_stop(); SEQUENCE_goToMultiplayerGameMode(SAVEFILE_getGameMode()); return; } if (init < INIT_FRAME) { init++; return; } else if (init == INIT_FRAME) { BACKGROUND_enable(true, true, true, false); SPRITE_enable(); highlighter->initialize(selected); init++; } pixelBlink->tick(); for (auto& it : arrowSelectors) it->tick(); multiplier->tick(); processKeys(keys); if (isMultiplayer()) { processMultiplayerUpdates(); if (!syncer->isPlaying()) return; } processDifficultyChangeEvents(); processSelectionChangeEvents(); processConfirmEvents(); processMenuEvents(keys); blendAlpha = max(min(blendAlpha + (confirmed ? 1 : -1), MAX_OPACITY), HIGHLIGHTER_OPACITY); EFFECT_setBlendAlpha(blendAlpha); } void SelectionScene::setUpSpritesPalette() { foregroundPalette = std::unique_ptr<ForegroundPaletteManager>{new ForegroundPaletteManager( palette_selectionPal, sizeof(palette_selectionPal))}; } void SelectionScene::setUpBackground() { auto backgroundFile = library->getPrefix() + std::to_string(getPageStart()); auto backgroundPaletteFile = backgroundFile + BACKGROUND_PALETTE_EXTENSION; auto backgroundTilesFile = backgroundFile + BACKGROUND_TILES_EXTENSION; auto backgroundMapFile = backgroundFile + BACKGROUND_MAP_EXTENSION; backgroundPalette = BACKGROUND_loadPaletteFile(fs, backgroundPaletteFile.c_str()); backgroundPalette->persist(); bg = BACKGROUND_loadBackgroundFiles(fs, backgroundTilesFile.c_str(), backgroundMapFile.c_str(), ID_MAIN_BACKGROUND); bg->useCharBlock(BANK_BACKGROUND_TILES); bg->useMapScreenBlock(BANK_BACKGROUND_MAP); bg->setMosaic(true); bg->persist(); TextStream::instance().setFontColor(TEXT_COLOR); loadChannels(); loadProgress(); } void SelectionScene::setUpArrows() { for (u32 i = 0; i < ARROWS_TOTAL; i++) { auto direction = static_cast<ArrowDirection>(i); arrowSelectors.push_back(std::unique_ptr<ArrowSelector>{ new ArrowSelector(static_cast<ArrowDirection>(direction), direction > 0, direction != ArrowDirection::CENTER)}); } arrowSelectors[ArrowDirection::DOWNLEFT]->get()->moveTo( SELECTOR_MARGIN, GBA_SCREEN_HEIGHT - ARROW_SIZE - SELECTOR_MARGIN); arrowSelectors[ArrowDirection::UPLEFT]->get()->moveTo(SELECTOR_MARGIN, SELECTOR_MARGIN); SPRITE_hide(arrowSelectors[ArrowDirection::CENTER]->get()); arrowSelectors[ArrowDirection::UPRIGHT]->get()->moveTo( GBA_SCREEN_WIDTH - ARROW_SIZE - SELECTOR_MARGIN, SELECTOR_MARGIN); arrowSelectors[ArrowDirection::DOWNRIGHT]->get()->moveTo( GBA_SCREEN_WIDTH - ARROW_SIZE - SELECTOR_MARGIN, GBA_SCREEN_HEIGHT - ARROW_SIZE - SELECTOR_MARGIN); if (isMultiplayer() && !syncer->isMaster()) { SPRITE_hide(arrowSelectors[ArrowDirection::DOWNLEFT]->get()); SPRITE_hide(arrowSelectors[ArrowDirection::DOWNRIGHT]->get()); if (isCoop()) { SPRITE_hide(arrowSelectors[ArrowDirection::UPLEFT]->get()); SPRITE_hide(arrowSelectors[ArrowDirection::UPRIGHT]->get()); } } } void SelectionScene::setUpChannelBadges() { for (u32 i = 0; i < PAGE_SIZE; i++) channelBadges.push_back(std::unique_ptr<ChannelBadge>{ new ChannelBadge(CHANNEL_BADGE_X[i], CHANNEL_BADGE_Y, i > 0)}); } void SelectionScene::setUpGradeBadges() { for (u32 i = 0; i < PAGE_SIZE; i++) { gradeBadges.push_back(std::unique_ptr<GradeBadge>{ new GradeBadge(GRADE_BADGE_X[i], GRADE_BADGE_Y, i > 0, false)}); gradeBadges[i]->get()->setPriority(ID_MAIN_BACKGROUND); } } void SelectionScene::setUpLocks() { for (u32 i = 0; i < PAGE_SIZE; i++) locks.push_back(std::unique_ptr<Lock>{new Lock(LOCK_X[i], LOCK_Y, i > 0)}); } void SelectionScene::setUpPager() { count = SAVEFILE_getLibrarySize(); scrollTo(SAVEFILE_read8(SRAM->memory.pageIndex), SAVEFILE_read8(SRAM->memory.songIndex)); } void SelectionScene::scrollTo(u32 songIndex) { scrollTo(Div(songIndex, PAGE_SIZE), DivMod(songIndex, PAGE_SIZE)); } void SelectionScene::scrollTo(u32 page, u32 selected) { this->page = page; this->selected = selected; if (getSelectedSongIndex() > getLastUnlockedSongIndex()) { scrollTo(getLastUnlockedSongIndex()); return; } setPage(page, 0); updateSelection(); } void SelectionScene::setNumericLevel(u8 numericLevelIndex) { SAVEFILE_write8(SRAM->memory.numericLevel, numericLevelIndex); updateSelection(true); pixelBlink->blink(); } void SelectionScene::goToSong() { if (numericLevels.empty()) return; player_stop(); confirmed = false; bool isStory = IS_STORY(SAVEFILE_getGameMode()); bool hasRemoteChart = isVs() && remoteNumericLevel != -1; std::vector<u8> selectedLevels; if (!isStory) { selectedLevels.push_back(getSelectedNumericLevel()); if (hasRemoteChart) selectedLevels.push_back(numericLevels[remoteNumericLevel]); } Song* song = SONG_parse(fs, getSelectedSong(), true, selectedLevels); Chart* chart = isStory ? SONG_findChartByDifficultyLevel(song, difficulty->getValue()) : SONG_findChartByNumericLevelIndex( song, getSelectedNumericLevelIndex(), isDouble()); Chart* remoteChart = hasRemoteChart ? SONG_findChartByNumericLevelIndex( song, (u8)remoteNumericLevel, false) : NULL; STATE_setup(song, chart); SEQUENCE_goToMessageOrSong(song, chart, remoteChart); } void SelectionScene::processKeys(u16 keys) { arrowSelectors[ArrowDirection::DOWNLEFT]->setIsPressed(KEY_DOWNLEFT(keys)); arrowSelectors[ArrowDirection::UPLEFT]->setIsPressed(KEY_UPLEFT(keys)); arrowSelectors[ArrowDirection::CENTER]->setIsPressed(KEY_CENTER(keys)); arrowSelectors[ArrowDirection::UPRIGHT]->setIsPressed(KEY_UPRIGHT(keys)); arrowSelectors[ArrowDirection::DOWNRIGHT]->setIsPressed(KEY_DOWNRIGHT(keys)); multiplier->setIsPressed(keys & KEY_SELECT); settingsMenuInput->setIsPressed(keys & KEY_START); } void SelectionScene::processDifficultyChangeEvents() { if (isCoop() && !syncer->isMaster()) return; if (IS_STORY(SAVEFILE_getGameMode())) { if (onDifficultyLevelChange( ArrowDirection::UPRIGHT, static_cast<DifficultyLevel>( min((int)difficulty->getValue() + 1, MAX_DIFFICULTY)))) return; onDifficultyLevelChange( ArrowDirection::UPLEFT, static_cast<DifficultyLevel>(max((int)difficulty->getValue() - 1, 0))); } else { auto currentIndex = getSelectedNumericLevelIndex(); auto previousIndex = max(currentIndex - 1, 0); auto nextIndex = min(currentIndex + 1, numericLevels.size() - 1); if (onNumericLevelChange(ArrowDirection::UPRIGHT, nextIndex)) return; onNumericLevelChange(ArrowDirection::UPLEFT, previousIndex); } } void SelectionScene::processSelectionChangeEvents() { if (isMultiplayer() && !syncer->isMaster()) return; bool isOnListEdge = getSelectedSongIndex() == getLastUnlockedSongIndex(); #ifdef SENV_DEVELOPMENT isOnListEdge = getSelectedSongIndex() == count - 1; #endif if (onSelectionChange(ArrowDirection::DOWNRIGHT, isOnListEdge, selected == PAGE_SIZE - 1, 1)) return; onSelectionChange(ArrowDirection::DOWNLEFT, page == 0 && selected == 0, selected == 0, -1); } void SelectionScene::processConfirmEvents() { if (isMultiplayer() && !syncer->isMaster()) return; if (arrowSelectors[ArrowDirection::CENTER]->hasBeenPressedNow()) { if (isMultiplayer() && syncer->isMaster()) syncer->send(SYNC_EVENT_START_SONG, confirmed); onConfirmOrStart(confirmed); } } void SelectionScene::processMenuEvents(u16 keys) { if (isMultiplayer()) { if (syncer->isMaster() && multiplier->hasBeenPressedNow()) { syncer->initialize(SyncMode::SYNC_MODE_OFFLINE); quit(); } return; } if (multiplier->hasBeenPressedNow()) { if (IS_STORY(SAVEFILE_getGameMode())) { player_play(SOUND_MOD); SAVEFILE_write8(SRAM->mods.multiplier, multiplier->change()); } else { player_stop(); engine->transitionIntoScene(new ModsScene(engine, fs), new PixelTransitionEffect()); } } if (settingsMenuInput->hasBeenPressedNow()) { player_stop(); engine->transitionIntoScene(new SettingsScene(engine, fs), new PixelTransitionEffect()); } } bool SelectionScene::onDifficultyLevelChange(ArrowDirection selector, DifficultyLevel newValue) { if (arrowSelectors[selector]->hasBeenPressedNow()) { unconfirm(); player_play(SOUND_STEP); if (newValue == difficulty->getValue()) return true; SAVEFILE_write8(SRAM->memory.difficultyLevel, newValue); difficulty->setValue(newValue); pixelBlink->blink(); u32 lastUnlockedSongIndex = getLastUnlockedSongIndex(); player_stop(); scrollTo(lastUnlockedSongIndex); return true; } return false; } bool SelectionScene::onNumericLevelChange(ArrowDirection selector, u8 newValue) { if (arrowSelectors[selector]->hasBeenPressedNow()) { unconfirm(); player_play(SOUND_STEP); if (newValue == getSelectedNumericLevelIndex()) { syncNumericLevelChanged(newValue); return true; } syncNumericLevelChanged(newValue); setNumericLevel(newValue); return true; } return false; } bool SelectionScene::onSelectionChange(ArrowDirection selector, bool isOnListEdge, bool isOnPageEdge, int direction) { if ((isMultiplayer() && arrowSelectors[selector]->hasBeenPressedNow()) || (!isMultiplayer() && arrowSelectors[selector]->shouldFireEvent())) { unconfirm(); if (isOnListEdge) { bool withSound = arrowSelectors[selector]->hasBeenPressedNow(); if (withSound) player_play(SOUND_STEP); if (isMultiplayer() && syncer->isMaster()) syncer->send(SYNC_EVENT_SONG_CORNER, withSound); return true; } player_stop(); if (isOnPageEdge) setPage(page + direction, direction); else { selected += direction; updateSelection(); pixelBlink->blink(); } if (isMultiplayer() && syncer->isMaster()) syncer->send(SYNC_EVENT_SONG_CHANGED, getSelectedSongIndex()); return true; } return false; } void SelectionScene::onConfirmOrStart(bool isConfirmed) { if (confirmed) goToSong(); else confirm(); } void SelectionScene::updateSelection(bool isChangingLevel) { Song* song = SONG_parse(fs, getSelectedSong(), false); updateLevel(song, isChangingLevel); setNames(song->title, song->artist); printNumericLevel(SONG_findChartByNumericLevelIndex( song, getSelectedNumericLevelIndex(), isDouble()) ->difficulty); loadSelectedSongGrade(song->id); if (!isChangingLevel) { player_play(song->audioPath.c_str()); player_seek(song->sampleStart); } SONG_free(song); SAVEFILE_write8(SRAM->memory.pageIndex, page); SAVEFILE_write8(SRAM->memory.songIndex, selected); highlighter->select(selected); } void SelectionScene::updateLevel(Song* song, bool isChangingLevel) { bool canUpdateLevel = false; u8 currentLevel; if (!numericLevels.empty()) { canUpdateLevel = true; currentLevel = getSelectedNumericLevel(); numericLevels.clear(); } for (u32 i = 0; i < song->chartCount; i++) if (song->charts[i].isDouble == isDouble()) numericLevels.push_back(song->charts[i].level); if (canUpdateLevel && !isChangingLevel) setClosestNumericLevel(currentLevel); if (getSelectedNumericLevelIndex() > numericLevels.size() - 1) setClosestNumericLevel(0); if (difficulty->getValue() != DifficultyLevel::NUMERIC) setClosestNumericLevel( SONG_findChartByDifficultyLevel(song, difficulty->getValue())->level); } void SelectionScene::confirm() { if (!IS_STORY(SAVEFILE_getGameMode())) { if (numericLevels.empty()) return; numericLevelBadge->get()->moveTo( NUMERIC_LEVEL_BADGE_X, NUMERIC_LEVEL_BADGE_Y + NUMERIC_LEVEL_BADGE_OFFSET_Y); } player_play(SOUND_STEP); confirmed = true; arrowSelectors[ArrowDirection::CENTER]->get()->moveTo(CENTER_X, CENTER_Y); TextStream::instance().scroll(0, TEXT_SCROLL_CONFIRMED); TextStream::instance().clear(); printNumericLevel(DifficultyLevel::NUMERIC, NUMERIC_LEVEL_BADGE_OFFSET_ROW); SCENE_write(CONFIRM_MESSAGE, TEXT_ROW); } void SelectionScene::unconfirm() { if (confirmed) { if (!IS_STORY(SAVEFILE_getGameMode())) numericLevelBadge->get()->moveTo(NUMERIC_LEVEL_BADGE_X, NUMERIC_LEVEL_BADGE_Y); SPRITE_hide(arrowSelectors[ArrowDirection::CENTER]->get()); TextStream::instance().scroll(0, TEXT_SCROLL_NORMAL); updateSelection(); } confirmed = false; } void SelectionScene::setPage(u32 page, int direction) { this->page = page; songs.clear(); songs = library->loadSongs(getLibraryType(), getPageStart()); if (direction == 0) setUpBackground(); else { this->selected = direction < 0 ? PAGE_SIZE - 1 : 0; highlighter->select(selected); pixelBlink->blinkAndThen([this]() { setUpBackground(); updateSelection(); }); } } void SelectionScene::loadChannels() { for (u32 i = 0; i < songs.size(); i++) { auto channel = SONG_getChannel(fs, SAVEFILE_getGameMode(), songs[i].get(), getLibraryType()); channelBadges[i]->setType(channel); } for (u32 i = songs.size(); i < PAGE_SIZE; i++) channelBadges[i]->hide(); } void SelectionScene::loadProgress() { progress->setValue(getCompletedSongs(), count); for (u32 i = 0; i < PAGE_SIZE; i++) { auto songIndex = page * PAGE_SIZE + i; gradeBadges[i]->setType( IS_STORY(SAVEFILE_getGameMode()) ? SAVEFILE_getStoryGradeOf(songIndex, difficulty->getValue()) : GradeType::UNPLAYED); locks[i]->setVisible(songIndex > getLastUnlockedSongIndex() && songIndex <= count - 1); } } void SelectionScene::setNames(std::string title, std::string artist) { TextStream::instance().clear(); SCENE_write(title, TEXT_ROW); TextStream::instance().setText("- " + artist + " -", TEXT_ROW + 1, TEXT_MIDDLE_COL - (artist.length() + 4) / 2); } void SelectionScene::printNumericLevel(DifficultyLevel difficulty, s8 offset) { if (IS_STORY(SAVEFILE_getGameMode())) return; if (numericLevels.empty()) { SCENE_write("--", NUMERIC_LEVEL_ROW + offset); return; } if (difficulty == DifficultyLevel::NORMAL) return SCENE_write("NM", NUMERIC_LEVEL_ROW + offset); if (difficulty == DifficultyLevel::HARD) return SCENE_write("HD", NUMERIC_LEVEL_ROW + offset); if (difficulty == DifficultyLevel::CRAZY) return SCENE_write("CZ", NUMERIC_LEVEL_ROW + offset); auto levelText = std::to_string(getSelectedNumericLevel()); if (levelText.size() == 1) levelText = "0" + levelText; SCENE_write(levelText, NUMERIC_LEVEL_ROW + offset); } void SelectionScene::loadSelectedSongGrade(u8 songId) { if (IS_STORY(SAVEFILE_getGameMode())) return; for (u32 i = 0; i < PAGE_SIZE; i++) { auto songIndex = page * PAGE_SIZE + i; gradeBadges[i]->setType( songIndex == getSelectedSongIndex() ? SAVEFILE_getArcadeGradeOf(songId, getSelectedNumericLevel()) : GradeType::UNPLAYED); } } void SelectionScene::processMultiplayerUpdates() { auto linkState = linkConnection->linkState.get(); auto remoteId = syncer->getRemotePlayerId(); while (syncer->isPlaying() && linkState->hasMessage(remoteId)) { u16 message = linkState->readMessage(remoteId); u8 event = SYNC_MSG_EVENT(message); u16 payload = SYNC_MSG_PAYLOAD(message); if (syncer->isMaster() && (isCoop() || event != SYNC_EVENT_LEVEL_CHANGED)) { syncer->registerTimeout(); continue; } switch (event) { case SYNC_EVENT_SONG_CHANGED: { unconfirm(); if (remoteNumericLevel != -1) setNumericLevel(remoteNumericLevel); scrollTo(payload); remoteNumericLevel = getSelectedNumericLevelIndex(); pixelBlink->blink(); syncer->clearTimeout(); break; } case SYNC_EVENT_LEVEL_CHANGED: { unconfirm(); player_play(SOUND_STEP); if (syncer->isMaster()) { setNumericLevel(getSelectedNumericLevelIndex()); remoteNumericLevel = payload; } else { setNumericLevel(payload); remoteNumericLevel = payload; } syncer->clearTimeout(); break; } case SYNC_EVENT_SONG_CORNER: { unconfirm(); if (payload) player_play(SOUND_STEP); syncer->clearTimeout(); break; } case SYNC_EVENT_START_SONG: { onConfirmOrStart(payload); syncer->clearTimeout(); break; } default: { syncer->registerTimeout(); } } } } void SelectionScene::syncNumericLevelChanged(u8 newValue) { if (!isMultiplayer()) return; syncer->send(SYNC_EVENT_LEVEL_CHANGED, newValue); if (syncer->isMaster()) remoteNumericLevel = -1; } void SelectionScene::quit() { player_stop(); engine->transitionIntoScene(SEQUENCE_getMainScene(), new PixelTransitionEffect()); } SelectionScene::~SelectionScene() { songs.clear(); arrowSelectors.clear(); channelBadges.clear(); gradeBadges.clear(); locks.clear(); }
29.336898
80
0.675355
[ "render", "vector" ]
2ab2eb03c84cf8cf771bd487483a209e6cfd2e62
3,258
cpp
C++
object_detection/viola_jones.cpp
dustsigns/lecture-demos
50d5abb252e7e467e9648b61310ce93b85c6c5f0
[ "BSD-3-Clause" ]
14
2018-03-26T13:43:58.000Z
2022-03-03T13:04:36.000Z
object_detection/viola_jones.cpp
dustsigns/lecture-demos
50d5abb252e7e467e9648b61310ce93b85c6c5f0
[ "BSD-3-Clause" ]
null
null
null
object_detection/viola_jones.cpp
dustsigns/lecture-demos
50d5abb252e7e467e9648b61310ce93b85c6c5f0
[ "BSD-3-Clause" ]
1
2019-08-03T23:12:08.000Z
2019-08-03T23:12:08.000Z
//Illustration of Viola-Jones object detection // Andreas Unterweger, 2017-2022 //This code is licensed under the 3-Clause BSD License. See LICENSE file for details. #include <iostream> #include <vector> #include <opencv2/core.hpp> #include <opencv2/highgui.hpp> #include <opencv2/objdetect.hpp> #include <opencv2/imgproc.hpp> #include "colors.hpp" static bool InitClassifier(cv::CascadeClassifier &classifier) { constexpr auto classifier_path = "/usr/local/share/opencv4/haarcascades/haarcascade_frontalface_alt.xml"; const bool successful = classifier.load(classifier_path); return successful; } static void FindFaces(const cv::Mat &image, /*const*/ cv::CascadeClassifier &classifier, std::vector<cv::Rect> &faces) { classifier.detectMultiScale(image, faces); } static void HighlightFaces(cv::Mat &image, std::vector<cv::Rect> faces) { constexpr auto line_width = 2; const auto face_color = imgutils::Red; for (const auto &face : faces) cv::rectangle(image, face, face_color, line_width); } static cv::Mat GetGrayscaleImage(const cv::Mat &image) { assert(image.type() == CV_8UC3); //Assume 8-bit RGB image cv::Mat grayscale_image; cv::cvtColor(image, grayscale_image, cv::COLOR_BGR2GRAY); return grayscale_image; } static void ShowImage(const cv::Mat &image, /*const*/ cv::CascadeClassifier &classifier) { constexpr auto window_name = "Frame with objects to detect"; cv::namedWindow(window_name, cv::WINDOW_GUI_NORMAL | cv::WINDOW_AUTOSIZE); cv::moveWindow(window_name, 0, 0); const cv::Mat grayscale_image = GetGrayscaleImage(image); std::vector<cv::Rect> faces; FindFaces(grayscale_image, classifier, faces); cv::Mat image_with_faces = image.clone(); HighlightFaces(image_with_faces, faces); cv::imshow(window_name, image_with_faces); } static int OpenVideo(const char * const filename, cv::VideoCapture &capture) { using namespace std::string_literals; const bool use_webcam = "-"s == filename; //Interpret - as the default webcam const bool opened = use_webcam ? capture.open(0) : capture.open(filename); if (use_webcam) //Minimize buffering for webcams to return up-to-date images capture.set(cv::CAP_PROP_BUFFERSIZE, 1); return opened; } int main(const int argc, const char * const argv[]) { if (argc != 2 && argc != 3) { std::cout << "Illustrates object detection on video frames with the object detector by Viola and Jones." << std::endl; std::cout << "Usage: " << argv[0] << " <input video> [<wait time between frames>]" << std::endl; return 1; } cv::CascadeClassifier classifier; if (!InitClassifier(classifier)) { std::cerr << "Could not initialize cascade classifier" << std::endl; return 2; } const auto video_filename = argv[1]; int wait_time = 0; if (argc == 3) { const auto wait_time_text = argv[2]; wait_time = std::stoi(wait_time_text); } cv::VideoCapture capture; if (!OpenVideo(video_filename, capture)) { std::cerr << "Could not open video '" << video_filename << "'" << std::endl; return 3; } cv::Mat frame; while (capture.read(frame) && !frame.empty()) { ShowImage(frame, classifier); if (cv::waitKey(wait_time) == 'q') //Interpret Q key press as exit break; } return 0; }
31.941176
122
0.706262
[ "object", "vector" ]
2ab7b04f3e0e69d7c213cf60ee6c28ef1fffb17c
7,864
cpp
C++
src/commands/Rdf.cpp
jjzhang166/chemfiles_cfiles
621f74661fed3b3f37363f063f5558ff6b1612f3
[ "BSD-3-Clause" ]
null
null
null
src/commands/Rdf.cpp
jjzhang166/chemfiles_cfiles
621f74661fed3b3f37363f063f5558ff6b1612f3
[ "BSD-3-Clause" ]
null
null
null
src/commands/Rdf.cpp
jjzhang166/chemfiles_cfiles
621f74661fed3b3f37363f063f5558ff6b1612f3
[ "BSD-3-Clause" ]
null
null
null
// cfiles, an analysis frontend for the Chemfiles library // Copyright (C) Guillaume Fraux and contributors -- BSD license #include <docopt/docopt.h> #include <unordered_set> #include <fstream> #include "Rdf.hpp" #include "Errors.hpp" #include "geometry.hpp" #include "utils.hpp" #include "warnings.hpp" using namespace chemfiles; /// Get the radius of the biggest inscribed sphere in the unit cell static double biggest_sphere_radius(const UnitCell& cell); static const char OPTIONS[] = R"(Compute radial pair distribution function (often denoted g(r)) and running coordination number. The pair of particles to use can be specified using the chemfiles selection language. It is possible to provide an alternative unit cell or topology for the trajectory file if they are not defined in the trajectory format. For more information about chemfiles selection language, please see http://chemfiles.github.io/chemfiles/latest/selections.html Usage: cfiles rdf [options] <trajectory> cfiles rdf (-h | --help) Examples: cfiles rdf water.tng -s "name O" --max=8.5 --output=rdf-O-O.dat cfiles rdf butane.tng -s "pairs: name(#1) C and name(#2) H" cfiles rdf methane.xyz --cell 15:15:25 --guess-bonds --points=150 cfiles rdf result.xtc --topology=initial.mol --topology-format=PDB cfiles rdf simulation.pdb --steps=10000::100 -o partial-rdf.dat Options: -h --help show this help -o <file>, --output=<file> write result to <file>. This default to the trajectory file name with the `.rdf.dat` extension. -s <sel>, --selection=<sel> selection to use for the atoms. This can be a single selection ("name O") or a selection of two atoms ("pairs: name(#1) O and name(#2) H") [default: all] --max=<max> maximal distance to use. If a custom unit cell is present (--cell option) and this option is not, the radius of the biggest inscribed sphere is used as maximal distance [default: 10] -p <n>, --points=<n> number of points in the histogram [default: 200])"; std::string Rdf::description() const { return "compute radial distribution functions"; } Averager<double> Rdf::setup(int argc, const char* argv[]) { auto options = command_header("rdf", Rdf().description()); options += "Guillaume Fraux <guillaume@fraux.fr>\n\n"; options += std::string(OPTIONS) + AveCommand::AVERAGE_OPTIONS; auto args = docopt::docopt(options, {argv, argv + argc}, true, ""); AveCommand::parse_options(args); if (args["--output"]){ options_.outfile = args["--output"].asString(); } else { options_.outfile = AveCommand::options().trajectory + ".rdf.dat"; } options_.rmax = string2double(args["--max"].asString()); options_.npoints = string2long(args["--points"].asString()); options_.selection = args["--selection"].asString(); auto begin = argv; auto end = argv + argc; auto max_options = std::find_if(begin, end, [](const std::string& arg){ return arg.substr(std::min(5ul, arg.length())) == "--max"; }); if (AveCommand::options().custom_cell && max_options == end) { options_.rmax = biggest_sphere_radius(AveCommand::options().cell); } selection_ = Selection(options_.selection); if (selection_.size() > 2) { throw CFilesError("Can not use a selection with more than two atoms in RDF."); } else { coordination_ = Averager<double>(options_.npoints, 0, options_.rmax); return Averager<double>(options_.npoints, 0, options_.rmax); } } void Rdf::finish(const Histogram<double>& histogram) { coordination_.average(); std::ofstream outfile(options_.outfile, std::ios::out); if(!outfile.is_open()) { throw CFilesError("Could not open the '" + options_.outfile + "' file."); } outfile << "# Radial distribution function in trajectory " << AveCommand::options().trajectory << std::endl; outfile << "# Using selection: " << options_.selection << std::endl; outfile << "# r\tg(r)\tN(r) " << std::endl; for (size_t i=0; i<histogram.size(); i++){ outfile << histogram.first_coord(i) << "\t" << histogram[i] << "\t" << coordination_[i] << "\n"; } } void Rdf::accumulate(const Frame& frame, Histogram<double>& histogram) { check_rmax(frame); auto positions = frame.positions(); auto cell = frame.cell(); size_t n_first = 0; size_t n_second = 0; if (selection_.size() == 1) { // If we have a single atom selection, use it for both atoms of the // pairs auto matched = selection_.list(frame); n_first = matched.size(); n_second = matched.size(); for (auto i: matched) { for (auto j: matched) { if (i == j) continue; auto rij = norm(cell.wrap(positions[j] - positions[i])); if (rij < options_.rmax){ histogram.insert(rij); } } } } else { // If we have a pair selection, use it directly assert(selection_.size() == 2); auto matched = selection_.evaluate(frame); std::unordered_set<size_t> first_particles; std::unordered_set<size_t> second_particles; for (auto match: matched) { auto i = match[0]; auto j = match[1]; first_particles.insert(i); second_particles.insert(j); auto rij = norm(cell.wrap(positions[j] - positions[i])); if (rij < options_.rmax){ histogram.insert(rij); } } n_first = first_particles.size(); n_second = second_particles.size(); } if (n_first == 0 || n_second == 0) { warn_once( "No pair corresponding to '" + selection_.string() + "' found." ); } // Normalize the rdf to be 1 at long distances double volume = cell.volume(); if (volume <= 0) {volume = 1;} double dr = histogram.first().dr; double factor = n_first * n_second / volume; histogram.normalize([factor, dr](size_t i, double val){ double r = (i + 0.5) * dr; return val / (4 * PI * factor * dr * r * r); }); double rho = (n_first + n_second) / volume; for (size_t i=1; i<histogram.size(); i++){ auto r = (i + 0.5) * dr; coordination_[i] = coordination_[i - 1] + 4 * PI * rho * histogram[i] * r * r * dr; } coordination_.step(); } void Rdf::check_rmax(const chemfiles::Frame& frame) const { auto r_sphere = biggest_sphere_radius(frame.cell()); if (r_sphere < options_.rmax) { warn_once( "The maximal distance (--max option) is too big for this cell.\n" "The cell contains values up to " + std::to_string(r_sphere) + " and the max distance is " + std::to_string(options_.rmax) + "." ); } } double biggest_sphere_radius(const UnitCell& cell) { auto matrix = cell.matricial(); auto a = vector3d(matrix[0][0], matrix[1][0], matrix[2][0]); auto b = vector3d(matrix[0][1], matrix[1][1], matrix[2][1]); auto c = vector3d(matrix[0][2], matrix[1][2], matrix[2][2]); // Make sure we have an upper triangular matrix assert(matrix[1][0] == 0); assert(matrix[2][0] == 0); assert(matrix[2][1] == 0); // Plan normal vectors auto na = cross(b, c); auto nb = cross(c, a); auto nc = cross(a, b); auto ra = std::abs(dot(na, a)) / (2 * norm(na)); auto rb = std::abs(dot(nb, b)) / (2 * norm(nb)); auto rc = std::abs(dot(nc, c)) / (2 * norm(nc)); return std::min(ra, std::min(rb, rc)); }
36.239631
112
0.594608
[ "geometry" ]
2ab8b92b5cc203c9af875ce6870df259261a7c0d
1,776
hpp
C++
src/file2passwd_interface.hpp
ThorsHamster/file2passwd
39a3f115a7b21d1a2e18c00557ab487f7d68bcb7
[ "MIT" ]
null
null
null
src/file2passwd_interface.hpp
ThorsHamster/file2passwd
39a3f115a7b21d1a2e18c00557ab487f7d68bcb7
[ "MIT" ]
20
2019-12-15T15:32:23.000Z
2022-03-01T19:13:49.000Z
src/file2passwd_interface.hpp
ThorsHamster/file2passwd
39a3f115a7b21d1a2e18c00557ab487f7d68bcb7
[ "MIT" ]
null
null
null
#ifndef SRC_FILE2PASSWD_INTERFACE_HPP_ #define SRC_FILE2PASSWD_INTERFACE_HPP_ #include "file2passwd.hpp" namespace file2passwd { /*! \mainpage * * \section intro_sec Introduction * * This program is a Fun project, to play around with modern c++, swig, python and CMake. \n * It doesn't make too much sense, but it can be used to generate a password from a file. \n * This can be used either in C++ or python. \n * * * How to use it as python binding: \n * ~~~~~~~~~~~~~{.py} * import pyfile2passwd * * fpo = pyfile2passwd.File2Passwd("/path_to_file/file") * print(fpo.get_passwd()) * ~~~~~~~~~~~~~ */ /** * @class File2Passwd * * @brief Main Class for generating a Password from a File. * * Use it as follows: \n * File2Passwd fpo("Path to File"); \n * std::string passwd = fpo.get_passwd(); */ class File2Passwd { public: /// @brief Returns MD5 hash of file auto get_md5_hash(void) -> std::string; /// @brief Returns password generated out of file auto get_passwd(void) -> std::string; /// @brief Construct object /// /// @pre The file should be existent. /// /// @param path_to_file Absolute Path to File /// explicit File2Passwd(const std::string &path_to_file) : file2passwd_(std::make_unique<file2passwd::File2PasswdInternal>(std::make_unique<utilities::Utilities>(), std::make_unique<filereader::FileReader>(path_to_file), std::make_unique<openssl::OpenSSL>())){}; private: std::unique_ptr<file2passwd::File2PasswdInternal> file2passwd_; }; } // namespace file2passwd #endif
30.101695
177
0.600225
[ "object" ]
2ac4bb555eea2ac3054c85377526ff80e866fac7
14,052
cpp
C++
CsPlugin/Source/CsCore/Public/Managers/Input/GameEvent/CsGameEventDefinition.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
2
2019-03-17T10:43:53.000Z
2021-04-20T21:24:19.000Z
CsPlugin/Source/CsCore/Public/Managers/Input/GameEvent/CsGameEventDefinition.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
CsPlugin/Source/CsCore/Public/Managers/Input/GameEvent/CsGameEventDefinition.cpp
closedsum/core
c3cae44a177b9684585043a275130f9c7b67fef0
[ "Unlicense" ]
null
null
null
// Copyright 2017-2021 Closed Sum Games, LLC. All Rights Reserved. #include "Managers/Input/GameEvent/CsGameEventDefinition.h" #include "CsCore.h" // FCsGameEventDefinition #pragma region FString FCsGameEventDefinition::PrintSummary() const { // GameEvent // Phrase [%d] // Word [%d] // AndInputs [%d] // OrInputs [%d] FString Summary; if (!IsValid()) return Summary; Summary += Event.GetName(); Summary += TEXT("\n"); // Phrases const TArray<FCsInputPhrase>& Phrases = Sentence.Phrases; const int32 PhraseCount = Phrases.Num(); for (int32 I = 0; I < PhraseCount; ++I) { Summary += FString::Printf(TEXT(" Phrase [%d]"), I); Summary += TEXT("\n"); const FCsInputPhrase& Phrase = Phrases[I]; // Words const TArray<FCsInputWord>& Words = Phrase.Words; const int32 WordCount = Words.Num(); for (int32 J = 0; J < WordCount; ++J) { Summary += FString::Printf(TEXT(" Word [%d]"), J); Summary += TEXT("\n"); const FCsInputWord& Word = Words[J]; // AndInputs const TArray<FCsInputDescription>& AndInputs = Word.AndInputs; const int32 AndInputCount = AndInputs.Num(); for (int32 K = 0; K < AndInputCount; ++K) { Summary += FString::Printf(TEXT(" AndInput [%d]"), K); Summary += TEXT("\n"); const FCsInputDescription& Desc = AndInputs[K]; // Action Summary += FString::Printf(TEXT(" Action: %s"), Desc.Action.ToChar()); Summary += TEXT("\n"); // Event if (Desc.bAnyEvent) { Summary += FString::Printf(TEXT(" Event: AnyEvent")); } else { Summary += FString::Printf(TEXT(" Event: %s"), EMCsInputEvent::Get().ToChar(Desc.Event)); } Summary += TEXT("\n"); // CompareValue const FCsInputCompareValue& CompareValue = Desc.CompareValue; bool ValidCompareValue = false; { // Value const float& Value = CompareValue.Value; const ECsInputValueRule& ValueRule = CompareValue.ValueRule; if (ValueRule != ECsInputValueRule::None) { Summary += FString::Printf(TEXT(" CompareValue: %s %f"), EMCsInputValueRule::Get().ToDisplayNameChar(ValueRule), Value); ValidCompareValue = true; } // Location const FVector& Location = CompareValue.Location; const ECsInputLocationRule& LocationRule = CompareValue.LocationRule; if (LocationRule != ECsInputLocationRule::None) { Summary += FString::Printf(TEXT(" CompareValue: %s %s"), EMCsInputLocationRule::Get().ToDisplayNameChar(LocationRule), *(Location.ToString())); ValidCompareValue = true; } // Rotation const FRotator& Rotation = CompareValue.Rotation; const ECsInputRotationRule& RotationRule = CompareValue.RotationRule; if (RotationRule != ECsInputRotationRule::None) { Summary += FString::Printf(TEXT(" CompareValue: %s %s"), EMCsInputRotationRule::Get().ToDisplayNameChar(RotationRule), *(Rotation.ToString())); ValidCompareValue = true; } } if (ValidCompareValue) Summary += TEXT("\n"); // CompletedValue const FCsInputCompletedValue& CompletedValue = Desc.CompletedValue; { const ECsInputValue& ValueType = CompletedValue.ValueType; const ECsInputCompletedValueReturnType& ReturnType = CompletedValue.ReturnType; if (ValueType != ECsInputValue::Void && ReturnType != ECsInputCompletedValueReturnType::PassThrough) { // Float if (ValueType == ECsInputValue::Float) { Summary += FString::Printf(TEXT(" CompletedValue: %f"), CompletedValue.Value); } // Location if (ValueType == ECsInputValue::Vector) { Summary += FString::Printf(TEXT(" CompletedValue: %s"), *(CompletedValue.Location.ToString())); } // Rotation if (ValueType == ECsInputValue::Rotator) { Summary += FString::Printf(TEXT(" CompletedValue: %s"), *(CompletedValue.Rotation.ToString())); } } } if (K < AndInputCount - 1) Summary += TEXT("\n"); } if (AndInputCount > 1) Summary += TEXT("\n"); // OrInputs const TArray<FCsInputDescription>& OrInputs = Word.OrInputs; const int32 OrInputCount = OrInputs.Num(); for (int32 K = 0; K < OrInputCount; ++K) { Summary += FString::Printf(TEXT(" OrInput [%d]"), K); Summary += TEXT("\n"); const FCsInputDescription& Desc = OrInputs[K]; // Action Summary += FString::Printf(TEXT(" Action: %s"), Desc.Action.ToChar()); Summary += TEXT("\n"); // Event if (Desc.bAnyEvent) { Summary += FString::Printf(TEXT(" Event: AnyEvent")); } else { Summary += FString::Printf(TEXT(" Event: %s"), EMCsInputEvent::Get().ToChar(Desc.Event)); } Summary += TEXT("\n"); // CompareValue const FCsInputCompareValue& CompareValue = Desc.CompareValue; bool ValidCompareValue = false; { // Value const float& Value = CompareValue.Value; const ECsInputValueRule& ValueRule = CompareValue.ValueRule; if (ValueRule != ECsInputValueRule::None) { Summary += FString::Printf(TEXT(" CompareValue: %s %f"), EMCsInputValueRule::Get().ToDisplayNameChar(ValueRule), Value); ValidCompareValue = true; } // Location const FVector& Location = CompareValue.Location; const ECsInputLocationRule& LocationRule = CompareValue.LocationRule; if (LocationRule != ECsInputLocationRule::None) { Summary += FString::Printf(TEXT(" CompareValue: %s %s"), EMCsInputLocationRule::Get().ToDisplayNameChar(LocationRule), *(Location.ToString())); ValidCompareValue = true; } // Rotation const FRotator& Rotation = CompareValue.Rotation; const ECsInputRotationRule& RotationRule = CompareValue.RotationRule; if (RotationRule != ECsInputRotationRule::None) { Summary += FString::Printf(TEXT(" CompareValue: %s %s"), EMCsInputRotationRule::Get().ToDisplayNameChar(RotationRule), *(Rotation.ToString())); ValidCompareValue = true; } } if (ValidCompareValue) Summary += TEXT("\n"); // CompletedValue const FCsInputCompletedValue& CompletedValue = Desc.CompletedValue; { const ECsInputValue& ValueType = CompletedValue.ValueType; const ECsInputCompletedValueReturnType& ReturnType = CompletedValue.ReturnType; if (ValueType != ECsInputValue::Void && ReturnType != ECsInputCompletedValueReturnType::PassThrough) { // Float if (ValueType == ECsInputValue::Float) { Summary += FString::Printf(TEXT(" CompletedValue: %f"), CompletedValue.Value); } // Location if (ValueType == ECsInputValue::Vector) { Summary += FString::Printf(TEXT(" CompletedValue: %s"), *(CompletedValue.Location.ToString())); } // Rotation if (ValueType == ECsInputValue::Rotator) { Summary += FString::Printf(TEXT(" CompletedValue: %s"), *(CompletedValue.Rotation.ToString())); } } } if (K < AndInputCount - 1) Summary += TEXT("\n"); } if (J < WordCount - 1) Summary += TEXT("\n"); } if (I < PhraseCount - 1) Summary += TEXT("\n"); } return Summary; } #pragma endregion FCsGameEventDefinition // FCsGameEventDefinitionActionOneOrWordNoCompletedValue #pragma region void FCsGameEventDefinitionActionOneOrWordNoCompletedValue::AddDefinition(TSet<FCsGameEventDefinition>& GameEventDefinitions, TMap<FECsGameEvent, FCsInputSentence>& InputSentenceByGameEventMap) const { check(IsValid()); // Check if a sentence has ALREADY been added to InputSentenceByGameEventMap. checkf(!InputSentenceByGameEventMap.Find(GameEvent), TEXT("GameEvent: %s is already Set in GameEventDefintions and InputSentenceByGameEventMap."), GameEvent.ToChar()); // Sentence FCsInputSentence Sentence; Sentence.Reset(); Sentence.Phrases.AddDefaulted(); // Phrase FCsInputPhrase& Phrase = Sentence.Phrases.Last(); Phrase.Words.AddDefaulted(); // Word FCsInputWord& Word = Phrase.Words.Last(); for (const FCsInputActionAndEvent& Pair : Words) { Word.OrInputs.AddDefaulted(); // Description FCsInputDescription& Description = Word.OrInputs.Last(); Description.Action = Pair.Action; Description.Event = Pair.Event; // CompareValue FCsInputCompareValue& CompareValue = Description.CompareValue; CompareValue.ValueType = ECsInputValue::Void; CompareValue.ValueRule = ECsInputValueRule::None; // CompletedValue FCsInputCompletedValue& CompletedValue = Description.CompletedValue; CompletedValue.ValueType = ECsInputValue::Void; CompletedValue.ReturnType = ECsInputCompletedValueReturnType::PassThrough; } FCsGameEventDefinition GameEventDefinition; GameEventDefinition.Event = GameEvent; GameEventDefinition.Sentence = Sentence; GameEventDefinitions.Add(GameEventDefinition); InputSentenceByGameEventMap.Add(GameEvent, Sentence); } FString FCsGameEventDefinitionActionOneOrWordNoCompletedValue::PrintSummary() const { FString Summary; if (!IsValid()) return Summary; // GameEvent // Action Event // Action Event // ... Summary += GameEvent.GetName(); Summary += TEXT("\n"); const int32 Count = Words.Num(); for (int32 I = 0; I < Count; ++I) { const FCsInputActionAndEvent& Word = Words[I]; Summary += TEXT(" ") + Word.Action.GetName() + TEXT(" ") + EMCsInputEvent::Get().ToString(Word.Event); if (I < Count - 1) Summary += TEXT("\n"); } return Summary; } #pragma endregion FCsGameEventDefinitionActionOneOrWordNoCompletedValue // FCsGameEventDefinitionActionOneOrWordOneEventNoCompletedValue #pragma region void FCsGameEventDefinitionActionOneOrWordOneEventNoCompletedValue::AddDefinition(TSet<FCsGameEventDefinition>& GameEventDefinitions, TMap<FECsGameEvent, FCsInputSentence>& InputSentenceByGameEventMap) const { check(IsValid()); // Check if a sentence has ALREADY been added to InputSentenceByGameEventMap. checkf(!InputSentenceByGameEventMap.Find(GameEvent), TEXT("GameEvent: %s is already Set in GameEventDefintions and InputSentenceByGameEventMap."), GameEvent.ToChar()); // Sentence FCsInputSentence Sentence; Sentence.Reset(); Sentence.Phrases.AddDefaulted(); // Phrase FCsInputPhrase& Phrase = Sentence.Phrases.Last(); Phrase.Words.AddDefaulted(); // Word FCsInputWord& Word = Phrase.Words.Last(); for (const FECsInputAction& Action : Actions) { Word.OrInputs.AddDefaulted(); // Description FCsInputDescription& Description = Word.OrInputs.Last(); Description.Action = Action; Description.Event = Event; // CompareValue FCsInputCompareValue& CompareValue = Description.CompareValue; CompareValue.ValueType = ECsInputValue::Void; CompareValue.ValueRule = ECsInputValueRule::None; // CompletedValue FCsInputCompletedValue& CompletedValue = Description.CompletedValue; CompletedValue.ValueType = ECsInputValue::Void; CompletedValue.ReturnType = ECsInputCompletedValueReturnType::PassThrough; } FCsGameEventDefinition GameEventDefinition; GameEventDefinition.Event = GameEvent; GameEventDefinition.Sentence = Sentence; GameEventDefinitions.Add(GameEventDefinition); InputSentenceByGameEventMap.Add(GameEvent, Sentence); } FString FCsGameEventDefinitionActionOneOrWordOneEventNoCompletedValue::PrintOneLineSummary() const { FString Summary; if (!IsValid()) return Summary; // GameEvent: [Action, Action, Action] Event Summary += GameEvent.GetName() + TEXT(": ["); const int32 Count = Actions.Num(); for (int32 I = 0; I < Count; ++I) { Summary += Actions[I].GetName(); if (I < Count - 1) Summary += TEXT(", "); } Summary += TEXT("] ") + EMCsInputEvent::Get().ToString(Event); return Summary; } #pragma endregion FCsGameEventDefinitionActionOneOrWordOneEventNoCompletedValue // FCsGameEventDefinitionAxisOneOrWordNoComparePassThroughValue #pragma region void FCsGameEventDefinitionAxisOneOrWordNoComparePassThroughValue::AddDefinition(TSet<FCsGameEventDefinition>& GameEventDefinitions, TMap<FECsGameEvent, FCsInputSentence>& InputSentenceByGameEventMap) const { check(IsValid()); // Check if a sentence has ALREADY been added to InputSentenceByGameEventMap. checkf(!InputSentenceByGameEventMap.Find(GameEvent), TEXT("GameEvent: %s is already Set in GameEventDefintions and InputSentenceByGameEventMap."), GameEvent.ToChar()); // Sentence FCsInputSentence Sentence; Sentence.Reset(); Sentence.Phrases.AddDefaulted(); // Phrase FCsInputPhrase& Phrase = Sentence.Phrases.Last(); Phrase.Words.AddDefaulted(); // Word FCsInputWord& Word = Phrase.Words.Last(); for (const FECsInputAction& Action : Actions) { Word.OrInputs.AddDefaulted(); // Description FCsInputDescription& Description = Word.OrInputs.Last(); Description.Action = Action; Description.bAnyEvent = true; // CompareValue FCsInputCompareValue& CompareValue = Description.CompareValue; CompareValue.ValueType = ECsInputValue::Float; CompareValue.ValueRule = ECsInputValueRule::None; // CompletedValue FCsInputCompletedValue& CompletedValue = Description.CompletedValue; CompletedValue.ValueType = ECsInputValue::Float; CompletedValue.ReturnType = ECsInputCompletedValueReturnType::PassThrough; } FCsGameEventDefinition GameEventDefinition; GameEventDefinition.Event = GameEvent; GameEventDefinition.Sentence = Sentence; GameEventDefinitions.Add(GameEventDefinition); InputSentenceByGameEventMap.Add(GameEvent, Sentence); } FString FCsGameEventDefinitionAxisOneOrWordNoComparePassThroughValue::PrintOneLineSummary() const { FString Summary; if (!IsValid()) return Summary; // GameEvent: [Action, Action, Action] Summary += GameEvent.GetName() + TEXT(": ["); const int32 Count = Actions.Num(); for (int32 I = 0; I < Count; ++I) { Summary += Actions[I].GetName(); if (I < Count - 1) Summary += TEXT(", "); } Summary += TEXT("]"); return Summary; } #pragma endregion FCsGameEventDefinitionAxisOneOrWordNoComparePassThroughValue
30.547826
207
0.698619
[ "vector" ]
2acb6ce867cc6a000389b4262397c80d96f92898
9,652
cpp
C++
sys/os/linker/LDLibkernModule.cpp
JustSid/Firedrake
65c6fbecf63ebbcd7d8798d9bfe35fa225cd5c41
[ "MIT" ]
8
2015-07-06T09:03:35.000Z
2019-07-15T22:53:16.000Z
sys/os/linker/LDLibkernModule.cpp
JustSid/Firedrake
65c6fbecf63ebbcd7d8798d9bfe35fa225cd5c41
[ "MIT" ]
null
null
null
sys/os/linker/LDLibkernModule.cpp
JustSid/Firedrake
65c6fbecf63ebbcd7d8798d9bfe35fa225cd5c41
[ "MIT" ]
6
2015-12-10T17:52:49.000Z
2019-07-15T22:53:23.000Z
// // LDLibkernModule.cpp // Firedrake // // Created by Sidney Just // Copyright (c) 2015 by Sidney Just // Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated // documentation files (the "Software"), to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, // and to permit persons to whom the Software is furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // #include <kern/kprintf.h> #include <kern/kalloc.h> #include <kern/panic.h> #include <libio/core/IOCatalogue.h> #include <libio/core/IONull.h> #include <libio/core/IOArray.h> #include <libio/core/IORegistry.h> #include <libio/hid/IOHIDKeyboardUtilities.h> #include <libio/video/IODisplay.h> #include <os/scheduler/scheduler.h> #include <vfs/devfs/devices.h> #include <machine/interrupts/interrupts.h> #include "LDModule.h" #include "LDService.h" // ------------- // The libkern.so library is a bit of hack since it provides symbols from the kernel // which are overriden hre to point to the real symbols in the kernel. // // It also contains stubs for __libkern_getIOCatalogue() and __libkern_getIONull() // which bridge the custom built libio/core in the Firedrake kernel // and the actual libio dynamic library. // ------------- namespace OS { namespace LD { void *__libio_getIOCatalogue() { return IO::Catalogue::GetSharedInstance(); } void *__libio_getIONull() { return IO::Catalogue::GetSharedInstance(); } void *__libio_getIORootRegistry() { return IO::RegistryEntry::GetRootEntry(); } void __libkern_threadEntry(void (*entry)(void *), void *argument) { entry(argument); Scheduler *scheduler = Scheduler::GetScheduler(); Thread *thread = scheduler->GetActiveThread(); scheduler->BlockThread(thread); scheduler->RemoveThread(thread); scheduler->GetActiveTask()->MarkThreadExit(thread); while(1) {} } void thread_yield() { Scheduler *scheduler = Scheduler::GetScheduler(); scheduler->YieldThread(scheduler->GetActiveThread()); } void thread_create(void (*entry)(void *), void *argument) { Task *task = Scheduler::GetScheduler()->GetActiveTask(); IO::Number *entryNum = IO::Number::Alloc()->InitWithUint32(reinterpret_cast<uint32_t>(entry)); IO::Number *argNum = IO::Number::Alloc()->InitWithUint32(reinterpret_cast<uint32_t>(argument)); IO::Array *parameters = IO::Array::Alloc()->Init(); parameters->AddObject(entryNum); parameters->AddObject(argNum); entryNum->Release(); argNum->Release(); task->AttachThread(reinterpret_cast<Thread::Entry >(&__libkern_threadEntry), Thread::PriorityClassKernel, 0, parameters); parameters->Release(); } void *__libkern_dma_map(uintptr_t physical, size_t pages) { Sys::VM::Directory *directory = Sys::VM::Directory::GetKernelDirectory(); KernReturn<vm_address_t> result = directory->Alloc(physical, pages, kVMFlagsKernel); return (result.IsValid()) ? reinterpret_cast<void *>(result.Get()) : nullptr; } void __libkern_dma_free(void *virt, size_t pages) { Sys::VM::Directory *directory = Sys::VM::Directory::GetKernelDirectory(); directory->Free(reinterpret_cast<vm_address_t>(virt), pages); } typedef void (*InterruptHandler)(void *argument, uint8_t vector); struct InterruptEntry { InterruptHandler handler; void *argument; }; static Mutex __interruptLock; static InterruptEntry __interruptEntries[255]; uint32_t __libkern_interruptHandler(uint32_t esp, __unused Sys::CPU *cpu) { Sys::CPUState *state = reinterpret_cast<Sys::CPUState *>(esp); InterruptEntry *entry = __interruptEntries + state->interrupt; entry->handler(entry->argument, static_cast<uint8_t>(state->interrupt)); return esp; } void register_interrupt(uint8_t vector, void *argument, InterruptHandler handler) { __interruptLock.Lock(Mutex::Mode::NoInterrupts); InterruptEntry *entry = __interruptEntries + vector; entry->argument = argument; entry->handler = handler; __interruptLock.Unlock(); if(vector < 0x30) Sys::APIC::MaskInterrupt(vector, (handler == nullptr)); Sys::SetInterruptHandler(vector, &__libkern_interruptHandler); } static IO::KeyboardEvent _eventStack[128]; static size_t _eventStackSize = 0; void __libkern_handleKeyboardEvent(void *context) { IO::KeyboardEvent *event = reinterpret_cast<IO::KeyboardEvent *>(context); VFS::Devices::Keyboard *keyboard = VFS::Devices::GetKeyboard(event->GetSender()); keyboard->HandleEvent(event); } void __libkern_dispatchKeyboardEvent(IO::KeyboardEvent *event) { memcpy(_eventStack + _eventStackSize, event, sizeof(IO::KeyboardEvent)); Sys::CPU::GetCurrentCPU()->GetWorkQueue()->PushEntry(&__libkern_handleKeyboardEvent, _eventStack + _eventStackSize); _eventStackSize = (_eventStackSize + 1) % 128; } IO::Object *__libkern_registerKeyboard(IO::Object *service) { VFS::Devices::Keyboard *keyboard = VFS::Devices::RegisterKeyboard(service); return keyboard; } void __libkern_unregisterKeyboard(IO::Object *service) { VFS::Devices::UnregisterKeyboard(service); } void __libkern_registerFramebuffer(IO::Framebuffer *buffer) { __unused VFS::Devices::Framebuffer *framebuffer = VFS::Devices::RegisterFramebuffer(buffer); } void __libkern_unregisterFramebuffer(IO::Framebuffer *buffer) { VFS::Devices::UnregisterFramebuffer(buffer); } ipc_return_t ipc_write(ipc_header_t *header) { IPC::Space *space = IPC::Space::GetKernelSpace(); IPC::Message *message = IPC::Message::Alloc()->Init(header); space->Lock(); KernReturn<void> result = space->Write(message); space->Unlock(); message->Release(); return result.IsValid() ? KERN_SUCCESS : result.GetError().GetCode(); } ipc_return_t ipc_read(ipc_header_t *header) { IPC::Space *space = IPC::Space::GetKernelSpace(); IPC::Message *message = IPC::Message::Alloc()->Init(header); space->Lock(); KernReturn<void> result = space->Read(message); space->Unlock(); message->Release(); return result.IsValid() ? KERN_SUCCESS : result.GetError().GetCode(); } ipc_return_t ipc_allocate_port(ipc_port_t *port) { IPC::Space *space = IPC::Space::GetKernelSpace(); space->Lock(); KernReturn<IPC::Port *> actual = space->AllocateReceivePort(); if(!actual.IsValid()) { space->Unlock(); return actual.GetError().GetCode(); } *port = actual->GetName(); space->Unlock(); return KERN_SUCCESS; } ipc_return_t ipc_port_deallocate(ipc_port_t port) { IPC::Space *space = IPC::Space::GetKernelSpace(); space->Lock(); IPC::Port *actual = space->GetPortWithName(port); if(!actual) { space->Unlock(); return KERN_INVALID_ARGUMENT; } space->DeallocatePort(actual); space->Unlock(); return KERN_SUCCESS; } ipc_port_t ipc_get_special_port(int port) { switch(port) { case 0: return GetKernelPort()->GetName(); } return IPC_PORT_NULL; } #define ELF_SYMBOL_STUB(function) \ { #function, { kModuleSymbolStubName, (elf32_address_t)function, 0, 0, 0, 0 } } struct LibKernSymbol { const char *name; elf_sym_t symbol; }; LibKernSymbol __libkernModuleSymbols[] = { ELF_SYMBOL_STUB(panic), ELF_SYMBOL_STUB(kprintf), ELF_SYMBOL_STUB(kputs), ELF_SYMBOL_STUB(knputs), ELF_SYMBOL_STUB(kalloc), ELF_SYMBOL_STUB(kfree), ELF_SYMBOL_STUB(__libio_getIOCatalogue), ELF_SYMBOL_STUB(__libio_getIONull), ELF_SYMBOL_STUB(__libio_getIORootRegistry), ELF_SYMBOL_STUB(thread_yield), ELF_SYMBOL_STUB(thread_create), ELF_SYMBOL_STUB(__libkern_dma_map), ELF_SYMBOL_STUB(__libkern_dma_free), ELF_SYMBOL_STUB(register_interrupt), ELF_SYMBOL_STUB(__libkern_dispatchKeyboardEvent), ELF_SYMBOL_STUB(__libkern_registerKeyboard), ELF_SYMBOL_STUB(__libkern_unregisterKeyboard), ELF_SYMBOL_STUB(__libkern_registerFramebuffer), ELF_SYMBOL_STUB(__libkern_unregisterFramebuffer), ELF_SYMBOL_STUB(ipc_write), ELF_SYMBOL_STUB(ipc_read), ELF_SYMBOL_STUB(ipc_allocate_port), ELF_SYMBOL_STUB(ipc_port_deallocate), ELF_SYMBOL_STUB(ipc_get_special_port) }; elf_sym_t *LibkernModule::GetSymbolWithName(const char *name) { for(size_t i = 0; i < sizeof(__libkernModuleSymbols) / sizeof(LibKernSymbol); i ++) { if(strcmp(name, __libkernModuleSymbols[i].name) == 0) { return &__libkernModuleSymbols[i].symbol; } } return Module::GetSymbolWithName(name); } void *LibkernModule::GetSymbolAddressWithName(const char *name) { elf_sym_t *symbol = GetSymbolWithName(name); if(symbol) { if(symbol->st_name == kModuleSymbolStubName) return reinterpret_cast<void *>(symbol->st_value); return reinterpret_cast<void *>(GetRelocationBase() + symbol->st_value); } return nullptr; } } }
28.72619
130
0.71809
[ "object", "vector" ]
2acbe6b77ca1e32b9e7cc8cee7e9bab296f7cab0
2,041
hh
C++
src/Zynga/Framework/Database/V2/Config/BaseTest.hh
ssintzz/zynga-hacklang-framework
9e165068f16f224edf2ee5bf5e25855714792d54
[ "MIT" ]
19
2018-04-23T09:30:48.000Z
2022-03-06T21:35:18.000Z
src/Zynga/Framework/Database/V2/Config/BaseTest.hh
ssintzz/zynga-hacklang-framework
9e165068f16f224edf2ee5bf5e25855714792d54
[ "MIT" ]
22
2017-11-27T23:39:25.000Z
2019-08-09T08:56:57.000Z
src/Zynga/Framework/Database/V2/Config/BaseTest.hh
ssintzz/zynga-hacklang-framework
9e165068f16f224edf2ee5bf5e25855714792d54
[ "MIT" ]
28
2017-11-16T20:53:56.000Z
2021-01-04T11:13:17.000Z
<?hh //strict namespace Zynga\Framework\Database\V2\Config; use Zynga\Framework\Testing\TestCase\V2\Base as TestCase; use Zynga\Framework\Database\V2\Test\Config\Mock\Base\Valid as MockValid; use Zynga\Framework\Database\V2\Test\Config\Mock\Base\NoUserName as MockNoUserName ; use Zynga\Framework\Database\V2\Test\Config\Mock\Base\NoPassword as MockNoPassword ; use Zynga\Framework\Database\V2\Test\Config\Mock\Base\NoPort as MockNoPort; use Zynga\Framework\Database\V2\Test\Config\Mock\Base\EmptyConfig as MockEmptyConfig ; class BaseTest extends TestCase { /** * Test the object stands up without any values */ << expectedException( "Zynga\Framework\Database\V2\Exceptions\NoUserNameException", ) >> public function testConstruct(): void { $obj = new MockEmptyConfig(); } /** * Test the lack of a username is emitting exceptions */ << expectedException( "Zynga\Framework\Database\V2\Exceptions\NoUserNameException", ) >> public function testNoUsername(): void { $obj = new MockNoUserName(); } /** * Test the lack of a password is emitting exceptions */ << expectedException( "Zynga\Framework\Database\V2\Exceptions\NoPasswordException", ) >> public function testNoPassword(): void { $obj = new MockNoPassword(); } /** * Test the lack of a port is emitting exceptions */ << expectedException( "Zynga\Framework\Database\V2\Exceptions\NoPortProvidedException", ) >> public function testNoPort(): void { $obj = new MockNoPort(); } public function testDatabaseFunctions(): void { $expectedDatabase = 'oratest'; $expectedServer = ''; $expectedPort = 123; $conf = new MockValid(); $this->assertEquals('', $conf->getCurrentDatabase()); $conf->setCurrentDatabase($expectedDatabase); $this->assertEquals($expectedDatabase, $conf->getCurrentDatabase()); $this->assertEquals($expectedPort, $conf->getPort()); $this->assertEquals($expectedServer, $conf->getCurrentServer()); } }
23.45977
82
0.701127
[ "object" ]
2acde052230ada18a362dd38e77f8bf7a6ea7616
14,602
hpp
C++
c++/include/objtools/readers/fasta.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
c++/include/objtools/readers/fasta.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
c++/include/objtools/readers/fasta.hpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
#ifndef OBJTOOLS_READERS___FASTA__HPP #define OBJTOOLS_READERS___FASTA__HPP /* $Id: fasta.hpp 368052 2012-07-02 14:37:28Z ucko $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Authors: Aaron Ucko, NCBI * */ /// @file fasta.hpp /// Interfaces for reading and scanning FASTA-format sequences. #include <corelib/ncbi_limits.hpp> #include <corelib/ncbi_param.hpp> #include <util/line_reader.hpp> #include <objects/seq/Bioseq.hpp> #include <objects/seq/seq_id_handle.hpp> #include <objects/seqloc/Seq_loc.hpp> #include <objtools/readers/source_mod_parser.hpp> // #include <objects/seqset/Seq_entry.hpp> #include <stack> /** @addtogroup Miscellaneous * * @{ */ BEGIN_NCBI_SCOPE BEGIN_SCOPE(objects) class CSeq_data; class CSeq_entry; class CSeq_loc; class CSeqIdGenerator; /// Base class for reading FASTA sequences. /// /// This class should suffice as for typical usage, but its /// implementation has been broken up into virtual functions, allowing /// for a wide range of specialized subclasses. /// /// @sa CFastaOstream class NCBI_XOBJREAD_EXPORT CFastaReader { public: /// Note on fAllSeqIds: some databases (notably nr) have merged /// identical sequences, joining their deflines together with /// control-As. Normally, the reader stops at the first /// control-A; however, this flag makes it parse all the IDs. enum EFlags { fAssumeNuc = 1<< 0, ///< Assume nucs unless accns indicate otherwise fAssumeProt = 1<< 1, ///< Assume prots unless accns indicate otherwise fForceType = 1<< 2, ///< Force specified type regardless of accession fNoParseID = 1<< 3, ///< Generate an ID (whole defline -> title) fParseGaps = 1<< 4, ///< Make a delta sequence if gaps found fOneSeq = 1<< 5, ///< Just read the first sequence found fAllSeqIds = 1<< 6, ///< Read Seq-ids past the first ^A (see note) fNoSeqData = 1<< 7, ///< Parse the deflines but skip the data fRequireID = 1<< 8, ///< Reject deflines that lack IDs fDLOptional = 1<< 9, ///< Don't require a leading defline fParseRawID = 1<<10, ///< Try to identify raw accessions fSkipCheck = 1<<11, ///< Skip (rudimentary) body content check fNoSplit = 1<<12, ///< Don't split out ambiguous sequence regions fValidate = 1<<13, ///< Check (alphabetic) residue validity fUniqueIDs = 1<<14, ///< Forbid duplicate IDs fStrictGuess = 1<<15, ///< Assume no typos when guessing sequence type fLaxGuess = 1<<16, ///< Use legacy heuristic for guessing seq. type fAddMods = 1<<17, ///< Parse defline mods and add to SeqEntry fLetterGaps = 1<<18, ///< Parse runs of Ns when splitting data fNoUserObjs = 1<<19, ///< Don't save raw deflines in User-objects fBadModThrow = 1<<20, ///< Throw an exception if there's a bad modifier value (e.g. "[topology=nonsense]") fUnknModThrow = 1<<21, ///< Throw if there are any unknown (unused) mods left over fLeaveAsText = 1<<22, ///< Don't reencode at all, just parse fQuickIDCheck = 1<<23 ///< Just check local IDs' first characters }; typedef int TFlags; ///< binary OR of EFlags CFastaReader(ILineReader& reader, TFlags flags = 0); CFastaReader(CNcbiIstream& in, TFlags flags = 0); CFastaReader(const string& path, TFlags flags = 0); virtual ~CFastaReader(void); /// Indicates (negatively) whether there is any more input. bool AtEOF(void) const { return m_LineReader->AtEOF(); } /// Read a single effective sequence, which may turn out to be a /// segmented set. virtual CRef<CSeq_entry> ReadOneSeq(void); /// Read multiple sequences (by default, as many as are available.) CRef<CSeq_entry> ReadSet(int max_seqs = kMax_Int); /// Read as many sequences as are available, and interpret them as /// an alignment, with hyphens marking relative deletions. /// @param reference_row /// 0-based; the special value -1 yields a full (pseudo-?)N-way alignment. CRef<CSeq_entry> ReadAlignedSet(int reference_row); // also allow changing? TFlags GetFlags(void) const { return m_Flags.top(); } typedef CRef<CSeq_loc> TMask; typedef vector<TMask> TMasks; /// Directs the *following* call to ReadOneSeq to note the locations /// of lowercase letters. /// @return /// A smart pointer to the Seq-loc that will be populated. CRef<CSeq_loc> SaveMask(void); void SaveMasks(TMasks* masks) { m_MaskVec = masks; } const CBioseq::TId& GetIDs(void) const { return m_CurrentSeq->GetId(); } const CSeq_id& GetBestID(void) const { return *m_BestID; } const CSeqIdGenerator& GetIDGenerator(void) const { return *m_IDGenerator; } CSeqIdGenerator& SetIDGenerator(void) { return *m_IDGenerator; } void SetIDGenerator(CSeqIdGenerator& gen); /// Re-allow previously seen IDs even if fUniqueIds is on. void ResetIDTracker(void) { m_IDTracker.clear(); } const CSourceModParser::TMods & GetBadMods(void) const { return m_BadMods; } void ClearBadMods(void) { m_BadMods.clear(); } protected: enum EInternalFlags { fAligning = 0x40000000, fInSegSet = 0x20000000 }; typedef CTempString TStr; virtual CRef<CSeq_entry> x_ReadSegSet(void); virtual void ParseDefLine (const TStr& s); virtual bool ParseIDs (const TStr& s); virtual size_t ParseRange (const TStr& s, TSeqPos& start, TSeqPos& end); virtual void ParseTitle (const TStr& s); virtual bool IsValidLocalID(const TStr& s); virtual void GenerateID (void); virtual void ParseDataLine (const TStr& s); virtual void CheckDataLine (const TStr& s); virtual void x_CloseGap (TSeqPos len); virtual void x_OpenMask (void); virtual void x_CloseMask (void); virtual bool ParseGapLine (const TStr& s); virtual void AssembleSeq (void); virtual void AssignMolType (void); virtual void SaveSeqData (CSeq_data& seq_data, const TStr& raw_string); typedef int TRowNum; typedef map<TRowNum, TSignedSeqPos> TSubMap; // align coord -> row -> seq coord typedef map<TSeqPos, TSubMap> TStartsMap; typedef vector<CRef<CSeq_id> > TIds; CRef<CSeq_entry> x_ReadSeqsToAlign(TIds& ids); void x_AddPairwiseAlignments(CSeq_annot& annot, const TIds& ids, TRowNum reference_row); void x_AddMultiwayAlignment(CSeq_annot& annot, const TIds& ids); // inline utilities void CloseGap(void); void OpenMask(void); void CloseMask(void) { if (m_MaskRangeStart != kInvalidSeqPos) { x_CloseMask(); } } Int8 StreamPosition(void) const { return NcbiStreamposToInt8(m_LineReader->GetPosition()); } unsigned int LineNumber(void) const { return m_LineReader->GetLineNumber(); } ILineReader& GetLineReader(void) { return *m_LineReader; } bool TestFlag(EFlags flag) const { return (GetFlags() & flag) != 0; } bool TestFlag(EInternalFlags flag) const { return (GetFlags() & flag) != 0; } CBioseq::TId& SetIDs(void) { return m_CurrentSeq->SetId(); } // NB: Not necessarily fully-formed! CBioseq& SetCurrentSeq(void) { return *m_CurrentSeq; } enum EPosType { eRawPos, ePosWithGaps, ePosWithGapsAndSegs }; TSeqPos GetCurrentPos(EPosType pos_type); void x_RecursiveApplyAllMods( CSeq_entry& entry ); std::string x_NucOrProt(void) const; private: struct SGap { TSeqPos pos; // 0-based, and NOT counting previous gaps TSignedSeqPos len; // 0: unknown, negative: negated nominal length }; typedef vector<SGap> TGaps; typedef set<CSeq_id_Handle> TIDTracker; CRef<ILineReader> m_LineReader; stack<TFlags> m_Flags; CRef<CBioseq> m_CurrentSeq; TMask m_CurrentMask; TMask m_NextMask; TMasks * m_MaskVec; CRef<CSeqIdGenerator> m_IDGenerator; string m_SeqData; TGaps m_Gaps; TSeqPos m_CurrentPos; // does not count gaps TSeqPos m_ExpectedEnd; TSeqPos m_MaskRangeStart; TSeqPos m_SegmentBase; TSeqPos m_CurrentGapLength; TSeqPos m_TotalGapLength; CRef<CSeq_id> m_BestID; TStartsMap m_Starts; TRowNum m_Row; TSeqPos m_Offset; TIDTracker m_IDTracker; CSourceModParser::TMods m_BadMods; }; class NCBI_XOBJREAD_EXPORT CSeqIdGenerator : public CObject { public: typedef CAtomicCounter::TValue TInt; CSeqIdGenerator(TInt counter = 1, const string& prefix = kEmptyStr, const string& suffix = kEmptyStr) : m_Prefix(prefix), m_Suffix(suffix), m_Counter(counter) { } CRef<CSeq_id> GenerateID(bool advance); /// Equivalent to GenerateID(false) CRef<CSeq_id> GenerateID(void) const; const string& GetPrefix (void) { return m_Prefix; } TInt GetCounter(void) { return m_Counter.Get(); } const string& GetSuffix (void) { return m_Suffix; } void SetPrefix (const string& s) { m_Prefix = s; } void SetCounter(TInt n) { m_Counter.Set(n); } void SetSuffix (const string& s) { m_Suffix = s; } private: string m_Prefix, m_Suffix; CAtomicCounter_WithAutoInit m_Counter; }; enum EReadFastaFlags { fReadFasta_AssumeNuc = CFastaReader::fAssumeNuc, fReadFasta_AssumeProt = CFastaReader::fAssumeProt, fReadFasta_ForceType = CFastaReader::fForceType, fReadFasta_NoParseID = CFastaReader::fNoParseID, fReadFasta_ParseGaps = CFastaReader::fParseGaps, fReadFasta_OneSeq = CFastaReader::fOneSeq, fReadFasta_AllSeqIds = CFastaReader::fAllSeqIds, fReadFasta_NoSeqData = CFastaReader::fNoSeqData, fReadFasta_RequireID = CFastaReader::fRequireID }; typedef CFastaReader::TFlags TReadFastaFlags; /// Traditional interface for reading FASTA files. The /// USE_NEW_IMPLEMENTATION parameter governs whether to use /// CFastaReader or the traditional implementation. /// @deprecated /// @sa CFastaReader NCBI_DEPRECATED NCBI_XOBJREAD_EXPORT CRef<CSeq_entry> ReadFasta(CNcbiIstream& in, TReadFastaFlags flags = 0, int* counter = 0, vector<CConstRef<CSeq_loc> >* lcv = 0); NCBI_PARAM_DECL(bool, READ_FASTA, USE_NEW_IMPLEMENTATION); ////////////////////////////////////////////////////////////////// // // Class - description of multi-entry FASTA file, // to keep list of offsets on all molecules in the file. // struct SFastaFileMap { struct SFastaEntry { SFastaEntry() : stream_offset(0) {} /// List of qll sequence ids typedef list<string> TFastaSeqIds; string seq_id; ///< Primary sequence Id string description; ///< Molecule description CNcbiStreampos stream_offset; ///< Molecule offset in file TFastaSeqIds all_seq_ids; ///< List of all seq.ids }; typedef vector<SFastaEntry> TMapVector; TMapVector file_map; // vector keeps list of all molecule entries }; /// Callback interface to scan fasta file for entries class NCBI_XOBJREAD_EXPORT IFastaEntryScan { public: virtual ~IFastaEntryScan(); /// Callback function, called after reading the fasta entry virtual void EntryFound(CRef<CSeq_entry> se, CNcbiStreampos stream_position) = 0; }; /// Function reads input stream (assumed that it is FASTA format) one /// molecule entry after another filling the map structure describing and /// pointing on molecule entries. Fasta map can be used later for quick /// CSeq_entry retrival void NCBI_XOBJREAD_EXPORT ReadFastaFileMap(SFastaFileMap* fasta_map, CNcbiIfstream& input); /// Scan FASTA files, call IFastaEntryScan::EntryFound (payload function) void NCBI_XOBJREAD_EXPORT ScanFastaFile(IFastaEntryScan* scanner, CNcbiIfstream& input, TReadFastaFlags fread_flags); /////////////////// CFastaReader inline methods inline void CFastaReader::CloseGap(void) { if (m_CurrentGapLength > 0) { x_CloseGap(m_CurrentGapLength); } m_CurrentGapLength = 0; } inline void CFastaReader::OpenMask() { if (m_MaskRangeStart == kInvalidSeqPos && m_CurrentMask.NotEmpty()) { x_OpenMask(); } } inline TSeqPos CFastaReader::GetCurrentPos(EPosType pos_type) { TSeqPos pos = m_CurrentPos; switch (pos_type) { case ePosWithGapsAndSegs: pos += m_SegmentBase; // fall through case ePosWithGaps: pos += m_TotalGapLength; // fall through case eRawPos: return pos; default: return kInvalidSeqPos; } } END_SCOPE(objects) END_NCBI_SCOPE /* @} */ #endif /* OBJTOOLS_READERS___FASTA__HPP */
36.780856
115
0.642241
[ "vector" ]
2ad7b545324f58e0b02bb285a623c5b25ae8262b
1,125
cpp
C++
computer_graphics/junkyard/glengine/gerenderer.cpp
asgeir/old-school-projects
96a502589c627e4556f9ee14fc1dc21ed53ce28a
[ "MIT" ]
null
null
null
computer_graphics/junkyard/glengine/gerenderer.cpp
asgeir/old-school-projects
96a502589c627e4556f9ee14fc1dc21ed53ce28a
[ "MIT" ]
null
null
null
computer_graphics/junkyard/glengine/gerenderer.cpp
asgeir/old-school-projects
96a502589c627e4556f9ee14fc1dc21ed53ce28a
[ "MIT" ]
null
null
null
#include "gerenderer.h" #include "gecamera.h" #include "gerenderstate.h" #include "geshaderprogram.h" #include "gl_core_3_2.h" void Renderable::render() { switch (primitiveType()) { case kPrimitiveTypeTriangles: glDrawArrays(GL_TRIANGLES, 0, numVertices()); break; default: break; } } void Renderer::render(const RenderList &renderables, RenderState *renderState) { renderState->bindProgram(); int clearFlags = renderState->clearFlags(); GLbitfield glClearFlags = 0; if (clearFlags & kClearFlagColor) { glClearFlags |= GL_COLOR_BUFFER_BIT; } if (clearFlags & kClearFlagDepth) { glClearFlags |= GL_DEPTH_BUFFER_BIT; } glClear(glClearFlags); glm::mat4 viewProjection = m_camera->viewProjectionMatrix(); for (auto renderable : renderables) { renderState->setShaderUniform(kShaderParamModelViewProjection, viewProjection * renderable->transform()); renderState->bind(); renderable->bind(renderState); renderable->render(); renderable->unbind(renderState); renderState->unbind(); renderState->unsetShaderUniform(kShaderParamModelViewProjection); } renderState->unbindProgram(); }
22.5
107
0.753778
[ "render", "transform" ]
2ae98e83f406185c87bc9fc8f836a6521e6c278e
7,226
cpp
C++
Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.0 Samples/[C++]-Windows Driver Kit (WDK) 8.0 Samples/C++/WDK 8.0 Samples/XPSDrv Driver and Filter Sample/Solution/src/ui/wmppg.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
2
2022-01-21T01:40:58.000Z
2022-01-21T01:41:10.000Z
Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.0 Samples/[C++]-Windows Driver Kit (WDK) 8.0 Samples/C++/WDK 8.0 Samples/XPSDrv Driver and Filter Sample/Solution/src/ui/wmppg.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
1
2022-03-15T04:21:41.000Z
2022-03-15T04:21:41.000Z
Official Windows Driver Kit Sample/Windows Driver Kit (WDK) 8.0 Samples/[C++]-Windows Driver Kit (WDK) 8.0 Samples/C++/WDK 8.0 Samples/XPSDrv Driver and Filter Sample/Solution/src/ui/wmppg.cpp
zzgchina888/msdn-code-gallery-microsoft
21cb9b6bc0da3b234c5854ecac449cb3bd261f29
[ "MIT" ]
2
2020-10-19T23:36:26.000Z
2020-10-22T12:59:37.000Z
/*++ Copyright (c) 2005 Microsoft Corporation All rights reserved. THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. File Name: wmppg.cpp Abstract: Implementation of the watermark property page. This class is responsible for initialising and registering the color management property page and its controls. --*/ #include "precomp.h" #include "debug.h" #include "globals.h" #include "xdexcept.h" #include "xdstring.h" #include "resource.h" #include "wmppg.h" #include "wmctrls.h" /*++ Routine Name: CWatermarkPropPage::CWatermarkPropPage Routine Description: CWatermarkPropPage class constructor. Creates a handler class object for every control on the watermark property page. Each of these handlers is stored in a collection. Arguments: None Return Value: None Throws CXDException(HRESULT) on an error --*/ CWatermarkPropPage::CWatermarkPropPage() { HRESULT hr = S_OK; try { CUIControl* pControl = new CUICtrlWMTypeCombo(); if (SUCCEEDED(hr = CHECK_POINTER(pControl, E_OUTOFMEMORY))) { hr = AddUIControl(IDC_COMBO_WMTYPE, pControl); } if (SUCCEEDED(hr)) { pControl = new CUICtrlWMLayeringCombo(); if (SUCCEEDED(hr = CHECK_POINTER(pControl, E_OUTOFMEMORY))) { hr = AddUIControl(IDC_COMBO_WMLAYERING, pControl); } } if (SUCCEEDED(hr)) { pControl = new CUICtrlWMTextEdit(); if (SUCCEEDED(hr = CHECK_POINTER(pControl, E_OUTOFMEMORY))) { hr = AddUIControl(IDC_EDIT_WMTEXT, pControl); } } if (SUCCEEDED(hr)) { pControl = new CUICtrlWMTransparencyEdit(); if (SUCCEEDED(hr = CHECK_POINTER(pControl, E_OUTOFMEMORY)) && SUCCEEDED(hr = AddUIControl(IDC_EDIT_WMTRANSPARENCY, pControl))) { pControl = new CUICtrlWMTransparencySpin(reinterpret_cast<CUICtrlDefaultEditNum *>(pControl)); if (SUCCEEDED(hr = CHECK_POINTER(pControl, E_OUTOFMEMORY))) { hr = AddUIControl(IDC_SPIN_WMTRANSPARENCY, pControl); } } } if (SUCCEEDED(hr)) { pControl = new CUICtrlWMAngleEdit(); if (SUCCEEDED(hr = CHECK_POINTER(pControl, E_OUTOFMEMORY)) && SUCCEEDED(hr = AddUIControl(IDC_EDIT_WMANGLE, pControl))) { pControl = new CUICtrlWMAngleSpin(reinterpret_cast<CUICtrlDefaultEditNum *>(pControl)); if (SUCCEEDED(hr = CHECK_POINTER(pControl, E_OUTOFMEMORY))) { hr = AddUIControl(IDC_SPIN_WMANGLE, pControl); } } } if (SUCCEEDED(hr)) { pControl = new CUICtrlWMOffsetXEdit(); if (SUCCEEDED(hr = CHECK_POINTER(pControl, E_OUTOFMEMORY)) && SUCCEEDED(hr = AddUIControl(IDC_EDIT_WMOFFX, pControl))) { pControl = new CUICtrlWMOffsetXSpin(reinterpret_cast<CUICtrlDefaultEditNum *>(pControl)); if (SUCCEEDED(hr = CHECK_POINTER(pControl, E_OUTOFMEMORY))) { hr = AddUIControl(IDC_SPIN_WMOFFX, pControl); } } } if (SUCCEEDED(hr)) { pControl = new CUICtrlWMOffsetYEdit(); if (SUCCEEDED(hr = CHECK_POINTER(pControl, E_OUTOFMEMORY)) && SUCCEEDED(hr = AddUIControl(IDC_EDIT_WMOFFY, pControl))) { pControl = new CUICtrlWMOffsetYSpin(reinterpret_cast<CUICtrlDefaultEditNum *>(pControl)); if (SUCCEEDED(hr = CHECK_POINTER(pControl, E_OUTOFMEMORY))) { hr = AddUIControl(IDC_SPIN_WMOFFY, pControl); } } } if (SUCCEEDED(hr)) { pControl = new CUICtrlWMWidthEdit(); if (SUCCEEDED(hr = CHECK_POINTER(pControl, E_OUTOFMEMORY)) && SUCCEEDED(hr = AddUIControl(IDC_EDIT_WMWIDTH, pControl))) { pControl = new CUICtrlWMWidthSpin(reinterpret_cast<CUICtrlDefaultEditNum *>(pControl)); if (SUCCEEDED(hr = CHECK_POINTER(pControl, E_OUTOFMEMORY))) { hr = AddUIControl(IDC_SPIN_WMWIDTH, pControl); } } } if (SUCCEEDED(hr)) { pControl = new CUICtrlWMHeightEdit(); if (SUCCEEDED(hr = CHECK_POINTER(pControl, E_OUTOFMEMORY)) && SUCCEEDED(hr = AddUIControl(IDC_EDIT_WMHEIGHT, pControl))) { pControl = new CUICtrlWMHeightSpin(reinterpret_cast<CUICtrlDefaultEditNum *>(pControl)); if (SUCCEEDED(hr = CHECK_POINTER(pControl, E_OUTOFMEMORY))) { hr = AddUIControl(IDC_SPIN_WMHEIGHT, pControl); } } } if (SUCCEEDED(hr)) { pControl = new CUICtrlWMFontSizeEdit(); if (SUCCEEDED(hr = CHECK_POINTER(pControl, E_OUTOFMEMORY)) && SUCCEEDED(hr = AddUIControl(IDC_EDIT_WMSIZE, pControl))) { pControl = new CUICtrlWMFontSizeSpin(reinterpret_cast<CUICtrlDefaultEditNum *>(pControl)); if (SUCCEEDED(hr = CHECK_POINTER(pControl, E_OUTOFMEMORY))) { hr = AddUIControl(IDC_SPIN_WMSIZE, pControl); } } } if (SUCCEEDED(hr)) { pControl = new CUICtrlColorBtn(); if (SUCCEEDED(hr = CHECK_POINTER(pControl, E_OUTOFMEMORY))) { hr = AddUIControl(IDC_BUTTON_WMCOLOR, pControl); } } } catch (CXDException& e) { hr = e; } if (FAILED(hr)) { DestroyUIComponents(); throw CXDException(hr); } } /*++ Routine Name: CWatermarkPropPage::~CWatermarkPropPage Routine Description: CWatermarkPropPage class destructor Arguments: None Return Value: None --*/ CWatermarkPropPage::~CWatermarkPropPage() { } /*++ Routine Name: CWatermarkPropPage::InitDlgBox Routine Description: Provides the base class with the data required to intialise the dialog box. Arguments: ppszTemplate - Pointer to dialog box template to be intialised. ppszTitle - Pointer to dialog box title to be intialised. Return Value: HRESULT S_OK - On success E_* - On error --*/ HRESULT CWatermarkPropPage::InitDlgBox( _Out_ LPCTSTR* ppszTemplate, _Out_ LPCTSTR* ppszTitle ) { HRESULT hr = S_OK; if (SUCCEEDED(hr = CHECK_POINTER(ppszTemplate, E_POINTER)) || SUCCEEDED(hr = CHECK_POINTER(ppszTitle, E_POINTER))) { *ppszTemplate = MAKEINTRESOURCE(IDD_WATERMARK); *ppszTitle = MAKEINTRESOURCE(IDS_WMARK); } ERR_ON_HR(hr); return hr; }
26.862454
110
0.583033
[ "object" ]
2afd32e67687bf340c62da5af688197d4f626b1b
1,909
cpp
C++
aws-cpp-sdk-nimble/source/model/StreamConfigurationSessionStorage.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-05T18:20:03.000Z
2022-01-05T18:20:03.000Z
aws-cpp-sdk-nimble/source/model/StreamConfigurationSessionStorage.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-nimble/source/model/StreamConfigurationSessionStorage.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/nimble/model/StreamConfigurationSessionStorage.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace NimbleStudio { namespace Model { StreamConfigurationSessionStorage::StreamConfigurationSessionStorage() : m_modeHasBeenSet(false), m_rootHasBeenSet(false) { } StreamConfigurationSessionStorage::StreamConfigurationSessionStorage(JsonView jsonValue) : m_modeHasBeenSet(false), m_rootHasBeenSet(false) { *this = jsonValue; } StreamConfigurationSessionStorage& StreamConfigurationSessionStorage::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("mode")) { Array<JsonView> modeJsonList = jsonValue.GetArray("mode"); for(unsigned modeIndex = 0; modeIndex < modeJsonList.GetLength(); ++modeIndex) { m_mode.push_back(StreamingSessionStorageModeMapper::GetStreamingSessionStorageModeForName(modeJsonList[modeIndex].AsString())); } m_modeHasBeenSet = true; } if(jsonValue.ValueExists("root")) { m_root = jsonValue.GetObject("root"); m_rootHasBeenSet = true; } return *this; } JsonValue StreamConfigurationSessionStorage::Jsonize() const { JsonValue payload; if(m_modeHasBeenSet) { Array<JsonValue> modeJsonList(m_mode.size()); for(unsigned modeIndex = 0; modeIndex < modeJsonList.GetLength(); ++modeIndex) { modeJsonList[modeIndex].AsString(StreamingSessionStorageModeMapper::GetNameForStreamingSessionStorageMode(m_mode[modeIndex])); } payload.WithArray("mode", std::move(modeJsonList)); } if(m_rootHasBeenSet) { payload.WithObject("root", m_root.Jsonize()); } return payload; } } // namespace Model } // namespace NimbleStudio } // namespace Aws
23
133
0.743845
[ "model" ]
6304bcbddc235e1439b66678a8e19e41028e20b9
1,325
cc
C++
src/3d/interp.cc
cedar-framework/cedar
9fb53ec221738b8dd16dfb31dc9a18d69fc2cc44
[ "BSD-3-Clause" ]
9
2018-03-07T19:15:27.000Z
2019-02-22T20:10:23.000Z
src/3d/interp.cc
cedar-framework/cedar
9fb53ec221738b8dd16dfb31dc9a18d69fc2cc44
[ "BSD-3-Clause" ]
5
2018-11-13T19:59:46.000Z
2020-04-09T19:31:25.000Z
src/3d/interp.cc
cedar-framework/cedar
9fb53ec221738b8dd16dfb31dc9a18d69fc2cc44
[ "BSD-3-Clause" ]
2
2018-07-20T01:06:48.000Z
2019-11-25T12:15:16.000Z
#include <cedar/2d/ftn/BMG_parameters_c.h> #include <cedar/3d/interp.h> extern "C" { using namespace cedar; void BMG3_SymStd_interp_add(real_t *q, real_t *qc, real_t *so, real_t *res, real_t *ci, len_t iic, len_t jjc, len_t kkc, len_t iif, len_t jjf, len_t kkf, int NStncl, int jpn); void BMG_get_bc(int, int*); } namespace cedar { namespace cdr3 { void interp_f90::run(const prolong_op & P, const grid_func & coarse, const grid_func & residual, grid_func & fine) { int nstencil, ibc; prolong_op & Pd = const_cast<prolong_op&>(P); grid_func & coarsed = const_cast<grid_func&>(coarse); grid_func & res = const_cast<grid_func&>(residual); real_t * fop_data; if (Pd.fine_is_seven) { nstencil = 4; fop_data = Pd.fine_op_seven->data(); } else { nstencil = 14; fop_data = Pd.fine_op_xxvii->data(); } BMG_get_bc(params->per_mask(), &ibc); BMG3_SymStd_interp_add(fine.data(), coarsed.data(), fop_data, res.data(), Pd.data(), coarsed.len(0), coarsed.len(1), coarsed.len(2), fine.len(0), fine.len(1), fine.len(2), nstencil, ibc); } }}
27.604167
86
0.556226
[ "3d" ]
63079916526013a73e74e376348a44c760a6781c
10,733
cpp
C++
QHTML_Static/qhtm/HtmlList.cpp
karolbe/DSS
5a834561fbe7345d0be36f41ed8620ebbdb2f222
[ "BSD-3-Clause" ]
null
null
null
QHTML_Static/qhtm/HtmlList.cpp
karolbe/DSS
5a834561fbe7345d0be36f41ed8620ebbdb2f222
[ "BSD-3-Clause" ]
null
null
null
QHTML_Static/qhtm/HtmlList.cpp
karolbe/DSS
5a834561fbe7345d0be36f41ed8620ebbdb2f222
[ "BSD-3-Clause" ]
1
2020-06-28T19:21:22.000Z
2020-06-28T19:21:22.000Z
/*---------------------------------------------------------------------- Copyright (c) 1998 Gipsysoft. All Rights Reserved. Please see the file "licence.txt" for licencing details. File: HTMLList.cpp Owner: rich@woodbridgeinternalmed.com Purpose: A List, and List Entries ----------------------------------------------------------------------*/ #include "stdafx.h" #include "htmlparse.h" #include "HTMLSectionCreator.h" #include "HTMLTextSection.h" #include "defaults.h" static UINT Decimal( LPTSTR pszBuffer, UINT uIndex ) { static LPCTSTR knBulletFormat = _T("%u."); return wsprintf( pszBuffer, knBulletFormat, uIndex ); } static TCHAR g_arrUpperAlphaChars[ 27 ] = _T("ABCDEFGHIJKLMNOPQRSTUVWXYZ"); static TCHAR g_arrLowerAlphaChars[ 27 ] = _T("abcdefghijklmnopqrstuvwxyz"); static int ConvertToAlpha( UINT uIndex, LPTSTR pszBuffer, LPCTSTR pcszChars, UINT uRadix ) { TCHAR szBuffer[ 32 ]; static const int nBufferSize = countof( szBuffer ); szBuffer[ 31 ] ='\000'; UINT u = countof( szBuffer ) - 1; if( uIndex <= 0 ) { uIndex = 1; } do { uIndex--; UINT cur = uIndex % uRadix; szBuffer[ --u ] = pcszChars[cur]; uIndex /= uRadix; } while ( uIndex > 0); _tcscpy( pszBuffer, szBuffer + u ); return nBufferSize - u - 1; } static UINT AlphaUpper( LPTSTR pszBuffer, UINT uIndex ) { return ConvertToAlpha( uIndex, pszBuffer, g_arrUpperAlphaChars, countof( g_arrUpperAlphaChars ) - 1 ); } static UINT AlphaLower( LPTSTR pszBuffer, UINT uIndex ) { return ConvertToAlpha( uIndex, pszBuffer, g_arrLowerAlphaChars, countof( g_arrUpperAlphaChars ) - 1); } static UINT g_arrRomanValue[]= {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1}; static LPTSTR g_arrRomanUpper[]= { _T("M"), _T("CM"), _T("D"), _T("CD"), _T("C"), _T("XC"), _T("L"), _T("XL"), _T("X"), _T("IX"), _T("V"), _T("IV"), _T("I") }; static LPTSTR g_arrRomanLower[]= { _T("m"), _T("cm"), _T("d"), _T("cd"), _T("c"), _T("xc"), _T("l"), _T("xl"), _T("x"), _T("ix"), _T("v"), _T("iv"), _T("i") }; static UINT ConvertToRoman( LPTSTR pszBuffer, UINT uIndex, LPTSTR *arr ) { pszBuffer[0] = '\000'; int pos=0; for( int i = 0; i < countof( g_arrRomanValue ) ; i++ ) { while( g_arrRomanValue[i] <= uIndex ) { _tcscat( pszBuffer + pos, arr[ i ] ); pos++; uIndex -= g_arrRomanValue[i]; } } pszBuffer[ pos ]= '\0'; return pos; } static UINT RomanUpper( LPTSTR pszBuffer, UINT uIndex ) { return ConvertToRoman( pszBuffer, uIndex, g_arrRomanUpper ); } static UINT RomanLower( LPTSTR pszBuffer, UINT uIndex ) { return ConvertToRoman( pszBuffer, uIndex, g_arrRomanLower ); } static UINT Bullet( LPTSTR pszBuffer, UINT ) { static TCHAR knBulletText[] = _T("\xB7"); _tcscpy( pszBuffer, knBulletText ); return countof( knBulletText ) - 1; } static UINT Circle( LPTSTR pszBuffer, UINT ) { static TCHAR knBulletText[] = _T("\xB0"); _tcscpy( pszBuffer, knBulletText ); return countof( knBulletText ) - 1; } static UINT Square( LPTSTR pszBuffer, UINT ) { static TCHAR knBulletText[] = _T("\xE0"); _tcscpy( pszBuffer, knBulletText ); return countof( knBulletText ) - 1; } CHTMLList::CHTMLList( bool bOrdered ) : CHTMLParagraphObject( CHTMLParagraphObject::knNone ) , m_bOrdered( bOrdered ) , m_bCompact( false ) { if( m_bOrdered ) { m_funcGetListItemText = Decimal; } else { m_funcGetListItemText = Bullet; } } CHTMLList::~CHTMLList() { for( UINT nIndex = 0; nIndex < m_arrItems.GetSize(); nIndex++ ) { delete m_arrItems[ nIndex ]; } m_arrItems.RemoveAll(); } void CHTMLList::AddItem( CHTMLListItem *pItem ) { m_arrItems.Add( pItem ); } UINT CHTMLList::GetItemText( LPTSTR pszBuffer, UINT uIndex ) const { return m_funcGetListItemText( pszBuffer, uIndex ); } void CHTMLList::SetType( const CStaticString &strType ) { if( strType.GetLength() == 1 ) { switch( *strType.GetData() ) { case 'a': m_funcGetListItemText = AlphaLower; break; case 'A': m_funcGetListItemText = AlphaUpper; break; case 'i': m_funcGetListItemText = RomanLower; break; case 'I': m_funcGetListItemText = RomanUpper; break; } } else if( m_bOrdered == false ) { if( !_tcsnicmp( strType, _T("circle"), strType.GetLength() ) ) { m_funcGetListItemText = Circle; } else if( !_tcsnicmp( strType, _T("disc"), strType.GetLength() ) ) { m_funcGetListItemText = Bullet; } else if( !_tcsnicmp( strType, _T("square"), strType.GetLength() ) ) { m_funcGetListItemText = Square; } } } #ifdef _DEBUG void CHTMLList::Dump() const { const size_t size = m_arrItems.GetSize(); TRACENL( _T("List----------------\n") ); TRACENL( _T(" Size (%d)\n"), size ); TRACENL( _T(" Ordered (%s)\n"), (m_bOrdered ? _T("true") : _T("false") )); TRACENL( _T(" Compact (%s)\n"), (m_bCompact ? _T("true") : _T("false") )); for( UINT nIndex = 0; nIndex < size; nIndex++ ) { TRACENL( _T(" Item %d\n"), nIndex ); m_arrItems[ nIndex ]->Dump(); } } #endif // _DEBUG void CHTMLList::AddDisplayElements( class CHTMLSectionCreator *psc ) { /* A List is similar to a table, in that each list item is a document in itself. Lists are laid out by creating the bullet, which is right justified along the left margin, and has width knIndentSize. The contents depend on whether the list is ordered, and the index of the item. The list item contents use the right edge if the bullet space as the left margin. That's it! Note that current font properties apply to the bullet. Only color applies to bullets in unordered lists. */ int nFontSize = 2; if( m_arrItems.GetSize() ) { CHTMLListItem* pItem = m_arrItems[0]; if( !pItem->m_bBullet ) { nFontSize = pItem->m_nSize; } } int nBulletSpace = WinHelper::MulDiv( m_bCompact ? g_defaults.m_nIndentSpaceSize / 2 : g_defaults.m_nIndentSpaceSize, GetDeviceCaps( psc->GetDC().GetSafeHdc(), LOGPIXELSX), 1000); int nIndex = 1; // Index, used for ordered lists // Iterate the list items, creating the bullet and the subdocument. const size_t nItems = m_arrItems.GetSize(); psc->SetNextYPos( psc->GetNextYPos() + psc->GetDC().GetCurrentFontHeight() ); TCHAR szBuffer[12]; UINT uLength = 1; // // Measure the indent size... size_t i; for ( i = 0; i < nItems; ++i) { CHTMLListItem* pItem = m_arrItems[i]; psc->NewParagraph( 0,0,CStyle::algLeft ); // Do we need to create a bullet? if( pItem->m_bBullet ) { // Create the bullet... LPCTSTR pcszFont; //int nFontSize; bool bBold, bItalic, bUnderline, bStrikeOut; LPCTSTR pcszText = 0; nIndex = pItem->GetValue( nIndex ); uLength = GetItemText( szBuffer, nIndex ); pcszText = szBuffer; if( m_bOrdered ) { // Set text parameters pcszFont = pItem->m_strFont; nFontSize = pItem->m_nSize; bBold = pItem->m_bBold; bItalic = pItem->m_bItalic; bUnderline = pItem->m_bUnderline; bStrikeOut = pItem->m_bStrikeout; } else { // Set text parameters pcszFont = _T("Symbol"); bBold = false; bItalic = false; bUnderline = false; bStrikeOut = false; } HTMLFontDef htmlfdef( pcszFont, nFontSize, bBold, bItalic, bUnderline, bStrikeOut, 0, 0, false ); const GS::FontDef *pfdef = psc->GetDrawingFont( htmlfdef ); // // Position the object... psc->GetDC().SelectFont( *pfdef ); const int nTextWidth = psc->GetDC().GetTextExtent(pcszText, uLength ); if( nTextWidth > nBulletSpace ) { nBulletSpace = nTextWidth; } } } const int nBulletWidth = WinHelper::MulDiv( m_bCompact ? g_defaults.m_nIndentSize / 4 : g_defaults.m_nIndentSize / 2, GetDeviceCaps( psc->GetDC().GetSafeHdc(), LOGPIXELSX), 1000); for( i = 0; i < nItems; ++i ) { int nBulletHeight = 0; CHTMLListItem* pItem = m_arrItems[i]; psc->NewParagraph( 0,0,CStyle::algLeft ); // Do we need to create a bullet? if( pItem->m_bBullet ) { // Create the bullet... LPCTSTR pcszFont; //int nFontSize; bool bBold, bItalic, bUnderline, bStrikeOut; LPCTSTR pcszText = 0; nIndex = pItem->GetValue( nIndex ); uLength = GetItemText( szBuffer, nIndex ); pcszText = szBuffer; if( m_bOrdered ) { // Set text parameters pcszFont = pItem->m_strFont; nFontSize = pItem->m_nSize; bBold = pItem->m_bBold; bItalic = pItem->m_bItalic; bUnderline = pItem->m_bUnderline; bStrikeOut = pItem->m_bStrikeout; } else { // Set text parameters pcszFont = _T("Symbol"); //nFontSize = nBulletFontSize; bBold = true; bItalic = false; bUnderline = false; bStrikeOut = false; } HTMLFontDef htmlfdef( pcszFont, nFontSize, bBold, bItalic, bUnderline, bStrikeOut, 0, 0, false ); const GS::FontDef *pfdef = psc->GetDrawingFont( htmlfdef ); CColor crBack; CHTMLTextSection* pText = new CHTMLTextSection( psc->GetHTMLSection(), pcszText, uLength, pfdef, pItem->m_crFore, crBack ); const size_t nLabelID = psc->GetCurrentShapeID(); psc->AddSection( pText ); // // Position the object... psc->GetDC().SelectFont( *pfdef ); const int nTextWidth = psc->GetDC().GetTextExtent(pcszText, uLength ); nBulletHeight = psc->GetCurrentYPos() + psc->GetDC().GetCurrentFontHeight(); const int right = psc->GetCurrentXPos() + nBulletSpace; const int left = right - nTextWidth; pText->Set( left, psc->GetCurrentYPos(), right, nBulletHeight ); // Increment the index nIndex++; // Now, create the sub-document CHTMLSectionCreator htCreate( psc->GetHTMLSection(), psc->GetDC(), psc->GetCurrentYPos(), right + nBulletWidth, psc->GetRightMargin(), psc->GetBackgroundColor(), false, psc->GetZoomLevel(), psc->GetCurrentLink(), psc ); htCreate.AddDocument( pItem ); const WinHelper::CSize size( htCreate.GetSize() ); // Adjust y-pos psc->SetCurrentYPos( max(size.cy, nBulletHeight) + 1 ); if( nLabelID + 1 > psc->GetCurrentShapeID() ) { CSectionABC *pSect = psc->GetHTMLSection()->GetSectionAt( nLabelID + 1 ); if( pSect ) { if( pSect->Height() > pText->Height() ) { const int nDiff = (pSect->Height() - pText->Height() ) / 2; pText->Offset( 0, nDiff ); } else { const int nDiff = (pText->Height() - pSect->Height() ) / 2; pText->Offset( 0, -nDiff ); } } } } else { // Now, create the sub-document CHTMLSectionCreator htCreate( psc->GetHTMLSection(), psc->GetDC(), psc->GetCurrentYPos(), psc->GetCurrentXPos() + nBulletWidth + nBulletSpace, psc->GetRightMargin(), psc->GetBackgroundColor(), false, psc->GetZoomLevel(), psc->GetCurrentLink(), psc ); htCreate.AddDocument( pItem ); const WinHelper::CSize size( htCreate.GetSize() ); // Adjust y-pos psc->SetCurrentYPos( max(size.cy, nBulletHeight) + 1 ); } } }
26.306373
253
0.651821
[ "object" ]
deb993450336140ee499b21f85f61193befddd90
402
cpp
C++
C++/KY/shenxinfu1.cpp
WhitePhosphorus4/xh-learning-code
025e31500d9f46d97ea634d7fd311c65052fd78e
[ "Apache-2.0" ]
null
null
null
C++/KY/shenxinfu1.cpp
WhitePhosphorus4/xh-learning-code
025e31500d9f46d97ea634d7fd311c65052fd78e
[ "Apache-2.0" ]
null
null
null
C++/KY/shenxinfu1.cpp
WhitePhosphorus4/xh-learning-code
025e31500d9f46d97ea634d7fd311c65052fd78e
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<vector> #include<unordered_map> using namespace std; int main() { int n; vector<int> number; vector<char> opera; cin>>n; for(int i=0;i<n;i++){ int x; cin>>x; number.push_back(x); } for(int i=0;i<n-1;i++){ char x; cin>>x; opera.push_back(x); } unordered_map<char,int> test; return 0; }
16.08
33
0.527363
[ "vector" ]
debd4b72d2f39278d4109b1d719b7409ab498419
820
hpp
C++
src/volume.hpp
makeclean/camconvert
32e2af42ee8b9f56bf194bd3837d0249f43cac3e
[ "MIT" ]
null
null
null
src/volume.hpp
makeclean/camconvert
32e2af42ee8b9f56bf194bd3837d0249f43cac3e
[ "MIT" ]
null
null
null
src/volume.hpp
makeclean/camconvert
32e2af42ee8b9f56bf194bd3837d0249f43cac3e
[ "MIT" ]
null
null
null
#include "surface.hpp" #include <vector> #include <string> #include <fstream> #ifndef VOLUME_HPP #define VOLUME_HPP 1 class Volume { public: Volume(); ~Volume(); // instanciate new volume Volume(int vol_id, double density, int material_number, std::vector<Surface*> bounding_surfaces, double x, double y, double z, std::string name); void SetDensity(double density); void AddSurfaces(std::vector<int> surface_ids); int GetId(); int Sense(Surface *surface); std::vector<Surface*> GetSurfaces(); void PrintFluka(std::ofstream &output); void Print(); private: bool PointInVolume(double x, double y, double z); void ConnectSurfaces(); private: int volId; double density; int materialNumber; double x,y,z; std::vector<Surface*> boundingSurfaces; std::string name; }; #endif
20.5
57
0.709756
[ "vector" ]
decb95f16a323fe26855dc0c337e49509ab72a36
2,058
cpp
C++
source/managers/meshPreviewHandler.cpp
AlexAUT/awEditor
c9e4e0dee36c1956b92a47f07a2309be4985e2a6
[ "MIT" ]
null
null
null
source/managers/meshPreviewHandler.cpp
AlexAUT/awEditor
c9e4e0dee36c1956b92a47f07a2309be4985e2a6
[ "MIT" ]
null
null
null
source/managers/meshPreviewHandler.cpp
AlexAUT/awEditor
c9e4e0dee36c1956b92a47f07a2309be4985e2a6
[ "MIT" ]
null
null
null
#include "meshPreviewHandler.hpp" #include <aw/runtime/components/meshProvider.hpp> #include <aw/runtime/components/meshRenderer.hpp> #include <aw/runtime/components/transform.hpp> #include <aw/runtime/loaders/assimpLoader.hpp> #include <aw/runtime/resourceManager/factories/meshFactory.hpp> #include <aw/runtime/scene/scene.hpp> #include <aw/utils/log.hpp> #include <fstream> MeshPreviewHandler::MeshPreviewHandler(aw::MessageBus& bus, aw::Scene& scene) : mSubscription(bus.subscribeToChannel<MeshEvent>([this](const MeshEvent& e) { this->processEvent(e); })), mScene(scene), mEntity(mScene.getEntitySystem().createEntity()) { using namespace aw::ecs::components; mEntity.add<Transform>(mEntity); mEntity.add<MeshRenderer>(); } void MeshPreviewHandler::processEvent(const MeshEvent& event) { switch (event.type) { case MeshEventType::NewMesh: loadNewMesh(static_cast<const NewMeshEvent&>(event)); break; default: break; } } void MeshPreviewHandler::loadNewMesh(const NewMeshEvent& event) { // Check path and get asset directory std::string key = "/assets/"; auto found = event.meshPath.find("assets"); if (found == std::string::npos) { LogTemp() << "Mesh has to be placed inside a assets directory"; return; } std::string assetPath = event.meshPath.substr(0, found + key.size() - 1); auto path = aw::createAbsolutePath(event.meshPath); using namespace aw::factories; auto& resManager = mScene.getResourceManager(); auto mesh = resManager.getRegistry<aw::Mesh>().create<MeshFactory>(path.getRelativePath(), path, resManager); if (!mesh) { LogTemp() << "Failed to load mesh: " << path << "!"; } else { // ECS using namespace aw::ecs::components; if (!mEntity.has<MeshProvider>()) mEntity.add<MeshProvider>(mesh); else mEntity.get<MeshProvider>()->mMesh = mesh; mEntity.get<Transform>()->setPosition(aw::Vec3{0.f}); mEntity.get<Transform>()->setRotation(aw::Vec3{0.f}); mEntity.get<Transform>()->setScale(aw::Vec3{1.f}); } }
28.985915
111
0.698251
[ "mesh", "transform" ]
ded157c3153ce0625287da820d99953a5db711c8
830
cpp
C++
ABC_208_C.cpp
kamlesh012/AtCoder-Editorials
d54e20da49317298096810a5a045253a810621a2
[ "Unlicense" ]
null
null
null
ABC_208_C.cpp
kamlesh012/AtCoder-Editorials
d54e20da49317298096810a5a045253a810621a2
[ "Unlicense" ]
null
null
null
ABC_208_C.cpp
kamlesh012/AtCoder-Editorials
d54e20da49317298096810a5a045253a810621a2
[ "Unlicense" ]
null
null
null
//Nice Problem //Was Medium for me as well. //Used a lot of STL-->many functions for the first time. #include <bits/stdc++.h> #define int long long #define mod 1000000007 #define rep(i,n,s) for(int i=0;i<n;i+=s) #define mxsize 100000 #define a first #define b second using namespace std; //Solved 5 mins after the contest. void s3() { int n, k; cin >> n >> k; vector<pair<int, int>> h; map<int, int> m; int a[n]; rep(i, n, 1) { cin >> a[i]; m.insert({a[i], 0}); } int x = k / n; rep(i, n, 1) { m[a[i]] = x; } x = k % n; int i = 0; map<int, int>::iterator it = m.begin(); while (it != m.end()) { if (x > 0) { it->second++; it++; x--; } if (x == 0)break; } rep(i, n, 1) { cout << m[a[i]] << " "; } } int32_t main() { ios_base::sync_with_stdio(false); cin.tie(NULL); s3(); }
14.067797
56
0.543373
[ "vector" ]
ded3b5a07a88a9b4198f81ff3b33de557a1e60c6
5,763
cpp
C++
src/HADoorService.cpp
mark1-umd/homebot
578c424b15331de32cc6b32a4cbf7ad27dbb5ffe
[ "BSD-3-Clause" ]
null
null
null
src/HADoorService.cpp
mark1-umd/homebot
578c424b15331de32cc6b32a4cbf7ad27dbb5ffe
[ "BSD-3-Clause" ]
null
null
null
src/HADoorService.cpp
mark1-umd/homebot
578c424b15331de32cc6b32a4cbf7ad27dbb5ffe
[ "BSD-3-Clause" ]
null
null
null
/** * @copyright (c) 2017 Mark R. Jenkins. All rights reserved. * @file HADoorService.cpp * * @author MJenkins, ENPM 808X Spring 2017 * @date Apr 27, 2017 - Creation * * @brief Provides a Home Automation "door" service (sends HA door commands) * * A home may be equipped with one or more doors operable by a Home Automation system. * This service accepts ROS service requests and sends Home Automation commands that * will act on the doors operable by a Home Automation system. * * * * * BSD 3-Clause License * * Copyright (c) 2017, Mark Jenkins * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "homebot/HADoorService.hpp" /** * @brief Constructor for HADoorService; creates an object for the HADoor Service that must be initialized before it can be used */ HADoorService::HADoorService() { } HADoorService::~HADoorService() { } /** * @brief Service callback for the Home Automation Door service - handles service calls * @param [in] req data specifying the request details (door number, action to take) * @param [out] rsp data going back to the service requestor (door number, door state) * @return boolean success or failure of the service call */ bool HADoorService::callback(homebot::HADoor::Request& req, homebot::HADoor::Response& rsp) { // Validate that the door number is between 1 and the number of doors (inclusive) if (req.doorNumber < 1 || req.doorNumber > doorState[0]) { ROS_WARN_STREAM( "HomeBot-HADoorService(callback): Non-existent door " << int(req.doorNumber) << " specified for HADoor service action " << int(req.action) << ", no action taken"); rsp.doorNumber = req.doorNumber; rsp.state = req.action; return false; } // Validate that the action requested is between the lowest and highest action values if (req.action < homebot::HADoorRequest::CLOSE || req.action > homebot::HADoorRequest::STATUS) { ROS_WARN_STREAM( "HomeBot-HADoorService(callback): Non-existent action " << int(req.action) << " specified for HADoor service on door " << int(req.doorNumber) << ", no action taken"); rsp.doorNumber = req.doorNumber; rsp.state = req.action; return false; } // Based on the action requested, format a command and send it to the Home // Automation system. Since this is just a demo, no actual commands will be // sent, but an ROS log message will be sent switch (req.action) { case homebot::HADoorRequest::CLOSE: ROS_INFO_STREAM( "HomeBot-HADoorService(callback): Sending Close Door command for door " << int(req.doorNumber) << " to Home Automation system"); doorState[req.doorNumber] = homebot::HADoorResponse::CLOSED; break; case homebot::HADoorRequest::OPEN: ROS_INFO_STREAM( "HomeBot-HADoorService(callback): Sending Open Door command for door " << int(req.doorNumber) << " to Home Automation system"); doorState[req.doorNumber] = homebot::HADoorResponse::OPENED; break; case homebot::HADoorRequest::STATUS: ROS_INFO_STREAM( "HomeBot-HADoorService(callback): Sending Door Status command for door " << int(req.doorNumber) << " to Home Automation system"); break; } rsp.doorNumber = req.doorNumber; rsp.state = doorState[rsp.doorNumber]; return true; } /** * @brief Called to start the actual service; advertises the service and establishes callback * @param numberOfDoors used to size the number of door states to track */ void HADoorService::init(int numberOfDoors) { ROS_INFO_STREAM( "HomeBot-HADoorService(init): HADoorService initializing; " << numberOfDoors << " doors to initialize."); // Store the number of doors in the first element of the door state vector doorState.push_back(numberOfDoors); for (int d = 1; d <= numberOfDoors; d++) { // Initialize all of the door states to closed doorState.push_back(homebot::HADoorResponse::CLOSED); ROS_INFO_STREAM( "HomeBot-HADoorService(init): Door " << d << " initialized to state " << doorState[d]); } // Set the service server object using the node handle's advertiseService method, // the service name, and the callback method from this object ss = nh.advertiseService("ha_door", &HADoorService::callback, this); }
46.104
174
0.720632
[ "object", "vector" ]
ded9bbbfb348da9a1760b3c5df9c0401ec751a8d
32,986
cpp
C++
LWSkaExporter/AnimExport.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
1
2022-02-14T15:46:44.000Z
2022-02-14T15:46:44.000Z
LWSkaExporter/AnimExport.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
null
null
null
LWSkaExporter/AnimExport.cpp
openlastchaos/lastchaos-source-client
3d88594dba7347b1bb45378136605e31f73a8555
[ "Apache-2.0" ]
2
2022-01-10T22:17:06.000Z
2022-01-17T09:34:08.000Z
/* Copyright (C) 2001-2002 Croteam, Ltd. See COPYING (GNU Library General Public License 2) for license */ #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include <assert.h> #include <lwsurf.h> #include <lwhost.h> #include <lwserver.h> #include <lwgeneric.h> #include <crtdbg.h> #include <stdarg.h> #include "vecmat.h" #include <crtdbg.h> #include <lwserver.h> #include <lwmotion.h> #include <lwxpanel.h> #include <stdio.h> #include <stdlib.h> #include <math.h> #include "base.h" static int _iFrame = 0; static int _ctFrames = 0; static int _ctBones = 0; static int ctBoneEnvelopes = 0; static int ctMorphEnvelopes = 0; bool bRecordDefaultFrame = false; extern int ReloadGlobalObjects(); extern bool bExportAbsPositions; // export first bone absolute position typedef float Matrix12[12]; void MakeRotationAndPosMatrix(Matrix12 &mrm_f, float *pmrm_vPos, float *pmrm_vRot) { assert(_CrtCheckMemory()); float mat[3][4]; float fSinH = sinf(pmrm_vRot[0]); // heading float fCosH = cosf(pmrm_vRot[0]); float fSinP = sinf(pmrm_vRot[1]); // pitch float fCosP = cosf(pmrm_vRot[1]); float fSinB = sinf(pmrm_vRot[2]); // banking float fCosB = cosf(pmrm_vRot[2]); memset(&mat,0,sizeof(mat)); mat[0][0] = fCosH*fCosB+fSinP*fSinH*fSinB; mat[0][1] = fSinP*fSinH*fCosB-fCosH*fSinB; mat[0][2] = -(fCosP*fSinH); mat[1][0] = fCosP*fSinB; mat[1][1] = fCosP*fCosB; mat[1][2] = -(-fSinP); mat[2][0] = -(fSinP*fCosH*fSinB-fSinH*fCosB); mat[2][1] = -(fSinP*fCosH*fCosB+fSinH*fSinB); mat[2][2] = fCosP*fCosH; // add Position mat[0][3] = pmrm_vPos[0]; mat[1][3] = pmrm_vPos[1]; mat[2][3] = pmrm_vPos[2]; memcpy(mrm_f,&mat,sizeof(mat)); } void MakeIdentityMatrix(Matrix12 &mat) { memset(&mat,0,sizeof(mat)); mat[0] = 1; mat[5] = 1; mat[10] = 1; //mat[11] = 1; } static void MatrixTranspose(Matrix12 &r, const Matrix12 &m) { r[ 0] = m[ 0]; r[ 5] = m[ 5]; r[10] = m[10]; r[ 3] = m[ 3]; r[ 7] = m[ 7]; r[11] = m[11]; r[1] = m[4]; r[2] = m[8]; r[4] = m[1]; r[8] = m[2]; r[6] = m[9]; r[9] = m[6]; r[ 3] = -r[0]*m[3] - r[1]*m[7] - r[ 2]*m[11]; r[ 7] = -r[4]*m[3] - r[5]*m[7] - r[ 6]*m[11]; r[11] = -r[8]*m[3] - r[9]*m[7] - r[10]*m[11]; } // concatenate two 3x4 matrices [conc = MxN] void MatrixMultiply(Matrix12 &c,const Matrix12 &m, const Matrix12 &n) { c[0] = m[0]*n[0] + m[1]*n[4] + m[2]*n[8]; c[1] = m[0]*n[1] + m[1]*n[5] + m[2]*n[9]; c[2] = m[0]*n[2] + m[1]*n[6] + m[2]*n[10]; c[3] = m[0]*n[3] + m[1]*n[7] + m[2]*n[11] + m[3]; c[4] = m[4]*n[0] + m[5]*n[4] + m[6]*n[8]; c[5] = m[4]*n[1] + m[5]*n[5] + m[6]*n[9]; c[6] = m[4]*n[2] + m[5]*n[6] + m[6]*n[10]; c[7] = m[4]*n[3] + m[5]*n[7] + m[6]*n[11] + m[7]; c[8] = m[8]*n[0] + m[9]*n[4] + m[10]*n[8]; c[9] = m[8]*n[1] + m[9]*n[5] + m[10]*n[9]; c[10] = m[8]*n[2] + m[9]*n[6] + m[10]*n[10]; c[11] = m[8]*n[3] + m[9]*n[7] + m[10]*n[11] + m[11]; } // matrix copy void MatrixCopy(Matrix12 &c, const Matrix12 &m) { memcpy(&c,&m,sizeof(c)); } void PrintMatrix(FILE *_f, Matrix12 &mat, int ctSpaces) { char str_Spaces[16]; memset(&str_Spaces,32,sizeof(str_Spaces)); str_Spaces[15] = 0; str_Spaces[ctSpaces] = 0; fprintf(_f,"%s",str_Spaces); fprintf(_f,"%g,%g,%g,%g,\t" ,mat[0],mat[1],mat[2],mat[3]); fprintf(_f,"%g,%g,%g,%g,\t" ,mat[4],mat[5],mat[6],mat[7]); fprintf(_f,"%g,%g,%g,%g;" ,mat[8],mat[9],mat[10],mat[11]); } void MakeRotationMatrix(Matrix12 &mRotation,float *afAngles) { float fSinH = (float) sin(afAngles[0]); // heading float fCosH = (float) cos(afAngles[0]); float fSinP = (float) sin(afAngles[1]); // pitch float fCosP = (float) cos(afAngles[1]); float fSinB = (float) sin(afAngles[2]); // banking float fCosB = (float) cos(afAngles[2]); mRotation[0] = fCosH*fCosB+fSinP*fSinH*fSinB; mRotation[1] = fSinP*fSinH*fCosB-fCosH*fSinB; mRotation[2] = fCosP*fSinH; mRotation[3] = 0; mRotation[4] = fCosP*fSinB; mRotation[5] = fCosP*fCosB; mRotation[6] = -fSinP; mRotation[7] = 0; mRotation[8] = fSinP*fCosH*fSinB-fSinH*fCosB; mRotation[9] = fSinP*fCosH*fCosB+fSinH*fSinB; mRotation[10] = fCosP*fCosH; mRotation[11] = 0; for (int i=0;i<12;i++) if(fabs(mRotation[i]) < 0.001) mRotation[i] = 0; } /* * Decompose rotation matrix into angles in 3D. */ // NOTE: for derivation of the algorithm, see mathlib.doc void DecomposeRotationMatrixNoSnap(const Matrix12 &mRotation,float *afAngles) { float &h=afAngles[0]; // heading float &p=afAngles[1]; // pitch float &b=afAngles[2]; // banking float a; // temporary // calculate pitch float f23 = mRotation[6]; p = (float) asin(-f23); a = (float) sqrt(1.0f-f23*f23); // if pitch makes banking beeing the same as heading if (a<0.001) { // we choose to have banking of 0 b = 0; // and calculate heading for that assert(fabs(mRotation[6])>0.5); // must be around 1, what is far from 0 h = (float) atan2(mRotation[1]/(-mRotation[6]), mRotation[0]); // no division by 0 // otherwise } else { // calculate banking and heading normally b = (float) atan2(mRotation[4], mRotation[5]); h = (float) atan2(mRotation[2], mRotation[10]); } } void MatchGoalOrientation(LWItemID objectID,float *frot,double time) { LWItemID goalID,parentID; double rot[3]; Matrix12 mGoal,mBone,mTemp,mMul; int bGoalOrient; goalID = _iti->goal(objectID); // the rotation of this bone must be the same as the rotation of it's goal object. // first get the absolute rotation of the goal object _iti->param(goalID,LWIP_ROTATION,time,rot); frot[0] = (float) rot[0]; frot[1] = (float) rot[1]; frot[2] = (float) rot[2]; MakeRotationMatrix(mGoal,frot); parentID = _iti->parent(goalID); while (parentID != LWITEM_NULL) { _iti->param(parentID,LWIP_ROTATION,time,rot); frot[0] = (float) rot[0]; frot[1] = (float) rot[1]; frot[2] = (float) rot[2]; MakeRotationMatrix(mTemp,frot); MatrixMultiply(mMul,mTemp,mGoal); MatrixCopy(mGoal,mMul); parentID = _iti->parent(parentID); } // now get the absolute rotation of this bone MakeIdentityMatrix(mBone); parentID = _iti->parent(objectID); while (parentID != LWITEM_NULL) { bGoalOrient = _iti->flags(parentID) & LWITEMF_GOAL_ORIENT; if (bGoalOrient) { MatchGoalOrientation(parentID,frot,time); } else { _iti->param(parentID,LWIP_ROTATION,time,rot); frot[0] = (float) rot[0]; frot[1] = (float) rot[1]; frot[2] = (float) rot[2]; } MakeRotationMatrix(mTemp,frot); MatrixMultiply(mMul,mTemp,mBone); MatrixCopy(mBone,mMul); parentID = _iti->parent(parentID); } MatrixTranspose(mTemp,mBone); MatrixMultiply(mMul,mTemp,mGoal); DecomposeRotationMatrixNoSnap(mMul,frot); }; bool ExecCmd(const char *strFormat, ...) { char strCommand[256]; va_list arg; va_start(arg, strFormat); vsprintf(strCommand, strFormat, arg); {int iOk = _evaluate(_serverData, strCommand); if (iOk==0) { _msg->error("Can't execute command", strCommand); return false; }} return true; } // enumeraion function used to test if the currently selected vmap is used by the current mesh static int CheckPointVmap(void *dummy, LWPntID id) { float v[3]; if (_pmesh->pntVGet(_pmesh, id, v)) { return 1; } else { return 0; } } static char *_strFileName = NULL; static const char *_strSceneName = NULL; static FILE *_f = NULL; static BoneInfo *_pbiFirst = NULL; // linked list of all instances static MorphInfo *_pmiFirst = NULL; // linked list of all instances static Matrix12 *_pmRootBoneAbs=NULL; /* ====================================================================== Create() Handler callback. Allocate and initialize instance data. ====================================================================== */ XCALL_( static LWInstance ) Create( void *priv, LWItemID item, LWError *err ) { // create the instance BoneInfo *pii = (BoneInfo*)malloc(sizeof(BoneInfo)); pii->bi_strName = _iti->name(item); _ctBones++; // get parent bone name LWItemID pParentID = _iti->parent(item); //strdup() pii->bi_strParentName = _iti->name(pParentID); if(_iti->type(pParentID) != LWI_BONE) { // this is root bone pii->bi_strParentName = ""; } // get item type pii->bi_lwItemType = _iti->type(item); pii->bi_uiFlags = _pbi->flags(item); // allocate space for storing frames pii->bi_abfFrames = (BoneFrame*)malloc(sizeof(BoneFrame)*_ctFrames); // if first time here if(_pbiFirst==NULL) { // allocate space for storing absolute position for root bone _pmRootBoneAbs = (Matrix12*)malloc(sizeof(Matrix12)*_ctFrames); for(int ifr=0;ifr<_ctFrames;ifr++) { // reset matrices of root bone for all frames MakeIdentityMatrix(_pmRootBoneAbs[ifr]); } } // link into list pii->bi_pbiNext = _pbiFirst; _pbiFirst = pii; return pii; } /* ====================================================================== Destroy() Handler callback. Free resources allocated by Create(). ====================================================================== */ XCALL_( static void ) Destroy( BoneInfo *inst) { free(inst); //free(_pmRootBoneAbs); } /* ====================================================================== Copy() Handler callback. Copy instance data. ====================================================================== */ XCALL_( static LWError ) Copy( BoneInfo *to, BoneInfo *from ) { *to = *from; return NULL; } /* ====================================================================== Load() Handler callback. Read instance data. ====================================================================== */ XCALL_( static LWError ) Load( BoneInfo *inst, const LWLoadState *ls ) { return NULL; } /* ====================================================================== Save() Handler callback. Write instance data. ====================================================================== */ XCALL_( static LWError ) Save( BoneInfo *inst, const LWSaveState *ss ) { return NULL; } /* ====================================================================== Describe() Handler callback. Write a short, human-readable string describing the instance data. ====================================================================== */ XCALL_( static const char * ) Describe( BoneInfo *inst ) { static char desc[ 80 ]; sprintf( desc, "SE Motion Export Handler"); return desc; } /* ====================================================================== Flags() Handler callback. ====================================================================== */ XCALL_( static int ) Flags( BoneInfo *inst ) { return LWIMF_AFTERIK; } /* ====================================================================== Evaluate() Handler callback. This is where we can modify the item's motion. ====================================================================== */ XCALL_( static void ) Evaluate( BoneInfo *pii, const LWItemMotionAccess *access ) { double pos[3], rot[3], pivotpos[3], pivotrot[3]; access->getParam( LWIP_POSITION, access->time, pos); access->getParam( LWIP_ROTATION, access->time, rot); //access->getParam( LWIP_PIVOT, access->time, rot2); LWItemID bone = access->item; int bGoalOrient = _iti->flags(bone) & LWITEMF_GOAL_ORIENT; if(bRecordDefaultFrame) { // default position _pbi->restParam( bone, LWIP_POSITION, pos ); _pbi->restParam( bone, LWIP_ROTATION, rot ); pii->fRestLength = (float)_pbi->restLength(bone); pii->bi_abfDefault.fi_vPos[0] = (float)pos[0]; pii->bi_abfDefault.fi_vPos[1] = (float)pos[1]; pii->bi_abfDefault.fi_vPos[2] = (float)pos[2]; if (fabs(rot[0]) < 0.001) rot[0] = 0; if (fabs(rot[1]) < 0.001) rot[1] = 0; if (fabs(rot[2]) < 0.001) rot[2] = 0; pii->bi_abfDefault.fi_vRot[0] = (float) rot[0]; pii->bi_abfDefault.fi_vRot[1] = (float) rot[1]; pii->bi_abfDefault.fi_vRot[2] = (float) rot[2]; LWDVector vMin; LWDVector vMax; unsigned int uiRet; uiRet = _iti->limits(bone,3,vMin,vMax); } else { pii->bi_abfFrames[_iFrame].fi_vPos[0] = (float)pos[0]; pii->bi_abfFrames[_iFrame].fi_vPos[1] = (float)pos[1]; pii->bi_abfFrames[_iFrame].fi_vPos[2] = (float)pos[2]; if (bGoalOrient) { MatchGoalOrientation(bone,pii->bi_abfFrames[_iFrame].fi_vRot,access->time); } else { pii->bi_abfFrames[_iFrame].fi_vRot[0] = (float)rot[0]; pii->bi_abfFrames[_iFrame].fi_vRot[1] = (float)rot[1]; pii->bi_abfFrames[_iFrame].fi_vRot[2] = (float)rot[2]; } // if this is not bone if((pii->bi_lwItemType!=LWI_BONE))// && (pii->bi_pbiNext!=NULL) && (pii->bi_pbiNext->bi_lwItemType == LWI_BONE)) { // get pivot position _iti->param(bone,LWIP_PIVOT,access->time,pivotpos); _iti->param(bone,LWIP_PIVOT_ROT,access->time,pivotrot); float fPivotPos[3], fPivotRot[3]; for(int ia=0;ia<3;ia++) { fPivotPos[ia] = (float)pivotpos[ia]; fPivotRot[ia] = (float)pivotrot[ia]; } fPivotPos[2] *=-1; pii->bi_abfFrames[_iFrame].fi_vPos[2] *=-1; // get object pivot matix Matrix12 mPivot,mPivotInvert; MakeRotationAndPosMatrix(mPivot,fPivotPos,fPivotRot); MatrixTranspose(mPivotInvert,mPivot); // get object matrix Matrix12 mTemp,mObject; MakeRotationAndPosMatrix(mObject,&pii->bi_abfFrames[_iFrame].fi_vPos[0],&pii->bi_abfFrames[_iFrame].fi_vRot[0]); MatrixCopy(mTemp,mObject); MatrixMultiply(mObject,mTemp,mPivotInvert); //MakeIdentityMatrix(mTemp); //MatrixCopy(mTemp,mPivot); // add its position and rotation to abs matrix //MakeIdentityMatrix(mTemp); MatrixCopy(mTemp,_pmRootBoneAbs[_iFrame]); MatrixMultiply(_pmRootBoneAbs[_iFrame],mObject,mTemp); pii->bi_abfFrames[_iFrame].fi_vPos[2] *=-1; } } //_RPT3(_CRT_WARN, "item: %s, frame: %d, time: %g\n", _iti->name(access->item), access->frame, access->time); //_RPT3(_CRT_WARN, "pos: %g, %g, %g\n", pos[0], pos[1], pos[2]); //_RPT3(_CRT_WARN, "rot: %g, %g, %g\n", rot[0], rot[1], rot[2]); } /* ====================================================================== Handler() Handler activation function. Check the version and fill in the callback fields of the handler structure. ====================================================================== */ XCALL_( int ) Animation_Handler( long version, GlobalFunc *_global, LWItemMotionHandler *local, void *serverData) { if ( version != LWITEMMOTION_VERSION ) return AFUNC_BADVERSION; _iti = (LWItemInfo *)_global(LWITEMINFO_GLOBAL, GFUSE_TRANSIENT); if (_iti==NULL) { return AFUNC_BADGLOBAL; } local->inst->create = Create; local->inst->destroy = (void (*)(void *))Destroy; local->inst->load = (const char *(__cdecl *)(void *,const struct st_LWLoadState *))Load; local->inst->save = (const char *(__cdecl *)(void *,const struct st_LWSaveState *))Save; local->inst->copy = (const char *(__cdecl *)(void *,void *))Copy; local->inst->descln = (const char *(__cdecl *)(void *))Describe; local->evaluate = (void (__cdecl *)(void *,const struct st_LWItemMotionAccess *))Evaluate; local->flags = (unsigned int (__cdecl *)(void *))Flags; return AFUNC_OK; } static bool ApplyExportHander(LWItemID itemID) { if (!ExecCmd("SelectItem %x", itemID)) { return false; } if (!ExecCmd("ApplyServer ItemMotionHandler " DEBUGEXT "internal_SEAnimExport")) { return false; } return true; } static bool ActivateExportHandler(LWItemID itemID) { LWItemID boneid = _iti->first(LWI_BONE, itemID); // if no bones in the scene if (!boneid) { // this is not a fatal error return true; } // get root bone parent LWItemID pParentID = _iti->parent(boneid); // apply export handeler for all bones in scene while (boneid!=LWITEM_NULL) { if(!ApplyExportHander(boneid)) { // failed return false; } boneid = _iti->next(boneid); } // add motion handler to all objects in hierarchy before skeleton if exportabspositions is turned on if(bExportAbsPositions) { while(pParentID != LWITEM_NULL) { // apply it only if item isn't bone if(_iti->type(pParentID) != LWI_BONE) { if(!ApplyExportHander(pParentID)) { return false; } } // get parents parent const char *bi_strParentName = _iti->name(pParentID); pParentID = _iti->parent(pParentID); } } return true; } static bool RemoveExportHander(LWItemID itemID) { if (!ExecCmd("SelectItem %x", itemID)) { return false; } for(int iServer=1;;iServer++) { const char *strServer = _iti->server(itemID, "ItemMotionHandler", iServer); if (strServer==NULL) { break; } if (strcmp(strServer, DEBUGEXT "internal_SEAnimExport")==0) { if (!ExecCmd("RemoveServer ItemMotionHandler %d", iServer)) { return false; } } } return true; } static void DeactivateExportHandler(LWItemID itemID) { LWItemID boneid = _iti->first(LWI_BONE, itemID); // remove motion handler from all objects in hierarchy before skeleton if exportabspositions is turned on if(bExportAbsPositions) { LWItemID pParentID = _iti->parent(boneid); while(pParentID != LWITEM_NULL) { // apply it only if item isn't bone if(_iti->type(pParentID) != LWI_BONE) { if(!RemoveExportHander(pParentID)) { return; } } // get parents parent const char *bi_strParentName = _iti->name(pParentID); pParentID = _iti->parent(pParentID); } } // remove export handeler for all bones in scene while (boneid!=LWITEM_NULL) { if(!RemoveExportHander(boneid)) { return; } boneid = _iti->next(boneid); } return; } // find all morph channels for the current mesh void FindMorphChannels(LWChanGroupID idParentGroup) { // for each group in the given parent for(LWChanGroupID idGroup = _chi->nextGroup(idParentGroup, NULL); idGroup!=NULL; idGroup = _chi->nextGroup(idParentGroup, idGroup)) { const char *strGroupName = _chi->groupName(idGroup); if (idParentGroup==NULL && strcmp(strGroupName, _iti->name(_objid))!=0) { continue; } // for each channel in the group for(LWChannelID idChan = _chi->nextChannel(idGroup, NULL); idChan!=NULL; idChan = _chi->nextChannel(idGroup, idChan)) { // generate morhpmap name from the info about the channel and its parents const char *strName = _chi->channelName(idChan); char strMapName[256] = ""; if (idParentGroup!=NULL) { strcat(strMapName, strGroupName); strcat(strMapName, "."); } strcat(strMapName, strName); // if the morphmap does not exist, skip the channel void *pMap = _pmesh->pntVLookup(_pmesh, LWVMAP_MORF, strMapName); if (pMap==NULL) { pMap = _pmesh->pntVLookup(_pmesh, LWVMAP_SPOT, strMapName); } if (pMap==NULL) { continue; } // select that morhpmap _pmesh->pntVSelect(_pmesh, pMap); // check if any point uses that vmap int iUsed = _pmesh->scanPoints(_pmesh, CheckPointVmap, NULL); // if not used if (iUsed==0) { // skip it continue; } // -- if we get here it means that the channel is really a morph map for this object // generate morph info MorphInfo *pmi = (MorphInfo *)malloc(sizeof(MorphInfo)); pmi->mi_strName = strdup(strMapName); pmi->mi_idChannel = idChan; pmi->mi_pmiNext = _pmiFirst; _pmiFirst = pmi; pmi->mi_afFrames = (float *)malloc(sizeof(float)*_ctFrames); } // enum all subgroups of this group FindMorphChannels(idGroup); } } // create anim name (from original file name) void GetAnimID(char *fnAnimFile) { char temp[256]; char strAnimName[256]; strcpy(temp,fnAnimFile); char *pchDot = strrchr(temp, '.'); char *pchSlash = strrchr(temp, '\\'); int IResultS = pchSlash - temp + 1; int IResultD = pchDot - temp; if((pchDot!=NULL) && (pchSlash!=NULL)) { int len = IResultD-IResultS; memcpy(strAnimName,&temp[IResultS],len); strAnimName[len] = '_'; strAnimName[len+1] = 0; strcat(strAnimName,_sci->name); char *pchDot2 = strrchr(strAnimName, '.'); if(pchDot2!=NULL) *pchDot2 = 0; } else { strcpy(strAnimName,fnAnimFile); } strcpy(fnAnimFile,strAnimName); } double GetCurrentTime() { LWTimeInfo *_tmi = (LWTimeInfo *)_global( LWTIMEINFO_GLOBAL, GFUSE_TRANSIENT ); return _tmi->time; } void WriteAnimFrame(BoneInfo *pbi,int iFrame) { // Fill 3x4 matrix and store rotation and position in it Matrix12 bi_mRot; BoneFrame &bf = pbi->bi_abfFrames[iFrame]; bf.fi_vPos[2] *= -1; MakeRotationAndPosMatrix(bi_mRot,bf.fi_vPos,bf.fi_vRot); // if doesent have parent (root bone) if(strlen(pbi->bi_strParentName) == 0) { // add position and rotation of parent object to root bone Matrix12 mTemp; MatrixCopy(mTemp,bi_mRot); MatrixMultiply(bi_mRot,_pmRootBoneAbs[iFrame],mTemp); } // write matrix to file PrintMatrix(_f,bi_mRot,4); fprintf(_f,"\n"); } // int ExportAnim(LWXPanelID pan) { if(!_evaluate) { // lightwave error _msg->error("Lightwave process error !\nClose plugins window and try again.\n", NULL); return AFUNC_BADAPP; } bool bDoBones = false; ctBoneEnvelopes = 0; ctMorphEnvelopes = 0; ReloadGlobalObjects(); // !!!! make it work with a selected object, not the first one in scene bool bExportOnlySelected = false; int bExportAnimBackward = *(int*)_xpanf->formGet( pan, ID_ANIM_ORDER); // count selected objects int ctSelectedMeshed = 0; int ctMeshes=0; _objid = _iti->first(LWI_OBJECT,0); while(_objid != LWITEM_NULL) { if(_iti->type(_objid) == LWI_OBJECT) { _pmesh = _obi->meshInfo(_objid, 0); if(_pmesh != NULL) { if(_ifi->itemFlags(_objid) & LWITEMF_SELECTED) { ctSelectedMeshed++; } } ctMeshes++; } _objid = _iti->next(_objid); } // get the first object in the scene _objid = _iti->first(LWI_OBJECT,0); if (!_objid) { _msg->error("No object in the scene.", NULL); return AFUNC_OK; } // if some objects are selected export only them if(ctSelectedMeshed > 0) bExportOnlySelected = true; // dont ask to export all meshes if only one mesh in the scene if(ctSelectedMeshed == 0) { if(ctMeshes > 1) { if(_msg->yesNo("No objects selected","Export animations for all objects?",NULL) == 0) return AFUNC_OK; bExportOnlySelected = false; } } // loop each mesh in scene while(_objid != LWITEM_NULL) { // get its mesh _pmesh = _obi->meshInfo(_objid, 0); if(_pmesh == NULL) { _objid = _iti->next(_objid); continue; } if(bExportOnlySelected) { if(!(_ifi->itemFlags(_objid) & LWITEMF_SELECTED)) { _objid = _iti->next(_objid); continue; } } // get mesh name _strFileName = strdup(_obi->filename(_objid)); // open the file to print into char fnmOut[256]; strcpy(fnmOut, _strFileName); // get first slash in filename char *pchSlash = strrchr(fnmOut, '.'); if (pchSlash!=NULL) { *(pchSlash++) = '_'; strcpy(pchSlash,_sci->name); char *pchDot = strrchr(fnmOut, '.'); if(pchDot!=NULL) { strcpy(pchDot, ".aa"); } } _f = fopen(fnmOut, "w"); if (_f==NULL) { _msg->error("Can't open file", fnmOut); goto end; } // calculate number of frames to export _ctFrames = ((_ifi->previewEnd-_ifi->previewStart)/_ifi->previewStep)+1; if (_ctFrames<=0) { _ctFrames = 1; } _iFrame = 0; // find all morph channels for the current mesh _pmiFirst = NULL; FindMorphChannels(NULL); // add internal motion handler to each bone if (!ActivateExportHandler(_objid)) { _msg->error("Cannot apply internal bone motion handler!", NULL); } bRecordDefaultFrame = true; if (!ExecCmd("GoToFrame 0")) { goto end; } bRecordDefaultFrame = false; { // for each frame in current preview selection for (int iFrame=_ifi->previewStart; iFrame<=_ifi->previewEnd; iFrame+=_ifi->previewStep) { // go to that frame if (!ExecCmd("GoToFrame %d", iFrame)) { goto end; } assert(_iFrame>=0 && _iFrame<_ctFrames); // NOTE: walking all frames implicitly lets the internal itemmotion handler record all bone positions // we walk the morph maps manually // for each morph in list for (MorphInfo *pmi=_pmiFirst; pmi!=NULL; pmi = pmi->mi_pmiNext) { // evaluate the channel value in this frame pmi->mi_afFrames[_iFrame] = (float)_chi->channelEvaluate(pmi->mi_idChannel, GetCurrentTime()); } _iFrame++; } } char strAnimID[256]; strcpy(strAnimID,_strFileName); GetAnimID(strAnimID); // write the animation header { // LWTimeInfo *_tmi = (LWTimeInfo *)_global( LWTIMEINFO_GLOBAL, GFUSE_TRANSIENT ); fprintf(_f, "SE_ANIM %s;\n\n",SE_ANIM_VER); fprintf(_f, "SEC_PER_FRAME %g;\n", GetCurrentTime() / _ifi->previewEnd * _ifi->previewStep); fprintf(_f, "FRAMES %d;\n", _ctFrames); fprintf(_f, "ANIM_ID \"%s\";\n\n", strAnimID); } // calculate bone and morph envelopes { for(BoneInfo *ptmpbi=_pbiFirst; ptmpbi!=NULL; ptmpbi = ptmpbi->bi_pbiNext) { // LWBONEF_ACTIVE = unsigned int uiFlags = ptmpbi->bi_uiFlags; // if this is bone and it is active if(ptmpbi->bi_lwItemType == LWI_BONE && ptmpbi->bi_uiFlags&LWBONEF_ACTIVE) { ctBoneEnvelopes++; } } for(MorphInfo *ptmpmi=_pmiFirst;ptmpmi!=NULL; ptmpmi = ptmpmi->mi_pmiNext) ctMorphEnvelopes++; } Matrix12 bi_mRot; // for each bone in list fprintf(_f, "BONEENVELOPES %d\n{\n", ctBoneEnvelopes); // last item { BoneInfo *pbiLast = NULL; for (BoneInfo *pbi=_pbiFirst; pbi!=NULL; pbi = pbi->bi_pbiNext) { bool bRootBone = false; if(pbi->bi_lwItemType == LWI_BONE && pbi->bi_uiFlags&LWBONEF_ACTIVE) { // write its info fprintf(_f, " NAME \"%s\"\n", pbi->bi_strName); // write first frame - default pose fprintf(_f, " DEFAULT_POSE {"); BoneFrame &bfDef = pbi->bi_abfDefault; bfDef.fi_vPos[2] *= -1; MakeRotationAndPosMatrix(bi_mRot,bfDef.fi_vPos,bfDef.fi_vRot); PrintMatrix(_f,bi_mRot,0); fprintf(_f, "}\n"); fprintf(_f, " {\n"); LWItemType itLast; if(!pbiLast) itLast = LWI_OBJECT; else itLast = pbiLast->bi_lwItemType; // is this root bone if(pbi->bi_lwItemType == LWI_BONE && itLast != LWI_BONE) { // mark as root bone bRootBone = true; } // if export anims backward if(bExportAnimBackward) { // for each frame for (int iFrame=_ctFrames-1; iFrame>=0; iFrame--) { // write anim WriteAnimFrame(pbi,iFrame); } // else export normal order } else { // for each frame for (int iFrame=0; iFrame<_ctFrames; iFrame++) { // write anim WriteAnimFrame(pbi,iFrame); } } fprintf(_f," }\n\n"); pbiLast = pbi; } } } fprintf(_f,"}\n"); fprintf(_f, "\nMORPHENVELOPES %d\n{\n", ctMorphEnvelopes); // for each morph in list {for (MorphInfo *pmi=_pmiFirst; pmi!=NULL; pmi = pmi->mi_pmiNext) { // write its info fprintf(_f, " NAME \"%s\"\n", pmi->mi_strName); fprintf(_f, " {\n"); // if export anims backward if(bExportAnimBackward) { for (int iFrame=_ctFrames-1; iFrame>=0; iFrame--) { fprintf(_f, " %g;\n", pmi->mi_afFrames[iFrame]); } // if anims order is normal } else { for (int iFrame=0; iFrame<_ctFrames; iFrame++) { fprintf(_f, " %g;\n", pmi->mi_afFrames[iFrame]); } } fprintf(_f," }\n\n"); } } fprintf(_f,"}\n"); // free all morph infos { MorphInfo *pmi=_pmiFirst; MorphInfo *pmiNext=NULL; for(;;) { if(pmi==NULL) { break; } pmiNext = pmi->mi_pmiNext; free(pmi->mi_strName); free(pmi->mi_afFrames); free(pmi); pmi = pmiNext; }} fprintf(_f, "SE_ANIM_END;\n"); _msg->info("Saved:", fnmOut); end: // remove internal motion handler from each bone DeactivateExportHandler(_objid); // close and free everything if (_f!=NULL) { fclose(_f); _f=NULL; } _pbiFirst = NULL; // get next mesh obj _objid = _iti->next(_objid); } return AFUNC_OK; } int ExportSkeleton(void) { if(!_evaluate) { // lightwave error _msg->error("Lightwave process error !\nClose plugins window and try again.\n", NULL); return AFUNC_BADAPP; } // !!!! make it work with a selected object, not the first one in scene ReloadGlobalObjects(); bool bExportOnlySelected = false; int ctSkeletonBones=0; // count selected objects int ctSelectedMeshed = 0; int ctMeshes=0; _objid = _iti->first(LWI_OBJECT,0); while(_objid != LWITEM_NULL) { if(_iti->type(_objid) == LWI_OBJECT) { _pmesh = _obi->meshInfo(_objid, 0); if(_pmesh != NULL) { if(_ifi->itemFlags(_objid) & LWITEMF_SELECTED) { ctSelectedMeshed++; } } ctMeshes++; } _objid = _iti->next(_objid); } // get the first object in the scene _objid = _iti->first(LWI_OBJECT,0); if (!_objid) { _msg->error("No object in the scene.", NULL); return AFUNC_OK; } // if some objects are selected export only them if(ctSelectedMeshed > 0) bExportOnlySelected = true; // dont ask to export all meshes if only one mesh in the scene if(ctSelectedMeshed == 0) { if(ctMeshes > 1) { if(_msg->yesNo("No objects selected","Export skeletons for all objects?",NULL) == 0) return AFUNC_OK; bExportOnlySelected = false; } } // loop each mesh in scene while(_objid != LWITEM_NULL) { // get its mesh _pmesh = _obi->meshInfo(_objid, 0); if(_pmesh == NULL) { _objid = _iti->next(_objid); continue; } if(bExportOnlySelected) { if(!(_ifi->itemFlags(_objid) & LWITEMF_SELECTED)) { _objid = _iti->next(_objid); continue; } } // get mesh name _strFileName = strdup(_obi->filename(_objid)); // open the file to print into char fnmOut[256]; strcpy(fnmOut, _strFileName); char *pchDot = strrchr(fnmOut, '.'); if (pchDot!=NULL) { strcpy(pchDot, ".as"); } _f = fopen(fnmOut, "w"); if (_f==NULL) { _msg->error("Can't open file", fnmOut); goto end; } // set bones counter to 0 _ctBones = 0; // add internal motion handler to each bone if (!ActivateExportHandler(_objid)) { _msg->error("Cannot apply internal bone motion handler!", NULL); } assert(_CrtCheckMemory()); bRecordDefaultFrame = true; if (!ExecCmd("GoToFrame 0")) { goto end; } bRecordDefaultFrame = false; { for(BoneInfo *ptmpbi=_pbiFirst; ptmpbi!=NULL; ptmpbi = ptmpbi->bi_pbiNext) { if(ptmpbi->bi_lwItemType == LWI_BONE) { ctSkeletonBones++; } } } fprintf(_f, "SE_SKELETON %s;\n\n",SE_ANIM_VER); fprintf(_f, "BONES %d\n{\n",ctSkeletonBones); Matrix12 bi_mRot; {for (BoneInfo *pbi=_pbiFirst; pbi!=NULL; pbi = pbi->bi_pbiNext) { if(pbi->bi_lwItemType == LWI_BONE) { assert(_CrtCheckMemory()); // write its info fprintf(_f, " NAME \"%s\";\n", pbi->bi_strName); fprintf(_f, " PARENT \"%s\";\n", pbi->bi_strParentName); fprintf(_f, " LENGTH %g;\n", pbi->fRestLength); fprintf(_f, " {\n"); // write first frame - default pose BoneFrame &bfDef = pbi->bi_abfDefault; bfDef.fi_vPos[2] *= -1; MakeRotationAndPosMatrix(bi_mRot,bfDef.fi_vPos,bfDef.fi_vRot); PrintMatrix(_f,bi_mRot,4); fprintf(_f,"\n }\n"); } } } assert(_CrtCheckMemory()); fprintf(_f, "}\n\nSE_SKELETON_END;\n"); _msg->info("Saved:", fnmOut); end: DeactivateExportHandler(_objid); if (_f!=NULL) { fclose(_f); _f=NULL; } _pbiFirst = NULL; // get next mesh obj _objid = _iti->next(_objid); } return AFUNC_OK; }
26.179365
118
0.592403
[ "mesh", "object", "3d" ]
deda22fba25f6991a7c632c9079db52b44b4c9bf
4,431
cpp
C++
test/lowlevel_perf.cpp
janmarthedal/kanooth-numbers
2c6ce4f588bdd26826c20a84154881d84a70191c
[ "BSL-1.0" ]
2
2017-10-02T13:29:54.000Z
2018-04-24T18:17:18.000Z
test/lowlevel_perf.cpp
janmarthedal/kanooth-numbers
2c6ce4f588bdd26826c20a84154881d84a70191c
[ "BSL-1.0" ]
null
null
null
test/lowlevel_perf.cpp
janmarthedal/kanooth-numbers
2c6ce4f588bdd26826c20a84154881d84a70191c
[ "BSL-1.0" ]
null
null
null
#include <vector> #include <boost/random/mersenne_twister.hpp> #include <boost/random/uniform_int_distribution.hpp> #include <kanooth/numbers/lowlevel/generic_has_double.hpp> #include <kanooth/numbers/lowlevel/generic_sim_double.hpp> #include <kanooth/numbers/lowlevel/low_double_int.hpp> #include <kanooth/number_bits.hpp> #include <kanooth/fixed_width_ints.hpp> #include "common/stopwatch.hpp" boost::random::mt19937 gen; template <typename T> void random_array(T* begin, T* end) { boost::random::uniform_int_distribution<T> rand; while (begin != end) *begin++ = rand(gen); } template <typename LOWLEVEL> class tester { public: tester(unsigned _length) : length(_length) { digit_type* r; for (unsigned k = 0; k < count; ++k) { r = new digit_type[length]; random_array(r, r + length); a.push_back(r); r = new digit_type[length]; random_array(r, r + length); b.push_back(r); c.push_back(new digit_type[length]); } random_array(&scalar, &scalar + 1); } ~tester() { for (unsigned k = 0; k < count; ++k) { delete[] a[k]; delete[] b[k]; delete[] c[k]; } } double test_add() { stopwatch<> timer; unsigned reps = length > 10000 ? 1 : 10000/length; for (unsigned j = 0; j < reps; ++j) for (unsigned k = 0; k < count; ++k) LOWLEVEL::add(c[k], a[k], length, b[k], length); return 0.000000001 * count * reps * length * digit_bits / timer.seconds(); } double test_sub() { stopwatch<> timer; unsigned reps = length > 10000 ? 1 : 10000/length; for (unsigned j = 0; j < reps; ++j) for (unsigned k = 0; k < count; ++k) LOWLEVEL::sub(c[k], a[k], length, b[k], length); return 0.000000001 * count * reps * length * digit_bits / timer.seconds(); } double test_mul_1() { stopwatch<> timer; unsigned reps = length > 10000 ? 1 : 10000/length; for (unsigned j = 0; j < reps; ++j) for (unsigned k = 0; k < count; ++k) LOWLEVEL::mul_1(c[k], a[k], length, b[k][0]); return 0.000000001 * count * reps * length * digit_bits / timer.seconds(); } void run() { std::cout.flags(std::ios::fixed); std::cout.precision(2); std::cout << "add " << test_add() << " Gbit/s" << std::endl; std::cout << "sub " << test_sub() << " Gbit/s" << std::endl; std::cout << "mul_1 " << test_mul_1() << " Gbit/s" << std::endl; } private: typedef typename LOWLEVEL::digit_type digit_type; static const unsigned digit_bits = kanooth::number_bits<digit_type>::value; static const unsigned count = 10000; const unsigned length; std::vector<digit_type*> a; std::vector<digit_type*> b; std::vector<digit_type*> c; digit_type scalar; }; int main() { //tester<kanooth::numbers::lowlevel::generic_has_double<kanooth::uint64_t, kanooth::uint128_t> >(1000).run(); tester<kanooth::numbers::lowlevel::generic_has_double<kanooth::uint32_t, kanooth::uint64_t> >(1000).run(); //tester<kanooth::numbers::lowlevel::generic_has_double<kanooth::uint16_t, kanooth::uint32_t> >(1000).run(); //tester<kanooth::numbers::lowlevel::generic_has_double<kanooth::uint64_t, kanooth::numbers::lowlevel::low_double_int<kanooth::uint64_t> > >(1000).run(); tester<kanooth::numbers::lowlevel::generic_sim_double<kanooth::uint64_t> >(1000).run(); /*tester<kanooth::numbers::lowlevel::generic_has_double<kanooth::uint16_t, kanooth::uint32_t> >(1000).run(); tester<kanooth::numbers::lowlevel::generic_has_double<kanooth::uint16_t, kanooth::numbers::lowlevel::low_double_int<kanooth::uint16_t> > >(1000).run(); tester<kanooth::numbers::lowlevel::generic_sim_double<kanooth::uint16_t> >(1000).run();*/ /*tester<kanooth::numbers::lowlevel::generic_has_double<kanooth::uint64_t, kanooth::uint128_t> >(1000).run(); tester<kanooth::numbers::lowlevel::generic_has_double<kanooth::uint64_t, kanooth::numbers::lowlevel::low_double_int<kanooth::uint64_t> > >(1000).run(); tester<kanooth::numbers::lowlevel::generic_sim_double<kanooth::uint64_t> >(1000).run();*/ return 0; }
36.02439
157
0.606635
[ "vector" ]
deda367d4efe4a696751cfa7ea0726b24b55c554
2,631
cpp
C++
zone3InterfaceCompatibilityRecordTests.cpp
mark0n/generateFRUStorage
0642937b8c4349aae4790d4bd5301b989960bee4
[ "MIT" ]
null
null
null
zone3InterfaceCompatibilityRecordTests.cpp
mark0n/generateFRUStorage
0642937b8c4349aae4790d4bd5301b989960bee4
[ "MIT" ]
null
null
null
zone3InterfaceCompatibilityRecordTests.cpp
mark0n/generateFRUStorage
0642937b8c4349aae4790d4bd5301b989960bee4
[ "MIT" ]
null
null
null
#include "zone3InterfaceCompatibilityRecord.hpp" #include "testUtils.hpp" #include <boost/test/unit_test.hpp> #include <boost/assign/list_of.hpp> #include <iostream> BOOST_AUTO_TEST_SUITE( zone3InterfaceCompatibilityTests ) BOOST_AUTO_TEST_CASE( constructorEmpty ) { zone3InterfaceCompatibilityRecord zone(uint8_t interface, interfaceIdentifierBody* body); } BOOST_AUTO_TEST_CASE( constructorGetBinaryData ) { uint8_t interface = 4; std::string ident = "00000000"; std::vector<std::string> interfaceBody; interfaceBody.push_back(ident); interfaceIdentifierBody bodyObject(interface, interfaceBody); interfaceIdentifierBody* body = &bodyObject; zone3InterfaceCompatibilityRecord zone(interface, body); std::vector<uint8_t> manResult = boost::assign::list_of(0xc0)(0x02)(0x0a)(0x40)(0xf4)(0x5a)(0x31)(0x00)(0x30)(0x01)(0x04)(0x00)(0x00)(0x00)(0x00); std::vector<uint8_t> autoResult = zone.getBinaryData(); BOOST_CHECK_EQUAL_COLLECTIONS( autoResult.cbegin(), autoResult.cend(), manResult.cbegin(), manResult.cend() ); if( autoResult != manResult ) { std::cout << "should be: "; std::copy(manResult.cbegin(), manResult.cend(), std::ostream_iterator<int>(std::cout << std::hex, " ")); std::cout << std::endl; std::cout << "is: "; std::copy(autoResult.cbegin(), autoResult.cend(), std::ostream_iterator<int>(std::cout << std::hex, " ")); std::cout << std::endl; } } BOOST_AUTO_TEST_CASE( binarySize ) { uint8_t interface = 1; std::string ident = "12345678"; std::string major = "01"; std::string minor = "05"; std::string opaque = "1234567890"; std::vector<std::string> interfaceBody; interfaceBody.push_back(ident); interfaceBody.push_back(major); interfaceBody.push_back(minor); interfaceBody.push_back(opaque); interfaceIdentifierBody bodyObject(interface, interfaceBody); interfaceIdentifierBody* body = &bodyObject; zone3InterfaceCompatibilityRecord zone(interface, body); BOOST_CHECK_EQUAL(zone.getBinaryData().size(), 22); } BOOST_AUTO_TEST_CASE( size ) { uint8_t interface = 1; std::string ident = "12345678"; std::string major = "01"; std::string minor = "05"; std::string opaque = "1234567890"; std::vector<std::string> interfaceBody; interfaceBody.push_back(ident); interfaceBody.push_back(major); interfaceBody.push_back(minor); interfaceBody.push_back(opaque); interfaceIdentifierBody bodyObject(interface, interfaceBody); interfaceIdentifierBody* body = &bodyObject; zone3InterfaceCompatibilityRecord zone(interface, body); BOOST_CHECK_EQUAL(zone.size(), 22); } BOOST_AUTO_TEST_SUITE_END()
35.08
148
0.735462
[ "vector" ]
dedb235e1cb2bbe97ad618fd8b67b53b4b01e599
6,747
cpp
C++
src/particle_filter.cpp
Sakshi-Rai/CarND-Kidnapped-Vehicle
535df4a9e7e3470ceec86185941087c577bc171d
[ "MIT" ]
null
null
null
src/particle_filter.cpp
Sakshi-Rai/CarND-Kidnapped-Vehicle
535df4a9e7e3470ceec86185941087c577bc171d
[ "MIT" ]
null
null
null
src/particle_filter.cpp
Sakshi-Rai/CarND-Kidnapped-Vehicle
535df4a9e7e3470ceec86185941087c577bc171d
[ "MIT" ]
null
null
null
/* * particle_filter.cpp * * Created on: Dec 12, 2016 * Author: Tiffany Huang */ #include <random> #include <algorithm> #include <iostream> #include <numeric> #include <math.h> #include <iostream> #include <sstream> #include <string> #include <iterator> #include <cstdlib> #include <cfloat> #include "particle_filter.h" using namespace std; void ParticleFilter::init(double x, double y, double theta, double std[]) { // TODO: Set the number of particles. Initialize all particles to first position (based on estimates of // x, y, theta and their uncertainties from GPS) and all weights to 1. // Add random Gaussian noise to each particle. // NOTE: Consult particle_filter.h for more information about this method (and others in this file). num_particles=10; default_random_engine gen; // This line creates a normal (Gaussian) distribution for x,y,theta normal_distribution<double> dist_x(x,std[0]); normal_distribution<double> dist_y(y,std[1]); normal_distribution<double> dist_theta(theta,std[2]); for(int i=0;i<num_particles;i++){ Particle p = {}; p.id=i; p.x=dist_x(gen); p.y=dist_y(gen); p.theta=dist_theta(gen); p.weight=1.0; particles.push_back(p); weights.push_back(p.weight); } is_initialized=true; } void ParticleFilter::prediction(double delta_t, double std_pos[], double velocity, double yaw_rate) { // TODO: Add measurements to each particle and add random Gaussian noise. // NOTE: When adding noise you may find std::normal_distribution and std::default_random_engine useful. // http://en.cppreference.com/w/cpp/numeric/random/normal_distribution // http://www.cplusplus.com/reference/random/default_random_engine/ default_random_engine gen; for(int i=0;i<num_particles;i++){ double in_theta=particles[i].theta; if(fabs(yaw_rate)>0.0001){ particles[i].x += (velocity/yaw_rate)*(sin(in_theta+(yaw_rate*delta_t))-sin(in_theta)); particles[i].y += (velocity/yaw_rate)*(cos(in_theta)-cos(in_theta+(yaw_rate*delta_t))); particles[i].theta += (yaw_rate*delta_t); } else{ particles[i].x += (velocity*delta_t*cos(in_theta)); particles[i].y += (velocity*delta_t*sin(in_theta)); particles[i].theta = in_theta; } normal_distribution<double> dist_x(0,std_pos[0]); normal_distribution<double> dist_y(0,std_pos[1]); normal_distribution<double> dist_theta(0,std_pos[2]); particles[i].x+=dist_x(gen); particles[i].y+=dist_y(gen); particles[i].theta+=dist_theta(gen); } //cout << "predicted"; } void ParticleFilter::dataAssociation(std::vector<LandmarkObs> predicted, std::vector<LandmarkObs>& observations) { // TODO: Find the predicted measurement that is closest to each observed measurement and assign the // observed measurement to this particular landmark. // NOTE: this method will NOT be called by the grading code. But you will probably find it useful to } void ParticleFilter::updateWeights(double sensor_range, double std_landmark[], const std::vector<LandmarkObs> &observations, const Map &map_landmarks) { //cout << observations.size() << endl; std::vector<LandmarkObs> closest_landmark(observations.size()); double den= (2 * M_PI * std_landmark[0] * std_landmark[1]); for(int i=0;i<num_particles;i++) { double p=1.0; double xm ; double ym ; for(int j=0;j<observations.size();j++) { xm = particles[i].x + (cos(particles[i].theta)*observations[j].x) - (sin(particles[i].theta)*observations[j].y); ym = particles[i].y + (sin(particles[i].theta)*observations[j].x) + (cos(particles[i].theta)*observations[j].y); //cout << "transformed coordinates" << xm << ym << endl; double distance=DBL_MAX; for(int k=0;k<map_landmarks.landmark_list.size();k++) { double value=dist(xm,ym,map_landmarks.landmark_list[k].x_f,map_landmarks.landmark_list[k].y_f); //cout << "distance" << value << endl; if(value<distance) { //cout << "map landmark" << map_landmarks.landmark_list[k].x_f << map_landmarks.landmark_list[k].y_f << endl; closest_landmark[j].x=map_landmarks.landmark_list[k].x_f; closest_landmark[j].y=map_landmarks.landmark_list[k].y_f; //cout << "closest landmark" << closest_landmark[j].x << "#" <<closest_landmark[j].y << endl; distance=value; } } double x_term = pow(xm - closest_landmark[j].x, 2) / (2 * pow(std_landmark[0], 2)); double y_term = pow(ym - closest_landmark[j].y, 2) / (2 * pow(std_landmark[1], 2)); double w= exp(-(x_term + y_term)) /den; //cout << "w" << p <<" "<< w << endl; //cout << p << endl; p=p*w; } //cout << "final weight" << p << endl; particles[i].weight=p; weights[i]=p; } } void ParticleFilter::resample() { // TODO: Resample particles with replacement with probability proportional to their weight. // NOTE: You may find std::discrete_distribution helpful here. // http://en.cppreference.com/w/cpp/numeric/random/discrete_distribution std::discrete_distribution<int> ddist(weights.begin(), weights.end()); default_random_engine gen; vector<Particle> resampled_particles; for (int i = 0; i < num_particles; i++) { Particle p={}; p = particles[ddist(gen)]; resampled_particles.push_back(p); } particles = resampled_particles; } Particle ParticleFilter::SetAssociations(Particle& particle, const std::vector<int>& associations, const std::vector<double>& sense_x, const std::vector<double>& sense_y) { //particle: the particle to assign each listed association, and association's (x,y) world coordinates mapping to // associations: The landmark id that goes along with each listed association // sense_x: the associations x mapping already converted to world coordinates // sense_y: the associations y mapping already converted to world coordinates particle.associations= associations; particle.sense_x = sense_x; particle.sense_y = sense_y; } string ParticleFilter::getAssociations(Particle best) { vector<int> v = best.associations; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<int>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseX(Particle best) { vector<double> v = best.sense_x; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; } string ParticleFilter::getSenseY(Particle best) { vector<double> v = best.sense_y; stringstream ss; copy( v.begin(), v.end(), ostream_iterator<float>(ss, " ")); string s = ss.str(); s = s.substr(0, s.length()-1); // get rid of the trailing space return s; }
35.510526
116
0.693345
[ "vector" ]
dede7dddeecf5b8e8f8e2a7ec974e99f8d3bd5b9
10,419
cpp
C++
src/AdditinalOutputPoint.cpp
yoshiya-usui/FEMTIC
0c529e9cfd4e2acc80412b84c758bd6a70bc03f0
[ "MIT" ]
13
2021-11-08T16:20:48.000Z
2021-12-16T12:30:35.000Z
src/AdditinalOutputPoint.cpp
yoshiya-usui/FEMTIC
0c529e9cfd4e2acc80412b84c758bd6a70bc03f0
[ "MIT" ]
3
2021-11-11T05:59:01.000Z
2021-11-11T06:05:05.000Z
src/AdditinalOutputPoint.cpp
yoshiya-usui/FEMTIC
0c529e9cfd4e2acc80412b84c758bd6a70bc03f0
[ "MIT" ]
1
2021-11-24T11:30:31.000Z
2021-11-24T11:30:31.000Z
//------------------------------------------------------------------------------------------------------- // The MIT License (MIT) // // Copyright (c) 2021 Yoshiya Usui // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. //------------------------------------------------------------------------------------------------------- #include <fstream> #include <iostream> #include "AnalysisControl.h" #include "AdditinalOutputPoint.h" #include "OutputFiles.h" #include "CommonParameters.h" // Constructer AdditinalOutputPoint::AdditinalOutputPoint(): m_elementIncludingStation(0) { m_location.X = 0.0; m_location.Y = 0.0; m_location.Z = 0.0; m_localCoordinateValues.X = 0.0; m_localCoordinateValues.Y = 0.0; m_localCoordinateValues.Z = 0.0; m_volumeCoordinateValues.coord0 = 0.0; m_volumeCoordinateValues.coord1 = 0.0; m_volumeCoordinateValues.coord2 = 0.0; m_volumeCoordinateValues.coord3 = 0.0; for( int iPol = 0; iPol < 2; ++iPol ){ m_ExCalculated[iPol] =NULL; m_EyCalculated[iPol] =NULL; m_EzCalculated[iPol] =NULL; m_HxCalculated[iPol] =NULL; m_HyCalculated[iPol] =NULL; m_HzCalculated[iPol] =NULL; } } // Destructer AdditinalOutputPoint::~AdditinalOutputPoint(){ for( int iPol = 0; iPol < 2; ++iPol ){ if( m_ExCalculated[iPol] != NULL ){ delete [] m_ExCalculated[iPol]; m_ExCalculated[iPol] =NULL; } if( m_EyCalculated[iPol] != NULL ){ delete [] m_EyCalculated[iPol]; m_EyCalculated[iPol] =NULL; } if( m_EzCalculated[iPol] != NULL ){ delete [] m_EzCalculated[iPol]; m_EzCalculated[iPol] =NULL; } if( m_HxCalculated[iPol] != NULL ){ delete [] m_HxCalculated[iPol]; m_HxCalculated[iPol] =NULL; } if( m_HyCalculated[iPol] != NULL ){ delete [] m_HyCalculated[iPol]; m_HyCalculated[iPol] =NULL; } if( m_HzCalculated[iPol] != NULL ){ delete [] m_HzCalculated[iPol]; m_HzCalculated[iPol] =NULL; } } } // Read data from input file void AdditinalOutputPoint::inputObservedData( std::ifstream& inFile ){ double dbuf(0.0); inFile >> dbuf; m_location.X = dbuf * CommonParameters::convKilometerToMeter; inFile >> dbuf; m_location.Y = dbuf * CommonParameters::convKilometerToMeter; inFile >> dbuf; m_location.Z = dbuf * CommonParameters::convKilometerToMeter; #ifdef _DEBUG_WRITE std::cout << m_location.X << " " << m_location.Y << " " << m_location.Z << std::endl; #endif } // Find element including station void AdditinalOutputPoint::findElementIncludingStation(){ const int meshType = ( AnalysisControl::getInstance() )->getTypeOfMesh(); if( meshType == MeshData::TETRA ){// Tetra mesh const MeshDataTetraElement* const ptrMeshDataTetraElement = ( AnalysisControl::getInstance() )->getPointerOfMeshDataTetraElement(); m_elementIncludingStation = ptrMeshDataTetraElement->findElementIncludingPoint( m_location.X, m_location.Y, m_location.Z, m_volumeCoordinateValues ); #ifdef _DEBUG_WRITE std::cout << "m_elementIncludingStation m_localCoordinateValues.coord0 m_localCoordinateValues.coord1 m_localCoordinateValues.coord2 m_localCoordinateValues.coord3 " << m_elementIncludingStation << " " << m_volumeCoordinateValues.coord0 << " " << m_volumeCoordinateValues.coord1 << " " << m_volumeCoordinateValues.coord2 << " " << m_volumeCoordinateValues.coord3 << std::endl; #endif }else if( meshType == MeshData::HEXA ){// Hexa mesh const MeshDataBrickElement* const ptrMeshDataBrickElement = ( AnalysisControl::getInstance() )->getPointerOfMeshDataBrickElement(); double dummy(0.0); m_elementIncludingStation = ptrMeshDataBrickElement->findElementIncludingPoint( m_location.X, m_location.Y, m_location.Z, m_localCoordinateValues.X, m_localCoordinateValues.Y, m_localCoordinateValues.Z, false, false, dummy, dummy ); }else if( meshType == MeshData::NONCONFORMING_HEXA ){ const MeshDataNonConformingHexaElement* const ptrMeshDataHexaElement = ( AnalysisControl::getInstance() )->getPointerOfMeshDataNonConformingHexaElement(); m_elementIncludingStation = ptrMeshDataHexaElement->findElementIncludingPoint( m_location.X, m_location.Y, m_location.Z, m_localCoordinateValues.X, m_localCoordinateValues.Y, m_localCoordinateValues.Z ); }else{ OutputFiles::m_logFile << "Error : Wrong type of mesh : " << meshType << std::endl; exit(1); } } // Calulate EM field void AdditinalOutputPoint::calculateEMField( const int ifreq, const Forward3D* const ptrForward3D ){ if( m_elementIncludingStation < 0 ){ return; } const int iPol = ptrForward3D->getPolarizationCurrent(); const int meshType = ( AnalysisControl::getInstance() )->getTypeOfMesh(); if( meshType == MeshData::TETRA ){// Tetra mesh m_ExCalculated[iPol][ifreq] = ptrForward3D->calcValueElectricFieldXDirection( m_elementIncludingStation, m_volumeCoordinateValues.coord1, m_volumeCoordinateValues.coord2, m_volumeCoordinateValues.coord3 ); m_EyCalculated[iPol][ifreq] = ptrForward3D->calcValueElectricFieldYDirection( m_elementIncludingStation, m_volumeCoordinateValues.coord1, m_volumeCoordinateValues.coord2, m_volumeCoordinateValues.coord3 ); m_EzCalculated[iPol][ifreq] = ptrForward3D->calcValueElectricFieldZDirection( m_elementIncludingStation, m_volumeCoordinateValues.coord1, m_volumeCoordinateValues.coord2, m_volumeCoordinateValues.coord3 ); m_HxCalculated[iPol][ifreq] = ptrForward3D->calcValueMagneticFieldXDirection( m_elementIncludingStation, m_volumeCoordinateValues.coord1, m_volumeCoordinateValues.coord2, m_volumeCoordinateValues.coord3 ); m_HyCalculated[iPol][ifreq] = ptrForward3D->calcValueMagneticFieldYDirection( m_elementIncludingStation, m_volumeCoordinateValues.coord1, m_volumeCoordinateValues.coord2, m_volumeCoordinateValues.coord3 ); m_HzCalculated[iPol][ifreq] = ptrForward3D->calcValueMagneticFieldZDirection( m_elementIncludingStation, m_volumeCoordinateValues.coord1, m_volumeCoordinateValues.coord2, m_volumeCoordinateValues.coord3 ); }else if( meshType == MeshData::HEXA || meshType == MeshData::NONCONFORMING_HEXA ){ m_ExCalculated[iPol][ifreq] = ptrForward3D->calcValueElectricFieldXDirection( m_elementIncludingStation, m_localCoordinateValues.X, m_localCoordinateValues.Y, m_localCoordinateValues.Z ); m_EyCalculated[iPol][ifreq] = ptrForward3D->calcValueElectricFieldYDirection( m_elementIncludingStation, m_localCoordinateValues.X, m_localCoordinateValues.Y, m_localCoordinateValues.Z ); m_EzCalculated[iPol][ifreq] = ptrForward3D->calcValueElectricFieldZDirection( m_elementIncludingStation, m_localCoordinateValues.X, m_localCoordinateValues.Y, m_localCoordinateValues.Z ); m_HxCalculated[iPol][ifreq] = ptrForward3D->calcValueMagneticFieldXDirection( m_elementIncludingStation, m_localCoordinateValues.X, m_localCoordinateValues.Y, m_localCoordinateValues.Z ); m_HyCalculated[iPol][ifreq] = ptrForward3D->calcValueMagneticFieldYDirection( m_elementIncludingStation, m_localCoordinateValues.X, m_localCoordinateValues.Y, m_localCoordinateValues.Z ); m_HzCalculated[iPol][ifreq] = ptrForward3D->calcValueMagneticFieldZDirection( m_elementIncludingStation, m_localCoordinateValues.X, m_localCoordinateValues.Y, m_localCoordinateValues.Z ); }else{ OutputFiles::m_logFile << "Error : Wrong type of mesh : " << meshType << std::endl; exit(1); } } // Initialize EM field void AdditinalOutputPoint::initializeEMfield( const int nfreq ){ for( int iPol = 0; iPol < 2; ++iPol ){ for( int ifreq = 0; ifreq < nfreq; ++ifreq ){ m_ExCalculated[iPol][ifreq] = std::complex<double>(0.0,0.0); m_EyCalculated[iPol][ifreq] = std::complex<double>(0.0,0.0); m_EzCalculated[iPol][ifreq] = std::complex<double>(0.0,0.0); m_HxCalculated[iPol][ifreq] = std::complex<double>(0.0,0.0); m_HyCalculated[iPol][ifreq] = std::complex<double>(0.0,0.0); m_HzCalculated[iPol][ifreq] = std::complex<double>(0.0,0.0); } } } // Allcate memory for EM field void AdditinalOutputPoint::allocateMemoryForCalculatedValues( const int nfreq ){ for( int iPol = 0; iPol < 2; ++iPol ){ m_ExCalculated[iPol] = new std::complex<double>[nfreq]; m_EyCalculated[iPol] = new std::complex<double>[nfreq]; m_EzCalculated[iPol] = new std::complex<double>[nfreq]; m_HxCalculated[iPol] = new std::complex<double>[nfreq]; m_HyCalculated[iPol] = new std::complex<double>[nfreq]; m_HzCalculated[iPol] = new std::complex<double>[nfreq]; } } // Output calculated values of EM field void AdditinalOutputPoint::outputCalculatedValues( const int nfreq, const double* const freq ) const{ if( m_elementIncludingStation < 0 ){ return; } for( int ifreq = 0; ifreq < nfreq; ++ifreq ){ fprintf( OutputFiles::m_csvFile, " %15.6lf, %15.6lf, %15.6lf, %15.6e,", m_location.X*0.001, m_location.Y*0.001, m_location.Z*0.001, freq[ifreq] ); for( int iPol = 0; iPol < 2; ++iPol ){ fprintf( OutputFiles::m_csvFile, " %15.6e, %15.6e, %15.6e, %15.6e, %15.6e, %15.6e, %15.6e, %15.6e, %15.6e, %15.6e, %15.6e, %15.6e,", m_ExCalculated[iPol][ifreq].real(), m_ExCalculated[iPol][ifreq].imag(), m_EyCalculated[iPol][ifreq].real(), m_EyCalculated[iPol][ifreq].imag(), m_EzCalculated[iPol][ifreq].real(), m_EzCalculated[iPol][ifreq].imag(), m_HxCalculated[iPol][ifreq].real(), m_HxCalculated[iPol][ifreq].imag(), m_HyCalculated[iPol][ifreq].real(), m_HyCalculated[iPol][ifreq].imag(), m_HzCalculated[iPol][ifreq].real(), m_HzCalculated[iPol][ifreq].imag() ); } fprintf( OutputFiles::m_csvFile, "\n"); } }
44.909483
207
0.74153
[ "mesh" ]
dee85875681b439f1b6e022235957ffd8b9d64d3
6,063
cpp
C++
control/json/triggers/init.cpp
mikecgithub/phosphor-fan-presence
a66d154ed073fda465616a40670c98979c47ee91
[ "Apache-2.0" ]
null
null
null
control/json/triggers/init.cpp
mikecgithub/phosphor-fan-presence
a66d154ed073fda465616a40670c98979c47ee91
[ "Apache-2.0" ]
null
null
null
control/json/triggers/init.cpp
mikecgithub/phosphor-fan-presence
a66d154ed073fda465616a40670c98979c47ee91
[ "Apache-2.0" ]
null
null
null
/** * Copyright © 2021 IBM Corporation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "init.hpp" #include "../manager.hpp" #include "action.hpp" #include "group.hpp" #include "sdbusplus.hpp" #include "trigger_aliases.hpp" #include <fmt/format.h> #include <nlohmann/json.hpp> #include <phosphor-logging/log.hpp> #include <algorithm> #include <iterator> #include <memory> #include <numeric> #include <utility> #include <vector> namespace phosphor::fan::control::json::trigger::init { using json = nlohmann::json; using namespace phosphor::logging; void getProperties(Manager* mgr, const Group& group) { for (const auto& member : group.getMembers()) { try { // Check if property already cached auto value = mgr->getProperty(member, group.getInterface(), group.getProperty()); if (value == std::nullopt) { // Property not in cache, attempt to add it mgr->addObjects(member, group.getInterface(), group.getProperty()); } } catch (const util::DBusMethodError& dme) { // Configured dbus object does not exist on dbus yet? // TODO How to handle this? Create timer to keep checking for // object/service to appear? When to stop checking? } } } void nameHasOwner(Manager* mgr, const Group& group) { std::string lastName = ""; for (const auto& member : group.getMembers()) { std::string servName = ""; auto intf = group.getInterface(); try { servName = mgr->getService(member, intf); if (!servName.empty() && lastName != servName) { // Member not provided by same service as last group member lastName = servName; auto hasOwner = util::SDBusPlus::callMethodAndRead<bool>( mgr->getBus(), "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "NameHasOwner", servName); // Update service name owner state of group object mgr->setOwner(member, servName, intf, hasOwner); } if (servName.empty()) { // Path and/or interface configured does not exist on dbus? // TODO How to handle this? Create timer to keep checking for // object/service to appear? When to stop checking? log<level::ERR>( fmt::format( "Unable to get service name for path {}, interface {}", member, intf) .c_str()); } } catch (const util::DBusMethodError& dme) { if (!servName.empty()) { // Failed to get service name owner state mgr->setOwner(member, servName, intf, false); } else { // Path and/or interface configured does not exist on dbus? // TODO How to handle this? Create timer to keep checking for // object/service to appear? When to stop checking? log<level::ERR>( fmt::format( "Unable to get service name for path {}, interface {}", member, intf) .c_str()); throw dme; } } } } enableTrigger triggerInit(const json& jsonObj, const std::string& eventName, std::vector<std::unique_ptr<ActionBase>>& actions) { // Get the method handler if configured auto handler = methods.end(); if (jsonObj.contains("method")) { auto method = jsonObj["method"].get<std::string>(); std::transform(method.begin(), method.end(), method.begin(), tolower); handler = methods.find(method); } for (auto& action : actions) { // Groups are optional, so a method is only required if there are groups // i.e.) An init triggered event without any groups results in just // running the actions if (!action->getGroups().empty() && handler == methods.end()) { // Construct list of available methods auto availMethods = std::accumulate( std::next(methods.begin()), methods.end(), methods.begin()->first, [](auto list, auto method) { return std::move(list) + ", " + method.first; }); auto msg = fmt::format("Event '{}' requires a supported method given to " "be init driven, available methods: {}", eventName, availMethods); log<level::ERR>(msg.c_str()); throw std::runtime_error(msg.c_str()); } } return [handler = std::move(handler)]( const std::string& eventName, Manager* mgr, std::vector<std::unique_ptr<ActionBase>>& actions) { for (auto& action : actions) { for (const auto& group : action->getGroups()) { // Call method handler for each group in the actions handler->second(mgr, group); } // Run the action action->run(); } }; } } // namespace phosphor::fan::control::json::trigger::init
34.844828
80
0.541646
[ "object", "vector", "transform" ]
def2e4a2da64f2349a5e1dfed487ebca1b749e89
2,962
hpp
C++
include/codegen/include/System/CultureAwareComparer.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/System/CultureAwareComparer.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/System/CultureAwareComparer.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" // Including type: System.StringComparer #include "System/StringComparer.hpp" // Including type: System.Globalization.CompareOptions #include "System/Globalization/CompareOptions.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: System::Globalization namespace System::Globalization { // Forward declaring type: CompareInfo class CompareInfo; // Forward declaring type: CultureInfo class CultureInfo; } // Completed forward declares // Type namespace: System namespace System { // Autogenerated type: System.CultureAwareComparer class CultureAwareComparer : public System::StringComparer { public: // private System.Globalization.CompareInfo _compareInfo // Offset: 0x10 System::Globalization::CompareInfo* compareInfo; // private System.Boolean _ignoreCase // Offset: 0x18 bool ignoreCase; // private System.Globalization.CompareOptions _options // Offset: 0x1C System::Globalization::CompareOptions options; // System.Void .ctor(System.Globalization.CultureInfo culture, System.Boolean ignoreCase) // Offset: 0x10CF128 static CultureAwareComparer* New_ctor(System::Globalization::CultureInfo* culture, bool ignoreCase); // public override System.Int32 Compare(System.String x, System.String y) // Offset: 0x10CF1DC // Implemented from: System.StringComparer // Base method: System.Int32 StringComparer::Compare(System.String x, System.String y) int Compare(::Il2CppString* x, ::Il2CppString* y); // public override System.Boolean Equals(System.String x, System.String y) // Offset: 0x10CF22C // Implemented from: System.StringComparer // Base method: System.Boolean StringComparer::Equals(System.String x, System.String y) bool Equals(::Il2CppString* x, ::Il2CppString* y); // public override System.Int32 GetHashCode(System.String obj) // Offset: 0x10CF280 // Implemented from: System.StringComparer // Base method: System.Int32 StringComparer::GetHashCode(System.String obj) int GetHashCode(::Il2CppString* obj); // public override System.Boolean Equals(System.Object obj) // Offset: 0x10CF324 // Implemented from: System.Object // Base method: System.Boolean Object::Equals(System.Object obj) bool Equals(::Il2CppObject* obj); // public override System.Int32 GetHashCode() // Offset: 0x10CF3EC // Implemented from: System.Object // Base method: System.Int32 Object::GetHashCode() int GetHashCode(); }; // System.CultureAwareComparer } #include "extern/beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(System::CultureAwareComparer*, "System", "CultureAwareComparer"); #pragma pack(pop)
42.927536
104
0.726199
[ "object" ]
def888e09cb2fa44ece267942c9964a9433a5dd3
3,415
cpp
C++
frameworks/bridge/declarative_frontend/engine/jsi/modules/jsi_app_module.cpp
openharmony-gitee-mirror/ace_ace_engine
78013960cdce81348d1910e466a3292605442a5e
[ "Apache-2.0" ]
null
null
null
frameworks/bridge/declarative_frontend/engine/jsi/modules/jsi_app_module.cpp
openharmony-gitee-mirror/ace_ace_engine
78013960cdce81348d1910e466a3292605442a5e
[ "Apache-2.0" ]
null
null
null
frameworks/bridge/declarative_frontend/engine/jsi/modules/jsi_app_module.cpp
openharmony-gitee-mirror/ace_ace_engine
78013960cdce81348d1910e466a3292605442a5e
[ "Apache-2.0" ]
1
2021-09-13T11:17:50.000Z
2021-09-13T11:17:50.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "frameworks/bridge/declarative_frontend/engine/jsi/modules/jsi_app_module.h" #include "base/log/log.h" #include "frameworks/bridge/declarative_frontend/engine/jsi/jsi_declarative_engine.h" #include "frameworks/bridge/js_frontend/engine/common/js_constants.h" namespace OHOS::Ace::Framework { shared_ptr<JsValue> AppGetInfo(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj, const std::vector<shared_ptr<JsValue>>& argv, int32_t argc) { auto instance = static_cast<JsiDeclarativeEngineInstance*>(runtime->GetEmbedderData()); if (instance == nullptr) { LOGE("get jsi engine instance failed"); return runtime->NewNull(); } auto delegate = instance->GetDelegate(); if (!delegate) { LOGE("get frontend delegate failed"); return runtime->NewNull(); } shared_ptr<JsValue> appInfo = runtime->NewObject(); auto appId = delegate->GetAppID(); auto appName = delegate->GetAppName(); auto versionName = delegate->GetVersionName(); auto versionCode = delegate->GetVersionCode(); appInfo->SetProperty(runtime, "appID", runtime->NewString(appId)); appInfo->SetProperty(runtime, "appName", runtime->NewString(appName)); appInfo->SetProperty(runtime, "versionName", runtime->NewString(versionName)); appInfo->SetProperty(runtime, "versionCode", runtime->NewNumber(versionCode)); return appInfo; } shared_ptr<JsValue> AppTerminate(const shared_ptr<JsRuntime>& runtime, const shared_ptr<JsValue>& thisObj, const std::vector<shared_ptr<JsValue>>& argv, int32_t argc) { auto instance = static_cast<JsiDeclarativeEngineInstance*>(runtime->GetEmbedderData()); if (instance == nullptr) { LOGE("get jsi engine instance failed"); return runtime->NewNull(); } auto delegate = instance->GetDelegate(); if (!delegate) { LOGE("get frontend delegate failed"); return runtime->NewNull(); } auto pipelineContext = instance->GetPipelineContext(runtime); if (!pipelineContext) { LOGE("get frontend pipelineContext failed"); return runtime->NewNull(); } auto uiTaskExecutor = delegate->GetUiTask(); WeakPtr<PipelineContext> pipelineContextWeak(pipelineContext); uiTaskExecutor.PostTask([pipelineContextWeak]() mutable { auto pipelineContext = pipelineContextWeak.Upgrade(); if (pipelineContext) { pipelineContext->Finish(); } }); return runtime->NewNull(); } void InitAppModule(const shared_ptr<JsRuntime>& runtime, shared_ptr<JsValue>& moduleObj) { moduleObj->SetProperty(runtime, APP_GET_INFO, runtime->NewFunction(AppGetInfo)); moduleObj->SetProperty(runtime, APP_TERMINATE, runtime->NewFunction(AppTerminate)); } } // namespace OHOS::Ace::Framework
40.176471
106
0.715081
[ "vector" ]
7207d10bc55f9dd727776eda54f555c5f7af58bf
1,220
cpp
C++
Leetcode/Dynamic Programming/Combination Sum IV (iterative).cpp
UVE-R/CP-CPP
67819f4115917f663c22ada899b27ace7b2e9b9e
[ "Unlicense" ]
1
2021-08-24T21:05:28.000Z
2021-08-24T21:05:28.000Z
Leetcode/Dynamic Programming/Combination Sum IV (iterative).cpp
UVE-R/CP-CPP
67819f4115917f663c22ada899b27ace7b2e9b9e
[ "Unlicense" ]
null
null
null
Leetcode/Dynamic Programming/Combination Sum IV (iterative).cpp
UVE-R/CP-CPP
67819f4115917f663c22ada899b27ace7b2e9b9e
[ "Unlicense" ]
null
null
null
//ITERATIVE SOLUTION class Solution { public: int combinationSum4(vector<int>& nums, int target) { unsigned long long dp[target + 1]; //Stores the number of ways to get ith sum memset(dp,0,sizeof(dp)); //Fill with zeros dp[0] = 1; //Only 1 way of getting a sum of 0 sort(nums.begin(), nums.end()); //Sort nums int n = nums.size(); //Size of nums for iteration for(int i=1; i<= target; i++){ //For each ith sum for(int j=0; j<n; j++){ if(nums[j] <= i){ //In case of out of bounds as dp[x] must have x>=0 //The problem of finding the ith sum is the same as finding the ways of getting // i-x sum where x is the coin number. // As coin x is added as a way of getting ith sum, it counts as a single way //Then is multipled by the ways to get i-x sum, which is just 1* dp[i-x] = dp[i-x] dp[i] += dp[i-nums[j]]; }else{ break; } } } return dp[target]; } };
32.972973
102
0.463934
[ "vector" ]
720c584ece1cba70a351abe1716d9ef983eea668
1,410
cpp
C++
ReframeLibrary/Code_samples/ReframeSampleCpp/reframe.cpp
adal02/swissREFRAME
7e6e53e4a5ec470d70566fb3d4355f9cf1ad6b6a
[ "MIT" ]
1
2021-10-20T23:19:27.000Z
2021-10-20T23:19:27.000Z
ReframeLibrary/Code_samples/ReframeSampleCpp/reframe.cpp
adal02/swissREFRAME
7e6e53e4a5ec470d70566fb3d4355f9cf1ad6b6a
[ "MIT" ]
1
2020-11-19T00:04:22.000Z
2020-11-19T13:54:51.000Z
ReframeLibrary/Code_samples/ReframeSampleCpp/reframe.cpp
adal02/swissREFRAME
7e6e53e4a5ec470d70566fb3d4355f9cf1ad6b6a
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include <Windows.h> #include "reframe.h" int main() { // Input coordinates to transform double east = 640000.0, north = 184000.0, height = 530.0; try { // ReframeWrapper object ReframeWrapper reframeLibObj; // Process coordinate transformation LV03->LV95, LN02->Bessel bool outsideChenyx06 = !reframeLibObj.ComputeReframe(east, north, east, ReframeWrapper::LV03_Military, ReframeWrapper::LV95, ReframeWrapper::LN02, ReframeWrapper::Ellipsoid); // Message if outside CHENyx06 if (outsideChenyx06) std::cout << "Input coordinates are outside Swiss TLM perimeter: a translation has been applied!" << std::endl; // Write results to console std::cout << "REFRAME transformation terminated: " << std::endl; // Format outputs (3 decimals) char buffer[100]; sprintf_s(buffer, "%.3lf", east); std::string sEast = buffer; sprintf_s(buffer, "%.3lf", north); std::string sNorth = buffer; sprintf_s(buffer, "%.3lf", height); std::string sHeight = buffer; std::cout << "E: " << sEast << " m / N: " << sNorth << " m / H: " << sHeight << " m" << std::endl; Sleep(5000); return 0; } catch (std::runtime_error re) { std::cout << "REFRAME error: " << re.what() << std::endl; Sleep(5000); return 1; } catch (...) { std::cout << "Internal error: impossible to load ReframeWrapper" << std::endl; Sleep(5000); return 1; } }
26.603774
176
0.66383
[ "object", "transform" ]
7211656807db507ba04ee9f51cf966324e2385e3
8,418
cpp
C++
libvast/src/system/partition.cpp
knapperzbusch/vast
9d2af995254519b47febe2062adbc55965055cbe
[ "BSD-3-Clause" ]
null
null
null
libvast/src/system/partition.cpp
knapperzbusch/vast
9d2af995254519b47febe2062adbc55965055cbe
[ "BSD-3-Clause" ]
1
2019-11-29T12:43:41.000Z
2019-11-29T12:43:41.000Z
libvast/src/system/partition.cpp
knapperzbusch/vast
9d2af995254519b47febe2062adbc55965055cbe
[ "BSD-3-Clause" ]
null
null
null
/****************************************************************************** * _ _____ __________ * * | | / / _ | / __/_ __/ Visibility * * | |/ / __ |_\ \ / / Across * * |___/_/ |_/___/ /_/ Space and Time * * * * This file is part of VAST. It is subject to the license terms in the * * LICENSE file found in the top-level directory of this distribution and at * * http://vast.io/license. No part of VAST, including this file, may be * * copied, modified, propagated, or distributed except according to the terms * * contained in the LICENSE file. * ******************************************************************************/ #include "vast/system/partition.hpp" #include <caf/event_based_actor.hpp> #include <caf/local_actor.hpp> #include <caf/make_counted.hpp> #include <caf/stateful_actor.hpp> #include "vast/concept/printable/to_string.hpp" #include "vast/concept/printable/vast/expression.hpp" #include "vast/concept/printable/vast/uuid.hpp" #include "vast/detail/assert.hpp" #include "vast/event.hpp" #include "vast/expression_visitors.hpp" #include "vast/ids.hpp" #include "vast/load.hpp" #include "vast/logger.hpp" #include "vast/save.hpp" #include "vast/system/atoms.hpp" #include "vast/system/index.hpp" #include "vast/system/spawn_indexer.hpp" #include "vast/system/table_indexer.hpp" #include "vast/time.hpp" using namespace std::chrono; using namespace caf; namespace vast::system { partition::partition(index_state* state, uuid id, size_t max_capacity) : state_(state), id_(std::move(id)), capacity_(max_capacity) { // If the directory already exists, we must have some state from the past and // are pre-loading all INDEXER types we are aware of. VAST_ASSERT(state != nullptr); } partition::~partition() noexcept { flush_to_disk(); } // -- persistence -------------------------------------------------------------- caf::error partition::init() { VAST_TRACE(""); auto file_path = meta_file(); if (!exists(file_path)) return ec::no_such_file; if (auto err = load(nullptr, file_path , meta_data_)) return err; VAST_DEBUG(state_->self, "loaded partition", id_, "from disk with", meta_data_.types.size(), "layouts"); return caf::none; } caf::error partition::flush_to_disk() { if (meta_data_.dirty) { // Write all layouts to disk. if (auto err = save(nullptr, meta_file(), meta_data_)) return err; meta_data_.dirty = false; } // Write state for each layout to disk. for (auto& kvp : table_indexers_) if (auto err = kvp.second.flush_to_disk()) return err; return caf::none; } // -- properties --------------------------------------------------------------- namespace { using eval_mapping = evaluation_map::mapped_type; caf::actor fetch_indexer(table_indexer& tbl, const data_extractor& dx, [[maybe_unused]] relational_operator op, [[maybe_unused]] const data& x) { VAST_TRACE(VAST_ARG(tbl), VAST_ARG(dx), VAST_ARG(op), VAST_ARG(x)); // Sanity check. if (dx.offset.empty()) return nullptr; auto& r = caf::get<record_type>(dx.type); auto k = r.resolve(dx.offset); VAST_ASSERT(k); auto index = r.flat_index_at(dx.offset); if (!index) { VAST_DEBUG(tbl.state().self, "got invalid offset for record type", dx.type); return nullptr; } return tbl.indexer_at(*index); } caf::actor fetch_indexer(table_indexer& tbl, const attribute_extractor& ex, relational_operator op, const data& x) { VAST_TRACE(VAST_ARG(tbl), VAST_ARG(ex), VAST_ARG(op), VAST_ARG(x)); auto& layout = tbl.layout(); if (ex.attr == system::type_atom::value) { // Doesn't apply if the query name doesn't match our type. if (!evaluate(layout.name(), op, x)) return nullptr; // We know the answer immediately: all IDs that are part of the table. // However, we still have to "lift" this result into an actor for the // EVALUATOR. // TODO: Spawning a one-shot actor is quite expensive. Maybe the // table_indexer could instead maintain this actor lazily. auto row_ids = tbl.row_ids(); return tbl.state().self->spawn([row_ids]() -> caf::behavior { return [=](const curried_predicate&) { return row_ids; }; }); } if (ex.attr == system::timestamp_atom::value) { if (!caf::holds_alternative<timestamp>(x)) { VAST_WARNING(tbl.state().self, "expected a timestamp as time extractor attribute , got:", x); return nullptr; } // Find the column with attribute 'time'. auto pred = [](auto& x) { return caf::holds_alternative<time_type>(x.type) && has_attribute(x.type, "timestamp"); }; auto& fs = layout.fields; auto i = std::find_if(fs.begin(), fs.end(), pred); if (i == fs.end()) return nullptr; // Redirect to "ordinary data lookup". auto pos = static_cast<size_t>(std::distance(fs.begin(), i)); data_extractor dx{layout, vast::offset{pos}}; return fetch_indexer(tbl, dx, op, x); } VAST_WARNING(tbl.state().self, "got unsupported attribute:", ex.attr); return nullptr; } } // namespace evaluation_map partition::eval(const expression& expr) { evaluation_map result; // Step #1: use the expression to select matching layouts. for (auto layout : layouts()) { // Step #2: Split the resolved expression into its predicates and select // all matching INDEXER actors per predicate. auto resolved = resolve(expr, layout); // Skip any layout that we cannot resolve. if (resolved.empty()) continue; // Add triples (offset, curried predicate, and INDEXER) to evaluation map. evaluation_map::mapped_type triples; for (auto& kvp: resolved) { auto& pred = kvp.second; auto get_indexer_handle = [&](const auto& ext, const data& x) { if (auto i = get_or_add(layout)) return fetch_indexer(i->first, ext, pred.op, x); VAST_ERROR(state_->self, "failed to initialize table_indexer for layout", layout, "-> query will not execute on the full data set"); return caf::actor{}; }; auto v = detail::overload( [&](const attribute_extractor& ex, const data& x) { return get_indexer_handle(ex, x); // clang-format fix }, [&](const data_extractor& dx, const data& x) { return get_indexer_handle(dx, x); }, [](const auto&, const auto&) { return caf::actor{}; // clang-format fix }); auto hdl = caf::visit(v, pred.lhs, pred.rhs); if (hdl != nullptr) { triples.emplace_back(kvp.first, curried(pred), std::move(hdl)); } } if (!triples.empty()) result.emplace(layout, std::move(triples)); } return result; } std::vector<record_type> partition::layouts() const { std::vector<record_type> result; auto& ts = meta_data_.types; result.reserve(ts.size()); std::transform(ts.begin(), ts.end(), std::back_inserter(result), [](auto& kvp) { return kvp.second; }); return result; } path partition::base_dir() const { return state_->dir / to_string(id_); } path partition::meta_file() const { return base_dir() / "meta"; } caf::expected<std::pair<table_indexer&, bool>> partition::get_or_add(const record_type& key) { VAST_TRACE(VAST_ARG(key)); auto i = table_indexers_.find(key); if (i != table_indexers_.end()) return std::pair<table_indexer&, bool>{i->second, false}; auto digest = to_digest(key); add_layout(digest, key); auto ti = table_indexer::make(this, key); if (!ti) return ti.error(); auto result = table_indexers_.emplace(key, std::move(*ti)); VAST_ASSERT(result.second == true); return std::pair<table_indexer&, bool>{result.first->second, true}; } } // namespace vast::system namespace std { namespace { using pptr = vast::system::partition_ptr; } // namespace <anonymous> size_t hash<pptr>::operator()(const pptr& ptr) const { hash<vast::uuid> f; return ptr != nullptr ? f(ptr->id()) : 0u; } } // namespace std
34.5
80
0.604419
[ "vector", "transform" ]
722575cebb09494cc98dd9c2f17eb8b43ff2168c
2,447
cpp
C++
lib/popsparse/BalancedPartitioner.cpp
graphcore/poplibs
3fe5a3ecafe995eddb72675d1b4a7af8a622009e
[ "MIT" ]
95
2020-07-06T17:11:23.000Z
2022-03-12T14:42:28.000Z
lib/popsparse/BalancedPartitioner.cpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
null
null
null
lib/popsparse/BalancedPartitioner.cpp
giantchen2012/poplibs
2bc6b6f3d40863c928b935b5da88f40ddd77078e
[ "MIT" ]
14
2020-07-15T12:32:57.000Z
2022-01-26T14:58:45.000Z
// Copyright (c) 2020 Graphcore Ltd. All rights reserved. #include "BalancedPartitioner.hpp" #include <algorithm> #include <float.h> #include <poplibs_support/logging.hpp> #include <poputil/exceptions.hpp> namespace logging = poplibs_support::logging; namespace popsparse { namespace experimental { void BalancedPartitioner::partition(const std::vector<float> &nodeW, int nPartition, std::vector<int> &nodeAssignment) { std::vector<std::pair<float, int>> nodes(nodeW.size()); for (unsigned i = 0; i < nodeW.size(); i++) { nodes[i].first = nodeW[i]; nodes[i].second = i; } std::sort(nodes.begin(), nodes.end(), std::greater<std::pair<float, int>>()); std::vector<std::vector<int>> partition(nPartition); std::vector<float> partitionW(nPartition, 0.0); for (unsigned i = 0; i < nodes.size(); i++) { // find the partition that has less weight float min = FLT_MAX; unsigned minIndex = -1; for (unsigned k = 0; k < partition.size(); k++) { if (partitionW[k] < min) { min = partitionW[k]; minIndex = k; } } partition[minIndex].push_back(nodes[i].second); partitionW[minIndex] += nodes[i].first; } nodeAssignment.resize(nodes.size()); for (unsigned k = 0; k < partition.size(); k++) { for (unsigned n = 0; n < partition[k].size(); n++) { nodeAssignment[partition[k][n]] = k; } } } float BalancedPartitioner::partitionGraph(const HyperGraphData &graphData, int nPartition, std::vector<int> &nodeAssignment) { partition(graphData.weights, nPartition, nodeAssignment); float minWeight, maxWeight, avgWeight, balance; int minTileId, maxTileId, zeroTiles; computeLoadBalance(graphData.weights, nPartition, nodeAssignment, minWeight, minTileId, maxWeight, maxTileId, avgWeight, balance, zeroTiles); logging::popsparse::info("Min weight {} on tile {}", minWeight, minTileId); logging::popsparse::info("Max weight {} on tile {}", maxWeight, maxTileId); logging::popsparse::info("Average weight {}", avgWeight); logging::popsparse::info( "partition load balance {}, number of tile that has no " "assignment {}", balance, zeroTiles); return balance + zeroTiles; } } // namespace experimental } // namespace popsparse
33.067568
79
0.622395
[ "vector" ]
722665110a20b2398616d2a73b62110fe8422d98
3,266
cpp
C++
PandoraDLL/cwPandoraUIApp.cpp
pegasusTrader/PandoraTraderUI
e79761390b60a54c195b6b50e34943e79576f917
[ "Apache-2.0" ]
7
2020-07-26T13:52:30.000Z
2021-11-29T11:39:13.000Z
PandoraDLL/cwPandoraUIApp.cpp
zhuzhenping/PandoraTraderUI
e79761390b60a54c195b6b50e34943e79576f917
[ "Apache-2.0" ]
null
null
null
PandoraDLL/cwPandoraUIApp.cpp
zhuzhenping/PandoraTraderUI
e79761390b60a54c195b6b50e34943e79576f917
[ "Apache-2.0" ]
13
2020-09-11T00:45:56.000Z
2022-03-26T15:02:24.000Z
#include "stdafx.h" #include "cwPandoraUIApp.h" cwPandoraUIApp::cwPandoraUIApp() : m_ppOrder(NULL) , m_ipOrderCount(0) , m_ppPosition(NULL) , m_ipPositionCount(0) , m_ppTrade(NULL) , m_ipTradeCount(0) { } cwPandoraUIApp::~cwPandoraUIApp() { if (m_ppOrder != NULL) { delete[]m_ppOrder; m_ppOrder = NULL; } m_UIOrderMap.clear(); if (m_ppPosition != NULL) { delete[] m_ppPosition; m_ppPosition = NULL; } m_UIPositionsMap.clear(); if (m_ppTrade != NULL) { delete[] m_ppTrade; m_ppTrade = NULL; } m_UITradeMap.clear(); } void cwPandoraUIApp::Run(const char* pszMdFront, const char* pszTradeFront) { this->m_TradeChannel.RegisterBasicStrategy(dynamic_cast<cwBasicStrategy*>(&(this->m_cwPandoraUIStategy))); this->m_mdCollector.RegisterTradeSPI(dynamic_cast<cwBasicTradeSpi*>(&(this->m_TradeChannel))); this->m_mdCollector.RegisterStrategy(dynamic_cast<cwBasicStrategy*>(&(this->m_cwPandoraUIStategy))); this->m_TradeChannel.SetSaveInstrumentDataToFile(true); if (pszTradeFront != NULL && strlen(pszTradeFront) > 0) { this->m_TradeChannel.Connect(pszTradeFront); } if (pszMdFront != NULL && strlen(pszMdFront) > 0) { this->m_mdCollector.Connect(pszMdFront); } std::vector<std::string> SubscribeInstrument; SubscribeInstrument.push_back("ag2012"); this->m_mdCollector.SubscribeMarketData(SubscribeInstrument); } bool cwPandoraUIApp::GetUIAllOrders() { bool Ret = m_cwPandoraUIStategy.GetAllOrders(m_UIOrderMap); if (m_UIOrderMap.size() > 0) { if ((int)m_UIOrderMap.size() > m_ipOrderCount) { m_ipOrderCount = (int)(m_UIOrderMap.size()); if (m_ppOrder != NULL) { delete[]m_ppOrder; } m_ppOrder = new ORDERFIELD * [m_ipOrderCount]; } memset(m_ppOrder, 0, sizeof(ORDERFIELD*) * m_ipOrderCount); int iCount = 0; for (auto it = m_UIOrderMap.begin(); it != m_UIOrderMap.end(); it++, iCount++) { m_ppOrder[iCount] = it->second.get(); } } return Ret; } bool cwPandoraUIApp::GetUIPositions() { bool Ret = m_cwPandoraUIStategy.GetPositions(m_UIPositionsMap); if (m_UIPositionsMap.size() > 0) { if ((int)m_UIPositionsMap.size() * 2 > m_ipPositionCount) { m_ipPositionCount = (int)(m_UIPositionsMap.size()) * 2; if (m_ppPosition != NULL) { delete[]m_ppPosition; } m_ppPosition = new POSITIONFIELD * [m_ipPositionCount]; } memset(m_ppPosition, 0, sizeof(POSITIONFIELD*) * m_ipPositionCount); int iCount = 0; for (auto it = m_UIPositionsMap.begin(); it != m_UIPositionsMap.end(); it++, iCount++) { m_ppPosition[iCount * 2] = it->second->LongPosition.get(); m_ppPosition[iCount * 2 + 1] = it->second->ShortPosition.get(); } } return Ret; } bool cwPandoraUIApp::GetUIAllTrades() { bool Ret = m_cwPandoraUIStategy.GetTrades(m_UITradeMap); if (m_UITradeMap.size() > 0) { if ((int)m_UITradeMap.size() > m_ipTradeCount) { m_ipTradeCount = (int)(m_UITradeMap.size()); if (m_ppTrade != NULL) { delete[]m_ppTrade; } m_ppTrade = new TRADEFIELD * [m_ipTradeCount]; } memset(m_ppTrade, 0, sizeof(TRADEFIELD*) * m_ipTradeCount); int iCount = 0; for (auto it = m_UITradeMap.begin(); it != m_UITradeMap.end(); it++, iCount++) { m_ppTrade[iCount] = it->second.get(); } } return Ret; }
21.486842
107
0.690447
[ "vector" ]
72272a96cf5b53907588f6410a7c3fe6bdeb4b66
2,859
cpp
C++
Co-Simulation/Sumo/sumo-1.7.0/src/guinetload/GUIEdgeControlBuilder.cpp
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
null
null
null
Co-Simulation/Sumo/sumo-1.7.0/src/guinetload/GUIEdgeControlBuilder.cpp
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
null
null
null
Co-Simulation/Sumo/sumo-1.7.0/src/guinetload/GUIEdgeControlBuilder.cpp
uruzahe/carla
940c2ab23cce1eda1ef66de35f66b42d40865fb1
[ "MIT" ]
null
null
null
/****************************************************************************/ // Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo // Copyright (C) 2001-2020 German Aerospace Center (DLR) and others. // This program and the accompanying materials are made available under the // terms of the Eclipse Public License 2.0 which is available at // https://www.eclipse.org/legal/epl-2.0/ // This Source Code may also be made available under the following Secondary // Licenses when the conditions for such availability set forth in the Eclipse // Public License 2.0 are satisfied: GNU General Public License, version 2 // or later which is available at // https://www.gnu.org/licenses/old-licenses/gpl-2.0-standalone.html // SPDX-License-Identifier: EPL-2.0 OR GPL-2.0-or-later /****************************************************************************/ /// @file GUIEdgeControlBuilder.cpp /// @author Daniel Krajzewicz /// @author Jakob Erdmann /// @author Michael Behrisch /// @date Sept 2002 /// // Derivation of NLEdgeControlBuilder which build gui-edges /****************************************************************************/ #include <config.h> #include <vector> #include <string> #include <map> #include <algorithm> #include <guisim/GUIEdge.h> #include <guisim/GUINet.h> #include <guisim/GUILane.h> #include <microsim/MSJunction.h> #include <netload/NLBuilder.h> #include "GUIEdgeControlBuilder.h" #include <gui/GUIGlobals.h> // =========================================================================== // method definitions // =========================================================================== GUIEdgeControlBuilder::GUIEdgeControlBuilder() : NLEdgeControlBuilder() {} GUIEdgeControlBuilder::~GUIEdgeControlBuilder() {} MSLane* GUIEdgeControlBuilder::addLane(const std::string& id, double maxSpeed, double length, const PositionVector& shape, double width, SVCPermissions permissions, int index, bool isRampAccel, const std::string& type) { MSLane* lane = new GUILane(id, maxSpeed, length, myActiveEdge, myCurrentNumericalLaneID++, shape, width, permissions, index, isRampAccel, type); myLaneStorage->push_back(lane); myCurrentLaneIndex = index; return lane; } MSEdge* GUIEdgeControlBuilder::buildEdge(const std::string& id, const SumoXMLEdgeFunc function, const std::string& streetName, const std::string& edgeType, const int priority, const double distance) { return new GUIEdge(id, myCurrentNumericalEdgeID++, function, streetName, edgeType, priority, distance); } /****************************************************************************/
40.267606
148
0.575026
[ "shape", "vector" ]
72374d1749c26fca163483dff244290b93fc1fa6
11,967
cpp
C++
Projects/Chess with mouse handling/main.cpp
umerfarooqpucit/Object-Oriented-Programming
4b8ef68d7f92c7768f72d0534787e8ac11727a55
[ "MIT" ]
null
null
null
Projects/Chess with mouse handling/main.cpp
umerfarooqpucit/Object-Oriented-Programming
4b8ef68d7f92c7768f72d0534787e8ac11727a55
[ "MIT" ]
null
null
null
Projects/Chess with mouse handling/main.cpp
umerfarooqpucit/Object-Oriented-Programming
4b8ef68d7f92c7768f72d0534787e8ac11727a55
[ "MIT" ]
null
null
null
#include<Windows.h> #include<iostream> #include<conio.h> #include<fstream> #include<string> #include "Chess.h" using namespace std; /* PLEASE OPEN IN 100x30 CONSOLE*/ void playGame(); HANDLE hStdin; DWORD fdwSaveOldMode; void GetMousePosWin(MOUSE_EVENT_RECORD); COORD CursorPosition; void setCursor(bool visible, DWORD size); // set bool visible = 0 - invisible, bool visible = 1 - visible void gotoXY(short int a,short int b); int wherex(); int wherey(); void setColor(int a); int main() { setCursor(0,0); DWORD cNumRead, fdwMode, i; INPUT_RECORD irInBuf[128]; int counter=0; // Get the standard input handle. hStdin = GetStdHandle(STD_INPUT_HANDLE); // Save the current input mode, to be restored on exit. GetConsoleMode(hStdin, &fdwSaveOldMode); // Enable the mouse input events. fdwMode = ENABLE_MOUSE_INPUT; SetConsoleMode(hStdin, fdwMode); cout<<endl; setColor(8); cout<<" CCCCCC HHH HHH EEEEEEEEE SSSSSSS SSSSSSS o o o o"<<endl; Sleep(80); setColor(8); cout<<" CCCCCCC HHH HHH EEEEEEEEE SSSSSSSS SSSSSSSS ooooo ooooooo"<<endl; Sleep(80); setColor(15); cout<<" CCC HHH HHH EEE SSS SSS ooooo ooooooo"<<endl; Sleep(80); setColor(15); cout<<" CCC HHH HHH EEE SSS SSS ooo ooo "<<endl; Sleep(80); setColor(15); cout<<" CCC HHHHHHHHHHH EEEEEEEE SSSSSSS SSSSSSS ooo ooo "<<endl; Sleep(80); setColor(15); cout<<" CCC HHHHHHHHHHH EEEEEEEE SSSSSSS SSSSSSS ooo ooo "<<endl; Sleep(80); setColor(15); cout<<" CCC HHH HHH EEE SSS SSS ooo ooo "<<endl; Sleep(80); setColor(15); cout<<" CCC HHH HHH EEE SSS SSS ooo ooo "<<endl; Sleep(80); setColor(8); cout<<" CCCCCCC HHH HHH EEEEEEEEE SSSSSSSS SSSSSSSS ooooooo ooooooo"<<endl; Sleep(80); setColor(8); cout<<" CCCCCC HHH HHH EEEEEEEEE SSSSSSS SSSSSSS OOOOOOO OOOOOOO"<<endl; gotoXY(1,28); cout<<"Copyright 2016 ( \xDB are buttons)"; gotoXY(1,27); cout << "\xDB Developers"; gotoXY(45,12); cout << "MENU"; gotoXY(39,14); cout << "\xDB Play"; gotoXY(39,16); cout << "\xDB Help"; gotoXY(39,18); cout << "\xDB Exit"; while (!counter) { // Wait for the events. ReadConsoleInput( hStdin, // input buffer handle irInBuf, // buffer to read into 128, // size of read buffer &cNumRead) ;// number of records read // Dispatch the events to the appropriate handler. for (i = 0; i < cNumRead; i++) { switch(irInBuf[i].EventType) { case MOUSE_EVENT: // mouse input GetMousePosWin(irInBuf[i].Event.MouseEvent); break; case FOCUS_EVENT: // disregard focus events case MENU_EVENT: // disregard menu events break; } } } SetConsoleMode(hStdin, fdwSaveOldMode); return 0; } void GetMousePosWin(MOUSE_EVENT_RECORD mer) { int x,y; INPUT_RECORD Inrec; DWORD evRead; HANDLE hStdIn; DWORD dwMode; bool Captured=false; hStdIn = GetStdHandle(STD_INPUT_HANDLE); dwMode = ENABLE_MOUSE_INPUT; if( SetConsoleMode( hStdIn, dwMode | ENABLE_MOUSE_INPUT) == TRUE) GetConsoleMode(hStdIn, &dwMode); SetConsoleMode(hStdIn, (dwMode & (ENABLE_MOUSE_INPUT))); do { PeekConsoleInput(hStdIn, &Inrec, 1, &evRead); if( evRead ) { ReadConsoleInput(hStdIn, &Inrec, 1, &evRead); x= Inrec.Event.MouseEvent.dwMousePosition.X ; y= Inrec.Event.MouseEvent.dwMousePosition.Y ; switch (Inrec.EventType ) { case MOUSE_EVENT: { Captured = true; } } } }while(!Captured); if((x>=39 && x<=44) && y==14) { gotoXY(45,16); cout<<" "; gotoXY(45,18); cout<<" "; gotoXY(45,14); cout<<char(251); } else if((x>=39 && x<=44) && y==16) { gotoXY(45,14); cout<<" "; gotoXY(45,18); cout<<" "; gotoXY(45,16); cout<<char(251); } else if((x>=39 && x<=44) && y==18) { gotoXY(45,14); cout<<" "; gotoXY(45,16); cout<<" "; gotoXY(45,18); cout<<char(251); } else { gotoXY(45,18); cout<<" "; gotoXY(45,14); cout<<" "; gotoXY(45,16); cout<<" "; } if(((x>=45 && x<=47) && y==22) && mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED) { SetConsoleMode(hStdin, fdwSaveOldMode); setCursor(1,10); exit(0); } if(((x>=52 && x<=53) && y==22) && mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED) { system("CLS"); main(); } if((x==1 && y==27) && mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED) { gotoXY(38,12); cout<<" "; gotoXY(38,14); cout<<" "; gotoXY(38,16); cout<<" "; gotoXY(38,18); cout<<" "; gotoXY(1,27); cout<<" "; for(int j=1,k=77;j<=35;j++,k--){ gotoXY(j,15); cout<<" Developed By"; gotoXY(k,17); cout<<"Sher Ali & Umer Farooq "; Sleep(80); } gotoXY(80,30); cout<<"\xDB Back"; } if((x==39 && y==14) && mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED) { gotoXY(38,12); cout<<" "; gotoXY(38,14); cout<<" "; gotoXY(38,16); cout<<" "; gotoXY(38,18); cout<<" "; gotoXY(30,16); cout<<"LOADING "; for(int j=0;j<40;j++){ cout<<char(178); Sleep(80); } system("CLS"); playGame(); } if((x==39 && y==16) && mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED) { system("CLS"); cout << "\t\t\t\tHOW TO PLAY\n\n"; cout << "\t\t\tINTRODUCTION\n\n"; cout << "1.The Board is divided into 8 rows and 8 columns.\n"; cout << "2.Columns are labeled with alphabets.\n"; cout << "3.Rows are labeled with numbers.\n"; cout << "4.It is a two players game.\n\n"; cout << "\t\t\tHOW TO MAKE A MOVE\n\n"; cout << "1.First enter the cell address to move from\n then enter the cell address to move to. For example,\n"; cout << " if the cell's address to move from is E1\n and the address to move to is E4 you will write E1E4 or simply e1e4.\n"; cout << "2.You can write address in both uppercase or lowercase format.\n\n"; cout << "\t\t\tMOVES\n\n"; cout << "1.It has original Chess Game's rules.\n"; cout << "2.Any invalid move will give an error.\n"; cout << "3.Moves are as follows :\n"; cout << "->King(k) : Can move to only one box around it.\n"; cout << "->Queen(q) : Can move through whole board.\n"; cout << "->Rook(r) : Can move straight line from front and side.\n"; cout << "->Bishop(b) : Can move through diagonals.\n"; cout << "->Pawn(p) : Can move 2 cells from front at start of game and one afterwards.\n"; cout << "->Knight(n) : Can move in L shape in any direction.(2 cells from front and 1 from side.)\n\n\n"; cout << "Developed By :\nSher Ali BCSF15M012\nM UMER FAROOQ BCSF15M025\n"; gotoXY(70,32); setCursor(1,10); cout<<"Press Any Key to go Back"; _getch(); system("CLS"); main(); } if((x==39 && y==18) && mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED) { gotoXY(38,12); cout<<" "; gotoXY(38,14); cout<<" "; gotoXY(38,16); cout<<" "; gotoXY(38,18); cout<<" "; gotoXY(35,20); cout<<"Are you Sure you want to Exit?"; gotoXY(44,21); cout<<char(201)<<char(205)<<char(205)<<char(205)<<char(187)<<" "<<char(201)<<char(205)<<char(205)<<char(187); gotoXY(44,22); cout<<char(186)<<"Yes"<<char(186)<<" "<<char(186)<<"No"<<char(186); gotoXY(44,23); cout<<char(200)<<char(205)<<char(205)<<char(205)<<char(188)<<" "<<char(200)<<char(205)<<char(205)<<char(188); } if((x==80 && y==30) && mer.dwButtonState == FROM_LEFT_1ST_BUTTON_PRESSED) { system("CLS"); main(); } } void playGame() { setCursor(1,10); Chess *chess = new Chess; chess->displayBoard(); char move[5] = { '\0' }; do { do { if (chess->getTurn()) { cout << "Player1's Move: "; } else { cout << "Player2's Move: "; } cin >> move; if ((toupper(move[0]) == 'E') && (toupper(move[1]) == 'X') && (toupper(move[2]) == 'I') && (toupper(move[3]) == 'T')) { if (chess->getTurn()) { system("cls"); cout << "Winner: Player2\n"; cout << "Press any key to continue..."; _getch(); system("CLS"); main(); } else { system("cls"); cout << "Winner: Player1\n"; cout << "Press any key to continue..."; _getch(); system("CLS"); main(); } } chess->setInput(move); chess->setCoordinatesOfPiece(); } while (chess->inputValidation()); if (chess->getTurn()) { if (chess->getPieceLocation() == 'P' && chess->isPawnValid()) { chess->stepsOfPlayer1(); } else if (chess->getPieceLocation() == 'R' && chess->isRookValid()) { chess->stepsOfPlayer1(); } else if (chess->getPieceLocation() == 'N' && chess->isKnightValid()) { chess->stepsOfPlayer1(); } else if (chess->getPieceLocation() == 'B' && chess->isBishopValid()) { chess->stepsOfPlayer1(); } else if (chess->getPieceLocation() == 'Q' && chess->isQueenValid()) { chess->stepsOfPlayer1(); } else if (chess->getPieceLocation() == 'K' && chess->isKingValid()) { chess->stepsOfPlayer1(); } else { cout << "Illegal Move!!!\n"; } } else { if (chess->getPieceLocation() == 'p' && chess->isPawnValid()) { chess->stepsOfPlayer2(); } else if (chess->getPieceLocation() == 'r' && chess->isRookValid()) { chess->stepsOfPlayer2(); } else if (chess->getPieceLocation() == 'n' && chess->isKnightValid()) { chess->stepsOfPlayer2(); } else if (chess->getPieceLocation() == 'b' && chess->isBishopValid()) { chess->stepsOfPlayer2(); } else if (chess->getPieceLocation() == 'q' && chess->isQueenValid()) { chess->stepsOfPlayer2(); } else if (chess->getPieceLocation() == 'k' && chess->isKingValid()) { chess->stepsOfPlayer2(); } else { cout << "Illegal Move!!!\n"; } } } while (chess->checkmate()); system("cls"); if (chess->gameWon()) { cout << "Winner: Player1\n"; cout << "Press any key to continue..."; _getch(); system("CLS"); main(); } else { cout << "Winner: Player2\n"; cout << "Press any key to continue..."; _getch(); system("CLS"); main(); } } void setCursor(bool visible, DWORD size) // set bool visible = 0 - invisible, bool visible = 1 - visible { HANDLE console=GetStdHandle(STD_OUTPUT_HANDLE); if(size == 0) { size = 20; // default cursor size Changing to numbers from 1 to 20, decreases cursor width } CONSOLE_CURSOR_INFO lpCursor; lpCursor.bVisible = visible; lpCursor.dwSize = size; SetConsoleCursorInfo(console,&lpCursor); } void gotoXY(short int a,short int b) { HANDLE screen=GetStdHandle(STD_OUTPUT_HANDLE); COORD position; position.X=a; position.Y=b; SetConsoleCursorPosition(screen,position); } int wherex() { CONSOLE_SCREEN_BUFFER_INFO csbi; HANDLE screen=GetStdHandle(STD_OUTPUT_HANDLE); if (!GetConsoleScreenBufferInfo(screen,&csbi)) return -1; return csbi.dwCursorPosition.X; } int wherey() { CONSOLE_SCREEN_BUFFER_INFO csbi; HANDLE screen=GetStdHandle(STD_OUTPUT_HANDLE); if (!GetConsoleScreenBufferInfo(screen,&csbi)) return -1; return csbi.dwCursorPosition.Y; } void setColor(int a) { SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), a); }
29.116788
136
0.562296
[ "shape" ]
cf0365672b8f50f7475db89fc7fa222b489e98e1
7,870
cpp
C++
Medusa/Medusa/Application/View/win/WinGLView.cpp
tony2u/Medusa
d4ac8181a693bc796681880e09aac3fdba9aaaaf
[ "MIT" ]
143
2015-11-18T01:06:03.000Z
2022-03-30T03:08:54.000Z
Medusa/Medusa/Application/View/win/WinGLView.cpp
tony2u/Medusa
d4ac8181a693bc796681880e09aac3fdba9aaaaf
[ "MIT" ]
1
2019-10-23T13:00:40.000Z
2019-10-23T13:00:40.000Z
Medusa/Medusa/Application/View/win/WinGLView.cpp
tony2u/Medusa
d4ac8181a693bc796681880e09aac3fdba9aaaaf
[ "MIT" ]
45
2015-11-18T01:17:59.000Z
2022-03-05T12:29:45.000Z
// Copyright (c) 2015 fjz13. All rights reserved. // Use of this source code is governed by a MIT-style // license that can be found in the LICENSE file. #include "MedusaPreCompiled.h" #include "WinGLView.h" #include "Application/Window/win/WinWindow.h" #include "Graphics/ResolutionAdapter.h" #include "Core/Chrono/ProfileSample.h" #include "Graphics/Render/Render.h" #include "Core/Log/Log.h" #include "Core/String/StringParser.h" #include "Graphics/GraphicsContext.h" #include "Rendering/RenderEngine.h" #ifdef MEDUSA_WINDOWS #ifdef MEDUSA_GLEW #include "Lib/win/GLEW/glew.h" MEDUSA_BEGIN; WinGLView::WinGLView(StringRef name/*=StringRef::Empty*/) :BaseRenderView(name) { mDC = nullptr; mRenderContext = nullptr; } WinGLView::~WinGLView(void) { } bool WinGLView::Initialize() { RETURN_FALSE_IF_FALSE(BaseRenderView::Initialize()); WinWindow* window = (WinWindow*)mParent; mDC = GetDC(window->WindowHandle()); if (!SetupPixelFormat()) { Log::FormatError("Failed to SetPixelFormat,Error code:{}", GetLastError()); return false; } mRenderContext = wglCreateContext(mDC); if (mRenderContext == nullptr) { Log::FormatError("Failed to wglCreateContext,Error:{}", GetLastError()); return false; } if (!wglMakeCurrent(mDC, mRenderContext)) { Log::FormatError("Failed to wglMakeCurrent,Error:{}", GetLastError()); return false; } if (!SetupGLEW()) { Log::FormatError("Failed to SetupGLEW."); return false; } RenderEngine::Instance().Initialize(); return true; } bool WinGLView::Uninitialize() { RETURN_TRUE_IF_NULL(mDC); if (mRenderContext != nullptr) { wglMakeCurrent(mDC, nullptr); wglDeleteContext(mRenderContext); mRenderContext = nullptr; } DeleteObject(mDC); mDC = nullptr; return true; } void WinGLView::SwapBuffers() { ::SwapBuffers(mDC); } void WinGLView::FinishDraw() { Render::Instance().Finish(); } void WinGLView::Resize(const Size2F& newSize) { } bool WinGLView::SetupPixelFormat() { int pixelFormat; byte depthBufferSize = GraphicsContext::Instance().NeedDepthBuffer() ? GraphicsContext::Instance().DepthBufferSize() : 0; byte stencilBufferSize = GraphicsContext::Instance().NeedStencilBuffer() ? GraphicsContext::Instance().StencilBufferSize() : 0; PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), // size 1, // version PFD_SUPPORT_OPENGL | // OpenGL window PFD_DRAW_TO_WINDOW | // render to window PFD_DOUBLEBUFFER, // support double-buffering PFD_TYPE_RGBA, // color type 32, // preferred color depth 0, 0, 0, 0, 0, 0, // color bits (ignored) 0, // no alpha buffer 0, // alpha bits (ignored) 0, // no accumulation buffer 0, 0, 0, 0, // accum bits (ignored) depthBufferSize, // depth buffer stencilBufferSize, // no stencil buffer 0, // no auxiliary buffers PFD_MAIN_PLANE, // main layer 0, // reserved 0, 0, 0, // no layer, visible, damage masks }; pixelFormat = ChoosePixelFormat(mDC, &pfd); return SetPixelFormat(mDC, pixelFormat, &pfd) == TRUE; } bool WinGLView::SetupGLEW() { GLenum initResult = glewInit(); if (GLEW_OK != initResult) { char* str = (char*)glewGetErrorString(initResult); Log::FormatError("Failed to glewInit,Error:{}", str); return false; } if (!GLEW_ARB_vertex_shader) { Log::Error("GLEW_ARB_vertex_shader isn't supported!"); return false; } if (!GLEW_ARB_fragment_shader) { Log::Error("GLEW_ARB_vertex_shader isn't supported!"); return false; } StringRef extensionStr = (const char*)glGetString(GL_EXTENSIONS); if (glGenFramebuffers == nullptr) { Log::Info("OpenGL: glGenFramebuffers is nullptr, try to detect an extension"); if (extensionStr.Contains("ARB_framebuffer_object")) { Log::Info("OpenGL: ARB_framebuffer_object is supported"); glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)wglGetProcAddress("glIsRenderbuffer"); glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)wglGetProcAddress("glBindRenderbuffer"); glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)wglGetProcAddress("glDeleteRenderbuffers"); glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)wglGetProcAddress("glGenRenderbuffers"); glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)wglGetProcAddress("glRenderbufferStorage"); glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)wglGetProcAddress("glGetRenderbufferParameteriv"); glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)wglGetProcAddress("glIsFramebuffer"); glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)wglGetProcAddress("glBindFramebuffer"); glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)wglGetProcAddress("glDeleteFramebuffers"); glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)wglGetProcAddress("glGenFramebuffers"); glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)wglGetProcAddress("glCheckFramebufferStatus"); glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC)wglGetProcAddress("glFramebufferTexture1D"); glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)wglGetProcAddress("glFramebufferTexture2D"); glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC)wglGetProcAddress("glFramebufferTexture3D"); glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)wglGetProcAddress("glFramebufferRenderbuffer"); glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)wglGetProcAddress("glGetFramebufferAttachmentParameteriv"); glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)wglGetProcAddress("glGenerateMipmap"); } else if (extensionStr.Contains("EXT_framebuffer_object")) { Log::Info("OpenGL: EXT_framebuffer_object is supported"); glIsRenderbuffer = (PFNGLISRENDERBUFFERPROC)wglGetProcAddress("glIsRenderbufferEXT"); glBindRenderbuffer = (PFNGLBINDRENDERBUFFERPROC)wglGetProcAddress("glBindRenderbufferEXT"); glDeleteRenderbuffers = (PFNGLDELETERENDERBUFFERSPROC)wglGetProcAddress("glDeleteRenderbuffersEXT"); glGenRenderbuffers = (PFNGLGENRENDERBUFFERSPROC)wglGetProcAddress("glGenRenderbuffersEXT"); glRenderbufferStorage = (PFNGLRENDERBUFFERSTORAGEPROC)wglGetProcAddress("glRenderbufferStorageEXT"); glGetRenderbufferParameteriv = (PFNGLGETRENDERBUFFERPARAMETERIVPROC)wglGetProcAddress("glGetRenderbufferParameterivEXT"); glIsFramebuffer = (PFNGLISFRAMEBUFFERPROC)wglGetProcAddress("glIsFramebufferEXT"); glBindFramebuffer = (PFNGLBINDFRAMEBUFFERPROC)wglGetProcAddress("glBindFramebufferEXT"); glDeleteFramebuffers = (PFNGLDELETEFRAMEBUFFERSPROC)wglGetProcAddress("glDeleteFramebuffersEXT"); glGenFramebuffers = (PFNGLGENFRAMEBUFFERSPROC)wglGetProcAddress("glGenFramebuffersEXT"); glCheckFramebufferStatus = (PFNGLCHECKFRAMEBUFFERSTATUSPROC)wglGetProcAddress("glCheckFramebufferStatusEXT"); glFramebufferTexture1D = (PFNGLFRAMEBUFFERTEXTURE1DPROC)wglGetProcAddress("glFramebufferTexture1DEXT"); glFramebufferTexture2D = (PFNGLFRAMEBUFFERTEXTURE2DPROC)wglGetProcAddress("glFramebufferTexture2DEXT"); glFramebufferTexture3D = (PFNGLFRAMEBUFFERTEXTURE3DPROC)wglGetProcAddress("glFramebufferTexture3DEXT"); glFramebufferRenderbuffer = (PFNGLFRAMEBUFFERRENDERBUFFERPROC)wglGetProcAddress("glFramebufferRenderbufferEXT"); glGetFramebufferAttachmentParameteriv = (PFNGLGETFRAMEBUFFERATTACHMENTPARAMETERIVPROC)wglGetProcAddress("glGetFramebufferAttachmentParameterivEXT"); glGenerateMipmap = (PFNGLGENERATEMIPMAPPROC)wglGetProcAddress("glGenerateMipmapEXT"); } else { Log::Error("No frame buffers extension is supported.Any call to FBO will crash!"); return false; } } return true; } MEDUSA_END; #endif #endif
35.133929
151
0.751715
[ "render" ]
cf05e77a0f12b7826b9cc443961fa5c1b2b86502
2,811
cpp
C++
expdist/mex_expdist.cpp
Jonathanzhao02/smlm_datafusion2d
0aff4e6025840bb0d9828e7e5dc9c13c3d241433
[ "Apache-2.0" ]
6
2018-08-28T11:40:00.000Z
2019-09-11T14:34:48.000Z
expdist/mex_expdist.cpp
Jonathanzhao02/smlm_datafusion2d
0aff4e6025840bb0d9828e7e5dc9c13c3d241433
[ "Apache-2.0" ]
7
2018-11-16T18:31:20.000Z
2022-03-29T19:54:44.000Z
expdist/mex_expdist.cpp
Jonathanzhao02/smlm_datafusion2d
0aff4e6025840bb0d9828e7e5dc9c13c3d241433
[ "Apache-2.0" ]
4
2018-10-19T08:58:48.000Z
2022-03-26T20:08:49.000Z
#include <stdio.h> /*%%===================================================================== * %% Project: Pointset Registration using Gaussian Mixture Model * %% Module: $RCSfile: mex_GaussTransform.c,v $ * %% Language: C * %% Author: $Author: bing.jian $ * %% Date: $Date: 2008-11-13 16:34:29 -0500 (Thu, 13 Nov 2008) $ * %% Version: $Revision: 109 $ * %%=====================================================================*/ #include "mex.h" #include "expdist.h" GPUExpDist *gpu_expdist = (GPUExpDist *)NULL; void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { /* Declare variables */ int m, n, dim; double *A, *B, *result, *scale_A, *scale_B; //prevent clearing from memory void mexLock(void); /* Check for proper number of input and output arguments */ if (nrhs != 4) { mexErrMsgTxt("Three input arguments required."); } if (nlhs > 2){ mexErrMsgTxt("Too many output arguments."); } /* Check data type of input argument */ if (!(mxIsDouble(prhs[0]))) { mexErrMsgTxt("Input array must be of type double."); } if (!(mxIsDouble(prhs[1]))) { mexErrMsgTxt("Input array must be of type double."); } if (!(mxIsDouble(prhs[2]))) { mexErrMsgTxt("Input array must be of type double."); } if (!(mxIsDouble(prhs[3]))) { mexErrMsgTxt("Input array must be of type double."); } /* Get the number of elements in the input argument */ /* elements=mxGetNumberOfElements(prhs[0]); */ /* Get the data */ A = (double *)mxGetPr(prhs[0]); B = (double *)mxGetPr(prhs[1]); scale_A = (double *)mxGetPr(prhs[2]); scale_B = (double *)mxGetPr(prhs[3]); /* Get the dimensions of the matrix input A&B. */ m = mxGetM(prhs[0]); n = mxGetM(prhs[1]); dim = mxGetN(prhs[0]); if (mxGetN(prhs[1])!=dim) { mexErrMsgTxt("The two input point sets should have same dimension."); } if (mxGetM(prhs[0])!=mxGetM(prhs[2])) { mexErrMsgTxt("localizations and uncertainties (A) should have same dimension."); } if (mxGetM(prhs[1])!=mxGetM(prhs[3])) { mexErrMsgTxt("localizations and uncertainties (B) should have same dimension."); } if (mxGetN(prhs[2])!=1) { mexErrMsgTxt("uncertainties should be a m*1 matrix."); } if (mxGetN(prhs[3])!=1) { mexErrMsgTxt("uncertainties should be a n*1 matrix."); } /* Allocate the space for the return argument */ plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL); result = mxGetPr(plhs[0]); if (gpu_expdist == (GPUExpDist *)NULL) { gpu_expdist = new GPUExpDist(1000000); } *result = gpu_expdist->compute(A, B, m, n, scale_A, scale_B); }
28.683673
84
0.559232
[ "model" ]
cf077a79189127e74f8b4d7460e787cd60ceea69
1,537
cpp
C++
Conteneurs/main.cpp
guillaumew16/PI_INF442_distrJoin
3600dda77075bfa1bbd9f48e37c609b28ea2c602
[ "ISC" ]
null
null
null
Conteneurs/main.cpp
guillaumew16/PI_INF442_distrJoin
3600dda77075bfa1bbd9f48e37c609b28ea2c602
[ "ISC" ]
null
null
null
Conteneurs/main.cpp
guillaumew16/PI_INF442_distrJoin
3600dda77075bfa1bbd9f48e37c609b28ea2c602
[ "ISC" ]
null
null
null
#include <iostream> #include <ctime> #include "Conteneurs.hpp" #define SAMPLE_SIZE 10000 using namespace std; int main(int argc, char** argv) { clock_t t; vector<vector<int> > sample(SAMPLE_SIZE); for (int x = 0; x < SAMPLE_SIZE; ++x) { for (int y = 0; y < 4; ++y) { sample[x].push_back(y*x); } } cout << "Test de ConteneurNaif :" << endl; cout.flush(); t = clock(); ConteneurNaif cn(sample); t = clock() - t; cout << "Temps de creation : " << t << " ticks." << endl; cout.flush(); t = clock(); for (int x = 0; x < SAMPLE_SIZE; ++x) { for (int y = 0; y < 4; ++y) cn.get(x, y)++; } t = clock() - t; cout << "Temps pour incrementer tous les elements : " << t << " ticks." << endl << endl; cout.flush(); cout << "Test de ConteneurBogoss :" << endl; cout.flush(); t = clock(); ConteneurBogoss cb(sample); t = clock() - t; cout << "Temps de creation : " << t << " ticks." << endl; cout.flush(); t = clock(); for (int x = 0; x < SAMPLE_SIZE; ++x) { for (int y = 0; y < 4; ++y) { try { cb.get(x, y)++; } catch (exception e) { cerr << "Arret sur cb.get pour (x,y) = (" << x << ", " << y << ")." << endl; cerr.flush(); return -1; } } } t = clock() - t; cout << "Temps pour incrementer tous les elements : " << t << " ticks." << endl << endl; cout.flush(); //system("pause"); for Windows, to stop window from closing immediately return 0; }
21.957143
90
0.501627
[ "vector" ]
cf12125e7948ea922036129cf68036c7fe55bcd7
3,678
hpp
C++
include/engine/api/matrix_api.hpp
neilbu/osrm-backend
2a8e1f77459fef33ca34c9fe01ec62e88e255452
[ "BSD-2-Clause" ]
null
null
null
include/engine/api/matrix_api.hpp
neilbu/osrm-backend
2a8e1f77459fef33ca34c9fe01ec62e88e255452
[ "BSD-2-Clause" ]
null
null
null
include/engine/api/matrix_api.hpp
neilbu/osrm-backend
2a8e1f77459fef33ca34c9fe01ec62e88e255452
[ "BSD-2-Clause" ]
1
2021-11-24T14:24:44.000Z
2021-11-24T14:24:44.000Z
#ifndef ENGINE_API_MATRIX_HPP #define ENGINE_API_MATRIX_HPP #include "engine/api/base_api.hpp" #include "engine/api/json_factory.hpp" #include "engine/api/matrix_parameters.hpp" #include "engine/datafacade/datafacade_base.hpp" #include "engine/guidance/assemble_geometry.hpp" #include "engine/guidance/assemble_leg.hpp" #include "engine/guidance/assemble_overview.hpp" #include "engine/guidance/assemble_route.hpp" #include "engine/guidance/assemble_steps.hpp" #include "engine/internal_route_result.hpp" #include "util/integer_range.hpp" #include <boost/range/algorithm/transform.hpp> #include <iterator> namespace osrm { namespace engine { namespace api { class MatrixAPI final : public BaseAPI { public: MatrixAPI(const datafacade::BaseDataFacade &facade_, const MatrixParameters &parameters_) : BaseAPI(facade_, parameters_), parameters(parameters_) { } virtual void MakeResponse(const std::vector<std::pair<EdgeWeight, double>> &durations, const std::vector<PhantomNode> &phantoms, util::json::Object &response) const { auto number_of_coordinates = phantoms.size(); response.values["sources"] = MakeWaypoints(phantoms); response.values["destinations"] = MakeWaypoints(phantoms); response.values["distances"] = MakeMatrix(durations, number_of_coordinates); response.values["code"] = "Ok"; } protected: virtual util::json::Array MakeWaypoints(const std::vector<PhantomNode> &phantoms) const { util::json::Array json_waypoints; json_waypoints.values.reserve(phantoms.size()); BOOST_ASSERT(phantoms.size() == parameters.coordinates.size()); boost::range::transform( phantoms, std::back_inserter(json_waypoints.values), [this](const PhantomNode &phantom) { util::json::Array array; array.values.push_back(static_cast<double>(util::toFloating(phantom.location.lon))); array.values.push_back(static_cast<double>(util::toFloating(phantom.location.lat))); return array; }); return json_waypoints; } virtual util::json::Array MakeMatrix(const std::vector<std::pair<EdgeWeight, double>> &values, std::size_t matrix_size) const { util::json::Array json_table; for (const auto row : util::irange<std::size_t>(0UL, matrix_size)) { util::json::Array json_row; auto row_begin_iterator = values.begin() + (row * matrix_size); auto row_end_iterator = values.begin() + ((row + 1) * matrix_size); json_row.values.resize(matrix_size); std::transform(row_begin_iterator, row_end_iterator, json_row.values.begin(), [](const std::pair<EdgeWeight, double> duration) { util::json::Object result = util::json::Object(); if (duration.first == MAXIMAL_EDGE_DURATION) { result.values["distance"] = util::json::Null(); result.values["time"] = util::json::Null(); } else { result.values["distance"] = duration.first; result.values["time"] = duration.second; } return result; }); json_table.values.push_back(std::move(json_row)); } return json_table; } const MatrixParameters &parameters; }; } // ns api } // ns engine } // ns osrm #endif
33.743119
98
0.610658
[ "object", "vector", "transform" ]
cf1f12e8f9021e2561549015afb2f55fe50c6048
3,367
cpp
C++
test/pubsub_test.cpp
sudo-panda/shadesmar
f181e2b7c4bd3ea5b84d797449285e316402fdd3
[ "MIT" ]
null
null
null
test/pubsub_test.cpp
sudo-panda/shadesmar
f181e2b7c4bd3ea5b84d797449285e316402fdd3
[ "MIT" ]
null
null
null
test/pubsub_test.cpp
sudo-panda/shadesmar
f181e2b7c4bd3ea5b84d797449285e316402fdd3
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2020 Dheeraj R Reddy Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ==============================================================================*/ #include <chrono> #include <iostream> #include <stdexcept> #ifdef SINGLE_HEADER #include "shadesmar.h" #else #include "shadesmar/message.h" #include "shadesmar/pubsub/serialized_publisher.h" #include "shadesmar/pubsub/serialized_subscriber.h" #include "shadesmar/stats.h" #endif const char topic[] = "benchmark_topic"; const int SECONDS = 10; const int VECTOR_SIZE = 1024 * 1024; shm::stats::Welford per_second_lag; class BenchmarkMsg : public shm::BaseMsg { public: uint8_t number{}; std::vector<uint8_t> arr; SHM_PACK(number, arr); explicit BenchmarkMsg(int n) : number(n) { for (int i = 0; i < VECTOR_SIZE; ++i) arr.push_back(n); } BenchmarkMsg() = default; }; void callback(const std::shared_ptr<BenchmarkMsg> &msg) { auto lag = static_cast<double>(shm::current_time() - msg->timestamp); per_second_lag.add(lag); for (auto i : msg->arr) { if (i != msg->number) { std::cerr << "Error on " << msg->number << std::endl; throw std::runtime_error("Subscriber data mismatch"); } } } void subscribe_loop() { std::this_thread::sleep_for(std::chrono::seconds(1)); shm::pubsub::SerializedSubscriber<BenchmarkMsg> sub(topic, callback); int seconds = 0; auto start = shm::current_time(); while (true) { sub.spin_once(); auto end = shm::current_time(); if (end - start > TIMESCALE_COUNT) { std::cout << "Lag (" << TIMESCALE_NAME << "): " << per_second_lag << std::endl; if (++seconds == SECONDS) break; start = shm::current_time(); per_second_lag.clear(); } } } void publish_loop() { shm::pubsub::SerializedPublisher<BenchmarkMsg> pub(topic, nullptr); msgpack::sbuffer buf; msgpack::pack(buf, BenchmarkMsg(VECTOR_SIZE)); std::cout << "Number of bytes = " << buf.size() << std::endl; auto start = shm::current_time(); int i = 0; while (true) { BenchmarkMsg msg(++i); msg.init_time(); pub.publish(msg); auto end = shm::current_time(); if (end - start > (SECONDS + 1) * TIMESCALE_COUNT) break; } } int main() { std::thread subscribe_thread(subscribe_loop); std::thread publish_thread(publish_loop); subscribe_thread.join(); publish_thread.join(); }
29.79646
80
0.686962
[ "vector" ]
cf2dbcc433b4aa69651ea1d652f1776c06b82c78
7,228
cxx
C++
src/Cxx/Visualization/KochSnowflake.cxx
cvandijck/VTKExamples
b6bb89414522afc1467be8a1f0089a37d0c16883
[ "Apache-2.0" ]
309
2017-05-21T09:07:19.000Z
2022-03-15T09:18:55.000Z
src/Cxx/Visualization/KochSnowflake.cxx
yijianmingliu/VTKExamples
dc8aac47c4384f9a2de9facbdd1ab3249f62ec99
[ "Apache-2.0" ]
379
2017-05-21T09:06:43.000Z
2021-03-29T20:30:50.000Z
src/Cxx/Visualization/KochSnowflake.cxx
yijianmingliu/VTKExamples
dc8aac47c4384f9a2de9facbdd1ab3249f62ec99
[ "Apache-2.0" ]
170
2017-05-17T14:47:41.000Z
2022-03-31T13:16:26.000Z
#include <vtkSmartPointer.h> #include <vtkPoints.h> #include <vtkMath.h> #include <vtkCellArray.h> #include <vtkPolyData.h> #include <vtkIntArray.h> #include <vtkPolyDataMapper.h> #include <vtkActor.h> #include <vtkRenderer.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkLookupTable.h> #include <vtkTriangle.h> #include <vtkPolyLine.h> #include <vtkCellData.h> # define VTK_CREATE(type, name) \ vtkSmartPointer<type> name = vtkSmartPointer<type>::New() # define LEVEL 6 /*----------------------------------------------------------------------------* * Koch Snowflake as vtkPolyLine * *----------------------------------------------------------------------------*/ vtkSmartPointer<vtkPolyData> as_polyline(vtkSmartPointer<vtkPoints> points, int level) { // Use the points from the previous iteration to create the points of the // next level. There is an assumption on my part that the curve is traversed // in a counterclockwise fashion. If the initial triangle above is written to // describe clockwise motion, the points will face inward instead of outward. for (int i = 0; i < level; i++) { // We're going to make the next set of points from the old one and swap // them at the end. The vtkSmartPointer will go out of scope and be // deleted. VTK_CREATE(vtkPoints, temp); double v0[3]; double v1[3]; // The first point of the previous vtkPoints is the first point of the next vtkPoints. points->GetPoint(0, v0); temp->InsertNextPoint(v0); // Iterate over "edges" in the vtkPoints for (int ii = 1; ii < points->GetNumberOfPoints(); ii++) { points->GetPoint(ii - 1, v0); points->GetPoint(ii, v1); double t = sqrt(vtkMath::Distance2BetweenPoints(v0, v1)); double nx = (v1[0] - v0[0])/t; // x-component of edge unit tangent double ny = (v1[1] - v0[1])/t; // y-component of edge unit tangent v1[0] = v0[0] + nx*t/3.; v1[1] = v0[1] + ny*t/3.; v1[2] = 0.; temp->InsertNextPoint(v1); v1[0] = v0[0] + t*(nx/2. + ny*sqrt(3.)/6.); v1[1] = v0[1] + t*(ny/2. - nx*sqrt(3.)/6.); v1[2] = 0.; temp->InsertNextPoint(v1); v1[0] = v0[0] + 2./3.*nx*t; v1[1] = v0[1] + 2./3.*ny*t; v1[2] = 0.; temp->InsertNextPoint(v1); v1[0] = v0[0] + nx*t; v1[1] = v0[1] + ny*t; v1[2] = 0.; temp->InsertNextPoint(v1); } points = temp; } // draw the outline VTK_CREATE(vtkCellArray, lines); VTK_CREATE(vtkPolyLine, pl); pl->GetPointIds()->SetNumberOfIds(points->GetNumberOfPoints()); for (int i = 0; i < points->GetNumberOfPoints(); i++) { pl->GetPointIds()->SetId(i, i); } lines->InsertNextCell(pl); // complete the polydata VTK_CREATE(vtkPolyData, polydata); polydata->SetLines(lines); polydata->SetPoints(points); return polydata; } /*----------------------------------------------------------------------------* * Koch Snowflake as collection of vtkTriangles * *----------------------------------------------------------------------------*/ void as_triangles(int start, int end, vtkCellArray *cells, int level, vtkIntArray *data) { if (end - start >= 3) { int stride = (end - start + 1)/4; VTK_CREATE(vtkTriangle, triangle); triangle->GetPointIds()->SetId(0, start + stride); triangle->GetPointIds()->SetId(1, start + 2*stride); triangle->GetPointIds()->SetId(2, start + 3*stride); cells->InsertNextCell(triangle); data->InsertNextValue(level); as_triangles(start, start + stride, cells, level + 1, data); as_triangles(start + stride, start + 2*stride, cells, level + 1, data); as_triangles(start + 2*stride, start + 3*stride, cells, level + 1, data); as_triangles(start + 3*stride, start + 4*stride, cells, level + 1, data); } } /*----------------------------------------------------------------------------* * Main Method * *----------------------------------------------------------------------------*/ int main(int, char *[]) { // Initially, set up the points to be an equilateral triangle. Note that the // first point is the same as the last point to make this a closed curve when // I create the vtkPolyLine. VTK_CREATE(vtkPoints, points); for (int i = 0; i < 4; i++) { points->InsertNextPoint(cos(2.*vtkMath::Pi()*i/3), sin(2*vtkMath::Pi()*i/3.), 0.); } vtkSmartPointer<vtkPolyData> outline_pd = as_polyline(points, LEVEL); // You have already gone through the trouble of putting the points in the // right places - so "all" you need to do now is to create polygons from the // points that are in the vtkPoints. // The points that are passed in, have an overlap of the beginning and the end. // Set this up for each of the initial sides, then call the recursive function. VTK_CREATE(vtkCellArray, triangles); int stride = outline_pd->GetPoints()->GetNumberOfPoints()/3; // The cell data will allow us to color the triangles based on the level of // the iteration of the Koch snowflake. VTK_CREATE(vtkIntArray, data); data->SetNumberOfComponents(0); data->SetName("Iteration Level"); // This is the starting triangle. VTK_CREATE(vtkTriangle, t); t->GetPointIds()->SetId(0, 0); t->GetPointIds()->SetId(1, stride); t->GetPointIds()->SetId(2, 2*stride); triangles->InsertNextCell(t); data->InsertNextValue(0); as_triangles( 0, stride, triangles, 1, data); as_triangles( stride, 2*stride, triangles, 1, data); as_triangles(2*stride, 3*stride, triangles, 1, data); VTK_CREATE(vtkPolyData, triangle_pd); triangle_pd->SetPoints(outline_pd->GetPoints()); triangle_pd->SetPolys(triangles); triangle_pd->GetCellData()->SetScalars(data); //-----------------// // rendering stuff // //-----------------// VTK_CREATE(vtkPolyDataMapper, outline_mapper); outline_mapper->SetInputData(outline_pd); VTK_CREATE(vtkLookupTable, lut); lut->SetNumberOfTableValues(256); lut->SetHueRange(0.6, 0.6); lut->SetSaturationRange(0., 1.); lut->Build(); VTK_CREATE(vtkPolyDataMapper, triangle_mapper); triangle_mapper->SetInputData(triangle_pd); triangle_mapper->SetScalarRange(0.0, LEVEL); triangle_mapper->SetLookupTable(lut); VTK_CREATE(vtkActor, outline_actor); outline_actor->SetMapper(outline_mapper); VTK_CREATE(vtkActor, triangle_actor); triangle_actor->SetMapper(triangle_mapper); VTK_CREATE(vtkRenderer, outline_ren); outline_ren->AddActor(outline_actor); outline_ren->SetViewport(0.0, 0.0, 0.5, 1.0); VTK_CREATE(vtkRenderer, triangle_ren); triangle_ren->AddActor(triangle_actor); triangle_ren->SetViewport(0.5, 0.0, 1.0, 1.0); triangle_ren->SetActiveCamera(outline_ren->GetActiveCamera()); VTK_CREATE(vtkRenderWindow, renw); renw->SetMultiSamples(0); renw->AddRenderer(outline_ren); renw->AddRenderer(triangle_ren); renw->SetSize(800, 400); VTK_CREATE(vtkRenderWindowInteractor, iren); iren->SetRenderWindow(renw); outline_ren->ResetCamera(); renw->Render(); iren->Start(); return EXIT_SUCCESS; }
33.934272
90
0.614416
[ "render" ]
cf2df0c32d542ecb47e6bd6875c7b407959148fb
1,094
cpp
C++
src/triangulate.cpp
zhearing/basic_Structure_from_Motion
110f4bca4a78c7a9357b6c2a6475ba922431677f
[ "MIT" ]
null
null
null
src/triangulate.cpp
zhearing/basic_Structure_from_Motion
110f4bca4a78c7a9357b6c2a6475ba922431677f
[ "MIT" ]
null
null
null
src/triangulate.cpp
zhearing/basic_Structure_from_Motion
110f4bca4a78c7a9357b6c2a6475ba922431677f
[ "MIT" ]
null
null
null
// Copyright 2018 Zeyu Zhong // Lincese(MIT) // Author: Zeyu Zhong // Date: 2018.5.7 #include "../src/triangulate.h" Mat triangulate::triangulate_points(vector <cv::Point2f> f1, vector <cv::Point2f> f2, float scale, Mat P2, Mat P1) { // cout<<"P1 = "<<P1<<endl; // cout<<"P2 = "<<P2<<endl; Mat J(4, 4, CV_32F, cv::Scalar(0)); Mat X(f1.size(), 4, CV_32F, cv::Scalar(0)); for (int i = 0; i < f1.size(); i++) { float x1 = f1[i].x / scale; float y1 = f1[i].y / scale; float x2 = f2[i].x / scale; float y2 = f2[i].y / scale; Mat t1 = (P1.row(2)).mul(x1) - P1.row(0); t1.copyTo(J.row(0)); Mat t2 = (P1.row(2)).mul(y1) - P1.row(1); t2.copyTo(J.row(1)); Mat t3 = (P2.row(2)).mul(x2) - P2.row(0); t3.copyTo(J.row(2)); Mat t4 = (P2.row(2)).mul(y2) - P2.row(1); t4.copyTo(J.row(3)); // Finding the solution with minimum error cv::SVD svd(J); Mat V = svd.vt.t(); Mat t = V.col(3); t = t.t(); t.copyTo(X.row(i)); } return X; }
26.682927
116
0.493601
[ "vector" ]
cf31f95a4f19fdc2d74983da5042991cd7572d45
3,654
cpp
C++
src/make_groundtruth_in_texmex.cpp
kampersanda/consistent_weighted_sampling
6fbcf372a23d778b4f346e1c181004d7a9e555c0
[ "MIT" ]
6
2019-07-22T08:53:14.000Z
2021-12-21T22:03:37.000Z
src/make_groundtruth_in_texmex.cpp
tonellotto/consistent_weighted_sampling
7d006b484ee4f3dfa048036210028fd239d2500a
[ "MIT" ]
null
null
null
src/make_groundtruth_in_texmex.cpp
tonellotto/consistent_weighted_sampling
7d006b484ee4f3dfa048036210028fd239d2500a
[ "MIT" ]
2
2021-02-17T17:09:58.000Z
2021-03-01T11:09:33.000Z
#include "cmdline.h" #include "misc.hpp" using namespace texmex_format; template <class InType> int run(const cmdline::parser& p) { auto base_fn = p.get<string>("base_fn"); auto query_fn = p.get<string>("query_fn"); auto groundtruth_fn = p.get<string>("groundtruth_fn"); auto dim = p.get<uint32_t>("dim"); auto topk = p.get<uint32_t>("topk"); auto progress = p.get<size_t>("progress"); vector<float> base_vecs = load_vecs<InType, float>(base_fn, dim); size_t N = base_vecs.size() / dim; vector<float> query_vecs = load_vecs<InType, float>(query_fn, dim); size_t M = query_vecs.size() / dim; struct id_sim_t { uint32_t id; float sim; }; vector<id_sim_t> id_sims(N); groundtruth_fn += ".txt"; ofstream ofs(groundtruth_fn); if (!ofs) { cerr << "open error: " << groundtruth_fn << endl; return 1; } ofs << M << '\n' << topk << '\n'; auto start_tp = chrono::system_clock::now(); size_t progress_point = progress; for (size_t j = 0; j < M; ++j) { if (j == progress_point) { progress_point += progress; auto cur_tp = chrono::system_clock::now(); auto dur_cnt = chrono::duration_cast<chrono::seconds>(cur_tp - start_tp).count(); cout << j << " queries processed in "; cout << dur_cnt / 3600 << "h" << dur_cnt / 60 % 60 << "m" << dur_cnt % 60 << "s..." << endl; } const float* query = &query_vecs[j * dim]; #pragma omp parallel for for (size_t i = 0; i < N; ++i) { const float* base = &base_vecs[i * dim]; id_sims[i].id = uint32_t(i); id_sims[i].sim = calc_minmax_sim(base, query, dim); } sort(id_sims.begin(), id_sims.end(), [](const id_sim_t& a, const id_sim_t& b) { if (a.sim != b.sim) { return a.sim > b.sim; } return a.id < b.id; }); for (uint32_t i = 0; i < topk; ++i) { ofs << id_sims[i].id << ':' << id_sims[i].sim << ','; } ofs << '\n'; } auto cur_tp = chrono::system_clock::now(); auto dur_cnt = chrono::duration_cast<chrono::seconds>(cur_tp - start_tp).count(); cout << "Completed!! --> " << M << " queries processed in "; cout << dur_cnt / 3600 << "h" << dur_cnt / 60 % 60 << "m" << dur_cnt % 60 << "s!!" << endl; cout << "Output " << groundtruth_fn << endl; return 0; } int main(int argc, char** argv) { ios::sync_with_stdio(false); cout << "num threads: " << omp_get_max_threads() << endl; cmdline::parser p; p.add<string>("base_fn", 'i', "input file name of database vectors (in fvecs/bvecs format)", true); p.add<string>("query_fn", 'q', "input file name of query vectors (in fvecs/bvecs format)", true); p.add<string>("groundtruth_fn", 'o', "output file name of the groundtruth", true); p.add<uint32_t>("dim", 'd', "dimension of the input data", true); p.add<uint32_t>("topk", 'k', "k-nearest neighbors", false, 100); p.add<size_t>("progress", 'p', "step of printing progress", false, 100); p.parse_check(argc, argv); auto base_fn = p.get<string>("base_fn"); auto query_fn = p.get<string>("query_fn"); auto base_ext = get_ext(base_fn); auto query_ext = get_ext(query_fn); if (base_ext != query_ext) { cerr << "error: base_ext != query_ext" << endl; return 1; } if (base_ext == "fvecs") { return run<float>(p); } if (base_ext == "bvecs") { return run<uint8_t>(p); } cerr << "error: invalid extension" << endl; return 1; }
32.625
104
0.559661
[ "vector" ]
cf3dc9ea693220f09be5c153dffb9d36f1a02a3c
2,920
cpp
C++
ScrapEngine/ScrapEngine/Engine/Rendering/RenderPass/GuiRenderPass/GuiRenderPass.cpp
alundb/ScrapEngine
755416a2b2b072a8713f5a6b669f2379608bbab0
[ "MIT" ]
118
2019-10-12T01:29:07.000Z
2022-02-22T08:08:18.000Z
ScrapEngine/ScrapEngine/Engine/Rendering/RenderPass/GuiRenderPass/GuiRenderPass.cpp
alundb/ScrapEngine
755416a2b2b072a8713f5a6b669f2379608bbab0
[ "MIT" ]
15
2019-09-02T16:51:39.000Z
2021-02-21T20:03:58.000Z
ScrapEngine/ScrapEngine/Engine/Rendering/RenderPass/GuiRenderPass/GuiRenderPass.cpp
alundb/ScrapEngine
755416a2b2b072a8713f5a6b669f2379608bbab0
[ "MIT" ]
11
2019-10-21T15:53:23.000Z
2022-02-20T20:56:39.000Z
#include <Engine/Rendering/RenderPass/GuiRenderPass/GuiRenderPass.h> #include <array> #include <Engine/Rendering/DepthResources/VulkanDepthResources.h> #include <Engine/Rendering/Device/VulkanDevice.h> #include <Engine/Debug/DebugLog.h> //Class ScrapEngine::Render::GuiRenderPass::GuiRenderPass(const vk::Format& swap_chain_image_format, const vk::SampleCountFlagBits msaa_samples) { const vk::AttachmentDescription color_attachment( vk::AttachmentDescriptionFlags(), swap_chain_image_format, msaa_samples, vk::AttachmentLoadOp::eLoad, vk::AttachmentStoreOp::eStore, vk::AttachmentLoadOp::eDontCare, vk::AttachmentStoreOp::eDontCare, vk::ImageLayout::eColorAttachmentOptimal, vk::ImageLayout::eColorAttachmentOptimal ); const vk::AttachmentDescription depth_attachment( vk::AttachmentDescriptionFlags(), VulkanDepthResources::find_depth_format(), msaa_samples, vk::AttachmentLoadOp::eDontCare, vk::AttachmentStoreOp::eDontCare, vk::AttachmentLoadOp::eDontCare, vk::AttachmentStoreOp::eDontCare, vk::ImageLayout::eUndefined, vk::ImageLayout::eDepthStencilAttachmentOptimal ); const vk::AttachmentDescription color_attachment_resolve( vk::AttachmentDescriptionFlags(), swap_chain_image_format, vk::SampleCountFlagBits::e1, vk::AttachmentLoadOp::eDontCare, vk::AttachmentStoreOp::eStore, vk::AttachmentLoadOp::eDontCare, vk::AttachmentStoreOp::eDontCare, vk::ImageLayout::eUndefined, vk::ImageLayout::ePresentSrcKHR ); vk::AttachmentReference color_attachment_ref( 0, vk::ImageLayout::eColorAttachmentOptimal ); vk::AttachmentReference depth_attachment_ref( 1, vk::ImageLayout::eDepthStencilAttachmentOptimal ); vk::AttachmentReference color_attachment_resolve_ref( 2, vk::ImageLayout::eColorAttachmentOptimal ); vk::SubpassDescription subpass( vk::SubpassDescriptionFlags(), vk::PipelineBindPoint::eGraphics, 0, nullptr, 1, &color_attachment_ref, &color_attachment_resolve_ref, &depth_attachment_ref ); vk::SubpassDependency dependency( VK_SUBPASS_EXTERNAL, 0, vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::PipelineStageFlagBits::eColorAttachmentOutput, vk::AccessFlags(), vk::AccessFlagBits::eColorAttachmentRead | vk::AccessFlagBits::eColorAttachmentWrite ); std::array<vk::AttachmentDescription, 3> attachments = { color_attachment, depth_attachment, color_attachment_resolve }; vk::RenderPassCreateInfo render_pass_info( vk::RenderPassCreateFlags(), static_cast<uint32_t>(attachments.size()), attachments.data(), 1, &subpass, 1, &dependency ); const vk::Result result = VulkanDevice::get_instance()->get_logical_device()->createRenderPass(&render_pass_info, nullptr, &render_pass_); if (result != vk::Result::eSuccess) { Debug::DebugLog::fatal_error(result, "VulkanRenderPass: Failed to create render pass!"); } }
28.627451
139
0.768836
[ "render" ]
cf3e8f7617611cd57b857c6fe2f3050cf9f0d175
2,445
cpp
C++
Sources/x10/xla_tensor/ops/adaptive_avg_pool2d.cpp
Shashi456/swift-apis
a89e74542e450a00aefcbcdea44ddb235a2d9c6f
[ "Apache-2.0" ]
null
null
null
Sources/x10/xla_tensor/ops/adaptive_avg_pool2d.cpp
Shashi456/swift-apis
a89e74542e450a00aefcbcdea44ddb235a2d9c6f
[ "Apache-2.0" ]
null
null
null
Sources/x10/xla_tensor/ops/adaptive_avg_pool2d.cpp
Shashi456/swift-apis
a89e74542e450a00aefcbcdea44ddb235a2d9c6f
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 TensorFlow Authors // // 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 "tensorflow/compiler/tf2xla/xla_tensor/ops/adaptive_avg_pool2d.h" #include "tensorflow/compiler/xla/xla_client/debug_macros.h" #include "tensorflow/compiler/xla/xla_client/util.h" #include "tensorflow/compiler/tf2xla/xla_tensor/lowering_context.h" #include "tensorflow/compiler/tf2xla/xla_tensor/ops/infer_output_shape.h" #include "tensorflow/compiler/tf2xla/xla_tensor/pooling.h" namespace swift_xla { namespace ir { namespace ops { namespace { xla::Shape NodeOutputShape(const Value& input, absl::Span<const xla::int64> output_size) { auto lower_for_shape_fn = [output_size](absl::Span<const xla::XlaOp> operands) -> xla::XlaOp { XLA_CHECK_EQ(operands.size(), 1); return BuildAdaptiveAvgPool2d(operands[0], output_size); }; return InferOutputShape({input.shape()}, lower_for_shape_fn); } } // namespace AdaptiveAvgPool2d::AdaptiveAvgPool2d(const Value& input, std::vector<xla::int64> output_size) : Node(ir::OpKind(at::aten::adaptive_avg_pool2d), {input}, [&]() { return NodeOutputShape(input, output_size); }, /*num_outputs=*/1, xla::util::MHash(output_size)), output_size_(std::move(output_size)) {} NodePtr AdaptiveAvgPool2d::Clone(OpList operands) const { return MakeNode<AdaptiveAvgPool2d>(operands.at(0), output_size_); } XlaOpVector AdaptiveAvgPool2d::Lower(LoweringContext* loctx) const { xla::XlaOp input = loctx->GetOutputOp(operand(0)); xla::XlaOp output = BuildAdaptiveAvgPool2d(input, output_size_); return ReturnOp(output, loctx); } std::string AdaptiveAvgPool2d::ToString() const { std::stringstream ss; ss << Node::ToString() << ", output_size=[" << absl::StrJoin(output_size_, ", ") << "]"; return ss.str(); } } // namespace ops } // namespace ir } // namespace swift_xla
36.492537
75
0.714928
[ "shape", "vector" ]
cf460aac2f89401795c86b6aa3521486c9585bff
8,297
cpp
C++
toynet/examples/diff2/diff2.t.cpp
pbrunelle/w2v
2ae0d95283c67ae5e27823a81edf05821280dae0
[ "MIT" ]
null
null
null
toynet/examples/diff2/diff2.t.cpp
pbrunelle/w2v
2ae0d95283c67ae5e27823a81edf05821280dae0
[ "MIT" ]
2
2020-11-28T18:42:15.000Z
2020-11-29T23:02:51.000Z
toynet/examples/diff2/diff2.t.cpp
pbrunelle/toynet
2ae0d95283c67ae5e27823a81edf05821280dae0
[ "MIT" ]
null
null
null
#include <toynet/examples/diff2/diff2.h> #include <toynet/stlio.h> #include <toynet/ublas/io.h> #include <toynet/ublas/convert.h> #include <iostream> #include <boost/test/unit_test.hpp> using namespace toynet; template<class T> std::string print(const T& v) { std::ostringstream oss; oss << v; return oss.str(); } BOOST_AUTO_TEST_CASE(test_GlorotBengio2010Initializer_empty) { diff2::GlorotBengio2010Initializer initializer; std::vector<diff2::Tensor2D> W{ diff2::Tensor2D(5, 1), diff2::Tensor2D(580, 20) }; initializer.initialize(W); for (int i = 0; i < W[0].size1(); ++i) for (int j = 0; j < W[0].size2(); ++j) BOOST_CHECK(W[0](i, j) <= 1.0 && W[0](i, j) >= -1.0); for (int i = 0; i < W[1].size1(); ++i) for (int j = 0; j < W[1].size2(); ++j) BOOST_CHECK(W[1](i, j) <= 0.1 && W[1](i, j) >= -0.1); } BOOST_AUTO_TEST_CASE(test_Network) { diff2::Network network(1, 3, 6, 2); BOOST_CHECK_EQUAL(1, network.hidden); BOOST_CHECK_EQUAL(3, network.width); BOOST_CHECK_EQUAL(6, network.inputs); BOOST_CHECK_EQUAL(2, network.outputs); BOOST_REQUIRE_EQUAL(2, network.W.size()); // 2 matrices: input -> hidden1, hidden1 -> output BOOST_CHECK_EQUAL(3, network.W[0].size1()); // 3 units per hidden layer BOOST_CHECK_EQUAL(6, network.W[0].size2()); // 6 units in input layer BOOST_CHECK_EQUAL(2, network.W[1].size1()); // 2 units in output layer BOOST_CHECK_EQUAL(3, network.W[1].size2()); // 3 units per hidden layer } BOOST_AUTO_TEST_CASE(test_Forward) { diff2::FixedWeightInitializer initializer; diff2::Network network(1, 2, 2, 1, &initializer); diff2::Workspace workspace = diff2::build_workspace(network); BOOST_CHECK_EQUAL("[[0, 0], [0, 0], [0]]", print(workspace.A)); network.forward(workspace, convert({4.0, 3.0})); BOOST_CHECK_EQUAL("[[4, 3], [-0.8, -0.1], [-0.14]]", print(workspace.A)); network.forward(workspace, convert({3.0, 4.0})); BOOST_CHECK_EQUAL("[[3, 4], [-0.6, 0.1], [-0.14]]", print(workspace.A)); } BOOST_AUTO_TEST_CASE(test_Workspace) { diff2::Network network(1, 2, 3, 1); diff2::Workspace workspace = diff2::build_workspace(network); BOOST_CHECK(!workspace.dA); BOOST_CHECK(!workspace.dW); BOOST_CHECK(!workspace.v); BOOST_REQUIRE_EQUAL(3, workspace.A.size()); BOOST_CHECK_EQUAL(3, workspace.A[0].size()); BOOST_CHECK_EQUAL(2, workspace.A[1].size()); BOOST_CHECK_EQUAL(1, workspace.A[2].size()); BOOST_CHECK_EQUAL(0.0, workspace.loss); } BOOST_AUTO_TEST_CASE(test_GradientOptimizer) { diff2::FixedWeightInitializer initializer; diff2::Network network(1, 2, 2, 1, &initializer); diff2::GradientOptimizer opt(0.1); MSELoss loss; diff2::Workspace workspace = diff2::build_workspace(network, opt); BOOST_CHECK_EQUAL("[[[-0.2, 0], [-0.1, 0.1]], [[0.2, -0.2]]]", print(network.W)); network.forward(workspace, convert({4.0, 3.0})); BOOST_CHECK_EQUAL("[[4, 3], [-0.8, -0.1], [-0.14]]", print(workspace.A)); opt.compute_gradients(network, workspace, loss, convert({1.0})); BOOST_CHECK_EQUAL("[[[-1.824, -1.368], [1.824, 1.368]], [[1.824, 0.228]]]", print(*workspace.dW)); BOOST_CHECK_EQUAL("[[0.0456, 0.0456], [-0.456, 0.456], [-2.28]]", print(*workspace.dA)); BOOST_CHECK_CLOSE(1.2996, workspace.loss, 1e-6); opt.update_weights(1, network, workspace); BOOST_CHECK_EQUAL("[[[-0.0176, 0.1368], [-0.2824, -0.0368]], [[0.0176, -0.2228]]]", print(network.W)); } // If the learning rate is too high, training will quickly diverge BOOST_AUTO_TEST_CASE(test_GradientOptimizer_divergence) { const double lr = 0.5; const diff2::Tensor1D x = convert({4.0, 3.0}); const diff2::Tensor1D y = convert({1.0}); diff2::FixedWeightInitializer initializer; diff2::Network network(1, 2, 2, 1, &initializer); diff2::GradientOptimizer opt(lr); MSELoss loss; diff2::Workspace workspace = diff2::build_workspace(network, opt); // First epoch network.forward(workspace, x); opt.compute_gradients(network, workspace, loss, y); opt.update_weights(1, network, workspace); BOOST_CHECK_EQUAL("[[4, 3], [-0.8, -0.1], [-0.14]]", print(workspace.A)); BOOST_CHECK_EQUAL("[[[0.712, 0.684], [-1.012, -0.584]], [[-0.712, -0.314]]]", print(network.W)); BOOST_CHECK_CLOSE(1.2996, workspace.loss, 1e-6); // Second epoch network.forward(workspace, x); opt.compute_gradients(network, workspace, loss, y); opt.update_weights(2, network, workspace); BOOST_CHECK_EQUAL("[[4, 3], [4.9, -5.8], [-1.6676]]", print(workspace.A)); BOOST_CHECK_EQUAL("[[1.00929, 1.61994], [3.79866, 1.67525], [-5.3352]]", print(*workspace.dA)); BOOST_CHECK_EQUAL("[[[15.1946, 11.396], [6.70101, 5.02576]], [[-26.1425, 30.9442]]]", print(*workspace.dW)); BOOST_CHECK_EQUAL("[[[-6.88532, -5.01399], [-4.36251, -3.09688]], [[12.3592, -15.7861]]]", print(network.W)); BOOST_CHECK_CLOSE(7.11608976, workspace.loss, 1e-6); // Third epoch (forward and loss) network.forward(workspace, x); opt.compute_gradients(network, workspace, loss, y); BOOST_CHECK_EQUAL("[[4, 3], [-42.5833, -26.7407], [-104.167]]", print(workspace.A)); BOOST_CHECK_CLOSE(11060.0515, workspace.loss, 1e-6); } BOOST_AUTO_TEST_CASE(test_MomentumOptimizer) { const double lr = 0.5; const double alpha = 0.8; const diff2::Tensor1D x = convert({4.0, 3.0}); const diff2::Tensor1D y = convert({1.0}); diff2::FixedWeightInitializer initializer; diff2::Network network(1, 2, 2, 1, &initializer); diff2::MomentumOptimizer opt(lr, alpha); MSELoss loss; diff2::Workspace workspace = diff2::build_workspace(network, opt); BOOST_REQUIRE(workspace.v); // First epoch -- same as GradientOptimizer because `v` is initially 0 network.forward(workspace, x); opt.compute_gradients(network, workspace, loss, y); opt.update_weights(1, network, workspace); BOOST_CHECK_EQUAL("[[4, 3], [-0.8, -0.1], [-0.14]]", print(workspace.A)); BOOST_CHECK_EQUAL("[[[-1.824, -1.368], [1.824, 1.368]], [[1.824, 0.228]]]", print(*workspace.dW)); BOOST_CHECK_EQUAL("[[[0.912, 0.684], [-0.912, -0.684]], [[-0.912, -0.114]]]", print(*workspace.v)); BOOST_CHECK_EQUAL("[[[0.712, 0.684], [-1.012, -0.584]], [[-0.712, -0.314]]]", print(network.W)); BOOST_CHECK_CLOSE(1.2996, workspace.loss, 1e-6); // Second epoch network.forward(workspace, x); opt.compute_gradients(network, workspace, loss, y); opt.update_weights(2, network, workspace); BOOST_CHECK_EQUAL("[[[15.1946, 11.396], [6.70101, 5.02576]], [[-26.1425, 30.9442]]]", print(*workspace.dW)); BOOST_CHECK_EQUAL("[[[-6.86772, -5.15079], [-4.08011, -3.06008]], [[12.3416, -15.5633]]]", print(*workspace.v)); BOOST_CHECK_EQUAL("[[[-6.15572, -4.46679], [-5.09211, -3.64408]], [[11.6296, -15.8773]]]", print(network.W)); BOOST_CHECK_CLOSE(7.11608976, workspace.loss, 1e-6); // Third epoch (forward and loss) network.forward(workspace, x); opt.compute_gradients(network, workspace, loss, y); BOOST_CHECK_EQUAL("[[4, 3], [-38.0233, -31.3007], [54.7723]]", print(workspace.A)); BOOST_CHECK_CLOSE(2891.45863, workspace.loss, 1e-6); } void help_test_Trainer_train_1_example(const diff2::Optimizer& opt) { const std::vector<diff2::Tensor1D> x{convert({4.0, 3.0})}; const std::vector<diff2::Tensor1D> y{convert({1.0})}; diff2::FixedWeightInitializer initializer; diff2::Network network(1, 2, 2, 1, &initializer); MSELoss loss; diff2::Trainer trainer(network, loss, opt); for (int e = 1; e <= 10; ++e) { trainer.train(e, x, y); // std::cout << e << " " << trainer.workspace.loss << " " << network.predict(x[0]) << std::endl; } BOOST_CHECK(trainer.workspace.loss < 1e-6); BOOST_CHECK_CLOSE(network.predict(x[0])[0], 1.0, 1e-6); } BOOST_AUTO_TEST_CASE(test_Trainer_train_1_example_GradientOptimizer) { help_test_Trainer_train_1_example(diff2::GradientOptimizer(0.05)); } #if 0 // For this problem, momentum gives worse convergence than gradient BOOST_AUTO_TEST_CASE(test_Trainer_train_1_example_MomentumOptimizer) { help_test_Trainer_train_1_example(diff2::MomentumOptimizer(0.02, 0.8)); } #endif
40.871921
116
0.650356
[ "vector" ]
cf48004798ff9eace4400d1f8250b8ccbee9f7fb
1,452
hh
C++
src/misc/gradient.hh
jhidding/nerve
91426397f1767c0981386244508faccc7bc5836e
[ "Apache-2.0" ]
null
null
null
src/misc/gradient.hh
jhidding/nerve
91426397f1767c0981386244508faccc7bc5836e
[ "Apache-2.0" ]
null
null
null
src/misc/gradient.hh
jhidding/nerve
91426397f1767c0981386244508faccc7bc5836e
[ "Apache-2.0" ]
null
null
null
#pragma once #include "../base/mvector.hh" #include "../base/boxconfig.hh" namespace Misc { template <unsigned R> class Gradient { typedef System::mVector<double, R> Vector; System::Array<double> data; System::ptr<System::cVector<R>> b; public: typedef Vector value_type; Gradient(System::ptr<System::BoxConfig<R>> box_, System::Array<double> data_): data(data_), b(new System::cVector<R>(box_->bits())) {} inline double fdi(size_t i, unsigned k) const { return data[b->sub(i, b->dx2_i[k])] / 12. - 2. * data[b->sub(i, b->dx_i[k])] / 3. + 2. * data[b->add(i, b->dx_i[k])] / 3. - data[b->add(i, b->dx2_i[k])] / 12.; } inline Vector grad(size_t i) const { Vector v; for (unsigned k = 0; k < R; ++k) v[k] = fdi(i, k); return v; } bool root_potentially_within_cell(size_t i) const { // true if within the cell all components of // the gradient change sign. std::vector<bool> test(R, false); int cnt = 0; Vector v1 = grad(i); for (auto &dx : b->sq_i) { Vector v2 = grad(b->add(i, dx)); for (unsigned k = 0; k < R; ++k) { if (v1[k] * v2[k] < 0. and not test[k]) { test[k] = true; ++cnt; } if (cnt == R) return true; } } return false; } Vector find_root(size_t i) const { return Vector(); } Vector operator[](size_t i) const { return grad(i); } }; }
19.890411
85
0.550275
[ "vector" ]
cf48f57b0a84c1c5ce7702bdc37867226981126f
1,900
cc
C++
caffe2/operators/rowmul_op.cc
brooks-anderson/pytorch
dd928097938b6368fc7e2dc67721550d50ab08ea
[ "Intel" ]
7
2021-05-29T16:31:51.000Z
2022-02-21T18:52:25.000Z
caffe2/operators/rowmul_op.cc
stas00/pytorch
6a085648d81ce88ff59d6d1438fdb3707a0d6fb7
[ "Intel" ]
1
2021-03-25T13:42:15.000Z
2021-03-25T13:42:15.000Z
caffe2/operators/rowmul_op.cc
stas00/pytorch
6a085648d81ce88ff59d6d1438fdb3707a0d6fb7
[ "Intel" ]
1
2021-12-26T23:20:06.000Z
2021-12-26T23:20:06.000Z
#include "caffe2/operators/rowmul_op.h" namespace caffe2 { namespace { // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) REGISTER_CPU_OPERATOR(ReduceTailSum, ReduceTailSumOp<float, CPUContext>); // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) REGISTER_CPU_OPERATOR(RowMul, RowMulOp<float, CPUContext>); // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) OPERATOR_SCHEMA(ReduceTailSum) .NumInputs(1, 1) .NumOutputs(1) .SetDoc(R"DOC( Reduce the tailing dimensions )DOC") .Input(0, "mat", "The matrix") .Output(0, "output", "Output"); // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) OPERATOR_SCHEMA(RowMul) .NumInputs(2, 2) .NumOutputs(1) .SetDoc(R"DOC( Given a matrix A and column vector w, the output is the multiplication of row i of A and element i of w, e.g. C[i][j] = A[i][j] * w[i]. This operator should be deprecated when the gradient operator of Mul with broadcast is implemented. )DOC") .Input(0, "mat", "The matrix") .Input(1, "w", "The column vector") .Output(0, "output", "Output"); class GetRowMulGradient : public GradientMakerBase { using GradientMakerBase::GradientMakerBase; vector<OperatorDef> GetGradientDefs() override { return vector<OperatorDef>{ CreateOperatorDef( "RowMul", "", vector<string>{GO(0), I(1)}, vector<string>{GI(0)}), CreateOperatorDef( "Mul", "", vector<string>{GO(0), I(0)}, vector<string>{GI(1) + "before_aggregate"}), CreateOperatorDef( "ReduceTailSum", "", vector<string>{GI(1) + "before_aggregate"}, vector<string>{GI(1)})}; } }; // NOLINTNEXTLINE(cppcoreguidelines-avoid-non-const-global-variables) REGISTER_GRADIENT(RowMul, GetRowMulGradient); } // namespace } // namespace caffe2
32.758621
79
0.678947
[ "vector" ]
cf4d885f8c5221e2517fe0d5d6c1c87609ad3c82
2,194
cpp
C++
Gfg/C++/Find the number of islands.cpp
abdzitter/Daily-Coding-DS-ALGO-Practice
26ddbf7a3673608039a07d26d812fce31b69871a
[ "MIT" ]
289
2021-05-15T22:56:03.000Z
2022-03-28T23:13:25.000Z
Gfg/C++/Find the number of islands.cpp
abdzitter/Daily-Coding-DS-ALGO-Practice
26ddbf7a3673608039a07d26d812fce31b69871a
[ "MIT" ]
1,812
2021-05-09T13:49:58.000Z
2022-01-15T19:27:17.000Z
Gfg/C++/Find the number of islands.cpp
abdzitter/Daily-Coding-DS-ALGO-Practice
26ddbf7a3673608039a07d26d812fce31b69871a
[ "MIT" ]
663
2021-05-09T16:57:58.000Z
2022-03-27T14:15:07.000Z
//Link to solution: //https://practice.geeksforgeeks.org/problems/find-the-number-of-islands/1 /*Algorithm: We will use DFS and check all 8 adjacent grid block. Number of times DFS will be called is equal to number of islands. */ #include<bits/stdc++.h> using namespace std; class Solution { public: void dfs(int i,int j,vector<vector<char>>grid,int v[501][501],int m,int n) { if(i<0 || j<0 || i>=m || j>=n) return; if(int(grid[i][j]-'0')==0) return; if(!v[i][j]) // checking all 8 adjacent block { v[i][j]=1; //marking visited dfs(i+1,j,grid,v,m,n); dfs(i-1,j,grid,v,m,n); dfs(i,j+1,grid,v,m,n); dfs(i,j-1,grid,v,m,n); dfs(i+1,j+1,grid,v,m,n); dfs(i-1,j-1,grid,v,m,n); dfs(i+1,j-1,grid,v,m,n); dfs(i-1,j+1,grid,v,m,n); } } //Function to find the number of islands. int numIslands(vector<vector<char>>& grid) { int i,j; int m=grid.size(),n=grid[0].size(); int v[501][501]; for(i=0;i<m;i++) for(j=0;j<n;j++) v[i][j]=0; //marking unvisited int ans=0; for(i=0;i<m;i++) for(j=0;j<n;j++) { if(!v[i][j] && int(grid[i][j]='0')==1) { ans++; dfs(i,j,grid,v,m,n); } } return ans; } }; // { Driver Code Starts. int main(){ int tc; cin >> tc; while(tc--){ int n, m; cin >> n >> m; vector<vector<char>>grid(n, vector<char>(m, '#')); for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ cin >> grid[i][j]; } } Solution obj; int ans = obj.numIslands(grid); cout << ans <<'\n'; } return 0; } // } Driver Code Ends /* Input: grid = {{0,1,1,1,0,0,0},{0,0,1,1,0,1,0}} Output: 2 Expanation: The grid is- 0 1 1 1 0 0 0 0 0 1 1 0 1 0 There are two islands one is colored in blue and other in orange. */
21.722772
119
0.43938
[ "vector" ]
cf4ea1711b8a68ef5c0db4fe01626dc409ca5aae
25,701
cpp
C++
designer/lib/shared/qdesigner_utils.cpp
liyuzhao/QWidgetDemo
a056894da7b7385e37a523ea4825cea48c82d297
[ "MulanPSL-1.0" ]
3,095
2019-10-11T03:00:33.000Z
2022-03-31T08:15:13.000Z
designer/lib/shared/qdesigner_utils.cpp
liyuzhao/QWidgetDemo
a056894da7b7385e37a523ea4825cea48c82d297
[ "MulanPSL-1.0" ]
28
2019-11-12T07:24:06.000Z
2022-02-28T02:04:48.000Z
designer/lib/shared/qdesigner_utils.cpp
liyuzhao/QWidgetDemo
a056894da7b7385e37a523ea4825cea48c82d297
[ "MulanPSL-1.0" ]
1,023
2019-10-09T12:54:07.000Z
2022-03-30T04:02:07.000Z
/**************************************************************************** ** ** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the Qt Designer of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** Commercial Usage ** Licensees holding valid Qt Commercial licenses may use this file in ** accordance with the Qt Commercial License Agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Nokia. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 as published by the Free Software ** Foundation and appearing in the file LICENSE.LGPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU Lesser General Public License version 2.1 requirements ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU ** General Public License version 3.0 as published by the Free Software ** Foundation and appearing in the file LICENSE.GPL included in the ** packaging of this file. Please review the following information to ** ensure the GNU General Public License version 3.0 requirements will be ** met: http://www.gnu.org/copyleft/gpl.html. ** ** If you have questions regarding the use of this file, please contact ** Nokia at qt-info@nokia.com. ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qdesigner_utils_p.h" #include "qdesigner_propertycommand_p.h" #include "abstractformbuilder.h" #include "formwindowbase_p.h" #include <QtDesigner/QDesignerFormEditorInterface> #include <QtDesigner/QDesignerFormWindowInterface> #include <QtDesigner/QDesignerIconCacheInterface> #include <QtDesigner/QDesignerResourceBrowserInterface> #include <QtDesigner/QDesignerLanguageExtension> #include <QtDesigner/QDesignerTaskMenuExtension> #include <QtDesigner/QExtensionManager> #include <QtGui/QIcon> #include <QtGui/QPixmap> #include <QtCore/QDir> #include <QtGui/QApplication> #include <QtCore/QProcess> #include <QtCore/QLibraryInfo> #include <QtCore/QDebug> #include <QtCore/QQueue> #include <QtGui/QListWidget> #include <QtGui/QTreeWidget> #include <QtGui/QTableWidget> #include <QtGui/QComboBox> QT_BEGIN_NAMESPACE namespace qdesigner_internal { QDESIGNER_SHARED_EXPORT void designerWarning(const QString &message) { qWarning("Designer: %s", qPrintable(message)); } void reloadTreeItem(DesignerIconCache *iconCache, QTreeWidgetItem *item) { if (!item) return; for (int c = 0; c < item->columnCount(); c++) { const QVariant v = item->data(c, Qt::DecorationPropertyRole); if (qVariantCanConvert<PropertySheetIconValue>(v)) item->setIcon(c, iconCache->icon(qVariantValue<PropertySheetIconValue>(v))); } } void reloadListItem(DesignerIconCache *iconCache, QListWidgetItem *item) { if (!item) return; const QVariant v = item->data(Qt::DecorationPropertyRole); if (qVariantCanConvert<PropertySheetIconValue>(v)) item->setIcon(iconCache->icon(qVariantValue<PropertySheetIconValue>(v))); } void reloadTableItem(DesignerIconCache *iconCache, QTableWidgetItem *item) { if (!item) return; const QVariant v = item->data(Qt::DecorationPropertyRole); if (qVariantCanConvert<PropertySheetIconValue>(v)) item->setIcon(iconCache->icon(qVariantValue<PropertySheetIconValue>(v))); } void reloadIconResources(DesignerIconCache *iconCache, QObject *object) { if (QListWidget *listWidget = qobject_cast<QListWidget *>(object)) { for (int i = 0; i < listWidget->count(); i++) reloadListItem(iconCache, listWidget->item(i)); } else if (QComboBox *comboBox = qobject_cast<QComboBox *>(object)) { for (int i = 0; i < comboBox->count(); i++) { const QVariant v = comboBox->itemData(i, Qt::DecorationPropertyRole); if (qVariantCanConvert<PropertySheetIconValue>(v)) { QIcon icon = iconCache->icon(qVariantValue<PropertySheetIconValue>(v)); comboBox->setItemIcon(i, icon); comboBox->setItemData(i, icon); } } } else if (QTreeWidget *treeWidget = qobject_cast<QTreeWidget *>(object)) { reloadTreeItem(iconCache, treeWidget->headerItem()); QQueue<QTreeWidgetItem *> itemsQueue; for (int i = 0; i < treeWidget->topLevelItemCount(); i++) itemsQueue.enqueue(treeWidget->topLevelItem(i)); while (!itemsQueue.isEmpty()) { QTreeWidgetItem *item = itemsQueue.dequeue(); for (int i = 0; i < item->childCount(); i++) itemsQueue.enqueue(item->child(i)); reloadTreeItem(iconCache, item); } } else if (QTableWidget *tableWidget = qobject_cast<QTableWidget *>(object)) { const int columnCount = tableWidget->columnCount(); const int rowCount = tableWidget->rowCount(); for (int c = 0; c < columnCount; c++) reloadTableItem(iconCache, tableWidget->horizontalHeaderItem(c)); for (int r = 0; r < rowCount; r++) reloadTableItem(iconCache, tableWidget->verticalHeaderItem(r)); for (int c = 0; c < columnCount; c++) for (int r = 0; r < rowCount; r++) reloadTableItem(iconCache, tableWidget->item(r, c)); } } // ------------- DesignerMetaEnum DesignerMetaEnum::DesignerMetaEnum(const QString &name, const QString &scope, const QString &separator) : MetaEnum<int>(name, scope, separator) { } QString DesignerMetaEnum::toString(int value, SerializationMode sm, bool *ok) const { // find value bool valueOk; const QString item = valueToKey(value, &valueOk); if (ok) *ok = valueOk; if (!valueOk || sm == NameOnly) return item; QString qualifiedItem; appendQualifiedName(item, qualifiedItem); return qualifiedItem; } QString DesignerMetaEnum::messageToStringFailed(int value) const { return QCoreApplication::translate("DesignerMetaEnum", "%1 is not a valid enumeration value of '%2'.").arg(value).arg(name()); } QString DesignerMetaEnum::messageParseFailed(const QString &s) const { return QCoreApplication::translate("DesignerMetaEnum", "'%1' could not be converted to an enumeration value of type '%2'.").arg(s).arg(name()); } // -------------- DesignerMetaFlags DesignerMetaFlags::DesignerMetaFlags(const QString &name, const QString &scope, const QString &separator) : MetaEnum<uint>(name, scope, separator) { } QStringList DesignerMetaFlags::flags(int ivalue) const { typedef MetaEnum<uint>::KeyToValueMap::const_iterator KeyToValueMapIterator; QStringList rc; const uint v = static_cast<uint>(ivalue); const KeyToValueMapIterator cend = keyToValueMap().constEnd(); for (KeyToValueMapIterator it = keyToValueMap().constBegin();it != cend; ++it ) { const uint itemValue = it.value(); // Check for equality first as flag values can be 0 or -1, too. Takes preference over a bitwise flag if (v == itemValue) { rc.clear(); rc.push_back(it.key()); return rc; } // Do not add 0-flags (None-flags) if (itemValue) if ((v & itemValue) == itemValue) rc.push_back(it.key()); } return rc; } QString DesignerMetaFlags::toString(int value, SerializationMode sm) const { const QStringList flagIds = flags(value); if (flagIds.empty()) return QString(); const QChar delimiter = QLatin1Char('|'); QString rc; const QStringList::const_iterator cend = flagIds.constEnd(); for (QStringList::const_iterator it = flagIds.constBegin(); it != cend; ++it) { if (!rc.isEmpty()) rc += delimiter ; if (sm == FullyQualified) appendQualifiedName(*it, rc); else rc += *it; } return rc; } int DesignerMetaFlags::parseFlags(const QString &s, bool *ok) const { if (s.isEmpty()) { if (ok) *ok = true; return 0; } uint flags = 0; bool valueOk = true; QStringList keys = s.split(QString(QLatin1Char('|'))); const QStringList::iterator cend = keys.end(); for (QStringList::iterator it = keys.begin(); it != cend; ++it) { const uint flagValue = keyToValue(*it, &valueOk); if (!valueOk) { flags = 0; break; } flags |= flagValue; } if (ok) *ok = valueOk; return static_cast<int>(flags); } QString DesignerMetaFlags::messageParseFailed(const QString &s) const { return QCoreApplication::translate("DesignerMetaFlags", "'%1' could not be converted to a flag value of type '%2'.").arg(s).arg(name()); } // ---------- PropertySheetEnumValue PropertySheetEnumValue::PropertySheetEnumValue(int v, const DesignerMetaEnum &me) : value(v), metaEnum(me) { } PropertySheetEnumValue::PropertySheetEnumValue() : value(0) { } // ---------------- PropertySheetFlagValue PropertySheetFlagValue::PropertySheetFlagValue(int v, const DesignerMetaFlags &mf) : value(v), metaFlags(mf) { } PropertySheetFlagValue::PropertySheetFlagValue() : value(0) { } // ---------------- PropertySheetPixmapValue PropertySheetPixmapValue::PropertySheetPixmapValue(const QString &path) : m_path(path) { } PropertySheetPixmapValue::PropertySheetPixmapValue() { } PropertySheetPixmapValue::PixmapSource PropertySheetPixmapValue::getPixmapSource(QDesignerFormEditorInterface *core, const QString & path) { if (const QDesignerLanguageExtension *lang = qt_extension<QDesignerLanguageExtension *>(core->extensionManager(), core)) return lang->isLanguageResource(path) ? LanguageResourcePixmap : FilePixmap; return path.startsWith(QLatin1Char(':')) ? ResourcePixmap : FilePixmap; } int PropertySheetPixmapValue::compare(const PropertySheetPixmapValue &other) const { return m_path.compare(other.m_path); } QString PropertySheetPixmapValue::path() const { return m_path; } void PropertySheetPixmapValue::setPath(const QString &path) { if (m_path == path) return; m_path = path; } // ---------- PropertySheetIconValue PropertySheetIconValue::PropertySheetIconValue(const PropertySheetPixmapValue &pixmap) { setPixmap(QIcon::Normal, QIcon::Off, pixmap); } PropertySheetIconValue::PropertySheetIconValue() { } bool PropertySheetIconValue::equals(const PropertySheetIconValue &rhs) const { return m_paths == rhs.m_paths; } bool PropertySheetIconValue::operator<(const PropertySheetIconValue &other) const { QMapIterator<ModeStateKey, PropertySheetPixmapValue> itThis(m_paths); QMapIterator<ModeStateKey, PropertySheetPixmapValue> itOther(other.m_paths); while (itThis.hasNext() && itOther.hasNext()) { const ModeStateKey thisPair = itThis.next().key(); const ModeStateKey otherPair = itOther.next().key(); if (thisPair < otherPair) return true; else if (otherPair < thisPair) return false; const int crc = itThis.value().compare(itOther.value()); if (crc < 0) return true; if (crc > 0) return false; } if (itOther.hasNext()) return true; return false; } PropertySheetPixmapValue PropertySheetIconValue::pixmap(QIcon::Mode mode, QIcon::State state) const { const ModeStateKey pair = qMakePair(mode, state); return m_paths.value(pair); } void PropertySheetIconValue::setPixmap(QIcon::Mode mode, QIcon::State state, const PropertySheetPixmapValue &pixmap) { const ModeStateKey pair = qMakePair(mode, state); if (pixmap.path().isEmpty()) m_paths.remove(pair); else m_paths.insert(pair, pixmap); } QPixmap DesignerPixmapCache::pixmap(const PropertySheetPixmapValue &value) const { QMap<PropertySheetPixmapValue, QPixmap>::const_iterator it = m_cache.constFind(value); if (it != m_cache.constEnd()) return it.value(); QPixmap pix = QPixmap(value.path()); m_cache.insert(value, pix); return pix; } void DesignerPixmapCache::clear() { m_cache.clear(); } DesignerPixmapCache::DesignerPixmapCache(QObject *parent) : QObject(parent) { } QIcon DesignerIconCache::icon(const PropertySheetIconValue &value) const { QMap<PropertySheetIconValue, QIcon>::const_iterator it = m_cache.constFind(value); if (it != m_cache.constEnd()) return it.value(); QIcon icon; QMap<QPair<QIcon::Mode, QIcon::State>, PropertySheetPixmapValue> paths = value.paths(); QMapIterator<QPair<QIcon::Mode, QIcon::State>, PropertySheetPixmapValue> itPath(paths); while (itPath.hasNext()) { QPair<QIcon::Mode, QIcon::State> pair = itPath.next().key(); icon.addFile(itPath.value().path(), QSize(), pair.first, pair.second); } m_cache.insert(value, icon); return icon; } void DesignerIconCache::clear() { m_cache.clear(); } DesignerIconCache::DesignerIconCache(DesignerPixmapCache *pixmapCache, QObject *parent) : QObject(parent), m_pixmapCache(pixmapCache) { } PropertySheetStringValue::PropertySheetStringValue(const QString &value, bool translatable, const QString &disambiguation, const QString &comment) : m_value(value), m_translatable(translatable), m_disambiguation(disambiguation), m_comment(comment) { } QString PropertySheetStringValue::value() const { return m_value; } void PropertySheetStringValue::setValue(const QString &value) { m_value = value; } bool PropertySheetStringValue::translatable() const { return m_translatable; } void PropertySheetStringValue::setTranslatable(bool translatable) { m_translatable = translatable; } QString PropertySheetStringValue::disambiguation() const { return m_disambiguation; } void PropertySheetStringValue::setDisambiguation(const QString &disambiguation) { m_disambiguation = disambiguation; } QString PropertySheetStringValue::comment() const { return m_comment; } void PropertySheetStringValue::setComment(const QString &comment) { m_comment = comment; } bool PropertySheetStringValue::equals(const PropertySheetStringValue &rhs) const { return (m_value == rhs.m_value) && (m_translatable == rhs.m_translatable) && (m_disambiguation == rhs.m_disambiguation) && (m_comment == rhs.m_comment); } PropertySheetKeySequenceValue::PropertySheetKeySequenceValue(const QKeySequence &value, bool translatable, const QString &disambiguation, const QString &comment) : m_value(value), m_standardKey(QKeySequence::UnknownKey), m_translatable(translatable), m_disambiguation(disambiguation), m_comment(comment) { } PropertySheetKeySequenceValue::PropertySheetKeySequenceValue(const QKeySequence::StandardKey &standardKey, bool translatable, const QString &disambiguation, const QString &comment) : m_value(QKeySequence(standardKey)), m_standardKey(standardKey), m_translatable(translatable), m_disambiguation(disambiguation), m_comment(comment) { } QKeySequence PropertySheetKeySequenceValue::value() const { return m_value; } void PropertySheetKeySequenceValue::setValue(const QKeySequence &value) { m_value = value; m_standardKey = QKeySequence::UnknownKey; } QKeySequence::StandardKey PropertySheetKeySequenceValue::standardKey() const { return m_standardKey; } void PropertySheetKeySequenceValue::setStandardKey(const QKeySequence::StandardKey &standardKey) { m_value = QKeySequence(standardKey); m_standardKey = standardKey; } bool PropertySheetKeySequenceValue::isStandardKey() const { return m_standardKey != QKeySequence::UnknownKey; } QString PropertySheetKeySequenceValue::comment() const { return m_comment; } void PropertySheetKeySequenceValue::setComment(const QString &comment) { m_comment = comment; } QString PropertySheetKeySequenceValue::disambiguation() const { return m_disambiguation; } void PropertySheetKeySequenceValue::setDisambiguation(const QString &disambiguation) { m_disambiguation = disambiguation; } bool PropertySheetKeySequenceValue::translatable() const { return m_translatable; } void PropertySheetKeySequenceValue::setTranslatable(bool translatable) { m_translatable = translatable; } bool PropertySheetKeySequenceValue::equals(const PropertySheetKeySequenceValue &rhs) const { return (m_value == rhs.m_value) && (m_standardKey == rhs.m_standardKey) && (m_translatable == rhs.m_translatable) && (m_disambiguation == rhs.m_disambiguation) && (m_comment == rhs.m_comment); } class StateMap { public: StateMap() { m_stateToFlag.insert(qMakePair(QIcon::Normal, QIcon::Off), 0x01); m_stateToFlag.insert(qMakePair(QIcon::Normal, QIcon::On), 0x02); m_stateToFlag.insert(qMakePair(QIcon::Disabled, QIcon::Off), 0x04); m_stateToFlag.insert(qMakePair(QIcon::Disabled, QIcon::On), 0x08); m_stateToFlag.insert(qMakePair(QIcon::Active, QIcon::Off), 0x10); m_stateToFlag.insert(qMakePair(QIcon::Active, QIcon::On), 0x20); m_stateToFlag.insert(qMakePair(QIcon::Selected, QIcon::Off), 0x40); m_stateToFlag.insert(qMakePair(QIcon::Selected, QIcon::On), 0x80); m_flagToState.insert(0x01, qMakePair(QIcon::Normal, QIcon::Off)); m_flagToState.insert(0x02, qMakePair(QIcon::Normal, QIcon::On)); m_flagToState.insert(0x04, qMakePair(QIcon::Disabled, QIcon::Off)); m_flagToState.insert(0x08, qMakePair(QIcon::Disabled, QIcon::On)); m_flagToState.insert(0x10, qMakePair(QIcon::Active, QIcon::Off)); m_flagToState.insert(0x20, qMakePair(QIcon::Active, QIcon::On)); m_flagToState.insert(0x40, qMakePair(QIcon::Selected, QIcon::Off)); m_flagToState.insert(0x80, qMakePair(QIcon::Selected, QIcon::On)); } uint flag(const QPair<QIcon::Mode, QIcon::State> &pair) const { return m_stateToFlag.value(pair); } QPair<QIcon::Mode, QIcon::State> state(uint flag) const { return m_flagToState.value(flag); } private: QMap<QPair<QIcon::Mode, QIcon::State>, uint > m_stateToFlag; QMap<uint, QPair<QIcon::Mode, QIcon::State> > m_flagToState; }; Q_GLOBAL_STATIC(StateMap, stateMap) uint PropertySheetIconValue::mask() const { uint flags = 0; QMapIterator<ModeStateKey, PropertySheetPixmapValue> itPath(m_paths); while (itPath.hasNext()) flags |= stateMap()->flag(itPath.next().key()); return flags; } uint PropertySheetIconValue::compare(const PropertySheetIconValue &other) const { uint diffMask = mask() | other.mask(); for (int i = 0; i < 8; i++) { uint flag = 1 << i; if (diffMask & flag) { // if state is set in both icons, compare the values const ModeStateKey state = stateMap()->state(flag); if (pixmap(state.first, state.second) == other.pixmap(state.first, state.second)) diffMask &= ~flag; } } return diffMask; } void PropertySheetIconValue::assign(const PropertySheetIconValue &other, uint mask) { for (int i = 0; i < 8; i++) { uint flag = 1 << i; if (mask & flag) { const ModeStateKey state = stateMap()->state(flag); setPixmap(state.first, state.second, other.pixmap(state.first, state.second)); } } } PropertySheetIconValue::ModeStateToPixmapMap PropertySheetIconValue::paths() const { return m_paths; } QDESIGNER_SHARED_EXPORT QDesignerFormWindowCommand *createTextPropertyCommand(const QString &propertyName, const QString &text, QObject *object, QDesignerFormWindowInterface *fw) { if (text.isEmpty()) { ResetPropertyCommand *cmd = new ResetPropertyCommand(fw); cmd->init(object, propertyName); return cmd; } SetPropertyCommand *cmd = new SetPropertyCommand(fw); cmd->init(object, propertyName, text); return cmd; } QDESIGNER_SHARED_EXPORT QAction *preferredEditAction(QDesignerFormEditorInterface *core, QWidget *managedWidget) { QAction *action = 0; if (const QDesignerTaskMenuExtension *taskMenu = qt_extension<QDesignerTaskMenuExtension*>(core->extensionManager(), managedWidget)) { action = taskMenu->preferredEditAction(); if (!action) { const QList<QAction *> actions = taskMenu->taskActions(); if (!actions.isEmpty()) action = actions.first(); } } if (!action) { if (const QDesignerTaskMenuExtension *taskMenu = qobject_cast<QDesignerTaskMenuExtension *>( core->extensionManager()->extension(managedWidget, QLatin1String("QDesignerInternalTaskMenuExtension")))) { action = taskMenu->preferredEditAction(); if (!action) { const QList<QAction *> actions = taskMenu->taskActions(); if (!actions.isEmpty()) action = actions.first(); } } } return action; } QDESIGNER_SHARED_EXPORT bool runUIC(const QString &fileName, UIC_Mode mode, QByteArray& ba, QString &errorMessage) { QStringList argv; QString binary = QLibraryInfo::location(QLibraryInfo::BinariesPath); binary += QDir::separator(); switch (mode) { case UIC_GenerateCode: binary += QLatin1String("uic"); break; case UIC_ConvertV3: binary += QLatin1String("uic3"); argv += QLatin1String("-convert"); break; } argv += fileName; QProcess uic; uic.start(binary, argv); if (!uic.waitForStarted()) { errorMessage = QApplication::translate("Designer", "Unable to launch %1.").arg(binary); return false; } if (!uic.waitForFinished()) { errorMessage = QApplication::translate("Designer", "%1 timed out.").arg(binary); return false; } if (uic.exitCode()) { errorMessage = QString::fromAscii(uic.readAllStandardError()); return false; } ba = uic.readAllStandardOutput(); return true; } QDESIGNER_SHARED_EXPORT QString qtify(const QString &name) { QString qname = name; Q_ASSERT(qname.isEmpty() == false); if (qname.count() > 1 && qname.at(1).isUpper()) { const QChar first = qname.at(0); if (first == QLatin1Char('Q') || first == QLatin1Char('K')) qname.remove(0, 1); } const int len = qname.count(); for (int i = 0; i < len && qname.at(i).isUpper(); i++) qname[i] = qname.at(i).toLower(); return qname; } // --------------- UpdateBlocker UpdateBlocker::UpdateBlocker(QWidget *w) : m_widget(w), m_enabled(w->updatesEnabled() && w->isVisible()) { if (m_enabled) m_widget->setUpdatesEnabled(false); } UpdateBlocker::~UpdateBlocker() { if (m_enabled) m_widget->setUpdatesEnabled(true); } } // namespace qdesigner_internal QT_END_NAMESPACE
34.967347
182
0.621688
[ "object" ]
cf510de5b6be48987bf905b0493ec3e0a1b325b9
608
cpp
C++
Arrays/missing_n_repeat.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
Arrays/missing_n_repeat.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
Arrays/missing_n_repeat.cpp
aneesh001/InterviewBit
fcbac096fd8e9554a52db10dc9e5a88cb8a83ef3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; vector<int> repeatedNumber(const vector<int> &A) { long a = 0, b = 0, a2 = 0, b2 = 0; for(int i = 1; i <= A.size(); ++i) { a += i; a2 += i * i; b += A[i - 1]; b2 += (long)A[i - 1] * (long)A[i - 1]; } long ypx = (a2 - b2) / (a - b); long ymx = a - b; long y = (ypx + ymx) / 2; long x = (ypx - ymx) / 2; // y - x = a - b // y + x = (a2 - b2) / (a - b) return vector<int>{(int)x, (int)y}; } int main(void) { vector<int> a{3, 1, 2, 5, 3}; repeatedNumber(a); return 0; }
20.965517
50
0.419408
[ "vector" ]
cf5184bbbc9ad4f50b41e219336c69b656620653
8,075
cpp
C++
source/code/utilities/filesystem/paths/lib.cpp
luxe/CodeLang-compiler
78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a
[ "MIT" ]
33
2019-05-30T07:43:32.000Z
2021-12-30T13:12:32.000Z
source/code/utilities/filesystem/paths/lib.cpp
luxe/CodeLang-compiler
78837d90bdd09c4b5aabbf0586a5d8f8f0c1e76a
[ "MIT" ]
371
2019-05-16T15:23:50.000Z
2021-09-04T15:45:27.000Z
source/code/utilities/filesystem/paths/lib.cpp
UniLang/compiler
c338ee92994600af801033a37dfb2f1a0c9ca897
[ "MIT" ]
6
2019-08-22T17:37:36.000Z
2020-11-07T07:15:32.000Z
#include "code/utilities/filesystem/paths/lib.hpp" #include "code/utilities/filesystem/files/observers/lstat_wrap/lib.hpp" #include <sys/stat.h> #include <sys/types.h> #include <dirent.h> #include <string> #include <unistd.h> #include <sys/types.h> #include <pwd.h> #include "boost/range/adaptor/reversed.hpp" // bazel derived std::string Bazel_Working_Directory(){ auto x = getenv("BUILD_WORKING_DIRECTORY"); if (x){ return x; } return ""; } std::string Bazel_Workspace_Directory(){ auto x = getenv("BUILD_WORKSPACE_DIRECTORY"); if (x){ return x; } return ""; } std::string Bazel_Derived_Root_Of_Repo(){ auto x = Bazel_Workspace_Directory(); x.erase(x.length()-std::string("source").size()); return x; } std::string Bazel_Derived_Path_To_Self_Unilang(){ auto x = Bazel_Workspace_Directory(); return x + "/code/external_projects/self/"; } std::string Bazel_Derived_Path_To_Essays(){ auto x = Bazel_Workspace_Directory(); return x + "/code/literature/essays/"; } std::string Bazel_Deps_Directory(){ return Bazel_Workspace_Directory() + "/bazel/deps/"; } std::string Root_Readme_Directory(){ return Bazel_Derived_Root_Of_Repo() + ".readme/"; } std::string Bazel_External_Dep_Targets_Directory(){ return Bazel_Workspace_Directory() + "/code/utilities/deps/external/"; } void Move_To_Repo_Root(){ auto p = Bazel_Derived_Root_Of_Repo(); Set_Path(p); } void Move_To_Bazel_Derived_Path_To_Self_Unilang(){ auto p = Bazel_Derived_Path_To_Self_Unilang(); Set_Path(p); } void Move_To_Bazel_Derived_Path_To_Essays(){ auto p = Bazel_Derived_Path_To_Essays(); Set_Path(p); } //+---------------------------------------+ //| changing path / traversing filesystem | //+---------------------------------------+ //THESE FUNCTIONS WILL CHANGE THE STATE OF THE CURRENT WORKING DIRECTORY void Set_Path(std::string const& path) { boost::filesystem::current_path(path); } void Possibly_Set_Path(bool const& set, std::string const& path) { if (set){ Set_Path(path); } } void Set_Path_If_Not_Empty(std::string const& path) { if (!path.empty()){ Set_Path(path); } } void Step_Into_Folder(std::string const folder_name){ //not sure if that "./" really needs to be there boost::filesystem::current_path("./" + folder_name); return; } void Step_Out_Of_Folder(void){ //not sure if that "./" really needs to be there boost::filesystem::current_path(std::string("./") + std::string("../")); return; } void Move_Back_Directories_Until_Directory_Exists(std::string root_directory_name){ while (!File_Exists(root_directory_name)){ Step_Out_Of_Folder(); } return; } //+-----------+ //| Observers | //+-----------+ std::string Current_Folder_Name(void){ //there is probably a way to get just the current folder name, but i couldn't find it std::string full = boost::filesystem::current_path().string(); std::string name; for (auto it = full.rbegin(); it != full.rend(); ++it){ if (*it == '/'){ break; } name+=*it; } std::reverse(name.begin(), name.end()); return name; } std::vector<std::string> Recursively_Get_All_Directories_From_Path(std::string const& path){ return Get_Each_Line_Of_Shell_Command("find \"" + path + "\" -type d"); } //+---------------+ //| Getting Paths | //+---------------+ std::vector<std::string> Current_Path_In_Parts(void){ auto full = boost::filesystem::current_path().string(); std::vector<std::string> parts; std::string part; for (auto const& c: full){ if (c == '/'){ parts.push_back(part); part.clear(); }else{ part+=c; } } if (!part.empty()){ parts.push_back(part); } return parts; } std::string Current_Path(void) { return boost::filesystem::current_path().string(); } std::string Full_Path(void) { return boost::filesystem::current_path().string(); } std::string Get_Path_Of_Directory_Starting_From_Root_Directory_Name(std::string root_directory_name){ std::string path; auto parts = Current_Path_In_Parts(); for (auto const& it: boost::adaptors::reverse(parts)){ if (it == root_directory_name){ path=path+it + '/'; break; } path=path+it + '/'; } return path; } std::string Get_Path_Of_Directory_Starting_From_One_Directory_Deeper_Than_Root_Directory_Name(std::string root_directory_name){ std::string path; auto parts = Current_Path_In_Parts(); for (auto const& it: boost::adaptors::reverse(parts)){ if (it == root_directory_name){ break; } path=path+it + '/'; } return path; } std::string Get_Path_Of_Directory_After_Found_Folder(std::string found_folder){ std::string path; bool found = false; auto parts = Current_Path_In_Parts(); for (auto const& it: parts){ if (found){ path += it + '/'; } if (it == found_folder){ found = true; } } return path; } std::string Get_Path_Of_Directory_After_Desktop() { return Get_Path_Of_Directory_After_Found_Folder("Desktop"); } std::string Full_Path_To_Home(){ auto home = getenv("HOME"); if (home){ return home; } return ""; } std::string Full_Path_To_Desktop(){ auto dir = Full_Path_To_Home(); dir += "/Desktop/"; return dir; } std::string Full_Path_For_Desktop_File(std::string const& file){ return Full_Path_To_Desktop() + file; } std::string Full_Path_To_Home_Config_File(std::string const& config_for) { return Full_Path_To_Home() + "/." + config_for; } std::string Full_Path_To_Home_File(std::string const& path) { return Full_Path_To_Home() + "/" + path; } std::string Full_Path_For_Tmp_File(std::string const& file) { return "/tmp/" + file; } //+--------------------+ //| Checking Existence | //+--------------------+ bool Directory_Exists_In_Current_Directory_Or_Any_Parents(std::string const& dir) { std::string full = boost::filesystem::current_path().string(); while (Current_Folder_Name() != "") { if (File_Exists(dir)) { boost::filesystem::current_path(full); return true; } Step_Out_Of_Folder(); } boost::filesystem::current_path(full); return false; } bool Directory_Exists(std::string path_to_dir){ struct stat info; if(stat(path_to_dir.c_str(), &info) != 0 ){ return false; } else if(info.st_mode & S_IFDIR){ return true; } return false; } //+----------------------------------+ //| Get Numerical Data on Filesystem | //+----------------------------------+ int Recursively_Get_Directory_Count(std::string const& path) { std::string str = exec("find " + path + " -type d | wc -l"); return atoi(str.c_str()); } int Get_Number_Of_Files_In_Directory(std::string path) { struct dirent* entry; DIR* dp; int count = 0; //add slash to the end if wer need it since we append the path onto the filename when storing if (path[path.size()-1] != '/'){path+="/";} //open folder dp = opendir(path.c_str()); if (dp == NULL){ return 0;} //loop and store while ((entry = readdir(dp))){ if (Is_Regular_File(path + entry->d_name)){ ++count; } } closedir(dp); return count; } unsigned int Number_Of_Directories_Deep_In_Root_Directory_Name(std::string root_directory_name){ unsigned int depth = 0; auto parts = Current_Path_In_Parts(); for (auto const& it: boost::adaptors::reverse(parts)){ if (it == root_directory_name){ break; } depth++; } return depth; } //+--------------+ //| Transformers | //+--------------+ void Create_Path_If_It_Doesnt_Already_Exist(std::string const& path){ if (!File_Exists(path)){ execute_quietly(("mkdir -p " + path).c_str()); } return; } //+--------------------------------------------------------+ //| Transforming AND changing path / traversing filesystem | //+--------------------------------------------------------+ void Create_Path_If_It_Doesnt_Already_Exist_And_Step_Into_It(std::string const& path){ Create_Path_If_It_Doesnt_Already_Exist(path); Step_Into_Folder(path); return; } void Create_The_Path_Empty_And_Step_Into_It(std::string const& path){ execute_quietly("rm -rf " + path); Create_Path_If_It_Doesnt_Already_Exist_And_Step_Into_It(path); return; } //utility void Shortify_Path(boost::filesystem::path & path){ path = boost::filesystem::canonical(path); return; }
24.469697
127
0.670341
[ "vector" ]
cf5430ba03118002acaefce4b9722c61e185a598
3,695
cpp
C++
materials/subsurface.cpp
cathook/rendering_final_proj
d0c147b563d6949839983bf38317c81367e2ed4c
[ "BSD-2-Clause" ]
3
2020-12-09T00:03:29.000Z
2021-07-03T13:31:41.000Z
materials/subsurface.cpp
piwell/CS348B-pbrt
147a9a3ef55cfcb0a1ad0132c63d1ac2f928418f
[ "BSD-2-Clause" ]
null
null
null
materials/subsurface.cpp
piwell/CS348B-pbrt
147a9a3ef55cfcb0a1ad0132c63d1ac2f928418f
[ "BSD-2-Clause" ]
1
2020-11-28T12:33:24.000Z
2020-11-28T12:33:24.000Z
/* pbrt source code Copyright(c) 1998-2012 Matt Pharr and Greg Humphreys. This file is part of pbrt. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // materials/subsurface.cpp* #include "stdafx.h" #include "materials/subsurface.h" #include "textures/constant.h" #include "volume.h" #include "spectrum.h" #include "reflection.h" #include "texture.h" #include "paramset.h" // SubsurfaceMaterial Method Definitions BSDF *SubsurfaceMaterial::GetBSDF(const DifferentialGeometry &dgGeom, const DifferentialGeometry &dgShading, MemoryArena &arena) const { // Allocate _BSDF_, possibly doing bump mapping with _bumpMap_ DifferentialGeometry dgs; if (bumpMap) Bump(bumpMap, dgGeom, dgShading, &dgs); else dgs = dgShading; BSDF *bsdf = BSDF_ALLOC(arena, BSDF)(dgs, dgGeom.nn); Spectrum R = Kr->Evaluate(dgs).Clamp(); float e = eta->Evaluate(dgs); if (!R.IsBlack()) bsdf->Add(BSDF_ALLOC(arena, SpecularReflection)(R, BSDF_ALLOC(arena, FresnelDielectric)(1., e))); return bsdf; } BSSRDF *SubsurfaceMaterial::GetBSSRDF(const DifferentialGeometry &dgGeom, const DifferentialGeometry &dgShading, MemoryArena &arena) const { float e = eta->Evaluate(dgShading); return BSDF_ALLOC(arena, BSSRDF)(scale * sigma_a->Evaluate(dgShading), scale * sigma_prime_s->Evaluate(dgShading), e); } SubsurfaceMaterial *CreateSubsurfaceMaterial(const Transform &xform, const TextureParams &mp) { float sa_rgb[3] = { .0011f, .0024f, .014f }, sps_rgb[3] = { 2.55f, 3.21f, 3.77f }; Spectrum sa = Spectrum::FromRGB(sa_rgb), sps = Spectrum::FromRGB(sps_rgb); string name = mp.FindString("name"); bool found = GetVolumeScatteringProperties(name, &sa, &sps); if (name != "" && !found) Warning("Named material \"%s\" not found. Using defaults.", name.c_str()); float scale = mp.FindFloat("scale", 1.f); Reference<Texture<Spectrum> > sigma_a, sigma_prime_s; sigma_a = mp.GetSpectrumTexture("sigma_a", sa); sigma_prime_s = mp.GetSpectrumTexture("sigma_prime_s", sps); Reference<Texture<float> > ior = mp.GetFloatTexture("index", 1.3f); Reference<Texture<Spectrum> > Kr = mp.GetSpectrumTexture("Kr", Spectrum(1.f)); Reference<Texture<float> > bumpMap = mp.GetFloatTextureOrNull("bumpmap"); return new SubsurfaceMaterial(scale, Kr, sigma_a, sigma_prime_s, ior, bumpMap); }
41.055556
86
0.717727
[ "transform" ]
cf582744e0d5c46ec91634e38aabfca769be5d8a
2,649
hpp
C++
VdfParser.hpp
cursey/vdf-parser
8d43593e9cda0d3bc2602e4bb4dfcbbf541f3b9e
[ "MIT" ]
null
null
null
VdfParser.hpp
cursey/vdf-parser
8d43593e9cda0d3bc2602e4bb4dfcbbf541f3b9e
[ "MIT" ]
null
null
null
VdfParser.hpp
cursey/vdf-parser
8d43593e9cda0d3bc2602e4bb4dfcbbf541f3b9e
[ "MIT" ]
null
null
null
#include <iostream> #include <stack> #include <unordered_map> #include <tao/pegtl.hpp> // https://developer.valvesoftware.com/wiki/KeyValues namespace vdf { struct Object { std::string name{}; std::string value{}; std::unordered_map<std::string, Object> kvs{}; Object& operator[](const std::string& key) { return kvs[key]; } }; namespace parser { using namespace tao::pegtl; struct Comment : disable<two<'/'>, until<eolf>> {}; struct Sep : sor<space, Comment> {}; struct Seps : star<Sep> {}; struct Escaped : if_must<one<'\\'>, sor<one<'"', '\\'>>> {}; struct Regular : not_one<'\r', '\n'> {}; struct Character : sor<Escaped, Regular> {}; struct String : if_must<one<'"'>, until<one<'"'>, Character>> {}; struct Key : String {}; struct Value : String {}; struct KeyValue : seq<Key, Seps, Value> {}; struct Object; struct ObjectName : String {}; struct ObjectMembers : sor<list<sor<KeyValue, Object>, Seps>, Seps> {}; struct Object : seq<ObjectName, Seps, one<'{'>, until<one<'}'>, ObjectMembers>> {}; struct Grammar : until<eof, sor<eolf, Sep, Object>> {}; struct State { std::string item{}; std::string key{}; std::string value{}; std::stack<vdf::Object> objs{}; vdf::Object final_obj{}; }; template <typename Rule> struct Action : nothing<Rule> {}; template <> struct Action<Character> { template <typename Input> static void apply(const Input& in, State& s) { s.item += in.string_view(); } }; template <> struct Action<Key> { template <typename Input> static void apply(const Input& in, State& s) { s.key = std::move(s.item); } }; template <> struct Action<Value> { template <typename Input> static void apply(const Input& in, State& s) { s.value = std::move(s.item); } }; template <> struct Action<KeyValue> { template <typename Input> static void apply(const Input& in, State& s) { vdf::Object obj{}; obj.name = std::move(s.key); obj.value = std::move(s.value); s.objs.top().kvs[obj.name] = std::move(obj); } }; template <> struct Action<ObjectName> { template <typename Input> static void apply(const Input& in, State& s) { vdf::Object obj{}; obj.name = std::move(s.item); s.objs.emplace(std::move(obj)); } }; template <> struct Action<Object> { template <typename Input> static void apply(const Input& in, State& s) { auto obj = std::move(s.objs.top()); s.objs.pop(); if (s.objs.empty()) { s.final_obj[obj.name] = std::move(obj); } else { s.objs.top().kvs[obj.name] = std::move(obj); } } }; } // namespace parser } // namespace vdf
28.483871
107
0.616459
[ "object" ]