blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
5
117
path
stringlengths
3
268
src_encoding
stringclasses
34 values
length_bytes
int64
6
4.23M
score
float64
2.52
5.19
int_score
int64
3
5
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
text
stringlengths
13
4.23M
download_success
bool
1 class
79ea6994db04a56eaa25b5b00972a20a789ebc7a
C++
apgearhart1/EECS560Labs
/Lab1/Node.h
UTF-8
1,622
3.265625
3
[]
no_license
/*@author Aaron Gearhart @file Node.h @date 9/19/2018 @brief This file is the header file for the Node object. Contains methods to manipulate the each node in the list. */ #ifndef NODE_H #define NODE_H class Node { private: int m_entry; Node* m_next; bool m_first; public: /* @pre none * @post sets the m_first variable to true/false as needed * @param check - T/F variable to indicate the node is first or not * @throw none **/ void setFirst(bool check); /* @pre none * @post Returns true/false if this node is first to enter in the list * @param none * @throw none **/ bool isFirst() const; /* @pre none * @post Returns the value at the current position * @param none * @throw none **/ int getEntry()const; /* @pre none * @post Returns the next object at the current position * @param none * @throw none **/ Node* getNext()const; /* @pre entry is the website url * @post The current position is given an entry * @param entry is a templated variable, for the url * @throw none **/ void setEntry(int entry); /* @pre next is the pointer to the next node in the list * @post The next object in chain from the current position is set * @param next is the pointer to the next object * @throw none **/ void setNext(Node* next); /* @pre none * @post The default node object is created without a parameter * @param none * @throw none **/ Node(); /* @pre Entry is the website url * @post The Node object is created with an entry inside * @param Templated entry: the website url * @throw none **/ Node(int entry); }; #endif
true
cb448930522e18373ae5a95b991a7266b86a4a7b
C++
michaeloed/DecoderPro_app
/libPr3/defaultmemory.h
UTF-8
776
2.671875
3
[]
no_license
#ifndef DEFAULTMEMORY_H #define DEFAULTMEMORY_H #include "abstractmemory.h" class DefaultMemory : public AbstractMemory { Q_OBJECT public: explicit DefaultMemory(QString sysName, QString userName="", QObject *parent = 0); /** * Provide generic access to internal state. *<P> * This generally shouldn't be used by Java code; use * the class-specific form instead. (E.g. getCommandedState in Turnout) * This provided to make Jython * script access easier to read. * <P> * If the current value can be reduced to an integer, that * is returned, otherwise a value of -1 is returned. */ /*public*/ int getState(); /*public*/ void setState(int s); signals: public slots: }; #endif // DEFAULTMEMORY_H
true
8f9d33352c4d203b30194d62c5034255137d4026
C++
bmal/trash
/test_accumulate2.cpp
UTF-8
2,340
3.484375
3
[]
no_license
#include <iostream> #include <thread> #include <future> #include <vector> #include <algorithm> using namespace std; class join_threads { public: explicit join_threads(vector<thread>& threads) : threads_(threads) {} ~join_threads() { for(auto& elem : threads_) if(elem.joinable()) elem.join(); } private: vector<thread>& threads_; }; template<class Iterator, typename T> T parallel_accumulate(Iterator beg, Iterator end, T init) { auto length = distance(beg, end); if(length == 0) return init; const unsigned long min_per_thread = 1000; const unsigned long max_threads = (length + min_per_thread - 1)/min_per_thread; const unsigned long hardware_threads = thread::hardware_concurrency(); const unsigned long num_threads = min( (hardware_threads != 0 ? hardware_threads : 2), max_threads); const unsigned long block_size = length/num_threads; vector<future<T>> futures(num_threads - 1); vector<thread> threads(num_threads - 1); join_threads joiner(threads); Iterator block_start = beg; for(unsigned long i = 0; i < threads.size(); ++i) { Iterator block_end = block_start; advance(block_end, block_size); packaged_task<T(Iterator, Iterator)> task( [](Iterator beg, Iterator end){return accumulate(beg, end, T()); }); futures[i] = task.get_future(); threads[i] = thread(move(task), block_start, block_end); block_start = block_end; } T last_result = accumulate(block_start, end, T()); T result = init; for(auto& elem : futures) result += elem.get(); result += last_result; return result; } int main() { vector<int> v; for(int i = 0; i < 1000000; ++i) v.push_back(i); auto start = chrono::steady_clock::now(); unsigned long sum = accumulate(v.begin(), v.end(), 0); auto end = chrono::steady_clock::now(); cout << "STD: sum = " << sum << ", t = " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << endl; start = chrono::steady_clock::now(); sum = parallel_accumulate(v.begin(), v.end(), 0); end = chrono::steady_clock::now(); cout << "MY: sum = " << sum << ", t = " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << endl; }
true
fed24f0260849749f961f0fe5e2041c2755ddc8a
C++
jensecj/code-challenges
/hackerrank/cracking-the-coding-interview/10-stacks-balanced-brackets.cpp
UTF-8
1,096
4.125
4
[]
no_license
/* tags: stack, paren matching task: given a string of braces (parens, curly braces, and brackets), check if the string is balanced (each opening has a corresponding ending in a proper place) */ #include <iostream> #include <string> #include <stack> using namespace std; int main() { int n; // number of string to check cin >> n; for(int i = 0; i < n; i++) { string s; cin >> s; stack<char> stack; bool balanced = true; // for each open paren we push its counter part on the stack, and // then compare each close paren we find with the top of the stack for(auto& c : s) { if(c == '{') stack.push('}'); else if (c == '(') stack.push(')'); else if (c == '[') stack.push(']'); else if (stack.empty() || c != stack.top()) { balanced = false; } else { stack.pop(); } } // there are some parens on the stack that we have not popped yet, // so the string is unmatching if(stack.size() > 0) balanced = false; if(balanced) cout << "YES" << endl; else cout << "NO" << endl; } }
true
b780d1df1c2e1812574cfc4c8d8a57925f70d4b2
C++
Takos4Lunch/proyecto-II
/Materia.h
UTF-8
483
2.515625
3
[]
no_license
#ifndef MateriaH #define MateriaH #include <fstream> using namespace std; class Materia { // Private section public: int cod=0;//Codigo char tit[80],uc[1] ;//titulo de la materia, unidades de credito fstream y; Materia(); Materia(int cd, char tt[80],char *ucc); void save(int cd, char tt[80],char *uc,Materia **mat,int& contmater); void load(Materia **mat,int& contmater); void print(); // Public Declarations protected: // Protected Declarations }; #endif
true
5d926eb876067479469644675173e72817977d8f
C++
VibhorKanojia/Programming
/Codeforces/312_2/largeArray.cpp
UTF-8
1,204
2.75
3
[]
no_license
#include <bits/stdc++.h> using namespace std; #define MAXN 1000001 struct data{ int count; int start; int end; }; int main(){ ios::sync_with_stdio(false); int n; cin >> n; map<int, struct data> mymap; map<int, struct data>::iterator it; int index = 0; for (int i = 0 ; i < n ; i++){ index++; int val; cin >>val; it = mymap.find(val); if (it == mymap.end()){ struct data d; d.count = 1; d.start = index; d.end = 0; mymap.insert(pair<int,struct data>(val,d)); } else { (it->second).count++; (it->second).end = index; } } int maxOcc = 0; int curdiff = 100000000; int l = 0; int r = 0; for (it = mymap.begin() ; it != mymap.end(); it++){ if ((it->second).count == maxOcc){ if ((it->second).end - (it->second).start < curdiff){ l = (it->second).start; r = (it->second).end; curdiff = r-l; } } else if ((it->second).count > maxOcc){ maxOcc = (it->second).count; l = (it->second).start; r = (it->second).end; curdiff = r - l; } } if (l > r) { l = 1; r = 1; } cout<<l<<" "<<r<<endl; return 0; }
true
4172cfed3fe2a89cd7e2d510a411bd85c467d751
C++
shasan247/LPG-MONITOR
/AlarmUnitV4_mqtt_final_pulled_up - OFFLINE STORAGE - No Debug/main/wifi_manager.ino
UTF-8
1,882
2.734375
3
[]
no_license
//for power and net status void toggleLed() { // digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); // set pin to the opposite state digitalWrite(STATUS_LED, !digitalRead(STATUS_LED)); } void alwaysOnLed(){ // digitalWrite (LED_BUILTIN, LOW); digitalWrite(STATUS_LED, HIGH); } void configModeCallback (WiFiManager *myWiFiManager) { Serial.println("Entered config mode"); Serial.println(WiFi.softAPIP()); //if you used auto generated SSID, PRINT it Serial.println(myWiFiManager->getConfigPortalSSID()); //entered config mode, make led toggle faster toggleTicker.attach(0.25, toggleLed); } void wifi_manager(){ // start ticker with 0.5 because we start in AP mode and try to connect toggleTicker.attach(1, toggleLed); P_R_I_N_T("AP Mode"); //WiFiManager //Local intialization. Once its business is done, there is no need to keep it around WiFiManager wifiManager; //sets timeout until configuration portal gets turned off //useful to make it all retry or go to sleep //in seconds wifiManager.setTimeout(30); //surprisingly wifi manager times out after 2*30=60s char buff[10];//max 9 digit AP name // did.toCharArray(buff, 10); strcpy(buff, did); wifiManager.autoConnect(buff, "support123");//START AP AS DEVICE ID NAME //set callback that gets called when connecting to previous WiFi fails, and enters Access Point mode // wifiManager.setAPCallback(configModeCallback); if (!wifiManager.autoConnect()) { P_R_I_N_T("failed to connect and hit timeout"); //reset and try again, or maybe put it to deep sleep ESP.reset(); delay(1000); } //if you get here you have connected to the WiFi P_R_I_N_T("connected...yeey :)"); delay(250); // toggleTicker.detach(); //shift inside mqtt reconnect // alwaysOnLed(); }
true
db79ece2d4e39361e9c892b56d22ec535a974af5
C++
TankKingOne/NewCodeANDLeetCode
/牛客网-分解因数.cpp
GB18030
559
3.625
4
[]
no_license
#include <cstdio> #include <cmath> #include <iostream> int main() { unsigned int n; while (std::cin >> n) { printf("%d =", n); //90 = for (unsigned i = 2; i <= std::sqrt(n); i++) { while (n % i == 0 && n != i) //ͬһֱųպǸnη { printf(" %u *", i); //һδӡ 2 *,ڶδӡ 3 * n /= i; //޸nֵ } } printf(" %d\n", n); //nѾǴһһ5 } return 0; }
true
924062bfdf3f9493f0739afc9615fb866aba769f
C++
borrislevin/TIL
/TIL/test.cpp
UTF-8
456
3.34375
3
[]
no_license
#include <iostream> #include <string> using namespace std; class Shape { public: virtual ~Shape() {} virtual void draw() = 0; virtual Shape* Clone() = 0; }; class Rect : public Shape { public: void draw() override { cout << "Rect draw" << endl; } Shape* Clone() override { return new Rect(*this); } }; int main() { Shape* v1; Rect* v2=new Rect; Shape* v3 = new Rect(*v2); Shape* v4 = new Rect(*v2); cout << v3 << endl; cout << v4 << endl; }
true
ec8743fdbbd30548fb998220f2f144342d7ba4bb
C++
xche03/CPP-Primer-5th
/Ch3/Exercise 3.44.cpp
UTF-8
1,154
4.15625
4
[]
no_license
/*Exercise 3.44: Rewrite the programs from the previous exercises using a C++ Primer, Fifth Edition type alias for the type of the loop control variables.*/ #include <iostream> #include <vector> #include <iterator> using namespace std; int main() { int ia[3][4] = { // three elements; each element is an array of size 4 { 0, 1, 2, 3 }, // initializers for the row indexed by 0 { 4, 5, 6, 7 }, // initializers for the row indexed by 1 { 8, 9, 10, 11 } // initializers for the row indexed by 2 }; //range for using int_array = int[4]; //typedef int int_array[4]; for (int_array &row : ia) {// for every element in the outer array for (int &col : row) { // for every element in the inner array cout << col << " "; } cout << endl; } cout << "***************************" << endl; //Ordinary for (int i = 0; i < 3; ++i) { for (int j = 0; j< 4; ++j) { cout << ia[i][j] << " "; } cout << endl; } cout << "***************************" << endl; //pointers for (int_array *p = ia; p < ia + 3; ++p) { for (int *q = *p; q != *p + 4; ++q) { cout << *q << " "; } cout << endl; } system("PAUSE"); return 0; }
true
891f0edfabb167ea9ff2c2e89f1edb183ec8e964
C++
jcyesc/assembly-language-computer-architecture
/architecture/H1/chapter7/problem52/program_c.cpp
UTF-8
247
3.234375
3
[]
no_license
// Program 7.52 #include <iostream> using namespace std; int a = 5; void f(int x) { cout << "x = " << x << endl; cout << "a = " << a << endl; } int main() { f(a++); // is a incremented before f is executed ? YES return 0; }
true
7d7ac4e700df6ced444260412985ef6b8471dd0c
C++
i-n-d-i/msu-practicum-5semestr
/home3/2.cpp
UTF-8
2,817
3.640625
4
[]
no_license
#include <iostream> #include <vector> #include <cmath> const float INF = 1000000001.0; class TGraph { private: uint32_t VerticesNumber; std::vector<std::pair<uint32_t, uint32_t>> Cities; std::vector<std::vector<std::pair<uint32_t, uint32_t>>> SpecialCities; public: TGraph(); TGraph(uint32_t n); void ReadFromStream(std::istream& stream); void ReadSpecialCities(std::istream& stream, uint32_t m); float Dijkstra(uint32_t a, uint32_t b); }; TGraph::TGraph() : VerticesNumber(0) , Cities() , SpecialCities() { } TGraph::TGraph(uint32_t n) : VerticesNumber(n) , Cities(n, std::pair<uint32_t, uint32_t>(0,0)) , SpecialCities(n, std::vector<std::pair<uint32_t, uint32_t>>()) { } void TGraph::ReadFromStream(std::istream& stream) { for (uint32_t i = 0; i < VerticesNumber; i++) { stream >> Cities[i].first >> Cities[i].second; } } void TGraph::ReadSpecialCities(std::istream& stream, uint32_t m) { uint32_t u, v, cost; for (uint32_t i = 0; i < m; i++) { stream >> u >> v >> cost; SpecialCities[u - 1].push_back(std::make_pair(v - 1, cost)); SpecialCities[v - 1].push_back(std::make_pair(u - 1, cost)); } } float TGraph::Dijkstra(uint32_t a, uint32_t b) { std::vector<float> distance(VerticesNumber, INF); std::vector<bool> visited(VerticesNumber, false); distance[a - 1] = 0; for (uint32_t i = 0; i < VerticesNumber; i++) { int32_t v = -1; for (uint32_t j = 0; j < VerticesNumber; j++) { if (!visited[j] && (v == -1 || distance[j] < distance[v])) { v = j; } } visited[v] = true; for (uint32_t j = 0; j < VerticesNumber; j++) { uint32_t flag = 0; for (uint32_t k = 0; k < SpecialCities[v].size(); k++) { if (SpecialCities[v][k].first == j) { flag = 1; if (!visited[j] && distance[v] + SpecialCities[v][k].second < distance[j]) { distance[j] = distance[v] + SpecialCities[v][k].second; } break; } } if (!flag) { float cost = sqrt(pow(abs(Cities[v].first - Cities[j].first), 2) + pow(abs(Cities[v].second - Cities[j].second), 2)); if (!visited[j] && distance[v] + cost < distance[j]) { distance[j] = distance[v] + cost; } } } } return distance[b - 1]; } int main() { uint32_t n, m, a, b; std::cin >> n; TGraph graph(n); graph.ReadFromStream(std::cin); std::cin >> m; graph.ReadSpecialCities(std::cin, m); std::cin >> a >> b; std::cout << graph.Dijkstra(a, b) << std::endl; return 0; }
true
411f6234a37ce525f38c3e881001201e3870980e
C++
YernurSFU/libflow
/example/leetcode1437.cpp
UTF-8
987
3.53125
4
[]
no_license
#include <flow.hpp> // Given an array nums of 0s and 1s and an integer k, return True if all 1's are // at least k places away from each other, otherwise return False. // https://leetcode.com/problems/check-if-all-1s-are-at-least-length-k-places-away/ constexpr auto k_length_apart = [](const auto& arr, int k) { return flow::split(arr, 1).map(flow::count).all(flow::pred::geq(k)); }; int main() { { constexpr auto nums = std::array{1, 0, 0, 0, 1, 0, 0, 0, 1}; constexpr auto k = 2; assert(k_length_apart(nums, k)); } { constexpr auto nums = std::array{1, 0, 0, 1, 0, 1}; constexpr auto k = 2; assert(not k_length_apart(nums, k)); } { constexpr auto nums = std::array{1, 1, 1, 1, 1}; constexpr auto k = 0; assert(k_length_apart(nums, k)); } { constexpr auto nums = std::array{0, 1, 0, 1}; constexpr auto k = 1; assert(k_length_apart(nums, k)); } }
true
f78da060d8ec55e63f0c5b540a46be1d1f8b9662
C++
tylermccreary/CS420-Compilers
/buffer.cc
UTF-8
2,299
3.75
4
[]
no_license
#include "buffer.h" // Open the source file and initialize the buffer. Buffer::Buffer(char *filename) { source_file = new ifstream(filename); b = new list<char>(); fill_buf(); } // Close the file and cleanup. Buffer::~Buffer () { if(source_file -> is_open()) { source_file -> close(); } if(source_file != NULL) { delete source_file; } if(b != NULL) { delete b; } } // Remove the next character from the buffer and // return it. char Buffer::next_char() { if(b -> empty()) { fill_buf(); } char next = b -> front(); b -> pop_front(); return next; } // Put a character back at the front of the buffer. void Buffer::unread_char (char c) { b -> push_front(c); } /* If you encounter an error from which you can't recover, print an error message and call this method. */ void Buffer::buffer_fatal_error() { cout << "Buffer fatal Error" << endl; exit(0); } /* Fill the buffer from the file. The buffer filling code is where all the action happens in this class. This function is responsible for filling the buffer until it is full with characters from the file. Comments should be omitted, whitespace should be compressed to a single space character, and a '$' should be inserted at the end of the program to mark the end of the source file. */ void Buffer::fill_buf() { char this_char; char prev_char; int buf_len = 0; while(buf_len < MAX_BUFFER_SIZE && !source_file -> eof()) { prev_char = this_char; source_file -> get(this_char); if(!source_file -> eof()) { if(is_legal_char(this_char)) { if(this_char != COMMENT_MARKER) { if(!is_whitespace(this_char)) { b -> push_back(this_char); buf_len++; } else if(!is_whitespace(prev_char)) { b -> push_back(' '); buf_len++; } } else { while(this_char != '\n') { prev_char = this_char; source_file -> get(this_char); } } } else { buffer_fatal_error(); } } else { b -> push_back(EOF_MARKER); buf_len++; } } } // For debugging: dump the contents of the buffer on the screen. void Buffer::dump_b() { std::list<char>::iterator this_char; for(this_char = b -> begin(); this_char != b -> end(); ++this_char) { cout << *this_char ; } }
true
5ad002f6da091d64647c694714ede86e5918b9f7
C++
aleks73337/Lib
/Autor.cpp
UTF-8
277
2.78125
3
[]
no_license
#include "Autor.h" void Autor::setAutName(const std::string& name_) { autName = name_; } std::vector<Book>& Autor::getAutorBooks() { return (Books); } const std::string& Autor::getAutName() { return autName; } void Autor::addBook(Book& book) { Books.push_back(book); }
true
cccef5420f11417c076745a94e42f35c3ca37e02
C++
shayslonim/MileStone
/Expression/EqualsExpression.cpp
UTF-8
462
2.921875
3
[]
no_license
// // Created by shira on 12/24/18. // #include "EqualsExpression.h" /** * Evaluate == * @return double 0 or 1 */ double EqualsExpression::calculate() { double result = this->getLeft()->calculate() == this->getRight()->calculate() ? TRUE : FALSE; return result; } /** * Constructor * @param left Expression* * @param right Expression* */ EqualsExpression::EqualsExpression(Expression* left, Expression* right) : BinaryExpression(left, right) {}
true
ced2d3d5c1daee09f16b9827d32168854ea4139c
C++
ghali/gcb
/GLOW/03/determinant.h
UTF-8
1,443
2.6875
3
[]
no_license
/* The following code example is described in the book "Introduction * to Geometric Computing" by Sherif Ghali, Springer-Verlag, 2008. * * Copyright (C) 2008 Sherif Ghali. This code may be freely copied, * modified, or republished electronically or in print provided that * this copyright notice appears in all copies. This software is * provided "as is" without express or implied warranty; not even for * merchantability or fitness for a particular purpose. */ #ifndef DETERMINANT_H #define DETERMINANT_H template<typename T> T determinant(const T& a, const T& b, const T& c, const T& d) { return a * d - b * c; } template<typename T> T determinant(const T& a, const T& b, const T& c, const T& d, const T& e, const T& f, const T& g, const T& h, const T& i) { return a * determinant(e,f,h,i) - b * determinant(d,f,g,i) + c * determinant(d,e,g,h); } template<typename T> T determinant(const T& a, const T& b, const T& c, const T& d, const T& e, const T& f, const T& g, const T& h, const T& i, const T& j, const T& k, const T& l, const T& m, const T& n, const T& o, const T& p) { return a * determinant(f,g,h, j,k,l, n,o,p) - b * determinant(e,g,h, i,k,l, m,o,p) + c * determinant(e,f,h, i,j,l, m,n,p) - d * determinant(e,f,g, i,j,k, m,n,o); } #endif // DETERMINANT_H
true
1abe9eb3a9fa52bee2a784605c739c84af905709
C++
flexatone/arachnewarp
/awmonodim/src/core/aw_Output.cpp
UTF-8
3,539
2.59375
3
[]
no_license
/*! \file aw_Output.cpp \brief Object model of output stream Created by Christopher Ariza on 6/30/10. Copyright 2010 Flexatone HFP. All rights reserved. */ #include <sndfile.hh> #include <boost/scoped_array.hpp> #include "aw_Output.h" #include "aw_Generator.h" namespace aw { // ============================================================================= Output :: Output(aw::SystemPtr o) : sys_(o) // initialize { } // ============================================================================= int Output :: write(aw::GeneratorPtr gen, double dur, char* fp, int fileFormat) { // char* outfilename="/Volumes/xdisc/_sync/_x/src/arachneWarp/out/foo.wav"; // should determine file format by file extension // sample format is indepedent of System settings int unsigned format = fileFormat; int unsigned channels; // number of channels is dependent on generator type if (gen->getGeneratorType() == aw::gTypeMono) { channels = 1; } else { // a gTypePoly channels = 2; } SndfileHandle outfile(fp, SFM_WRITE, format, channels, sys_->getSamplingRate()); if (not outfile) return -1; // create an array of the necessary size based on sampling rate and dur // dur is given in floating point seconds: // means this is being casted to an integer aw::Int64Unsigned sampleCount = sys_->getSamplingRate() * dur; std::clog << "about to write samples samples: " << sampleCount << " gen->getGeneratorType(): " << gen->getGeneratorType() << " to: " << fp << std::endl; // must declare sample array within scope of each branch if (gen->getGeneratorType() == aw::gTypeMono) { // other methods of creating storage array, pre file writing, led // to problems over a certain size; thus, a dynamic array must be used // the boost scoped array manages deletion // other approaches that work //float *sample = new float [sampleCount]; //float sample[sampleCount]; // this fails over a certain size boost::scoped_array<float> sample(new float[sampleCount]); // write each sample for (unsigned int i=0; i<sampleCount; i++) { //std::clog<< "writing samples: " << i << std::endl; sample[i] = gen->getValueAtSample(i); } // pass a pointer to the first array index, as well as the size outfile.write(&sample[0], sampleCount); } else { // interleaved, twice as large //const unsigned int size = sampleCount * 2; //float sample[size]; boost::scoped_array<float> sample(new float[sampleCount * 2]); // get a pointer to double aw::WorkingArrayPtr outPoly; for (unsigned int i=0; i<sampleCount; i++) { // pointer to poly array outPoly = gen->getPolyAtSample(i); // get first two values in array sample[2*i] = outPoly[0]; sample[(2*i)+1] = outPoly[1]; } outfile.write(&sample[0], sampleCount * 2); } return 0; } int Output :: write(aw::GeneratorPtr gen, double dur, char* fp) { int format = SF_FORMAT_WAV | SF_FORMAT_PCM_16; return write(gen, dur, fp, format); } int Output :: write(aw::GeneratorPtr gen, double dur) { // cast const to normal char* char* fp=(char*)"/Volumes/xdisc/_sync/_x/src/arachnewarp/arachnewarp/out/audio/foo.wav"; int format = SF_FORMAT_WAV | SF_FORMAT_PCM_16; return write(gen, dur, fp, format); } } // end namespace aw
true
90aa8564de6bc31f08d788d697d842774eb0fe3f
C++
lljjff/PCA
/princomp.cpp
UTF-8
6,971
2.84375
3
[]
no_license
#include "princomp.h" #include <math.h> #include <QLineF> #include <QPointF> #include <QDebug> namespace pca { int PrinComp::m_dimension = 2; // Вычисление средних void PrinComp::computeMeans(vector<QPointF> points, vector<double> & means) { // Инициализация means[0] = 0; means[1] = 0; for (unsigned i = 0; i < points.size(); i++) means[0] += points[i].x(), means[1] += points[i].y(); means[0] /= points.size(), means[1] /= points.size(); } // Вычисление ковариационной матрицы void PrinComp::computeCovarianceMatrix(vector<QPointF> points, vector<double> means, vector< vector<double> > & covarianceMatrix) { // // Вычисление средних // vector<double> means(DIMENSION); // computeMeans(points, means); // Вычисление ковариационной матрицы for (int i = 0; i < m_dimension; i++) { for (int j = i; j < m_dimension; j++) { covarianceMatrix[i][j] = 0.0; for (unsigned k = 0; k < points.size(); k++) { double coord_i = (i == 0) ? points[k].x() : points[k].y(); double coord_j = (j == 0) ? points[k].x() : points[k].y(); covarianceMatrix[i][j] += (means[i] - coord_i) * (means[j] - coord_j); } covarianceMatrix[i][j] /= points.size() - 1; // В силу симметричности ковариационной матрицы if (i != j) covarianceMatrix[j][i] = covarianceMatrix[i][j]; } } return; } // Вычисление собственных значений void PrinComp::computeEigenValues(vector< vector<double> > covarianceMatrix, vector<double> & eigenValues) { // Инициализация eigenValues[0] = 0; eigenValues[1] = 0; // // Вычисление ковариационной матрицы // vector< vector<double> > covarianceMatrix(DIMENSION, vector<double>(DIMENSION)); // computeCovarianceMatrix(points, covarianceMatrix); // Вычисление собственных значений: // Решаем характеристическое уранение (квадратное) double a = covarianceMatrix[0][0]; double b = covarianceMatrix[1][0]; // covarianceMatrix[1][0] == covarianceMatrix[0][1]; double d = covarianceMatrix[1][1]; // Корень из дискриминанта (после упрощения) double discriminantSqrt = sqrt( pow((a - d), 2) + (4 * pow(b, 2) ) ); eigenValues[0] = ( (a + d) + discriminantSqrt ) / 2; eigenValues[1] = ( (a + d) - discriminantSqrt ) / 2; } // Вычисление собственных векторов void PrinComp::computeEigenVectors(vector< vector<double> > covarianceMatrix, vector<double> eigenValues, vector< vector<double> > & eigenVectors) { // Собственные векторы double aplus = covarianceMatrix[0][0] + covarianceMatrix[0][1] - eigenValues[1]; double bplus = covarianceMatrix[1][1] + covarianceMatrix[0][1] - eigenValues[1]; double aminus = covarianceMatrix[0][0] + covarianceMatrix[0][1] - eigenValues[0]; double bminus = covarianceMatrix[1][1] + covarianceMatrix[0][1] - eigenValues[0]; // Нормализация double denomPlus = sqrtf(aplus*aplus + bplus*bplus); double denomMinus= sqrtf(aminus*aminus + bminus*bminus); eigenVectors[0][0] = aplus / denomPlus; eigenVectors[0][1] = bplus / denomPlus; eigenVectors[1][0] = aminus / denomMinus; eigenVectors[1][1] = bminus / denomMinus; } // Последовательное вычисление необходимых данных void PrinComp::computePCAData(vector<QPointF> points, vector<double> & means, vector< vector<double> > & covarianceMatrix, vector<double> & eigenValues, vector< vector<double> > & eigenVectors) { // Вычисление средних computeMeans(points, means); // Вычисление ковариационной матрицы computeCovarianceMatrix(points, means, covarianceMatrix); // Вычисление собственных значений computeEigenValues(covarianceMatrix, eigenValues); // Вычисление собственных векторов computeEigenVectors(covarianceMatrix, eigenValues, eigenVectors); } /* ----------------------------------------------------- */ // Вычисление центральной точки QPointF PrinComp::computeMeanPoint(vector<QPointF> points) { // Вычисление средних vector<double> means(m_dimension); computeMeans(points, means); // Центральная точка QPointF meanPoint(means[0], means[1]); return meanPoint; } // Вычисление главных компонент (первой и второй) vector<QLineF> PrinComp::computePCA(vector<QPointF> points) { // Вычисляем необходимые данные vector<double> means(m_dimension); vector< vector<double> > covarianceMatrix(m_dimension, vector<double>(m_dimension)); vector<double> eigenValues(m_dimension); vector< vector<double> > eigenVectors(m_dimension, vector<double>(m_dimension)); computePCAData(points, means, covarianceMatrix, eigenValues, eigenVectors); // Вычисляем главные компоненты (первую и вторую) QLineF firstPrincipalComponent; QLineF secondPrincipalComponent; // Полуоси (первой и второй главных компонент) double k = 2; // scale factor double majoraxis = k*sqrtf(eigenValues[0]); double minoraxis = k*sqrtf(eigenValues[1]); // Первая главная компонента QPointF start (means[0] - eigenVectors[0][0] * majoraxis, means[1] - eigenVectors[0][1] * majoraxis); QPointF finish(means[0] + eigenVectors[0][0] * majoraxis, means[1] + eigenVectors[0][1] * majoraxis); firstPrincipalComponent.setPoints(start, finish); // Вторая главная компонента QPointF secondStart (means[0] - eigenVectors[1][0] * minoraxis, means[1] - eigenVectors[1][1] * minoraxis); QPointF secondFinish(means[0] + eigenVectors[1][0] * minoraxis, means[1] + eigenVectors[1][1] * minoraxis); secondPrincipalComponent.setPoints(secondStart, secondFinish); vector<QLineF> PCAVectors; PCAVectors.push_back(firstPrincipalComponent); PCAVectors.push_back(secondPrincipalComponent); return PCAVectors; } } // namespace
true
4be3938898281df493911be56c7044d53e5ab990
C++
alexandrekcosta/cpp
/cprojects/mathOperations/main.cpp
UTF-8
463
3.703125
4
[]
no_license
#include <iostream> using namespace std; int n1,n2;//Global variables int main() { int n3,n4; //Local variables //Operators: + - / * % () int r,r1,r2; n1 = 11; n2 = 3; n3 = 5; n4 = 2; r = (n1+n2)*n4; r1 = n1/n2; r2 = n1%n2; cout<<"Sum equals: " << r <<endl; cout<<"Division equals: " << r1 <<endl; cout<<"Mod equals: " << r2 <<endl; return 0; }
true
c983670b82fce01867c25ae64f4652150045f809
C++
dakins1/dabs
/hw5_FileLinkedList/ArrayListTestCode.cpp
UTF-8
1,937
3.046875
3
[]
no_license
#include <iostream> using namespace std; #include "FileArrayList.h" int main() { //testing opening FileArrayList<int> testOpen("myFile.txt"); //if (testOpen.size() != 0) cout << "initializer test failed\n"; //push_back for (int i=0; i!=10; i++) { testOpen.push_back(i); if (testOpen[i] != i) cout << "push_back test failed at " << i << endl; } if (testOpen[0] == testOpen.size()) cout << "something wrong with the sz\n"; int initSz = testOpen.size(); for (int i=0; i!=10; i++) { testOpen.pop_back(); } if (testOpen.size() != initSz-10) cout << "something wrong with pop_back\n"; for (int i=0; i!=20; i++) { testOpen.push_back(i); } testOpen.clear(); if (testOpen.size() != 0) cout << "clear test failed\n"; for (int i=0; i!=20; i++) { testOpen.push_back(i); if (testOpen[i] != i) cout << "something went wrong after clear \n"; } int count = 0; for (auto iter=testOpen.begin(); iter!= testOpen.end(); iter++) { if (*iter != count) cout << "iter test failed\n"; if (*iter != testOpen[count]) cout << "iter fail\n"; count++; } testOpen.insert(--(--(--(--(testOpen.end())))), 42); if (testOpen[testOpen.size()-4] != 42) cout << "something wrong with insert\n"; count = 0; FileArrayList<int> testInsert("myFileTest.txt"); for (int i=0; i!=20; i++) { testInsert.push_back(i); } testInsert.insert(++(testInsert.begin()++), 42); if (testInsert[2] != 42) cout << "something wrong with insert\n"; if (testInsert.size() != 21) cout << "somethign wrong with size after insert\n"; testInsert.erase(++(++(testInsert.begin()++))); if (testInsert[2] == 42) cout << "something wrong with erase\n"; count =0; for (auto iter=testInsert.begin(); iter!= testInsert.end(); iter++) { if (*iter != count) cout << "erase failed\n"; count++; } }
true
472f25b7a2cf613d9966663221f2720746bf7410
C++
shaosHumbleAccount/roso_viz
/roso_viz/Setting/settingcenter.cpp
UTF-8
999
2.6875
3
[ "MIT" ]
permissive
#include "settingcenter.h" #include <QMessageBox> SettingCenter* global_settingCenter_instance = NULL; SettingCenter::SettingCenter(QObject *parent) : QObject(parent), settings("rosoviz.ini",QSettings::IniFormat) { if(!settings.contains("network/port")) { QMessageBox::warning(NULL, "rosoviz.ini NOT FOUND", "rosoviz.ini cannot be found. Please copy it to the same folder as the executable."); } } SettingCenter* SettingCenter::singleton() { if(!global_settingCenter_instance) { global_settingCenter_instance = new SettingCenter(); } return global_settingCenter_instance; } QVariant SettingCenter::getSettingValue(QString name) const { if(settings.contains(name)) { return settings.value(name); } else { return QVariant(); } } void SettingCenter::set_SettingValue(QString name, QVariant value) { settings.setValue(name, value); emit settingChanged(name,value); }
true
8b1196fe47755e56e4c5d133cb2a9c8792de124f
C++
YannDubs/modellingBacterias
/src/Lab/TwitchingBacterium.hpp
UTF-8
2,222
2.71875
3
[]
no_license
#ifndef TWITCHINGBACTERIUM_HPP #define TWITCHINGBACTERIUM_HPP #include "Bacterium.hpp" #include "Grip.hpp" #include "Utility/Vec2d.hpp" //il faut prédeclarer chaque nutriment pour casser la dependance circulaire class Nutriment; class NutrimentA; class NutrimentB; enum States { IDLE, WAIT_TO_DEPLOY, DEPLOY, ATTRACT, RETRACT, EAT }; class TwitchingBacterium : public Bacterium { public: //CONSTRUCTEUR TwitchingBacterium (Vec2d const& position); //CONSTRUCTEUR DE COPIE // onfait une surcharge pour faciliter la maintenance pour ne // par avoir à changer le constructuer de copie TwitchingBacterium(TwitchingBacterium const& autre, int const& valeur); //on réinitialise le constructeur par défaut pour pouvoir le //rappeler dans la copie (nous sert justepour incrémenter le compteur TwitchingBacterium(TwitchingBacterium const& autre) = default; //METHODES //notre fonction moveGrip est fondamentalement pensée différemment //afin d'éviter des duplications de code nous utilisions donc //pour passer les test une valeur par defaut de dt qui est 1 //vu que pour nous le move grip a pas besoin de dt mais que //vous l'appeler sans dt (il faudrais mieux theoriquement //changer votre code ) void moveGrip (Vec2d const& direction, sf::Time const& dt = sf::seconds(1)); //GETTEURS Quantity getConsommationMove() const; Quantity getConsommationTentacle() const; //METHODES OVERRIDE virtual void drawOn (sf::RenderTarget& target) const override; //VIRTUAL PUR OVERRIDE virtual Bacterium* copie() const override; virtual Quantity getConsoEnergy() const override; virtual void move (sf::Time dt) override; j::Value& getConfig() const override; //SURCHARGE DE METHODE VIRTUELLE PURES OVERRIDE virtual Quantity eatableQuantity (NutrimentA& nutriment) override; virtual Quantity eatableQuantity (NutrimentB& nutriment) override; //STATIC static unsigned int getTwitchingCompteur(); static void resetTwitchingCompteur(); //DESTRUCTEUR virtual ~TwitchingBacterium(); private: Grip m_grip; States m_state; static unsigned int twitchingBacteriumCompteur; }; #endif
true
02d96df89c1bd728887719057d45857884799882
C++
deliangyang/Data-Structure
/chapter14/14.12/Dict.h
UTF-8
1,534
3.15625
3
[]
no_license
#ifndef __DICT_H__ #define __DICT_H__ #include "HashTable.h" #include "KeyValue.h" #include "HashTableIterator.h" #include "Linked.h" template<class K, class V> class Dict:public HashTable<KeyValue<K, V> > { public: // destructor Dict(const V &defval, unsigned long hashf(KeyValue<K, V> key)); // operator method V &operator[](const K &key); // adjust the element is exsit or not int InDict(const K &key); // delete the element if exsit void DeleteKey(const K &key); private: V defvalue; }; template<class K, class V> Dict<K, V>::Dict(const V &defval, unsigned long hashf(KeyValue<K, V> key)): HashTable<KeyValue<K, V> >(26, hashf), defvalue(defval) {} template<class K, class V> V &Dict<K, V>::operator [](const K &key) { KeyValue<K, V> temp(key, defvalue); if(!Find(temp)) Insert(temp); // is not find int hashval=int(hf(temp)%numBuckets); // get hash code Linked<KeyValue<K, V> > &lst=buckets[hashval]; for(lst.Reset(); !lst.EndOfList(); lst.Next()) if(lst.Data()==temp) return lst.Data().value; /* HashTableIterator<KeyValue<K, V> > iterator(temp); for(iterator.Reset(); !iterator.EndOfList(); iterator.Next()) if(iterator.Data()==temp) return iterator.Data().value; */ //return defvalue; } template<class K, class V> int Dict<K, V>::InDict(const K &key) { KeyValue<K, V> temp(key, defvalue); if(Find(temp)) return 1; return 0; } template<class K, class V> void Dict<K, V>::DeleteKey(const K &key) { KeyValue<K, V> temp(key, defvalue); if(Find(temp)) Delete(temp); } #endif
true
e2b7925a7a8b4cb99b0396f2f9c99b181409027d
C++
gitgaoqian/C
/BalanceBinaryTree/balancebinarytree.cpp
UTF-8
2,321
3.421875
3
[]
no_license
//关于平衡二叉树学习内容比较复杂一点.尤其是左平衡和右平衡函数.没有掌握 //平衡二叉树接口 #define LH 1 #define EH 0 #define RH -1 #define TREE_TYPE char //定义二叉树存储的数据类型 typedef struct BIT_NODE { TREE_TYPE data; int bf;//相比二叉树,增加BF因子 struct BIT_NODE *lchild; struct BIT_NODE *rchild; } BITNode, *BITree; //右旋函数 void R_Rotation(BITree *T)//传入最小非平衡树, { BITree L; L=(*T)->lchild; (*T)->lchild=L->rchild; L->rchild=(*T); *T=L; } // 左旋函数 void L_Rotation(BITree *T)//传入最小非平衡树, { BITree R; R=(*T)->rchild; (*T)->rchild=R->lchild; R->lchild=(*T); *T=R; } void LeftBalance(BITree *T)//解决LL和LR型 { BITree L,Lr; L = (*T)->lchild; switch(L->bf) { case LH://右旋处理,LL型 (*T)->bf=L->bf=EH; R_Rotation(T); break; case RH://根节点和左子树的符号不同,要先左旋再右旋,LR型 Lr=L->rchild; switch(Lr->bf) { case LH: (*T)->bf=RH; L->bf=EH; break; case EH: (*T)->bf=L->bf=EH; break; case RH: (*T)->bf=EH; L->bf=LH; break; } Lr->bf=EH; L_Rotation(&(*T)->lchild); R_Rotation(T); } } void RightBalance(BITree *T) { BITree R,Rl; R = (*T)->rchild; switch (R->bf) { case RH://右旋处理 (*T)->bf=R->bf=EH; L_Rotation(T); break; case LH://根节点和左子树的符号不同,要先左旋再右旋 Rl=R->lchild; switch(Rl->bf) { case RH: (*T)->bf=LH; R->bf=EH; break; case EH: (*T)->bf=R->bf=EH; break; case LH: (*T)->bf=EH; R->bf=RH; break; } Rl->bf=EH; R_Rotation(&(*T)->rchild); L_Rotation(T); } }
true
ea55ea7a66b7a42ad81aee9649303b27aed8018a
C++
juwon0605/algorithm_basics
/1.코드구현력 기르기/07. 영어단어 복구.cpp
UTF-8
1,213
3.078125
3
[]
no_license
// #define _CRT_SECURE_NO_WARNINGS #include<iostream> #include<string> using namespace std; /* 7. 영어단어 복구 현수의 컴퓨터가 바이러스에 걸려 영어단어가 뛰어쓰기와 대소문자가 혼합되어 표현된다. 예를 들면 아름다운 이란 뜻을 가지고 있는 beautiful 단어가 “bE au T I fu L” 과 같이 컴퓨터에 표시되고 있습니다. 위와 같이 에러로 표시되는 영어단어를 원래의 표현대로 공백을 제거하고 소문자화 시켜 출력하는 프로그램을 작성하세요. */ int main() { // freopen("input.txt", "rt", stdin); string text; string correct; getline(cin, text); for (unsigned int i = 0; i < text.length(); i++) { if (text[i] != ' ') { correct += text[i]; } } for (unsigned int i = 0; i < correct.length(); i++) { correct[i] = tolower(correct[i]); } cout << correct; } /* 모범 답안 #include<stdio.h> using namespace std; int main(){ //freopen("input.txt", "rt", stdin); char a[101], b[101]; int i, p=0; gets(a); for(i=0; a[i]!='\0'; i++){ if(a[i]!=' '){ if(a[i]>=65 && a[i]<=90){ b[p++]=a[i]+32; } else b[p++]=a[i]; } } b[p]='\0'; printf("%s\n", b); return 0; } */
true
5fda5ae272f516ecf6df5ffb352a10ed781c908f
C++
SeoGB/exam
/GraphicEditor/GEllipse.cpp
UHC
14,035
2.546875
3
[]
no_license
/* [ GEllipse Ŭ by ] ** GEllipse Ŭ Ӽ ŬԴϴ. */ #include "StdAfx.h" #include "GEllipse.h" enum POSITION_LIST {TOPLEFT, HALFTOPLEFT, BOTTOMLEFT, HALFBOTTOMLEFT, BOTTOMRIGHT, HALFBOTTOMRIGHT, TOPRIGHT, HALFTOPRIGHT}; IMPLEMENT_SERIAL(GEllipse, GObject, 0) //-------------------------------------------------------------------------- // Ҹ //-------------------------------------------------------------------------- // //hhh GEllipse::GEllipse(void) { GObject::m_sType = ELLIPSE; } // GEllipse::GEllipse(const GEllipse& pGEllipse) { this->GObject::m_sType = pGEllipse.GObject::m_sType; this->GObject::m_sStartPoint = pGEllipse.GObject::m_sStartPoint; this->GObject::m_sEndPoint = pGEllipse.GObject::m_sEndPoint; this->GObject::m_sLineColor = pGEllipse.GObject::m_sLineColor; this->GObject::m_nsThickness = pGEllipse.GObject::m_nsThickness; this->GObject::m_bsGrouped = pGEllipse.GObject::m_bsGrouped; this->m_nsPenStyle = pGEllipse.m_nsPenStyle; this->m_pBrushColor = pGEllipse.m_pBrushColor; } // Ҹ GEllipse::~GEllipse(void) { } //-------------------------------------------------------------------------- //ȭ by ö //-------------------------------------------------------------------------- void GEllipse::Serialize(CArchive& ar) { GObject::Serialize(ar); if(ar.IsStoring()) // { ar << (WORD)m_nsPenStyle; ar << m_pBrushColor; ar << (WORD)m_esBrushStyle; ar << (WORD)m_esFaceType; ar << (WORD)m_npGrdMode; ar << (WORD)m_nsHatchStyle; ar << (WORD)m_nsLineJoin; ar << this->m_sGrdEndColor; } else //ε { WORD wTemp; ar >> wTemp; m_nsPenStyle = wTemp; ar >> m_pBrushColor; ar >> wTemp; m_esBrushStyle = (GBrushType)wTemp; ar >> wTemp; m_esFaceType = (GFaceType)wTemp; ar >> wTemp; m_npGrdMode = wTemp; ar >> wTemp; m_nsHatchStyle = wTemp; ar >> wTemp; m_nsLineJoin = wTemp; ar >> m_sGrdEndColor; } } //-------------------------------------------------------------------------- // Լ(̵) //-------------------------------------------------------------------------- void GEllipse::Move(int dX, int dY){ GObject::m_sStartPoint.Offset(dX, dY); GObject::m_sEndPoint.Offset(dX, dY); } //-------------------------------------------------------------------------- // Լ //-------------------------------------------------------------------------- CRgn* GEllipse::GetRegion() { // 簢 CRect rect(GObject::m_sStartPoint, GObject::m_sEndPoint); // β ʹ Ƿ ⺻ ũ 5 int dx = (int)(m_nsThickness > 4 ? m_nsThickness : 5); int dy = (int)(m_nsThickness > 4 ? m_nsThickness : 5); m_sRgn.DeleteObject(); // ̹ ִٸ // 籸 GObject::m_sRgn.CreateRectRgn(rect.TopLeft().x - m_nsThickness/2-1, rect.TopLeft().y - m_nsThickness/2-1, rect.BottomRight().x + m_nsThickness/2+1, rect.BottomRight().y + m_nsThickness/2+1); return &m_sRgn; } //------------------------------------------------------------- // ũ 缳 Լ // : ڷ Ѿ Ʈ ġ ľ // 8 Ǿִ 簢 ϸ ȴ // * * * // * * * // * * * // ݽð TOPLEFT -> HALFTOPLEFT -> BOTTOMLEFT // HALFBOTTOMLEFT -> BOTTOMRIGHT -> HALFBOTTOMRIGHT // TOPRIGHT -> HALFTOPRIGHT //------------------------------------------------------------- void GEllipse::Resize(int index, int dX, int dY) { if(GObject::m_bsGrouped == FALSE) //׷ȭ Ǿ { switch(index) { case TOPLEFT : GObject::m_sStartPoint.Offset(dX, dY); break; case HALFTOPLEFT : GObject::m_sStartPoint.Offset(dX, 0); break; case BOTTOMLEFT : GObject::m_sStartPoint.x += dX; GObject::m_sEndPoint.y += dY; break; case HALFBOTTOMLEFT : GObject::m_sEndPoint.Offset(0, dY); break; case BOTTOMRIGHT : GObject::m_sEndPoint.Offset(dX, dY); break; case HALFBOTTOMRIGHT : GObject::m_sEndPoint.Offset(dX, 0); break; case TOPRIGHT : GObject::m_sEndPoint.x += dX; GObject::m_sStartPoint.y += dY; break; case HALFTOPRIGHT : GObject::m_sStartPoint.Offset(0, dY); break; } } else // ׷ȭ Ǿִ { switch(index) { case TOPLEFT: GObject::m_sStartPoint.Offset(dX, dY); break; } } } //-------------------------------------------------------------------------- //Ʈ ġ ã Լ //-------------------------------------------------------------------------- int GEllipse::FindSelectPoint(CPoint pt) { int pos = -1; int i; CRgn rgn[8]; int tempThick = (GObject::m_nsThickness > 4 ? GObject::m_nsThickness : 5); // ⺻ ũ 5 // Rect TopLeft ġ // TopLeft ݽð 8 Rgn // * * * // * * // * * * CRect rect(GObject::m_sStartPoint, GObject::m_sEndPoint); // TopLeft rgn[0].CreateEllipticRgn(rect.TopLeft().x - tempThick, rect.TopLeft().y - tempThick, rect.TopLeft().x + tempThick, rect.TopLeft().y + tempThick); // TopLeft Rect ݸŭ rgn[1].CreateEllipticRgn(rect.TopLeft().x - tempThick, rect.CenterPoint().y - tempThick, rect.TopLeft().x + tempThick, rect.CenterPoint().y + tempThick); // TopLeft Rect ̸ŭ rgn[2].CreateEllipticRgn(rect.TopLeft().x - tempThick, rect.BottomRight().y - tempThick, rect.TopLeft().x + tempThick, rect.BottomRight().y + tempThick); // BottomRight Rect ʺ ݸŭ ̵ rgn[3].CreateEllipticRgn(rect.CenterPoint().x - tempThick, rect.BottomRight().y - tempThick, rect.CenterPoint().x + tempThick, rect.BottomRight().y + tempThick); // BottomRight rgn[4].CreateEllipticRgn(rect.BottomRight().x - tempThick, rect.BottomRight().y - tempThick, rect.BottomRight().x + tempThick, rect.BottomRight().y + tempThick); // BottomRight Rect ݸŭ ö rgn[5].CreateEllipticRgn(rect.BottomRight().x - tempThick, rect.CenterPoint().y- tempThick, rect.BottomRight().x + tempThick, rect.CenterPoint().y + tempThick); // BottomRight Rect ̸ŭ ö rgn[6].CreateEllipticRgn(rect.right - tempThick, rect.top - tempThick, rect.right + tempThick, rect.top + tempThick); // TopLeft Rect ʺ ݸŭ ̵ rgn[7].CreateEllipticRgn(rect.CenterPoint().x - tempThick, rect.TopLeft().y - tempThick, rect.CenterPoint().x + tempThick, rect.TopLeft().y + tempThick); // ãϴ ġ ã for(i = 0; i < 8; i++) { if(rgn[i].PtInRegion(pt) == TRUE) { pos = i; i = 8; } } return pos; } //-------------------------------------------------------------------------- // Ÿ Լ //-------------------------------------------------------------------------- void GEllipse::SetFaceType(int faceType) { m_esFaceType = (GFaceType)faceType; } //-------------------------------------------------------------------------- //귯 Լ //-------------------------------------------------------------------------- void GEllipse::SetBrushStyle(int brushStyle) { this->m_esBrushStyle = (GBrushType)brushStyle; } //-------------------------------------------------------------------------- //귯 Լ //-------------------------------------------------------------------------- void GEllipse::SetBrushColor(COLORREF brushColor) { this->m_pBrushColor = brushColor; } //-------------------------------------------------------------------------- // Ÿ Լ //-------------------------------------------------------------------------- void GEllipse::SetPenStyle(int penStyle) { m_nsPenStyle = penStyle; } //-------------------------------------------------------------------------- //ġ Ÿ Լ //-------------------------------------------------------------------------- void GEllipse::SetHatchStyle(int hatch) { this->m_nsHatchStyle = hatch; } //-------------------------------------------------------------------------- // Ÿ Լ //-------------------------------------------------------------------------- void GEllipse::SetLineJoinStyle(int lineJoin) { this->m_nsLineJoin = lineJoin; } //-------------------------------------------------------------------------- //׶Ʈ Լ // : Horizontal, Vertical, ForwardDiagonal, BackwardDiagonal //-------------------------------------------------------------------------- void GEllipse::SetGradientMode(int grdMode) { this->m_npGrdMode = grdMode; } //-------------------------------------------------------------------------- //׶̼ Լ //-------------------------------------------------------------------------- void GEllipse::SetGrdEndColor(COLORREF grdEndColor) { this->m_sGrdEndColor = grdEndColor; } //-------------------------------------------------------------------------- //׸ Լ //-------------------------------------------------------------------------- void GEllipse::Draw(CDC* cdc) { Graphics graphics(*cdc); graphics.SetSmoothingMode(SmoothingModeHighQuality); // Antialiasing // ÷ İ Color penColor = GObject::COLORREFtoColor(GObject::m_sLineColor); Color foreColor = GObject::COLORREFtoColor(this->m_pBrushColor); Color gradientColor = GObject::COLORREFtoColor(this->m_sGrdEndColor); Pen pen(penColor, REAL(m_nsThickness)); pen.SetLineJoin((LineJoin)this->m_nsLineJoin); // (ܰ ) GObject::SetDashStyle(pen, this->m_nsPenStyle); // Rect tempRect(GObject::m_sStartPoint.x, GObject::m_sStartPoint.y, GObject::m_sEndPoint.x - GObject::m_sStartPoint.x, GObject::m_sEndPoint.y - GObject::m_sStartPoint.y); //귯 SolidBrush pSolidBrush(foreColor); //ܻ 귯 HatchBrush pHatchBrush((HatchStyle)m_nsHatchStyle, foreColor, Color::Transparent); //ڹ 귯 LinearGradientBrush sGradientBrush(tempRect, foreColor, gradientColor, (LinearGradientMode)m_npGrdMode); //׶Ʈ 귯 // ä switch(m_esBrushStyle) //귯 ŸϿ б { case SOLID: //ܻ Ÿ if(m_esFaceType != OUTLINE) //ܰ ׸Ⱑ ƴ ä graphics.FillEllipse(&pSolidBrush, tempRect); break; case HATCH: //ڹ Ÿ if(m_esFaceType != OUTLINE) //ܰ ׸Ⱑ ƴ ä graphics.FillEllipse(&pHatchBrush, tempRect); break; case GRADIENT: //׶Ʈ Ÿ if(m_esFaceType != OUTLINE) //ܰ ׸Ⱑ ƴ ä graphics.FillEllipse(&sGradientBrush, tempRect); break; } //ܰ ׸ if(m_esFaceType != FILLONLY) graphics.DrawEllipse(&pen, tempRect); // if(this->m_npBrushStyle == BS_SOLID) { // SolidBrush pSolidBrush(foreColor); // graphics.DrawEllipse(&pen, tempRect); // graphics.FillEllipse(&pSolidBrush, tempRect); // } // else { // //HatchBrush pHatchBrush((HatchStyle)this->m_nsHatchStyle, foreColor, Color::Transparent); // HatchBrush pHatchBrush((HatchStyle)HatchStyleHorizontal, foreColor, Color::Transparent); // graphics.DrawEllipse(&pen, tempRect); // graphics.FillEllipse(&pHatchBrush, tempRect); // } /* CPen pen(m_nsPenStyle, GObject::m_nsThickness, GObject::m_sLineColor); // CPen *oldPen = cdc->SelectObject(&pen); // CBrush brush; if(m_npBrushStyle == BS_SOLID) { // BS_SOLID Ÿϰ brush.CreateSolidBrush(m_pBrushColor); // SOLID 귯 } else { brush.CreateHatchBrush(m_lpHatchStyle, m_pBrushColor); // HATCH 귯 } CBrush *oldBrush = cdc->SelectObject(&brush); // 귯ü CRect rect(GObject::m_sStartPoint, GObject::m_sEndPoint); // Rect cdc->Ellipse(rect); //Ÿ ׸ cdc->SelectObject(&oldPen); // ǵ cdc->SelectObject(&oldBrush); // 귯 ǵ*/ } //-------------------------------------------------------------------------- // ׸ Լ by ö //-------------------------------------------------------------------------- void GEllipse::DrawSelectLine(CDC *pDC) { //׸ Ӽ pDC->SelectStockObject(NULL_BRUSH); CPen penDotted(PS_DOT, 1, RGB(51,94,168)); // dot Ÿ CPen* oldPen = pDC->SelectObject(&penDotted); // dot Ÿ CRect rect; GetRegion()->GetRgnBox(rect); // 簢 pDC->Rectangle(rect); //簢 ׸ //׸ Ӽ CBrush brush(RGB(51,94,168)); //귯 CBrush* oldBrush = pDC->SelectObject(&brush); pDC->SelectStockObject(NULL_PEN); //NULL_PEN //ũ ġ CPoint sPointArray[8]; sPointArray[0] = rect.TopLeft(); sPointArray[1] = CPoint(rect.left, rect.CenterPoint().y); sPointArray[2] = CPoint(rect.left, rect.bottom); sPointArray[3] = CPoint(rect.CenterPoint().x, rect.bottom); sPointArray[4] = CPoint(rect.BottomRight()); sPointArray[5] = CPoint(rect.right, rect.CenterPoint().y); sPointArray[6] = CPoint(rect.right, rect.top); sPointArray[7] = CPoint(rect.CenterPoint().x, rect.top); //ũ ׸ for(int i=0;i<8;i++) pDC->Ellipse(sPointArray[i].x-5, sPointArray[i].y-5, sPointArray[i].x+5, sPointArray[i].y+5); // 귯 Ӽ ǵ pDC->SelectObject(oldPen); pDC->SelectObject(oldBrush); }
true
74a17d718caf97c4ad66792226a71234fdcc246a
C++
fofoni/atfa
/src/utils.h
UTF-8
4,079
2.515625
3
[]
no_license
/* * Universidade Federal do Rio de Janeiro * Escola Politécnica * Projeto Final de Graduação * Ambiente de Teste para Filtros Adaptativos * Pedro Angelo Medeiros Fonini * Orientador: Markus Lima */ /** * * \file utils.h * * Holds convenient definitions and other utilities. * * \author Pedro Angelo Medeiros Fonini */ #ifndef UTILS_H #define UTILS_H #include <sstream> #include <stdexcept> #include <QtCore> #ifndef ATFA_DIR # include <cstring> extern "C" { # include <libgen.h> } char static_filename[] = __FILE__; char static_dirname[] = __FILE__; char static_projdirname[] = __FILE__; // watch out, because dirname() may modify its argument, // and also, ATFA_DIR might get evaluated more than once /// Macro for getting the path to the project directory from cmake /** Should be passed from `CMakeLists.txt`, but if it's not, we try to deduce it from the `__FILE__` macro */ # define ATFA_DIR (static_cast<const char *>( \ std::strcpy(static_dirname, dirname(static_filename)), \ std::strcpy(static_filename, __FILE__), \ std::strcpy(static_projdirname, dirname(static_dirname)), \ static_projdirname \ )) #endif #define html_link(url) "<a href='" url "'>" url "</a>" #define html_email(address) "<a href='mailto:" address "'>" address "</a>" #define html_tt(text) "<span style='font-family: monospace'>" text "</span>" inline QString qt_html_tt(QString text) { return QStringLiteral("<span style='font-family: monospace'>") + text + QStringLiteral("</span>"); } /// Shorthand for the number \f$2\pi\f$. /** * Useful in the generation of the table of sines and cosines for the * Signal::DFTDriver class, for example. */ static constexpr double TAU = 6.283185307179586477; /// Initialize PortAudio. void portaudio_init(bool list_devices=false); /// Close PortAudio. void portaudio_end(); /// \brief A runtime exception while trying to process a file. /// /// Thrown when we cannot read a file, for some reason. /// /// Usage: /// /// if (error ocurred) throw FileError("badfile.wav"); /// /// Or: /// /// std::string filename; /// std::cin >> filename; /// ... /// if (error ocurred) throw FileError(filename); /// class FileError : public std::runtime_error { /// The message that will be displayed if we don't catch the exception. /** * Must be static, so that we can modify it inside the * `what()` `const` function, and read it after the * temporary object has been destroyed. */ static std::ostringstream msg; /// The name of the file that caused the error. const std::string filename; public: /// Constructs the exception object from the filename. /** * \param[in] fn A `std::string` that holds the filename. */ FileError(const std::string& fn) : runtime_error("File I/O error"), filename(fn) {} /// Destructor that does nothing. /** * Needed to prevent the `looser throw specifier` error because, * `std::runtime_error::~runtime_error()` is declared as `throw()` */ ~FileError() throw() {} /// Gives a description for the error. /** * Updates the \ref msg static member with the error * message, and returns it as a C string. */ virtual const char *what() const throw() { msg.str(""); // static member `msg' can be modified by const methods msg << runtime_error::what() << ": Couldn't read file `" << filename << "'."; return msg.str().c_str(); } }; // Compile-time utils namespace CTUtils { // compile-time exponentiation (using exponentiation-by-squaring algorithm) // Taken from: // http://stackoverflow.com/a/16443849 template<class T> inline constexpr T pow(const T base, unsigned const exponent) { return (exponent == 0) ? 1 : (exponent % 2 == 0) ? pow(base, exponent/2)*pow(base, exponent/2) : base * pow(base, (exponent-1)/2) * pow(base, (exponent-1)/2); } } QJsonObject read_json_file(const QString& filename); #endif // UTILS_H
true
9766377257df91a1d314947d881c8e12c6f93940
C++
varsanyikaroly/Munka
/amobaobjekt.cpp
UTF-8
4,710
3.265625
3
[]
no_license
#include <iostream> #include <vector> using namespace std; const int hossz = 9; // tárolja a bábukat, kirajzolja a táblát. class tabla { char helyek[hossz]; public: tabla(); void valaszthato(); void tablakiir (); bool lepes(int hova, char mit); char hely(int melyik); }; tabla::tabla(){ for (int i = 0; i < 9; i++){ helyek[i] = ' '; } } void tabla::valaszthato () { for (int i = 9; i > 0; i-= 3){ cout << "-------" << endl; cout << "|" << i-2 << "|" << i-1 << "|" << i << "|" << endl; } cout << "-------" << endl; } void tabla::tablakiir(){ for (int i = 8; i > 0; i-= 3){ cout << "-------" << endl; cout << "|" << helyek[i-2] << "|" << helyek [i-1] << "|" << helyek [i] << "|" << endl; } cout << "-------" << endl; } bool tabla::lepes(int hova, char mit) { if (hova < 0 || hova > 8) return false; if (helyek[hova] != ' ') return false; helyek[hova] = mit; return true; } char tabla::hely(int melyik) { if (melyik < 0 || melyik > 8) return ' '; return helyek[melyik]; } // tárolja a két bábu jelét struct babuk { //public: char jatekos1; char jatekos2; babuk(); }; babuk::babuk () { jatekos1 = 'X'; jatekos2 = 'O'; } // lebonyolítja a játékot, betartatja a szabályokat. class jatek { int hova; bool nyert; tabla t; // amikor létrejön a jatek osztály egy objektuma, akkor létrejön a t is. (jelen esetben paraméter nélküli konstruktor lefuttatásával) babuk bk; int kovi; public: jatek(); void lepes(); bool nyeres (); void lefolytat(); }; jatek::jatek()/* : t(ydkfmsmdkf, dfsfd)*/ { kovi = 0; } void jatek::lepes (){ int hova; bool jolepes; do { cout << "Adja meg hova szeretne lepni" << endl; cin >> hova; if (kovi % 2 == 0){ jolepes = t.lepes(hova-1, bk.jatekos1); // helyek[hova-1] = bk.jatekos1; }else{ jolepes = t.lepes(hova-1, bk.jatekos2); // helyek[hova-1] = bk.jatekos2; } if (!jolepes) { cout << "Huba van!" << endl; } } while (!jolepes); kovi++; } bool jatek::nyeres () { t.hely(4); if ((t.hely(0) == bk.jatekos1 && t.hely(1) == bk.jatekos1 && t.hely(2) == bk.jatekos1) || (t.hely(0) == bk.jatekos2 && t.hely(1) == bk.jatekos2 && t.hely(2) == bk.jatekos2)) return true; if (t.hely(3) == bk.jatekos1 && t.hely(4) == bk.jatekos1 && t.hely(5) == bk.jatekos1 || t.hely(3) == bk.jatekos2 && t.hely(4) == bk.jatekos2 && t.hely(5) == bk.jatekos2) return true; if (t.hely(6) == bk.jatekos1 && t.hely(7) == bk.jatekos1 && t.hely(8) == bk.jatekos1 || t.hely(6) == bk.jatekos2 && t.hely(7) == bk.jatekos2 && t.hely(8) == bk.jatekos2) return true; if (t.hely(1) == bk.jatekos1 && t.hely(4) == bk.jatekos1 && t.hely(7) == bk.jatekos1 || t.hely(1) == bk.jatekos2 && t.hely(4) == bk.jatekos2 && t.hely(7) == bk.jatekos2) return true; if (t.hely(0) == bk.jatekos1 && t.hely(3) == bk.jatekos1 && t.hely(6) == bk.jatekos1 || t.hely(0) == bk.jatekos2 && t.hely(3) == bk.jatekos2 && t.hely(6) == bk.jatekos2) return true; if (t.hely(2) == bk.jatekos1 && t.hely(5) == bk.jatekos1 && t.hely(8) == bk.jatekos1 || t.hely(2) == bk.jatekos2 && t.hely(5) == bk.jatekos2 && t.hely(8) == bk.jatekos2) return true; if (t.hely(0) == bk.jatekos1 && t.hely(4) == bk.jatekos1 && t.hely(8) == bk.jatekos1 || t.hely(0) == bk.jatekos2 && t.hely(4) == bk.jatekos2 && t.hely(8) == bk.jatekos2) return true; if (t.hely(6) == bk.jatekos1 && t.hely(4) == bk.jatekos1 && t.hely(2) == bk.jatekos1 || t.hely(6) == bk.jatekos2 && t.hely(4) == bk.jatekos2 && t.hely(2) == bk.jatekos2) return true; return false; } //ő a vezérlő void jatek::lefolytat (){ cout << "ket tablat lat ez elson a szabad lehetosegek helyet szammal jeloltuk" << endl << "a masodikon azt lethatja hogy all jelenleg a palya" << endl << "adjon meg egy szamot hova szeretne lepni" << endl; do { t.valaszthato(); t.tablakiir(); lepes(); if (kovi == 9){ cout << "a jatek kimenetele dontetlen lett!" << endl; t.tablakiir(); return; } }while (nyeres() == false); cout << "A jateknak vege a nyero allas: " << endl; t.tablakiir(); } int main () { jatek j; j.lefolytat(); return 0; }
true
5875acb0d9b6028472ff74338b998258fc4c8888
C++
manojk16/Dream_2019
/cpp_src/Increment_op_ooverloading.cc
UTF-8
987
3.8125
4
[]
no_license
/* * Increment_op_ooverloading.cc * * Created on: Jul 23, 2019 * Author: user1 */ #include <iostream> using namespace std; class Time { int hours; int minutes; public: Time() { hours = 0; minutes = 0; } Time(int h, int m) { hours = h; minutes = m; } void display() { cout << "Total Time is: " << hours << " hours " << "and " << minutes << endl; } // ++ Prefix Operator Overloading Time operator ++() { ++minutes; if (minutes >= 60) { ++hours; minutes -= 60; } if (hours >= 13) { hours %= 12; } return Time(hours, minutes); } // ++ Postfix Operator Overloading Time operator ++(int) { cout<<"Post Increment fucn get called " << "\n"; ++minutes; if (minutes >= 60) { ++hours; minutes -= 60; } if (hours >= 13) { hours %= 12; } return Time(hours, minutes); } }; int main(){ Time T1(11,59),T2(30,40); ++T1; T1.display(); ++T1; T1.display(); T2++; T2.display(); T2++; T2.display(); }
true
7382acea0b30fe3e7c9c04dadb6acf03ff93d700
C++
STEllAR-GROUP/hpx_historic
/examples_07.16.13/gravity/gravity_dataflow/gravity_dataflow.hpp
UTF-8
2,944
2.65625
3
[]
no_license
/////////////////////////////////////////////////////////////////////////////// /////////////////// Gravity Dataflow Header File //////////////////////// //Copyright (c) 2012 Adrian Serio // //Distributed under the Boost Software License, Version 1.0. (See accompanying //file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt /////////////////////////////////////////////////////////////////////////////// #include <string> #include <vector> #include <boost/shared_ptr.hpp> #include <boost/make_shared.hpp> #include <boost/serialization/base_object.hpp> using namespace std; using boost::serialization::access; class point { public: point(double xx, double yy, double zz, double mm, double vxx, double vyy, double vzz) :x(xx),y(yy),z(zz),m(mm),vx(vxx),vy(vyy),vz(vzz){} point():x(0),y(0),m(0),vx(0),vy(0),vz(0),fx(0),fy(0),fz(0),ft(0) {} ~point(){} double x; //x-coordinate double y; //y-coordinate double z; //z-coordinate double m; //mass double vx; //velocity in the x direction double vy; //velocity in the y direction double vz; //velocity in the z direction double fx; //force in the x direction double fy; //force in the y direction double fz; //force in the z direction double ft; //the sum of the forces }; class Vector_container { //This class wrapps a vecotr in a shared_ptr private: boost::shared_ptr<vector<point> > p; friend class boost::serialization::access; template <typename Archive> void serialize(Archive & ar,unsigned) { ar & p; } public: Vector_container(): p(boost::make_shared<vector<point> >()) {}; Vector_container(vector<point> vp) :p(boost::make_shared<vector<point> > (vp)) {}; ~Vector_container(){}; // Vector_container operator= (Vector_container, vector<point>) { // for(int i=0;i<pts.size();i++) { // p->at(i) // } point& operator [] (std::size_t c) { return p->at(c); } point const& operator [] (std::size_t c) const { return p->at(c); } }; struct components { double d; //distance double xc; //x-component double yc; //y-component double zc; //z-component }; struct config_f { string input; string output; uint64_t steps; uint64_t timestep; uint64_t print; uint64_t num_cores; }; //Serialization namespace boost{ namespace serialization{ template <typename Archive> void serialize(Archive & ar, point & a,unsigned) { ar & a.x & a.y & a.z & a.m & a.vx & a.vy & a.fz & a.vz & a.fx & a.fy & a.fz & a.ft; } template <typename Archive> void serialize(Archive & ar, components & a,unsigned) { ar & a.d & a.xc & a.yc & a.zc; } template <typename Archive> void serialize(Archive & ar, config_f & a,unsigned) { ar & a.input; ar & a.output; ar & a.steps; ar & a.timestep; } }} /////////////////////////////////////////////////////////////////////////////// //Global Variables //extern vector<vector<point> > pts_timestep; extern bool debug;
true
5beee550faa22fa46e3cd021218465e60e88cfb8
C++
leios/simuleios
/FDTD/inv_lens/geometrical.cpp
UTF-8
8,059
3.1875
3
[ "MIT" ]
permissive
/*-------------geometrical_optics.cpp-----------------------------------------// * * geometrical optics * * Purpose: to simulate light going through a lens with a variable refractive * index. Not wave-like. * * Notes: This file was mostly written by Gustorn. Thanks! * *-----------------------------------------------------------------------------*/ #include <array> #include <cassert> #include <cmath> #include <fstream> #include <iostream> /*----------------------------------------------------------------------------// * STRUCTS / FUNCTIONS *-----------------------------------------------------------------------------*/ // Constants const int NUM_LIGHTS = 10; const int TIME_RES = 500000; // A very simple vector type with operators that are used in this file struct vec { double x, y; vec() : x(0.0), y(0.0) {} vec(double x0, double y0) : x(x0), y(y0) {} }; // The static inlines are our best bet to force the inlining of the functions // without using platform-specific extensions static inline vec& operator+=(vec& a, vec b) { a.x += b.x; a.y += b.y; return a; } static inline vec operator-(vec a) { return vec(-a.x, -a.y); } static inline vec operator+(vec a, vec b) { return vec(a.x + b.x, a.y + b.y); } static inline vec operator-(vec a, vec b) { return vec(a.x - b.x, a.y - b.y); } static inline vec operator*(vec a, double b) { return vec(a.x * b, a.y * b); } static inline vec operator*(double a, vec b) { return b * a; } static inline vec operator/(vec a, double b) { double inv = 1.0 / b; return a * inv; } static inline double dot(vec a, vec b) { return a.x * b.x + a.y * b.y; } static inline double length(vec a) { return sqrt(dot(a, a)); } static inline vec normalize(vec a) { return a / length(a); } static inline double distance(vec a, vec b) { return length(a - b); } static inline bool is_null(vec a) { return a.x == 0.0 && a.y == 0.0; } // This normally wouldn't store the previous index, but there's no // ray-shape intersection code yet. struct ray { vec p, v; double previous_index; }; // A convenience shorthand so we don't have to write the full type everywhere using ray_array = std::array<ray, NUM_LIGHTS>; // A struct describing a simple lens. Add additional lenses by adding // a new struct and overloading the corresponding functions (see below) struct simple { double left, right; simple(double l, double r) : left(l), right(r) {} }; // A simple struct for circular / spherical lens struct sphere{ double radius; vec origin; sphere(double rad, double x, double y) : radius(rad), origin(x, y) {} }; // Add overloads for 'normal_at' and 'refractive_index_at' for your own stuff, // example (you'll need a separate struct for the different lenses): // // vec normal_at(const circle& lens, vec p) { ... } // double refractive_index_at(const circle& lens, vec p) { ... } bool inside_of(const simple& lens, vec p); bool inside_of(const sphere& lens, vec p); vec normal_at(const simple& lens, vec p); vec normal_at(const sphere& lens, vec p); double refractive_index_at(const simple& lens, vec p); double refractive_index_at(const sphere& lens, vec p); // Templated so it can accept any lens type. Stuff will dispatch at compile // time, so the performance will be good template <typename T> ray_array light_gen(vec dim, const T& lens, double max_vel, double angle); // Same as above template <typename T> void propagate(ray_array& rays, const T& lens, double step_size, double max_vel, std::ofstream &output); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main() { // defines output std::ofstream output("geometrical.dat", std::ofstream::out); vec dim = {4, 10}; double max_vel = 1; // Implement other lenses and change this line to use them sphere lens = {4, 5, 5}; ray_array rays = light_gen(dim, lens, max_vel, 0 /*0.523598776*/); propagate(rays, lens, 0.0001, max_vel, output); } /*----------------------------------------------------------------------------// * SUBROUTINE *-----------------------------------------------------------------------------*/ // Refracts the given normalized vector "l", based on the normalized normal "n" // and the given index of refraction "ior", where ior = n1 / n2 vec refract(vec l, vec n, double ior) { double c = dot(-n, l); double d = 1.0 - ior * ior * (1.0 - c * c); if (d < 0.0) { return vec(0.0, 0.0); } return ior * l + (ior * c - sqrt(d)) * n; } vec reflect(vec l, vec n) { return l - (2.0 * dot(n, l)) * n; } template <typename T> ray_array light_gen(vec dim, const T& lens, double max_vel, double angle) { ray_array rays; vec velocity = vec(cos(angle), sin(angle)) * max_vel; // Create rays for (size_t i = 0; i < rays.size(); i++) { rays[i].p = vec(0.0, 3 + i * dim.x / NUM_LIGHTS); rays[i].v = velocity; rays[i].previous_index = refractive_index_at(lens, rays[i].p); } return rays; } template <typename T> void propagate(ray_array& rays, const T& lens, double step_size, double max_vel, std::ofstream& output) { // move simulation every timestep for (auto& ray : rays) { for (size_t i = 0; i < TIME_RES; i+= 1){ if (ray.p.x > lens.origin.x + lens.radius + 1){ continue; } ray.p += ray.v * step_size; double n1 = ray.previous_index; double n2 = refractive_index_at(lens, ray.p); // If the ray passed through a refraction index change if (n1 != n2) { vec n = normal_at(lens, ray.p); vec l = normalize(ray.v); double ior = n1 / n2; if (dot(-n, l) < 0.0) { n = -n; } vec speed = refract(l, n, ior); if (is_null(speed)) { speed = reflect(l, n); } // Multiply with ior * length(ray.v) to get the proper velocity // for the refracted vector ray.v = normalize(speed) * ior * length(ray.v); } ray.previous_index = n2; if (i % 1000 == 0){ output << ray.p.x <<'\t'<< ray.p.y << '\t' << ray.v.x <<'\t'<< ray.v.y << '\n'; } } output << '\n' << '\n'; } } // Inside_of functions // simple lens slab bool inside_of(const simple& lens, vec p) { return p.x > lens.left && p.x < lens.right; } // Circle / sphere bool inside_of(const sphere& lens, vec p) { double diff = distance(lens.origin, p); return diff < lens.radius; } // Find the normal // Lens slab vec normal_at(const simple&, vec) { return normalize(vec(-1.0, 0.0)); } // Circle / sphere // ERROR: This is defined incorrectly! vec normal_at(const sphere& lens, vec p) { //return normalize(vec(-1.0, 0.0)); return normalize(p - lens.origin); } // find refractive index // Lens slab double refractive_index_at(const simple& lens, vec p) { return inside_of(lens, p) ? 1.4 : 1.0; } // Circle / sphere double refractive_index_at(const sphere& lens, vec p) { //return inside_of(lens, p) ? 1.4 : 1.0; double index, diff, Q, cutoff; cutoff = 0.0001; if (inside_of(lens, p)){ double r = distance(lens.origin, p); if (fabs(r) > cutoff){ double a = lens.radius; double q = cbrt(-(a/r) + sqrt((a * a) / (r * r) + 1.0 / 27.0)); index = (q - 1.0 / (3.0 * q)) * (q - 1.0 / (3.0 * q)); } else{ r = cutoff; double a = lens.radius; double q = cbrt(-(a/r) + sqrt((a * a) / (r * r) + 1.0 / 27.0)); index = (q - 1.0 / (3.0 * q)) * (q - 1.0 / (3.0 * q)); } } else{ index = 1.0; } return index; }
true
b884aab4b2621acae4f7b0e3c3515d6e16dde0f9
C++
joaopmatias/Competitions
/leetcode/1-50/720.h
UTF-8
882
2.78125
3
[]
no_license
class Solution { public: string longestWord(vector<string>& words) { vector < vector < string > > dic (33); vector < string > current, next; int i, j, k, n; for(i = 0; i < words.size(); i++) dic[words[i].size()].push_back(words[i]); current = dic[1]; for(i = 2; i < 33; i++){ for(j = 0; j < dic[i].size(); j++){ for(k = 0; k < current.size(); k++){ if(dic[i][j].substr(0, (dic[i][j]).size() - 1) == current[k]){ next.push_back(dic[i][j]); } } } if(next.size() != 0){ current = next; next.resize(0); } else { break; } } sort(current.begin(), current.end()); return current[0]; } };
true
862b4dc0360c7060ceb3bc6fb7431fa783bc690d
C++
SaracenOne/renik
/renik/renik_limb.h
UTF-8
2,048
2.578125
3
[ "MIT" ]
permissive
#ifndef RENIK_LIMB_H #define RENIK_LIMB_H #include <scene/3d/skeleton.h> struct RenIKLimb : public Resource { GDCLASS(RenIKLimb, Resource); public: Transform upper; Transform lower; Transform leaf; BoneId leaf_id = -1; BoneId lower_id = -1; BoneId upper_id = -1; void set_leaf(Skeleton *skeleton, BoneId p_leaf_id); BoneId get_leaf_bone(); BoneId get_lower_bone(); BoneId get_upper_bone(); bool is_valid(); Transform get_upper(); Transform get_lower(); Transform get_leaf(); float upper_twist_offset = 0; float lower_twist_offset = 0; float roll_offset = 0; //Rolls the entire limb so the joint points in a different direction float upper_limb_twist = 0; //How much the upper limb follows the lower limb float lower_limb_twist = 0; //How much the lower limb follows the leaf limb float twist_inflection_point_offset = 0; //When the limb snaps from twisting in the positive direction to twisting in the negative direction float twist_overflow = 0; //How much past the inflection point we go before snapping Quat pole_offset; /*ADVANCED - Moving the limb 180 degrees from rest tends to be a bit unpredictable as there is a pole in the forward vector sphere at that spot. This offsets the rest position so that the pole is in a place where the limb is unlikely to go*/ Vector3 target_position_influence; //ADVANCED - How much each of the leaf's axis of translation from rest affects the ik float target_rotation_influence; //ADVANCED - How much the rotation the leaf points in affects the ik //STATE: We're keeping a little bit of state now... kinda goes against the design, but it makes life easier so fuck it int overflow_state = 0;// 0 means no twist overflow. -1 means underflow. 1 means overflow. void init(float p_upper_twist_offset, float p_lower_twist_offset, float p_roll_offset, float p_upper_limb_twist, float p_lower_limb_twist, float p_twist_inflection_point_offset, float p_twist_overflow, float p_target_rotation_influence, Vector3 p_pole_offset, Vector3 p_target_position_influence); }; #endif
true
43f20ad9a14c7e420b9da68809b34f04e66af9fe
C++
RaBuko/SzeregowanieZadan
/SzeregowanieZadan/GA.cpp
UTF-8
6,990
3
3
[]
no_license
#include "GA.h" string GA(vector <Task*> & problemData, int populationCount, int numberOfIterations, double percentChanceOfMutation, bool print) { string toReturn = ""; // generowanie populacji startowej vector <vector <Task*>> population; vector <vector <Task*>> nextGeneration; pair <vector<Task*>, vector<Task*>> children; population.push_back(genFirstOrder(problemData)); for (size_t i = 1; i < populationCount; i++) population.push_back(shuffleOrder(problemData)); // uczynienie pierwszego obiektu z populacji startowej najlepszym vector <Task*> bestGlobalOrder = population[0]; int bestGlobalCost = calculateCost(bestGlobalOrder); while (numberOfIterations > 0) { nextGeneration = population; if (print) { toReturn += "\n------------------------------------------------------------\nIlosc pozostalych iteracji = " + to_string(numberOfIterations) + "\n"; toReturn += "BestGlobalOrder: " + orderToString(bestGlobalOrder) + "\n"; toReturn += "BestGlobalCost : " + to_string(bestGlobalCost) + "\n"; toReturn += "PopulationCount: " + to_string(nextGeneration.size()) + "\n"; } // krzyzowanie osobnikow ze soba i twrzenie nowej generacji for (size_t i = 0; i < populationCount; i+=2) { children = crossover(population[i], population[i + 1]); nextGeneration.push_back(children.first); nextGeneration.push_back(children.second); if (print) { toReturn += "Rodzic " + to_string(i) + " : " + orderToString(population[i]) + "\n"; toReturn += "Rodzic " + to_string(i + 1) + " : " + orderToString(population[i + 1]) + "\n"; toReturn += "Dziecko 1 : " + orderToString(children.first) + "\n"; toReturn += "Dziecko 2 : " + orderToString(children.second) + "\n\n"; } } if (print) toReturn += "PopulationCount: " + to_string(nextGeneration.size()) + "\n"; // mutowanie osobnikow z nowej generacji for (size_t i = populationCount; i < nextGeneration.size(); i++) { int chance = rand() % 100; if ( chance <= percentChanceOfMutation) { if (print) { toReturn += "Mutacja dla osobnika " + to_string(i) + "\n"; toReturn += "Przed: " + orderToString(nextGeneration[i]) + "\n"; } nextGeneration[i] = mutateOrder(nextGeneration[i]); if (print) toReturn += "Po : " + orderToString(nextGeneration[i]) + "\n"; } } // sortowanie populacji nextGeneration = sortPopulation(nextGeneration); population.clear(); // zachowanie najlepszych osobnikow for (size_t i = 0; i < populationCount; i++) { population.push_back(nextGeneration[i]); } numberOfIterations--; bestGlobalOrder = nextGeneration[0]; bestGlobalCost = calculateCost(bestGlobalOrder); } toReturn += "Najlepsza sciezka: " + orderToString(bestGlobalOrder) + "\n"; toReturn += "Najlepszy koszt: " + to_string(bestGlobalCost) + "\n"; return toReturn; } vector <vector <Task*>> sortPopulation(vector <vector <Task*>> population) { int n = population.size(); do { for (size_t i = 0; i < n - 1; i++) { if (calculateCost(population[i]) > calculateCost(population[i + 1])) { swap(population[i], population[i + 1]); } } n = n - 1; } while (n > 1); return population; } vector <Task*> mutateOrder(vector <Task*> oldOrder) { vector <Task*> vec = oldOrder; int orderLength = oldOrder.size(); int startIndex = rand() % orderLength; int endIndex = startIndex + rand() % (orderLength - startIndex); swap(vec[startIndex], vec[endIndex]); return vec; } pair< vector<Task*>, vector<Task*> > crossover(vector <Task*> parent1, vector <Task*> parent2) { pair <vector<Task*>, vector<Task*>> children; // inicjalizacja dzieci wynikajacych z krzyzowania int orderLength = parent1.size(); int startIndex = rand() % orderLength; // losowo wybrany index startowy sekcji dopasowania if (startIndex == orderLength - 1) startIndex = 0; int endIndex = (rand() % (orderLength - startIndex)) + startIndex + 1; // losowo wybrany index koncowy sekcji dopasowania (musi sie znajdowac po startIndex) //cout << "Start: " << startIndex << "| End: " << endIndex << "|Lenght: " << orderLength << endl; //cout << "Parent1: " << orderToString(parent1) << endl; //cout << "Parent2: " << orderToString(parent2) << endl; children.first = parent2; // dziecko pierwsze chwilo w pelni dziedziczy po rodzicu 2 children.second = parent1; // odwrotnie z drugim dzieckiem // uczynienie indeksow poza sekcja dopasowania w dzieciach jeszcze nieznanych for (size_t i = 0; i < orderLength; i++) { if (i < startIndex || i >= endIndex) { children.first[i] = new Task(-1, INT_MAX, INT_MAX, INT_MAX); children.second[i] = new Task(-1, INT_MAX, INT_MAX, INT_MAX); } } // wypelnianie dzieci odpowiednimi zadaniami poza sekcja dopasowania for (int i = 0; i < orderLength; i++) { // pominiecie sekcji dopasowania if (i >= startIndex && i < endIndex) continue; // uzupelnienie niekonfliktujacych zadan z podstawiona sekcja dopasowania dla dziecka 1 if (!isBeetweenInTask(startIndex, endIndex, children.first, parent1[i])) children.first[i] = parent1[i]; // uzupelnienie niekonfliktujacych zadan z podstawiona sekcja dopasowania dla dziecka 2 if (!isBeetweenInTask(startIndex, endIndex, children.second, parent2[i])) children.second[i] = parent2[i]; } for (int i = 0; i < orderLength; i++) { if (children.first[i]->index == -1) { //cout << "C1: I : " << i << " |"; for (int j = 0; j < orderLength; j++) { if (!isBeetweenInTask(0, orderLength, children.first, parent1[j])) { //cout << "Nie ma j = " << parent1[j]->index << " jeszcze w C1" << endl; children.first[i] = parent1[j]; break; } } } if (children.second[i]->index == -1) { //cout << "C2: I : " << i << " |"; for (size_t j = 0; j < orderLength; j++) { if (!isBeetweenInTask(0, orderLength, children.second, parent2[j])) { //cout << "Nie ma j = " << parent2[j]->index << " jeszcze w C2" << endl; children.second[i] = parent2[j]; break; } } } } //cout << "-----------------------------------------------------------------------------------\n"; //cout << "Child 1: " << orderToString(children.first) << endl; //cout << "Child 2: " << orderToString(children.second) << endl; return children; } bool isBeetweenInTask(int startIndex, int endIndex, vector <Task*> orderToCheck, Task* taskToCheck) { for (int i = startIndex; i < endIndex; i++) if (taskToCheck == orderToCheck[i]) return true; return false; } vector <Task*> genFirstOrder(vector <Task*> problemData) { vector <Task*> best = problemData; vector <float> wc; for (size_t i = 0; i < problemData.size(); i++) wc.push_back((float)problemData[i]->weight / (float)problemData[i]->time); for (int i = 0; i < problemData.size(); i++) { for (int j = 0; j < problemData.size() - 1; j++) { if (wc[j] < wc[j + 1]) { swap(best[j], best[j + 1]); swap(wc[j], wc[j + 1]); } } } orderToString(best); return best; }
true
a628ba5a1eedf3589cf3e2605c4b026b55f1419b
C++
lukaa12/TKOM-simple_language_interpreter
/src/stdlib/Functions.cpp
UTF-8
6,027
2.90625
3
[]
no_license
#include "Functions.h" #include "../Error.h" using namespace tkom; using namespace lib; GLuint compileShaders(); GLFWwindow* initWindow(GLuint w, GLuint h); // Shaders const GLchar* vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec2 position;\n" "uniform mat3 transform;\n" "void main()\n" "{\n" "gl_Position = vec4(transform * vec3(position, 1.0), 1.0);\n" "}\0"; const GLchar* fragmentShaderSource = "#version 330 core\n" "out vec4 color;\n" "uniform vec3 inColor;\n" "void main()\n" "{\n" "color = vec4(inColor, 1.0f);\n" "}\n\0"; int tkom::lib::print(std::string in) { std::cout << in << std::endl; return 0; } Graphic tkom::lib::blank(int w, int h) { Graphic blank; blank.width = w; blank.height = h; blank.color.color = glm::vec3(1.0f, 1.0f, 1.0f); blank.transform = glm::mat3(1.0f); blank.transform = glm::scale(blank.transform, glm::vec2(2.0f / w, 2.0f / h)); return blank; } Graphic tkom::lib::triangle(int h, int w) { Graphic triangle; triangle.transform = glm::mat3(1.0f); triangle.vertices = { 0.0f, h/2.0f, -w/2.0f, -h/2.0f, w/2.0f, -h/2.0f, }; triangle.indices = { 0, 1, 2 }; return triangle; } Graphic tkom::lib::rectangularTriangle(int a, int b) { Graphic triangle; triangle.transform = glm::mat3(1.0f); triangle.vertices = { -a / 2.0f, b / 2.0f, -a / 2.0f, -b / 2.0f, a / 2.0f, -b / 2.0f, }; triangle.indices = { 0, 1, 2 }; return triangle; } Graphic tkom::lib::rectangle(int a, int b) { Graphic rect; rect.transform = glm::mat3(1.0f); rect.vertices = { a / 2.0f, b / 2.0f, -a / 2.0f, b / 2.0f, -a / 2.0f, -b / 2.0f, a / 2.0f, -b / 2.0f, }; rect.indices = { 0, 1, 2, 2, 3, 0 }; return rect; } Graphic tkom::lib::circle(int r) { Graphic circle; circle.transform = glm::mat3(1.0f); circle.vertices = { 0.0f, 0.0f }; for (int i = 0; i != 36; ++i) { circle.vertices.push_back(glm::cos(glm::radians(i * 10.0f))*r); circle.vertices.push_back(glm::sin(glm::radians(i * 10.0f))*r); circle.indices.push_back(0); circle.indices.push_back(i + 1); circle.indices.push_back(i + 2 > 36 ? 1 : i + 2); } return circle; } Graphic tkom::lib::line(int len) { return rectangle(len, 20); } Graphic tkom::lib::add(Graphic parent, Graphic child) { parent.children.push_back(child); return parent; } Graphic tkom::lib::translate(Graphic object, int x, int y) { object.transform = glm::translate(object.transform, glm::vec2(static_cast<float>(x), static_cast<float>(y))); return object; } Graphic tkom::lib::scale(Graphic object, int x, int y) { object.transform = glm::scale(object.transform, glm::vec2(x/100.0f, y/100.0f)); return object; } Graphic tkom::lib::rotate(Graphic object, int x) { object.transform = glm::rotate(object.transform, glm::radians(static_cast<float>(x))); return object; } Graphic tkom::lib::unFill(Graphic object) { object.fill = false; return object; } Color tkom::lib::colorRGB(int r, int g, int b) { Color color; color.color = glm::vec3(r / 255.0f, g / 255.0f, b / 255.0f); return color; } Graphic tkom::lib::setColor(Graphic obj, Color c) { obj.color = c; return obj; } void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) glfwSetWindowShouldClose(window, GL_TRUE); } int tkom::lib::show(Graphic image) { if (glfwInit() != GL_TRUE) throw Error(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); try { GLFWwindow* window = initWindow(image.width, image.height); GLuint shaderProgram = compileShaders(); image.start(); while (!glfwWindowShouldClose(window)) { glfwPollEvents(); glClearColor(image.color.color.x, image.color.color.y, image.color.color.z, 1.0f); glClear(GL_COLOR_BUFFER_BIT); glUseProgram(shaderProgram); image.render(shaderProgram, glm::mat3(1.0f)); glfwSwapBuffers(window); } image.destroy(); } catch (std::exception ex) { std::cout << ex.what() << std::endl; } glfwTerminate(); return 0; } GLuint compileShaders() { GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, NULL); glCompileShader(vertexShader); GLint success; GLchar infoLog[512]; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertexShader, 512, NULL, infoLog); std::string msg = std::string("Vertex shader compilation: ") + infoLog; throw std::exception(msg.c_str()); } GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL); glCompileShader(fragmentShader); glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog); std::string msg = std::string("Fragment shader compilation: ") + infoLog; throw std::exception(msg.c_str()); } GLuint shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog); std::string msg = std::string("Shader linking: ") + infoLog; throw std::exception(msg.c_str()); } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); return shaderProgram; } GLFWwindow* initWindow(GLuint w, GLuint h) { GLFWwindow* window = glfwCreateWindow(w, h, "Press ESC to exit", nullptr, nullptr); if (window == nullptr) throw std::exception("GLFW window not created"); glfwMakeContextCurrent(window); glfwSetKeyCallback(window, key_callback); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) throw std::exception("GLEW Initialization failed"); glViewport(0, 0, w, h); glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); return window; }
true
e9cb4766eff567f1a55eb45fd43b471ab651feeb
C++
ezhangle/MinkowskiEngine
/src/broadcast.hpp
UTF-8
4,616
2.609375
3
[ "MIT" ]
permissive
#ifndef CPU_BROADCAST #define CPU_BROADCAST #include "math_functions.hpp" #include "utils.hpp" template <typename Dtype, typename Itype> void BroadcastForwardKernelCPU(const Dtype *p_in_feat, int in_nrows, const Dtype *p_in_feat_global, int in_nrows_global, Dtype *p_out_feat, int nchannel, int op, const InOutMapPerKernel<Itype> &in_map, const InOutMapPerKernel<Itype> &glob_map) { Dtype *p_curr_out_feat; const Dtype *p_curr_in_feat_global; // Copy all in_feat to out_feat std::memcpy(p_out_feat, p_in_feat, sizeof(Dtype) * in_nrows * nchannel); if (in_map.size() != 1) throw std::invalid_argument("InOut map must have one kernel for Broadcast"); if (in_map[0].size() != in_nrows) throw std::invalid_argument("Invalid in_map"); // To speed up, put switch outside for loops switch (op) { case 0: // + for (int row = 0; row < in_nrows; row++) { p_curr_out_feat = p_out_feat + in_map[0][row] * nchannel; p_curr_in_feat_global = p_in_feat_global + glob_map[0][row] * nchannel; cpu_add<Dtype>(nchannel, p_curr_in_feat_global, p_curr_out_feat, p_curr_out_feat); } break; case 1: // * for (int row = 0; row < in_nrows; row++) { p_curr_out_feat = p_out_feat + in_map[0][row] * nchannel; p_curr_in_feat_global = p_in_feat_global + glob_map[0][row] * nchannel; cpu_mul<Dtype>(nchannel, p_curr_in_feat_global, p_curr_out_feat, p_curr_out_feat); } break; case 2: // division for (int row = 0; row < in_nrows; row++) { p_curr_out_feat = p_out_feat + in_map[0][row] * nchannel; p_curr_in_feat_global = p_in_feat_global + glob_map[0][row] * nchannel; cpu_div<Dtype>(nchannel, p_curr_in_feat_global, p_curr_out_feat, p_curr_out_feat); } break; default: throw std::invalid_argument(Formatter() << "Operation not supported: " << std::to_string(op)); } } template <typename Dtype, typename Itype> void BroadcastBackwardKernelCPU(const Dtype *p_in_feat, Dtype *p_grad_in_feat, int in_nrows, const Dtype *p_in_feat_global, Dtype *p_grad_in_feat_global, int in_nrows_global, const Dtype *p_grad_out_feat, int nchannel, int op, const InOutMapPerKernel<Itype> &in_map, const InOutMapPerKernel<Itype> &glob_map) { Dtype *p_curr_grad_in_feat, *p_curr_grad_in_feat_global; const Dtype *p_curr_in_feat_global, *p_curr_in_feat, *p_curr_grad_out_feat; // Clear grad memory std::memset(p_grad_in_feat_global, 0, sizeof(Dtype) * in_nrows_global * nchannel); // Initialize the grad_in_feat as grad_out_feat std::memcpy(p_grad_in_feat, p_grad_out_feat, sizeof(Dtype) * in_nrows * nchannel); // To speed up, put switch outside for loops switch (op) { case 0: // + // For p_grad_in_feat, copy all grad_out for (int row = 0; row < in_nrows; row++) { p_curr_grad_out_feat = p_grad_out_feat + in_map[0][row] * nchannel; p_curr_grad_in_feat_global = p_grad_in_feat_global + glob_map[0][row] * nchannel; cpu_add<Dtype>(nchannel, p_curr_grad_out_feat, p_curr_grad_in_feat_global, p_curr_grad_in_feat_global); } break; case 1: // * std::memset(p_grad_in_feat, 0, sizeof(Dtype) * in_nrows * nchannel); for (int row = 0; row < in_nrows; row++) { // In feat global p_curr_in_feat = p_in_feat + in_map[0][row] * nchannel; p_curr_grad_in_feat = p_grad_in_feat + in_map[0][row] * nchannel; p_curr_grad_in_feat_global = p_grad_in_feat_global + glob_map[0][row] * nchannel; p_curr_grad_out_feat = p_grad_out_feat + in_map[0][row] * nchannel; p_curr_in_feat_global = p_in_feat_global + glob_map[0][row] * nchannel; // In feat cpu_mul<Dtype>(nchannel, p_curr_in_feat_global, p_curr_grad_out_feat, p_curr_grad_in_feat); // In feat glob for (int j = 0; j < nchannel; j++) { p_curr_grad_in_feat_global[j] += p_curr_grad_out_feat[j] * p_curr_in_feat[j]; } } break; default: throw std::invalid_argument(Formatter() << "Operation not supported: " << std::to_string(op)); } } #endif
true
a950455144af37a2ef4201eb122e0f81dc10ed0e
C++
kaba2/pastel
/pastel/geometry/overlap/overlaps_plane_triangle.h
UTF-8
1,514
3.15625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
// Description: Overlap tests between a plane and a triangle #ifndef PASTELGEOMETRY_OVERLAPS_PLANE_TRIANGLE_H #define PASTELGEOMETRY_OVERLAPS_PLANE_TRIANGLE_H #include "pastel/geometry/shape/plane.h" #include "pastel/geometry/shape/triangle.h" #include "pastel/sys/mytypes.h" namespace Pastel { //! Tests if a plane and a triangle overlap. /*! The triangle is considered to be closed and solid. */ template <typename Real, int N> bool overlaps( const Plane<Real, N> &plane, const PASTEL_TRIANGLE(Real, N) &triangle) { // A triangle overlaps the plane // if there is a triangle point // that is on the plane or // there exists two triangle points // that are on the opposite sides // of the plane. Real d1(dot(plane.normal(), triangle[0] - plane.position())); // EPSILON if (d1 == 0) { // A vertex is on the plane, // thus the triangle intersects it. return true; } Real d2(dot(plane.normal(), triangle[1] - plane.position())); // EPSILON if (d2 == 0) { // A vertex is on the plane, // thus the triangle intersects it. return true; } Real d3(dot(plane.normal(), triangle[2] - plane.position())); // EPSILON if (d3 == 0) { // A vertex is on the plane, // thus the triangle intersects it. return true; } bool aSide = d1 > 0; bool bSide = d2 > 0; bool cSide = d3 > 0; return ((aSide != bSide) || (aSide != cSide)); } } #endif
true
fb2ffe1cfdb6dde645877f69772a0f61c5551a90
C++
RYNO8/BigInt-cpp
/sample.cpp
UTF-8
349
3.078125
3
[]
no_license
#include <iostream> #include <string> #include "BigInt.hpp" using namespace std; int main() { BigInt num1 = (string)"01189998819991197253"; BigInt num2; cin >> num2; cout << "Num2 is : " << num2 << "\n"; cout << num1 + num2 << "\n"; cout << num1 * num2 << "\n"; cout << num1 - num2 << "\n"; cout << num1.pow(num2) << "\n"; }
true
778d26d4b9248d233620d18b256e304d4616bd72
C++
ackevil/TCP-Server
/main.cpp
UTF-8
513
2.515625
3
[]
no_license
/* * main.cpp * * Created on: 2017年2月27日 * Author: ackevil */ #include <iostream> #include <string> #include <unistd.h> #include <cstdlib> #include "tcpServer.h" using namespace std; int main(int argc,char* argv[]){ int opt=0; string ip="127.0.0.1"; int port=getuid()==0?80:8080; while((opt=getopt(argc,argv,"a::p::"))!=-1){ switch(opt){ case 'a': ip=optarg; break; case 'p': port=atoi(optarg); break; } } TcpServer server(ip,port); server.run(); return 0; }
true
3ad716721dd8f995f6d67a7aa35e1fb6f582efe0
C++
mikehershey/bamf
/Bamf/SynchronousGameLoop.h
UTF-8
1,088
2.828125
3
[]
no_license
// // SynchronousGameLoop.h // Bamf // // Created by Matthew Hinkle on 2/1/13. // // #ifndef __Bamf__SynchronousGameLoop__ #define __Bamf__SynchronousGameLoop__ #include <SDL2/SDL.h> #include "GameLoop.h" namespace bamf { /** The instructions in a SynchronousGameLoop will execute each subsystem in order. This does not guarentee that the current subsystem is the only running subsystem as previous subsystems may have spawned childen which are still running. */ class SynchronousGameLoop : public GameLoop { public: /** Default Constructor @brief create a new gameloop in a non-running state */ explicit SynchronousGameLoop(); virtual ~SynchronousGameLoop(); inline bool isSuspended() const { return this->suspended; } /* GameLoop interface */ virtual void restart(); virtual void start(); virtual void stop(); virtual void suspend(); private: static int run(void * loop); int run(); bool running; bool suspended; SDL_Thread * thread; SDL_cond * suspendCond; SDL_mutex * suspendMutex; }; } #endif /* defined(__Bamf__SynchronousGameLoop__) */
true
624ddaae674889624a67d31703844f715ffcaac6
C++
btrangcal/CS162-Final-Project-version-3
/Lounge.cpp
UTF-8
3,435
3.328125
3
[]
no_license
#include "Lounge.hpp" #include <iostream> char Lounge::sequence() { int userChoice; //rat is still alive and didn't speak to hostess if(!ratDead && !spokeHostess ) { std::cout << "\nPlease make a selection below.\n"; std::cout << "---------------------------------\n"; std::cout << "(1) Talk to the hostess.\n"; std::cout << "(2) Return to the entrance.\n"; std::cout << "(3) Interact with the terrifying rat.\n"; std::cout << "(4) Go to the card room.\n"; std::cout << "(5) Go to the bar.\n"; std::cout << "(6) Check the backpack.\n"; std::cout << "\n"; std::cin >> userChoice; while(userChoice<0 || userChoice>6) { std::cout << "Please pick a valid choice.\n"; std::cin >> userChoice; } std::cout << "\n"; if (userChoice == 1) return 'e'; else if (userChoice == 2) return 's'; else if (userChoice == 3) return 'n'; else if (userChoice == 4) return 'd'; else if (userChoice == 5) return 'w'; else if (userChoice == 6) return 'b'; } else if(!ratDead &&spokeHostess) //if rat is not dead and you already spoke to hostess { std::cout << "\nPlease make a selection below.\n"; std::cout << "---------------------------------\n"; std::cout << "(1) Talk to the hostess.\n"; std::cout << "(2) Return to the entrance.\n"; std::cout << "(3) Interact with the terrifying rat.\n"; std::cout << "(4) Go to the card room.\n"; std::cout << "(5) Go to the bar.\n"; std::cout << "(6) Check backpack.\n"; std::cout << "(7) Quit the game.\n"; std::cout << "\n"; std::cin >> userChoice; while (userChoice<0 || userChoice>7) { std::cout << "Please pick a valid choice.\n"; std::cin >> userChoice; } std::cout << "\n"; if (userChoice == 1) return 'p'; //event pending else if (userChoice == 2) return 's'; //go south else if (userChoice == 3) return 'n'; //npc else if (userChoice == 4) return 'd'; //go east else if (userChoice == 5) //go north return 'w'; else if (userChoice == 6) return 'b'; else if (userChoice == 7) return 'q'; } else if(ratDead && spokeHostess) //if rat is dead and hostess quest activated { std::cout << "\nPlease make a selection below.\n"; std::cout << "---------------------------------\n"; std::cout << "(1) Talk to the hostess.\n"; std::cout << "(2) Return to the entrance.\n"; std::cout << "(3) Interact with the dead rat.\n"; std::cout << "(4) Go to the card room.\n"; std::cout << "(5) Go to the bar.\n"; std::cout << "(6) Check the backpack.\n"; std::cout << "(7) Quit the game.\n"; std::cout << "\n"; std::cin >> userChoice; //input validation while (!std::cin) { std::cout << "You didn't enter an integer.\n"; std::cin.clear(); std::cin.ignore(); std::cin >> userChoice; } while (userChoice<0 || userChoice>7) { std::cout << "Please pick a valid choice.\n"; std::cin >> userChoice; } std::cout << "\n"; if (userChoice == 1) return 'f'; //event finished else if (userChoice == 2) return 's'; //go south else if (userChoice == 3) return 'n'; //npc finished if (userChoice == 4) //go east return 'd'; if (userChoice == 5) return 'w'; if (userChoice == 6) return 'b'; if (userChoice == 7) return 'q'; } // }
true
2f3bae7429e42f00c52a67ce80783354d436feae
C++
jiny9395/AlgorithmStudy
/ex17822.cpp
UTF-8
2,834
2.84375
3
[]
no_license
#include <stdio.h> #include <queue> #include <string.h> #define MAX 50 using namespace std; int N, M, T; int circle[MAX + 2][MAX + 2]; bool visited[MAX + 2][MAX + 2]; int dy[] = { 0,0,-1,+1 }; int dx[] = { -1,+1,0,0 }; int getSum() { int sum = 0; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { sum += circle[i][j]; } } return sum; } double getAvg() { double avg = 0; int cnt = 0; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { if (circle[i][j] == 0) continue; cnt++; avg += circle[i][j]; } } return avg / cnt; } void cw(int n) { int tmp[MAX + 2] = { 0, }; tmp[1] = circle[n][M]; for (int i = 1; i <= M - 1; i++) { tmp[i + 1] = circle[n][i]; } for (int i = 1; i <= M; i++) { circle[n][i] = tmp[i]; } } void ccw(int n) { int tmp[MAX + 2] = { 0, }; tmp[M] = circle[n][1]; for (int i = 2; i <= M; i++) { tmp[i - 1] = circle[n][i]; } for (int i = 1; i <= M; i++) { circle[n][i] = tmp[i]; } } void rotate(int n, int d, int k) { k %= M; if (d == 0) { // 시계방향 for (int i = 1; i <= k; i++) { cw(n); } } else { // 반시계방향 for (int i = 1; i <= k; i++) { ccw(n); } } } bool removeNum(int y, int x, int n) { memset(visited, false, sizeof(visited)); bool changed = false; queue<pair<int, int>> q; queue<pair<int, int>> zero; visited[y][x] = true; q.push({ y,x }); while(!q.empty()){ pair<int, int> cur = q.front(); q.pop(); for (int dir = 0; dir < 4; dir++) { int ny = cur.first + dy[dir]; int nx = cur.second + dx[dir]; if (ny < 1 || ny > N) continue; if (nx < 1) nx = M; if (nx > M) nx = 1; if (visited[ny][nx]) continue; visited[ny][nx] = true; if (circle[ny][nx] == n) { q.push({ ny,nx }); zero.push({ ny,nx }); } } while (!zero.empty()) { pair<int, int> cur = zero.front(); zero.pop(); circle[cur.first][cur.second] = 0; changed = true; } } if (changed) circle[y][x] = 0; return changed; } void findNum() { bool changed = false; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { if (circle[i][j] == 0) continue; // 숫자가 없는 경우 bool ret = removeNum(i, j, circle[i][j]); if (ret) changed = true; } } if (changed == false) { double avg = getAvg(); for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { if (!circle[i][j]) continue; if (avg < circle[i][j]) circle[i][j]--; else if (avg > circle[i][j]) circle[i][j]++; } } } } int main() { scanf("%d %d %d", &N, &M, &T); for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { scanf("%d", &circle[i][j]); } } for (int i = 1; i <= T; i++) { int x, d, k; scanf("%d %d %d", &x, &d, &k); for (int n = x; n <= N; n += x) { rotate(n, d, k); } findNum(); } printf("%d\n", getSum()); }
true
4dbdef6b0c81176f8c3889846b922f47a0b148f7
C++
BlueSquid1/NANE
/NANE/src/NES/APU/ApuMemoryMap.cpp
UTF-8
7,823
2.546875
3
[]
no_license
#include "ApuMemoryMap.h" namespace { const int JOYSTICK_STROBE_ADDRESS = 0x4016; } ApuMemoryMap::ApuMemoryMap() : IMemoryRW(0x4000, 0x4017), sq1(false), sq2(true) { } bool ApuMemoryMap::PowerCycle() { bool regReturn = this->GetRegisters().PowerCycle(); if(regReturn == false) { return false; } this->sq1.SetWatchdogTimer(0); this->sq2.SetWatchdogTimer(0); //TODO return true; } byte ApuMemoryMap::Read(dword address) { return this->apuRegMem.Read(address); } void ApuMemoryMap::Write(dword address, byte value) { this->apuRegMem.Write(address, value); switch(address) { case ApuRegisters::ApuAddresses::SQ1_VOL_ADDR: { this->sq1.SetDutyCycle(this->apuRegMem.name.SQ1.dutyNum); this->sq1.SetHaltWatchdogTimer(this->apuRegMem.name.SQ1.lengthCounterHault); this->sq1.SetConstantVolume(this->apuRegMem.name.SQ1.constantVolume); this->sq1.SetMaxVolumeOrEnvelopePeriod(this->apuRegMem.name.SQ1.volumeAndEnvelopePeriod); this->sq1.ResetVolumeDecayEnvelope(); break; } case ApuRegisters::ApuAddresses::SQ1_SWEEP_ADDR: { this->sq1.SetFrequencySweep(this->apuRegMem.name.SQ1.enable, this->apuRegMem.name.SQ1.period, this->apuRegMem.name.SQ1.negative, this->apuRegMem.name.SQ1.shift); break; } case ApuRegisters::ApuAddresses::SQ1_LO_ADDR: { dword upperVal = this->sq1.GetPulsePeriod() & 0xFF00; this->sq1.SetPulsePeriod(upperVal | this->apuRegMem.name.SQ1.LO); break; } case ApuRegisters::ApuAddresses::SQ1_HI_ADDR: { dword lowerVal = this->sq1.GetPulsePeriod() & 0x00FF; dword period = (this->apuRegMem.name.SQ1.timerHigh << 8) | lowerVal; this->sq1.SetPulsePeriod(period); this->sq1.SetDutyCycle(0); this->sq1.ResetVolumeDecayEnvelope(); this->sq1.SetWatchdogTimerFromCode(this->apuRegMem.name.SQ1.lengthCounter); break; } case ApuRegisters::ApuAddresses::SQ2_VOL_ADDR: { this->sq2.SetDutyCycle(this->apuRegMem.name.SQ2.dutyNum); this->sq2.SetHaltWatchdogTimer(this->apuRegMem.name.SQ2.lengthCounterHault); this->sq2.SetConstantVolume(this->apuRegMem.name.SQ2.constantVolume); this->sq2.SetMaxVolumeOrEnvelopePeriod(this->apuRegMem.name.SQ2.volumeAndEnvelopePeriod); this->sq2.ResetVolumeDecayEnvelope(); break; } case ApuRegisters::ApuAddresses::SQ2_SWEEP_ADDR: { this->sq2.SetFrequencySweep(this->apuRegMem.name.SQ2.enable, this->apuRegMem.name.SQ2.period, this->apuRegMem.name.SQ2.negative, this->apuRegMem.name.SQ2.shift); break; } case ApuRegisters::ApuAddresses::SQ2_LO_ADDR: { dword upperVal = this->sq2.GetPulsePeriod() & 0xFF00; this->sq2.SetPulsePeriod(upperVal | this->apuRegMem.name.SQ2.LO); break; } case ApuRegisters::ApuAddresses::SQ2_HI_ADDR: { dword lowerVal = this->sq2.GetPulsePeriod() & 0x00FF; dword period = (this->apuRegMem.name.SQ2.timerHigh << 8) | lowerVal; this->sq2.SetPulsePeriod(period); this->sq2.SetDutyCycle(0); this->sq2.ResetVolumeDecayEnvelope(); this->sq2.SetWatchdogTimerFromCode(this->apuRegMem.name.SQ2.lengthCounter); break; } case ApuRegisters::ApuAddresses::TRI_LINEAR_ADDR: { this->tri.SetLinearCounter(this->apuRegMem.name.TRI.linearCounter); this->tri.SetHaltTimers(this->apuRegMem.name.TRI.lengthCounterHalt); break; } case ApuRegisters::ApuAddresses::TRI_LO_ADDR: { dword upperVal = this->tri.GetPeriod() & 0xFF00; this->tri.SetPeriod(upperVal | this->apuRegMem.name.TRI.LO); break; } case ApuRegisters::ApuAddresses::TRI_HI_ADDR: { dword lowerVal = this->tri.GetPeriod() & 0x00FF; dword period = (this->apuRegMem.name.TRI.timerHigh << 8) | lowerVal; this->tri.SetPeriod(period); this->tri.SetWatchdogTimerFromCode(this->apuRegMem.name.TRI.lengthCounter); this->tri.TriggerLinearReset(); break; } case ApuRegisters::ApuAddresses::NOISE_VOL_ADDR: { this->noise.SetMaxVolumeOrEnvelopePeriod(this->apuRegMem.name.NOISE.volumeAndEnvelopePeriod); this->noise.SetConstantVolume(this->apuRegMem.name.NOISE.constantVolume); this->noise.SetHaltWatchdogTimer(this->apuRegMem.name.NOISE.lengthCounterHault); this->noise.ResetVolumeDecayEnvelope(); break; } case ApuRegisters::ApuAddresses::NOISE_PERIOD_ADDR: { this->noise.SetPeriodFromLookupTable(this->apuRegMem.name.NOISE.noisePeriod); this->noise.SetUseSixthBit(this->apuRegMem.name.NOISE.loopNoise); break; } case ApuRegisters::ApuAddresses::NOISE_LENGTH_COUNTER_ADDR: { this->noise.SetWatchdogTimerFromCode(this->apuRegMem.name.NOISE.lengthCounterLoad); this->noise.ResetVolumeDecayEnvelope(); break; } case ApuRegisters::ApuAddresses::SND_CHN_ADDR: { bool sq1Enabled = this->apuRegMem.name.channels.pulse1; this->sq1.SetEnabled(sq1Enabled); if(sq1Enabled == false) { this->sq1.SetWatchdogTimer(0); } bool sq2Enabled = this->apuRegMem.name.channels.pulse2; this->sq2.SetEnabled(sq2Enabled); if(sq2Enabled == false) { this->sq2.SetWatchdogTimer(0); } bool triEnabled = this->apuRegMem.name.channels.triangle; this->tri.SetEnabled(triEnabled); if(triEnabled == false) { this->tri.SetWatchdogTimer(0); } bool noiseEnabled = this->apuRegMem.name.channels.noise; this->noise.SetEnabled(noiseEnabled); if(noiseEnabled) { this->noise.SetWatchdogTimer(0); } break; } case ApuRegisters::ApuAddresses::FRAME_COUNTER_ADDR: { //reset frame counter this->apuRegMem.vRegs.frameCounterSeqNum = 0; this->resetFrameCounter = true; break; } } } byte ApuMemoryMap::Seek(dword address) const { return this->apuRegMem.Seek(address); } bool ApuMemoryMap::Contains(dword address) const { if(address == JOYSTICK_STROBE_ADDRESS) { return false; } return IMemoryRW::Contains(address); } int ApuMemoryMap::GetCpuClockRateHz() { return this->cpuClockRateHz; } int ApuMemoryMap::GetFrameCounterRateHz() { return this->frameCounterRateHz; } const long long& ApuMemoryMap::GetTotalApuCycles() const { return this->totalApuCycles; } void ApuMemoryMap::SetTotalApuCycles(const long long& value) { this->totalApuCycles = value; } ApuRegisters& ApuMemoryMap::GetRegisters() { return this->apuRegMem; } SquareWave& ApuMemoryMap::GetSquareWave1() { return this->sq1; } SquareWave& ApuMemoryMap::GetSquareWave2() { return this->sq2; } TriangleWave& ApuMemoryMap::GetTriangleWave() { return this->tri; } NoiseWave& ApuMemoryMap::GetNoiseWave() { return this->noise; } bool ApuMemoryMap::GetResetFrameCounter() { return this->resetFrameCounter; } void ApuMemoryMap::SetResetFrameCounter( bool frameCounterReset ) { this->resetFrameCounter = frameCounterReset; }
true
edc3a629e31db99f23bc791d86f99fd77de09126
C++
InjectiveSheaf/image-segmenter
/drawer.h
UTF-8
607
2.734375
3
[]
no_license
#ifndef DRAWER_H #define DRAWER_H #include <QImage> #include <QColor> /* Класс Drawer * Qimage Filter - медианный фильтр * Qimage Draw_Contours - рисует контуры цветом color * bool Is_boundary - определяет, находится ли пиксель на границе компоненты связности */ class Drawer{ public: QImage Filter(const QImage & Image); QImage Draw_Contours(const QImage &Label, const QImage &Original_Image, uint color); protected: bool Is_Boundary(const QImage &Label, int x, int y); }; #endif // DRAWER_H
true
b55d9ff4f19986c1233ed525cc65061183d0ed44
C++
cetcjinjian/SysCtrl
/SysCtrl/CmdData.cpp
UTF-8
718
2.65625
3
[]
no_license
#include "stdafx.h" #include "CmdData.h" CCmdData::CCmdData() { m_length = sizeof(data1) + sizeof(data2) + sizeof(data3); } CCmdData::~CCmdData() { } int CCmdData::HandleData(unsigned char* ptr, int len) { int begin = 1; memcpy(&data1, ptr + begin, 4); begin += 4; memcpy(&data2, ptr + begin, 4); begin += 4; memcpy(&data3, ptr + begin, 4); begin += 4; return begin; } int CCmdData::MakeData(unsigned char* ptr, int len) { int begin = 0; memcpy(ptr + begin, &data1, 4); begin += 4; memcpy(ptr + begin, &data1, 4); begin += 4; memcpy(ptr + begin, &data1, 4); begin += 4; return begin; } int CCmdData::GetLength() { return m_length; }
true
d632e5db8c0c0539f2d0d9cafe9b25854279bc98
C++
yangzhilinAndy/algorithm-exercise
/bit manipulation/29_11_2018-338. Counting Bits.cpp
UTF-8
246
3.15625
3
[]
no_license
//Use a bit manipulation trick class Solution { public: vector<int> sol; vector<int> countBits(int num) { sol.push_back(0); for (int n=1; n<=num; n++) sol.push_back(sol[n/2]+n%2); return sol; } };
true
4c8c607525c5bd1cd9742af7d1ac0d4c4618d6d0
C++
Refuge89/WoWCraft
/directory.h
UTF-8
1,635
2.9375
3
[]
no_license
#ifndef DIRECTORY_H #define DIRECTORY_H #include <QDir> #include <QFileDialog> #include <QApplication> #include "config.h" class directory { private: QDir m_dir; public: directory(QString path) : m_dir(path) { } ~directory(){} void configure(QString path){ m_dir.setPath(path); } QString path() const { return m_dir.absolutePath(); } bool add_file(const QString & file_name) const { QString file = QFileDialog::getOpenFileName(QApplication::activeWindow(), QString{"Open "} + file_name, m_dir.absolutePath(), QString{file_name}); if(!file.isNull()) { return QFile::copy(file, m_dir.absolutePath() + file_name); } else return false; } bool exists(const QString & file_name) const { return m_dir.exists(file_name); } }; class dbc_directory { private: directory m_directory; public: dbc_directory(const configuration & cfg) : m_directory(cfg.get_string("DBC.Directory")) { } ~dbc_directory(){} void configure(const configuration & cfg) { m_directory.configure(cfg.get_string("DBC.Directory")); } QString path() const { return m_directory.path(); } bool exists(const QString & file_name) const { return m_directory.exists(file_name); } bool add_file(const QString & file_name) const { return m_directory.add_file(file_name); } }; #endif // DIRECTORY_H
true
be7b969eda9c5b1a6e65ee5d8cd28e05a353d6e5
C++
lock19960613/SCL
/SCL/Sort/MergeSort/mergeSort.cpp
UTF-8
1,332
3.15625
3
[]
no_license
#include <iostream> using namespace std; //归并排序分为三步 //1 选中间点 //2 归:递归的排序左半边的右半边 //3 并:利用一个额外的数组,合并两个已经排序的部分 const int N= 1e5 + 10; int q[N],temp[N]; //自底向上 void mergeSort(int q[],int l,int r){ if(l >= r){ return; } // >>的优先级是低于+的 int mid = l + r >> 1; //不建议使用mid - 1 分割 //因为向下取整的话,造成mid+1,r这个区间循环不变 mergeSort(q,l,mid), mergeSort(q,mid+1,r); int k = 0,i = l,j = mid+1; //把排序信息记录到缓存数组 while(i <=mid && j <= r){ //稳定排序在此处 if(q[i] <= q[j]){ temp[k++] = q[i++]; }else{ temp[k++] = q[j++]; } } while(i <= mid) temp[k++] = q[i++]; while(j <= r) temp[k++] = q[j++]; //复原的操作,注意复原的区间是从l->r //不同的递归深度的的区间是不同的 //所以要严格按照区间去合并数组 for(int i = l,j = 0;i <= r;i++,j++){ q[i] = temp[j]; } } int main(){ int n; scanf("%d",&n); for(int i = 0;i < n;i++){ scanf("%d",&q[i]); } mergeSort(q,0,n-1); for(int i = 0;i < n;i++){ printf("%d ",q[i]); } return 0; }
true
ecbce7edddcb1d0f05dabb712db5b2e940fb3253
C++
pengjunjie1207/robot
/grayscale_sensor/grayscale_sensor.ino
UTF-8
8,178
2.875
3
[]
no_license
//const int linePin[0] = 22; //const int linePin[1] = 28; //const int linePin[2] = 34; //const int linePin[3] = 40; const int positionPin = 46; // four position and 46 is the leftest const int butPin = 52; const int grayPin = 0; const int seedPin = 1; // analog pin 1 should not be used const int pinNum = 32; const int rowOfLed = 5; // the lengths of row of len const int colOfLed = 4; const int linePin[colOfLed] = {22, 28, 34, 40}; // 5 led per line and the 6th pin is not connected with a led const long interval = 1000; unsigned long previousMillis = 0; int gray = 0; int numPosition = 0; // up to 3 from left to right int nums[4] = {0}; // the nums of four positions int part = 0; // which part to play, 0 - 2, and part 1 is a game int lens[5] = {0}; // use to show part 2 and lens[0] is meaningless void setup() { // put your setup code here, to run once: for (int i = 0; i < 24 + 4; ++i) { pinMode(linePin[0] + i, OUTPUT); } randomSeed(analogRead(seedPin)); Serial.begin(9600); } void lightLed(int startPin, int * array, int len) { for (int i = 0; i < len; ++i) { digitalWrite(startPin + array[i], HIGH); } } void flashLed(int pin) { digitalWrite(pin, HIGH); delay(interval); digitalWrite(pin, LOW); } void printNum(int num) { switch(num) { case 0: { int array1[] = {0, 1, 2, 3, 4}; int array2[] = {0, 4}; lightLed(linePin[0], array1, sizeof(array1) / sizeof(int)); lightLed(linePin[1], array2, sizeof(array2) / sizeof(int)); lightLed(linePin[2], array2, sizeof(array2) / sizeof(int)); lightLed(linePin[3], array1, sizeof(array1) / sizeof(int)); break; } case 1: { int array1[] = {0, 1, 2, 3, 4}; lightLed(linePin[2], array1, sizeof(array1) / sizeof(int)); break; } case 2: { int array1[] = {0, 1, 2, 4}; int array2[] = {0, 2, 4}; int array3[] = {0, 2, 3, 4}; lightLed(linePin[0], array1, sizeof(array1) / sizeof(int)); lightLed(linePin[1], array2, sizeof(array2) / sizeof(int)); lightLed(linePin[2], array2, sizeof(array2) / sizeof(int)); lightLed(linePin[3], array3, sizeof(array3) / sizeof(int)); break; } case 3: { int array1[] = {0, 2, 4}; int array2[] = {0, 1, 2, 3, 4}; lightLed(linePin[0], array1, sizeof(array1) / sizeof(int)); lightLed(linePin[1], array1, sizeof(array1) / sizeof(int)); lightLed(linePin[2], array1, sizeof(array1) / sizeof(int)); lightLed(linePin[3], array2, sizeof(array2) / sizeof(int)); break; } case 4: { int array1[] = {2, 3, 4}; int array2[] = {2}; int array3[] = {0, 1, 2, 3, 4}; lightLed(linePin[0], array1, sizeof(array1) / sizeof(int)); lightLed(linePin[1], array2, sizeof(array2) / sizeof(int)); lightLed(linePin[2], array3, sizeof(array3) / sizeof(int)); lightLed(linePin[3], array2, sizeof(array2) / sizeof(int)); break; } case 5: { int array1[] = {0, 2, 3, 4}; int array2[] = {0, 2, 4}; int array3[] = {0, 1, 2, 4}; lightLed(linePin[0], array1, sizeof(array1) / sizeof(int)); lightLed(linePin[1], array2, sizeof(array2) / sizeof(int)); lightLed(linePin[2], array2, sizeof(array2) / sizeof(int)); lightLed(linePin[3], array3, sizeof(array3) / sizeof(int)); break; } case 6: { int array1[] = {0, 1, 2, 3, 4}; int array2[] = {0, 2, 4}; int array3[] = {0, 1, 2, 4}; lightLed(linePin[0], array1, sizeof(array1) / sizeof(int)); lightLed(linePin[1], array2, sizeof(array2) / sizeof(int)); lightLed(linePin[2], array2, sizeof(array2) / sizeof(int)); lightLed(linePin[3], array3, sizeof(array3) / sizeof(int)); break; } case 7: { int array1[] = {4}; int array2[] = {0, 1, 2, 3, 4}; lightLed(linePin[0], array1, sizeof(array1) / sizeof(int)); lightLed(linePin[1], array1, sizeof(array1) / sizeof(int)); lightLed(linePin[2], array1, sizeof(array1) / sizeof(int)); lightLed(linePin[3], array2, sizeof(array2) / sizeof(int)); break; } case 8: { int array1[] = {0, 1, 2, 3, 4}; int array2[] = {0, 2, 4}; lightLed(linePin[0], array1, sizeof(array1) / sizeof(int)); lightLed(linePin[1], array2, sizeof(array2) / sizeof(int)); lightLed(linePin[2], array2, sizeof(array2) / sizeof(int)); lightLed(linePin[3], array1, sizeof(array1) / sizeof(int)); break; } case 9: { int array1[] = {0, 2, 3, 4}; int array2[] = {0, 2, 4}; int array3[] = {0, 1, 2, 3, 4}; lightLed(linePin[0], array1, sizeof(array1) / sizeof(int)); lightLed(linePin[1], array2, sizeof(array2) / sizeof(int)); lightLed(linePin[2], array2, sizeof(array2) / sizeof(int)); lightLed(linePin[3], array3, sizeof(array3) / sizeof(int)); break; } default: break; } } void loop() { // put your main code here, to run repeatedly: int butState = digitalRead(butPin); if(butState == HIGH) { // blocked gray = analogRead(grayPin); Serial.println(gray, DEC); part = 2; previousMillis = millis(); unsigned long currentMillis = millis(); while (currentMillis - previousMillis <= interval) { butState = digitalRead(butPin); if (butState == LOW) { part = 0; break; } currentMillis = millis(); } if (part == 2) { previousMillis = millis(); currentMillis = millis(); while (currentMillis - previousMillis <= interval * 2) { butState = digitalRead(butPin); if (butState == LOW) { part = 1; break; } currentMillis = millis(); } } if (part == 0) { for (int i = 0; i < pinNum; ++i) { digitalWrite(linePin[0] + i, LOW); } int tmp = gray; for (int i = 0; i < 4; ++i) { nums[3 - i] = tmp % 10; tmp /= 10; } previousMillis = millis(); } else if (part == 1){ for (int i = 0; i < pinNum; ++i) { digitalWrite(linePin[0] + i, LOW); } // game Serial.println("game start"); int fail = 0; // 1 if game is over int p = 0; // up to 3 from left to right and // determine the place of player while (fail != 1) { int lr = random(4); // determine the place of bullet for (int i = rowOfLed - 1; i >= 0; --i) { gray = analogRead(grayPin); if(gray > 400) { // right p++; Serial.println("right"); if (p >= colOfLed) { p = colOfLed - 1; } } else if (gray > 300){ // left p--; Serial.println("left"); if (p < 0) { p = 0; } } else { // do nothing } for (int itr = 0; itr < colOfLed; ++itr) { digitalWrite(linePin[itr], LOW); } digitalWrite(linePin[p], HIGH); flashLed(linePin[lr] + i); if (i == 0 && lr == p) { fail = 1; } delay(interval); } } // game end Serial.println("game end"); } else { for (int i = 0; i < pinNum; ++i) { digitalWrite(linePin[0] + i, LOW); } for (int i = 1; i <= 3; ++i) { lens[i] = lens[i + 1]; } lens[4] = gray / 100; int array0[] = {0, 1, 2, 3, 4}; lightLed(linePin[3], array0, lens[4]); lightLed(linePin[2], array0, lens[3]); lightLed(linePin[1], array0, lens[2]); lightLed(linePin[0], array0, lens[1]); } } else { // show nuber unsigned long currentMillis = millis(); if(currentMillis - previousMillis >= interval * 2) { for (int i = 0; i < pinNum; ++i) { digitalWrite(linePin[0] + i, LOW); } numPosition++; if (numPosition == 4) { numPosition = 0; } previousMillis = currentMillis; } else { printNum(nums[numPosition]); digitalWrite(positionPin + numPosition, HIGH); } } }
true
65a1cbf6ce87604e58b06a8c3cb2407e74c13e53
C++
nat-chan/InteractiveCG
/Impressionist/impBrush.cpp
UTF-8
1,607
2.5625
3
[ "MIT" ]
permissive
// // impBrush.cpp // // The implementation of virtual brush. All the other brushes inherit from it. // #include "impressionistDoc.h" #include "impressionistUI.h" #include "impBrush.h" // Static class member initializations int ImpBrush::c_nBrushCount = 0; ImpBrush** ImpBrush::c_pBrushes = NULL; ImpBrush::ImpBrush(ImpressionistDoc* pDoc, char* name) : m_pDoc(pDoc), m_pBrushName(name) { } //--------------------------------------------------- // Return m_pDoc, which connects the UI and brushes //--------------------------------------------------- ImpressionistDoc* ImpBrush::GetDocument(void) { return m_pDoc; } //--------------------------------------------------- // Return the name of the current brush //--------------------------------------------------- char* ImpBrush::BrushName(void) { return m_pBrushName; } //---------------------------------------------------- // Set the color to paint with to the color at source, // which is the coord at the original window to sample // the color from //---------------------------------------------------- void ImpBrush::SetColor (const Point source) { ImpressionistDoc* pDoc = GetDocument(); GLubyte color[3]; memcpy ( color, pDoc->GetOriginalPixel( source ), 3 ); glColor3ubv( color ); } void ImpBrush::SetColorAlpha (const Point source, float alpha) { ImpressionistDoc* pDoc = GetDocument(); GLubyte color[3]; memcpy ( color, pDoc->GetOriginalPixel( source ), 3 ); glColor4f(color[0]/255.0, color[1]/255.0, color[2]/255.0, alpha); }
true
d9a928be3ba041582a1ac0be72aea54c6c53fdf4
C++
gianct79/bst
/ransom note (str).cpp
UTF-8
536
3.1875
3
[]
no_license
#include <iostream> using namespace std; bool ransom_note(string const &magazine, string const &ransom) { int count[128] = {0}; for (auto &c : magazine) { count[c]++; } for (auto &c : ransom) { if (!count[c]) { return false; } count[c]--; } return true; } int main() { cout << ransom_note("oi, seu bundao", "fuck you, you") << '\n'; cout << ransom_note("the quick brown fox jumps over the lazy dog", "abcdefghijklmnopqrstuvwxyz") << '\n'; return 0; }
true
21e6816f618d834909b848febe1ead5893ea15ff
C++
Randl/CS
/External sort/filesize.cpp
UTF-8
347
2.734375
3
[]
no_license
// // Created by Evgenii on 28.09.2015. // #include <fstream> #include "filesize.h" int64_t file_size(const std::string filename) { std::ifstream file(filename.c_str(), std::ifstream::in | std::ifstream::binary); if (!file.is_open()) { return -1; } file.seekg(0, std::ios::end); int size = file.tellg(); file.close(); return size; }
true
308e97dd48474414a1bece69d3148e68450a33b6
C++
LeBronWilly/Engineering_Cpp
/ch02/prog2_5.cpp
BIG5
488
3.671875
4
[]
no_license
// prog2_5, yN~{ #include <iostream> // tAiostreamɮ #include <cstdlib> // tAcstdlibɮ using namespace std; int main(void) { int num1=35; // ŧiܼ num1Aó]Ȭ35 int num2=28; // ŧiܼ num2Aó]Ȭ28 cout<<"I have "<<num1<<" books."<<endl; cout<<"You have "<<num2<<" books."<<endl; cout<<"We have "<<(num1-num2)<<" books."<<endl; system("pause"); return 0; }
true
f93cd14c6b8ec767135063f103f19a94f75dbf9f
C++
SCOTT-HAMILTON/monetcours-app
/builder.h
UTF-8
1,815
2.515625
3
[]
no_license
#ifndef BUILDER_H #define BUILDER_H #include <QObject> #include <QString> #include <QThread> #include <QDir> #include <QDebug> #include <QCoreApplication> #include <QProcess> #include <iostream> class MonetbuildThread : public QThread { Q_OBJECT public: explicit MonetbuildThread(QObject* parent = nullptr) : QThread(parent) {} void setDir(QDir newdir){ dir = newdir; } protected: virtual void run() override{ #ifdef Q_OS_WIN QString script_path('"'+QCoreApplication::applicationDirPath() +"/Monetcours-windows/monetbuild.ps1"+'"'); QString param('"'+dir.absolutePath()+'"'); qDebug() << "script_path" << script_path; qDebug() << "param : " << param; QString cmd("powershell.exe -File "+script_path+' '+param); std::cerr << "cmd : " << cmd.toStdString() << '\n'; [](std::string cmd){ QProcess p; p.start(cmd.c_str()); p.waitForFinished(); std::cerr << p.readAllStandardOutput().toStdString() << '\n'; QFile logsFile(QCoreApplication::applicationDirPath()+"/logs.out"); logsFile.write(p.readAllStandardOutput().toStdString().c_str()); }(cmd.toStdString()); #else std::string cmd("monetbuild.sh \""+dir.absolutePath().toStdString()+'"'); qDebug() << "cmd : " << cmd.c_str(); std::system(cmd.c_str()); #endif emit builded(); } signals: void builded(); private: QDir dir; }; class Builder : public QObject { Q_OBJECT public: explicit Builder(QObject* parent = nullptr); ~Builder(); Q_INVOKABLE void build(); public slots: void emitFinished(); signals: void finished(); private: MonetbuildThread* builder; }; #endif // BUILDER_H
true
7982cf94846a6a3eb4aaec701c604858918553ca
C++
sailzeng/zcelib
/src/commlib/zcelib/zce/util/singleton.h
UTF-8
5,277
3.140625
3
[ "Apache-2.0" ]
permissive
/*! * @copyright 2004-2013 Apache License, Version 2.0 FULLSAIL * @filename zce_boost_singleton.h * @author Sailzeng <sailzeng.cn@gmail.com> * @version * @date 2013年1月1日 * @brief signleton的模版实现。 * * @details * * @note 我其实并不特别赞同使用signleton的的模版,特别是所谓的小技巧的signleton的的模 * 版。你可以看到我的代码里面大部分都是自己实现的signleton instance函数。 * 关于signleton的的模版实现,大致有2个好处,一是避免重复初始化,一是少写代码。 * 首先我个人认为signleton的多次初始化问题是一个被放大夸大来用于卖弄技巧的的问题, * 其实好的代码都应该保证自己的初始化代码是单线程状态,而且由于如果你代码逻辑复杂, * 很多代码都是有先后初始化顺序的,必须先实现A,才能初始化B,而且销毁优势有顺序, * 而且两者顺序可能不一定正好相反(初始化A,B,C,销毁C,B,A), * * 这个问题让我想起来了一句话。时间对于别出心裁的小花样是最无情的,某种程度上我认为 * 这玩意就是这样一个东西, * * 网上有一偏文章是,里面有若干signleton的的模版 * http://leoxiang.com/dev/different-cpp-singleton-implementaion * 我自己对这个问题也做过分析, * http://www.cnblogs.com/fullsail/archive/2013/01/03/2842618.html */ #pragma once namespace zce { //======================================================================================================== // /*! * @brief 所谓的普通青年的单件模版,用于单件模式的快速应用, * 优点:含义清晰,方法明确,构造顺序可控,销毁顺序正好相反, * 和C++大部分语义一致, * 缺点:多线程以及特殊的构造依赖和销毁依赖仍然不支持, * 个人感觉在依赖关系不大,不需要考虑所谓多线程的初始化过程 * 可以使用 * @tparam T 希望使用singleton模式的数据结构 */ template <typename T> class singleton { public: ///实例函数 inline static T* instance() { static T obj; return &obj; } private: /// ctor is hidden singleton() = delete; /// copy ctor is hidden singleton(singleton const&) = delete; }; //======================================================================================================== /*! * @brief 这个准确说并不是BOOST的singleton实现,而是BOOST的POOL库的 * singleton实现。用于快速创建SingleTon模式的代码。 * 优点:多线程安全,存在(构造)依赖关系下,可以保证构造安全 * 缺点:代码理解困难,对于如果存在复杂的先后生成关系调用顺序仍然 * 有问题(类全局静态变量的初始化顺序仍然是不可控的), * 个人并不是特别推荐使用这个模版,仍然使用类静态变量这种不可控制 * 周期的方式,而且中间的技巧,呵呵。(你第一次就看明白了?) * @tparam T 希望使用singleton模式的数据结构 */ template <typename T> class b_singleton { private: struct object_creator { object_creator() { b_singleton<T>::instance(); } inline void do_nothing() const {} }; //利用类的静态对象object_creator的构造初始化,在进入main之前已经调用了instance //从而避免了多次初始化的问题 static object_creator create_object_; public: // static T* instance() { static T obj; //do_nothing 是必要的,do_nothing的作用有点意思, //如果不加create_object_.do_nothing();这句话,在main函数前面 //create_object_的构造函数都不会被调用,instance当然也不会被调用, //我的估计是模版的延迟实现的特效导致,如果没有这句话,编译器也不会实现 // Singleton_WY<T>::object_creator,所以就会导致这个问题 create_object_.do_nothing(); return &obj; } }; //因为create_object_是类的静态变量,必须有一个通用的声明 template <typename T> typename zce::b_singleton<T>::object_creator \ zce::b_singleton<T>::create_object_; //======================================================================================================== //古典的singleton template <typename T> class c_singleton { public: typedef T ST; ///实例函数 inline static T* instance() { return instance_; } ///实例函数 static void set(T* instance) { instance_ = instance; return; } static void clear() { delete instance_; instance_ = nullptr; } private: static T* instance_; }; template <typename T> zce::c_singleton<T>::ST * \ zce::c_singleton<T>::instance_ = nullptr; //======================================================================================================== }
true
3d20ad1bf8e35185e0ef568fa342e910a63e0d20
C++
tjdgus3537/algorithm
/baekjoon/DP/9095.cpp
UTF-8
602
2.609375
3
[]
no_license
#include <iostream> using namespace std; void solution(); int main() { #ifdef _DEBUG freopen("/home/ubuntu/workspace/input", "r", stdin); #endif solution(); return 0; } void solution() { int dp[11] = {0,}; int T, n; dp[1] = 1; dp[2] = 2; dp[3] = 4; //1개 전 값에 1 더하기, 2개 전 값에 2더하기, 3개 전 값에 3 더하기 for(int i = 4; i < 11; i++) dp[i] = dp[i - 1] + dp[i - 2] + dp[i - 3]; cin >> T; while(T--) { cin >> n; cout << dp[n] << endl; } }
true
846a8243697664b2edc53fc257c0f3fa1b7ab655
C++
Vancasola/DataStructure
/DataStructure/A1028.cpp
UTF-8
1,156
2.890625
3
[]
no_license
// // A1028.cpp // DataStructure // // Created by vancasola on 2019/12/31. // Copyright © 2019 none. All rights reserved. // 4:49 5:04 /* #include <stdio.h> #include <iostream> #include <string> #include <cstring> #include <algorithm> #include <vector> using namespace std; struct record { int id; string name; int grade; }; bool cmp1(const record& a,const record& b) { return a.id<b.id; } bool cmp2(const record& a,const record& b) { if(a.name!=b.name)return a.name<b.name; return a.id<b.id; } bool cmp3(const record& a,const record& b) { if(a.grade!=b.grade)return a.grade<b.grade; return a.id<b.id; } int main() { int n,c; vector< record> v; cin>>n; if(!n)return 0; cin>>c; for(int i=0;i<n;i++) { record r; cin>>r.id>>r.name>>r.grade; v.push_back(r); } if(c==1) sort(v.begin(), v.end(), cmp1); else if(c==2) sort(v.begin(), v.end(), cmp2); else if(c==3) sort(v.begin(), v.end(), cmp3); for(int i=0;i<v.size();i++) { printf("%06d %s %d\n",v[i].id,v[i].name.c_str(),v[i].grade); } return 0; } */
true
2bc8c5e57f3822aec36fd3495774fa34d0ad70cf
C++
krystianwozniak92/ZSSK
/Source/CourierDelivery/CourierDelivery/Edge.h
WINDOWS-1250
252
2.765625
3
[]
no_license
#pragma once class Edge { public: // Wierzchoki int vertexA; int vertexB; // Konstruktor Edge(); // Konstruktor Edge(int, int); // Destruktor ~Edge(void); // Operator porwnania friend bool operator==(const Edge&, const Edge&); };
true
f8e8525197b4099c19c21326537756e4b2861234
C++
Jiyoung-h/algorithm
/programmers/2 x n 타일링.cpp
UTF-8
304
2.859375
3
[]
no_license
#include <string> #include <vector> using namespace std; int solution(int n) { vector<int> d; for(int i=0; i<n; i++){ if(i==0) d.push_back(1); else if(i==1) d.push_back(2); else d.push_back((d[i-1]+d[i-2])%1000000007); } int answer = d[n-1]; return answer; }
true
ea69b01e62350438aa32b5a8248752d597cd644d
C++
marc-hanheide/cogx
/subarchitectures/conceptual.sa/branches/avs-iros11/src/c++/conceptual/components/PlaceholderPropertyUpdater/PlaceholderPropertyUpdater.h
UTF-8
3,441
2.859375
3
[]
no_license
/** * @author Andrzej Pronobis * * Declaration of the conceptual::PlaceholderPropertyUpdater class. */ #ifndef CONCEPTUAL_PLACEHOLDERPROPERTYUPDATER_H #define CONCEPTUAL_PLACEHOLDERPROPERTYUPDATER_H #include <cast/architecture/ManagedComponent.hpp> #include "ConceptualData.hpp" #include "DefaultData.hpp" #include "SpatialProbabilities.hpp" #include "SpatialProperties.hpp" namespace conceptual { /** * @author Andrzej Pronobis * * Updates the values of placeholder properties on the spatial.sa WM. */ class PlaceholderPropertyUpdater: public cast::ManagedComponent { public: /** Constructor. */ PlaceholderPropertyUpdater(); /** Destructor. */ virtual ~PlaceholderPropertyUpdater(); protected: /** Called by the framework to configure the component. */ virtual void configure(const std::map<std::string,std::string> & _config); /** Called by the framework after configuration, before run loop. */ virtual void start(); /** The main run loop. */ virtual void runComponent(); /** Called by the framework after the run loop finishes. */ virtual void stop(); private: /** World state changed, infer and then update the coma room structs. */ void worldStateChanged(const cast::cdl::WorkingMemoryChange &wmChange); void placeChanged(const cast::cdl::WorkingMemoryChange &wmChange); /** Updates or creates the property on Spatial.SA working memory. */ void updateRoomCategoryPlaceholderProperty(int placeholderId, std::string category, const SpatialProbabilities::ProbabilityDistribution &pd); /** Returns WM id of property based on the info stored in _placeholderProperties. */ cast::cdl::WorkingMemoryAddress getRoomCategoryPlaceholderPropertyWmAddress( int placeholderId, std::string category); /** Updates the probability distribution in the property struct. */ void setRoomCategoryPlaceholderPropertyDistribution( SpatialProperties::RoomCategoryPlaceholderPropertyPtr propertyPtr, const SpatialProbabilities::ProbabilityDistribution &pd); bool placeholderExists(int id); private: pthread_cond_t _worldStateChangedSignalCond; pthread_mutex_t _worldStateChangedSignalMutex; /** True if the world state has changed since the last time we checked. */ bool _worldStateChanged; /** Vector of Placeholder Ids. */ std::vector<int> _placeholderIds; /** Name of the QueryHandler component. */ std::string _queryHandlerName; /** Name of the DefaultChainGraphInferencer component. */ std::string _defaultChainGraphInferencerName; /** Names of all room categories. */ DefaultData::StringSeq _roomCategories; /** ICE proxy to the QueryHandlerInterface. */ ConceptualData::QueryHandlerServerInterfacePrx _queryHandlerServerInterfacePrx; /** ICE proxy to the DefaultData::ChainGraphInferencerInterface. */ DefaultData::ChainGraphInferencerServerInterfacePrx _defaultChainGraphInferencerServerInterfacePrx; /** Map of place wmAddress -> place id */ std::map<cast::cdl::WorkingMemoryAddress, int> _placeWmAddressMap; private: struct RoomCategoryPlaceholderPropertyInfo { cast::cdl::WorkingMemoryAddress wmAddress; int placeholderId; std::string category; }; /** Map containing all the placeholder properties created by the component. */ std::list<RoomCategoryPlaceholderPropertyInfo> _placeholderProperties; }; // class PlaceholderPropertyUpdater } // namespace #endif // CONCEPTUAL_PLACEHOLDERPROPERTYUPDATER_H
true
2f94ff443545864ee272a07554e9b2ca991ea986
C++
sshjj/note
/leetcode/DFS,BFS/695.岛屿的最大面积.cpp
UTF-8
1,456
3.515625
4
[]
no_license
给定一个包含了一些 0 和 1 的非空二维数组 grid 。 一个 岛屿 是由一些相邻的 1 (代表土地) 构成的组合,这里的「相邻」要求两个 1 必须在水平或者竖直方向上相邻。你可以假设 grid 的四个边缘都被 0(代表水)包围着。 找到给定的二维数组中最大的岛屿面积。(如果没有岛屿,则返回面积为 0 。) 示例 1: [[0,0,1,0,0,0,0,1,0,0,0,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,1,1,0,1,0,0,0,0,0,0,0,0], [0,1,0,0,1,1,0,0,1,0,1,0,0], [0,1,0,0,1,1,0,0,1,1,1,0,0], [0,0,0,0,0,0,0,0,0,0,1,0,0], [0,0,0,0,0,0,0,1,1,1,0,0,0], [0,0,0,0,0,0,0,1,1,0,0,0,0]] 对于上面这个给定矩阵应返回 6。注意答案不应该是 11 ,因为岛屿只能包含水平或垂直的四个方向的 1 。 class Solution { public: int maxAreaOfIsland(vector<vector<int>>& grid) { int ans = 0; for(int i =0;i<grid.size();i++){ for(int j = 0;j<grid[0].size();j++){ ans = max(ans,dfs(grid,i,j)); } } return ans; } int dfs(vector<vector<int>>&grid,int i,int j){ if(i<0 || j<0 || i>=grid.size() || j>=grid[0].size()||grid[i][j]!=1)return 0; grid[i][j] = 0; int dx[4] = {-1,0,1,0},dy[4] = {0,1,0,-1}; int res =1; for(int k =0;k<4;k++){ int x = i+dx[k], y = j+dy[k]; res +=dfs(grid,x,y); } return res; } };
true
14653ddfe143fa85c222dd6ab9de2d3701d80e2e
C++
CODARcode/MGARD
/src/unstructured/estimators.cpp
UTF-8
3,094
2.53125
3
[ "Apache-2.0" ]
permissive
#include "unstructured/estimators.hpp" #include <cassert> #include <limits> #include <stdexcept> #include "blas.hpp" #include "unstructured/MassMatrix.hpp" namespace mgard { // We might be able to obtain better bounds by using some information about // the hierarchy. If I recall correctly, our proofs depend on (at least) the // refinement strategy used. For now, we just check its dimension. RatioBounds s_square_estimator_bounds(const MeshHierarchy &hierarchy) { const std::size_t d = hierarchy.meshes.front().topological_dimension; if (d == 2) { return {.realism = 0.1, .reliability = 1}; } else if (d == 3) { return {.realism = 1.f / 24, .reliability = 1}; } else { throw std::domain_error("unsupported topological dimension"); } } static double s_square_estimator(const MultilevelCoefficients<double> u, const MeshHierarchy &hierarchy, const float s) { std::vector<double> squares_for_estimate(hierarchy.L + 1); // TODO: allow passing in of memory. std::vector<double> scratch(hierarchy.ndof_new(hierarchy.L)); double *const rhs = scratch.data(); for (std::size_t l = 0; l <= hierarchy.L; ++l) { const MeshLevel &mesh = hierarchy.meshes.at(l); const std::size_t n = hierarchy.ndof_new(l); // Originally, `hierarchy.new_nodes` returned a `moab::Range`, which could // be passed straight to the constructor below. In order to avoid problems // with iterators pointing to temporaries that have gone out of scope, // `hierarchy.new_nodes` now returns a pair of iterators to the appropriate // `moab::Range` in `hierarchy`. Rather than rewriting `SubsetMassMatrix` to // deal with iterators, we will just manually construct the `moab::Range`. const RangeSlice<moab::Range::const_iterator> iterators = hierarchy.new_nodes(l); const moab::Range::const_iterator new_nodes_begin = iterators.begin(); moab::Range::const_iterator new_nodes_end = iterators.end(); // Check that it's safe to decrement `new_nodes_end`. assert(new_nodes_begin != new_nodes_end); const moab::Range new_nodes(*new_nodes_begin, *--new_nodes_end); ContiguousSubsetMassMatrix M(mesh, new_nodes); // Nodal values of multilevel component on level `l`. double const *const mc = hierarchy.on_new_nodes(u, l).begin(); M(mc, rhs); squares_for_estimate.at(l) = blas::dotu(n, mc, rhs); } // Could have accumulated this as we went. double square_estimate = 0; for (std::size_t l = 0; l <= hierarchy.L; ++l) { // Code repeated here from `norms.cpp`. square_estimate += std::exp2(2 * s * l) * squares_for_estimate.at(l); } return square_estimate; } double estimator(const MultilevelCoefficients<double> u, const MeshHierarchy &hierarchy, const float s) { if (s == std::numeric_limits<double>::infinity()) { throw std::domain_error( "pointwise estimator not implemented for unstructured grids"); } else { return std::sqrt(s_square_estimator(u, hierarchy, s)); } } } // namespace mgard
true
260dcb22f03486866d4ec99f72d2baf98df304ac
C++
jing-zhao/algorithm
/array/minRangeIn2DArray.cpp
UTF-8
1,680
3.53125
4
[]
no_license
#include <vector> using namespace std; // There is two dimensional array where each sub array (row) is sorted, i.e. // [1 10000 2000] // [20 10001 5000] // [55 10002 222222]] // Find a minimum range contain a number from each row. For above array it should be (10000-10002) range vector<int> minRange(vector<vector<int>>& matrix) { vector<int> range; int row = matrix.size(); if (row == 0) return range; int col = matrix[0].size(); if (col == 0) return range; vector<int> indexes(row, 0); int minRange = INT_MAX; while (1) { int minVal = INT_MAX, minRow = 0, maxVal = INT_MIN; for (int i = 0; i < row; i++) { if (indexes[i] >= col) return range; if (matrix[i][indexes[i]] < minVal) { minVal = matrix[i][indexes[i]]; minRow = i; } maxVal = max(maxVal, matrix[i][indexes[i]]); } if (maxVal - minVal < minRange) { minRange = maxVal - minVal; if (!range.size()) range.insert(range.end(), 2, 0); range[0] = minVal; range[1] = maxVal; } indexes[minRow]++; } return range; } int main(int argc, _TCHAR* argv[]) { vector<vector<int>> matrix; int r1[] = {1, 10000, 2000}; int r2[] = {20, 10001, 5000}; int r3[] = {55, 10002, 222222}; vector<int> v1; for (int i = 0; i < sizeof(r1)/sizeof(int); i++) v1.push_back(r1[i]); matrix.push_back(v1); vector<int> v2; for (int i = 0; i < sizeof(r2)/sizeof(int); i++) v2.push_back(r2[i]); matrix.push_back(v2); vector<int> v3; for (int i = 0; i < sizeof(r3)/sizeof(int); i++) v3.push_back(r3[i]); matrix.push_back(v3); vector<int> ret = minRange(matrix); return 0; }
true
8b73f30d31669fc2578fc0012ee3631afb9b5c1c
C++
dsalearning/Nano33-AIoT
/arduino.c/button2_LED/button2_LED.ino
UTF-8
499
2.890625
3
[]
no_license
#define BTN 2 #define LED 13 void setup() { // put your setup code here, to run once: Serial.begin(9600); pinMode(BTN,INPUT_PULLUP); //1.1 上拉電阻 pinMode(LED,OUTPUT); } void loop() { // put your main code here, to run repeatedly: bool btnState = digitalRead(BTN); Serial.println(String(btnState)); if(btnState==LOW){ Serial.println("按鈕被按了"); digitalWrite(LED,HIGH); }else{ Serial.println("沒按按鈕"); digitalWrite(LED,LOW); } delay(10); }
true
a8fab2f5bad1242c2b493d6d1cc30af9687dead2
C++
mfurkin/logger
/LoggerList.cpp
ISO-8859-7
2,899
2.984375
3
[]
no_license
/* * LoggerList.cpp * * Created on: 22 . 2017 . * Author: */ #include "LoggerList.h" LoggerList& LoggerList::getLoggerList() { static LoggerList list; return list; } void LoggerList::addLogger(std::string name, std::string fname) { EnterCriticalSection(&c_section); // printf("LoggerList::addLogger this=%p name=%s\n",this,name.c_str()); if (!(exists(name))) { loggers[name] = new Logger(fname); } LeaveCriticalSection(&c_section); } void LoggerList::deleteLogger(std::string name) { EnterCriticalSection(&c_section); if (exists(name)) { Logger* ptr = loggers[name]; // printf("LoggerList::deleteLogger ptr=%p\n",ptr); (*ptr).stop(); // printf("LoggerList::deleteLogger pt2\n"); loggers.erase(name); // printf("LoggerList::deleteLogger pt3\n"); } LeaveCriticalSection(&c_section); } Logger* LoggerList::getLogger(std::string name) { Logger* result = NULL; EnterCriticalSection(&c_section); // printf("LoggerList::getLogger this=%p name=%s\n",this,name.c_str()); result = (exists(name)) ? loggers[name] : NULL; LeaveCriticalSection(&c_section); return result; } LoggerList::LoggerList() { InitializeCriticalSection(&c_section); } LoggerList::~LoggerList() { DeleteCriticalSection(&c_section); } void LoggerList::stopLogger(std::string name) { } int LoggerList::exists(std::string& name) { std::map<std::string,Logger*>::iterator it = loggers.find(name); int result = (it != loggers.end()); // printf("LoggerList::exists this=%p name=%s result=%d\n",this,name.c_str(),result); return result; } void __declspec(dllexport) createLogger(const char* name, const char* fname) { // printf("createLogger enter name=%s\n",name); LoggerList& list = LoggerList::getLoggerList(); list.addLogger(std::string(name),std::string(fname)); } int __declspec(dllexport) log(const char* loggerName, const char* tag, const char* msg) { int result; // printf("log enter name=%s tag=%s msg=%s\n",loggerName,tag,msg); LoggerList& list = LoggerList::getLoggerList(); Logger* ptr = list.getLogger(loggerName); // printf("log ptr=%p\n",ptr); if (!(ptr)) result = 0; else { result = 1; std::string tag_st(tag),msg_st(msg); (*ptr).log(tag_st,msg_st); } return result; } int __declspec(dllexport) logPtr(const char* loggerName, const char* tag, const char* msg, unsigned p) { int result; LoggerList& list = LoggerList::getLoggerList(); std::string loggerName_st(loggerName); Logger* ptr = list.getLogger(loggerName_st); if (!(ptr)) result = 0; else { result = 1; std::string tag_st(tag),msg_st(msg); (*ptr).logPtr(tag_st,msg_st,p); } return result; } void __declspec(dllexport) deleteLogger(const char* name) { LoggerList& list = LoggerList::getLoggerList(); std::string name_st(name); list.deleteLogger(name_st); }
true
3f854ccae5cae2a75e3b705e404c74e15853a126
C++
mridulraturi7/Algorithms
/Searching Algorithms/Searching Problems/Problem11.cpp
UTF-8
822
3.640625
4
[]
no_license
/* Search an element in an Array. This problem is taken from GFG. Problem Statement - https://practice.geeksforgeeks.org/problems/search-an-element-in-an-array/0/?category[]=Searching&difficulty[]=-1&page=1&query=category[]Searchingdifficulty[]-1page1 Difficulty - Basic */ #include<iostream> using namespace std; int main() { int testCase; cin>>testCase; while(testCase-- != 0) { int n, k; cin>>n; int *array = new int[n]; for(int i = 0; i < n; i++) { cin>>array[i]; } cin>>k; int index = -1; for(int i = 0; i < n; i++) { if(array[i] == k) { index = i; break; } } cout<<index<<endl; } return 0; }
true
029aef1d5183699f28de1e0f5ccbc6af7349f554
C++
ZeroNerodaHero/USACO-Training-Gateway
/dp120On1/treasures.cpp
UTF-8
1,955
2.78125
3
[]
no_license
/* ID: billyz43 PROG: treasures LANG: C++11 */ #include <iostream> #include <fstream> #include <algorithm> #include <vector> #include <cstring> #include <climits> #include <unordered_map> #include <iomanip> #include <cmath> #define INF 160000 std::ifstream in("treasures.in"); std::ofstream out("treasures.out"); using namespace std; struct node{ int x,y,p,c,sx,ex;; bool operator < (node const& o) const{ if(sx == o.sx) return ex < o.ex; return sx < o.sx; } }; int N; node ar[1000]; int dp[1005]; int ans; void print(){ for(int i = 0; i < N; i++){ cout << i << " " << dp[i] << endl; } } int over(int i, int j){ int b = (ar[i].ex - ar[j].sx); if(b < 0) b = -b; if(b&1){ b /= 2; return b*b+b; } else{ b /= 2; return b*b; } } void dfs(){ for(int i = 0; i < N; i++){ dp[i] = ar[i].p - ar[i].c; } ans = max(ans,dp[0]); //cout << "dp " <<0 << ' '<< dp[0] << endl; for(int i = 1; i < N; i++){ for(int j = 0; j < i; j++){ if(ar[i].ex <= ar[j].ex){ dp[j] += ar[i].p; // ans = max(ans,dp[j]); //cout << "\tdp j " <<j << ' '<< dp[j] << endl; } else{ int a = dp[j] + ar[i].p - ar[i].c;; if((ar[j].ex - ar[i].sx) > 1){ a+=over(j,i); //cout << "over " << over(j,i) << endl; } dp[i] = max(dp[i],a); //cout << "\tdp i " <<i << ' '<< dp[i] << endl; } } //cout << "dp i " <<i << ' '<< dp[i] << endl; } for(int i = 0; i < N; i++){ if(dp[i] > ans) ans = dp[i]; } } int main(){ in >> N; for(int i = 0; i < N; i++){ in >> ar[i].x >> ar[i].y >> ar[i].p; ar[i].sx = ar[i].x+ar[i].y; ar[i].ex = ar[i].x-ar[i].y; ar[i].c = (ar[i].y* ar[i].y); } sort(ar,ar+N); dfs(); // print(); out << ans << endl; }
true
0ad5b29d775e15306fab99bb5a0f5e397f2c799b
C++
mi2think/DoPixel
/DpLib/DpLog.cpp
UTF-8
2,011
2.515625
3
[]
no_license
/******************************************************************** created: 2016/01/07 created: 7:1:2016 23:33 filename: D:\OneDrive\3D\DpLib\DpLib\DpLog.cpp file path: D:\OneDrive\3D\DpLib\DpLib file base: DpLog file ext: cpp author: mi2think@gmail.com purpose: Log *********************************************************************/ #include "DpLog.h" #include <windows.h> #include <iostream> #include <cstdarg> namespace dopixel { Log::Log() : hwnd_(nullptr) , newline_(true) {} void Log::WriteBuf(int level, const char* fmt, ...) { SetTextColor(GetTextColor(level)); static char buffer[1024]; va_list ap; va_start(ap, fmt); vsprintf_s(buffer, fmt, ap); va_end(ap); buffer[1023] = 0; std::ostream* os = nullptr; if (level == Error || level == Fatal) os = &std::cout; else os = &std::cerr; (*os) << buffer; if (newline_) (*os) << std::endl; } unsigned short Log::GetTextColor(int level) { unsigned short color; switch (level) { case Info: // info is bright white color = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY; break; case Warn: // warn is bright yellow color = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_INTENSITY; break; case Error: // error is red color = FOREGROUND_RED | FOREGROUND_INTENSITY; break; case Fatal: // fatal is white on red color = FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY | BACKGROUND_RED | BACKGROUND_INTENSITY; break; default: // other is cyan color = FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_INTENSITY; break; } return color; } void Log::SetTextColor(unsigned short color) { if (hwnd_ == NULL) { hwnd_ = GetStdHandle(STD_OUTPUT_HANDLE); } SetConsoleTextAttribute(hwnd_, color); } Log::ScopeNewline::ScopeNewline(bool newline) { newline_ = GLOG.GetNewline(); GLOG.SetNewline(newline); } Log::ScopeNewline::~ScopeNewline() { GLOG.SetNewline(newline_); } }
true
cfc1767a4fa19a36e5c1f9a3a1e54a388b1a0699
C++
shinbyh/ns3-p2p-wmn
/route_flow_accept_request.cc
UTF-8
4,168
2.671875
3
[]
no_license
/* * route_flow_accept_request.cc * * Created on: Feb 17, 2018 * Author: bhshin */ #include "route_flow_accept_request.h" #include <sstream> #include "string_tokenizer.h" #include "my_config.h" FlowAcceptRequest::FlowAcceptRequest(Flow flow, int seqNo, uint32_t senderId, uint32_t nextHop, int TTL) { this->flow = flow; this->seqNo = seqNo; this->senderId = senderId; this->nextHop = nextHop; this->TTL = TTL; } FlowAcceptRequest::FlowAcceptRequest(){ this->seqNo = 0; this->senderId = 9999999; this->nextHop = 9999999; this->TTL = 0; } FlowAcceptRequest::~FlowAcceptRequest() { } const Flow& FlowAcceptRequest::getFlow() const { return flow; } void FlowAcceptRequest::setFlow(const Flow& flow) { this->flow = flow; } const QoSRequirement& FlowAcceptRequest::getQosReq() const { return qosReq; } void FlowAcceptRequest::setQosReq(const QoSRequirement& qosReq) { this->qosReq = qosReq; } uint32_t FlowAcceptRequest::getSenderId() const { return senderId; } void FlowAcceptRequest::setSenderId(uint32_t senderId) { this->senderId = senderId; } int FlowAcceptRequest::getTtl() const { return TTL; } void FlowAcceptRequest::setTtl(int ttl) { TTL = ttl; } string FlowAcceptRequest::serializeTrace() { if(this->detourTrace.size() == 0){ return "--"; } else { stringstream ss; for(size_t i=0; i<this->detourTrace.size(); i++){ if(i + 1 < this->detourTrace.size()) ss << this->detourTrace[i] << ","; else ss << this->detourTrace[i]; } return ss.str(); } } const string FlowAcceptRequest::serialize() { stringstream ss; ss << std::fixed; ss << ROUTE_FLOW_ACCEPT_REQUEST << "@" << this->flow.getSrc() << "@" << this->flow.getSrcPort() << "@" << this->flow.getDst() << "@" << this->flow.getDstPort() << "@" << this->flow.getTypeStr() << "@" << this->seqNo << "@" << this->senderId << "@" << this->nextHop << "@" << this->TTL << "@" << this->qosReq.serialize() << "@" << this->linkQuality.serialize() << "@" << serializeTrace(); return ss.str(); } uint32_t FlowAcceptRequest::getNextHop() const { return nextHop; } int FlowAcceptRequest::getSeqNo() const { return seqNo; } void FlowAcceptRequest::setSeqNo(int seqNo) { this->seqNo = seqNo; } void FlowAcceptRequest::setNextHop(uint32_t nextHop) { this->nextHop = nextHop; } FlowAcceptRequest FlowAcceptRequest::parse(string str) { vector<string> tokens; tokenizeString(str, tokens, "@"); //atoi(tokens[0].c_str()); // message type, not used here. uint32_t src = atoi(tokens[1].c_str()); int srcPort = atoi(tokens[2].c_str()); uint32_t dst = atoi(tokens[3].c_str()); int dstPort = atoi(tokens[4].c_str()); FlowType::Type type = checkType(tokens[5]); Flow flow(src, srcPort, dst, dstPort, type); //this->setFlow(flow); int seqNo = atoi(tokens[6].c_str()); uint32_t senderId = atoi(tokens[7].c_str()); uint32_t nextHop = atoi(tokens[8].c_str()); int TTL = atoi(tokens[9].c_str()); QoSRequirement qosReq = QoSRequirement::parse(tokens[10]); LinkQuality lq = LinkQuality::parse(tokens[11]); vector<uint32_t> detourTrace = FlowAcceptRequest::parseDetourIDs(tokens[12]); FlowAcceptRequest request(flow, seqNo, senderId, nextHop, TTL); request.setQosReq(qosReq); request.setLinkQuality(lq); request.setDetourTrace(detourTrace); return request; } vector<uint32_t> FlowAcceptRequest::parseDetourIDs(std::string str){ vector<uint32_t> ids; if(str == "--") return ids; std::vector<std::string> tokens; tokenizeString(str, tokens, ","); for(std::string addr : tokens){ ids.push_back(atoi(addr.c_str())); } return ids; } void FlowAcceptRequest::decrementTtl() { if(this->TTL > 0) this->TTL--; } LinkQuality* FlowAcceptRequest::getLinkQuality() { return &linkQuality; } void FlowAcceptRequest::setLinkQuality(const LinkQuality& linkQuality) { this->linkQuality = linkQuality; } const vector<uint32_t>& FlowAcceptRequest::getDetourTrace() const { return detourTrace; } void FlowAcceptRequest::addDetourTrace(uint32_t nodeId) { this->detourTrace.push_back(nodeId); } void FlowAcceptRequest::setDetourTrace(const vector<uint32_t>& detourTrace) { this->detourTrace = detourTrace; }
true
71033f6c1ee0bc7cab8449abda3646c4850a1422
C++
zakar/LittleWorld
/src/math/Frustum.cpp
UTF-8
2,339
3
3
[]
no_license
#include "Frustum.h" using namespace std; void Frustum::update(Matrix4x4f projection) { // left clipping plane: planes[0].a = projection.m[3] + projection.m[0]; planes[0].b = projection.m[7] + projection.m[4]; planes[0].c = projection.m[11] + projection.m[8]; planes[0].d = projection.m[15] + projection.m[12]; // right clipping plane: planes[1].a = projection.m[3] - projection.m[0]; planes[1].b = projection.m[7] - projection.m[4]; planes[1].c = projection.m[11] - projection.m[8]; planes[1].d = projection.m[15] - projection.m[12]; // top clipping plane: planes[2].a = projection.m[3] - projection.m[1]; planes[2].b = projection.m[7] - projection.m[5]; planes[2].c = projection.m[11] - projection.m[9]; planes[2].d = projection.m[15] - projection.m[13]; // bottom clipping plane: planes[3].a = projection.m[3] + projection.m[1]; planes[3].b = projection.m[7] + projection.m[5]; planes[3].c = projection.m[11] + projection.m[9]; planes[3].d = projection.m[15] + projection.m[13]; // near clipping plane: planes[4].a = projection.m[3] + projection.m[2]; planes[4].b = projection.m[7] + projection.m[6]; planes[4].c = projection.m[11] + projection.m[10]; planes[4].d = projection.m[15] + projection.m[14]; // far clipping plane: planes[5].a = projection.m[3] - projection.m[2]; planes[5].b = projection.m[7] - projection.m[6]; planes[5].c = projection.m[11] - projection.m[10]; planes[5].d = projection.m[15] - projection.m[14]; float length; for (int i = 0; i < 6; ++i) { length = sqrtf(planes[i].a * planes[i].a + planes[i].b * planes[i].b + planes[i].c * planes[i].c); planes[i].a /= length; planes[i].b /= length; planes[i].c /= length; planes[i].d /= length; } } float Frustum::distanceFromPlaneToPoint(const Plane &plane, const Vector3 &point) { return plane.a * point.x + plane.b * point.y + plane.c * point.z + plane.d; } bool Frustum::sphereInFrustum(const Vector3 &center, float radius) { unsigned int within = 0; for(unsigned int i = 0; i < 6; i ++) { if (distanceFromPlaneToPoint(planes[i], center) > -radius) { within ++; } } return (within == 6) ? true : false; }
true
ef0730a3bda64c365cf3bd9a328e8232d4c73643
C++
chwdy/6913-CSA-LAB
/LAB2/test.cpp
UTF-8
769
3.15625
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <bitset> #include <fstream> using namespace std; bitset<32> bitadd(bitset<32> a, bitset<32> b) { bitset<32> re = a; bitset<32> temp = b; bitset<32> newre; bitset<32> newtemp; do { newre = re ^ temp; newtemp = re & temp; newtemp <<= 1; re = newre; temp = newtemp; } while (temp.any()); return re; } bitset<32> signextimm(bitset<16> ori) { int msb = ori.to_string().substr(0, 1)=="1"?-1:0; bitset<32> res = bitset<32>(msb); res <<= 16; res = bitadd(res, bitset<32>(ori.to_string())); cout<<ori<<":res after immextend : "<<res<<endl; return res; } int main(){ signextimm(bitset<16>(-1)); return 0; }
true
c8e88799af061ab4fabd26841cf88bf653c1c674
C++
tameer7595/school-app
/test.cpp
UTF-8
2,287
3.421875
3
[]
no_license
// // Created by tameer on 9/5/19. // #include <iostream> #include "person.h" #include "student.h" #include "teacher.h" #include "school.h" #include <list> #include "test.h" #include "String.h" void Test::test() { std::cout << "Welcome To My School" << std::endl; std::vector<Person*> p = std::vector<Person*>(11); String student_names[8] = {"Tameer","Kameel","Rawad","Arwa","Sari","daniel","Ahmned","Shady"}; String teacher_names[3] = {"Amitai","Ola","Margilit"}; String leason_names[3] = {"c++","python","data stucture"}; School *school = initSchool(p,student_names,teacher_names,leason_names); std::cout<<"running action method:"<<std::endl; for(unsigned int i = 0 ; i < p.size() ; i++){ p[i]->action(); } for(unsigned i =0 ;i<p.size() ; i++){ delete p[i]; } delete school; } /* help func that print a list of the students paired with a certain teacher*/ School* Test:: initSchool(std::vector<Person*> &p,String student_names[],String teacher_names[],String leason_names[]){ School *school = new School(); for (int i=0 ; i<8 ; i++){ Student* student = new Student(student_names[i],96); school->addStudent(student); p[i] = student; } for (int i=8 ; i<11 ; i++){ Teacher * teacher = new Teacher(teacher_names[i%3] ,leason_names[i%3]); school->addTeacher(teacher); p[i] = teacher; } school->pairTeacherToStudent(4); for ( int i = 0 ; i < 3; i++) { showTeachersStudent(*school,teacher_names[i]); } cout<<"after deleting teacher with id 9:"<<endl; school->deleteTeacher(9); for ( int i = 0 ; i < 3; i++) { showTeachersStudent(*school,teacher_names[i]); } cout<<"after deleting student with id 2:"<<endl; school->deleteStudent(2); for ( int i = 0 ; i < 3; i++) { showTeachersStudent(*school,teacher_names[i]); } return school; } void Test :: showTeachersStudent(School school , String teachername){ std::list<Student *> l = school.getTeacherStudents(teachername); std::list<Student *>::iterator it; if(l.size() != 0){ for (it = l.begin(); it != l.end(); ++it) { std::cout << '\t' << (*it)->getName(); std::cout << '\n'; } } }
true
23381801488d73653ce9f7992d371997b22da26e
C++
Skalwalker/CodeCollector
/source/A/BeautifulMatrix.cpp
UTF-8
512
2.859375
3
[ "MIT" ]
permissive
/* Beautiful Matrix - URL: https://codeforces.com/contest/263/problem/A - Tags: - implementation - 700 */ #include <bits/stdc++.h> using namespace std; int main(){ int mat[5][5]; int posx, posy, count = 0; for(int i = 0; i < 5; i++){ for(int j = 0; j < 5; j++){ cin >> mat[i][j]; if(mat[i][j] == 1){ posx = i; posy = j; } } } count = abs(posx - 2) + abs(posy - 2); cout << count << endl; }
true
85a63c187c5830cdea9ce4c0a378b64e0d93062b
C++
ajorians/nHearts
/src/Metrics.cpp
UTF-8
3,039
2.953125
3
[]
no_license
#include "Metrics.h" Metrics::Metrics() { } bool Metrics::SetCardDimensions(int nWidth, int nHeight) { m_nCardWidth = nWidth; m_nCardHeight = nHeight; m_nTop = SCREEN_HEIGHT - nHeight - 35; return true; } void Metrics::SetNumCards(int nNumCards) { m_nNumCards = nNumCards; } int Metrics::GetNumCards() const { return m_nNumCards; } int Metrics::GetXPos(CardLocation eLocation, int nCardIndex) const { if( eLocation == LocLeft ) { return 0; } else if( eLocation == LocRight ) { return SCREEN_WIDTH-m_nCardWidth; } return GetLeft() + nCardIndex*GetCardOffsetX(); } int Metrics::GetYPos(CardLocation eLocation, int nCardIndex) const { if( eLocation == LocBottom ) { return GetTop(); } else if( eLocation == LocLeft || eLocation == LocRight ) { return 30 + nCardIndex*(m_nCardHeight/3); } return 0; } int Metrics::GetSelectedXPos(int nSelectedIndex) const { int nWidthRemaining = SCREEN_WIDTH - m_nCardWidth*3; int nLeft = nWidthRemaining/2; return nLeft + nSelectedIndex*m_nCardWidth; } int Metrics::GetSelectedTop() const { return GetTop() - GetCardHeight() - 10; } int Metrics::GetPlayerSideX(CardLocation eLocation) const { if( eLocation == LocBottom || eLocation == LocTop ) return SCREEN_WIDTH/2; else if( eLocation == LocLeft ) return -50; return SCREEN_WIDTH + 50; } int Metrics::GetPlayerSideY(CardLocation eLocation) const { if( eLocation == LocBottom ) return SCREEN_HEIGHT + 50; else if ( eLocation == LocLeft || eLocation == LocRight ) return SCREEN_HEIGHT/2; return -50; } int Metrics::GetMiddleCardX(CardLocation eLocation) const { int nWidthRemaining = SCREEN_WIDTH - m_nCardWidth*3 - 3*10; int nLeft = nWidthRemaining/2; if( eLocation == LocLeft ) { return nLeft; } else if( eLocation == LocBottom || eLocation == LocTop ) { return nLeft + m_nCardWidth + 10; } return nLeft + 2*m_nCardWidth + 20; } int Metrics::GetMiddleCardY(CardLocation eLocation) const { int nTop = 30; if( eLocation == LocTop ) { return nTop; } else if( eLocation == LocLeft || eLocation == LocRight ) { return nTop + m_nCardHeight; } return nTop + 2*m_nCardHeight; } int Metrics::GetInitialCardX() const { return GetMiddleCardX(LocLeft) + m_nCardWidth + 10; } int Metrics::GetInitialCardY() const { return GetMiddleCardY(LocTop) + m_nCardHeight; } int Metrics::GetCardWidth() const { return m_nCardWidth; } int Metrics::GetCardHeight() const { return m_nCardHeight; } int Metrics::GetLeft() const { int nSpaceRequired = GetCardOffsetX()*m_nNumCards; int nWidthRemaining = SCREEN_WIDTH - nSpaceRequired - 6/*padding*/; return nWidthRemaining/2; } int Metrics::GetTop() const { return m_nTop; } int Metrics::GetCardOffsetX() const { int nSpaceAllocated = m_nCardWidth*13; int nSpacePerCard = nSpaceAllocated / m_nNumCards; if( nSpacePerCard < m_nCardWidth ) return nSpacePerCard; return m_nCardWidth; }
true
b13b830f127c63d8d4b8db9917a0c7d399b0a8af
C++
asreepada/DS-Algo
/nthNodeFromLast.cpp
UTF-8
1,442
3.890625
4
[]
no_license
#include<stdio.h> #include<malloc.h> #include<iostream> using namespace std; typedef struct node { int data; struct node *link; }Node; Node* newNode(int data) { Node *newNode; newNode = (struct node *) malloc(sizeof(Node)); newNode->data = data; newNode->link = NULL; return newNode; } void addNodeAtFront(Node **head,int data) { if(head==NULL) { *head=newNode(data); } else { Node *n = newNode(data); n->link = *head; *head = n; } } void display(Node *source) { Node *temp = source; cout<<"list data = "; while(temp != NULL) { printf(" %d ",temp->data); temp = temp->link; } cout<<endl; } void getNthNodeFromLast(Node *head,int n) { Node *p1=head; Node *p2=head; int pos = n; if(head==NULL) return; while(n>0) { if(p1==NULL) { cout<<pos<<" is larger than the list"<<endl; return; } p1=p1->link; n--; } while(p1!=NULL) { p1=p1->link; p2=p2->link; } cout<<"The node at ["<< pos<<"] position from last is : "<<p2->data<<endl; } int main() { Node *head=NULL; addNodeAtFront(&head,1); addNodeAtFront(&head,2); addNodeAtFront(&head,3); addNodeAtFront(&head,4); addNodeAtFront(&head,5); addNodeAtFront(&head,6); display(head); //getNthNodeFromLast(head,10); getNthNodeFromLast(head,3); }
true
d3279c4ba3c191435b6928f356528b0b230f9ce8
C++
ssh352/cppcode
/DotNet/ProVisualC++CLI/Chapter19/TcpServer_Stream/TcpServer_Stream.cpp
UTF-8
1,786
2.953125
3
[]
no_license
using namespace System; using namespace System::IO; using namespace System::Net; using namespace System::Net::Sockets; using namespace System::Threading; ref class TcpServer { public: void ProcessThread(Object ^clientObj); }; void TcpServer::ProcessThread(Object ^clientObj) { TcpClient^ client = (TcpClient^)clientObj; IPEndPoint^ clientEP = (IPEndPoint^)client->Client->RemoteEndPoint; Console::WriteLine("Connected on IP: {0} Port: {1}", clientEP->Address, clientEP->Port); StreamWriter^ writer = gcnew StreamWriter(client->GetStream()); StreamReader^ reader = gcnew StreamReader(client->GetStream()); writer->WriteLine("Successful connection to the server on port {0}", clientEP->Port); writer->Flush(); String^ msg; while (true) { try { msg = reader->ReadLine(); Console::WriteLine("Port[{0}] {1}", clientEP->Port, msg); writer->WriteLine(msg); writer->Flush(); } catch (IOException^) { break; // connection lost } } client->Close(); Console::WriteLine("Connection to IP: {0} Port {1} closed.", clientEP->Address, clientEP->Port); } void main() { TcpServer^ server = gcnew TcpServer(); TcpListener^ socket = gcnew TcpListener(IPAddress::Any, 12345); socket->Start(); while(true) { Console::WriteLine("Waiting for client connection."); TcpClient^ client = socket->AcceptTcpClient(); Thread ^thr = gcnew Thread( gcnew ParameterizedThreadStart(server, &TcpServer::ProcessThread)); thr->Start(client); } }
true
23a1c2b9e53ec5e66962b642e1324163dbc15dc0
C++
a137748099/QtAnimation
/animaldemo1.cpp
UTF-8
3,893
2.625
3
[]
no_license
#include "animaldemo1.h" #include <QPushButton> #include <QPainter> #include <QSequentialAnimationGroup> AnimalDemo1::AnimalDemo1(int w, int h, QWidget *parent): QWidget(parent) { this->resize(w, h); initUi(); } void AnimalDemo1::initUi() { m_pBaseWidget = new QWidget(this); m_pBaseWidget->resize(58, 494); m_pBaseWidget->move(this->width()/2 - m_pBaseWidget->width()/2, this->height()/2 - m_pBaseWidget->height()/2); m_pBgWidget = new BgWidget(m_pBaseWidget); m_pBgWidget->move(0, 156); for(int i = 0; i < 9; ++i) { QPushButton *btn = new QPushButton(m_pBaseWidget); btn->setStyleSheet("background:red;"); btn->resize(32, 32); btn->move(m_pBaseWidget->width()/2 - btn->width()/2, 21 + i*(btn->height() + 20)); m_btnList.append(btn); initBtnHideAnimal(btn, btn->pos()); if(i < 3){ btn->resize(0, 0); } if(i == 3){ connect(btn, &QPushButton::clicked, this, [=](){ checked = !checked; m_btnList.at(0)->resize(0, 0); m_btnList.at(1)->resize(0, 0); m_btnList.at(2)->resize(0, 0); if(checked) { m_pBgWidget->startAnimal(QPropertyAnimation::Forward); m_pPreviewAnimalGroup->start(); } else { m_pBgWidget->startAnimal(QPropertyAnimation::Backward); } }); } } m_pPreviewAnimalGroup = new QSequentialAnimationGroup(this); m_pPreviewAnimalGroup->addAnimation(m_animalMap.value(m_btnList.at(2))); m_pPreviewAnimalGroup->addAnimation(m_animalMap.value(m_btnList.at(1))); m_pPreviewAnimalGroup->addAnimation(m_animalMap.value(m_btnList.at(0))); } void AnimalDemo1::initBtnHideAnimal(QWidget *item, QPoint pos) { QPropertyAnimation *animation = new QPropertyAnimation(item, "geometry", m_pBaseWidget); animation->setDuration(200); animation->setStartValue(QRect(this->width()/2, item->y() + item->height()/2, 0, 0)); animation->setEndValue(QRect(pos, item->size())); m_animalMap.insert(item, animation); } /***********************************************************************************************/ BgWidget::BgWidget(QWidget *parent): QWidget(parent), m_normalSize(58, 338), m_expandSize(58, 494) { this->resize(m_normalSize); m_pPreviewShowAnimation = new QPropertyAnimation(this, "geometry", this); m_pPreviewShowAnimation->setDuration(300); m_pPreviewShowAnimation->setKeyValueAt(0, QRect(0, 156, m_normalSize.width(), m_normalSize.height())); m_pPreviewShowAnimation->setKeyValueAt(1, QRect(0, 0, m_normalSize.width(), m_expandSize.height())); } void BgWidget::startAnimal(QAbstractAnimation::Direction direction) { m_direction = direction; m_pPreviewShowAnimation->setDirection(direction); #if 1 if(direction == QPropertyAnimation::Forward){ m_pPreviewShowAnimation->setDuration(300); }else{ m_pPreviewShowAnimation->setDuration(200); } #endif m_pPreviewShowAnimation->start(); } void BgWidget::setChecked(bool checked) { m_bIsExpand = checked; if(m_bIsExpand){ this->resize(m_expandSize); }else{ this->resize(m_normalSize); } update(); } void BgWidget::paintEvent(QPaintEvent *event) { QPainter painter(this); painter.setRenderHints(QPainter::SmoothPixmapTransform | QPainter::HighQualityAntialiasing); painter.setBrush(Qt::white); QPen pen; pen.setWidth(2); pen.setColor(QColor("#d1d1d1")); painter.setPen(pen); painter.drawRoundedRect(QRect(2, 2, this->width() - 4, this->height() - 4), 10, 10); QWidget::paintEvent(event); }
true
81dcd18bc12b8fa037a188db7b0bc8c7cccf1ecb
C++
hugo-maker/til
/ezoe_cpp/bernoulli_distribution.cpp
UTF-8
3,851
3.09375
3
[]
no_license
// コンパイル時に all.h(コンパイル済みヘッダーファイルはall.h.gch) をインクルードする必要あり // g++ -std=c++20 -Wall --pedantic-error -include all.h <ソースファイル名> -o <実行ファイル名> // コイントス100回 template <typename Engine> auto coinflips100(Engine & e) { // t == 100, p == 0.5 std::binomial_distribution d(100, 0.5); return d(e); } // 6面ダイス60投 template <typename Engine> auto roll_for_one(Engine & e) { // t == 60, p == 1.0 / 6.0 std::binomial_distribution d(60, 1.0 / 6.0); return d(e); } // 1%であたるくじを100回引く template <typename Engine> auto lootbox(Engine & e) { // t == 100, p == 0.01 std::binomial_distribution d(100, 1.0 / 100.0); return d(e); } // 表が出るまでコイントス template <typename Engine> auto try_coinflips(Engine & e) { std::geometric_distribution d(0.5); // 幾何分布は成功する"まで"の試行回数を返す==成功した施行は施行回数に含めない // 成功した施行も回数に含めるには +1が必要 return d(e) + 1; } // 1がでるまで6面ダイスを振る template <typename Engine> auto try_rolls(Engine & e) { std::geometric_distribution d(1.0 / 6.0); return d(e) + 1; } // あたりが出るまでくじを引く template <typename Engine> auto try_lootboxes(Engine & e) { std::geometric_distribution d(1.0 / 100.0); return d(e) + 1; } // 表が10回出るまでコイントス template <typename Engine> auto count_10_coinflips(Engine & e) { std::negative_binomial_distribution d(10, 0.5); return d(e) + 10; } // 1が10回でるまで6面ダイスを振る template <typename Engine> auto count_10_rolls(Engine & e) { std::negative_binomial_distribution d(10, 1.0 / 6.0); return d(e) + 10; } // あたりが10回出るまでくじを引く template <typename Engine> auto count_10_lootboxes(Engine & e) { std::negative_binomial_distribution d(10, 1.0 / 100.0); return d(e) + 10; } int main() { // ベルヌーイ分布 // ベルヌーイ分布 // 施行回数 const int trial_count = 1000; std::mt19937 e; std::bernoulli_distribution d(32.0 / 100.0); std::array<int, 2> result{}; for (int i = 0; i != trial_count; ++i) { // boolからintへの変換はfaluseが0, trueが1 ++result[d(e)]; } std::cout << "false: "sv << double(result[0]) / double(trial_count) * 100 << "%\n"sv << "true: "sv << double(result[1]) / double(trial_count) * 100 << "\n"sv; // 二項分布 // コイントス for (int i = 0; i != 10; ++i) { std::cout << coinflips100(e) << " "sv; } std::cout << "\n"sv; // 6面ダイス for (int i = 0; i != 10; ++i) { std::cout << roll_for_one(e) << " "sv; } std::cout << "\n"sv; // くじ for (int i = 0; i != 10; ++i) { std::cout << lootbox(e) << " "sv; } std::cout << "\n"sv; // 幾何分布 // 表がでるまでコイントス for (int i = 0; i != 10; ++i) { std::cout << try_coinflips(e) << " "sv; } std::cout << "\n"sv; // 1がでるまで6面ダイスを振る for (int i = 0; i != 10; ++i) { std::cout << try_rolls(e) << " "sv; } std::cout << "\n"sv; // あたりが出るまでくじを引く for (int i = 0; i != 10; ++i) { std::cout << try_lootboxes(e) << " "sv; } std::cout << "\n"sv; // 負の二項分布 // 表が10回でるまでコイントス for (int i = 0; i != 10; ++i) { std::cout << count_10_coinflips(e) << " "sv; } std::cout << "\n"sv; // 1がでるまで6面ダイスを振る for (int i = 0; i != 10; ++i) { std::cout << count_10_rolls(e) << " "sv; } std::cout << "\n"sv; // あたりが出るまでくじを引く for (int i = 0; i != 10; ++i) { std::cout << count_10_lootboxes(e) << " "sv; } std::cout << "\n"sv; }
true
b3b9c0fa7d251d930de4df7dd90b68648174afd6
C++
sundsx/RevBayes
/src/core/datatypes/trees/TreeChangeEventHandler.cpp
UTF-8
1,607
2.515625
3
[]
no_license
// // TreeChangeEventHandler.cpp // RevBayesCore // // Created by Sebastian Hoehna on 8/27/12. // Copyright 2012 __MyCompanyName__. All rights reserved. // #include "TreeChangeEventHandler.h" #include "TreeChangeEventListener.h" #include <iostream> using namespace RevBayesCore; TreeChangeEventHandler::TreeChangeEventHandler(void) : listeners() { } TreeChangeEventHandler::TreeChangeEventHandler(const TreeChangeEventHandler &h) : listeners() { } TreeChangeEventHandler::~TreeChangeEventHandler(void) { if ( listeners.empty() == false ) { std::cerr << "Deleting handler while " << listeners.size() << " listener are still listening." << std::endl; } } TreeChangeEventHandler& TreeChangeEventHandler::operator=(const TreeChangeEventHandler &h) { if ( this != &h ) { listeners.clear(); } return *this; } void TreeChangeEventHandler::addListener(TreeChangeEventListener *l) { listeners.insert( l ); } void TreeChangeEventHandler::fire(const TopologyNode &n) { for (std::set<TreeChangeEventListener*>::iterator it = listeners.begin(); it != listeners.end(); ++it) { TreeChangeEventListener *l = *it; l->fireTreeChangeEvent( n ); } } const std::set<TreeChangeEventListener*>& TreeChangeEventHandler::getListeners( void ) const { return listeners; } void TreeChangeEventHandler::removeListener(TreeChangeEventListener *l) { std::set<TreeChangeEventListener*>::iterator pos = listeners.find( l ); if ( pos != listeners.end() ) { listeners.erase( l ); } }
true
7a75d5d1430cd6b4befe471a874e7bdb3e2c0a8d
C++
0x8000-0000/ftags
/src/db/record.cc
UTF-8
7,991
2.578125
3
[ "Apache-2.0" ]
permissive
/* Copyright 2019 Florin Iucha 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 <record.h> namespace { class OrderRecordsBySymbolKey { public: explicit OrderRecordsBySymbolKey(const ftags::Record* records) : m_records{records} { } bool operator()(const unsigned& left, const unsigned& right) const { const ftags::Record& leftRecord = m_records[left]; const ftags::Record& rightRecord = m_records[right]; if (leftRecord.symbolNameKey < rightRecord.symbolNameKey) { return true; } if (leftRecord.symbolNameKey == rightRecord.symbolNameKey) { if (leftRecord.attributes.type < rightRecord.attributes.type) { return true; } } return false; } private: const ftags::Record* m_records; }; bool compareRecordsByLocation(const ftags::Record& leftRecord, const ftags::Record& rightRecord) { if (leftRecord.location.fileNameKey < rightRecord.location.fileNameKey) { return true; } if (leftRecord.location.fileNameKey == rightRecord.location.fileNameKey) { if (leftRecord.location.line < rightRecord.location.line) { return true; } if (leftRecord.location.line == rightRecord.location.line) { if (leftRecord.location.column < rightRecord.location.column) { return true; } } } return false; } class OrderRecordsByFileKey { public: explicit OrderRecordsByFileKey(const std::vector<ftags::Record>& records) : m_records{records} { } bool operator()(const unsigned& left, const unsigned& right) const { const ftags::Record& leftRecord = m_records[left]; const ftags::Record& rightRecord = m_records[right]; return compareRecordsByLocation(leftRecord, rightRecord); } private: const std::vector<ftags::Record>& m_records; }; } // anonymous namespace void ftags::Record::filterDuplicates(std::vector<const ftags::Record*>& records) { const auto begin = records.begin(); const auto end = records.end(); std::sort(begin, end, [](const ftags::Record* leftRecord, const ftags::Record* rightRecord) { return *leftRecord < *rightRecord; }); auto last = std::unique(begin, end, [](const ftags::Record* leftRecord, const ftags::Record* rightRecord) { return *leftRecord == *rightRecord; }); records.erase(last, end); } /* * Record serialization */ template <> std::size_t ftags::util::Serializer<std::vector<ftags::Record>>::computeSerializedSize(const std::vector<ftags::Record>& val) { return sizeof(ftags::util::SerializedObjectHeader) + sizeof(uint64_t) + val.size() * sizeof(ftags::Record); } template <> void ftags::util::Serializer<std::vector<ftags::Record>>::serialize(const std::vector<ftags::Record>& val, ftags::util::TypedInsertor& insertor) { ftags::util::SerializedObjectHeader header{"std::vector<ftags::Record>"}; insertor << header; const uint64_t vecSize = val.size(); insertor << vecSize; insertor << val; } template <> std::vector<ftags::Record> ftags::util::Serializer<std::vector<ftags::Record>>::deserialize(ftags::util::TypedExtractor& extractor) { ftags::util::SerializedObjectHeader header; extractor >> header; uint64_t vecSize = 0; extractor >> vecSize; std::vector<ftags::Record> retval(/* __n = */ vecSize); extractor >> retval; return retval; } #if 0 std::shared_ptr<ftags::RecordSpan> ftags::RecordSpanCache::add(std::shared_ptr<ftags::RecordSpan> original) { m_spansObserved++; auto range = m_cache.equal_range(original->getHash()); for (auto iter = range.first; iter != range.second; ++iter) { auto elem = iter->second; std::shared_ptr<RecordSpan> val = elem.lock(); if (!val) { continue; } else { if (val->operator==(*original)) { return val; } } } m_cache.emplace(original->getHash(), original); indexRecordSpan(original); return original; } void ftags::RecordSpanCache::indexRecordSpan(std::shared_ptr<ftags::RecordSpan> original) { /* * gather all unique symbols in this record span */ std::set<ftags::StringTable::Key> symbolKeys; original->forEachRecord([&symbolKeys](const Record* record) { symbolKeys.insert(record->symbolNameKey); }); /* * add a mapping from this symbol to this record span */ std::for_each(symbolKeys.cbegin(), symbolKeys.cend(), [this, original](ftags::StringTable::Key symbolKey) { m_symbolIndex.emplace(symbolKey, original); }); } std::size_t ftags::RecordSpanCache::getRecordCount() const { std::size_t recordCount = 0; for (auto iter = m_cache.begin(); iter != m_cache.end(); ++iter) { std::shared_ptr<RecordSpan> val = iter->second.lock(); if (val) { recordCount += val->getSize(); } } return recordCount; } std::size_t ftags::RecordSpanCache::computeSerializedSize() const { std::size_t recordSpanSizes = 0; for (auto iter = m_cache.begin(); iter != m_cache.end(); ++iter) { std::shared_ptr<RecordSpan> val = iter->second.lock(); if (val) { recordSpanSizes += val->computeSerializedSize(); } } return sizeof(ftags::SerializedObjectHeader) + sizeof(uint64_t) + recordSpanSizes + m_store.computeSerializedSize(); } void ftags::RecordSpanCache::serialize(ftags::TypedInsertor& insertor) const { ftags::SerializedObjectHeader header{"ftags::RecordSpanCache"}; insertor << header; m_store.serialize(insertor); const uint64_t vecSize = m_cache.size(); insertor << vecSize; std::for_each(m_cache.cbegin(), m_cache.cend(), [&insertor](const cache_type::value_type& iter) { std::shared_ptr<RecordSpan> val = iter.second.lock(); if (val) { val->serialize(insertor); } }); } ftags::RecordSpanCache ftags::RecordSpanCache::deserialize(ftags::TypedExtractor& extractor, std::vector<std::shared_ptr<RecordSpan>>& hardReferences) { ftags::RecordSpanCache retval; ftags::SerializedObjectHeader header = {}; extractor >> header; retval.m_store = RecordStore::deserialize(extractor); uint64_t cacheSize = 0; extractor >> cacheSize; retval.m_cache.reserve(cacheSize); hardReferences.reserve(cacheSize); for (size_t ii = 0; ii < cacheSize; ii++) { RecordSpan recordSpan = RecordSpan::deserialize(extractor, retval.m_store); std::shared_ptr<RecordSpan> newSpan = std::make_shared<RecordSpan>(std::move(recordSpan)); hardReferences.push_back(newSpan); retval.m_cache.emplace(newSpan->getHash(), newSpan); retval.indexRecordSpan(newSpan); } return retval; } std::shared_ptr<ftags::RecordSpan> ftags::RecordSpanCache::getSpan(const std::vector<Record>& records) { const RecordSpan::Hash spanHash = RecordSpan::computeHash(records); cache_type::const_iterator iter = m_cache.find(spanHash); if (iter != m_cache.end()) { return iter->second.lock(); } else { std::shared_ptr<RecordSpan> newSpan = makeEmptySpan(records.size()); newSpan->copyRecordsFrom(records); m_cache.emplace(newSpan->getHash(), newSpan); indexRecordSpan(newSpan); return newSpan; } } #endif
true
f131d7647045098c33c848a2b9d927b6bb3f4994
C++
delta4d/AlgoSolution
/zoj/05/1429.cpp
UTF-8
1,492
2.5625
3
[]
no_license
#include <cmath> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; #define RIGHT 1 #define STRAIGHT 0 #define LEFT -1 const int MAXN = 50; struct point { int x, y; int index; point(int _x=0, int _y=0, int _index=0):x(_x), y(_y), index(_index) {} bool input() { return scanf("%d %d %d", &index, &x, &y) == 3; } int xmult(const point &o, const point &a) { return (x - o.x) * (a.y - o.y) - (a.x - o.x) * (y - o.y); } int dis2(const point &a) { return (a.x - x) * (a.x - x) + (a.y - y) * (a.y - y); } int righter(const point &o, const point &a) { int ret(xmult(o, x)); if (ret > 0) return RIGHT; return ret == 0 ? STRAIGHT : LEFT; } void set_inf() { } } f[MAXN]; bool visit[MAXN]; int out[MAXN]; inline int min(const int c, const int i, const int j) { int k(f[i].righter(f[c], f[j])); if (k == RIGHT) return i; if (k == LEFT) return j; return f[i].dis2(f[c]) < f[j].dis2(f[c]) ? i : j; } inline int min(const int i, const int j) { if (f[i].x < f[j].x) return i; if (f[j].x < f[i].x) return j; return f[i].y < f[j].y ? i : j; } int main() { int i, j, k; int m, n; int tc; int src; int p; point temp; freopen("f:\\in.txt", "r", stdin); scanf("%d", &tc); while (tc--) { scanf("%d", &n); for (i=0; i<n; visit[i++]=false) f[i].input(); src = 0; for (i=1; i<n; ++i) src = min(src, i); p = 0; visit[out[p++] = src] = true; } return 0; }
true
c6c3e3feb97cdb7814302683454abad380a9ba03
C++
jose-joaquim/AcervoMaratona
/Maratona Regional 2017/Problema D/D.cpp
UTF-8
1,265
3
3
[]
no_license
//Autor: Joaquim //Complexidade: O(sqrt(N) + numero_divisores(N) * sqrt(max(divisor(N)))) #include <vector> #include <cstdio> #include <cmath> #include <iostream> #include <cstring> using namespace std; typedef long long ll; ll n; vector<ll> divisores; bool ehDespojado(ll numero){ //printf("verificando divisor %lld\n", numero); int qtdPrimos = 0; bool distintos = true; ll aux = numero; for(ll i = 2; i * i <= numero; i++){ bool divide = false, foi = false; int cnt = 0; while(aux % i == 0){ aux /= i; cnt++; foi = true; } if(cnt > 1) return false; if(foi){ qtdPrimos++; } } if(aux != 1) qtdPrimos++; //printf(" %lld tem %d fatores primos\n", numero, qtdPrimos); return (qtdPrimos >= 2 && distintos); } int main(){ scanf("%lld", &n); ll ans = 0; for(long long i = 1; i * i <= n; i++){ if(n % i == 0){ divisores.push_back(i); if(i != n / i){ divisores.push_back(n / i); } } } //printf("%lld tem %d divisores\n", n, (int) divisores.size()); //para cada divisor, verifico se ele eh despojado... for(int k = 0; k < (int) divisores.size(); k++){ if(ehDespojado(divisores[k])) ans++; } printf("%lld\n", ans); return 0; }
true
7ba2f0a512dc18054e2416c93ed2ea83c3499b95
C++
NEJI12212/Pac_Man
/Pacman/PacTileMap.cpp
UTF-8
6,683
2.8125
3
[]
no_license
#include "PacTileMap.h" namespace { // txture size magic number constexpr float textureSize = 16.0f; // instance std::unique_ptr<PacTileMap> sInstance; } //---------------------------------------------------------------------------------- void PacTileMap::StaticInitialize() { // create the map XASSERT(sInstance == nullptr, "TileMap already initialized!"); sInstance = std::make_unique<PacTileMap>(); } //---------------------------------------------------------------------------------- void PacTileMap::StaticTerminate() { // clear out the instance sInstance.reset(); } //---------------------------------------------------------------------------------- PacTileMap& PacTileMap::Get() { // get the map instance XASSERT(sInstance != nullptr, "No tile map created!"); return *sInstance; } //---------------------------------------------------------------------------------- void PacTileMap::Load() { //get the stage text file std::string line; std::ifstream myFile("stage3.txt"); unsigned int rows = 0; bool firstFlag = false; std::vector<int> tile; //zero number char tempChar = '0'; int compareValue = static_cast<int>(tempChar); //read through the file if(myFile.is_open()) { while (std::getline(myFile, line)) { if (rows == 0) rows = line.length(); else if (rows != line.length()) { XASSERT(rows == line.length(), "ERROR: Uneven rows"); } mColumns++; for (int i = 0; i < rows; i++) { char value = line[i]; int intValue = static_cast<int>(value) - compareValue; tile.push_back(intValue); } } mRows = rows; myFile.close(); } //apply the files data mTiles.reset(new int[mColumns * mRows]); for (int y = 0; y < mColumns; ++y) { for (int x = 0; x < mRows; ++x) { int i = GetIndex(x, y); mTiles.get()[i] = tile[i]; } } //Open, mTilesTexture.push_back(X::LoadTexture("black3.png")); //Wall, mTilesTexture.push_back(X::LoadTexture("blue3.png")); //Ball mTilesTexture.push_back(X::LoadTexture("orb2.png")); //Power Orb mTilesTexture.push_back(X::LoadTexture("power_orb.png")); //White Border mTilesTexture.push_back(X::LoadTexture("white2.png")); } //---------------------------------------------------------------------------------- void PacTileMap::Render() { // render the map for (int y = 0; y < mColumns; ++y) { for (int x = 0; x < mRows; ++x) { int i = GetIndex(x, y); X::TextureId id = mTilesTexture[mTiles.get()[i]]; X::Math::Vector2 pos{ x * textureSize, y * textureSize }; X::DrawSprite(id, pos, X::Pivot::TopLeft); } } } //---------------------------------------------------------------------------------- void PacTileMap::RenderOutside() { // render the outer bounds so it will overlap the player/enemies for teleporting for (int y = 0; y < mColumns; ++y) { for (int x = 0; x < mRows; ++x) { if (y == 0 || y == mColumns -1 || x == 0 || x == mRows -1 || y == mColumns || x == mRows) { int i = GetIndex(x, y); X::TextureId id = mTilesTexture[mTiles.get()[i]]; X::Math::Vector2 pos{ x * textureSize, y * textureSize }; X::DrawSprite(id, pos, X::Pivot::TopLeft); } } } } //---------------------------------------------------------------------------------- void PacTileMap::Unload() { // unload the map mTilesTexture.clear(); } //---------------------------------------------------------------------------------- void PacTileMap::Update(float deltaTime) { //update the power mode to see if the player is in a power up state mPowerMode = mPowerTimer > 0; mPowerTimer -= deltaTime; } int PacTileMap::GetIndex(int row, int column) const { // get the tile return row + (column * mRows); } //---------------------------------------------------------------------------------- X::Math::Vector2 PacTileMap::GetMaxBoundaries() const { // get the max boundaries of the map float removeHalfTexture = textureSize / 2; float x = (mRows * textureSize) - removeHalfTexture; float y = (mColumns * textureSize) - removeHalfTexture; return X::Math::Vector2{ x, y }; } //---------------------------------------------------------------------------------- int PacTileMap::CheckPlayerCollision(const X::Math::LineSegment& lineSegment) const { // get max/min of the X/Y values int startX = static_cast<int>(lineSegment.from.x / textureSize); int startY = static_cast<int>(lineSegment.from.y / textureSize); int endX = static_cast<int>(lineSegment.to.x / textureSize); int endY = static_cast<int>(lineSegment.to.y / textureSize); for (int x = startX; x <= endX; ++x) { for (int y = startY; y <= endY; ++y) { int index = GetIndex(x, y); mTeleport = (x == 0 || x == mRows); int tileValue = mTiles.get()[index]; // if a point is grabbed change the texture if (mTiles.get()[index] == static_cast<int>(TileTypes::POWERORB) || mTiles.get()[index] == static_cast<int>(TileTypes::BALL)) { mTiles.get()[index] = static_cast<int>(TileTypes::OPEN); } return tileValue; } } return static_cast<int>(TileTypes::WALL); } //---------------------------------------------------------------------------------- bool PacTileMap::CheckCollision(const X::Math::LineSegment& lineSegment) const { // get max/min of the X/Y values int startX = static_cast<int>(lineSegment.from.x / textureSize); int startY = static_cast<int>(lineSegment.from.y / textureSize); int endX = static_cast<int>(lineSegment.to.x / textureSize); int endY = static_cast<int>(lineSegment.to.y / textureSize); for (int x = startX; x <= endX; ++x) { for (int y = startY; y <= endY; ++y) { int index = GetIndex(x, y); if (mTiles.get()[index] == 1) // Wall return true; } } return false; } //---------------------------------------------------------------------------------- bool PacTileMap::HitEnemy(const X::Math::Rect player, const X::Math::Rect enemy) const { // see if a player and an enemy collide return X::Math::Intersect(player, enemy); }
true
a6e2665a7cf8e569880a60492256442d188144a0
C++
kbc16b15/game
/GameTemplate/game/gameCamera.h
SHIFT_JIS
1,536
2.546875
3
[]
no_license
#pragma once class gameCamera:public IGameObject { public: //RXgN^ gameCamera(); //fXgN^ ~gameCamera(); // void Init(); //XV void Update(); //J̉] void RotCamera(); //Ǐ]J void TrackingCamera(); //{XX^[gJ@JoH void BossStartCamera(); //{XJ void BossCamera(); //{XGhJ void BossEndCamera(); //{XŒJ void BossRockCamera(); // //CX^X̐ // static void gameCamera::Create() // { // if (!m_gameCamera) // { // m_gameCamera = new gameCamera; // } // } // // //CX^X̏ // static void gameCamera::Destroy() // { // delete m_gameCamera; // m_gameCamera = nullptr; // } // //CX^X̎擾 // static gameCamera& GetInstance() // { // return *m_gameCamera; // } //private: // // static gameCamera* m_gameCamera; //CX^X private: D3DXVECTOR3 m_position; //JW const float m_rotSpeed = 2.0f; //]x bool m_isBossStartCamera = false;//{XJ int m_stateCameraTime = 250; //JnJ̎ bool m_isBossEndCamera = false; //{XJ int m_endCameraTime = 500; //IJ̎ bool m_isBossCamera = false; //D3DXVECTOR3 m_targetPos = { 0.0f,0.0f,0.0f }; //const float CameraUpLimit = 30.0f; //J㉺x //bool m_istoCamera = false; //J𑀍쒆ǂ };
true
c193b76ae1cb41a893f4b7ed80942e10e2a34640
C++
mschwartz/amos
/kernel/Types/BSparseArray.cpp
UTF-8
2,096
2.59375
3
[ "MIT" ]
permissive
#include <Types/BSparseArray.hpp> // constructor BSparseArrayNode::BSparseArrayNode(const char *aName, TInt64 aKey) : BNode(aName) { mSparseKey = aKey; } BSparseArrayNode::~BSparseArrayNode() { // } // constructor BSparseArray::BSparseArray(const TInt aSparseArrayBuckets) { mCount = 0; mSparseArrayBuckets = aSparseArrayBuckets; // mDiskCache = new BSparseArray(mSparseArrayBuckets); dlog("construct BSparseArray(%d)\n", mSparseArrayBuckets); // mSparseArrayLists = new BList[aSparseArrayBuckets]; } BSparseArray::~BSparseArray() { for (TInt i = 0; i < mSparseArrayBuckets; i++) { BList *list = (BList *)&mSparseArrayLists[i]; while (BSparseArrayNode *node = (BSparseArrayNode *)list->RemHead()) { delete node; } } // delete[] mSparseArrayLists; } BSparseArrayNode *BSparseArray::Find(const TInt64 aKey) { // dlog("BSParsaeArray::Find(%d) buckets(%d)\n", aKey, mSparseArrayBuckets); TInt64 index = aKey % mSparseArrayBuckets; // dlog("index(%d)\n", index); BList *list = (BList *)&mSparseArrayLists[index]; // dlog("list(%x)\n", list); for (BSparseArrayNode *node = (BSparseArrayNode *)list->First(); !list->End(node); node = (BSparseArrayNode *)node->mNext) { // dlog("node(%x)\n", node); if (node->mSparseKey == aKey) { return node; } } return ENull; } TBool BSparseArray::Add(BSparseArrayNode &aNode) { if (Find(aNode.mSparseKey)) { return EFalse; } TInt64 index = aNode.mSparseKey % mSparseArrayBuckets; BList *list = (BList *)&mSparseArrayLists[index]; list->AddHead(aNode); mCount++; return ETrue; } TBool BSparseArray::Remove(TInt64 aKey) { BSparseArrayNode *node = Find(aKey); if (!node) { return EFalse; } node->Remove(); mCount--; return ETrue; } BSparseArrayNode *BSparseArray::Replace(BSparseArrayNode &aNode) { BSparseArrayNode *node = Find(aNode.mSparseKey); if (!node) { node->Remove(); } TInt64 index = aNode.mSparseKey % mSparseArrayBuckets; BList *list = (BList *)&mSparseArrayLists[index]; list->AddHead(aNode); return node; }
true
41e0cc21bffdf773a1d1e8603a0fd3e320f464b8
C++
mcmellawatt/VectorGraphicsFramework
/Element.h
UTF-8
869
2.546875
3
[]
no_license
#pragma once #include "SharedPtr.h" #include <string> #include <vector> #include <map> namespace Xml { class Element; typedef Cst::SharedPtr<Element> HElement; typedef std::map<std::string, std::string> AttributeMap; typedef std::vector<HElement> ElementList; class Element { public: Element(const std::string& name); std::string getName() const; void setAttribute(const std::string& name, const std::string& value); std::string getAttribute(const std::string& name) const; ElementList getChildElements() const; AttributeMap getAttributes() const; void appendChild(const HElement& child); private: std::string myName; AttributeMap myAttributes; ElementList myElements; }; }
true
e2f6c640b634265e05824e801fd80a7fe477421a
C++
oficialtavarez/Calculator-in-C-Calculadora-en-C-
/Dev c++/Calculadora.cpp
WINDOWS-1250
17,381
2.796875
3
[]
no_license
/* Gracias por bajar mi aplicacion en C++ */ /*Version 2.0 */ /*Ultima Actualizacion: 26/1/2021 */ /*Creado por Anderson Tavarez (Oficialtavarz)*/ /*Soporte Nevekley */ /* Aviso:(Puedes usar este programa cuando y donde des creditos al autor original del proyecto)*/ /* Inicio de bibliotecas */ #include <stdio.h> #include <stdlib.h> #include <process.h> #include <math.h> #include <conio.h> #include <string.h> #include <iostream> #include <windows.h> /* Final bibliotecas */ using namespace std; /* Este es el menu principal */ main() { int op=0, a=0, b=0, c=0; m1: system("cls"); printf("Bienvenido : )\n"); printf("\n"); printf("1-Calculadora.\n"); printf("2-Buscador.\n"); printf("3-Calendario 2021.\n"); printf("4-Juegos en linea.\n"); printf("5-Otros.\n"); printf("6-Salir.\n"); printf("Digite la opcion a seguir==>"); printf("\n"); printf("Programado por oficialtavarezz\n"); scanf("%d",&op); /* Fin del menu principal */ /* Sub menu tipo de calculadora*/ switch(op) { case 1: { m2: system("cls"); printf("Bienvenido a la Calculadora:\n"); printf("1- Estandar.\n"); printf("2-Cientifica.\n"); printf("3-Regresar.\n"); printf("4-Salir.\n"); printf("Digite la opcion a seguir==>"); scanf("%d",&op); /* Fin del sub tipo menu de calculadora */ /* Sub menu estandar*/ switch(op) { case 1: { m3: system("cls"); printf("Estandar : )\n"); printf("1-Suma\n"); printf("2-Resta\n"); printf("3-Multiplicacion\n"); printf("4-Division\n"); printf("5-Raiz Cuadrada\n"); printf("6-Pocierto\n"); printf("7-Regresar\n"); printf("8-SALIR\n"); printf("Digite una opcion a seguir==>"); scanf("%d",&op); switch(op) { case 1: { system("cls"); printf("Este programa suma dos numeros\n"); printf("digite un numero\n"); scanf("%d",&a); printf("digite otro numero\n"); scanf("%d",&b); c=a+b; printf("la resta de %d + %d es %d\n",a,b,c); system("pause"); goto m3; } case 2: { system("cls"); printf("Este programa resta dos numeros\n"); printf("Digite un numero\n"); scanf("%d",&a); printf("Digite otro numero\n"); scanf("%d",&b); c=a-b; printf("la reesta de %d - %d es %d\n",a,b,c); system("pause"); goto m3; } case 3: { system("cls"); printf("Este programa multiplica dos numeoros\n"); printf("digite un numero\n"); scanf("%d",&a); printf("digite otro numero\n"); scanf("%d",&b); c=a*b; printf("la multiplicacion de %d * %d es %d\n",a,b,c); system("pause"); goto m3; } case 4: { system("cls"); printf("Este preograma divide dos numeoros\n"); printf("digite un numero\n"); scanf("%d",&a); printf("digite otro numero\n"); scanf("%d",&b); c=a/b; printf("la divicion de %d / %d es %d\n",a,b,c); system("pause"); goto m3; } case 5: {system("cls"); int a; float c; printf("coloque un valor\n"); scanf("%d",&a); c=sqrt(a); printf("el resultado de %d es %f\n",a,c); system("pause"); goto m3; } case 6: {system("cls"); float a,b,c; printf("coloque el porciento\n"); scanf("%f",&a); printf("coloque la cantidad ha sacarle el porciento\n"); scanf("%f",&b); c=a*b /100; printf("c=%f",c); system("pause"); goto m3; } case 7: {goto m2;} case 8: {exit(0); } } /* Final de sub menu estandar*/ /* Sub menu cientifica*/ case 2: { m4: system("cls"); printf("Cientifica\n"); printf("1-Suma\n"); printf("2-Resta\n"); printf("3-Multiplicacion\n"); printf("4-Divisin\n"); printf("5-Residuo\n"); printf("6-Raiz Cuadrada\n"); printf("7-Pociento\n"); printf("8-X^2\n"); printf("9-X^Y\n"); printf("10-1/X\n"); printf("11-PI\n"); printf("12-(+/-)\n"); printf("13-CONVIERTE A POTENCIA DE 10\n"); printf("14-VALOR ABSOLUTO\n"); printf("15-TRIGONOMETRIA (SUB)\n"); printf("16-MENU ANTERIOR\n"); printf("17-SALIR\n"); printf("Digite una opcion a seguir==>"); scanf("%d",&op); switch(op) { case 1: {system("cls"); printf("coloque el primer valor\n"); scanf("%d",&a); printf("coloque el segundo valor\n"); scanf("%d",&b); c=a+b; printf("el resultado de %d + %d es %d\n",a,b,c); system("pause"); goto m4; } case 2: {system("cls"); printf("coloque el primer valor\n"); scanf("%d",&a); printf("coloque el segundo valor\n"); scanf("%d",&b); c=a-b; printf("el resultado de %d -%d es %d\n",a,b,c); system("pause"); goto m4; } /* Final sub menu cientifica*/ /* Sub menu multiplicacion*/ case 3: {m5: system("cls"); printf("SUD MENU MULTIPLICACION\n"); printf("1-MULTIPLICACION MEDIANTE LA SUMA\n"); printf("2-MULTIPLICACION RUSA\n"); printf("3-MULTIPLICACION NORMAL\n"); printf("4-MENU ANTERIOR\n"); printf("5-SALIR\n"); printf("Digite una opcion==>"); scanf("%d",&op); switch(op) { case 1: {system("cls"); printf("ESTE PROGRAMA MULTIPLICA MEDIANTE LA SUMA\n"); printf("Digite un numero\n"); scanf("%d",&a); printf("Digite otro numero\n"); scanf("%d",&b); c=a*b; printf("la multiplicacion de %b * %b es %b\n",a,b,c); system("pause"); goto m5; } case 2: {system("cls"); int num1,num2,resultado=0; printf("Introduce primer numero de la multiplicacion\n"); scanf("%d",&num1); printf("Introduce segundo numero de la multiplicacion\n"); scanf("%d",&num2); while(num1>=1) { if(num1%2!=0) resultado+=num2; num1=num1/2; num2=num2*2; } printf("El resultado es: %d",resultado); system("pause"); goto m5; } case 3: {system("cls"); printf("digite el primer valor\n"); scanf("%d",&a); printf("digite el segundo valor\n"); scanf("%d",&b); c=a*b; printf("el resultado de %d * %d es %d\n",a,b,c); system("pause"); goto m5; } case 4: { goto m4; } case 5: {goto m1; default:{ system("cls");printf("Has salido \n");} system("pause"); goto m3; } } } case 4: {system("cls"); printf("coloque el primer valor\n"); scanf("%d",&a); printf("coloque el segundo valor\n"); scanf("%d",&b); c=a/b; printf("el resultado de %d / %d es %d\n",a,b,c); system("pause"); goto m4; } case 5: {system("cls"); printf("coloque el primer valor\n"); scanf("%d",&a); printf("coloque el segundo valor\n"); scanf("%d",&b); c=a/b; printf("el residuo de %d / %d es %d\n",a,b,c); printf("pause"); goto m4; } case 6: {system("cls"); int a; float c; printf("coloque un valor\n"); scanf("%d",&a); c=sqrt(a); printf("el resultado de %d es %f\n",a,c); system("pause"); goto m4; } case 7: {system("cls"); float a,b,c; printf("coloque el porciento\n"); scanf("%f",&a); printf("coloque la cantidad ha sacarle el porciento\n"); scanf("%f",&b); c=a*b /100; printf("c=%f",c); system("pause"); goto m4; } case 8: {system("cls"); scanf("%d",&a); c=pow(a,2); printf("el resultado de %d es %d\n",a,c); system("pause"); goto m4; } case 9: {system("cls"); int base,exponente; printf("digite la base"); scanf("%d",&base); printf("digite el exponente\n"); scanf("%d",&exponente); printf("%d elevado a %d es %lf\n", base, exponente, pow (base, exponente)); system("pause"); goto m4; } case 10: {system("cls"); int x; float y; printf("digite el valor de x"); scanf("%d",&x); y=1/x; printf("y=%f",y); system("pause"); goto m4; } case 11: {system("cls"); c=3.14; printf("el valor del PI es 3.14\n",c); system("pause"); goto m4; } case 12: {system("cls"); printf("ESTE PROGRAMA (+/-)\\n"); printf("Digite un numero\n"); scanf("%d",&a); printf("En proceso\n"); system("pause"); goto m4; } case 13: {system("cls"); printf("CONVIERTE A POTENCIA DE 10\n"); printf("Digite un numero\n"); scanf("%d",&a); printf("En proceso\n"); system("pause"); goto m4; } case 14: {system("cls"); int a,absoluto; printf("digite un valor"); scanf("%d",&a); absoluto=abs(a); printf("absoluto=%d",absoluto); system("pause"); goto m4; } /* Final sub menu multiplicacion*/ /* Sub menu trigonometria*/ case 15: {m6: system("cls"); printf("SUB MENU TRIGONOMETRIA\n"); printf("1-SEN X\n"); printf("2-COS X\n"); printf("3-TAN X\n"); printf("4-SECANTE X\n"); printf("5-COSC X\n"); printf("6-COTANGENTE X\n"); printf("7-LONG\n"); printf("8-LN\n"); printf("9-CONVIERTA(SUB)\n"); printf("10-MENU ANTERIOR\n"); printf("11-SALIR\n"); printf("Digite una opcion==>"); scanf("%d",&op); switch(op) { case 1: #define PI 3.14159265 {system("cls"); int param; float result; printf("digite un valor==>"); scanf("%d",&param); result = sin (param*PI/180); printf ("el seno de %d grados es %f.\n", param, result ); system("pause"); goto m6; } case 2: #define PI 3.14159265 {system("cls"); int param; float result; printf("digite un valor==>"); scanf("%d",&param); result = cos (param*PI/180); printf ("el coseno de %d grados es %f.\n", param, result ); system("pause"); goto m6; } {system("cls"); int param; float result; printf("digite un valor==>"); scanf("%d",&param); result = tan (param*PI/180); printf ("la tangente de %d grados es %f.\n", param, result ); system("pause"); goto m6; } case 4: #define PI 3.14159265 {system("cls"); int param; float result; printf("digite un valor==>"); scanf("%d",&param); result = 1/cos (param*PI/180); printf ("la secante de %d grados es %f.\n", param, result ); system("pause"); goto m6; } case 5: #define PI 3.14159265 {system("cls"); int param; float result; printf("digite un valor==>"); scanf("%d",&param); result = 1/sin (param*PI/180); printf ("la cosecante de %d grados es %f.\n", param, result ); system("pause"); goto m6; } case 6: #define PI 3.14159265 {system("cls"); int param; float result; printf("digite un valor==>"); scanf("%d",&param); result = cos (param*PI/180)/sin (param*PI/180); printf ("la cotangente de %d grados es %f.\n", param, result ); system("pause"); goto m6; } case 7: {system("cls"); double numero, resultado; printf("\nIntroduce valor: "); scanf("%lf", &numero); if (numero > 0) { resultado = log10(numero); printf("\nEl logaritmo de %.3f es %.3f", numero, resultado); } system("pause"); goto m6; } case 8: {system("cls"); printf("LN\n"); printf("Digite un numero\n"); scanf("%d",&a); printf("En proceso\n"); system("pause"); goto m6; } case 9: {system("cls"); int n; int bin; int j=0; int k; int n_tem; int n_temp=0; int n_temp1=0; // char n_tem2; scanf("%d",&n); //for(n=1;n<=256;n++){ printf("binario:\n"); for(bin=1;bin<=n;bin*=2) j=bin; for(j=bin;j>=1;j=(bin/=2)){ for(j=bin;j>=1;j=(bin/=2)) { n_tem=n; k=n_temp; n_temp=n_tem%j; if(n_tem>=j){ n_temp1=k/j; printf("%d",n_temp1); } } } printf("\n"); /*octal*/ printf("octal\n"); for(bin=1;bin<=n;bin*=8) j=bin; for(j=bin;j>=1;j=(bin/=8)){ for(j=bin;j>=1;j=(bin/=8)) { n_tem=n; k=n_temp; n_temp=n_tem%j; if(n_tem>=j){ n_temp1=k/j; printf("%d",n_temp1); } } printf("\n"); /*hexadecimal*/ printf("hexadecimal\n"); for(bin=1;bin<=n;bin*=16) j=bin; for(j=bin;j>=1;j=(bin/=16)){ for(j=bin;j>=1;j=(bin/=16)) { n_tem=n; k=n_temp; n_temp=n_tem%j; if(n_tem>=j){ n_temp1=k/j; if(n_temp1==10){ n_temp1='A'; printf("%c",n_temp1); } if(n_temp1==11){ n_temp1='B'; printf("%c",n_temp1); } if(n_temp1==12){ n_temp1='C'; printf("%c",n_temp1); } if(n_temp1==13){ n_temp1='D'; printf("%c",n_temp1); } if(n_temp1==14){ n_temp1='E'; printf("%c",n_temp1); } if(n_temp1==15){ n_temp1='F'; printf("%c",n_temp1); } else if(n_temp1>=0 && n_temp1<=9) printf("%d",n_temp1); } } printf("\n"); } } // } return 0; } case 10: {goto m1;} default:{ system("cls"); printf("Has salido \n");} system("pause"); goto m1; } } case 16: {goto m3;} case 17: {goto m1;} default:{ system("cls"); printf("Has salido \n");} system("pause"); goto m1; } } case 3: { goto m1; } } } /* Final sub menu trigonometria*/ /* Buscandador*/ case 2: {m8: system("cls"); { string link; cout<<"Introduce la pagina que deseas visitar\n"; cin>> link; ShellExecute(NULL, "open", link.c_str(), NULL, NULL, SW_SHOWNORMAL); system("pause"); return 0; } /* Final del buscandador*/ /* Otro codigo */ switch(op) { case 1: {system("cls"); int x=1; while(x<=64) { printf(" x vale %d\n",x); x=x*2; } system("pause"); goto m8; } case 2: {system("cls"); int x=1; int y=0; int z=y; while(x<=34) { printf(" x vale %d\n",x); z=x; x=x+y; y=z; } system("pause"); goto m8; } case 3: {system("cls"); int x; printf("digite el valor de x\n"); scanf("%d",&x); for(int i = 1; i <= x; ++i) { for(int j = 1; j <= i; ++j) { printf("%d",i); } printf("\n"); } return 0; } case 4: {goto m1;} case 5: {system("cls"); printf("Has salido\n"); goto m1; } } } /* Final del codigo */ /*Calendario */ case 3: {system("cls"); printf("El calendario no esta diposnible en este momento por favor intente mas tarde.\n"); system("pause"); goto m1; } /* Final calendario */ /*Sub menu juegos */ case 4: {m9: system("cls"); printf("Los sentimos no tenemos juegos en linea por ahora : (\n"); printf("1-Adivinanza\n"); printf("2-Loteria\n"); printf("3-Loto\n"); printf("4-Regresar\n"); printf("5-Salir\n"); printf("Eliga una opcion==>"); scanf("%d",&op); /*Final sub menu juegos */ /*Juegos menu juegos */ switch(op) { case 1: int respuesta,ballena; printf("la reina de los mares es, nunca vacia, siempre va llena\n"); printf("cual es la respuesta"); scanf("%d",&respuesta); if (respuesta==ballena) { printf("correcto"); } else{ printf("vuelve a intentarlo"); system("pause"); goto m9; } case 2: {system("cls"); printf("eliga un numero del 1 al 100>>>"); scanf("%d",&a); printf("***Tienes mucha suerte, Feliciades***\n"); system("pause"); goto m9; } case 3: {system("cls"); printf("NO HAY SISTEMA PRIMO (Mantenimiento).\n"); system("pause"); goto m9; } case 4: {goto m1; } case 5: {goto m1; } } } case 5: {system("cls"); printf("EN MATENIMIENTO PROXIMAMENTE EN FUNCIONAMIENNTO.\n"); system("pause"); goto m9; } case 6: {system("cls"); printf("seguro que desea salir\n"); system("pause"); return 0; } case 7: {system("cls"); printf("NOMBRE:< Nevekley>\n"); system("pause"); goto m1; } } } } /* Final juegos menu juegos */ /*Gracias por bajar mi aplicacion y espero que la disfrutes y te sea util, originalmente era un proyecto para mi clase el cual mejore para subirlo en esta plataforma por lo cual solo difruta del mismo */
true
2b25bbca799020993facfc91424e05c397ca0ea3
C++
rustamNSU/FinalTest
/Executable/task2.cpp
UTF-8
389
3.078125
3
[]
no_license
// // Created by rustam on 22.05.2020. // #include <iostream> #include <iomanip> // for std::boolalpha #include "task2.h" using namespace std; int main() { auto a1 = close_enough(2.0, 3.0); auto a2 = close_enough(3, 3); auto a3 = close_enough(1.0f, 1.0000000001f); cout << boolalpha; cout << a1 << endl << a2 << endl << a3 << endl; return 0; }
true
cb5c91ba1cae7ac6a655f0139fedab98657fe787
C++
ArturKal/SnakeGame
/source/repos/SnakeGameTdd/SnakeGameTdd/Coord.cpp
UTF-8
1,521
3.25
3
[]
no_license
#include "pch.h" #include "Coord.h" //Constructors: Coord::Coord() { Xcolumn = BOARDSIZE / 2; Yrow = BOARDSIZE / 2; } Coord::Coord(ICoord * _coord) : Icoord(_coord) { coords = Icoord; } Coord::Coord(int x, int y) { try { compare(x, y); } catch (std::runtime_error & e) { std::cout << "Runtime error: " << e.what(); if (x >= BOARDSIZE) x = 0; if (y >= BOARDSIZE) y = 0; if (x < 0 ) x = BOARDSIZE-1; if (y < 0 ) y = BOARDSIZE-1; } setCoordX(x); setCoordY(y); } //Methods: int Coord::getCoordX() { return this->Xcolumn; } int Coord::getCoordY() { return this->Yrow; } int Coord::setCoordX(int _x) { return this->Xcolumn = checkBorders(_x); } int Coord::setCoordY(int _y) { return this->Yrow = checkBorders(_y); } std::string Coord::printCoordinates() { std::string coordX = std::to_string(getCoordX()); std::string coordY = std::to_string(getCoordY()); std::string concatate = "Coord Xcolumn : " + coordX + " Coord Ycolumn : " + coordY + "\n"; return concatate; } int Coord::checkBorders(int fieldcoord) { if (fieldcoord >= BOARDSIZE) fieldcoord = 0; if (fieldcoord <= -1) fieldcoord = BOARDSIZE - 1; return fieldcoord; } int Coord::compare(int a, int b) { if (a < 0 || b < 0) { throw std::runtime_error("Coord parameter cannot be minus value, changed wrong value to 0\n"); } if (a > BOARDSIZE || b > BOARDSIZE) { throw std::runtime_error("Coord parameter cannot be bigger then Boardsize value, changed wrong value to BordSize value\n"); } return a; }
true
c6f14fb6eb49b84550b797ed1dcde28ce24379f8
C++
martakuzak/ASOD1
/Kamera/sources/utils/FileUtils.cpp
UTF-8
4,882
2.578125
3
[]
no_license
#include "stdafx.h" #include "FileUtils.h" #include "structs.h" BITMAPINFO* PrepareBitmapInfo(int w, int h) { BITMAPINFO *bip; bip = (BITMAPINFO*) new unsigned char[sizeof(BITMAPINFOHEADER)]; bip->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bip->bmiHeader.biWidth = w; bip->bmiHeader.biHeight = h; bip->bmiHeader.biPlanes = 1; bip->bmiHeader.biBitCount = 24; bip->bmiHeader.biCompression = BI_RGB; bip->bmiHeader.biSizeImage = 0; bip->bmiHeader.biXPelsPerMeter = 0; bip->bmiHeader.biYPelsPerMeter = 0; bip->bmiHeader.biClrUsed = 0; bip->bmiHeader.biClrImportant = 0; return bip; } void SaveJPG(CString filename, unsigned char *data, int iWidth, int iHeight) { CImage im; BITMAPINFO *bip = PrepareBitmapInfo(iWidth, iHeight); im.Create(iWidth, iHeight, 24); HDC hdc = im.GetDC(); StretchDIBits(hdc, 0, 0, iWidth, iHeight, 0, 0, iWidth, iHeight, data, bip, DIB_RGB_COLORS, SRCCOPY); im.Save(filename); im.ReleaseDC(); delete bip; } void LoadJPG(CString filename, unsigned char **data, int &iWidth, int &iHeight) { CImage im; int pitch, bpp; byte *pdata; im.Load(filename); pitch = im.GetPitch(); pdata = (byte*)im.GetBits(); iWidth = im.GetWidth(); iHeight = im.GetHeight(); bpp = abs(pitch/iWidth); (*data) = new unsigned char[iWidth*iHeight*3]; for (int i=0; i<iHeight; i++) { pdata = (byte*)im.GetBits() + pitch*i; for (int j=0; j<iWidth; j++) { (*data)[((iHeight-1-i)*iWidth)*3 + 3*j] = *pdata; (*data)[((iHeight-1-i)*iWidth)*3 + 3*j+1] = *(pdata+1); (*data)[((iHeight-1-i)*iWidth)*3 + 3*j+2] = *(pdata+2); /* (*data)[(i*iWidth)*3 + 3*j] = *pdata; (*data)[(i*iWidth)*3 + 3*j+1] = *(pdata+1); (*data)[(i*iWidth)*3 + 3*j+2] = *(pdata+2); */ pdata+=bpp; } } } void skipLine(FILE *f) { int c = -1; while (c!='\n') c = getc(f); } bool CheckFileExistence(CString filename) { FILE *f; if (fopen_s(&f, filename, "rt")!=0) return false; fclose(f); return true; } bool CheckFileExistence(char *filename) { FILE *f; if (fopen_s(&f, filename, "rt")!=0) return false; fclose(f); return true; } void WriteToTmp1(char* filename, float *buffer, int element_size, bool printZeros, int n) { float *tmp; FILE *f; fopen_s(&f, filename, "wt"); tmp = buffer; int cnt=0; for (int el=0; el<n; el++) { if (el%element_size==0) { fprintf(f, "\n\n"); cnt = 0; } if (printZeros || tmp[el]!=0) { fprintf(f, "%f ", /*cnt, */tmp[el]); cnt++; } } fclose(f); } int ReadCoordinates(CString filename, int *pointsx, int *pointsy) { int xcounter = 0; filename.Replace(".pgm", ".txt"); filename.Replace(".jpg", ".txt"); FILE *f; fopen_s(&f, filename, "rt"); if (f!=NULL) { for (int i=0; i<N_POINTS; i++) if (fscanf_s(f, "%d %d ", &pointsx[i], &pointsy[i])==EOF) { pointsx[i] = -1; pointsy[i] = -1; xcounter = 0; } else xcounter++; fclose(f); } else for (int i=0; i<N_POINTS; i++) { pointsx[i] = -1; pointsy[i] = -1; } return xcounter; } CString* loadAllClassifiersFileNames(char *path, int &n_files) { CString *sFileNames; WIN32_FIND_DATA fdata; HANDLE hnd; bool found = true; SetCurrentDirectory(path); char tmp[255]; n_files=0; // finding number of files hnd = FindFirstFile("cascade*.scs", &fdata); if (hnd == INVALID_HANDLE_VALUE){ return 0; } while (found) { n_files++; found = (FindNextFile(hnd, &fdata)!=0); } found = true; sFileNames = new CString[n_files]; // loading filenames n_files = 0; hnd = FindFirstFile("cascade*.scs", &fdata); while (found) { sprintf_s(tmp, "cascade_stage%d.scs", n_files); sFileNames[n_files] = tmp; n_files++; found = (FindNextFile(hnd, &fdata)!=0); } return sFileNames; } CString* loadAllFileNames(char *path, char *filter, int &n_files, bool full_name) { CString *sFileNames; WIN32_FIND_DATA fdata; HANDLE hnd; bool found = true; SetCurrentDirectory(path); n_files=0; // finding number of files hnd = FindFirstFile(filter, &fdata); if (hnd == INVALID_HANDLE_VALUE){ return NULL; } while (found) { n_files++; found = (FindNextFile(hnd, &fdata)!=0); } if (n_files==0) return NULL; found = true; sFileNames = new CString[n_files]; // loading filenames n_files = 0; hnd = FindFirstFile(filter, &fdata); while (found) { if (full_name) sFileNames[n_files] = path; else sFileNames[n_files].Format(""); sFileNames[n_files].Append(fdata.cFileName); n_files++; found = (FindNextFile(hnd, &fdata)!=0); } return sFileNames; } void MarkCodePoint(char *label, int l) // write to the c:\label.txt label { char tmp[256]; sprintf_s(tmp, 256, "c:\\label_%d.txt", l); FILE *f; fopen_s(&f, tmp, "wt"); fprintf(f, "%s", label); fclose(f); }
true
a8a35d60643206cc899d969a8273bb55a393ebf4
C++
LaserStark/calculator
/parser.h
UTF-8
554
2.5625
3
[]
no_license
/* Calculator Interpreter & Compiler * Author: robin1001 * Date: 2015-07-03 */ #ifndef _PARSER_H_ #define _PARSER_H_ #include "utils.h" #include "lexer.h" #include "node.h" class Parser { public: Parser(const char *input = "", bool is_file = true): lexer_(input, is_file) {} Node *parse(); private: //recursive down funtions of parser Node *expr(); Node *term(); Node *factor(); Node *assign(); Node *statements(); void match(TokenType expect_type); private: Lexer lexer_; TokenType next_token_; }; #endif
true
bdc4f88a64b48771f6f7282da938dd1472c6ff3a
C++
taketakeyyy/atcoder
/abc/263/d.cpp
UTF-8
2,650
2.515625
3
[]
no_license
#define _USE_MATH_DEFINES // M_PI等のフラグ #include <bits/stdc++.h> #define MOD 1000000007 #define COUNTOF(array) (sizeof(array)/sizeof(array[0])) #define rep(i,n) for (int i = 0; i < (n); ++i) #define intceil(a,b) ((a+(b-1))/b) using namespace std; using ll = long long; using pii = pair<int,int>; using pll = pair<long,long>; const long long INF = LONG_LONG_MAX - 1001001001001001; void chmax(int& x, int y) { x = max(x,y); } void chmin(int& x, int y) { x = min(x,y); } void solve1() { ll N, L, R; cin >> N >> L >> R; vector<ll> A(N+1, 0); ll SUM = 0; vector<ll> rA(N+1, 0); // 累積和 for(ll i=1; i<N+1; i++) { cin >> A[i]; SUM += A[i]; rA[i] = rA[i-1] + A[i]; } vector<ll> dpL(N+1, INF); // dpL[i] := 1~iまでLに書き換えられるときの、配列全体の最小値 dpL[0] = SUM; for(ll i=1; i<=N; i++) { dpL[i] = min(dpL[i-1], SUM - rA[i] + L*i); } vector<ll> dpR(N+1, INF); // dpR[i] := i~NまでRに書き換えられるときの、配列全体の最小値 dpR[N] = min(SUM, SUM-A[N]+R); for(ll i=N-1; i>=1; i--) { dpR[i] = min(dpR[i+1], SUM - (rA[N]-rA[i-1]) + R*(N-i+1)); } // 答えを探す ll ans = SUM; for(ll i=0; i<=N; i++) { if (i == N) { ans = min(ans, dpL[i]); } else if (i == 0) { ans = min(ans, dpR[i+1]); } else { ans = min(ans, dpL[i] + dpR[i+1] - (rA[N]-rA[i]) - rA[i]); } } cout << ans << endl; } void solve2() { ll N, L, R; cin >> N >> L >> R; vector<ll> A(N+1, 0); ll SUM = 0; for(ll i=1; i<N+1; i++) { cin >> A[i]; SUM += A[i]; } // dpL[i] := 1~iまでLに書き換えられる場合の、1~Lまでの和の最小値 vector<ll> dpL(N+1, 0); ll total = 0; for(ll i=1; i<=N; i++) { total += A[i]; dpL[i] = min(total, L*i); if (i-1 >= 1) { dpL[i] = min(dpL[i], dpL[i-1]+A[i]); } } // dpR[i] := i~NまでRに書き換えられる場合の、i~Nまでの和の最小値 vector<ll> dpR(N+2, 0); total = 0; for(ll i=N; i>=1; i--) { total += A[i]; dpR[i] = min(total, R*(N-i+1)); if (i+1 <= N) { dpR[i] = min(dpR[i], dpR[i+1]+A[i]); } } // 答えを探す ll ans = SUM; for(ll i=0; i<=N; i++) { ans = min(ans, dpL[i]+dpR[i+1]); } cout << ans << endl; } int main() { // solve1(); solve2(); return 0; }
true
9b706b3e6b22c15e9d1d3045fa98eb95a52476f3
C++
shi1252/SeamlessVoxel
/SeamlessVoxel/Material.cpp
UTF-8
357
2.59375
3
[]
no_license
#include "Material.h" #include "Texture.h" Material::Material(std::string name, std::string shaderName, Texture* texture) : name(name), shaderName(shaderName) { textures.push_back(texture); } ID3D11ShaderResourceView* Material::GetTextureSRV(int index) { if (textures.size() > 0) return textures[index]->GetSRV(); return nullptr; }
true
30f6dc4490814de5dc151d681216163bb3e6bf06
C++
Jerry-Terrasse/Programming
/比赛/校内/NOIP模拟试题/201810060830(50)/B.cpp
UTF-8
4,129
2.65625
3
[]
no_license
#include<iostream> #define MAXN 1000010 #define MAXA 70070 #define max(x,y) ((x)<(y)?(y):(x)) using namespace std; struct node { int val[2],l,r,mid,lazy,lst,cnt; node *son,*daughter; int build(int,int); int change(int,int); int set(int,int,int); int que(int,int,int); void output(); }*head; int outer[MAXA*3+3],n=0,m=0,ans=0,ccnt=0; bool bo=false; char c='\0'; inline void out(int,int); int main() { int u=0,v=0; char ou='\0',ov='\0'; ios::sync_with_stdio(0); head=new node; head->build(1,MAXA*3); for(;cin>>c;) { if(c==EOF) { break; } if(c<'A'||c>'Z') { continue; } cin>>ou>>u>>ov>>v>>ov; u*=3;v*=3; if(ou=='(') { ++u; } if(ov==')') { --v; } switch(c) { case 'U': head->set(u,v,1); break; case 'I': head->set(1,u-1,0); head->set(v+1,MAXA*3,0); break; case 'D': head->set(u,v,0); break; case 'C': head->set(1,u-1,0); head->set(v+1,MAXA*3,0); head->change(u,v); break; case 'S': head->change(u,v); break; default: for(int rp=0;19260817;++rp); } } head->output(); for(u=1;u<=MAXA*3;++u) { if(outer[u]) { for(v=u+1;outer[v];++v); out(u,v-1); u=v-1; } } if(!bo) { cout<<"empty set"<<endl; } return 0; } void node::output() { if(l==r) { if(lst==2) { outer[++ccnt]=1; } else if(lst==1) { outer[++ccnt]=0; } else { outer[++ccnt]=val[lazy^1]; } } else { son->output(); daughter->output(); } return; } inline void out(int u,int v) { bo=true; if(u%3) { cout<<'('; } else { cout<<'['; } cout<<u/3<<','; if(v%3) { cout<<v/3+1<<')'; } else { cout<<v/3<<']'; } return; } int node::que(int il,int ir,int o) { if(il==l&&ir==r) { return val[lazy^o]; } else { if(ir<=mid) { return son->que(il,ir,o^lazy); } if(il>mid) { return daughter->que(il,ir,o^lazy); } return son->que(il,mid,o^lazy)+daughter->que(mid+1,ir,o^lazy); } } int node::set(int il,int ir,int o) { if(il==l&&ir==r) { lst=o+1; lazy=0; if(o) { val[1]=cnt; return val[0]=0; } else { val[0]=0; return val[0]=cnt; } } if(lst) { val[0]=son->set(l,mid,lst-1)+daughter->set(mid+1,r,lst-1); val[1]=r-l+1-val[0]; lst=0; } if(lazy) { val[0]=son->change(l,mid)+daughter->change(mid+1,r); val[1]=r-l+1-val[0]; lazy=0; } if(mid>=ir) { val[0]=son->set(il,ir,o)+daughter->val[daughter->lazy]; val[1]=r-l+1-val[0]; return val[0]; } if(mid<il) { val[0]=son->val[son->lazy]+daughter->set(il,ir,o); val[1]=r-l+1-val[0]; return val[0]; } val[0]=son->set(il,mid,o)+daughter->set(mid+1,ir,o); val[1]=r-l+1-val[0]; return val[0]; } int node::change(int il,int ir) { if(il==l&&ir==r) { if(lst) { lst^=3; val[0]^=val[1];val[1]^=val[0];val[0]^=val[1]; } else { lazy^=1; val[0]^=val[1];val[1]^=val[0];val[0]^=val[1]; } return val[lazy]; } if(lst) { val[0]=son->set(il,mid,lst-1)+daughter->set(mid+1,ir,lst-1); val[1]=r-l+1-val[0]; lst=0; } if(lazy) { val[0]=son->change(l,mid)+daughter->change(mid+1,r); val[1]=r-l+1-val[0]; lazy=0; } if(mid>=ir) { val[0]=son->change(il,ir)+daughter->val[daughter->lazy]; val[1]=r-l+1-val[0]; return val[0]; } if(mid<il) { val[0]=son->val[son->lazy]+daughter->change(il,ir); val[1]=r-l+1-val[0]; return val[0]; } val[0]=son->change(il,mid)+daughter->change(mid+1,ir); val[1]=r-l+1-val[0]; return val[0]; } int node::build(int il,int ir) { if(il==ir) { l=r=mid=il;lst=lazy=0;cnt=1; val[1]=0; return val[0]=1; } l=il;r=ir;mid=l+r>>1;lst=lazy=0; son=new node;daughter=new node; val[0]=son->build(l,mid)+daughter->build(mid+1,r); cnt=son->cnt+daughter->cnt; val[1]=r-l+1-val[0]; return val[0]; }
true
9ea7ee8af8490917cf7089c49b763d035be95b47
C++
jcowles/effects-salad
/common/sketchUtil.cpp
UTF-8
1,011
2.5625
3
[]
no_license
#include "common/sketchScene.h" #include "common/sketchUtil.h" #include "glm/gtx/string_cast.hpp" #include "pez/pez.h" using namespace sketch; using namespace glm; using namespace std; vec3 sketch::AddOffset(vec2 p2, const Plane* plane) { vec3 p3 = plane->GetCenterPoint(); p3 += plane->GetCoordSys() * vec3(p2.x, 0, p2.y); return p3; } void sketch::VerifyPlane(vec3 v, const Plane* plane, const char* msg) { // XXX: in theory this should be a valid sanity check, but seems to be // giving false positives #if 0 float distance = plane->Eqn.x * v.x + plane->Eqn.y * v.y + plane->Eqn.z * v.z - plane->Eqn.w; pezCheck(std::abs(distance) < 0.0001, msg); #endif } bool sketch::IsOrthogonal(const CoplanarPath* p1, const CoplanarPath* p2, float epsilon) { float dp = dot(p1->GetNormal(), p2->GetNormal()); return dp < epsilon; } bool sketch::IsEquivDirections(vec3 v1, vec3 v2, float epsilon) { return dot(v1, v2) > (1.0 - epsilon); }
true
7b378e4c83375c12065c30046df215f953442ca7
C++
ParkYeoungJun/Algorithm
/Samsung/Expert/4012_expert_tast.cpp
UTF-8
1,315
2.71875
3
[]
no_license
#include<iostream> #include<cstdio> #include<climits> #include<cmath> #include<vector> #include<cstring> using namespace std; int arr[20][20]; bool visit[20]; int n, result = INT_MAX; int calc(vector<int> t) { int rtn = 0; for(int i = 0 ; i < n/2 ; ++i) { for(int j = 0 ; j < n/2 ; ++j) { if(i == j) continue; rtn += arr[t[i]][t[j]]; } } return rtn; } int getRes() { vector<int> a; vector<int> b; for(int i = 0 ; i < n ; ++i) { if(visit[i]) a.push_back(i); else b.push_back(i); } return abs(calc(a) - calc(b)); } void tracking(int v, int cnt) { visit[v] = true; if(cnt == n/2) { result = min(getRes(), result); } else { for(int i = v + 1 ; i < n ; ++i) { tracking(i, cnt+1); } } visit[v] = false; } int main() { int t=0,testcase; scanf("%d", &testcase); while(++t <= testcase) { scanf("%d", &n); for(int i = 0 ; i < n ; ++i) for(int j = 0 ; j < n ; ++j) scanf("%d", &arr[i][j]); tracking(0,1); printf("#%d %d\n", t, result); memset(visit, false, sizeof(visit)); result = INT_MAX; } }
true
25173a2df2ee5427ca18687fc81dc11a7759e4d6
C++
dimitrov-k/Chess
/source/chess.cpp
UTF-8
1,090
3.171875
3
[ "MIT" ]
permissive
#include "includes.h" #include "chess.h" #include "user_interface.h" // Chess class int Chess::getPieceColor(char piece) { if (isupper(piece)) { return WHITE_PIECE; } else { return BLACK_PIECE; } } bool Chess::isWhitePiece(char piece) { return getPieceColor(piece) == Chess::WHITE_PIECE ? true : false; } bool Chess::isBlackPiece(char piece) { return getPieceColor(piece) == Chess::BLACK_PIECE ? true : false; } std::string Chess::describePiece(char piece) { std::string description; if (isWhitePiece(piece)) { description += "White "; } else { description += "Black "; } switch (toupper(piece)) { case Chess::PIECE_TYPE_PAWN: { description += "pawn"; } break; case Chess::PIECE_TYPE_KNIGHT: { description += "knight"; } break; case Chess::PIECE_TYPE_BISHOP: { description += "bishop"; } break; case Chess::PIECE_TYPE_ROOK: { description += "rook"; } break; case Chess::PIECE_TYPE_QUEEN: { description += "queen"; } break; default: { description += "unknow piece"; } break; } return description; } // Game class
true
25ad3484612521aa3857ada673da16e90652b711
C++
dh-wuho/myLeetCode
/C++/253_Meeting_Rooms_II.cpp
UTF-8
1,429
3.4375
3
[]
no_license
/** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: int minMeetingRooms(vector<Interval>& intervals) { map<int, int> table; for(int i = 0; i < intervals.size(); i++) { table[intervals[i].start]++; table[intervals[i].end]--; } int currM = 0; int minM = 0; for(auto it : table) { currM += it.second; minM = max(currM, minM); } return minM; } }; /** * Definition for an interval. * struct Interval { * int start; * int end; * Interval() : start(0), end(0) {} * Interval(int s, int e) : start(s), end(e) {} * }; */ class Solution { public: int minMeetingRooms(vector<Interval>& intervals) { sort(intervals.begin(), intervals.end(), cmp()); priority_queue<int, vector<int>, greater<int>> pq; for(int i = 0; i < intervals.size(); i++) { if(!pq.empty() && pq.top() <= intervals[i].start) { pq.pop(); } pq.push(intervals[i].end); } return pq.size(); } struct cmp { bool operator()(Interval& a, Interval& b) { return a.start < b.start; } }; };
true
0bc79137734a196bf1c5174d176e69ffa5122929
C++
LeandroGuillen/rompebolas
/src/motor/motor.h
UTF-8
1,435
3
3
[]
no_license
#ifndef MOTOR_H_ #define MOTOR_H_ #define TAM_TABLERO 11 class Motor { public: Motor(); ~Motor(); int** getMatriz(); int** getAdyacentes(); int getPuntos(); int calcularPuntos(); int getTamTablero(){ return TAM_TABLERO; } int nSeleccionadas(){ return numero_seleccionadas; } void sustituirMatriz(int **); void encontrarAdyacentes(int, int); void restableceAdyacentes(); void go(int); void restableceSeleccionadas(){numero_seleccionadas=0;}; private: int ** matriz; int ** adyacentes; int numero_seleccionadas; int puntuacion; struct Posicion { int fila, col; }; bool hayColumnasLibres(); /** finPartida * Comprueba si la partida se puede continuar o no, * basandose en si hay al menos dos bolas del mismo * color adyacentes.*/ bool finPartida(); void rellenaConAleatorios(); void encontrarAdyacentes(Posicion&); void intercambia(int&, int&); /** borrarAdyacentes * Dado un tablero marca como borradas (borra) las bolas que habian * sido seleccionadas por encontrarAdyacentes.*/ void borrarAdyacentes(); /** bajarColumnas * Baja todas las bolas por "gravedad".*/ void bajarColumnas(); /** moverDerecha * Mueve todos las bolas hacia la derecha en una fila. * @param v Vector que contiene las bolas.*/ void moverDerecha(int *v); /** moverDerecha * Mueve todas las bolas del tablero a la derecha. * @param t Tablero cuyas bolas se mueven.*/ void moverDerecha(); }; #endif
true