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
8df55cc20b643112268bf058034f650e25875508
C++
citiral/olliOS
/kernel/memory/LinearAlloc.cpp
UTF-8
1,197
3.015625
3
[]
no_license
// // Created by citiral on 9/23/16. // #include "LinearAlloc.h" #include "linker.h" #include "cdefs.h" #include <stdio.h> #include <string.h> LinearAlloc::LinearAlloc() { } void LinearAlloc::init(void* start, size_t length) { this->start = static_cast<char*>(start); remaining = length; } void* LinearAlloc::malloc(size_t size) { // allocate size bytes + 1 size_t to remember the length if (remaining < size + sizeof(size_t)) { printf("OUT OF MEMORY"); return nullptr; } start += size + sizeof(size_t); remaining -= size + sizeof(size_t); *(size_t*)(start - size - sizeof(size_t)) = size; return start - size; } void* LinearAlloc::realloc(void* ptr, size_t size) { size_t originalsize = *(size_t*)(static_cast<char*>(ptr) - sizeof(size_t)); void* next = malloc(size); if (originalsize < size) memcpy(next, ptr, originalsize); else memcpy(next, ptr, size); free(ptr); return next; } void LinearAlloc::free(void* ptr) { UNUSED(ptr); // eh, fuck it } void* LinearAlloc::calloc(size_t num, size_t size) { void* ptr = malloc(num * size); memset(ptr, 0, num*size); return ptr; }
true
0a4668d49aed9075ff922469862c0ab98d44d203
C++
VVZzzz/MyWebServer
/MyWebServer/Log/LogFile.cpp
UTF-8
748
2.734375
3
[]
no_license
#include "LogFile.h" #include <stdio.h> #include "FileUtil.h" using namespace std; LogFile::LogFile(const std::string &str, int n) : basename_(str), everyNAppendFlush_(n), count_(0), mutex_(new MutexLock) { file_.reset(new AppendFile(basename_)); } LogFile::~LogFile(){}; void LogFile::append(const char *logline, int len) { MutexLockGuard lock(*mutex_); append_unlocked(logline, len); } void LogFile::append_unlocked(const char *logline,int len){ //append中循环write直至写完 file_->append(logline,len); //增加append次数 ++count_; if(count_>= everyNAppendFlush_) { count_ = 0; file_->flush(); } } void LogFile::flush() { MutexLockGuard lock(*mutex_); file_->flush(); }
true
5d9bd21e99c07c1750303df55df70a904bbad02f
C++
kmrshivamit/check_redis
/check_redis_master_connected_slaves.cpp
UTF-8
12,903
2.625
3
[]
no_license
#include "check_redis_config.h" #include "redis_info.hpp" #include "redis_slave_info.hpp" #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <hiredis.h> #include <iostream> #include <string> #include <vector> #include <climits> const char *short_options = "SH:hp:t:c:w:"; static struct option long_options[] = { { "host", required_argument, 0, 'H' }, { "help", no_argument, 0, 'h' }, { "port", required_argument, 0, 'p' }, { "timeout", required_argument, 0, 't' }, { "slaves", no_argument, 0, 'S' }, { "critical", required_argument, 0, 'c' }, { "warn", required_argument, 0, 'w' }, { NULL, 0, 0, 0 }, }; void usage(void) { std::cout << "check_redis_master_connected_slaves version " << CHECK_REDIS_VERSION << std::endl; std::cout << std::endl; std::cout << "Copyright (c) by Andreas Maus <maus@ypbind.de>" << std::endl; std::cout << "This program comes with ABSOLUTELY NO WARRANTY." << std::endl; std::cout << std::endl; std::cout << "check_redis_master_connected_slaves is distributed under the terms of the GNU General" << std::endl; std::cout << "Public License Version 3. (http://www.gnu.org/copyleft/gpl.html)" << std::endl; std::cout << std::endl; std::cout << "Check if number of connected slaves and the amount of missing data on the slaves." << std::endl; std::cout << std::endl; std::cout << "Usage: check_redis_master_connected_slaves [-h|--help] -H <host>|--host=<host> [-p <port>|--port=<port>]" <<std::endl; std::cout << " [-t <sec>|--timeout=<sec>] [-c <lim>|--critical=<lim>] [-w <lim>|--warn=<lim>] [-S|--slaves] " << std::endl; std::cout << std::endl; std::cout << " -h This text." << std::endl; std::cout << " --help" << std::endl; std::cout << std::endl; std::cout << " -S Check number of connected slaves." << std::endl; std::cout << " --slaves" << std::endl; std::cout << std::endl; std::cout << " -H <host> Redis server to connect to." << std::endl; std::cout << " --host=<host> This option is mandatory." << std::endl; std::cout << std::endl; std::cout << " -p <port> Redis port to connect to," << std::endl; std::cout << " --port=<port> Default: " << DEFAULT_REDIS_PORT << std::endl; std::cout << std::endl; std::cout << " -c <lim> Report critical condition if master has <lim> slaves or less." << std::endl; std::cout << " --critical=<lim> or if missing data is greater or equal than <lim> (if -S/--slave is used)" << std::endl; std::cout << " Default: " << DEFAULT_REDIS_MASTER_CONNECTED_SLAVES_CRITICAL << " or " << DEFAULT_REDIS_SLAVE_OFFET_CRITICAL << " bytes" << std::endl; std::cout << std::endl; std::cout << " -t <sec> Connection timout in seconds." << std::endl; std::cout << " --timeout=<sec> Default: " << DEFAULT_REDIS_CONNECT_TIMEOUT << std::endl; std::cout << std::endl; std::cout << " -w <lim> Report warning condition if master has <lim> slaves or less." << std::endl; std::cout << " --warn=<lim> or if missing data is greater or equal than <lim> (if -D/--data is used)" << std::endl; std::cout << " Default: " << DEFAULT_REDIS_MASTER_CONNECTED_SLAVES_WARNING << " or " << DEFAULT_REDIS_SLAVE_OFFET_CRITICAL << " bytes" << std::endl; std::cout << std::endl; } int main(int argc, char **argv) { std::string hostname { "" }; int port = DEFAULT_REDIS_PORT; redisContext *conn = NULL; redisReply *reply = NULL; int t_sec = DEFAULT_REDIS_CONNECT_TIMEOUT; int option_index = 0; int _rc; bool slave_check = false; long long warn_limit = -1; long long crit_limit = -1; int connected_slaves = -1; int slv_warn = DEFAULT_REDIS_MASTER_CONNECTED_SLAVES_WARNING; int slv_crit = DEFAULT_REDIS_MASTER_CONNECTED_SLAVES_CRITICAL; long long warn_delta = DEFAULT_REDIS_SLAVE_OFFSET_WARNING; long long crit_delta = DEFAULT_REDIS_SLAVE_OFFET_CRITICAL; long long max_delta = LLONG_MIN; long slave_online = 0; long slave_wait_bgsave = 0; long slave_send_bulk = 0; std::vector<RedisSlaveInfo> slaves; int slave_state = REDIS_SLAVE_STATE_UNKNOWN; std::string mip; int mport; long long mofs; long long delta; long long master_offset = -1; while ((_rc = getopt_long(argc, argv, short_options, long_options, &option_index)) != -1) { switch (_rc) { case 'h': { usage(); return STATUS_OK; break; } case 'H': { hostname = optarg; break; } case 'S': { slave_check = true; break; } case 'p': { std::string port_str{ optarg }; std::string::size_type remain; port = std::stoi(port_str, &remain); if (remain != port_str.length()) { std::cerr << "Error: Can't convert port " << optarg << " to a number" << std::endl; return STATUS_UNKNOWN; } break; } case 'c': { std::string c_str{ optarg }; std::string::size_type remain; crit_limit = std::stoll(c_str, &remain); if (remain != c_str.length()) { std::cerr << "Error: Can't convert critical threshold " << optarg << " to a number" << std::endl; return STATUS_UNKNOWN; } break; } case 'w': { std::string w_str{ optarg }; std::string::size_type remain; warn_limit = std::stoll(w_str, &remain); if (remain != w_str.length()) { std::cerr << "Error: Can't convert warning threshold " << optarg << " to a number" << std::endl; return STATUS_UNKNOWN; } break; } case 't': { std::string t_str{ optarg }; std::string::size_type remain; t_sec = std::stoi(t_str, &remain); if (remain != t_str.length()) { std::cerr << "Error: Can't convert timeout " << optarg << " to a number" << std::endl; return STATUS_UNKNOWN; } if (t_sec <= 0) { std::cerr << "Error: Timout must be greater than 0" << std::endl; return STATUS_UNKNOWN; } break; } default: { std::cerr << "Error: Unknwon argument " << _rc << std::endl; usage(); return STATUS_UNKNOWN; break; } } } if (hostname == "") { std::cerr << "Error: No host specified" << std::endl; std::cerr << std::endl; usage(); return STATUS_UNKNOWN; } if (slave_check) { if (warn_limit != -1) { slv_warn = warn_limit; } if (crit_limit != -1) { slv_crit = crit_limit; } } else { if (warn_limit != -1) { warn_delta = warn_limit; } if (crit_limit != -1) { crit_delta = crit_limit; } } if (slave_check) { if (slv_warn < 0) { std::cerr << "Error: Warning threshold must be greater than 0" << std::endl; return STATUS_UNKNOWN; } if (slv_crit < 0) { std::cerr << "Error: Critical threshold must be greater than 0" << std::endl; return STATUS_UNKNOWN; } if (slv_crit > slv_warn) { std::cerr << "Error: Critical threshold must be less or equal than warning threshold for number of connected slaves" << std::endl; return STATUS_UNKNOWN; } } else { if (warn_delta <= 0) { std::cerr << "Error: Warning threshold must be greater or equal than 0" << std::endl; return STATUS_UNKNOWN; } if (crit_delta <= 0) { std::cerr << "Error: Critical threshold must be greater or equal than 0" << std::endl; return STATUS_UNKNOWN; } if (crit_delta < warn_delta) { std::cerr << "Error: Critical threshold must be greater or equal than warning threshold" << std::endl; return STATUS_UNKNOWN; } } struct timeval timeout = { t_sec, 0 }; conn = redisConnectWithTimeout(hostname.c_str(), port, timeout); if (!conn) { std::cout << "Error: Can't connect to redis server" << std::endl; return STATUS_CRITICAL; } if (conn->err) { std::cout << "Error: Can't connect to redis server: " << conn->errstr << std::endl; return STATUS_CRITICAL; } reply = (redisReply *) redisCommand(conn, "INFO REPLICATION"); if (!reply) { std::cout << "Error: INFO command to redis server failed" << std::endl; redisFree(conn); return STATUS_CRITICAL; } if (reply->type == REDIS_REPLY_ERROR) { std::cout << "Error: INFO command to redis server returned an error: " << reply->str << std::endl; freeReplyObject(reply); redisFree(conn); return STATUS_CRITICAL; } std::string redis_info{ reply->str }; freeReplyObject(reply); redisFree(conn); RedisRoleInfo role { redis_info }; connected_slaves = role.GetNumberOfConnectedSlaves(); if (role.GetRole() != REDIS_ROLE_MASTER) { std::cout << "Not running as a master" << std::endl; return STATUS_CRITICAL; } slaves = role.GetSlaveInformation(); _rc = STATUS_OK; if (slave_check) { // Note: INFO REPLICATION reports all _connected_ slaves, not slaves that _should_ be // connected (something the server can't know). // We consider slaves in states "wait_bgsave" or "send_bulk" as "online" too. for (auto slv: slaves) { slave_state = slv.GetState(); if (slave_state == REDIS_SLAVE_STATE_WAIT_BGSAVE) { slave_wait_bgsave ++; } else if (slave_state == REDIS_SLAVE_STATE_SEND_BULK) { slave_send_bulk ++; } else if (slave_state == REDIS_SLAVE_STATE_ONLINE) { slave_online ++; } } if (connected_slaves <= slv_crit) { _rc = STATUS_CRITICAL; } else if (connected_slaves <= slv_warn) { _rc = STATUS_WARNING; } std::cout << connected_slaves << " slaves connected to master | connected_slaves=" << role.GetNumberOfConnectedSlaves() << ";;;0"; std::cout << " slaves_online=" << slave_online << ";;;0" << " slaves_send_bulk=" << slave_send_bulk << ";;;0"; std::cout << " slaves_wait_bgsave=" << slave_wait_bgsave << ";;;0" << std::endl; } else { if (slaves.empty()) { std::cout << "No slaves connected to this master" << std::endl; _rc = STATUS_CRITICAL; } else { master_offset = role.GetMasterReplicationOffset(); std::string perfdata{ "" }; for (auto slv: slaves) { mip = slv.GetIP(); mport = slv.GetPort(); mofs = slv.GetOffset(); delta = master_offset - mofs; if (std::abs(delta) > max_delta) { max_delta = std::abs(delta - mofs); } perfdata += "slave_" + mip + "_" + std::to_string(mport) + "_replication_delta=" + std::to_string(delta) + ";"; perfdata += std::to_string(warn_delta) + ";" + std::to_string(crit_delta) + ";0"; } if (max_delta >= crit_delta) { _rc = STATUS_CRITICAL; } else if (max_delta >= warn_delta) { _rc = STATUS_WARNING; } std::cout << "Maximum of outstanding data to slaves is " << delta << " bytes | connected_slaves=" << role.GetNumberOfConnectedSlaves() << ";;;0 "; std::cout << perfdata << std::endl; } } return _rc; }
true
187ddb933725735dd7d20b02bf907cad40721f07
C++
oneapi-src/oneAPI-samples
/DirectProgramming/C++SYCL_FPGA/ReferenceDesigns/merge_sort/src/sorting_networks.hpp
UTF-8
4,753
3.234375
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#ifndef __SORTINGNETWORKS_HPP__ #define __SORTINGNETWORKS_HPP__ #include <algorithm> #include <sycl/sycl.hpp> #include <sycl/ext/intel/fpga_extensions.hpp> // Included from DirectProgramming/C++SYCL_FPGA/include/ #include "constexpr_math.hpp" using namespace sycl; // // Creates a merge sort network. // Takes in two sorted lists ('a' and 'b') of size 'k_width' and merges them // into a single sorted output in a single cycle, in the steady state. // // Convention: // a = {data[0], data[2], data[4], ...} // b = {data[1], data[3], data[5], ...} // template <typename ValueT, unsigned char k_width, class CompareFunc> void MergeSortNetwork(sycl::vec<ValueT, k_width * 2>& data, CompareFunc compare) { if constexpr (k_width == 4) { // Special case for k_width==4 that has 1 less compare on the critical path #pragma unroll for (unsigned char i = 0; i < 4; i++) { if (!compare(data[2 * i], data[2 * i + 1])) { std::swap(data[2 * i], data[2 * i + 1]); } } if (!compare(data[1], data[4])) { std::swap(data[1], data[4]); } if (!compare(data[3], data[6])) { std::swap(data[3], data[6]); } #pragma unroll for (unsigned char i = 0; i < 3; i++) { if (!compare(data[2 * i + 1], data[2 * i + 2])) { std::swap(data[2 * i + 1], data[2 * i + 2]); } } } else { // the general case // this works well for k_width = 1 or 2, but is not optimal for // k_width = 4 (see if-case above) or higher constexpr unsigned char merge_tree_depth = fpga_tools::Log2(k_width * 2); #pragma unroll for (unsigned i = 0; i < merge_tree_depth; i++) { #pragma unroll for (unsigned j = 0; j < k_width - i; j++) { if (!compare(data[i + 2 * j], data[i + 2 * j + 1])) { std::swap(data[i + 2 * j], data[i + 2 * j + 1]); } } } } } // // Creates a bitonic sorting network. // It accepts and sorts 'k_width' elements per cycle, in the steady state. // For more info see: https://en.wikipedia.org/wiki/Bitonic_sorter // template <typename ValueT, unsigned char k_width, class CompareFunc> void BitonicSortNetwork(sycl::vec<ValueT, k_width>& data, CompareFunc compare) { #pragma unroll for (unsigned char k = 2; k <= k_width; k *= 2) { #pragma unroll for (unsigned char j = k / 2; j > 0; j /= 2) { #pragma unroll for (unsigned char i = 0; i < k_width; i++) { const unsigned char l = i ^ j; if (l > i) { const bool comp = compare(data[i], data[l]); const bool cond1 = ((i & k) == 0) && !comp; const bool cond2 = ((i & k) != 0) && comp; if (cond1 || cond2) { std::swap(data[i], data[l]); } } } } } } // // The sorting network kernel. // This kernel streams in 'k_width' elements per cycle, sends them through a // 'k_width' wide bitonic sorting network, and writes the sorted output or size // 'k_width' to device memory. The result is an output array ('out_ptr') of size // 'total_count' where each set of 'k_width' elements is sorted. // template <typename Id, typename ValueT, typename IndexT, typename InPipe, unsigned char k_width, class CompareFunc> event SortNetworkKernel(queue& q, ValueT* out_ptr, IndexT total_count, CompareFunc compare) { // the number of loop iterations required to process all of the data const IndexT iterations = total_count / k_width; return q.single_task<Id>([=]() [[intel::kernel_args_restrict]] { // Creating a device_ptr tells the compiler that this pointer is in // device memory, not host memory, and avoids creating extra connections // to host memory // This is only done in the case where we target a BSP as device // pointers are not supported when targeting an FPGA family/part #if defined(IS_BSP) device_ptr<ValueT> out(out_ptr); #else ValueT* out(out_ptr); #endif for (IndexT i = 0; i < iterations; i++) { // read the input data from the pipe sycl::vec<ValueT, k_width> data = InPipe::read(); // bitonic sort network sorts the k_width elements of 'data' in-place // NOTE: there are no dependencies across loop iterations on 'data' // here, so this sorting network can be fully pipelined BitonicSortNetwork<ValueT, k_width>(data, compare); // write the 'k_width' sorted elements to device memory #pragma unroll for (unsigned char j = 0; j < k_width; j++) { out[i * k_width + j] = data[j]; } } }); } #endif /* __SORTINGNETWORKS_HPP__ */
true
e41471c8e59c85d6597bed5b3de81eafff0284ff
C++
YuSangBeom/algorithm
/BOJ/18. 이분 검색/1654 랜선 자르기.cpp
UTF-8
742
2.90625
3
[]
no_license
#include<iostream> #include<algorithm> typedef unsigned long long ull; using namespace std; ull Arr[10001]; ull binarySearch(const int & K, const int & N) { ull first = 1; ull last = 0; ull ret = 0; for (int i = 0; i < K; i++) { last += Arr[i]; } last /= N; ull mid = 1; while (first <= last) { mid = (first + last) / 2; ull temp = 0; for (int i = 0; i < K; i++) { temp += Arr[i] / mid; } //cout << mid << endl; if (temp >= N) { ret = max(ret, mid); first = mid + 1; } else last = mid - 1; } return ret; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); int K, N; cin >> K >> N; for (int i = 0; i < K; i++) { cin >> Arr[i]; } sort(Arr, Arr + K); cout << binarySearch(K, N); }
true
2423c48a936050bff51c2c7eb61195ab6f415d24
C++
Yvaine/obstacle-avoidance
/src/core/types/Image16bit.h
UTF-8
1,787
3.3125
3
[]
no_license
// // Created by paul on 12/05/15. // #ifndef OBSTACLE_AVOIDANCE_IMAGE16BIT_H #define OBSTACLE_AVOIDANCE_IMAGE16BIT_H #include <opencv2/core/core.hpp> #include "exceptions/IncorrectImageTypeException.h" /** * A convenience class to distinguish 16-bit images from 8-bit images. */ class Image16bit : public cv::Mat { public: Image16bit() : cv::Mat() { forceConversion(*this); } Image16bit(int rows, int cols) : Mat(rows, cols, CV_16UC1) { } Image16bit(int rows, int cols, void* data) : Mat(rows, cols, CV_16UC1, data) {} /** * PARAM m: Mat used to seed this Image16bit. Must be of type CV_16UC1, * i.e. an 16-bit grayscale image. * PARAM copyData: if True, copy the pixel data stored in m into this object. * If False, share the data between the two objects, such that a change in one * results in a change in the other. */ Image16bit(const cv::Mat &m, bool copyData) : Mat( copyData ? m.clone() : m ) { if(m.type() != CV_16UC1){ throw IncorrectImageTypeException("parameter m is of wrong type"); } } /** * Overloads square brackets to work as a getter. */ uint16_t pixelAt(int row, int col) const{ return this->at<uint16_t>(row, col); } /** * Overloads square brackets to work as a setter. */ uint16_t & pixelAt(int row, int col) { return this->at<uint16_t>(row, col); } /** * Force the given cv::Mat to become of type CV_16UC1. * * CAUTION: always sets the flag to CV_16UC1 even if mat is malformed. */ static void forceConversion(cv::Mat &mat) { mat.flags = mat.flags & (1 << 12); mat.flags += CV_16UC1; } }; #endif //OBSTACLE_AVOIDANCE_IMAGE16BIT_H
true
66a793d6e0cdb1565553d971180342bd6f5c5a0e
C++
icrelae/cpp_primer
/8-io_library/8.3a-manage_output_buffer.cpp
UTF-8
756
3.15625
3
[]
no_license
/* 2016.11.07 22:01 * P_283 * !!! * endl; flush; ends; unitbuf; nounitbuf; tie !!! * exceptions will cause buffer stuck !!! * cout is relavant with cin, so cin will make cout refresh !!! * stream can tie with only one ostream pointer !!! */ #include <iostream> #include <string> #include <vector> using namespace std; int main(int argc, char **argv) { // output a '\n' then refresh buffer cout << "asdf" << endl << '#'; // output nothing then refresh buffer cout << "asdf" << flush << '#'; // output a ' ' then refresh buffer cout << "asdf" << ends << '#'; // cout after this all follow a flush cout << unitbuf; // with no flush cout << nounitbuf; // *a = cout ostream *a = cin.tie(); cin.tie(NULL); cin.tie(&cout); return 0; }
true
5663df24d13c8b8d04a8d2afe287eabca0d4591a
C++
sankalp163/CPP-codes
/Linked-Lists/Check Palindrome Linked LIst(Important).cpp
UTF-8
1,412
3.375
3
[]
no_license
void ReverseList(Node**head){ Node* prev=NULL; Node*curr=*head; Node*fwd=NULL; while(curr){ fwd=curr->next; curr->next=prev; prev=curr; curr=fwd; } *head=prev; } bool compareLists(struct Node* head1, struct Node* head2) { struct Node* temp1 = head1; struct Node* temp2 = head2; while (temp1 && temp2) { if (temp1->data == temp2->data) { temp1 = temp1->next; temp2 = temp2->next; } else return 0; } /* Both are empty reurn 1*/ if (temp1 == NULL && temp2 == NULL) return 1; /* Will reach here when one is NULL and other is not */ return 0; } bool isPalindrome(Node *head) { //Write your code here Node*fast=head; Node*slow=head; Node* prev_slow=head; Node*second_list; Node*mid=NULL; bool res = true; if(head!=NULL && head->next!=NULL){ while(fast!=NULL &&fast->next!=NULL){ fast=fast->next->next; prev_slow=slow; slow=slow->next; } if(fast!=NULL){ mid=slow; slow=slow->next; } second_list=slow; prev_slow->next=NULL; ReverseList(&second_list); res = compareLists(head, second_list); } return res; }
true
244520418b7bb0c62b60666871c90885b4fba496
C++
Neinun/100codes
/leetcode#34.cpp
UTF-8
1,213
3.0625
3
[]
no_license
class Solution { public: vector<int> searchRange(vector<int>& nums, int target) { int start = 0; int n = nums.size(); int end = n-1; int mid,first = -1,last = -1; if(n == 1 && nums[0] == target) { first = 0; last = 0; } else { while(start<=end) { mid = start + (end-start)/2; if(nums[mid] == target) { first = mid; end = mid -1; } else if(nums[mid]<target) start = mid +1; else end = mid -1; } start = 0; end = n-1; while(start<=end) { mid = start + (end-start)/2; if(nums[mid] == target) { last = mid; start = mid+ 1; } else if(nums[mid]<target) start = mid +1; else end = mid -1; } } vector<int> result; result.push_back(first); result.push_back(last); return result; } };
true
91e5f0cc10d20ebb8e63f7f78424ad0a8ea2a5db
C++
titasurbonas/-EmbeddedRealTimeSystems-
/project/lab_based_hardware/audio/audio.sdk/Driver_alt/src/UserControlThread.h
UTF-8
1,042
2.71875
3
[]
no_license
/* * UserThread.h * * Created on: 18. aug. 2017 * Author: Kim Bjerge */ #ifndef SRC_USERCONTROLTHREAD_H_ #define SRC_USERCONTROLTHREAD_H_ #include "hal/Switch.h" #include "hal/Leds.h" #include "os/Thread.h" #include "UserParameters.h" class UserControlThread : public Thread { public: UserControlThread(ThreadPriority pri, string name, UserParameters *pUP) : Thread(pri, name) { pParameters = pUP; counter = 1000; } void updateUserParameters(void) { bool onSW0 = sws.isOn(Switch::SW0); bool onSW1 = sws.isOn(Switch::SW1); pParameters->setMute(onSW0); leds.setOn(Leds::LED0, onSW0); pParameters->setBypass(onSW1); leds.setOn(Leds::LED1, onSW1); } virtual void run() { while (counter > 0) { printf("%s running %d\r\n", getName().c_str(), counter--); updateUserParameters(); Sleep(500); } } private: Switch sws; Leds leds; int counter; UserParameters *pParameters; }; #endif /* SRC_USERCONTROLTHREAD_H_ */
true
dcb4649ebac6788f9f67b677dc04c680346c73d3
C++
PowerFighter/AlgorithmsDataStructures
/FramworkDev/linkedList.h
UTF-8
1,043
3.421875
3
[]
no_license
#pragma once /* The List class is a one way linked list with functions that can be implemented for higher level data-structures*/ /* Uses the lNode structure which has the one-way link to the next node*/ #include <iostream> #include "lNode.h" using namespace std; template <class datType> class List { public: //Initialize the root List(); //Function declarations void appendToTail(datType data); void appendToHead(datType data); void appendToPosition(datType data , int position); void deleteFromTail(); void deleteFromHead(); void deleteFromPosition(int position); void printList(); int getSize(); lNode<datType>* GetTail(); lNode<datType>* GetHead(); void clear(); bool IsEmpty(); bool Find(datType data); //Specifics for queue lNode<datType>* appendToTailAndReturn(datType data); datType deleteFromHeadAndReturn(); private: //Specifics for current count / size int _size; //The root of the list lNode<datType> *root; //The tail of the list (or the end) lNode<datType> *tail; };
true
d9841edca57aef5e2f33940333313ed3cbb9fb33
C++
GregWagner/EyeOfTheBeholder2
/EyeOfTheyBeholder2/language.cpp
UTF-8
666
2.9375
3
[]
no_license
#pragma warning(disable : 4996) #include "language.h" #include <cstdio> #include <string> void Language::init(short language = 0) { // 0 = English, 1 = German FILE* file; std::string fileName; if (language == 0) fileName = "data/english.lang"; if (language == 1) fileName = "data/german.lang"; file = fopen(fileName.c_str(), "r"); char data[512]; short arrayPointer = 0; while (!feof(file)) { fgets(data, 512, file); if (strlen(data) > 1) { data[strlen(data) - 1] = '\0'; mText[arrayPointer++] = strdup(data); } data[0] = '\0'; } fclose(file); }
true
e0af8a97d39ee1c55ebfa9a8c171056507705fa1
C++
daniel0ferraz/Introducao-a-Programacao
/Tema 7 - Estrutura de repetição WHILE/Ex1.cpp
ISO-8859-1
351
2.84375
3
[]
no_license
#include<stdio.h> int main(){ int cont,par=0,impar=0; cont=1; while(cont<=20){ // condico para que a repetio seja realizada printf("%d\n",cont); cont++;// incremento da variavel para atualiza-la if(cont%2==0) par++; else impar++; } printf("Par: %d\n",par); printf("Impar: %d\n",impar); }
true
27546c0fa46143965765f13c19f554f625156bab
C++
gongzhxu/GxNetBase
/base/Buffer.h
UTF-8
713
2.875
3
[]
no_license
#ifndef buf_FER_H_ #define buf_FER_H_ #include <vector> #include <memory> class Buffer; typedef std::shared_ptr<Buffer> BufferPtr; #define MakeBufferPtr std::make_shared<Buffer> /* Buffer: extensible buffer block */ class Buffer { public: Buffer() {} virtual ~Buffer() {} public: char * data() { return buf_.data(); } char * data(size_t len) { return buf_.data()+len; } void clear() { buf_.clear(); } bool empty() { return buf_.empty(); } size_t size() { return buf_.size(); } void resize(size_t len) { buf_.resize(len); } void reserve(size_t len) { buf_.reserve(len); } size_t append(const void * buf, size_t len); private: std::vector<char> buf_; }; #endif
true
4398fa5ab51b23b7496423c49e2c711bd13c685f
C++
stanley-yangguang/Random-Seating
/start.cpp
UTF-8
7,286
2.90625
3
[ "Unlicense" ]
permissive
#include<iostream> #include<fstream> #include<vector> #include<map> #include<chrono> #include<random> using namespace std; #define MAXN 100 mt19937_64 rng(chrono::steady_clock::now().time_since_epoch().count()); bool mp[MAXN][MAXN]; int opt,len,dep,len2,dep2,num,stunum,numCancel,numStudent,numNotTgt,filled,randm; string newname; vector<string> names; vector<string> namesNotTgt; vector<string> seats; map<string,int> book; map<string,pair<int,int> > pos; void OptErr() { cout<<"Error! Wrong option!\n"; } bool isAdj(string a, string b) { pair<int,int> pr1=pos[a],pr2=pos[b]; if(abs(pr1.first-pr2.first)<=1 && abs(pr1.second-pr2.second)<=1) return 1; return 0; } int main() { cout<<"Hi user, welcome to the Random Seating Program\n designed by Stanley\n"; cout<<"Options: \n1: Init\n2: Start Assigning Seat\n3: Clear all settings\n"; cin>>opt; if(opt==1) { ofstream outConfigure("LenDepConfigure.txt"); cout<<"Input length: "; cin>>len; cout<<"Input depth: "; cin>>dep; outConfigure<<len<<endl<<dep<<endl; for(int i=1;i<=len;i++) for(int j=1;j<=dep;j++) mp[i][j]=1; cout<<"How many blocks to cancel: "; cin>>num; outConfigure<<num<<endl; for(int i=1;i<=num;i++) { cout<<"For the "<<i<<"th block, input length and depth: "; cin>>len2>>dep2; outConfigure<<len2<<" "<<dep2<<endl; mp[len2][dep2]=0; } cout<<"Display current map: \n"; for(int i=1;i<=len;i++) { for(int j=1;j<=dep;j++) { cout<<mp[i][j]<<" "; } cout<<endl; } outConfigure.close(); cout<<"Map updated successfully.\n"; cout<<"Next: input students' names. You can either input names manually or provide an external file containing all students' names.\n"; cout<<"1. Input students' names\n2. Import students' names\n"; cin>>opt; if(opt==1) { ofstream outStuName("StudentNameList.txt"); stunum=len*dep-num; cout<<"Total: "<<stunum<<" students\n"; outStuName<<stunum<<endl; for(int i=1;i<=stunum;i++) { cout<<i<<": "; cin>>newname; names.push_back(newname); outStuName<<newname<<endl; } outStuName.close(); cout<<"End. The list of students is in \"StudentNameList.txt\".\n"; } else if(opt==2) { cout<<"Please make sure that a file named \"StudentNameList.txt\" is in the correct path.\nInput format: a number \"num\" in the first line representing the number of students, followed by num lines, each line is the name of that student. Any order of names is ok.\n"; ifstream inStuName("StudentNameList.txt"); inStuName>>stunum; if(stunum!=len*dep-num) { cout<<"Error found in the number of students in \"StudentNameList.txt\"\n"; return 1; } inStuName.close(); /* outputStream<<stunum<<endl; for(int i=1;i<=stunum;i++) { inputStream>>newname; names.push_back(newname); outputStream<<newname<<endl; } outputStream.close(); */ cout<<"End. The list of students is in \"StudentNameList.txt\".\n"; } else OptErr(); cout<<"Next: input those students that should not sit together: \n"; ofstream outNotTgt("StudentNotTogetherList.txt"); cout<<"Number of students that should not sit together: "; cin>>num; outNotTgt<<num<<endl; for(int i=1;i<=num;i++) { cout<<i<<": "; cin>>newname; namesNotTgt.push_back(newname); outNotTgt<<newname<<endl; } outNotTgt.close(); cout<<"End. The list of students is in \"StudentNotTogetherList.txt\".\n"; } else if(opt==2) { ifstream inConfigure("LenDepConfigure.txt"); ifstream inStuName("StudentNameList.txt"); ifstream inNotTgt("StudentNotTogetherList.txt"); inConfigure>>len>>dep>>numCancel; for(int i=1;i<=len;i++) for(int j=1;j<=dep;j++) mp[i][j]=1; for(int i=1;i<=numCancel;i++) { inConfigure>>len2>>dep2; mp[len2][dep2]=0; } cout<<"Display current map: \n"; for(int i=1;i<=len;i++) { for(int j=1;j<=dep;j++) { cout<<mp[i][j]<<" "; } cout<<endl; } inConfigure.close(); inStuName>>numStudent; for(int i=1;i<=numStudent;i++) { inStuName>>newname; names.push_back(newname); } inStuName.close(); inNotTgt>>numNotTgt; for(int i=1;i<=numStudent;i++) { inNotTgt>>newname; namesNotTgt.push_back(newname); } inNotTgt.close(); cout<<endl; START: while(filled<numStudent) { randm=rng()%numStudent; if(!book[names[randm]]) { book[names[randm]]=1; seats.push_back(names[randm]); filled++; } } ofstream outSeating("seating.csv", ios::out | ios::trunc); int tempnum=0; for(int i=1;i<=len;i++) { for(int j=1;j<=dep;j++) { if(mp[i][j]) { outSeating<<seats[tempnum]<<","; printf("%10s",seats[tempnum].c_str()); pos[seats[tempnum]]=make_pair(i,j); tempnum++; } else { outSeating<<","; printf("%10s",""); } } outSeating<<endl; printf("\n"); } outSeating.close(); for(int i=0;i<numNotTgt;i++) for(int j=i+1;j<numNotTgt;j++) if(isAdj(namesNotTgt[i],namesNotTgt[j])) { goto START; } } else if(opt==3) { cout<<"Are you sure to clear all the settings? This process is irrecoverable. Press 1 to confirm and 2 to cancel.\n"; cin>>opt; if(opt==1) { remove("StudentNameList.txt"); remove("LenDepConfigure.txt"); remove("StudentNotTogetherList.txt"); ofstream outConfigure("LenDepConfigure.txt");outConfigure.close(); ofstream outStuName("StudentNameList.txt"); outStuName.close(); ofstream outNotTgt("StudentNotTogetherList.txt"); outNotTgt.close(); ofstream outSeating("seating.csv"); outSeating.close(); cout<<"Settings cleared.\n"; } else if(opt==2) { cout<<"Cancelled.\n"; } else OptErr(); } else OptErr(); cout<<"This is the end of the program. If you want to use other functions, please restart the program. Thank you for using.\n"; #ifdef _WIN32 system("pause"); #endif // __WIN32 #ifdef __WINDOWS_ system("pause"); #endif // __WINDOWS_ return 0; }
true
30ea6a06d21ada9ea587f27c4d791f0d899d0d8c
C++
soseyeritsyan/bigint-full-
/bigint.hpp
UTF-8
2,497
2.765625
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <string> #include <stdio.h> using namespace std; class bigint { private: vector<unsigned char> dig; friend void del_zero ( vector<unsigned char> & v ); friend void sys256 ( string & a , vector<unsigned char> & res ); friend void to_bigint ( string & a , vector<unsigned char> & res ); friend void plus_vec( vector<unsigned char> & v1 , vector<unsigned char> & v2 , vector<unsigned char> & res ); friend void minus_vec( vector<unsigned char> & v1 , vector<unsigned char> & v2 , vector<unsigned char> & res ); friend void mult_vec( vector<unsigned char> & v1 , vector<unsigned char> & v2 , vector<unsigned char> & res ); friend bool is_zero(vector<unsigned char> & v ); friend void unar_minus_vec( vector<unsigned char> & res ); friend bool big_vec( vector<unsigned char> & v1 , vector<unsigned char> & v2 ); friend bool less_vec( vector<unsigned char> & v1 , vector<unsigned char> & v2 ); friend bool eq_vec( vector<unsigned char> & v1 , vector<unsigned char> & v2 ); public: bigint(); bigint( string & s ); bigint( vector<unsigned char> & v); // ~bigint(); friend bigint operator+( bigint & ths , bigint & oth ); friend bigint operator-( bigint & ths , bigint & oth ); friend bigint operator*( bigint & ths , bigint & oth ); friend bigint operator/( bigint & ths , bigint & oth ); friend bigint operator%( bigint & ths , bigint & oth ); friend bool operator<( bigint & ths , bigint & oth ); friend bool operator>( bigint & ths , bigint & oth ); friend bool operator==( bigint & ths , bigint & oth ); friend bool operator>=( bigint & ths , bigint & oth ); friend bool operator<=( bigint & ths , bigint& oth ); friend bool operator!=( bigint & ths , bigint & oth ); friend bigint operator-( bigint & oth );// const; friend int size_bigint( bigint & ths ); friend void operator+=( bigint & ths , bigint& oth );// friend void operator-=( bigint & ths , bigint& oth ); friend void operator*=( bigint & ths , bigint& oth ); friend void operator/=( bigint & ths , bigint& oth ); friend void operator%=( bigint & ths , bigint& oth ); friend ostream & operator<<(ostream & out, bigint & b); friend istream & operator>> ( istream & in , bigint & b ); friend bigint & operator++( bigint & ths ); friend bigint operator++( bigint & ths , int ); friend bigint & operator--( bigint & ths ); friend bigint operator--( bigint & ths , int ); };
true
608676974cf9d9cd6cb0fe59c5ec081b845c6331
C++
R0bLucci/platformGame
/src/graphic.cpp
UTF-8
2,591
2.984375
3
[]
no_license
#include <SDL2/SDL.h> #include <SDL2/SDL_image.h> #include "../header/graphic.hpp" #include "../header/globals.hpp" #include <iostream> Graphic::Graphic() : window(nullptr), renderer(nullptr) { if(!this->window){ this->window = SDL_CreateWindow("Game", 100, 100, globals::WIDTH, globals::HEIGHT, SDL_WINDOW_SHOWN); // Check if window was successufuly creted if(!this->window){ std::cout << SDL_GetError() << std::endl; SDL_Quit(); } } if(!this->renderer){ this->renderer = SDL_CreateRenderer(this->window, -1, SDL_RENDERER_ACCELERATED); // Check if renderer was successufuly creted if(!this->renderer){ std::cout << SDL_GetError() << std::endl; SDL_DestroyWindow(this->window); SDL_Quit(); } } } SDL_Texture * Graphic::getTexture(const std::string name, bool isLevel){ std::string path; if(isLevel){ path = "resources/level/" + name; }else{ path = "resources/spriteSheet/" + name; } if(this->textures.count(path) == 0){ SDL_Surface * surface = IMG_Load(path.c_str()); if(!surface){ SDL_FreeSurface(surface); return (SDL_Texture*) this->throwError("Could not load surface", name); } // make black color transparent SDL_SetColorKey(surface, SDL_TRUE, 0); SDL_Texture * texture = SDL_CreateTextureFromSurface(this->renderer, surface); if(!texture){ SDL_FreeSurface(surface); SDL_DestroyTexture(texture); return (SDL_Texture *) this->throwError("Could not load texture", name); } this->textures[path] = texture; SDL_FreeSurface(surface); return texture; } return this->textures[path]; } void *Graphic::throwError(const std::string errMsg, const std::string filepath){ std::cout << errMsg << ": " << filepath << std::endl; return nullptr; } Graphic::~Graphic(){ for(auto & texture: textures){ std::pair<std::string, SDL_Texture*> pair = texture; SDL_DestroyTexture(pair.second); } SDL_DestroyWindow(this->window); SDL_DestroyRenderer(this->renderer); } void Graphic::blitSurface(SDL_Texture * texture, const SDL_Rect * source, const SDL_Rect * destination){ SDL_RenderCopy(Graphic::renderer, texture, source, destination); } void Graphic::blitBoundingBox(const std::string textureName, const SDL_Rect * source, const SDL_Rect & destination){ if(blitBB){ SDL_Texture * texture = this->getTexture(textureName, false); SDL_RenderCopy(Graphic::renderer, texture, source, &destination); } } SDL_Renderer * Graphic::getRenderer(){ return this->renderer; } void Graphic::clear(){ SDL_RenderClear(this->renderer); } void Graphic::render(){ SDL_RenderPresent(this->renderer); }
true
157658f1445ed5c4b23ee64281dcddc1a7972668
C++
jer22/OI
/hdu/1518/1518.cpp
UTF-8
1,148
2.765625
3
[]
no_license
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> using namespace std; int T, n; int arr[25]; bool vis[25]; int totlen; bool dfs(int pos, int len, int cnt) { // cout << pos << ' ' << len << ' ' << cnt << endl; if (cnt == 4) return true; for (int i = pos; i >= 1; i--) { if (vis[i]) continue; if (len + arr[i] < totlen) { vis[i] = 1; if (dfs(i - 1, len + arr[i], cnt)) return true; vis[i] = 0; } else if (len + arr[i] == totlen) { vis[i] = 1; if (dfs(n - 1, 0, cnt + 1)) return true; vis[i] = 0; return false; } } return false; } int main() { freopen("1518.in", "r", stdin); scanf("%d", &T); while (T--) { scanf("%d", &n); int sum = 0; for (int i = 1; i <= n; i++) { scanf("%d", &arr[i]); sum += arr[i]; } totlen = sum / 4; if (sum % 4) { printf("no\n"); continue; } if (arr[n] > totlen) { printf("no\n"); continue; } sort(arr + 1, arr + n + 1); memset(vis, 0, sizeof(vis)); bool ans; if (arr[n] == totlen) { ans = dfs(n - 1, 0, 1); } else ans = dfs(n, 0, 0); if (ans) printf("yes\n"); else printf("no\n"); } return 0; }
true
532f6729e1e9522f0ee58af8cb9ca1ea428d4e12
C++
jeremygf/HCVMicro
/HCVMicro/hcvstatus.h
UTF-8
1,428
2.546875
3
[]
no_license
//////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// //// //// Title: Person.h //// //// Description: A class that represents aspects of a person and //// his/her health etc. //// //// //////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////// #ifndef HCVSTATUS_H #define HCVSTATUS_H using namespace std; class HCVStatus { public: typedef enum infected_T { UNINFECTED = 0, INFECTED = 1, PREVINFECTED = 2 }; typedef enum genotype_T { GNONE = -1, G1 = 0, G2 = 1, G3 = 2, GOther = 3 }; typedef enum fibrosis_T { NOFIB = -1, F0 = 0, F1 = 1, F2 = 2, F3 = 3, F4 = 4, DC = 5, HCC = 6, LIVER_TRANSPLANT = 7, FDEAD = 8}; typedef enum progressor_T { PNONE = -1, PROGRESSOR = 0, NONPROGRESSOR = 1 }; typedef enum treatment_T { NOTX = 0, ONGOING = 1, SUCCESS = 2, FAIL = 3 }; typedef enum aware_T { ANONE = -1, UNAWARE = 0, AWARE = 1 }; HCVStatus(); infected_T infected; genotype_T genotype; fibrosis_T fibrosis; progressor_T progressor; treatment_T treatment; aware_T aware; int HCCtime; int LTtime; }; class HCVRiskStatus { public: typedef enum IL28B_T { CC = 0, CT = 1, TT = 2 }; typedef enum risk_T { LOWRISK = 0, HIGHRISK = 1 }; HCVRiskStatus(); IL28B_T il28b; risk_T risk; }; #endif
true
54cc4111f5f63bf0d5a8860b898dab2339b217f6
C++
ConcordUniversityMath240/FinalProject
/roguelike/inventory.h
UTF-8
7,871
3.484375
3
[]
no_license
/************************************************ inventory.h - Inventory related classes header file. - Item - Inventory Author: MATH 240 Team Purpose: These classes create items and control the player's inventory. *************************************************/ #ifndef INVENTORY_H #define INVENTORY_H #include <iostream> #include <ctime> #include <cstdlib> #include <cassert> #include <vector> using namespace std; /************************************************ Item class Item() Create a default Item with 0 bonuses. getName Return the Item's name. getItemType Return the Item's type (Armor, weapon, etc) getHealthBonus() Return the health bonus the item provides. getMagicAmount_CapBonus() Return the magic bonus the item provides. getDamageBonus() Return the damage bonus the item provides. getMagicDamageBonus() Return the magic damage bonus the item provides. getDefenseBonus() Return the defense bonus the item provides. getMagicDefenseBonus() Return the magic defense bonus the item provides. getEvasionBonus() Return the evasion bonus the item provides. getCriticalBonus() Return the critical hit bonus the item provides. setCurrentFloorLevel() Return the floor level the item is on. setName() Set the item's name. randomize() Randomly assign the Item's bonus stats depending on floor level it is found on. *************************************************/ class Item : public Object { private: string name; int currentFloorLevel; int itemType; int healthBonus; int magicAmount_CapBonus; int damageBonus; int magicDamageBonus; int defenseBonus; int magicDefenseBonus; int evasionBonus; int criticalBonus; public: Item() { name = ""; itemType = 0; healthBonus = 0; magicAmount_CapBonus = 0; damageBonus = 0; magicDamageBonus = 0; defenseBonus = 0; magicDefenseBonus = 0; evasionBonus = 0; criticalBonus = 0; } string getName() { return name; } int getItemType() { return itemType; } int getHealthBonus() { return healthBonus; } int getMagicAmount_CapBonus() { return magicAmount_CapBonus; } int getDamageBonus() { return damageBonus; } int getMagicDamageBonus() { return defenseBonus; } int getDefenseBonus() { return defenseBonus; } int getMagicDefenseBonus() { return magicDefenseBonus; } int getEvasionBonus() { return evasionBonus; } int getCriticalBonus() { return criticalBonus; } void setCurrentFloorLevel(int input) { currentFloorLevel = input; } void setName(string input) { name = input; } // Gives an item relevant random stats. void randomize() { itemType = rand() % 2; // Armor if (itemType == 0) { name = "Shield"; healthBonus = rand() % 10 + currentFloorLevel; defenseBonus = rand() % 1 + currentFloorLevel; magicDefenseBonus = rand() % 5 + currentFloorLevel; evasionBonus = rand() % 1 + currentFloorLevel; } // Weapon else if (itemType == 1) { name = "Sword"; damageBonus = rand() % 5 + currentFloorLevel; magicDamageBonus = rand() % 5 + currentFloorLevel; criticalBonus = rand() % 1 + currentFloorLevel; } } }; /*********************************************** Inventory class print() Displays inventory and allows player to equip items. ***********************************************/ class Inventory { public: vector <Item> storage; Item nullItem; // Displays inventory and allows player to equip items. int print() { unsigned int counter = 0; int input; if (storage.size() == 0) { move(44, 0); printw("No items!"); getch(); return 99; } for (int i = 15; i < 45 ; i += 10) for (int j = 5; j < 77; j += 18) { move(i-1, j-1); printw("--------------------"); move(i, j-1); printw("- -"); move(i+1, j-1); printw("- -"); move(i+2, j-1); printw("- -"); move(i+3, j-1); printw("- -"); move(i+4, j-1); printw("- -"); move(i+5, j-1); printw("- -"); move(i+6, j-1); printw("- -"); move(i+7, j-1); printw("--------------------"); move(i,j); printw(" %i. ", counter); const char *itemName = storage[counter].getName().c_str(); printw(itemName); // Armor if (storage[counter].getItemType() == 0) { move(i+1,j); printw(" Defense: +%i", storage[counter].getDefenseBonus()); move(i+2,j); printw(" Health: +%i", storage[counter].getHealthBonus()); move(i+3,j); printw(" M.Defense: +%i", storage[counter].getMagicDefenseBonus()); move(i+4,j); printw(" Evasion: +%i", storage[counter].getEvasionBonus()); } // Weapon else if (storage[counter].getItemType() == 1) { move(i+1,j); printw(" Damage: +%i", storage[counter].getDamageBonus()); move(i+2,j); printw(" Magic Damage: +%i", storage[counter].getMagicDamageBonus()); move(i+3,j); printw(" Critical: +%i", storage[counter].getCriticalBonus()); } counter++; // Equip functionality. if (counter >= storage.size()) { move(44, 0); printw("Press 'E' to equip an item or any other key to exit."); input = getch(); // options to equip go here. if(input == 'e' || input == 'E') { move(46, 0); printw("Enter the number of the item to equip:"); input = getch() - '0'; return input; } return 99; } } getch(); return 99; } }; #endif
true
eb048ddeb79af9dc630b88f8547ddb0957932cd6
C++
rishabhdhenkawat/DS_LAB_ASSINGMENT
/1 bubble sort.cpp
UTF-8
825
3.5
4
[]
no_license
#include <iostream> using namespace std; void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } void bubble_sort(int a[],int n) { int flag=0; for(int i=0;i<n-1;i++) { for(int j=0;j<n-i-1;j++) { if(a[j]>a[j+1]) { swap(&a[j],&a[j+1]); flag=1; } } if (flag==0) break; } cout<<"sorted array"<<endl; for(int i=0;i<n;i++) cout<<a[i]<<" "; } int main() { int n; cout << "Enter the number of items:" << "\n"; cin >>n; int *arr = new int(n); cout << "Enter " << n << " items" << endl; for (int x = 0; x < n; x++) { cin >> arr[x]; } bubble_sort(arr,n); return 0; }
true
37143402bc6234a4fb54e4da67c6a0b6f77fb386
C++
jph83405/Arduino
/Winning_Hackathon_Design/EEPROM_READ.ino
UTF-8
492
2.78125
3
[]
no_license
//EEPROM READER #include <EEPROM.h> int addr=0; byte value; void setup() { Serial.begin(9600); } void loop() { value=EEPROM.read(addr); if((addr+3)%3==0){ Serial.print("temp level = "); Serial.println(value,DEC); } else if((addr+3)%3==1){ Serial.print("sound level = "); Serial.println(value,DEC); } else{ Serial.print("light level = "); Serial.println(value,DEC); } addr++; if(addr==EEPROM.length()){ addr=0; } delay(100); }
true
073fdd6e6379fc3451b4e68da064c3251abdd3e5
C++
galgreg/SchoolStatistics
/school/test/confirmdialogmock.cpp
UTF-8
981
2.609375
3
[]
no_license
#include "confirmdialogmock.h" ConfirmDialogMock::ConfirmDialogMock( const QString &defaultAction, const QString &defaultStudentName) noexcept : mActionString(defaultAction), mStudentName(defaultStudentName) { } void ConfirmDialogMock::showDialog() noexcept { } void ConfirmDialogMock::hideDialog() noexcept { } void ConfirmDialogMock::customizeDialogMessage( StudentDataAction actionToDo, const QString &studentName) noexcept { if (actionToDo == ADD_STUDENT) { mActionString = "add"; } else if (actionToDo == EDIT_STUDENT) { mActionString = "edit"; } else if (actionToDo == DELETE_STUDENT) { mActionString = "delete"; } else { mActionString = ""; } mStudentName = studentName; } QString ConfirmDialogMock::getCurrentActionString() noexcept { return mActionString; } QString ConfirmDialogMock::getCurrentStudentName() noexcept { return mStudentName; }
true
bce7b919002ec4f8ec9c21a3aa624ef2f59bce18
C++
i2s-sys/CSDN
/图论/graph.cpp
UTF-8
8,587
3.0625
3
[]
no_license
#include<iostream> #include<vector> #include<queue> using namespace std; vector<int> sortTopo(vector<vector<int>> ad, vector<int> inDec);//拓扑排序 ad为邻接表 inDec为节点的入度 void sortTopoResult(void);//显示拓扑排序的例子 vector<int> minPathGraphWithoutWeight(vector<vector<int>>ad, int n,int start, int end=-1);//无权无向图的最小路径算法 void minPathGraphWithoutWeightResult(void);//显示无权无向图的最小路径例程 vector<int> minPathGraphWithWeight(vector<vector<pair<int, int>>> ad, int n, int start, int end = -1);//显示有权有向图最小路径 void minPathGraphWithWeightResult(void);//有权有向图最小路径的显示例程 vector<int> minSpanningTree(vector<vector<pair<int, int>>> ad, int n);//无向图最小生成树 void minSpanningTreeResult(void);//最小生成树显示例程 vector<int> minPathWithMinusWeight(vector<vector<pair<int, int>>> ad, int n, int start, int end = -1);//有负值权重有向图的最小路径 void minPathWithMinusWeight(void);//有负值权重的有向图最小路径例程 int main() { cout << "Please call function. " << endl; return 0; } vector<int> sortTopo(vector<vector<int>> ad, vector<int> cnt) { int n = cnt.size();//节点个数 queue<int> q;//辅助队列 顺序访问 for (int i = 0; i < n; i++) if (cnt[i] == 0) q.push(i);//入度为0的节点入队列 vector<int> res;//拓扑排序 while (!q.empty()) { int cur = q.front();//当前节点 res.push_back(cur);//放入拓扑排序 q.pop();//出队列 auto adCur = ad[cur];//当前节点的邻接节点 for (auto p : adCur)//遍历每一个节点p { cnt[p]--;//邻接节点p的入度减1 if (cnt[p] == 0)//入度为0 q.push(p);//放入队列 } } if (res.size() == n)//所有节点均拓扑有序 return res; else return {};//无拓扑排序 } void sortTopoResult(void) { int n = 5;//节点个数 vector<vector<int>> ad(5); ad[0] = { 2,3,4 };//1邻接3 4 5 ad[1] = { 0,2,3 };//2邻接 1 3 4 ad[2] = { 4 };//3邻接 5 ad[3] = { 4 };//4邻接 5 ad[4] = {};//5无邻接 vector<int> cnt(n, 0); for (auto p : ad) for (auto pp : p) cnt[pp]++; vector<int> sortTopoNum = sortTopo(ad, cnt); if (sortTopoNum.empty()) cout << "Graph has not topo sort arr." << endl; else { for (auto p : sortTopoNum) cout << p + 1 << " ";//图中节点序号与数组索引对齐 cout << endl; } } vector<int> minPathGraphWithoutWeight(vector<vector<int>>ad, int n,int start, int end)//无权无向图的最小路径算法 { start--;//节点序号与索引对齐 end--;//节点序号与索引对齐 queue<int> q; vector<bool> known(n, false); vector<int> res(n,-1);//起始距离为-1 q.push(start); known[start] = true; int layer = 0; while (!q.empty()) { int size = q.size();//当前层的节点个数 for (int i = 0; i < size; i++)//遍历当前层 { auto cur = q.front();//当前节点 q.pop();//出队列 res[cur] = layer;//记录最小路径 if (cur == end) return res;//指定终点 提前退出 for(auto p:ad[cur]) if (!known[p])//未访问 { q.push(p);//放入队列 known[p] = true;//记录已在队列中 } } layer++;//层序增加 } return res; } void minPathGraphWithoutWeightResult(void) { int n = 7; vector<vector<int>> ad(n); ad[0] = { 1,2 }; ad[1] = { 0,3 }; ad[2] = { 0,3,5 }; ad[3] = { 1,2,5,6 }; ad[4] = { 6 }; ad[5] = { 2,3 }; ad[6] = { 3,4 }; int start = 3; vector<int> path = minPathGraphWithoutWeight(ad, n, start);//path[i]=path start->(i+1) cout << "minPath of Vertex" << start << " to every Vertex:" << endl; for (auto p : path) cout << p << " "; cout << endl; int end = 2; path = minPathGraphWithoutWeight(ad, n, start, end); cout << "minPath of Vertex" << start << " to Vertex" << end << endl; for (auto p : path) cout << p << " "; cout << endl; } vector<int> minPathGraphWithWeight(vector<vector<pair<int, int>>> ad, int n, int start, int end) { start--;//序号对齐 end--;//序号对齐 vector<int> res(n,INT_MAX); vector<bool> known(n, false); res[start] = 0; //queue<int> q; int cur = start;//当前节点 while (cur != -1)//当没有下个需要更新或者能更新的节点 置cur为-1 使循环退出 { known[cur] = true; if (cur == end) return res; priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> s;//使用小顶堆求当前下个待处理节点 for(auto p:ad[cur]) if (!known[p.first])//未读节点 { res[p.first] = min(res[p.first], res[cur] + p.second);//更新最小距离 s.push({ res[p.first],p.first});//放入小顶堆 求下一个节点 } if (s.empty())//没有需要更新的节点或没有能更新的节点了 cur = -1;//结束 else cur = s.top().second; } return res; } void minPathGraphWithWeightResult(void) { int n = 7; vector<vector<pair<int, int>>> ad(n); ad[0] = { {3,1} }; ad[1] = { {3,3},{4,10} }; ad[2] = { {0,4},{5,5} }; ad[3] = { {2,2},{5,8},{6,4},{4,2} }; ad[4] = { {6,6} }; ad[5] = {}; ad[6] = { {5,1} }; vector<int> path = minPathGraphWithWeight(ad, n, 3); for (auto p : path) cout << p << " "; cout << endl; } vector<int> minSpanningTree(vector<vector<pair<int, int>>> ad, int n) { vector<bool> known(n, false);//记录每个顶点是否已读 vector<int> res(n,-1);//记录每个顶点连接的顶点 vector<int> cost(n, INT_MAX);//cost[i]=min(w(j,i)) 所有邻接到i的边的最小权重 初值为INT_MAX便于取min queue<int> q; q.push(0);//从顶点1开始构建最小生成树 起点任意 known[0] = true; while (!q.empty()) { int cur = q.front(); q.pop(); auto adj = ad[cur];//cur的所有边 for (auto p : adj) if (!known[p.first] && cost[p.first] > p.second) { res[p.first] = cur;//记录边 要在更新当前边的cost时 更新连接的顶点 cost[p.first] = p.second; } priority_queue<pair<int, int>, vector<pair<int, int>>, greater<>> s;//小顶堆 求当前顶点的最小边 for (int i = 0; i < n; i++) if (!known[i]) s.push({ cost[i],i }); if (!s.empty()) { int nxt = s.top().second;//当前顶点在最小生成树中的边 做为下个顶点 q.push(nxt); known[nxt] = true;//记为已读 } cout << "cur=" << cur+1 << ":";//当前顶点和 当前轮每个顶点的连接情况 for (auto p : res) cout << p + 1 << " "; cout << endl; } return res; } void minSpanningTreeResult(void) { int n = 7; vector<vector<pair<int, int>>> ad(n); ad[0] = { {1,2},{3,1},{2,4} }; ad[1] = { {0,2},{3,3},{4,10} }; ad[2] = { {0,4},{3,2},{5,5} }; ad[3] = { {0,1},{1,3},{2,2},{4,7},{5,8},{6,4} }; ad[4] = { {1,10},{3,7},{6,6} }; ad[5] = { {2,5},{3,8},{6,1} }; ad[6] = { {3,4},{5,1},{4,6} }; vector<int> res = minSpanningTree(ad, n); for (int i = 0; i < n; i++) cout << "Vertex" << i + 1 << " link Vertex" << res[i] + 1 << endl; } vector<int> minPathWithMinusWeight(vector<vector<pair<int, int>>> ad, int n,int start,int end) { start--;//顶点序号与索引对齐 end--;//顶点序号与索引对齐 vector<int> path(n, INT_MAX);//从start出发到其他顶点的最小距离 path[start] = 0;//起点到起点的最小距离 初始值为0 for (int i = 0; i <= n; i++)//若能进入第n次循环说明存在负值圈 { if (i == n) return {};//有负值圈时返回空 当i==n时能更新(更小路径)的顶点都是在负值圈上的点 bool update = true;//记录本轮是否有更新 若无更新 说明已达到所有顶点的最小路径 若指定end顶点 则update只检测end顶点是否更新 //遍历每条边 若d[u]不为INT_MAX 则以min(path[u]+w(u,v),path[u])更新v j记录边的起点 p.first为边的终点 p.second为边的权重 for (int j = 0; j < n; j++) { if (path[j] == INT_MAX) continue;//起点为j的路径 s->j还未更新 for (auto p : ad[j])//遍历起点为顶点j的每条边 { if (path[p.first] > path[j] + p.second)//path[v]>path[u]+w(u,v) { path[p.first] = path[j] + p.second;//更新start->v的最小路径 update = false;//记录本轮有最小路径更新 } } } if (update) break;//该轮没有更小的路径更新 说明已经迭代已经停止 } return path; } void minPathWithMinusWeight(void) { int n = 4; int start = 1; vector<vector<pair<int, int>>> ad(n); ad[0] = { {1,8},{3,4} }; ad[1] = { {3,-5} }; ad[2] = {}; ad[3] = { {2,3} }; vector<int> res = minPathWithMinusWeight(ad, n, start);//从顶点1出发的所有最小路径 for (int i = 0; i < n; i++) cout << "Path of " << start << " to " << i + 1 << " = " << res[i] << endl; }
true
c1702517c465408672edb79a96dac8b83f917304
C++
DitaRahmaAmalia/praktikum-algo
/GIT 4/Tugas4_124200032.cpp
UTF-8
985
3.28125
3
[]
no_license
#include <iostream> #include <iomanip> using namespace std; main () { int pilih, M, N, jumlah; cout << "Perkalian dan Perpangkatan" << endl; cout << "[1] Perkalian" << endl; cout << "[2] Perpangkatan" << endl; cout << "Pilih = "; cin >> pilih ; cout << " " <<endl; switch (pilih) { case 1 : cout << "Masukkan Nilai M = "; cin >> M; cout << "Masukkan Nilai N = "; cin >> N; jumlah = 0; for (int loop = 1; loop <=N; loop++) { jumlah += M; if (loop != N) {cout << M << "+";} else {cout << M << "=" << jumlah;} } break; case 2 : cout << "Masukkan Nilai M = "; cin >> M; cout << "Masukkan Nilai N = "; cin >> N; cout << "\nhasil" << " " << M << "^" << N << endl; jumlah = 1; for (int loop = 1; loop <= N; loop++) { jumlah *= M; if (loop != N) {cout << M << "x";} else {cout << setprecision (999999) << M << "=" << jumlah;} } break; default : cout << ("Input salah!\n"); } }
true
8efdd1e641603154c0ae3e7302ceafbb6d267700
C++
JaredMacDonald/NDSEngine
/Engine/include/Input/InputManager.h
UTF-8
918
2.515625
3
[]
no_license
#pragma once #include <nds.h> namespace JM { enum EButton { BUTTON_A = KEY_A, BUTTON_B = KEY_B, BUTTON_SELECT = KEY_SELECT, BUTTON_START = KEY_START, BUTTON_DPAD_RIGHT = KEY_RIGHT, BUTTON_DPAD_LEFT = KEY_LEFT, BUTTON_DPAD_UP = KEY_UP, BUTTON_DPAD_DOWN = KEY_DOWN, BUTTON_RIGHT_SHOULDER = KEY_R, BUTTON_LEFT_SHOULDER = KEY_L, BUTTON_X = KEY_X, BUTTON_Y = KEY_Y, BUTTON_TOUCH = KEY_TOUCH, BUTTON_LID = KEY_LID }; class InputManager { public: static InputManager* GetInstance() { if (Instance == nullptr) { Instance = new InputManager(); } return Instance; } ~InputManager(); void UpdateInput(); bool IsButtonDown(EButton button); bool IsButtonUp(EButton button); bool IsButtonHeld(EButton button); private: InputManager(); uint32 m_CurrentState; uint32 m_PrevState; static InputManager* Instance; }; }
true
ad066304800a7087a43957e9ef581bf3d5b6c0d5
C++
tyhenry/LoVid-ReactionBubble-RAW
/Arduino/IR_Receiver_BeamBreak_CodeDetector_SERIAL_UNO/IR_Receiver_BeamBreak_CodeDetector_SERIAL_UNO.ino
UTF-8
7,799
2.59375
3
[]
no_license
/* * BeamBreak and IR Code detector for LoVid Reaction Bubble Project * by Tyler Henry * * jump from pin 3 to +v sets to IR code detector mode * otherwise, will only report beam breaks over radio * * Designed to work with Atmega328 (Adafruit Trinket Pro or Uno) * * Input Capture function * uses timer hardware to measure pulses on pin 8 on 168/328 * * Input capture timer code based on Input Capture code found in Arduino Cookbook */ #include <RF24.h> #include <RF24Network.h> #include <SPI.h> /* IR CODES GO HERE */ /*--------------------------------------------------------*/ //value of IR CODEs to be checked for (these are length of IR burst in microseconds) const int codeArraySize = 5; const int codes[codeArraySize] = {1000, 1200, 1400, 1600, 1800}; /*--------------------------------------------------------*/ /* RF24 NODE ADDRESS GOES HERE */ /*--------------------------------------------------------*/ // node address of this IR beam for RF24Network: const uint16_t rfNode = 01; // IR beams are addressed: 01, 02, 03, 04, 05 // Master receiver Arduino Uno is base node: 00 /*--------------------------------------------------------*/ const int ledBBPin = 3; // LED Beam Break Pin: ON when beam break detected (OFF when receiving IR signal) const int inputCapturePin = 8; // Input Capture pin fixed to internal Timer - MUST BE 8 on ATMega168/328 const int prescale = 64; // prescale factor 64 needed to count to 62 ms for beam break const byte prescaleBits = B011; // see Table 18-1 or data sheet // calculate time per counter tick in ns const long precision = (1000000/(F_CPU/1000)) * prescale ; const long compareMatch = (F_CPU/(16 * prescale)) - 1; //compareMatch interrupt value for beam break detection (16Hz) volatile unsigned long burstCount; // CPU tick counter for current burst volatile unsigned long pauseCount; // CPU tick counter for current pause unsigned long burstCounts[3]; // storage array of burst samples for checking code matches unsigned int burstIndex = 0; // index to the bursCounts storage array unsigned long burstTimes[3]; // storage array for conversion of burstCounts to time in microseconds volatile boolean bursted = false; volatile boolean paused = false; volatile boolean beamBroken = false; volatile boolean beamBrokenNew = true; boolean codeDetectMode = true; /* RF24Network setup */ /*--------------------------------------------------------*/ RF24 radio(9,10); // RF module on pins 9,10 RF24Network network(radio); // create the RF24Network object /*--------------------------------------------------------*/ /* ICR interrupt capture vector */ /* runs when pin 8 detects an input change (rising or falling trigger depends on ICES1 value) */ ISR(TIMER1_CAPT_vect){ TCNT1 = 0; // reset counter if(bitRead(TCCR1B, ICES1)){ // rising edge was detected on pin 8 - meaning IR signal ended (NO IR signal now) burstCount = ICR1; // save ICR timer value as burst length beamBrokenNew = true; bursted = true; // burst complete } else { // falling edge was detected on pin 8 - meaning IR signal now present beamBroken = false; pauseCount = ICR1; // save ICR timer value as pause length paused = true; // pause complete } TCCR1B ^= _BV(ICES1); // toggle bit to trigger on the other edge } //beam break interrupt vector ISR(TIMER1_COMPA_vect){ //timer1 interrupt at 16Hz (62.5 milliseconds) beamBroken = true; } void setup() { Serial.begin(115200); // SPI.begin(); // radio.begin(); // start the RF24 module // network.begin(90, rfNode); // start the RF24 network on channel 90 with rfNode address pinMode(inputCapturePin, INPUT); // ICP pin (digital pin 8 on Arduino) as input pinMode(ledBBPin, OUTPUT); // LED on when beam break detected // pinMode(3, INPUT); // jumper on 3 to +v to set to code detector mode // if (digitalRead(3) == 1){ // codeDetectMode = true; // } // cli(); //stop interrupts temporarily //input capture timer: TCCR1A = 0; // Normal counting mode TCCR1B = 0; TCCR1B = prescaleBits ; // set prescale bits TCNT1 = 0; //reset counter TCCR1B |= _BV(ICES1); // enable input capture: counter value written to ICR1 on rising edge bitSet(TIMSK1,ICIE1); // enable input capture interrupt for timer 1: runs ISR //TIMSK1 |= _BV(TOIE1); // Add this line to enable overflow interrupt //beam break interrupt: TCCR1B |= (1 << WGM12); //Timer 1 CTC mode: TCNT1 clears when OCR1A reached OCR1A = compareMatch; //set compare match interrupt for beam break to 62ms (~16Hz) TIMSK1 |= (1 << OCIE1A); // enable timer compare interrupt sei(); //turn interrupts back on } void loop(){ // network.update(); if (bursted && codeDetectMode){ // run if a burst was detected burstCounts[burstIndex] = burstCount; // save the current burst count in the array if(burstIndex == 2){ // if array is full // calculate time (microseconds) values of burstCounts array for(int i = 0 ; i < 3 ; i++){ burstTimes[i] = calcTime(burstCounts[i]); Serial.println(burstTimes[i]); } // bubble sort (i.e. from small to large) the time value array for easy comparisons bubbleSort(burstTimes, 3); //check for close matches in array for(int i=0; i<2; i++){ bool bMatched = false; unsigned long dif = burstTimes[i+1] - burstTimes[i]; if (dif < 100) { //check to see if the two times are close (100 is fairly arbitrary, depends on sensor accuracy) unsigned long avg = (burstTimes[i+1] + burstTimes[i]) / 2; //use average to check for matches to CODE values for (int j=0; j<codeArraySize; j++){ // check the CODE value array for matches if (avg > codes[j]-75 && avg < codes[j]+75){ //if the avg of the two values is within 150 micros of a CODE // SEND MATCHED CODE VALUE TO RF unsigned long code = codes[j]; // sendRF(code); // CODE value received Serial.print("MATCH: "); Serial.println(code); bMatched = true; break; } } if (bMatched) break; // just find one match per 3 bursts } } burstIndex = 0; } else { burstIndex++; } bursted = false; // reset bursted boolean } if (beamBroken){ if (beamBrokenNew){ // sendRF(62500); // send beam break value of 62500 Serial.print("BREAK: "); Serial.println(62500); beamBrokenNew = false; } digitalWrite(ledBBPin, HIGH); burstIndex = 0; } else { digitalWrite(ledBBPin, LOW); } } // converts a timer count to microseconds long calcTime(unsigned long count){ long durationNanos = count * precision; // pulse duration in nanoseconds if(durationNanos > 0){ long durationMicros = durationNanos / 1000; return (durationMicros); // duration in microseconds } else { return 0; } } /* lifted from http://www.hackshed.co.uk/arduino-sorting-array-integers-with-a-bubble-sort-algorithm/ */ void bubbleSort(unsigned long a[], int aSize) { for(int i=0; i<(aSize-1); i++) { for(int j=0; j<(aSize-(i+1)); j++) { if(a[j] > a[j+1]) { int t = a[j]; a[j] = a[j+1]; a[j+1] = t; } } } } /* RF24 Network */ struct payload_t { // structure of message payload unsigned long rfCode; }; // sends RF packet to base node (address: 00) void sendRF(unsigned long _rfCode){ payload_t payload = {_rfCode}; RF24NetworkHeader header(00); // node to send to (base node 00) network.write(header,&payload,sizeof(payload)); }
true
15239223f4f18610d3b9f6b63b4ac154a04a6118
C++
AidanTemple/Network_Game_Sample
/AG1107A/UDPSocket.cpp
UTF-8
2,414
2.65625
3
[]
no_license
#pragma region Includes #include "UDPSocket.h" #include <stdio.h> #pragma endregion #pragma comment(lib, "ws2_32.lib") UDPSocket::UDPSocket() { m_SocketAddrSize = sizeof(sockaddr_in); Socket = 0; } UDPSocket::~UDPSocket() { Shutdown(); } int UDPSocket::NonBlocking(void) { u_long isNonBlocking = true; if ((ioctlsocket(Socket, FIONBIO, (u_long*)&isNonBlocking)) == SOCKET_ERROR) { printf("Error: Can't make Socket nonblocking\n"); printf("%d\n" , WSAGetLastError()); return 0; } return 1; } int UDPSocket::Initialise(void) { int error = WSAStartup(0x0202,&m_WSAData); if (error) { printf("You need WinSock 2.2\n"); return 0; } if (m_WSAData.wVersion!=0x0202) { printf("Error: Wrong WinSock version!\n"); WSACleanup (); return 0; } Socket = socket(AF_INET, SOCK_DGRAM, 0); if(Socket < 0) { printf("%d\n" , WSAGetLastError()); printf("Cannot open socket \n"); return 0; } return 1; } int UDPSocket::Bind(const int Port) { m_LocalAddr.sin_family = AF_INET; m_LocalAddr.sin_addr.s_addr = htonl(INADDR_ANY); m_LocalAddr.sin_port = htons(Port); int result = bind (Socket, (struct sockaddr *)&m_LocalAddr, m_SocketAddrSize); if(result < 0) { printf("%d\n" , WSAGetLastError()); printf("cannot bind port number %d \n", Port); return 0; } return 1; } int UDPSocket::Receive(char * Buffer) { int data = recvfrom(Socket, Buffer, PACKETSIZE, 0, (struct sockaddr*)&m_RemoteAddr, &m_SocketAddrSize); return data; } int UDPSocket::Send(char * Buffer) { int data = sendto(Socket, Buffer, PACKETSIZE, 0, (struct sockaddr*)&m_RemoteAddr, m_SocketAddrSize); return data; } sockaddr_in UDPSocket::GetDestAddr(void) { return m_RemoteAddr; } void UDPSocket::SetDestAddr(char * IP, const int Port) { m_RemoteAddr.sin_family = AF_INET; m_RemoteAddr.sin_port = htons (Port); m_RemoteAddr.sin_addr.s_addr = inet_addr (IP); } int UDPSocket::Shutdown() { if(Socket) { closesocket(Socket); } WSACleanup (); Socket = 0; return 1; }
true
2f5fdf964dbe9c986b51987b309de07c7c9f0b16
C++
vxl/vxl
/contrib/brl/bbas/bocl/bocl_buffer_mgr.cxx
UTF-8
4,215
2.65625
3
[]
no_license
#include <iostream> #include "bocl_buffer_mgr.h" #ifdef _MSC_VER # include "vcl_msvc_warnings.h" #endif bocl_buffer_mgr* bocl_buffer_mgr::instance_=NULL; bocl_buffer_mgr* bocl_buffer_mgr::instance() { if (instance_ == NULL) instance_= new bocl_buffer_mgr(); return instance_; } bool bocl_buffer_mgr::create_read_buffer(const cl_context& context, std::string name, void* data, unsigned size) { bocl_buffer* buf = new bocl_buffer(context); if (!buf->create_buffer(CL_MEM_READ_ONLY | CL_MEM_COPY_HOST_PTR, size, data)) { std::cout << "bocl_buffer_mgr::create_read_buffer -- clCreateBuffer failed for " << name << std::endl; return false; } buffers_[name]=buf; return true; } bool bocl_buffer_mgr::create_write_buffer(const cl_context& context, std::string name, void* data, unsigned size) { bocl_buffer* buf = new bocl_buffer(context); if (!buf->create_buffer(CL_MEM_READ_WRITE | CL_MEM_COPY_HOST_PTR, size, data)){ std::cout << "bocl_buffer_mgr::create_write_buffer -- clCreateBuffer failed for " << name << std::endl; return false; } buffers_[name]=buf; return true; } bool bocl_buffer_mgr::create_image2D(cl_context context, std::string name, cl_mem_flags flags, const cl_image_format * format, std::size_t width, std::size_t height, std::size_t row_pitch, void * data) { bocl_buffer* buf = new bocl_buffer(context); if (!buf->create_image2D(flags,format,width,height,row_pitch,data)){ std::cout << "bocl_buffer_mgr::create_write_buffer -- clCreateBuffer failed for " << name << std::endl; return false; } buffers_[name]=buf; return true; } bocl_buffer* bocl_buffer_mgr::get_buffer(std::string name) { if (buffers_.find(name) != buffers_.end()) return buffers_[name]; else return 0; } bool bocl_buffer_mgr::set_buffer(const cl_context& context, std::string name, cl_mem buffer) { bocl_buffer* buf = new bocl_buffer(context); return true; // was: return buf->set_mem(buffer); } bool bocl_buffer_mgr::enqueue_read_buffer(const cl_command_queue& queue, std::string name, cl_bool block_read, std::size_t offset,std::size_t cnb, void* data, cl_uint num_events, const cl_event* ev1, cl_event *ev2) { cl_int status = clEnqueueReadBuffer(queue,buffers_[name]->mem(), block_read, offset, cnb, data, num_events, ev1, ev2); return check_val(status,CL_SUCCESS,"clCreateBuffer failed for "+ name); } bool bocl_buffer_mgr::enqueue_write_buffer(const cl_command_queue& queue, std::string name, cl_bool block_write, std::size_t offset /* offset */, std::size_t cnb /* cb */, const void* data /* ptr */, cl_uint num_events /* num_events_in_wait_list */, const cl_event * ev1 /* event_wait_list */, cl_event * ev2) { cl_int status = clEnqueueWriteBuffer(queue,buffers_[name]->mem(),block_write, offset,cnb,data,num_events,ev1,ev2); return check_val(status,CL_SUCCESS,"enqueue_write_buffer failed."); } bool bocl_buffer_mgr::release_buffer(std::string name) { if (buffers_.find(name) != buffers_.end()) { buffers_[name]->release_memory(); return true; } std::cout << "clReleaseMemObject failed for " << name << std::endl; return false; } bool bocl_buffer_mgr::release_buffers() { std::map<std::string, bocl_buffer*>::const_iterator it=buffers_.begin(); while (it != buffers_.end()) { if (!it->second->release_memory()) return false; ++it; } return true; }
true
8b74b8f745407c1e1b281b104f46f7ba343e422c
C++
AkiraRafhaelJP/IoT
/test_relay_dht.ino
UTF-8
2,238
2.609375
3
[]
no_license
#include <WiFi.h> #include <MQTT.h> #include "DHT.h" #define RELAYPIN 23 #define DHTPIN 19 #define DHTTYPE DHT11 const char ssid[] = "ANDEKO 07"; const char pass[] = "LANTAI 1 MAS"; // //const char ssid[] = "ANDEKO 06"; //const char pass[] = "LANTAI 2 MAS"; const char espname[] = "ESP32"; const char username[] = "1bdbde55"; const char password[] = "8d6971631d05bb0b"; char floatConverted[10]; boolean isTemperatureToogled = false; WiFiClient net; MQTTClient client; DHT dht(DHTPIN, DHTTYPE); void connect() { Serial.print("checking wifi..."); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(1000); } Serial.print("\nconnecting..."); while (!client.connect(espname, username, password)) { Serial.print("."); delay(1000); } Serial.println("\nconnected!"); client.subscribe("/suhu"); client.publish("/suhu", "Mati"); // client.unsubscribe("/"); } void messageReceived(String &topic, String &payload) { Serial.println("incoming: " + topic + " - " + payload); if(payload == "ON"){ digitalWrite(RELAYPIN, LOW); Serial.println("SUHU NYALA"); isTemperatureToogled = true; } else if(payload == "OFF"){ digitalWrite(RELAYPIN, HIGH); Serial.println("SUHU MATI"); isTemperatureToogled = false; client.publish("/suhu", "Mati"); } } void calculateTemperature(){ delay(2000); float t = dht.readTemperature(); if (isnan(t)) { Serial.println(F("Failed to read from DHT sensor!")); client.publish("/suhu", "error"); return; } Serial.print(F("Temperature: ")); Serial.print(t); Serial.print(F("°C\n")); sprintf(floatConverted, "%.2f", t); client.publish("/suhu", floatConverted); } void setup() { // put your setup code here, to run once: Serial.begin(9600); WiFi.begin(ssid, pass); client.begin("broker.shiftr.io", net); client.onMessage(messageReceived); pinMode(RELAYPIN, OUTPUT); digitalWrite(RELAYPIN, HIGH); dht.begin(); connect(); } void loop() { client.loop(); delay(10); if (!client.connected()) { connect(); } if(isTemperatureToogled){ calculateTemperature(); } }
true
ccd6b3ae623d238c763a093794d15df336f2e06c
C++
morkvinaValeria/OOP
/Lab8/c++/Lab 8.cpp
UTF-8
1,064
3.390625
3
[]
no_license
#include <stdexcept> #include <iostream> #include <string> using namespace std; int LenRow(string** a) { int i = 0; while (a[0][i] != "\0") i++; return i; } int LenCol(string** a) { int j = 0; while (a[j][0] != "\0") j++; return j; } string* Get_MainDiagonal(string** a) { if(LenRow(a)==0 && LenCol(a) == 0) throw invalid_argument("Array cannot be null"); int n; if (LenRow(a) >= LenCol(a)) n = LenCol(a); else n = LenRow(a); string* b = new string[n]; for(int i = 0; i < LenRow(a); i++) for (int j = 0; j < LenCol(a); j++) if (i == j) b[i] = a[i][j]; return b; } int main() { int n = 5; string** a = new string* [n]; for (int i = 0; i < 2; i++) a[i] = new string[n]; a[0][0] = "w"; string*(*Ptr)(string**) = Get_MainDiagonal; try { Ptr(a); } catch (invalid_argument ex) { cout << ex.what(); } }
true
08b46bb04b9f511411709d50cd77f86a2d832cd0
C++
hunkar/c-c-
/deleteSpaces.cpp
UTF-8
569
3.21875
3
[]
no_license
/*Hünkar PURTUL*/ /*hunkarpurtul.blogspot.com*/ /*02.07.2016*/ /*Delete spaces in the char array*/ #include <stdio.h> #include <conio.h> int main() { char dizgi[100]; //Char array with 100 limit. int i, j; printf("Enter the array: \n"); gets(dizgi); for(i=0; dizgi[i]!='\0'; i++) //first loop till the end of char array { if(dizgi[i]==' ') for(j=i; dizgi[j]!='\0'; j++) dizgi[j]=dizgi[j+1]; //all elements which are after the space swap to before one index } puts(dizgi); //Show output array getch(); return 0; }
true
23c7a064b099cfd35d240504a7645a20645b56c9
C++
rahsinha2/Algorithms
/ArraysNStrings/UniqueCharacters/unique_characters.cpp
UTF-8
1,226
3.609375
4
[]
no_license
#include<iostream> #include<stdio.h> #include<string.h> #include<stdlib.h> using namespace std; #define ASCII_CHARACTERS 128 void bool_check_unique_characters(char * string); int main(int argc, char ** argv) { char * string = (char*)malloc(strlen(argv[1]+1)); memset(string,0, strlen(argv[1])+1); strncpy(string, argv[1], strlen(argv[1])); string[strlen(argv[1])] = '\0'; int len = strlen(string); if(len>ASCII_CHARACTERS) { cout<<"\nString has duplicate Characters\n"; free(string); exit(1); } bool_check_unique_characters(string); for(int i=0; i<(len-1); i++) { for(int j=i+1; j<len; j++) { if(string[i] == string[j]) { cout<<"\nString has duplicate Characters\n"; free(string); exit(1); } } } cout<<"\nString has all unique characters\n"; free(string); return 0; } void bool_check_unique_characters(char * string) { bool table[128]; for(int i=0; i<ASCII_CHARACTERS; i++) table[i] = false; for(int i=0; i<(int)strlen(string); i++) { if(table[(int)string[i]] == true) { cout<<"\nbool_check_unique_chars:String has duplicate Characters\n"; return; } table[(int)string[i]] = true; } cout<<"\nbool_check_unique_chars:String has all unique characters\n"; }
true
abd427a15b343daae99f05246cf4b94167de5caf
C++
LCMcu/QT_TCP_client
/serialport/mainwindow.cpp
UTF-8
3,742
2.625
3
[]
no_license
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { int ret=0; timer=new QTimer(); ui->setupUi(this); ret=SerialPortInit(); timer->setInterval(100); connect(serialport,SIGNAL(readyRead()),this,SLOT(ReadSerialPortData())); connect(timer,SIGNAL(timeout()),this,SLOT(TimerFunc())); } MainWindow::~MainWindow() { delete ui; } //初始化串口 int MainWindow::SerialPortInit(void) { int ret=0; int time=10; serialport=new QSerialPort(this); serialport->setPortName(QString("COM6")); serialport->setBaudRate(QSerialPort::Baud9600); serialport->setDataBits(QSerialPort::Data8);//8位数据位 serialport->setParity(QSerialPort::NoParity );//无校验 serialport->setStopBits(QSerialPort::OneStop );//1个停止位 serialport->setFlowControl(QSerialPort::NoFlowControl);//无流控制 do //打开串口 { ret=serialport->open(QIODevice::ReadWrite); } while (time--); if(ret!=0) goto SERIAL_PORT_ERR; this->timer->start(); // this->ui->comboBox_2->addItem(""); #ifdef DEBUG qDebug("serial_port open OK"); #endif return 0; SERIAL_PORT_ERR: #ifdef DEBUG qDebug("serial_port open FAIL"); #endif return -1; } //读取串口数据 int MainWindow::ReadSerialPortData(void) { int ret=0; QByteArray readba; QByteArray tempba; QString str; tempba.clear(); while(1) { tempba=serialport->readAll(); if(tempba.isEmpty()) break; readba.append(tempba); } str.append(readba); qDebug(readba.toHex()); ShowSerialPortData(str,0); return ret; } //发送串口数据 int MainWindow::WriteSerialPortData(QByteArray sendbuf) { int ret=0; ret=serialport->write(sendbuf); this->ui->comboBox_2->addItem("0000"); return ret; } //串口发送数据按钮 void MainWindow::on_sendButton_clicked() { QString send_str=this->ui->SendTextEdit->toPlainText(); WriteSerialPortData(send_str.toLatin1()); qDebug("write"); } //清除接收窗口内容 void MainWindow::on_pushButton_clicked() { this->ui->textBrowser->clear(); } //显示串口信息 int MainWindow::ShowSerialPortData(QString str, int mode) { int ret=0; static QString strbuf; switch (mode) { case 0: this->ui->textBrowser->append(str); break; case 1: break; default: break; } return ret; } //刷新按钮 void MainWindow::on_flushButton_clicked() { UpdateSerialPort(); } //更新串口列表 int MainWindow::UpdateSerialPort(void) { /* 查找可用串口 */ foreach(const QSerialPortInfo &info, QSerialPortInfo::availablePorts()) { QSerialPort serial; serial.setPort(info); info.isNull(); /* 判断端口是否能打开 */ if(serial.open(QIODevice::ReadWrite)) { int isHaveItemInList = 0; /* 判断是不是已经在列表中了 */ for(int i=0; i<ui->serial_name_Box->count(); i++) { /* 如果,已经在列表中了,那么不添加这一项了就 */ if(ui->serial_name_Box->itemText(i) == serial.portName()) { isHaveItemInList=1; } } if(isHaveItemInList == 0) { ui->serial_name_Box->addItem(serial.portName()); } serial.close(); } } } //定时器 void MainWindow::TimerFunc(void) { UpdateSerialPort(); }
true
25f9710b11de0851674f85772f0eb2d1fd9fb440
C++
The-DeadPixel/Parralell-Programming-Term-Project
/OMPSearch/StemExcep.h
UTF-8
1,251
2.59375
3
[]
no_license
/* Updated for implimenting Parralell OMP * Name: Luke Burford * Data: 12/6/18 * Email: lburford@rams.colostate.edu */ /* Name: Luke Burford * Date: 10/17/17 * Email: lburford@rams.colostate.edu */ #ifndef STEMEXCEP_H_INCLUDE #define STEMEXCEP_H_INCLUDE #include <Stem.h> #include <iostream> #include <fstream> #include <sstream> #include <unordered_map> #include <algorithm> #include <string> #include <ctime> #include <ratio> #include <chrono> using namespace std::chrono; using namespace std; extern duration<double> timer; class StemExcep { public: /* initalizes the exceptions file to iterate to check for exceptions before stemming * adds all strings to the 2 vectors: eVect & rVect * takes in a char pointer (to the start of a file) * returns true if it encountered an error, false if it went smoothly */ bool initExcep(char* list); /* with the input string check to see if it exsists in the exception vector * if so, modify it with its appropriate replacement from the replacement vector * if not just return the original string */ string checkExcep(string &sIn); private: unordered_map<string,string> eMap; // vector to store all of the possible exceptions Stem stem = Stem(); }; #endif //FREAD_H_INCLUDE
true
4fb644321fab80930c3fc26e2d1fac054d8e1e37
C++
andrewmo2014/Ray-Casting
/Sphere.cpp
UTF-8
1,101
2.859375
3
[]
no_license
#include "Sphere.h" using namespace std; bool Sphere::intersect( const Ray& r , Hit& h , float tmin){ //Ray-Sphere Intersection //t = (-b +- sqrt(b^2 - 4ac)) / 2a //a = (R_d . R_d) //b = 2(R_d . R_o) //c = (R_o . R_o) - r^2 Vector3f R_o = r.getOrigin() - this->center; Vector3f R_d = r.getDirection(); float a = R_d.absSquared(); float b = 2.0*Vector3f::dot(R_d, R_o); float c = R_o.absSquared() - pow(this->radius, 2); float discrim = pow(b,2) - (4*a*c); if (discrim >= 0){ //Want closest positive, therefore try t(-) first float t = (-1.0*b - sqrt(discrim)) / (2.0*a); if (t >= tmin && t <= h.getT()){ Vector3f normalNew = (r.getOrigin() + t*R_d - this->center).normalized(); h.set(t, this->material, normalNew); return true; } //Then try t(+) t = (-1.0*b + sqrt(discrim)) / (2.0*a); if (t >= tmin && t <= h.getT()){ Vector3f normalNew = (r.getOrigin() + t*R_d - this->center).normalized(); h.set(t, this->material, normalNew); return true; } } return false; }
true
464eba082e8d494a6d7becde0ef2f69165e9c804
C++
cjamanambu/OO_EventDriven_Sim
/IntItem.cpp
UTF-8
325
2.625
3
[]
no_license
// // Created by CJ on 2017-03-08. // #include "IntItem.h" // descriptors for the header file declarations in IntItem.h IntItem::IntItem() {} IntItem::~IntItem() {} IntItem::IntItem(int value) { this->value = value; } int IntItem::getValue() { return value; } void IntItem::print() { cout << value << endl; }
true
c46a0131498194ccfcee3a8316164327df793ec7
C++
johntalton/PortSpy
/IPHistory.cpp
UTF-8
1,464
2.6875
3
[]
no_license
/******************************************************* * PortSpy© * * @author YNOP(ynop@acm.org) * @vertion beta * @date October 19 1999 *******************************************************/ #include "IPHistory.h" IPHistory iphistory; /******************************************************* * *******************************************************/ IPHistory::IPHistory(){ AddIP(127,0,0,1,"Localhost"); /* AddIP(192,168,1,1,"Brain"); AddIP(192,168,1,37,"Abstract"); AddIP(192,168,0,1,"Plenty");*/ } /******************************************************* * *******************************************************/ IPHistory::~IPHistory(){ } /******************************************************* * *******************************************************/ status_t IPHistory::AddIP(uint8 a, uint8 b, uint8 c, uint8 d, BString name){ // test to see if this ip is already in the list !!! ip_hist *item = NULL; for(int32 i = 0; i < ips.CountItems();i++){ item = (ip_hist*)ips.ItemAt(i); if(item){ if((item->a == a) && (item->b == b) && (item->c == c) && (item->d == d)){ // same ip :P //item->name = name; return B_ERROR; } } } ip_hist *iph = new ip_hist; iph->a = a; iph->b = b; iph->c = c; iph->d = d; iph->name = name; ips.AddItem(iph); return B_OK; }
true
2f5993bea07ff1b7cf59e474963c7533f5be1206
C++
tnsgh9603/BOJ_Old
/최단경로.cpp
UHC
2,711
3.6875
4
[]
no_license
#include <iostream> #include <vector> #include <queue> // priority_queue ʿ #define max 200000000 // infinity ǥϱ using namespace std; vector< pair<int, int>> arr[20001]; // 2 迭 20001 vector<int> dijkstra(int start, int V, int E) { vector<int> dist(V, max); // dist ͸ Vũ ŭ max ʱȭ dist[start] = 0; // Ÿ 0̹Ƿ priority_queue<pair<int, int>> pq; //priority_queue pq.push(make_pair(0, start)); //  ־ while (!pq.empty()) // ݺ { int cost = -pq.top().first; // -ϴ ؿ int here = pq.top().second; // ġ pq.pop(); // ͺ ª θ ˰ ִٸ Ѵ. if (dist[here] < cost) { continue; } //dist[here] κ here ִܺ // ˻. for (int i = 0; i < arr[here].size(); i++) { int there = arr[here][i].first; int nextDist = cost + arr[here][i].second; // ª θ ߰ϸ, dist[] ϰ 켱 ť ִ´. if (dist[there] > nextDist) { dist[there] = nextDist; pq.push(make_pair(-nextDist, there)); /* ⼭ - ִ ? priority_queue STL ⺻ ū Ұ ť Ÿ ȣ ٲ㼭 Ÿ ϱ */ } } } return dist; } int main() { // , , Է¹޴´. int vertex, edge, start_edge; cin >> vertex >> edge; cin >> start_edge; vertex++; // 1 ϸ V++ش. ʹ 0 ϴµ 0̶ Ƿ ++. for (int i = 0; i < edge; i++) { int from, to, weight; cin >> from >> to >> weight; arr[from].push_back(make_pair(to, weight)); //Է  arr ־ } vector<int> ans = dijkstra(start_edge, vertex, edge); for (int i = 1; i < vertex; i++) { ans[i] == max ? printf("INF\n") : printf("%d\n", ans[i]); // ans[i] max INF, ƴϸ ans[i] } return 0; }
true
d0780d580a23582b07c566dffbb4d99decf8c3bd
C++
zeos/signalflow
/examples/cpp/sine-field-example.cpp
UTF-8
1,553
2.84375
3
[ "MIT" ]
permissive
/*------------------------------------------------------------------------ * SineOscillator field example * * An array of delayed sine pings. *-----------------------------------------------------------------------*/ #include <signalflow/signalflow.h> using namespace signalflow; int main() { /*------------------------------------------------------------------------ * Create the global processing graph and begin playback. *-----------------------------------------------------------------------*/ AudioGraphRef graph = new AudioGraph(); graph->start(); /*------------------------------------------------------------------------ * Create a bank of sine bleeps. *-----------------------------------------------------------------------*/ for (int x = 0; x < 32; x++) { NodeRef sine = new SineOscillator(random_uniform(220, 1660)); NodeRef resample = new Resample(sine, 11025, 12); NodeRef noise = new WhiteNoise(0.3, 1.0, 2); NodeRef dust = new RandomImpulse(noise); NodeRef env = new EnvelopeASR(0.005, 0.01, 0.05); env->set_input("clock", dust); NodeRef sum = resample * env; NodeRef pan = new LinearPanner(2, sum * 0.1, random_uniform(-1, 1)); NodeRef delay = new CombDelay(pan, 0.2, 0.4); graph->play(delay); } /*------------------------------------------------------------------------ * Run forever. *-----------------------------------------------------------------------*/ graph->wait(); }
true
9a657f7aa15bd04a6eb1348cf35cc03a0285a527
C++
atharva1910/DailyChallenges
/cipher.cpp
UTF-8
339
3
3
[]
no_license
#include <string> #include <iostream> /* Ceaser cipher */ int main(int argc, char **argv) { int n,i=0; std::string text; std::cout<<"Enter the shift\n"; std::cin>>n; std::cout<<"Enter the text\n"; std::cin>>text; while(text[i]){ text[i]=text[i]+n; i++; } std::cout<<text<<std::endl; }
true
ddba7ee1e1a574ff1a644b107a6b5fe79beb5d87
C++
firmread/cinderBasic
/basic2_3D/src/basic2_3DApp.cpp
UTF-8
3,482
2.515625
3
[]
no_license
#include "cinder/app/App.h" #include "cinder/app/RendererGl.h" #include "cinder/gl/gl.h" using namespace ci; using namespace ci::app; using namespace std; class basic2_3DApp : public App { public: void setup() override; void mouseDown( MouseEvent event ) override; void update() override; void draw() override; }; void basic2_3DApp::setup() { } void basic2_3DApp::mouseDown( MouseEvent event ) { } void basic2_3DApp::update() { } void basic2_3DApp::draw() { gl::clear(); // 3D! NOPE not that easy... // gl::drawCube(vec3(), vec3(2)); /* // 1 - we need a camera! CameraPersp cam; cam.lookAt(vec3(3),vec3(0)); gl::setMatrices(cam); gl::drawCube(vec3(), vec3(2)); */ //check out CameraPersp sample // console() << gl::getProjectionMatrix() << std::endl; /* // 2 - lambert shading CameraPersp cam; cam.lookAt(vec3(3), vec3(0)); gl::setMatrices(cam); auto lambert = gl::ShaderDef().lambert(); auto shader = gl::getStockShader(lambert); shader->bind(); gl::drawSphere(vec3(), 1.0f); */ /* // 3 - z buffering & sphere subdivisions gl::enableDepthRead(); gl::enableDepthWrite(); CameraPersp cam; cam.lookAt(vec3(3), vec3(0)); gl::setMatrices(cam); auto lambert = gl::ShaderDef().lambert(); auto shader = gl::getStockShader(lambert); shader->bind(); gl::drawSphere(vec3(), 1.0f, 40); */ /* // 4 - 3d with matrix transformations gl::enableDepthRead(); gl::enableDepthWrite(); CameraPersp cam; cam.lookAt(vec3(5,2,5), vec3(0,1,0)); gl::setMatrices(cam); auto lambert = gl::ShaderDef().lambert().color(); auto shader = gl::getStockShader(lambert); shader->bind(); int numSpheres = 64; float maxAngle = M_PI * 7; float spiralRadius = 1; float height = 3; for (int s = 0; s< numSpheres; ++s) { float rel = s / (float)numSpheres; float angle = rel * maxAngle; float y = rel * height; float r = rel * spiralRadius * spiralRadius; vec3 offset(r*cos(angle), y , r*sin(angle)); gl::pushModelMatrix(); gl::translate(offset); gl::color(Color(CM_HSV, rel , 1, 1)); gl::drawSphere(vec3(), 0.1f, 30); gl::popModelMatrix(); } */ /* // 5 - anim from getElapsedFrames gl::enableDepthRead(); gl::enableDepthWrite(); CameraPersp cam; cam.lookAt(vec3(3,4.5,4.5), vec3(0,1,0)); gl::setMatrices(cam); auto lambert = gl::ShaderDef().lambert().color(); auto shader = gl::getStockShader(lambert); shader->bind(); int numSpheres = 64; float maxAngle = M_PI * 7; float spiralRadius = 1; float height = 2; float anim = getElapsedFrames() / 30.0f; for (int s = 0; s<numSpheres; ++s) { float rel = s/(float)numSpheres; float angle = rel * maxAngle; float y = fabs(cos(rel*M_PI + anim))*height; float r = rel * spiralRadius; vec3 offset(r*cos(angle), y/2, r*sin(angle)); gl::pushModelMatrix(); gl::translate(offset); gl::scale(vec3(0.05f, y, 0.05f)); gl::color(Color(CM_HSV, rel, 1, 1)); gl::drawCube(vec3(), vec3(1)); gl::popModelMatrix(); } */ } CINDER_APP( basic2_3DApp, RendererGl )
true
1970fce1ef65c30e347790a8d647ac029c8638ee
C++
claytonkristiansen/CSCE221
/DebuggingActivity/baseTypes.h
UTF-8
3,998
3.328125
3
[]
no_license
//Contains the un-obfuscated base types for the functions to call/throw #pragma once #include "common.h" #include <exception> #include <iostream> #include <string.h> // for c-string functions class Exception0 : std::exception {}; class Exception1 : std::exception {}; class Exception2 : std::exception {}; class Exception3 : std::exception {}; class Exception4 : std::exception {}; class Exception5 : std::exception {}; class Exception6 : std::exception {}; class Exception7 : std::exception {}; class Exception8 : std::exception {}; class Exception9 : std::exception {}; class MaskedException : std::exception {}; //each of these simply call the provided function from the pointer void theMagicFruitIsApple(ReentryFunctionPointer p) { p(); return;} void theMagicFruitIsBanana(ReentryFunctionPointer p) { p(); return;} void theMagicFruitIsCherry(ReentryFunctionPointer p) { p(); return;} void theMagicFruitIsDate(ReentryFunctionPointer p) { p(); return;} void theMagicFruitIsElderberry(ReentryFunctionPointer p) { p(); return;} void theMagicFruitIsFig(ReentryFunctionPointer p) { p(); return;} void theMagicFruitIsGrape(ReentryFunctionPointer p) { p(); return;} void theMagicFruitIsHoneydew(ReentryFunctionPointer p) { p(); return;} void theMagicFruitIsLime(ReentryFunctionPointer p) { p(); return;} void theMagicFruitIsJuice(ReentryFunctionPointer p) { p(); return;} //throws a line that reports the error that void throwOnSomeLine(void){ std::cerr << "About to throw an error with the line number of the error " << std::endl; throw __LINE__; } void infiniteLoopError(void){ int i = 0; int answer = __LINE__ + 1; while(true){i += 1;} std::cout << i << answer << std::endl; return; } //masks the actual exception thrown // takes a function pointer to allow for insertion // anwhere in the call-stack template <class FuncPointer> void exceptionMasker(FuncPointer f, uint const number){ try{ f(number); }catch(const char* e){ //generic string exception //i.e. throw "some message"; throw MaskedException(); }catch(const int e){ //generic int exception //i.e. throw 5; throw MaskedException(); }catch(const Exception0 e){ throw MaskedException(); }catch(const Exception1 e){ throw MaskedException(); }catch(const Exception2 e){ throw MaskedException(); }catch(const Exception3 e){ throw MaskedException(); }catch(const Exception4 e){ throw MaskedException(); }catch(const Exception5 e){ throw MaskedException(); }catch(const Exception6 e){ throw MaskedException(); }catch(const Exception7 e){ throw MaskedException(); }catch(const Exception8 e){ throw MaskedException(); }catch(const Exception9 e){ throw MaskedException(); } } void permanentMessage(char* myMessage, unsigned int messageLength){ throw "Dont Read My Messages"; } //erases the value stored at c before throwing the exception void ephemeralMessage(char* myMessage, unsigned int messageLength){ //VVV this line erases the messages memset(myMessage, 0, messageLength); messageLength = 0; throw "Secrets Destroyed"; } // somewhere in c[0] to c[numMessages-1] there is a hidden message; void hiddenMessage(char** messageArray, unsigned int numMessages, unsigned int messageLength){ //VVV this line erases the messages memset(messageArray, 0, sizeof(char*) * numMessages); throw "Perfect Encryption"; } void reallyHiddenMessage(uintptr_t ptr, uintptr_t ptr1, uintptr_t ptr2){ int sleep_ctr = 0; while(sleep_ctr < 256) { sleep_ctr *= 2; } void* truePointer = (void*)(ptr ^ ptr1 ^ ptr2); //Some really, really nasty pointer math char *** bufferChar = (char***)(truePointer); unsigned int* bufferInt = (unsigned int*)(bufferChar+1); //call the previous message handler hiddenMessage(*bufferChar, bufferInt[0], bufferInt[1]); }
true
5136f31c0c562973346abdf8996ce05ebbaec8a9
C++
vaplilya/graph-depth-
/обход в глубину/обход в глубину.cpp
WINDOWS-1251
1,150
2.921875
3
[]
no_license
// ConsoleApplication3.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include<conio.h> #include<locale.h> #include<iostream> #include <stack> int main() { int n, t; std::stack<int> vertex; setlocale(0, "Russian"); std::cout << " :" << std::endl; std::cin >> n; int** matrix = new int*[n]; for (int y = 0; y < n; y++) matrix[y] = new int[n]; int* mas = new int[n]; std::cout << " :" << std::endl; for (int o = 0; o < n; o++) { mas[o] = 0; for (int h = 0; h < n; h++) std::cin >> matrix[o][h]; } vertex.push(mas[0]); while (!vertex.empty()) { t = vertex.top(); vertex.pop(); if (mas[t] == 2) continue; // , mas[t] = 2; for (int i = n; i > 0; i--)// , { if ((matrix[t][i] == 1) && (mas[i] !=2)) { mas[i] = 1;//, vertex.push(i); } } std::cout << t + 1 << std::endl; } _getch(); return 0; }
true
08049a9ac6304a0794996f5c8a7450ff59de235a
C++
simon0987/HMM-implementation
/test_hmm.cpp
UTF-8
1,698
2.71875
3
[]
no_license
#include "hmm.h" #include <math.h> #include <string> double viterbi(const HMM &hmm, const char *seq){ double delta[MAX_SEQ][MAX_STATE]; //initialize delta for(int i = 0; i < hmm.state_num;i++) delta[0][i] = hmm.initial[i]*hmm.observation[seq[0]-'A'][i]; //recursion delta only calculate to size-2 std::string s(seq); for(int t = 0;t<s.size()-1;t++){ for(int j = 0;j<hmm.state_num;j++){ double max = -100.0; for(int i = 0; i < hmm.state_num;i++){ double tmp = delta[t][i] * hmm.transition[i][j]; if(tmp > max) max = tmp; } delta[t+1][j] = max* hmm.observation[seq[t+1]-'A'][j]; } } //return the max of t-1 double max = -100; for(int i = 0 ; i < hmm.state_num;i++){ if(max < delta[s.size()-1][i]) max = delta[s.size()-1][i]; } return max; } int main(int argc,char** argv){ HMM hmms[5]; char seq[MAX_SEQ] = ""; int model_num = load_models(argv[1], hmms, 5); FILE *data = open_or_die(argv[2], "r"); FILE *result = open_or_die(argv[3], "w"); while(fscanf(data, "%s",seq)!=EOF){ int record_model = -100; double max = -100; for(int i = 0; i < model_num;i++){ double tmp = viterbi(hmms[i], seq); if(max<tmp){ max = tmp; record_model = i; } } fprintf(result, "%s %e\n",hmms[record_model].model_name, max); } fclose(data); fclose(result); return 0; }
true
722c4f847a105b787f00a80fec4b08430d5e4786
C++
XRJHandsome/nowcoder
/huawei/0046.cpp
UTF-8
358
3.4375
3
[]
no_license
// 0046.按字节截取字符串 // 根据题意,在判题系统中,汉字以2个字节存储。 #include <iostream> #include <cstring> using namespace std; int main() { string s; int n; while(cin >> s >> n) { if(s[n-1] < 0) s = s.substr(0, n-1); else s = s.substr(0, n); cout << s << endl; } return 0; }
true
c7f15c72a481fbbd1ba6855a2503d44ab0a766ec
C++
willflowers95/src
/simulation/utilities/gauss_markov.h
UTF-8
3,580
2.625
3
[]
no_license
/* ISC License Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder Permission to use, copy, modify, and/or distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef _GaussMarkov_HH_ #define _GaussMarkov_HH_ #include <string> #include <stdint.h> #include <vector> #include <random> #include <Eigen/Dense> /*! \addtogroup Sim Utility Group * This group contains the simulation utilities that are used globally on the * simulation side of the software. Note that FSW should not generally use * these utilities once we reach a CDR level of maturity on a project. * @{ */ /*! This module is used to apply a second-order bounded Gauss-Markov random walk on top of an upper level process. The intent is that the caller will perform the set methods (setUpperBounds, setNoiseMatrix, setPropMatrix) as often as they need to, call computeNextState, and then call getCurrentState cyclically */ class GaussMarkov { public: GaussMarkov(); GaussMarkov(uint64_t size); ~GaussMarkov(); void computeNextState(); /*!@brief Method does just what it says, seeds the random number generator @param newSeed The seed to use in the random number generator @return void*/ void setRNGSeed(uint64_t newSeed) {rGen.seed((unsigned int)newSeed); RNGSeed = newSeed;} /*!@brief Method returns the current random walk state from model @return The private currentState which is the vector of random walk values*/ Eigen::VectorXd getCurrentState() {return(currentState);} /*!@brief Set the upper bounds on the random walk to newBounds @param newBounds the bounds to put on the random walk states @return void*/ void setUpperBounds(Eigen::VectorXd newBounds){stateBounds = newBounds;} /*!@brief Set the noiseMatrix that is used to define error sigmas @param noise The new value to use for the noiseMatrix variable (error sigmas) @return void*/ void setNoiseMatrix(Eigen::MatrixXd noise){noiseMatrix = noise;} /*!@brief Set the propagation matrix that is used to propagate the state. @param prop The new value for the state propagation matrix @return void*/ void setPropMatrix(Eigen::MatrixXd prop){propMatrix = prop;} Eigen::VectorXd stateBounds; //!< -- Upper bounds to use for markov Eigen::VectorXd currentState; //!< -- State of the markov model Eigen::MatrixXd propMatrix; //!< -- Matrix to propagate error state with Eigen::MatrixXd noiseMatrix; //!< -- covariance matrix to apply errors with private: uint64_t RNGSeed; //!< -- Seed for random number generator std::minstd_rand rGen; //!< -- Random number generator for model std::normal_distribution<double> rNum; //!< -- Random number distribution for model uint64_t numStates; //!< -- Number of states to generate noise for }; /*! @} */ #endif /* _GaussMarkov_HH_ */
true
629f6599106b29a9fd24ec1aa1253f924320d0f1
C++
VinInn/FPOptimization
/OldExercises/limits.cpp
UTF-8
793
3.09375
3
[]
no_license
#include <iostream> // std::cout #include <limits> // std::numeric_limits int main () { std::cout << std::boolalpha; std::cout << "Minimum value: " << std::numeric_limits<float>::min() << '\n'; std::cout << "Maximum value: " << std::numeric_limits<float>::max() << '\n'; std::cout << "Minimum subnormal: " << std::numeric_limits<float>::denorm_min() << '\n'; std::cout << "epsilon: " << std::numeric_limits<float>::epsilon() << '\n'; std::cout << "error: " << std::numeric_limits<float>::round_error() << '\n'; std::cout << "Is signed: " << std::numeric_limits<float>::is_signed << '\n'; std::cout << "Non-sign bits: " << std::numeric_limits<float>::digits << '\n'; std::cout << "has infinity: " << std::numeric_limits<float>::has_infinity << '\n'; return 0; }
true
d3aa9202d859e992deda47bd8d21d64e3f45f1da
C++
beru/imageio
/common/gl/circleDrawer.h
UTF-8
4,307
2.625
3
[]
no_license
#pragma once /* 円描画処理 */ #include "buffer2d.h" double elapsed; namespace gl { template <typename NumericT, typename ColorT, typename ColorBlenderT> class CircleDrawer { public: void DrawCircle(ColorT color, NumericT x, NumericT y, NumericT radius) { NumericT sqrRad = radius * radius; NumericT halfWay = sqrt(sqrRad / 2); int iHalfWay = int(halfWay+0.5); ColorT* pCenter = pBuff_->GetPixelPtr(x, y); int lineOffset = pBuff_->GetLineOffset(); ColorT* curPixel = 0; const NumericT one = OneMinusEpsilon(NumericT(1.0)); { NumericT distance = radius; int iDistance = int(distance); NumericT fraction = frac(distance); NumericT fracRemain = one - fraction; SetPixel(x - iDistance, y, color); SetPixel(x + iDistance, y, color); SetPixel(x, y - iDistance, color); SetPixel(x, y + iDistance, color); } ColorT* curLine = 0; for (size_t i=1; i<=iHalfWay; ++i) { NumericT sqrHeight = i * i; NumericT sqrWidth = sqrRad - sqrHeight; NumericT distance = sqrt(sqrWidth); int iDistance = int(distance); NumericT fraction = frac(distance); NumericT fracRemain = one - fraction; SetPixel(x - iDistance, y - i, color); SetPixel(x + iDistance, y - i, color); SetPixel(x - iDistance, y + i, color); SetPixel(x + iDistance, y + i, color); SetPixel(x - i, y - iDistance, color); SetPixel(x + i, y - iDistance, color); SetPixel(x - i, y + iDistance, color); SetPixel(x + i, y + iDistance, color); } } void DrawCircle_AA(ColorT color, NumericT x, NumericT y, NumericT radius) { NumericT sqrRad = radius * radius; NumericT halfWay = sqrt(sqrRad / 2); int iHalfWay = int(halfWay+0.5); ColorT* pCenter = pBuff_->GetPixelPtr(x, y); int lineOffset = pBuff_->GetLineOffset(); ColorT* curPixel = 0; const NumericT one = OneMinusEpsilon(NumericT(1.0)); { NumericT distance = radius; int iDistance = int(distance); NumericT fraction = frac(distance); NumericT fracRemain = one - fraction; SetPixel(x - iDistance + 0, y, color, fraction); SetPixel(x - iDistance + 1, y, color, fracRemain); SetPixel(x + iDistance - 1, y, color, fracRemain); SetPixel(x + iDistance + 0, y, color, 0.0 + fraction); SetPixel(x, y - iDistance + 0, color, fraction); SetPixel(x, y - iDistance + 1, color, fracRemain); SetPixel(x, y + iDistance - 1, color, fracRemain); SetPixel(x, y + iDistance + 0, color, fraction); } ColorT* curLine = 0; for (size_t i=1; i<=iHalfWay; ++i) { NumericT sqrHeight = i * i; NumericT sqrWidth = sqrRad - sqrHeight; NumericT distance = sqrt(sqrWidth); int iDistance = int(distance); NumericT fraction = frac(distance); NumericT fracRemain = one - fraction; SetPixel(x - iDistance + 0, y - i, color, fraction); SetPixel(x - iDistance + 1, y - i, color, fracRemain); SetPixel(x + iDistance - 1, y - i, color, fracRemain); SetPixel(x + iDistance + 0, y - i, color, 0.0 + fraction); SetPixel(x - iDistance + 0, y + i, color, fraction); SetPixel(x - iDistance + 1, y + i, color, fracRemain); SetPixel(x + iDistance - 1, y + i, color, fracRemain); SetPixel(x + iDistance + 0, y + i, color, fraction); SetPixel(x - i, y - iDistance + 0, color, fraction); SetPixel(x + i, y - iDistance + 0, color, fraction); SetPixel(x - i, y - iDistance + 1, color, fracRemain); SetPixel(x + i, y - iDistance + 1, color, fracRemain); SetPixel(x - i, y + iDistance - 1, color, fracRemain); SetPixel(x + i, y + iDistance - 1, color, fracRemain); SetPixel(x - i, y + iDistance + 0, color, fraction); SetPixel(x + i, y + iDistance + 0, color, fraction); } } void SetPixel(size_t x, size_t y, ColorT c) { if (x < pBuff_->GetWidth() && y < pBuff_->GetHeight()) { pBuff_->SetPixel( x, y, (*pBlender_)(c, pBuff_->GetPixel(x, y)) ); } } void SetPixel(size_t x, size_t y, ColorT c, NumericT a) { if (x < pBuff_->GetWidth() && y < pBuff_->GetHeight()) { pBuff_->SetPixel( x, y, (*pBlender_)(c, a, pBuff_->GetPixel(x, y)) ); } } Buffer2D<ColorT>* pBuff_; ColorBlenderT* pBlender_; }; } // namespace gl {
true
75ee9ef40c53c56b962f257f2ad1b22622d75a6c
C++
michaeleisel/zld
/ld/src/ld/code-sign-blobs/superblob.h
UTF-8
7,777
2.65625
3
[ "MIT", "APSL-2.0" ]
permissive
// // SuperBlob - a typed bag of Blobs // #ifndef _H_SUPERBLOB #define _H_SUPERBLOB #include "blob.h" #include <assert.h> #include <utility> #include <map> #define REPRO #include "MapDefines.h" using namespace std; namespace Security { // // A SuperBlob is a Blob that contains multiple sub-Blobs of varying type. // The SuperBlob is contiguous and contains a directory of its sub-blobs. // A Maker is included. // // SuperBlobCore lets you define your own SuperBlob type. To just use a generic // SuperBlob, use SuperBlob<> below. // template <class _BlobType, uint32_t _magic, class _Type> class SuperBlobCore: public Blob<_BlobType, _magic> { public: class Maker; friend class Maker; typedef _Type Type; // echoes from parent BlobCore (the C++ type system is too restrictive here) typedef BlobCore::Offset Offset; template <class BlobType> BlobType *at(Offset offset) { return BlobCore::at<BlobType>(offset); } template <class BlobType> const BlobType *at(Offset offset) const { return BlobCore::at<BlobType>(offset); } void setup(size_t size, unsigned cnt) { this->initialize(size); this->mCount = cnt; } struct Index { Endian<Type> type; // type of sub-Blob Endian<Offset> offset; // starting offset }; bool validateBlob(size_t maxSize = 0) const; unsigned count() const { return mCount; } // access by index number Type type(unsigned n) const { assert(n < mCount); return mIndex[n].type; } const BlobCore *blob(unsigned n) const { assert(n < mCount); Offset off=mIndex[n].offset; return off ? at<const BlobCore>(off) : NULL; } template <class BlobType> const BlobType *blob(unsigned n) const { return BlobType::specific(blob(n)); } // access by index type (assumes unique types) const BlobCore *find(Type type) const; template <class BlobType> const BlobType *find(Type t) const { return BlobType::specific(find(t)); } private: Endian<uint32_t> mCount; // number of sub-Blobs following Index mIndex[0]; // <count> IndexSlot structures // followed by sub-Blobs, packed and ordered in an undefined way }; template <class _BlobType, uint32_t _magic, class _Type> inline bool SuperBlobCore<_BlobType, _magic, _Type>::validateBlob(size_t maxSize /* = 0 */) const { unsigned cnt = mCount; size_t ixLimit = sizeof(SuperBlobCore) + cnt * sizeof(Index); // end of index vector if (!BlobCore::validateBlob(_magic, ixLimit, maxSize)) return false; for (const Index *ix = mIndex + cnt - 1; ix >= mIndex; ix--) { Offset offset = ix->offset; if ( offset == 0 ) continue; // offset==0 means unused entry if (offset < ixLimit // offset not too small || offset + sizeof(BlobCore) > this->length() // fits Blob header (including length field) || offset + at<const BlobCore>(offset)->length() > this->length()) // fits entire blob return false; } return true; } // // A generic SuperBlob ready for use. You still need to specify a magic number. // template <uint32_t _magic, class _Type = uint32_t> class SuperBlob : public SuperBlobCore<SuperBlob<_magic, _Type>, _magic, _Type> { }; template <class _BlobType, uint32_t _magic, class _Type> const BlobCore *SuperBlobCore<_BlobType, _magic, _Type>::find(Type t) const { for (unsigned slot = 0; slot < mCount; slot++) { if (mIndex[slot].type == t) { uint32_t off = mIndex[slot].offset; if ( off == 0 ) return NULL; else return at<const BlobCore>(off); } } return NULL; // not found } // // A SuperBlob::Maker simply assembles multiple Blobs into a single, indexed // super-blob. Just add() sub-Blobs by type and call build() to get // the result, malloc'ed. A Maker is not reusable. // Maker can repeatedly make SuperBlobs from the same (cached) inputs. // It can also tell you how big its output will be, given established contents // plus (optional) additional sizes of blobs yet to come. // template <class _BlobType, uint32_t _magic, class _Type> class SuperBlobCore<_BlobType, _magic, _Type>::Maker { public: Maker() { } Maker(const Maker &src) { for (typename BlobMap::iterator it = mPieces.begin(); it != mPieces.end(); ++it) mPieces.insert(make_pair(it->first, it->second->clone())); } ~Maker() { for (typename BlobMap::iterator it = mPieces.begin(); it != mPieces.end(); ++it) ::free(it->second); } void add(Type type, BlobCore *blob); // takes ownership of blob void add(const _BlobType *blobs); // copies all blobs void add(const Maker &maker); // ditto size_t size(size_t size1 = 0, ...) const; // size with optional additional blob sizes _BlobType *make() const; // create (malloc) and return SuperBlob _BlobType *operator () () const { return make(); } private: typedef LDOrderedMap<Type, BlobCore *> BlobMap; BlobMap mPieces; }; // // Add a Blob to a SuperBlob::Maker. // This takes ownership of the blob, which must have been malloc'ed. // Any previous value set for this Type will be freed immediately. // template <class _BlobType, uint32_t _magic, class _Type> void SuperBlobCore<_BlobType, _magic, _Type>::Maker::add(Type type, BlobCore *blob) { pair<typename BlobMap::iterator, bool> r = mPieces.insert(make_pair(type, blob)); if (!r.second) { // already there //secdebug("superblob", "Maker %p replaces type=%d", this, type); ::free(r.first->second); r.first->second = blob; } } template <class _BlobType, uint32_t _magic, class _Type> void SuperBlobCore<_BlobType, _magic, _Type>::Maker::add(const _BlobType *blobs) { for (uint32_t ix = 0; ix < blobs->mCount; ix++) this->add(blobs->mIndex[ix].type, blobs->blob(ix)->clone()); } template <class _BlobType, uint32_t _magic, class _Type> void SuperBlobCore<_BlobType, _magic, _Type>::Maker::add(const Maker &maker) { for (typename BlobMap::const_iterator it = maker.mPieces.begin(); it != maker.mPieces.end(); ++it) this->add(it->first, it->second->clone()); } // // Calculate the size the new SuperBlob would have, given the contents of the Maker // so far, plus additional blobs with the sizes given. // template <class _BlobType, uint32_t _magic, class _Type> size_t SuperBlobCore<_BlobType, _magic, _Type>::Maker::size(size_t size1, ...) const { // count established blobs unsigned count = mPieces.size(); size_t total = 0; for (typename BlobMap::const_iterator it = mPieces.begin(); it != mPieces.end(); ++it) { if ( it->second != NULL ) total += (it->second->length() + 3) & (-4); // 4-byte align each element } // add preview blob sizes to calculation (if any) if (size1) { va_list args; va_start(args, size1); do { count++; total += size1; size1 = va_arg(args, size_t); } while (size1); va_end(args); } return sizeof(SuperBlobCore) + count * sizeof(Index) + total; } // // Finish SuperBlob construction and return the new, malloc'ed, SuperBlob. // This can be done repeatedly. // template <class _BlobType, uint32_t _magic, class _Type> _BlobType *SuperBlobCore<_BlobType, _magic, _Type>::Maker::make() const { Offset pc = sizeof(SuperBlobCore) + mPieces.size() * sizeof(Index); Offset total = size(); _BlobType *result = (_BlobType *)calloc(1, total); if (!result) throw ENOMEM; result->setup(total, mPieces.size()); unsigned n = 0; for (typename BlobMap::const_iterator it = mPieces.begin(); it != mPieces.end(); ++it) { result->mIndex[n].type = it->first; BlobCore* b = it->second; if ( b != NULL ) { result->mIndex[n].offset = pc; memcpy(result->template at<unsigned char>(pc), b, b->length()); pc += ((b->length() + 3) & (-4)); // 4-byte align each element } else { result->mIndex[n].offset = 0; } n++; } //secdebug("superblob", "Maker %p assembles %ld blob(s) into %p (size=%d)", // this, mPieces.size(), result, total); return result; } } // Security #endif //_H_SUPERBLOB
true
2a4b3f09c17a2f9be5ab2bf7cfbdf60e2b109836
C++
YEJIN-LILY/HandGestureDetection
/countFinger.cpp
UTF-8
5,018
2.609375
3
[]
no_license
#include <opencv2/core.hpp> #include <opencv2/videoio.hpp> #include <opencv2/highgui.hpp> #include <opencv2/opencv.hpp> #include <opencv2/xfeatures2d.hpp> #include <opencv2/imgproc.hpp> #include <iostream> #include <string> #include <math.h> #include <stdio.h> using namespace cv; using namespace std; #define PI 3.14159265 // HandGestureDetection // 영상을 프레임별로 계속 가져오기 Mat getImage(Mat img); // 피부 검출 및 이진화 Mat skinDetection(Mat img); // 손바닥 검출 Point palmDetectuon(Mat img); // 손가락 개수 세기 void countFinger(Mat img); int main(int argc, char** argv) { Mat image = imread("../../../handtest.jpg",0); resize(image, image, Size(500, 500)); threshold(image, image, 100, 255, THRESH_BINARY); namedWindow("binary hand image"); imshow("binary hand image", image); //image = getImage(image); //image = skinDetection(image); //image = palmDetectuon(image); countFinger(image); cout << "end" << endl; waitKey(0); return 0; } Point palmDetectuon(Mat img) { } void countFinger(Mat img) { Mat dst; img.copyTo(dst); //Mat image = imread("hand.jpg"); //Point center = palmDetectuon(img); // input gray-scale image Point_<double> center((double)dst.size().width/2, (double)dst.size().height/2); cout << "손바닥 중심점 좌표:" << center << endl; //손바닥 중심점 그리기 //circle(img, center, 2, Scalar(0, 255, 0), -1); double radius = 5.0; double x, y; bool stop; while (1) { // 원을 그린다 stop = 0; //circle(img, center, radius, Scalar(255, 0, 0), 1, 8, 0); //imshow("count finger", img); //waitKey(50); //circle(img, center, radius, Scalar(255, 255, 255), 1, 8, 0); //remove //원이 그려진 곳에 검은색 화소가 있는지 검사 for (int theta = 0; theta < 360; theta++) { x = (double)cos(theta * PI / 180) * radius + center.x; y = (double)sin(theta * PI / 180) * radius + center.y; //cout << "(x = " << x << ", y= " << y << ") "; //cout << "value: " << img.at<uchar>(x, y) << endl; if (img.at<uchar>(x,y) == 0) { // 원이 그려진 곳에 검은색 화소가 있다면 stop = 1; break; } } if (stop) { break; } radius++;// 원 반지름 증가 } // 실제 반지름 원 //circle(img, center, radius, Scalar(0, 0, 255), 1, 8, 0); //red // 최종 원 그리기 radius = radius * 1.5; circle(dst, center, radius, Scalar(0, 0, 255), 1, 8, 0); //red cout << "손바닥 중심점 좌표:" << center << ", 반지름:" << radius << endl; namedWindow("draw circle on hand"); imshow("draw circle on hand", dst); // 손가락과 원이 겹치는 부분만 추출 Mat circle_img = Mat::zeros(dst.size().width, dst.size().height, CV_8U); //circle(circle_img, center, radius, Scalar(255, 255, 255), 1, 8, 0); //red for (int theta = 0; theta < 360; theta++) { x = (double)cos(theta * PI / 180) * radius + center.x; y = (double)sin(theta * PI / 180) * radius + center.y; circle_img.at<uchar>(x, y) = 255; // 원이 그려진 곳에 검은색 화소가 있다면 } bitwise_and(img, circle_img, dst); namedWindow("& operate"); imshow("& operate", dst); // 원 둘레를 돌며 손가락 카운트 int pre_x = (double)cos(0 * PI / 180) * radius + center.x; int pre_y = (double)sin(0 * PI / 180) * radius + center.y; int count = 0; Mat test = Mat::zeros(dst.size().width, dst.size().height, CV_8UC1); dst.copyTo(test); cvtColor(dst, test, COLOR_GRAY2BGR); //Point th0(pre_x, pre_y); //circle(test, th0, 3, Scalar(0, 0, 255), 1, 8, 0); //red for (int theta = 1; theta < 360; theta++) { x = (double)cos(theta * PI / 180) * radius + center.x; y = (double)sin(theta * PI / 180) * radius + center.y; //cout << "(x = " << x << ", y= " << y << ") "; //cout << "value: " << img.at<uchar>(x, y) << endl; //if ((img.at<uchar>(pre_x, pre_y) == 0) && (img.at<uchar>(x, y) == 255)) { // 이전 화소와 같이 다르다면 // img.at<uchar>(x, y) = 120; // count++; // //} //if (theta == 90) { // Point th90(x, y); // circle(test, th90, 3, Scalar(0, 255, 0), 1, 8, 0); //green //} //if (theta == 180) { // Point th180(x, y); // circle(test, th180, 3, Scalar(255, 0, 255), 1, 8, 0); //magenta //} //if (theta == 270) { // Point th270(x, y); // circle(test, th270, 3, Scalar(255, 255, 0), 1, 8, 0); //cyan //} printf("t = %d (x, y) = %d \n", theta, dst.at<uchar>(x, y)); if (dst.at<uchar>(pre_x, pre_y) != dst.at<uchar>(x, y)) { // 이전 화소와 값이 다르다면 //printf("---------------------red point (x, y) = (%d, %d) value = %d", x, y, dst.at<uchar>(x, y)); //test.at<Vec3b>(x, y)[2] = 255; Point th(x, y); circle(test, th, 3, Scalar(0, 0, 255), 1, 8, 0); //green //img.at<uchar>(x, y) = 120; count++; } pre_x = x; pre_y = y; imshow("test", test); waitKey(100); } cout << "count: " << count << endl; count = (count / 2) - 1; cout << "손가락 개수: " << count << endl; }
true
604e4bee0f26a981a7ab8a34f10a63b43224bc59
C++
LeatherWang/leetcode_cpp
/2_dfs/486_Predict the Winner/main.cpp
UTF-8
1,144
2.890625
3
[]
no_license
#include <iostream> // std::cout #include <vector> // std::vector #include <algorithm> // std::sort #include <math.h> #include <list> #include <map> #include <unordered_map> #include <unordered_set> #include <memory.h> #include <climits> #include <sstream> #include <set> #include <queue> using namespace std; struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; // 递归表达式:max(nums[beg] - partition(beg + 1, end), nums[end] - partition(beg, end + 1)) int dfs(vector<int>& nums, vector<vector<int>>& midStatus, int begin, int end) { if(begin > end) return 0; if(midStatus[begin][end] != -1) return midStatus[begin][end]; else return midStatus[begin][end] = max(nums[begin]-dfs(nums, midStatus, begin+1, end), nums[end]-dfs(nums, midStatus, begin, end-1)); } bool PredictTheWinner(vector<int>& nums) { vector<vector<int>> midStatus(nums.size(), vector<int>(nums.size(), -1)); if(dfs(nums, midStatus, 0, nums.size()-1) >= 0) return true; return false; } int main() { return 0; }
true
2c529a02bb635be983bf60cd88818e3274093310
C++
sterling757/Intro-to-Algorithms
/Lab 1/SortingAlgorithm.cpp
UTF-8
4,035
3.1875
3
[]
no_license
// // Created by Sterling on 8/26/2018. // #include "SortingAlgorithm.h" #include "BubbleSort.h" #include "InsertionSort.h" #include "MergeSort.h" #include <chrono> SortingAlgorithm::SortingAlgorithm() { } void SortingAlgorithm::Load(string filePath) { string line; ifstream myFile(filePath); if (myFile.is_open()) { while ( getline (myFile,line) ) { rowOfNums.clear(); istringstream is(line); int n; while(is >> n) { rowOfNums.push_back(n); } nums.push_back(rowOfNums); } myFile.close(); } else cout << "Unable to open file"; } void SortingAlgorithm::Execute(int algoId) { if(algoId == 0){ BubbleSort bs; for (int i = 0; i < nums.size(); i++) { auto start = std::chrono::high_resolution_clock::now(); bs.Sort(nums[i]); auto end = std::chrono::high_resolution_clock::now(); auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); int size = nums[i].size(); pair <int,double> p (size,ms); statsStrings.push_back(p); } } else if(algoId == 1){ InsertionSort is; for (int i = 0; i < nums.size(); i++) { auto start = std::chrono::high_resolution_clock::now(); is.Sort(nums[i]); auto end = std::chrono::high_resolution_clock::now(); auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); int size = nums[i].size(); pair <int,double> p (size,ms); //string stat = std::string("Duration for Bubble Sort of Data Set of Size: " + to_string(nums[i].size()) + " = " + duration + " milliseconds"); statsStrings.push_back(p); } } else if(algoId == 2){ MergeSort merge; for (int i = 0; i < nums.size(); i++) { auto start = std::chrono::high_resolution_clock::now(); merge.Sort(nums[i]); auto end = std::chrono::high_resolution_clock::now(); auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count(); int size = nums[i].size(); pair <int,double> p (size,ms); //string stat = std::string("Duration for Bubble Sort of Data Set of Size: " + to_string(nums[i].size()) + " = " + duration + " milliseconds"); statsStrings.push_back(p); } } else cerr << "something went wrong somehow, index out of bounds!" << endl; } void SortingAlgorithm::Display(){ for(int i =0; i < nums.size(); i++){ for (int j = 0; j < nums[i].size(); j++) { cout << nums[i][j] << " "; } cout << '\n'; } } void SortingAlgorithm::Stats(){ //bubble for(int i = 0; i < 16; i++) { cout << string("Duration for Bubble Sort of Data Set of Size: " + to_string(statsStrings[i].first) + " = " + to_string(statsStrings[i].second) + " milliseconds") << endl; } } //When using Select, input 1 void SortingAlgorithm::Select(int algoId){ if(algoId == 0){ typeOfSort = "BUBBLE"; } else if(algoId == 1){ typeOfSort = "INSERTION"; } else if(algoId == 2){ typeOfSort = "MERGE"; } else cerr<< "Algo id out of bounds" << endl; } void SortingAlgorithm::Save(string filePath){ fstream file; vector<int> tempvec; file.open(filePath, fstream::out); for(int i =0; i < nums.size(); i++) { for (int j = 0; j < nums[i].size() ; j++){ file << nums[i][j] << std::endl; } file << std::endl; } file.close(); } void SortingAlgorithm::Configure(){ }
true
4a7616819bf39210f5b0bc907186c1308a25c206
C++
Majesty5/ET-575-C-
/Day 9/05_Branching_Examples/EX_1a_evaluating_true_1.cpp
UTF-8
727
3.890625
4
[]
no_license
// (c) 2018 S. Trowbridge // Ex 1a - evaluating_true_1 #include <iostream> #include <string> using namespace std; int main() { cout << "Boolean Evaluation" << endl; cout << "------------------" << endl; int w = 4, x = 3, y = 2, z = 1; cout << "w = 4\nx = 3\ny = 2\nz = 1\n\n"; cout << "Evaluate (w > x):\t\t" << (w > x) << endl; cout << "Evaluate (y < z):\t\t" << (y < z) << endl << endl; // && operations: true only if both operands are true // || operations: false only if both operands are false cout << "Evaluate (w > x) && (y < z):\t" << ((w > x) && (y < z)) << endl; cout << "Evaluate (w > x) || (y < z):\t" << ((w > x) || (y < z)) << endl; return 0; }
true
0d6945b2799c52725d90e44f7698ef4cbceef884
C++
Ciubix8513/Vulkan-engine
/Math/EngineMath.cpp
UTF-8
5,318
2.8125
3
[]
no_license
#include "EngineMath.h" Matrix4x4 EngineMath::Multiply(Matrix4x4 a, Matrix4x4 b) { return a * b; } Vector4 EngineMath::TransformVector(Vector4 v, Matrix4x4 m) { return m * v; } Matrix4x4 EngineMath::PerspectiveProjectionMatrix(float FOV, float screenAspect, float screenNear, float screenDepth) { float xScale, yScale, C, D; yScale = 1 / (float)tan((FOV * Deg2Rad) / 2); xScale = yScale / screenAspect; C = screenDepth / (screenDepth - screenNear); D = -screenNear * screenDepth / (screenDepth - screenNear); return Matrix4x4( xScale, 0, 0, 0, 0, yScale, 0, 0, 0, 0, C, 1, 0, 0, D, 0); } Matrix4x4 EngineMath::OrthographicProjectionMatrix(float screenWidth, float screenHeight, float screenNear, float screenDepth) { float A, B, C, D, E; A = 2 / screenWidth; B = 2 / screenHeight; C = 1 / (screenDepth - screenNear); D = 1; E = -screenNear / (screenDepth - screenNear); return (Matrix4x4( Vector4(A, 0, 0, 0), Vector4(0, B, 0, 0), Vector4(0, 0, C, 0), Vector4(0, 0, E, D))) ;//* Matrix4x4(-1,0,0,0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 ))* Matrix4x4(1, 0, 0, 0, 0, -1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); } Matrix4x4 EngineMath::Identity() { return Matrix4x4( Vector4(1, 0, 0, 0), Vector4(0, 1, 0, 0), Vector4(0, 0, 1, 0), Vector4(0, 0, 0, 1)); } Matrix4x4 EngineMath::LookAtMatrix(Vector3 Eye, Vector3 At, Vector3 up) { Vector3 zaxis, xaxis, yaxis; zaxis = Normalized(At - Eye ); xaxis = Normalized(zaxis.CrossProdut(up, zaxis)); yaxis = zaxis.CrossProdut(zaxis, xaxis); Matrix4x4 a = Matrix4x4( xaxis.x, yaxis.x, zaxis.x, 0, xaxis.y, yaxis.y, zaxis.y, 0, xaxis.z, yaxis.z, zaxis.z, 0, -(xaxis * Eye), -(yaxis * Eye), -(zaxis * Eye), 1); return a; } Matrix4x4 EngineMath::RotationPitchYawRoll(float P, float Y, float R) // p = x Y = y r = z { float pitch = P * Deg2Rad; float yaw = Y * Deg2Rad; float roll = R * Deg2Rad; Matrix4x4 p, y, r; y = Matrix4x4( (float)cos(yaw), 0, (float)-sin(yaw), 0, 0, 1, 0, 0, (float)sin(yaw), 0, (float)cos(yaw), 0, 0, 0, 0, 1); r = Matrix4x4( (float)cos(roll), (float)sin(roll), 0, 0, (float)-sin(roll), (float)cos(roll), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); p = Matrix4x4( 1, 0, 0, 0, 0, (float)cos(pitch), (float)sin(pitch),0, 0, (float)-sin(pitch), (float)cos(pitch), 0, 0, 0, 0, 1); Matrix4x4 buff = (r.operator*(p)); return buff.operator*(y); } Matrix4x4 EngineMath::RotationPitchYawRoll(Vector3 rpy) { float pitch = rpy.x * Deg2Rad; float yaw = rpy.y * Deg2Rad; float roll = rpy.z * Deg2Rad; Matrix4x4 p, y, r; y = Matrix4x4( (float)cos(yaw), 0, (float)-sin(yaw), 0, 0, 1, 0, 0, (float)sin(yaw), 0, (float)cos(yaw), 0, 0, 0, 0, 1); r = Matrix4x4( (float)cos(roll), (float)sin(roll), 0, 0, (float)-sin(roll), (float)cos(roll), 0, 0, 0, 0, 1, 0, 0, 0, 0, 1); p = Matrix4x4( 1, 0, 0, 0, 0, (float)cos(pitch), (float)sin(pitch), 0, 0, (float)-sin(pitch), (float)cos(pitch), 0, 0, 0, 0, 1); Matrix4x4 buff = (r.operator*(p)); return buff.operator*(y); } //---------------------------------------- Matrix4x4 EngineMath::TransformationMatrix(Vector3 posistion, Vector3 Rotation, Vector3 Scale) { Matrix4x4 scale, translation, rotation; scale = ScaleMatrix(Scale); translation = TranslationMatrix(posistion); rotation = RotationPitchYawRoll(Rotation); auto a = rotation * translation; return (translation * scale) * rotation; } Matrix4x4 EngineMath::TransformationMatrix(Vector3 posistion, Vector3 Rotation, float Scale) { Matrix4x4 scale, translation, rotation; scale = ScaleMatrix(Scale); translation = TranslationMatrix(posistion); rotation = RotationPitchYawRoll(Rotation); auto a = rotation * translation; return (translation * scale) * rotation; } //---------------------------------------- Matrix4x4 EngineMath::TranslationScaleMatrix(Vector3 translation, Vector3 scale) { return TranslationMatrix(translation) * ScaleMatrix(scale); } Matrix4x4 EngineMath::TranslationScaleMatrix(Vector3 translation, float scale) { return TranslationMatrix(translation) * ScaleMatrix(scale); } //---------------------------------------- Matrix4x4 EngineMath::TranslationMatrix(Vector3 translation) { Matrix4x4 a = Identity(); a._m03 = translation.x; a._m13 = translation.y; a._m23 = translation.z; return a; } //---------------------------------------- Matrix4x4 EngineMath::ScaleMatrix(Vector3 scale) { Matrix4x4 a = Identity(); a._m00 = scale.x; a._m11 = scale.y; a._m22 = scale.z; return a; } Matrix4x4 EngineMath::ScaleMatrix(float scale) { Matrix4x4 a = Identity(); a._m00 = scale; a._m11 = scale; a._m22 = scale; return a; } //---------------------------------------- Vector3 EngineMath::Normalized(Vector3 v) { if(v != Vector3(0,0,0)) return v / v.Length(); return Vector3(0, 0, 0); } Matrix4x4 EngineMath::Transpose(Matrix4x4 m) { return m.Transposed(); }
true
b7927882c5d92532c2f97b42d2aca35690bbaaf2
C++
etmo6394/Craft
/Sources/Source/Maths/NoiseGenerator.h
UTF-8
730
2.609375
3
[]
no_license
#ifndef NOISEGENERATOR_H_INCLUDED #define NOISEGENERATOR_H_INCLUDED #include "../Util/Random.h" struct NoiseParameters { int octaves; int amplitude; int smoothness; int heightOffset; double roughness; }; class NoiseGenerator { public: NoiseGenerator(int seed); double getHeight(int x, int z, int chunkX, int chunkZ) const; void setParameters(const NoiseParameters& params); private: double getNoise(int n) const; double getNoise(double x, double z) const; double lerp(double a, double b, double z) const; double noise(double x, double z) const; NoiseParameters m_noiseParameters; int m_seed; }; #endif // NOISEGENERATOR_H_INCLUDED
true
0f84d156643efd07ecb029bfe810afbe448b8ae5
C++
WyattMayfield/SudokuSolver
/NineByNine.h
UTF-8
2,177
3.265625
3
[]
no_license
#pragma once #include <iostream> #include <fstream> using namespace std; const int maxRow = 9; const int maxColumn = 9; class NineByNine { public: void readIn(); int getNineByNine(int r, int c); bool solved(); void insert(int r, int c, int n); void test(); //void insert(int number, int row, int column); void print(); private: int nineByNine[maxRow][maxColumn] = { 0 }; }; void NineByNine::readIn() { ifstream i_s; i_s.open("Test01.txt"); if (!i_s) { cerr << "Unable to open file datafile.txt"; exit(1); // call system to stop } int num; for (int i = 0; i < maxRow; i++) { for (int j = 0; j < maxColumn; j++) { i_s >> num; nineByNine[i][j] = num; } } i_s.close(); } int NineByNine::getNineByNine(int r, int c) { return nineByNine[r][c]; } /*void NineByNine::insert(int n, int r, int c) { nineByNine[r - 1][c - 1] = n; }*/ bool NineByNine::solved() { for (int i = 0; i < maxRow; i++) { for (int j = 0; j < maxColumn; j++) { if (nineByNine[i][j] == 0) { return false; } } } return true; } void NineByNine::print() { for (int i = 0; i < maxRow; i++) { if (i == 0) { cout << "--------------------------------" << endl; cout << "--------------------------------" << endl; } cout << "|| "; for (int j = 0; j < maxColumn; j++) { if (nineByNine[i][j] == 0) { cout << " |"; } else { cout << nineByNine[i][j] << "|"; } if (j == 2 || j == 5 || j == 8) { cout << "| "; } else { cout << " "; } } cout << endl; cout << "--------------------------------" << endl; if (i == 2 || i == 5 || i == 8) { cout << "--------------------------------" << endl; } } } void NineByNine::insert(int r, int c, int n) { nineByNine[r][c] = n; print(); } void NineByNine::test() { int f = 0; do { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { f++; if (getNineByNine(i, j) == 0) { cout << endl << endl; insert(i, j, 1); } } } } while (!solved() && f < 1000); }
true
95997cafbc675f6b4864136923f47a8acb3fd146
C++
Fernandofgs/lista_exercicios_estruturas_e_dados
/exercicios_21_03_2018/exercicios_5.cpp
UTF-8
542
3.09375
3
[]
no_license
//Escreva um programa que declare uma matriz 100x100 de inteiros. Voc? deve inicializar a matriz com //zeros usando ponteiros. Preencha depois a matriz com os numeros de 1 a 10.000 usando ponteiros. #include <stdio.h> #define N 100 main () { int matriz[N][N]; int *p; int i, j, sma = 0; p = &matriz[0][0]; for (i=0; i<N; i++) for (j=0; j<N; j++) { *p = 0; p++; } p = &matriz[0][0]; for (i=0; i<N; i++) for (j=0; j<N; j++) { *p = sma; sma++; p++; } }
true
a6c9967574c3246c0dbaf99a9f57094601337c87
C++
Gh-Story/CodingInterviews
/Offer33.cpp
UTF-8
771
3.234375
3
[]
no_license
#include<iostream> #include<vector> using namespace std; class Solution { public: bool verifyPostorder(vector<int>& postorder) { return dfs(0,postorder.size()-1,postorder); } bool dfs(int i,int j,vector<int> &arr){ if(i>=j)return true; int index = i; while(arr[index]<arr[j])index++; int m = index; while(arr[index]>arr[j])index++; return index==j&&dfs(i,m-1,arr) && dfs(m,j-1,arr); } }; /* 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。 5 / \ 2 6 / \ 1 3 输入: [1,6,3,2,5] 输出: false 输入: [1,3,2,6,5] 输出: true */
true
0b4a5f0fea01b5d122501af0c42305e2d1a08cc3
C++
ScanNet/ScanNet
/CameraParameterEstimation/apps/basics/gfx/param_shapes.h
UTF-8
11,853
2.515625
3
[ "MIT" ]
permissive
#pragma once namespace bsc { /* gpu_asset create_plane( const u32 div_u = 1, const u32 div_v = 1 ); gpu_asset create_cube(); gpu_asset create_sphere( const u32 div_u = 32, const u32 div_v = 32 ); */ void create_extrusion( gpu_geometry * geo, const vec3 * line_points, const i32 n_line_points, const vec2 * shape_points, const i32 n_shape_points, const r32 size, const vec3i * color_map ); }; #ifdef BSC_IMPLEMENTATION namespace bsc { void create_extrusion( gpu_geometry * geo, const vec3 * line_points, const i32 n_line_points, const vec2 * shape_points, const i32 n_shape_points, const r32 size, const vec3i * color_map ) { vec3 *tmp_pos = (vec3 *)malloc(n_shape_points * n_line_points * sizeof(vec3)); vec4 *tmp_col = (vec4 *)malloc(n_line_points * sizeof(vec4)); for (i32 i = 0; i < n_line_points; i++) { // calculate current and next color r32 cur_offset = 8.0f * (r32)i / (r32)n_line_points; i32 col_idx = floor(cur_offset); r32 b = cur_offset - col_idx; r32 a = 1.0 - b; vec3 color_a( color_map[col_idx].r, color_map[col_idx].g, color_map[col_idx].b); vec3 color_b( color_map[col_idx + 1].r, color_map[col_idx + 1].g, color_map[col_idx + 1].b); // figure out the base vec3 point_a = line_points[i]; vec3 point_b, point_c, n1, n2; if (i == n_line_points - 1) { point_c = line_points[i-1]; n2 = point_a - point_c; point_b = point_a - n2; n1 = point_b - point_a; } if (i == 0) { point_b = line_points[i+1]; n1 = point_b - point_a; point_c = point_a - n1; n2 = point_a - point_c; } else { point_b = vec3(line_points[i+1]); point_c = vec3(line_points[i-1]); n1 = point_b - point_a; n2 = point_a - point_c; } vec3 up(0, 1, 0); vec3 u1 = normalize(cross(up, n1)); vec3 u2 = normalize(cross(up, n2)); vec3 u = normalize(u1 + u2); vec3 v = normalize(cross(u, n1)); // with the base we can push any shape really. for ( i32 j = 0 ; j < n_shape_points ; ++j ) { r32 u_mul = shape_points[j].x * size; r32 v_mul = shape_points[j].y * size; tmp_pos[ n_shape_points * i + j ] = point_a + u_mul * u + v_mul * v; } // tmp_pos[4 * i + 0] = point_a + size * v; // tmp_pos[4 * i + 1] = point_a + size * u; // tmp_pos[4 * i + 2] = point_a - size * v; // tmp_pos[4 * i + 3] = point_a - size * u; tmp_col[i] = vec4(a * color_a + b * color_b, 255.0f); } const int n_tri_per_seg = n_shape_points * 2; r32 positions[n_tri_per_seg * 3 * 3 * (n_line_points - 1)]; u8 colors[n_tri_per_seg * 3 * 4 * (n_line_points - 1)]; i32 pos_idx = 0; i32 col_idx = 0; // TODO: Use DrawElements?! for (int i = 0; i < n_line_points - 1; ++i) { i32 ba = n_shape_points * i; i32 bb = n_shape_points * (i + 1); for (int j = 0; j < n_shape_points; ++j) { vec3 cur_pos[6]; vec4 cur_col[6]; cur_pos[0] = tmp_pos[ba + j]; cur_pos[1] = tmp_pos[ba + (j + 1) % n_shape_points]; cur_pos[2] = tmp_pos[bb + j]; cur_pos[3] = tmp_pos[ba + (j + 1) % n_shape_points]; cur_pos[4] = tmp_pos[bb + j]; cur_pos[5] = tmp_pos[bb + (j + 1) % n_shape_points]; cur_col[0] = tmp_col[i]; cur_col[1] = tmp_col[i]; cur_col[2] = tmp_col[i + 1]; cur_col[3] = tmp_col[i]; cur_col[4] = tmp_col[i + 1]; cur_col[5] = tmp_col[i + 1]; r32 *pos_cpy_loc = (r32 *)&(cur_pos[0]); r32 *col_cpy_loc = (r32 *)&(cur_col[0]); for (i32 k = 0; k < 3 * 6; ++k) { positions[pos_idx++] = pos_cpy_loc[k]; } for (i32 k = 0; k < 4 * 6; ++k) { colors[col_idx++] = (u8)col_cpy_loc[k]; } } } bsc::geometry_data extrusion; extrusion.positions = positions; extrusion.colors_a = colors; extrusion.n_vertices = n_tri_per_seg * 3 * (n_line_points - 1); bsc::init_gpu_geo(&extrusion, geo, POSITION | COLOR_A ); free(tmp_pos); free(tmp_col); } /* gpu_asset create_plane( const u32 div_u, const u32 div_v ) { // storage const u32 vert_count = (div_u + 1) * (div_v + 1); const u32 tri_count = 2 * div_u * div_v; r32 positions[ 3 * vert_count ]; r32 texcoords[ 2 * vert_count ]; r32 normals[ 3 * vert_count ]; r32 tangents[ 3 * vert_count ]; u32 indices[ 2 * tri_count ]; // generate vertex data for ( u32 v = 0 ; v < div_v + 1 ; ++v ) { u32 base = v * (div_u + 1); for ( u32 u = 0 ; u < div_u + 1 ; ++u ) { u32 idx = base + u; texcoords[ 2 * idx + 0 ] = (r32)u / div_u; texcoords[ 2 * idx + 1 ] = (r32)v / div_v; positions[ 3 * idx + 0 ] = -0.5f + texcoords[ 2 * idx + 0 ]; positions[ 3 * idx + 1 ] = -0.5f + texcoords[ 2 * idx + 1 ]; positions[ 3 * idx + 2 ] = 0.0f; normals[ 3 * idx + 0 ] = 0.0f; normals[ 3 * idx + 1 ] = 0.0f; normals[ 3 * idx + 2 ] = 1.0f; tangents[ 3 * idx + 0 ] = 0.0f; tangents[ 3 * idx + 1 ] = 1.0f; tangents[ 3 * idx + 2 ] = 0.0f; } } // generate face data int idx = 0; for ( u32 v = 0 ; v < div_v ; ++v ) { u32 row_1 = v * ( div_u + 1 ); u32 row_2 = ( v + 1 ) * ( div_u + 1 ); for ( u32 u = 0 ; u < div_u ; ++u ) { u32 a = row_1 + u; u32 b = row_1 + u + 1; u32 c = row_2 + u; u32 d = row_2 + u + 1; indices[ idx++ ] = a; indices[ idx++ ] = b; indices[ idx++ ] = c; indices[ idx++ ] = c; indices[ idx++ ] = b; indices[ idx++ ] = d; } } // store in a helper structure mesh_data host_plane; host_plane.positions = &(positions[ 0 ]); host_plane.texcoords = &(texcoords[ 0 ]); host_plane.normals = &(normals[ 0 ]); host_plane.tangents = &(tangents[ 0 ]); host_plane.indices = &(indices[ 0 ]); // upload to gpu gpu_asset device_plane; device_plane.vert_count = vert_count; device_plane.tri_count = tri_count; init_gpu_mem( &host_plane, &device_plane ); return device_plane; } gpu_asset create_sphere( const u32 div_u, const u32 div_v ) { // storage const u32 vert_count = (div_u + 1) * (div_v + 1); const u32 tri_count = 2 * div_u * div_v; r32 positions[ 3 * vert_count ]; r32 texcoords[ 2 * vert_count ]; r32 normals[ 3 * vert_count ]; r32 tangents[ 3 * vert_count ]; u32 indices[ 2 * tri_count ]; // generate vertex data for ( u32 v = 0 ; v < div_v + 1 ; ++v ) { u32 base = v * (div_u + 1); for ( u32 u = 0 ; u < div_u + 1 ; ++u ) { u32 idx = base + u; texcoords[ 2 * idx + 0 ] = (r32)u / div_u; texcoords[ 2 * idx + 1 ] = (r32)v / div_v; float phi = texcoords[ 2 * idx + 0 ] * M_PI; float theta = texcoords[ 2 * idx + 1 ] * 2 * M_PI; positions[ 3 * idx + 0 ] = cosf(theta) * sinf(phi); positions[ 3 * idx + 1 ] = sinf(theta) * sinf(phi); positions[ 3 * idx + 2 ] = cosf(phi); tangents[ 3 * idx + 0 ] = cosf(theta + M_PI/2.0f) * sinf(phi); tangents[ 3 * idx + 1 ] = sinf(theta + M_PI/2.0f) * sinf(phi); tangents[ 3 * idx + 2 ] = cosf(phi); normals[ 3 * idx + 0 ] = positions[ 3 * idx + 0 ]; normals[ 3 * idx + 1 ] = positions[ 3 * idx + 1 ]; normals[ 3 * idx + 2 ] = positions[ 3 * idx + 2 ]; } } // generate face data int idx = 0; for ( u32 v = 0 ; v < div_v ; ++v ) { u32 row_1 = v * ( div_u + 1 ); u32 row_2 = ( v + 1 ) * ( div_u + 1 ); for ( u32 u = 0 ; u < div_u ; ++u ) { u32 a = row_1 + u; u32 b = row_1 + u + 1; u32 c = row_2 + u; u32 d = row_2 + u + 1; indices[ idx++ ] = a; indices[ idx++ ] = b; indices[ idx++ ] = c; indices[ idx++ ] = b; indices[ idx++ ] = d; indices[ idx++ ] = c; } } // store in a helper structure mesh_data host_sphere; host_sphere.positions = &(positions[ 0 ]); host_sphere.texcoords = &(texcoords[ 0 ]); host_sphere.normals = &(normals[ 0 ]); host_sphere.tangents = &(tangents[ 0 ]); host_sphere.indices = &(indices[ 0 ]); // upload to gpu gpu_asset device_sphere; device_sphere.vert_count = vert_count; device_sphere.tri_count = tri_count; init_gpu_mem( &host_sphere, &device_sphere ); return device_sphere; } // Possibly it would be better to simply create a function // that creates simple sphere with shared normals, and then add // subdivision function, and unwelding function. // For now this works gpu_asset create_cube() { // // storage const u32 vert_count = 24; const u32 tri_count = 12; r32 positions[ 3 * vert_count ] = { // FRONT -0.5, 0.5, -0.5, // 0 0.5, 0.5, -0.5, // 1 -0.5, 0.5, 0.5, // 2 0.5, 0.5, 0.5, // 3 // BACK -0.5, -0.5, -0.5, // 4 0.5, -0.5, -0.5, // 5 -0.5, -0.5, 0.5, // 6 0.5, -0.5, 0.5, // 7 // LEFT 0.5, 0.5, -0.5, // 8 0.5, -0.5, -0.5, // 9 0.5, 0.5, 0.5, // 10 0.5, -0.5, 0.5, // 11 // RIGHT -0.5, 0.5, -0.5, // 12 -0.5, -0.5, -0.5, // 13 -0.5, 0.5, 0.5, // 14 -0.5, -0.5, 0.5, // 15 // TOP -0.5, 0.5, 0.5, // 16 0.5, 0.5, 0.5, // 17 0.5, -0.5, 0.5, // 18 -0.5, -0.5, 0.5, // 19 // BOTTOM -0.5, 0.5, -0.5, // 20 0.5, 0.5, -0.5, // 21 0.5, -0.5, -0.5, // 22 -0.5, -0.5, -0.5, // 23 }; r32 texcoords[ 2 * vert_count ]; // TODO r32 normals[ 3 * vert_count ] = { // FRONT 0.0, 1.0, 0.0, // 0 0.0, 1.0, 0.0, // 1 0.0, 1.0, 0.0, // 2 0.0, 1.0, 0.0, // 3 // BACK 0.0, -1.0, 0.0, // 4 0.0, -1.0, 0.0, // 5 0.0, -1.0, 0.0, // 6 0.0, -1.0, 0.0, // 7 // LEFT 1.0, 0.0, 0.0, // 8 1.0, 0.0, 0.0, // 9 1.0, 0.0, 0.0, // 10 1.0, 0.0, 0.0, // 11 // RIGHT -1.0, 0.0, 0.0, // 12 -1.0, 0.0, 0.0, // 13 -1.0, 0.0, 0.0, // 14 -1.0, 0.0, 0.0, // 15 // TOP 0.0, 0.0, 1.0, // 16 0.0, 0.0, 1.0, // 17 0.0, 0.0, 1.0, // 18 0.0, 0.0, 1.0, // 19 // BOTTOM 0.0, 0.0, -1.0, // 20 0.0, 0.0, -1.0, // 21 0.0, 0.0, -1.0, // 22 0.0, 0.0, -1.0, // 23 }; r32 tangents[ 3 * vert_count ]; // TODO u32 indices[ 3 * tri_count ] = { 0, 3, 1, 0, 2, 3, // front 5, 6, 4, 5, 7, 6, // back 8, 11, 9, 8, 10, 11, // left 12, 13, 14, 13, 15, 14, // right 16, 18, 17, 16, 19, 18, // top 20, 21, 22, 20, 22, 23 // bottom }; // store in a helper structure mesh_data host_cube; host_cube.positions = &(positions[ 0 ]); host_cube.texcoords = &(texcoords[ 0 ]); host_cube.normals = &(normals[ 0 ]); host_cube.tangents = &(tangents[ 0 ]); host_cube.indices = &(indices[ 0 ]); // // upload to gpu gpu_asset device_cube; device_cube.vert_count = vert_count; device_cube.tri_count = tri_count; init_gpu_mem( &host_cube, &device_cube ); return device_cube; } */ } #endif
true
bb299ad5ee8a9ecf69add9634299866cdc3a548c
C++
GoodByeYesterday/code_practice
/longest_increasing_path_in_matrix.cpp
UTF-8
1,526
2.9375
3
[]
no_license
#include<iostream> #include<fstream> #include<algorithm> #include<functional> #include<vector> #include<sstream> #include<queue> #include<stack> #include<map> #include<set> #include<unordered_set> #include<bitset> #include<unordered_map> using namespace std; #define _debug #ifdef _debug ifstream ifs("test.txt"); #else istream &ifs = cin; #endif class Solution { public: int longestIncreasingPath(vector<vector<int>>& matrix) { if (matrix.empty()) return 0; int row = matrix.size(), col = matrix[0].size(); vector<vector<int>> path(row, vector<int>(col, -1)); int res = 0; for (int i = 0; i < row; ++i){ for (int j = 0; j < col; ++j){ if (path[i][j] == -1) res=max(res,dfs(matrix,path,i,j,row,col,-1)); } } return res; } int dfs(vector<vector<int>>& matrix, vector<vector<int>>& path,int i,int j,int row,int col,int lastVal){ if (i < 0 || i >= row || j < 0 || j >= col) return 0; if (matrix[i][j]>lastVal){ if (path[i][j] != -1) return path[i][j]; int left = dfs(matrix, path, i - 1, j, row, col, matrix[i][j]) + 1; int right = dfs(matrix, path, i +1, j, row, col, matrix[i][j]) + 1; int up = dfs(matrix, path, i, j-1, row, col, matrix[i][j]) + 1; int down = dfs(matrix, path, i, j + 1, row, col, matrix[i][j]) + 1; path[i][j] = max(max(left, right), max(up, down)); return path[i][j]; } return 0; } }; int main(){ vector<vector<int>> iv{ { 3, 4, 5 }, { 3, 2, 6 }, { 2, 2, 1 } }; Solution s; cout<<s.longestIncreasingPath(iv); return 0; }
true
a66c469cf30b1aa01bd9b2944aa84f12d7b4cb70
C++
ech1/Random-Scripts
/C++/23.cpp
UTF-8
279
3.578125
4
[]
no_license
#include <iostream> using namespace std; int add(int,int); int main(){ int num1,num2,sum; cout << "Enter 2 numbers to add: "; cin >> num1 >> num2; sum = add(num1,num2); cout << "Sum = " << sum; return 0; } int add(int a, int b){ int add; add = a + b; return add; }
true
289e68a14d8347d2d0e9eb22e1f37b2163c41fa2
C++
paulkokos/CppReference
/AlgorithmsLibrary/ Non-modifying sequence operations/all_of_any_of_none_of/main.cpp
UTF-8
911
3.46875
3
[ "MIT" ]
permissive
#include <vector> #include <numeric> #include <algorithm> #include <iterator> #include <iostream> #include <functional> int main () { std::vector<int> v(10,2); std::partial_sum(v.cbegin(),v.cend(),v.begin()); std::cout << "Among numbers: "; std::copy(v.cbegin(),v.cend(),std::ostream_iterator<int>(std::cout," ")); std::cout << "\n"; if (std::all_of(v.cbegin(),v.cend(),[](int i) {return i%2 ==0;})) { std::cout << "All numbers are even\n"; } if (std::none_of(v.cbegin(),v.cend(),std::bind(std::modulus<int>(),std::placeholders::_1,2))) { std::cout << "None of them are odd\n"; } struct DivisibleBy { const int d; DivisibleBy(int n) :d(n) {} bool operator() (int n) const {return n%d==0;} }; if (std::any_of(v.cbegin(),v.cend(),DivisibleBy(7))) { std::cout << "At least on number is divisible by 7\n"; } }
true
ce098b78ebfd94c56bf801bd8c7eb95a6dce726d
C++
ullasreddy-chennuri/Interview-Prep-Programs
/Strings/chewbacca_and_number.cpp
UTF-8
335
2.8125
3
[]
no_license
// 999 -> 900 //4545 -> 4444 #include<bits/stdc++.h> using namespace std; int main(){ string s; cin>>s; for(int i=0;i<s.length();i++){ int l =(int)(s[i]-'0'); if(l>=5){ l=9-l; } s[i]=(char)(l+'0'); } if(s.front() == '0'){ s.front() = '9'; } cout<<s<<endl; }
true
0dfd9b4f7f25aac3339c15318b12b8adb869aac3
C++
JamesMCannon/AVID-DAQ-Software
/PostProcessors/Narrowband_C_dev/FIR.cpp
UTF-8
4,984
3.03125
3
[]
no_license
#include "FIR.h" #include <assert.h> FIR::FIR() { m_filterTable = NULL; m_pastSum = NULL; m_filterLength = 0; m_filterOffset = 0; m_decimateLength = 1; m_filterCopy = true; } FIR::FIR(double* filter, int filterLength, int decimateLength, bool copyFilter) { m_filterTable = NULL; m_pastSum = NULL; m_filterLength = 0; m_filterOffset = 0; m_decimateLength = 1; m_filterCopy = true; Create(filter, filterLength, decimateLength, copyFilter); } FIR::~FIR() { Destroy(); } bool FIR::IsCreated() { return(m_filterTable != NULL); } void FIR::Create(double* filter, int filterLength, int decimateLength, bool copyFilter) { int temp; if ((filter == NULL) || (filterLength == 0)) return; if (m_filterTable != NULL) return; // Must call FIR::Destroy before a new // filter can be created. m_filterLength = filterLength; m_decimateLength = decimateLength; m_filterCopy = copyFilter; m_filterOffset = 0; if (m_filterCopy) { m_filterTable = new double[m_filterLength]; if (m_filterTable == NULL) { Destroy(); return; } memcpy(m_filterTable, filter, m_filterLength*sizeof(double)); } else { m_filterTable = filter; } temp = m_filterLength / m_decimateLength + 1; m_pastSum = new double[temp]; if (m_pastSum == NULL) { Destroy(); return; } memset(m_pastSum,0,temp*sizeof(double)); } void FIR::Destroy() { if (m_pastSum != NULL) { delete[] m_pastSum; m_pastSum = NULL; } if (m_filterCopy) { if (m_filterTable != NULL) { delete[] m_filterTable; m_filterTable = NULL; } } else { m_filterTable = NULL; } m_decimateLength = 1; m_filterCopy = true; m_filterLength = 0; m_filterOffset = 0; } double* FIR::GetFilterPointer(int* filterlength) { *filterlength = m_filterLength; return(m_filterTable); } void FIR::Filter(double* output, int* outputLength, double* input, unsigned int inputLength) { unsigned int i,j,index; unsigned int offset1, offset2, offset3; if (m_filterTable == NULL) return; // Must take sum values from the past vector input index = 0; offset1 = (unsigned int)m_filterLength-1; for(i=(unsigned int)m_filterOffset; i<offset1; i+=(unsigned int)m_decimateLength) { output[index] = m_pastSum[index]; offset2 = offset1-i; for(j=0; j<i+1; j++) { output[index] += input[j] * m_filterTable[offset2+j]; } index++; } // Can filter the data from the current input for(; i<inputLength; i+=(unsigned int)m_decimateLength) { output[index] = (double)0.0; offset2 = i-(unsigned int)m_filterLength+1; for(j=0; j<(unsigned int)m_filterLength; j++) { output[index] += input[offset2+j] * m_filterTable[j]; } index++; } m_filterOffset = (int)(i - inputLength); // Fill in the sum vector for next input sequence *outputLength = (int) index; index = 0; offset1 = (unsigned int)m_filterLength-1; offset3 = i; for(i=0; i<offset1; i+=(unsigned int)m_decimateLength) { m_pastSum[index] = (double)0.0; offset2 = offset3-offset1+i; for(j=0; j<offset1-i; j++) { m_pastSum[index] += input[offset2+j] * m_filterTable[j]; } index++; } } void FIR::Filter(float* output, int* outputLength, short* input, unsigned int inputLength) { unsigned int i,j,index; unsigned int offset1, offset2, offset3; double tempdbl; if (m_filterTable == NULL) return; // Must take sum values from the past vector input index = 0; offset1 = (unsigned int)m_filterLength-1; for(i=(unsigned int)m_filterOffset; i<offset1; i+=(unsigned int)m_decimateLength) { tempdbl = m_pastSum[index]; //output[index] = (float)(m_pastSum[index]); offset2 = offset1-i; for(j=0; j<i+1; j++) { tempdbl += ((double)(input[j])) * m_filterTable[offset2+j]; //output[index] += (float)(((double)(input[j])) * m_filterTable[offset2+j]); } output[index] = (float) tempdbl; index++; } // Can filter the data from the current input for(; i<inputLength; i+=(unsigned int)m_decimateLength) { tempdbl = 0.0; //output[index] = (float)0.0; offset2 = i-(unsigned int)m_filterLength+1; for(j=0; j<(unsigned int)m_filterLength; j++) { tempdbl += ((double)(input[offset2+j])) * m_filterTable[j]; //output[index] += (float)(((double)(input[offset2+j])) * m_filterTable[j]); } output[index] = (float) tempdbl; index++; } m_filterOffset = (int)(i - inputLength); // Fill in the sum vector for next input sequence *outputLength = (int) index; index = 0; offset1 = (unsigned int)m_filterLength-1; offset3 = i; for(i=0; i<offset1; i+=(unsigned int)m_decimateLength) { m_pastSum[index] = (double)0.0; offset2 = offset3-offset1+i; for(j=0; j<offset1-i; j++) { m_pastSum[index] += ((double)(input[offset2+j])) * m_filterTable[j]; } index++; } } void FIR::Reset() { int temp = m_filterLength / m_decimateLength + 1; if (m_filterTable == NULL) return; memset(m_pastSum,0,temp*sizeof(double)); m_filterOffset = 0; }
true
eeb7648a25ddb45bd6c426c7df54a21efb1ce9c1
C++
JoergWarthemann/ringbuffer
/RingBuffer.Test/src/getValues.cpp
UTF-8
4,258
3.609375
4
[ "BSL-1.0" ]
permissive
#include "catch.hpp" #include <array> #include "RingBuffer.h" #include <string> TEST_CASE("Get values from the ring buffer", "[get values]") { static const std::size_t sourceSize = 20; static const std::size_t destinationSize = 19; using ValueType = typename std::string; using SourceArrayType = typename std::array<ValueType, sourceSize>; using DestinationArrayType = typename Buffer::RingBuffer<ValueType>; SourceArrayType source { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fivteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty" }; SourceArrayType sourceControl = source; DestinationArrayType destination(destinationSize); REQUIRE(source.size() == sourceSize); SECTION("Get elements from the ring buffer. The count of elements is bigger than the ring buffers capacity.") { destination.insert(source, sourceSize); // Check whether the elements in destination match the elements from the control group. // Also walk over the buffer size which causes giving back elements in ring like manner. for (std::size_t i = 0, iEnd = destinationSize * 2; i < iEnd; ++i) { ValueType element = destination.copy(i); ValueType expected = sourceControl[sourceSize - (i % destinationSize) - 1]; DYNAMIC_SECTION(" The " << i << ". ring element contains the expected data.") { REQUIRE(element == expected); } } } SECTION("Get a block of elements from the ring buffer. The block is bigger than the ring buffers capacity.") { destination.insert(source, sourceSize); const std::size_t blockCount = 4; std::size_t blockSize = static_cast<std::size_t>(round(sourceSize / blockCount)); for (std::size_t i = 1; i <= blockCount; ++i) { std::array<ValueType, destinationSize> output; std::size_t currentBlockSize = i * blockSize; destination.copy(&output[0], currentBlockSize); for (std::size_t j = 0, jEnd = ((currentBlockSize <= destinationSize) ? currentBlockSize : destinationSize); j < jEnd; ++j) { DYNAMIC_SECTION(" The " << j << ". element of the copied block contains the expected data.") { REQUIRE(sourceControl[sourceSize - j - 1] == output[jEnd - j - 1]); } } } } SECTION("Copy various blocks of elements into the ring buffer. Get blocks of elements from the ring buffer and check their data integrity.") { const std::size_t size1 = 5, size2 = 10, size3 = 15; std::vector<ValueType> controlGroup; // Build up a control group that contains the expected elements in the right order at the destinationSize last positions. std::copy(source.begin(), source.begin() + size1, std::back_inserter(controlGroup)); std::copy(source.begin(), source.begin() + size2, std::back_inserter(controlGroup)); std::copy(source.begin(), source.begin() + size3, std::back_inserter(controlGroup)); std::copy(source.begin(), source.begin() + size1, std::back_inserter(controlGroup)); std::copy(source.begin(), source.begin() + size1, std::back_inserter(controlGroup)); std::copy(source.begin(), source.begin() + size2, std::back_inserter(controlGroup)); // Insert blocks of elements into the ring buffer. destination.insert(source, size1); destination.insert(source, size2); destination.insert(source, size3); destination.insert(source, size1); destination.insert(source, size1); destination.insert(source, size2); std::array<std::string, destinationSize> output; destination.copy(&output[0], destinationSize); for (std::size_t i = 0; i < destinationSize; ++i) { DYNAMIC_SECTION(" The " << i << ". element of the copied block contains the expected data.") { REQUIRE(controlGroup[controlGroup.size() - destinationSize + i] == output[i]); } } } }
true
bc6eb3b2c4809fc73ea02ce0a1a5b0c7a0faa942
C++
Alybaev/MathTasks
/Algorithms/Project2/10305.cpp
UTF-8
821
2.765625
3
[]
no_license
#include <bits/stdc++.h> using namespace std; void dfs(vector<vector<int>>& g, std::vector<int>& visited,int u,vector<int>& res) { visited[u] = 1; for(int i = 0; i < g[u].size();i++) { if(not visited[g[u][i]]) { dfs(g,visited,g[u][i],res); } } res.push_back(u); } int main() { int n,m; while(cin >> n >> m and (n != 0 or m != 0)) { int before; int task; vector<vector<int> > g(n); for(int i = 0;i < m;i++) { cin >> before >> task; g[before - 1].push_back(task - 1); } vector<int> visited(n, 0); vector<int> res; for(int i = 0;i < n;i++) { if(not visited[i]) { dfs(g,visited, i,res); } } reverse(res.begin(),res.end()); for(int i = 0;i < res.size();i++) { cout << res[i] + 1<< ((i != res.size() - 1) ? " " : ""); } cout << "\n"; } }
true
d6de828181cf3f0f0bb101c2d1f492f110b75f4f
C++
bogdan-kovalchuk/August-leetcoding-challenge
/day_27.cpp
UTF-8
892
3.171875
3
[]
no_license
#include <iostream> #include <vector> #include <map> using namespace std; class Solution { public: vector<int> findRightInterval(vector<vector<int>> &intervals) { map<int, int> m; vector<int> res; int n = intervals.size(); for (int i = 0; i < n; ++i) m[intervals[i][0]] = i; for (auto in : intervals) { auto itr = m.lower_bound(in[1]); if (itr == m.end()) { res.push_back(-1); } else { res.push_back(itr->second); } } return res; } }; int main() { vector<vector<int>> intervals = {{3, 4}, {2, 3}, {1, 2}}; Solution solution; auto res = solution.findRightInterval(intervals); for (auto r : res) { cout << r << " "; } return 0; }
true
6de6a51be310280b9852cc48a81a244a46f32d01
C++
darkmatter18/Personal-Smartphone-Locating-Becon-Module
/serialToMorse/serialToMorse.ino
UTF-8
7,715
2.65625
3
[]
no_license
//Include Header file #include <LiquidCrystal.h> LiquidCrystal lcd(12, 11, 5, 4, 3, 2); //Declearing lcd pins int pinLED = 9; //Declearing LED pin for Android input int PIN_OUT = 13; //Define the LED Pin for MorseCode #define UNIT_LENGTH 250 //Define unit length in ms const int ST_0 = 0; //waiting Sync word const int ST_1_CMD = 1; //Waiting CMD const int ST_2_LENGTH= 2; //Receiving Length for CMD_03_TEXT const int ST_3_DATA= 3; //Receiving Data for CMD_03_TEXT const byte IGNORE_00 = 0x00; //There Variables are pre-decleared in android side const byte SYNC_WORD = 0xFF; //For Perform a equality cheak; const byte CMD_01_LEDON = 0x01; //This is Led On var const byte CMD_02_LEDOFF= 0x02; //This is Led Off Var const byte CMD_03_TEXT = 0x03; //This var used to receive String int cmdState; //Uses as a var to store incoming operaton int dataIndex; //Used for index data const int MAX_LENGTH = 16; //Decleared Maximum dataLength byte data[MAX_LENGTH]; //Decleared a arrey for receiving data int dataLength; //Used to store the dataLength of Receiving byte char receiveMessage; //Used to convert receivedData to receiveMessage for Morse char arrReceiveMassage[20]; //making an array of receivedmessage int xi; //needed for arrReceiveMassage indexing //Build a struct with the morse code mapping // static const struct{ // const char letter, *code; // } MorseMap[] = // { // //Small letter // { 'a', ".-" },{ 'b', "-..." },{ 'c', "-.-."},{ 'd', "-.." },{ 'e', "." },{ 'f', "..-." },{ 'g', "--." },{ 'h', "...." },{ 'i', ".." }, // { 'j', ".---" },{ 'k', ".-.-" },{ 'l', ".-.." },{ 'm', "--" },{ 'n', "-." },{ 'o', "---" },{ 'p', ".--." },{ 'q', "--.-" }, // { 'r', ".-." },{ 's', "..." },{ 't', "-" },{ 'u', "..-" },{ 'v', "...-" },{ 'w', ".--" },{ 'x', "-..-" },{ 'y', "-.--" },{ 'z', "--.." }, // //Capital Letter // { 'A', ".-" },{ 'B', "-..." },{ 'C', "-.-."},{ 'D', "-.." },{ 'E', "." },{ 'F', "..-." },{ 'G', "--." },{ 'H', "...." },{ 'I', ".." }, // { 'J', ".---" },{ 'K', ".-.-" },{ 'L', ".-.." },{ 'M', "--" },{ 'N', "-." },{ 'O', "---" },{ 'P', ".--." },{ 'Q', "--.-" }, // { 'R', ".-." },{ 'S', "..." },{ 'T', "-" },{ 'U', "..-" },{ 'V', "...-" },{ 'W', ".--" },{ 'X', "-..-" },{ 'Y', "-.--" },{ 'Z', "--.." }, // //space // { ' ', " " }, //Gap between word, seven units // //Numbers // { '1', ".----" },{ '2', "..---" },{ '3', "...--" },{ '4', "....-" },{ '5', "....." },{ '6', "-...." },{ '7', "--..." },{ '8', "---.." }, // { '9', "----." },{ '0', "-----" }, // //Symbols // { '.', "·–·–·–" },{ ',', "--..--" },{ '?', "..--.." },{ '!', "-.-.--" },{ ':', "---..." },{ ';', "-.-.-." },{ '(', "-.--." }, // { ')', "-.--.-" },{ '"', ".-..-." },{ '@', ".--.-." },{ '&', ".-..." }, // }; void setup() { Serial.begin(9600); pinMode(pinLED, OUTPUT); //Assign Android led pin as output pin digitalWrite(pinLED, LOW); //Assign Android led pin as LOW // pinMode( PIN_OUT, OUTPUT ); //Assign Morse led as output pin // digitalWrite( PIN_OUT, LOW ); //Assign Morse led pin as LOW lcd.begin(16, 2); // 16*2 LCD decleared lcd.print("PSLBM"); //Print the Line } void loop(){ xi = 0; //Getting Data via Serial if(Serial.available()){ //Cheak if the serial is available while(Serial.available() > 0){ //If Serial is avaiable, then int byteIn = Serial.read(); //Read data from serial and cmdHandle(byteIn); //Put data one bit by another -using loop } //Unless Serial stop sendind data } // Morse code Execution // String morseWord = encode(arrReceiveMassage); //Gives the LED responce for(int i=0; i<=morseWord.length(); i++){ switch( morseWord[i] ){ case '.': //dit digitalWrite( PIN_OUT, HIGH ); delay( UNIT_LENGTH ); digitalWrite( PIN_OUT, LOW ); delay( UNIT_LENGTH ); break; case '-': //dah digitalWrite( PIN_OUT, HIGH ); delay( UNIT_LENGTH*3 ); digitalWrite( PIN_OUT, LOW ); delay( UNIT_LENGTH ); break; case ' ': //gap delay( UNIT_LENGTH ); } } } //Function that handles all received bytes from phone void cmdHandle(int incomingByte){ //prevent from lost-sync if(incomingByte == SYNC_WORD){ cmdState = ST_1_CMD; return; } if(incomingByte == IGNORE_00){ return; } //Switch for use commend state switch(cmdState){ case ST_1_CMD:{ switch(incomingByte){ case CMD_01_LEDON: digitalWrite(pinLED, HIGH); break; case CMD_02_LEDOFF: digitalWrite(pinLED, LOW); break; case CMD_03_TEXT: for(int i=0; i < MAX_LENGTH; i++){ data[i] = 0; } lcd.setCursor(0, 1); lcd.print(" "); lcd.setCursor(0, 1); cmdState = ST_2_LENGTH; dataIndex = 0; break; default: cmdState = ST_0; } } break; case ST_2_LENGTH:{ dataLength = incomingByte; if(dataLength > MAX_LENGTH){ dataLength = MAX_LENGTH; } cmdState = ST_3_DATA; } break; case ST_3_DATA:{ data[dataIndex] = incomingByte; dataIndex++; Serial.write(incomingByte); lcd.write(incomingByte); receiveMessage = (char)incomingByte; arrReceiveMassage[xi] = receiveMessage; xi++; if(dataIndex==dataLength){ cmdState = ST_0; } } break; } } //Function to endone the String to morse code // String encode(const char *string){ // size_t i, j; // String morseWord = ""; // for( i = 0; string[i]; ++i ){ // for( j = 0; j < sizeof MorseMap / sizeof *MorseMap; ++j ){ // if( toupper(string[i]) == MorseMap[j].letter ){ // morseWord += MorseMap[j].code; // break; // } // } // morseWord += " "; //Add tailing space to seperate the chars // } // return morseWord+" "; // }
true
217bc4fcb0b56fc1388c250f1993dbb4c01d9dd0
C++
Kansukey/piscine_2019
/main_ex01.cpp
UTF-8
1,763
2.75
3
[]
no_license
// // main.cpp for in /home/barrie_j/Piscine/piscine_cpp_d14m/ex00 // // Made by Jean BARRIERE // Login <barrie_j@epitech.net> // // Started on Tue Jan 19 09:57:16 2016 Jean BARRIERE // Last update Tue Jan 19 11:37:53 2016 Jean BARRIERE // #include <iostream> #include "assert.h" #include "Banana.h" #include "Lemon.h" #include "Lime.h" #include "FruitBox.h" #include "LittleHand.h" int main() { FruitBox unsorted(6); FruitBox bananas(2); FruitBox lemons(2); FruitBox limes(1); Lemon lemon1; Lemon lemon2; Banana banana1; Banana banana2; Lime lime1; Lime lime2; Fruit* cur; unsorted.putFruit(&lemon1); unsorted.putFruit(&lemon2); unsorted.putFruit(&banana1); unsorted.putFruit(&banana2); unsorted.putFruit(&lime1); unsorted.putFruit(&lime2); LittleHand::sortFruitBox(unsorted, lemons, bananas, limes); std::cout << "size de unsorted : [expected :1] " << unsorted.nbFruits() << std::endl; while ((cur = unsorted.pickFruit()) != NULL) { std::cout << "unsorted getName : [expected :lime] " << cur->getName() << std::endl; } std::cout << "size de lemons : [expected :2] " << lemons.nbFruits() << std::endl; while ((cur = lemons.pickFruit()) != NULL) { std::cout << "lemons getName : [expected :lemon] " << cur->getName() << std::endl; } std::cout << "size de bananas : [expected :2] " << bananas.nbFruits() << std::endl; while ((cur = bananas.pickFruit()) != NULL) { std::cout << "bananas getName : [expected :banana] " << cur->getName() << std::endl; } std::cout << "size de limes : [expected :1] " << limes.nbFruits() << std::endl; while ((cur = limes.pickFruit()) != NULL) { std::cout << "limes getName : [expected :lime] " << cur->getName() << std::endl; } return 1337; }
true
ae0af1e8096130c70b73883aa295ac432e6251ea
C++
shanewa/coding
/primer/10.27.cpp
UTF-8
510
3.15625
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> #include <list> using namespace std; void uniqxx_copy(const vector<int> &v1, list<int> &v2) { unique_copy(v1.begin(), v1.end(), v2.begin()); } int main() { list<int> v2(4); vector<int> v1 = {1, 2, 2, 3, 4, 1}; uniqxx_copy(v1, v2); for_each(v1.cbegin(), v1.cend(), [&](int i){cout << i << endl;}); cout << "------------------" << endl; for_each(v2.cbegin(), v2.cend(), [&](int i){cout << i << endl;}); }
true
c7a508f00aa72bc87523d4b49aae9e022fc6d3cd
C++
Rinkeeee96/FoxTrot_SA_Engine
/engineFoxtrot/Engine/SceneManager/Objects/Button.cpp
UTF-8
2,464
3.0625
3
[]
no_license
#include "stdafx.h" #include "Button.h" /// @brief Sets the default values /// @param id /// @param _text /// @param _onClick /// @param _spriteObject /// @param _dispatcher Button::Button(int id, ColoredText _text, const function<void(void)> _onClick, shared_ptr<SpriteObject> _spriteObject, EventDispatcher& _dispatcher) : Drawable(id), text(_text), onClick(_onClick), dispatcher{ _dispatcher } { setSize(200, 50); setStatic(true); registerSprite(DEFAULT_STATE, _spriteObject); changeToState(DEFAULT_STATE); dispatcher.setEventCallback<MouseButtonPressed>(BIND_EVENT_FN(Button::isClicked)); dispatcher.setEventCallback<MouseMovedEvent>(BIND_EVENT_FN(Button::mouseOver)); } /// @brief Sets the width and height of the buttons object /// @param width /// @param height void Button::setSize(float width, float height) { setWidth(width); setHeight(height); } /// @brief /// A function to check if a mouse is over a button /// @param event /// The mouse moved event for the mouse position. /// @return bool Button::mouseOver(const Event& event) { auto mouseOverEvent = static_cast<const MouseMovedEvent&>(event); float mousePositionX = mouseOverEvent.getX(); float mousePositionY = mouseOverEvent.getY(); isMouseOver = (mousePositionX >= positionX && mousePositionX <= (positionX + width) && mousePositionY >= (positionY - height) && mousePositionY <= positionY); if (!buttonPressed && isEnabled) { if (isMouseOver && hasHoverSprite) { changeToState(HOVER_STATE); } else { changeToState(DEFAULT_STATE); } } return false; } /// @brief /// A function to handle a mouse click on a button /// @param event /// The mouse pressed event for the mouse type. /// @return bool Button::isClicked(const Event& event) { if (!buttonPressed) { auto mousePressedEvent = static_cast<const MouseButtonPressed&>(event); MouseCode pressedBtn = mousePressedEvent.GetButton(); // TODO expand functionallity, buttons only handle a primary "left click" for now if (isMouseOver && isEnabled && pressedBtn == MouseCode::MOUSE_BTN_LEFT) { onClick(); buttonPressed = true; return true; } } return false; } /// @brief /// A function to register a hover effect over a btn /// @param SpriteObject /// The spriteobject with the hover effect. /// @return void Button::registerHoverSprite(shared_ptr<SpriteObject> spriteObject) { hasHoverSprite = true; Drawable::registerSprite(HOVER_STATE, spriteObject); }
true
d30f30ed6c15d778ad095507f8d429366a9fca3e
C++
liangyourong/BAIDU-IFE
/华为机试整理85道 含源码/38.cpp
UTF-8
1,146
3.375
3
[]
no_license
#include <stdio.h> #include<string.h> #include<stdlib.h> void arithmetic(const char *input, long len, char *output) { char s1[10]; char s2[10]; char s3[10]; int cnt = 0; int len_input=strlen(input); for(int i=0;i<len_input;++i) { if(input[i]==' ') cnt++; } if(cnt!=2) { *output++ = '0'; *output = '\0'; return; } sscanf(input,"%s %s %s",s1,s2,s3); if(strlen(s2)!=1||(s2[0]!='+'&&s2[0]!='-')) { *output++ = '0'; *output = '\0'; return; } int len_s1=strlen(s1); int i=0; for(i=0;i<len_s1;i++) { if(s1[i]<'0'||s1[i]>'9') { *output++ = '0'; *output = '\0'; return; } } int len_s3=strlen(s3); for(i=0;i<len_s3;i++) { if(s3[i]<'0'||s3[i]>'9') { *output++ = '0'; *output = '\0'; return; } } int x = atoi(s1); int y = atoi(s3); if(s2[0]=='+') { int result = x+y; itoa(result,output,10); } else if(s2[0]=='-') { int result = x-y; itoa(result,output,10); } else { *output++ = '0'; *output = '\0'; return; } } void main() { char str[10] = {}; gets(str); char outstr[10]; int len = strlen(str); arithmetic(str,len,outstr); printf("%s\n",outstr); }
true
8e8609f65148a70a995ba731b7066cae6c8079d4
C++
C-OnlineLessonCode/FactoryMethod
/Practice.cpp
UTF-8
871
3.40625
3
[]
no_license
#include <iostream> #include <fstream> #include <windows.h> class ICar { public: virtual ~ICar() {} virtual int GetEngineVolume() const = 0; }; class BmwX3 : public ICar { public: int GetEngineVolume() const { return 3; } }; class BmwX5 : public ICar { public: int GetEngineVolume() const { return 4; } }; std::shared_ptr<ICar> CreateCar(int expectedEngineVolume) { if (expectedEngineVolume == 3) { return std::make_shared<BmwX3>(); } else if (expectedEngineVolume == 4) { return std::make_shared<BmwX5>(); } else { throw std::runtime_error("Can't produce the car with expected engine volume"); } } void ShowCarInfo(std::shared_ptr<ICar> car) { std::cout << car->GetEngineVolume(); } int main() { std::shared_ptr<ICar> car = CreateCar(4); ShowCarInfo(car); /* Factory method */ }
true
90815b48c3d6573fab647654a28d2d4d00bb8087
C++
cramaechi/char-counter
/main.cpp
UTF-8
545
3.84375
4
[]
no_license
//Program uses a class called CounterType to count characters read in. #include <iostream> #include <cstdlib> #include "countertype.h" using namespace std; int main() { CounterType counter; counter.setCount(0); cout<<"Please write a random statement: "; char c; do { cin>>c; counter.incrementCount(); }while (cin.peek() != '\n'); cout<<endl; cout<<"The CounterType object recorded "<<counter.getCount()<<" characters"; cout<<" typed."<<endl; return 0; }
true
bcac649cefc634199f43ef66eeafecd804937524
C++
sumeshthakr/Raytracer-CG
/ray.h
UTF-8
440
3.296875
3
[]
no_license
#pragma once #include "vec3.h" /* Class Definition for Ray object */ class Ray { public: Vec3 origin; Vec3 direction; Ray() {} Ray(const Vec3& o, const Vec3& d) { origin = o; direction = d; } Vec3 getOrigin() const { return origin; } Vec3 getDirection() const { return direction; } Vec3 getPoint(float t) const { return origin + t*direction; } };
true
49e2e7b465d6a0a0f9396417a448704d6b05291b
C++
thomazthz/programming-challenges
/SpojBR/2838_brincadeira-das-tentativas.cpp
UTF-8
614
2.75
3
[]
no_license
#include <iostream> #include <algorithm> #include <vector> using namespace std; int main(int argc, char const *argv[]) { const int MAX_FIG = 8; int n, i, figurinha; while(cin >> n && n != 0){ vector<int> figurinhas; for(i=0; i<n; i++){ cin >> figurinha; figurinhas.push_back(figurinha); } sort(figurinhas.begin(), figurinhas.end()); do{ for(vector<int>::iterator it = figurinhas.begin(); it != figurinhas.end()-1; it++){ cout << *it << ' '; } cout << figurinhas.back() << '\n'; }while(next_permutation(figurinhas.begin(), figurinhas.end())); cout << '\n'; } return 0; }
true
45b3223eb4776e7cc14c306dfb41d2e5da861295
C++
Pherndogg13/CIS2013_Week10_Lab
/person.cpp
UTF-8
570
3.453125
3
[]
no_license
#include <string> using namespace std; class person { private: string name; string gender; int age; string race; bool is_alive; public: string getName(){return name; } string getGender() {return gender; } int getAge() {return age; } string getRace() {return race; } bool getAlive() {return is_alive; } void setName(string n){ name = n; } void setGender(string g){ gender = g; } void setAge(int a){ age = a; } void setRace(string r){ race = r; } void setAlive(bool a){ is_alive = a; } };
true
a6db22aab1fa95d6cd509b6279e4c5d07e902b8d
C++
KyloRilo/C-Projects
/Lab3/Lab3/Lab3.cpp
UTF-8
1,405
3.796875
4
[]
no_license
/* Kyle Riley SE114.21 October 26th */ #include <iostream> #include <iomanip> using namespace std; void main() { int bigMac=563,bigNum,mFries=378,mNum,sShake=580,sNum; double timeRun, timeJog,burnRun=557,burnJog=398; double cost, money, change; int x; cout << " Which part are you testing? (1/2)" << endl; cin >> x; switch(x) { case 1: //Part I cout << "How many Big Macs have you eaten?" << endl; cin >> bigNum; cout << "How many Medium fries have you eaten?" << endl; cin >> mNum; cout << "How many small shakes have you drank?" << endl; cin >> sNum; timeRun = ((bigMac * bigNum) + (mFries * mNum) + (sShake * sNum))/burnRun; timeJog = ((bigMac * bigNum) + (mFries * mNum) + (sShake * sNum))/burnJog; cout << "If you ran, it would take " << timeRun << " hours to burn these calories. If you jogged, it would take " << timeJog << " hours." << endl; system("pause"); break; case 2: //Part 2 cout << fixed << setprecision(2); cout << "How much does the item cost?" << endl; cin >> cost; cout << "How much are you paying with?" << endl; cin >> money; if (money<cost) cout << "You do not have enough money" << endl; else { change = money - cost; cout << "You will get $" << change << endl; } system("pause"); break; } } /* A1: double amount=4.56,cost=3.2,total=0; A2: It is not because grand_total must be stated before the math. A3: CIN */
true
7ae127ca49f7de9d08e33e59f7e2f664fc80dc56
C++
Lev1ty/mattes-image-registration-1
/CHECK/CHECK.h
UTF-8
1,023
3.0625
3
[ "MIT" ]
permissive
#pragma once #include <exception> #include <iostream> #include <string> namespace reg { /// \struct CHECK /// \brief error checking class /// \details avoid exceptions because they cause undefined behavior; rather, use /// detailed reporting /// \note every class should directly or indirectly be derived from this class /// \param T the base type to monitor template <typename T> struct CHECK { protected: void NULLPTR_ERROR(T *t, std::string &&msg = "NULLPTR_ERROR") const noexcept { if (t == nullptr) std::cerr << "Error: " << std::forward<std::string>(msg) << std::endl; } void NULLPTR_NOTE(T *t, std::string &&msg = "NULLPTR_NOTE") const noexcept { if (t == nullptr) std::cout << "Note: " << std::forward<std::string>(msg) << std::endl; } void NULLPTR_WARNING(T *t, std::string &&msg = "NULLPTR_WARNING") const noexcept { if (t == nullptr) std::cerr << "Warning: " << std::forward<std::string>(msg) << std::endl; } }; } // namespace reg
true
cfdfb2c4b68883a565005a7db33d2bf0b58a9485
C++
caisan/work_code
/verify_bucket_policy.cc
UTF-8
9,594
2.609375
3
[]
no_license
#include <iostream> #include <cstring> #include <stdio.h> #include <stdlib.h> #include <list> #include <algorithm> #include <string> using namespace std; #define MAX_REFERER_DOMAIN_LENGTH 1024 int FindingString(const char* lpszSour, const char* lpszFind, int nStart /* = 0 */) { // ASSERT(lpszSour && lpszFind && nStart >= 0); if(lpszSour == NULL || lpszFind == NULL || nStart < 0) return -1; int m = strlen(lpszSour); int n = strlen(lpszFind); if( nStart+n > m ) return -1; if(n == 0) return nStart; //KMP算法 int* next = new int[n]; //得到查找字符串的next数组 { n--; int j, k; j = 0; k = -1; next[0] = -1; while(j < n) { if(k == -1 || lpszFind[k] == '?' || lpszFind[j] == lpszFind[k]) { j++; k++; next[j] = k; } else k = next[k]; } n++; } int i = nStart, j = 0; while(i < m && j < n) { if(j == -1 || lpszFind[j] == '?' || lpszSour[i] == lpszFind[j]) { i++; j++; } else j = next[j]; } delete []next; if(j >= n) return i-n; else return -1; } /*lpszMatch:pattern*/ bool match_string(const char* lpszSour, const char* lpszMatch, bool bMatchCase /* = true */) { // ASSERT(AfxIsValidString(lpszSour) && AfxIsValidString(lpszMatch)); if(lpszSour == NULL || lpszMatch == NULL) return false; if(lpszMatch[0] == 0)//Is a empty string { if(lpszSour[0] == 0) return true; else return false; } int i = 0, j = 0; //生成比较用临时源字符串'szSource' char* szSource = new char[ (j = strlen(lpszSour)+1) ]; if( bMatchCase ) { //memcpy(szSource, lpszSour, j); while( *(szSource+i) = *(lpszSour+i++) ); } else { //Lowercase 'lpszSour' to 'szSource' i = 0; while(lpszSour[i]) { if(lpszSour[i] >= 'A' && lpszSour[i] <= 'Z') szSource[i] = lpszSour[i] - 'A' + 'a'; else szSource[i] = lpszSour[i]; i++; } szSource[i] = 0; } //生成比较用临时匹配字符串'szMatcher' char* szMatcher = new char[strlen(lpszMatch)+1]; //把lpszMatch里面连续的“*”并成一个“*”后复制到szMatcher中 i = j = 0; while(lpszMatch[i]) { szMatcher[j++] = (!bMatchCase) ? ( (lpszMatch[i] >= 'A' && lpszMatch[i] <= 'Z') ?//Lowercase lpszMatch[i] to szMatcher[j] lpszMatch[i] - 'A' + 'a' : lpszMatch[i] ) : lpszMatch[i]; //Copy lpszMatch[i] to szMatcher[j] //Merge '*' if(lpszMatch[i] == '*') while(lpszMatch[++i] == '*'); else i++; } szMatcher[j] = 0; //开始进行匹配检查 int nMatchOffset, nSourOffset; bool bIsMatched = true; nMatchOffset = nSourOffset = 0; while(szMatcher[nMatchOffset]) { if(szMatcher[nMatchOffset] == '*') { if(szMatcher[nMatchOffset+1] == 0) { //szMatcher[nMatchOffset]是最后一个字符 bIsMatched = true; break; } else { //szMatcher[nMatchOffset+1]只能是'?'或普通字符 int nSubOffset = nMatchOffset+1; while(szMatcher[nSubOffset]) { if(szMatcher[nSubOffset] == '*') break; nSubOffset++; } if( strlen(szSource+nSourOffset) < size_t(nSubOffset-nMatchOffset-1) ) { //源字符串剩下的长度小于匹配串剩下要求长度 bIsMatched = false; //判定不匹配 break; //退出 } if(!szMatcher[nSubOffset])//nSubOffset is point to ender of 'szMatcher' { //检查剩下部分字符是否一一匹配 nSubOffset--; int nTempSourOffset = strlen(szSource)-1; //从后向前进行匹配 while(szMatcher[nSubOffset] != '*') { if(szMatcher[nSubOffset] == '?') ; else { if(szMatcher[nSubOffset] != szSource[nTempSourOffset]) { bIsMatched = false; break; } } nSubOffset--; nTempSourOffset--; } break; } else//szMatcher[nSubOffset] == '*' { nSubOffset -= nMatchOffset; char* szTempFinder = new char[nSubOffset]; nSubOffset--; memcpy(szTempFinder, szMatcher+nMatchOffset+1, nSubOffset); szTempFinder[nSubOffset] = 0; int nPos = ::FindingString(szSource+nSourOffset, szTempFinder, 0); delete []szTempFinder; if(nPos != -1)//在'szSource+nSourOffset'中找到szTempFinder { nMatchOffset += nSubOffset; nSourOffset += (nPos+nSubOffset-1); } else { bIsMatched = false; break; } } } } //end of "if(szMatcher[nMatchOffset] == '*')" else if(szMatcher[nMatchOffset] == '?') { if(!szSource[nSourOffset]) { bIsMatched = false; break; } if(!szMatcher[nMatchOffset+1] && szSource[nSourOffset+1]) { //如果szMatcher[nMatchOffset]是最后一个字符, //且szSource[nSourOffset]不是最后一个字符 bIsMatched = false; break; } nMatchOffset++; nSourOffset++; } else//szMatcher[nMatchOffset]为常规字符 { if(szSource[nSourOffset] != szMatcher[nMatchOffset]) { bIsMatched = false; break; } if(!szMatcher[nMatchOffset+1] && szSource[nSourOffset+1]) { bIsMatched = false; break; } nMatchOffset++; nSourOffset++; } } delete []szSource; delete []szMatcher; return bIsMatched; } bool if_in(bool array[], unsigned long length) { for(int i=0;i<(int)length;i++) if(array[i] == true) return true; return false; } int is_same_conf(list<string> whitelist, list<string> blacklist) { whitelist.sort(); blacklist.sort(); list<string> result; std::set_intersection( whitelist.begin(),whitelist.end(), blacklist.begin(),blacklist.end(), std::inserter(result, result.end())); if (result.size() == 0 ) return -1;//No intersection; else if (result.size() > 0) return 1;//intersection; } int wildcard_intersection(list<string> whitelist, list<string> blacklist) { } bool if_match_referer(const char*match_domain, list<string> referer) { bool match_result[referer.size()]; memset(match_result, 0, referer.size()*sizeof(bool)); unsigned long i =0; list<string>::iterator iter; iter = find(referer.begin(), referer.end(), match_domain); if (iter != referer.end()) { return true; } else /*if (iter == referer.end())*/ { /*wildcard*/ for(iter=referer.begin();iter!=referer.end()&&i<referer.size();++iter,i++) match_result[i] = match_string( match_domain, (*iter).c_str(), true ); bool if_match = if_in(match_result, referer.size()); for(int j=0;j<(int)i;j++) { cout<<"match_result: \n"<<match_result[j]<<endl; } if (!if_match) { return false; } else return true; } } const char* get_domain(string http_header_referer) { const char* patterns[] = {"http://","https://", NULL}; const char* const url = http_header_referer.c_str(); char* domain = (char*)malloc(sizeof(char)*MAX_REFERER_DOMAIN_LENGTH); int j=0; size_t start = 0; for(int i=0; patterns[i]; i++) { if( strncmp( url, patterns[i], strlen( patterns[i] ) ) == 0 ) start = strlen(patterns[i]); } for(int i=start;url[i]!='/'&&url[i]!='\0';i++,j++) domain[j] = url[i]; domain[j] = '\0'; const char* match_domain = domain; return domain; } int verify_referer(string header_referer, list<string> b_list, list<string> w_list) { bool in_white_list, in_black_list; list<string>::iterator iter; const char* domain = get_domain(header_referer); list<string> black_list = b_list; list<string> white_list = w_list; in_white_list = if_match_referer( domain, white_list ); in_black_list = if_match_referer( domain, black_list ); /*if whitelist and blacklist are same*/ if (is_same_conf(white_list, black_list) > 0) { if (in_white_list) return 0; else return -1; } if( !white_list.empty() && !black_list.empty() ) { if( in_white_list && !in_black_list ) { cout<<"----> in_white_list, Not in_black_list"<<endl; return 0; } else if (!in_white_list && in_black_list) { cout<<"----> Not in_white_list, in black_list"<<endl; return -1; } else if(in_white_list && in_black_list) { iter = find(black_list.begin(), black_list.end(), domain); if (iter!=black_list.end()) return -1; else return 0; } } if (!white_list.empty() && black_list.empty()) { if (in_white_list) return 0; else return -1; } if (white_list.empty() && black_list.empty()) return 0; else if (white_list.empty() && !black_list.empty()) { if (in_black_list) return -1; else return 0; } } int main() { /* list<string> wlist = {"www.baidu.com"}; list<string> blist = {"www.baidu.com"}; */ /* list<string> wlist = {"www.baidu.com", "www.eayun.com"}; list<string> blist = {"www.baidu.com"}; */ list<string> wlist = {"www.baidu.com", "www.eayun.*"}; list<string> blist = {"www.baidu.*"}; string referer = "http://www.eayun.com"; /* * -1;deny * 0:allow * */ int result = verify_referer(referer,blist,wlist); if (result<0) cout<<"deny"<<endl; else if (result==0) cout<<"allow"<<endl; return 0; }
true
cddf3839e7b30a03c17642c6aaa3acc29cb2ff88
C++
thegamer1907/Code_Analysis
/DP/1774.cpp
UTF-8
1,649
3.109375
3
[]
no_license
#include <iostream> using std::cin; using std::cout; const int limit = 100000; char s[limit]; bool findAB(char a, char b) { return (a == 'A' && b == 'B'); } bool findBA(char a, char b) { return (a == 'B' && b == 'A'); } int main() { cin >> s; int i = 0; bool gotab = false; bool gotba = false; while(s[i] != 0) { if (i+1 != limit) { if (!gotab && findAB(s[i], s[i+1])) { gotab = true; i+=2; continue; } if(gotab && !gotba && findBA(s[i], s[i+1])) { gotba = true; i+=2; continue; } } i++; } if (gotab && gotba) { cout << "YES"; return 0; } gotab = gotba = i = 0; while(s[i] != 0) { if (i+1 != limit) { if(!gotba && findBA(s[i], s[i+1])) { gotba = true; i+=2; continue; } if (gotba && !gotab && findAB(s[i], s[i+1])) { gotab = true; i+=2; continue; } } i++; } if (gotab && gotba) { cout << "YES"; return 0; } cout << "NO"; return 0; }
true
f46f7aa806d6df72a6d7a96842a58b7930b6b758
C++
ocirne23/GLEngine
/Engine/Graphics/Private/Frustum.ixx
UTF-8
3,635
2.78125
3
[]
no_license
#pragma once #include "Core.h" export module Graphics.Frustum; class PerspectiveCamera; enum FrustumPlane { FRUSTUM_PLANE_NEAR = 0, FRUSTUM_PLANE_FAR = 1, FRUSTUM_PLANE_LEFT = 2, FRUSTUM_PLANE_RIGHT = 3, FRUSTUM_PLANE_TOP = 4, FRUSTUM_PLANE_BOTTOM = 5 }; export class Frustum { public: Frustum() {} ~Frustum() {} Frustum(const Frustum& copy) = delete; /* void calculateFrustum(const glm::mat4& vpMatrix) { glm::mat4 mat = glm::transpose(vpMatrix); m_planes[FRUSTUM_PLANE_LEFT].normal.x = mat[3][0] + mat[0][0]; m_planes[FRUSTUM_PLANE_LEFT].normal.y = mat[3][1] + mat[0][1]; m_planes[FRUSTUM_PLANE_LEFT].normal.z = mat[3][2] + mat[0][2]; m_planes[FRUSTUM_PLANE_LEFT].d = mat[3][3] + mat[0][3]; m_planes[FRUSTUM_PLANE_RIGHT].normal.x = mat[3][0] - mat[0][0]; m_planes[FRUSTUM_PLANE_RIGHT].normal.y = mat[3][1] - mat[0][1]; m_planes[FRUSTUM_PLANE_RIGHT].normal.z = mat[3][2] - mat[0][2]; m_planes[FRUSTUM_PLANE_RIGHT].d = mat[3][3] - mat[0][3]; m_planes[FRUSTUM_PLANE_TOP].normal.x = mat[3][0] - mat[1][0]; m_planes[FRUSTUM_PLANE_TOP].normal.y = mat[3][1] - mat[1][1]; m_planes[FRUSTUM_PLANE_TOP].normal.z = mat[3][2] - mat[1][2]; m_planes[FRUSTUM_PLANE_TOP].d = mat[3][3] - mat[1][3]; m_planes[FRUSTUM_PLANE_BOTTOM].normal.x = mat[3][0] + mat[1][0]; m_planes[FRUSTUM_PLANE_BOTTOM].normal.y = mat[3][1] + mat[1][1]; m_planes[FRUSTUM_PLANE_BOTTOM].normal.z = mat[3][2] + mat[1][2]; m_planes[FRUSTUM_PLANE_BOTTOM].d = mat[3][3] + mat[1][3]; m_planes[FRUSTUM_PLANE_NEAR].normal.x = mat[3][0] + mat[2][0]; m_planes[FRUSTUM_PLANE_NEAR].normal.y = mat[3][1] + mat[2][1]; m_planes[FRUSTUM_PLANE_NEAR].normal.z = mat[3][2] + mat[2][2]; m_planes[FRUSTUM_PLANE_NEAR].d = mat[3][3] + mat[2][3]; m_planes[FRUSTUM_PLANE_FAR].normal.x = mat[3][0] - mat[2][0]; m_planes[FRUSTUM_PLANE_FAR].normal.y = mat[3][1] - mat[2][1]; m_planes[FRUSTUM_PLANE_FAR].normal.z = mat[3][2] - mat[2][2]; m_planes[FRUSTUM_PLANE_FAR].d = mat[3][3] - mat[2][3]; // Renormalise any normals which were not unit length for (int i = 0; i < 6; i++) { float length = glm::length(m_planes[i].normal); m_planes[i].normal /= length; m_planes[i].d /= length; } } bool pointInFrustum(const glm::vec3& point) const { for (int p = 0; p < 6; p++) if (m_planes[p].getSide(point) == Plane::Side::NEGATIVE) return false; return true; } bool sphereInFrustum(const glm::vec3& point, float radius) const { for (int p = 0; p < 6; p++) if (m_planes[p].getDistance(point) < -radius) return false; return true; } bool aabbInFrustum(const glm::vec3& center, const glm::vec3& halfSize) const { for (uint plane = 0; plane < 6; ++plane) if (m_planes[plane].getSide(center, halfSize) == Plane::Side::NEGATIVE) return false; return true; } private: class Plane { public: enum class Side { POSITIVE, NEGATIVE, BOTH }; public: float getDistance(const glm::vec3& a_point) const { return glm::dot(normal, a_point) + d; } Side getSide(const glm::vec3& a_point) const { float distance = getDistance(a_point); return distance < 0.0f ? Side::NEGATIVE : Side::POSITIVE; } Side getSide(const glm::vec3& a_centre, const glm::vec3& a_halfSize) const { float dist = getDistance(a_centre); float maxAbsDist = glm::abs(normal.x * a_halfSize.x) + glm::abs(normal.y * a_halfSize.y) + glm::abs(normal.z * a_halfSize.z); if (dist < -maxAbsDist) return Side::NEGATIVE; if (dist > +maxAbsDist) return Side::POSITIVE; return Side::BOTH; } public: glm::vec3 normal; float d; }; Plane m_planes[6]; */ };
true
52360fda1cf1ce3ef01984a25562855eb229be13
C++
Fija/Leetcode
/SingleNumber/Single.cpp
UTF-8
472
3.03125
3
[ "Apache-2.0" ]
permissive
#include <iostream> using namespace std; int main (int argc, char * const argv[]) { // insert code here... class Solution{ public: int singleNumber(int A[], int n) { int val,i; for (val=0,i=0;i<n;i++) { val = val ^ A[i]; } return val; } }; Solution sol; int A[5] = {1,1,2,3,3}; cout<<sol.singleNumber(A,5); return 0; }
true
7a6747be9740df70cd9bfb164a94e55de5c886ec
C++
landsrover/MyCodilityExamples
/Counting Elements/MissingInteger2.cpp
UTF-8
551
2.984375
3
[]
no_license
// you can use includes, for example: // #include <algorithm> // you can write to stdout for debugging purposes, e.g. // cout << "this is a debug message" << endl; int solution(vector<int> &A) { // write your code in C++14 (g++ 6.2.0) int res = 0; vector<int> PosV((int)A.size()+2,0); for (auto i: A){ if (i>0 && i< (int)PosV.size()){ PosV[i]++; } } for (unsigned int i=1; i< PosV.size(); i++){ if (PosV[i] == 0){ res = i; break; } } return res; }
true
306eed952ae00c02cefefa085af1d8c4f728d03e
C++
jonasspinner/weighted-f-free-edge-editing
/src/search_strategy/Exponential.h
UTF-8
3,817
2.96875
3
[ "MIT" ]
permissive
// // Created by jonas on 27.02.20. // #ifndef WEIGHTED_F_FREE_EDGE_EDITING_EXPONENTIAL_H #define WEIGHTED_F_FREE_EDGE_EDITING_EXPONENTIAL_H #include <deque> #include <cmath> #include <cassert> #include <algorithm> #include "SearchStrategyI.h" /** * From initial implementation as method: * * This search strategy makes the assumption that the number of calls grows exponentially with the parameter k. * We want to increment the paramter k in such a way that each step the number of calls doubles. If we can achieve * that, then the overall amount of work (=number of calls) is dominated by the last step. * * We try to estimate the relationship between k and the number of calls and fit a log linear model with the * information of the last calls (max_history_length). * * In early steps with not enough information the result of the model is very unstable. We fix that by clamping the * size of the step between search_delta estimate (quantile) and a multiple of the last step size (max_step_factor). * * TODO: Add clamping. */ class Exponential : public SearchStrategyI { std::deque<Cost> m_cost_history; std::deque<size_t> m_num_calls_history; size_t m_max_history_size; double m_targeted_growth_factor; public: void set_initial_search_k(Cost initial_search_k) override { push_history(initial_search_k); } std::optional<Cost> get_next_search_k() override { Cost next_search_k = find_next_k(m_cost_history, m_num_calls_history, m_targeted_growth_factor); push_history(next_search_k); return next_search_k; } void register_call(Cost /*k*/) override { assert(!m_num_calls_history.empty()); ++m_num_calls_history.back(); } void register_bound(Cost /*k*/, Cost /*lower_bound_k*/) override {} private: void push_history(Cost k) { if (m_cost_history.size() == m_max_history_size) { m_cost_history.pop_front(); m_num_calls_history.pop_front(); } m_cost_history.push_back(k); m_num_calls_history.push_back(0); } static Cost find_next_k(const std::deque<Cost> &ks, const std::deque<size_t> &calls, double factor) { // Convert ks to double std::vector<double> xs(ks.begin(), ks.end()); // Convert calls to double and apply log-transform std::vector<double> ys; std::transform(calls.begin(), calls.end(), std::back_inserter(ys), [](size_t c) { return std::log(static_cast<double>(c)); }); const auto[alpha, beta] = solve_linear_regression(xs, ys); double next_num_calls = std::log(factor * calls.back()); double next_x = (next_num_calls - alpha) / beta; return std::ceil(next_x); } /** * Solves linear regression model of the form * * y ~ alpha + beta * x * * for alpha and beta. * * References: * [1] https://en.wikipedia.org/wiki/Simple_linear_regression * * @param xs * @param ys * @return */ static std::pair<double, double> solve_linear_regression(const std::vector<double> &xs, const std::vector<double> &ys) { double x_sum = 0, y_sum = 0; for (size_t i = 0; i < xs.size(); ++i) { x_sum += xs[i]; y_sum += ys[i]; } auto x_mean = x_sum / xs.size(); auto y_mean = y_sum / ys.size(); double s_xy = 0, s2_x = 0; for (size_t i = 0; i < xs.size(); ++i) { s_xy += (xs[i] - x_mean) * (ys[i] - y_mean); s2_x += (xs[i] - x_mean) * (xs[i] - x_mean); } double beta = s_xy / s2_x; double alpha = y_mean - beta * x_mean; return {alpha, beta}; } }; #endif //WEIGHTED_F_FREE_EDGE_EDITING_EXPONENTIAL_H
true
8acdbb2ddc71c1cf6c50d72f81e52f3903122e09
C++
pjsdev/DX11Cloth
/Engine/src/Solver.cpp
UTF-8
2,797
2.578125
3
[]
no_license
#include "Solver.h" using namespace pjs; Solver::Solver() {} Solver::~Solver() {} Solver::Solver(const Solver&) {} void Solver::verlet(std::vector<Particle> &_particles, float _timeStep) { float radius = 2.0f; Vec3 spherePos = Vec3(0.0f,-4.0f, 4.0f); for(unsigned int i = 0; i < _particles.size(); i++) { if(!_particles[i].isConstrained) { pjs::Vec3 previousPos = _particles[i].pos; _particles[i].pos = _particles[i].pos + (_particles[i].pos - _particles[i].lastPos) + ( _particles[i].acceleration * _timeStep) * _timeStep; _particles[i].lastPos = previousPos; //Vec3 sphereToPoint = _particles[i].pos - spherePos; //float dist = D3DXVec3Length(&sphereToPoint); //if(dist < radius) //{ // D3DXVec3Normalize(&sphereToPoint, &sphereToPoint); // _particles[i].pos = radius*sphereToPoint; //} } } } void Solver::calculateSpringForce(std::vector<Spring> &_springs) { for(unsigned int i= 0; i < _springs.size(); i++) { float restLength = _springs[i].restLength; pjs::Vec3 dist = _springs[i].p1->pos - _springs[i].p2->pos; float currentLength = D3DXVec3Length(&dist); float extension = currentLength - restLength; pjs::Vec3 vel = _springs[i].p2->velocity - _springs[i].p1->velocity; pjs::Vec3 sNorm = _springs[i].p1->pos - _springs[i].p2->pos; pjs::Vec3 sNormResult; if(D3DXVec3Length(&sNorm) !=0 ) { D3DXVec3Normalize(&sNormResult, &sNorm); } pjs::Vec3 stiffnessForce = pjs::Vec3(0,0,0); pjs::Vec3 springForce = pjs::Vec3(0,0,0); pjs::Vec3 dampingForce = pjs::Vec3(0,0,0); stiffnessForce = 1.0f * _springs[i].stiffness * extension * sNormResult; dampingForce = -1.0f * _springs[i].damping * vel; springForce = stiffnessForce + dampingForce; _springs[i].p1->acceleration += -springForce / _springs[i].p1->mass; _springs[i].p2->acceleration += springForce / _springs[i].p2->mass; } } bool Solver::initialize() { m_forces.clear(); return true; } void Solver::shutdown(){} void Solver::addForce(const std::string &_name, const pjs::Vec3 &_force) { m_forces[_name] = _force; } void Solver::removeForce(const std::string &_name) { m_forces.erase(_name); } void Solver::editForce(const std::string &_name, const pjs::Vec3 &_modifier) { m_forces[_name] += _modifier; } void Solver::accumulateForces(std::vector<Particle> &_particles) { for(unsigned int i = 0; i < _particles.size(); i++) { _particles[i].acceleration = pjs::Vec3(0,0,0); for(std::map<std::string, pjs::Vec3>::iterator it = m_forces.begin(); it != m_forces.end(); it++) { _particles[i].acceleration += it->second / _particles[i].mass; } } }
true
1f914428313fb628e4609963b2c29c182dbed79b
C++
jimmyandrade/evolution
/cromossomo.cpp
UTF-8
803
2.84375
3
[]
no_license
#include <ctime> #include <iostream> #include "cromossomo.h" Cromossomo::Cromossomo( Indice quantidade_genes ) : quantidade_genes_( quantidade_genes ), ultimo_item_( quantidade_genes - 1 ) { // Gera valores aleatorios para os genes do individuo for ( unsigned int i = 0; i < quantidade_genes_; ++i ) { srand(time(NULL) + i); cromossomo_.push_back( GerarValorAleatorio() ); } } Cromossomo::~Cromossomo(void) { cromossomo_.clear(); } void Cromossomo::Imprimir(void) { char x; std::cout << "["; for ( unsigned int i = 0; i < quantidade_genes_; ++i ) { // std::cout << i << ": "; x = cromossomo_[i] ? '1' : '0'; std::cout << x; if( i < ultimo_item_ ) { std::cout << "\t"; } } std::cout << "]"; }
true
2da7d7ca218d4f1d959247661fc8956ad4c90545
C++
realwakka/xml_compiler
/xml_parser.h
UTF-8
10,861
3
3
[]
no_license
#ifndef XML_PARSER_H_ #define XML_PARSER_H_ #include <functional> #include <tuple> #include <utility> #include <string> #include "conststr.h" namespace xml_compiler { enum class EventType { kStartElement, kEndElement, kText }; class XMLAttribute { public: constexpr XMLAttribute() {} constexpr XMLAttribute(const conststr& key, const conststr& value) : key_(key), value_(value) {} constexpr conststr GetKey() const { return key_; } constexpr conststr GetValue() const { return value_; } constexpr void SetKey(conststr key) {key_ = key;} constexpr void SetValue(conststr value) {value_ = value;} constexpr void Clear() { key_ = conststr(); value_ = conststr(); } private: conststr key_; conststr value_; }; class XMLAttributeList { public: constexpr XMLAttributeList() : size_(0) {} constexpr void AddAttribute(const XMLAttribute& attr) { if( size_ < 16 ) { attributes_[size_] = attr; ++size_; } } constexpr XMLAttribute GetAttribute(std::size_t index) const { return index < size_? attributes_[index] : throw std::out_of_range(""); } constexpr std::size_t GetSize() const { return size_; } private: std::size_t size_; XMLAttribute attributes_[128]; }; class XMLElement { public: constexpr XMLElement() {} constexpr void AddAttribute(const XMLAttribute& attr) { attr_list_.AddAttribute(attr); } constexpr void SetName( const conststr& name ) { name_ = name;} constexpr conststr GetName() const { return name_;} constexpr XMLAttributeList GetAttributeList() const { return attr_list_; } constexpr void Clear() { name_ = conststr(); attr_list_ = XMLAttributeList(); } private: conststr name_; XMLAttributeList attr_list_; }; class Event { public: constexpr Event() : Event(EventType::kStartElement){} constexpr Event(EventType type) : type_(type){} constexpr EventType GetType() const { return type_; } constexpr XMLElement GetElement() const { return element_; } public: EventType type_; XMLElement element_; }; class EventList { public: constexpr EventList() : size_(0), typelist_{EventType::kStartElement,} {} constexpr std::size_t GetSize() const { return size_; } constexpr Event GetEvent(std::size_t i) const { return i < size_ ? list_[i] :throw std::out_of_range(""); } constexpr void PushEvent(const Event& event); Event list_[255]; EventType typelist_[255]; int size_; }; template<EventType Type> class NewEvent; template<> class NewEvent<EventType::kStartElement> { public: constexpr NewEvent() {} constexpr void CopyFrom(const Event& event) { element_ = event.element_; } public: XMLElement element_; }; template<> class NewEvent<EventType::kEndElement> { public: constexpr NewEvent() {} constexpr void CopyFrom(const Event& event) { element_ = event.element_; } public: XMLElement element_; }; template<> class NewEvent<EventType::kText> { public: constexpr NewEvent() {} }; template<EventType Type> constexpr void InsertNewEvent(const NewEvent<Type>& event) { } template<> constexpr void InsertNewEvent<EventType::kStartElement>(const NewEvent<EventType::kStartElement>& event) { } template<> constexpr void InsertNewEvent<EventType::kEndElement>(const NewEvent<EventType::kEndElement>& event) { } template<> constexpr void InsertNewEvent<EventType::kText>(const NewEvent<EventType::kText>& event) { } template<std::size_t Size> class FixedEventList { public: constexpr FixedEventList(){} constexpr void CopyFrom(const EventList& event_list); std::size_t GetSize() const { return Size; } Event GetEvent(std::size_t i) const { return list_[i]; } //constexpr void pushEvent(EventType type, const char* name, int name_len); private: Event list_[Size]; }; template<std::size_t Size> constexpr void FixedEventList<Size>::CopyFrom(const EventList& event_list) { for( auto i =0 ; i<Size ; ++i ) { list_[i] = event_list.list_[i]; } } constexpr void EventList::PushEvent(const Event& event) { if( size_ < 255 ) { list_[size_] = event; ++size_; } } class XMLParser { public: typedef void (XMLParser::*CharFunc)(char); constexpr XMLParser() : char_func_(&XMLParser::CharOnContent), stream_(nullptr), stream_len_(0), progress_(nullptr) {} constexpr EventList parse(const char* xml); private: constexpr void CharOnIdle(char ch); constexpr void CharOnMarkup(char ch); constexpr void CharOnContent(char ch); constexpr void CharOnStartMarkup(char ch); constexpr void CharOnEndMarkup(char ch); constexpr void CharOnEmptyMarkup(char ch); constexpr void CharOnAttributeKey(char ch); constexpr void CharOnAttributeValueBegin(char ch); constexpr void CharOnAttributeValue(char ch); constexpr void CharOnAttributeValueEnd(char ch); constexpr void OnMarkup(); constexpr void CallStartElement(); constexpr void CallEndElement(); constexpr void PushToStream(); constexpr void ClearStream(); private: CharFunc char_func_; //void (XMLParser::*char_func_)(char ch); const char* progress_; const char* stream_; int stream_len_; EventList list_; XMLElement element_; XMLAttribute attr_; }; constexpr void XMLParser::PushToStream() { if( stream_len_ == 0 ) { stream_ = progress_; } ++stream_len_; } constexpr void XMLParser::ClearStream() { stream_ = nullptr; stream_len_ = 0; } constexpr EventList XMLParser::parse(const char* xml) { auto index = 0; progress_ = xml; while( true ) { auto buf = progress_[0]; if( buf ) { (this->*char_func_)(buf); } else { break; } ++progress_; } return list_; } // template<std::size_t Index, EventList& list> // constexpr auto GetEventType() // { // //constexpr EventList list2 = list; // return NewEvent<list.list_[Index].type_>(); // } // template <std::size_t... Is> // constexpr auto CreateTupleImpl(const EventList& list, std::index_sequence<Is...> ) { // return std::make_tuple(list.list_[Is].type_...); // //return std::make_tuple(GetEventType<Is>(list)...); // } // template <std::size_t N> // constexpr auto CreateTuple(const EventList& list) // { // return CreateTupleImpl(list, std::make_index_sequence<N>{} ); // } // template<class Tuple, std::size_t... Is> // constexpr auto CreateTuple2Impl(const Tuple& t, std::index_sequence<Is...>) // { // return std::make_tuple(NewEvent<std::get<Is>(t)>()...); // } // template<class... Args> // constexpr auto CreateTuple2( const std::tuple<Args...>& t ) // { // return CreateTuple2Impl(t, std::index_sequence_for<Args...>{}); // } constexpr void XMLParser::CallStartElement() { Event event; event.element_ = element_; list_.PushEvent(event); ClearStream(); element_.Clear(); attr_.Clear(); } constexpr void XMLParser::CallEndElement() { //auto element = ParseElement(stream_, stream_len_); Event event(EventType::kEndElement); event.element_ = element_; list_.PushEvent(event); ClearStream(); element_.Clear(); attr_.Clear(); } constexpr void XMLParser::CharOnIdle(char ch) { switch(ch) { case '<': char_func_ = &XMLParser::CharOnMarkup; break; case '/': break; case '>': break; case ' ': case '\n': case '\t': break; default: ++stream_len_; break; } } constexpr void XMLParser::CharOnMarkup(char ch) { switch(ch) { case '/': stream_ = progress_ + 1; char_func_ = &XMLParser::CharOnEndMarkup; break; case '!': break; case ' ': case '\n': case '\t': break; default: stream_ = progress_; CharOnStartMarkup(ch); char_func_ = &XMLParser::CharOnStartMarkup; break; } } constexpr void XMLParser::CharOnStartMarkup(char ch) { switch(ch) { case '/': // //empty? no! // CallStartElement(); // CallEndElement(); break; case '>': element_.SetName(conststr(stream_, stream_len_)); ClearStream(); char_func_ = &XMLParser::CharOnContent; CallStartElement(); break; case ' ': char_func_ = &XMLParser::CharOnAttributeKey; element_.SetName(conststr(stream_, stream_len_)); ClearStream(); break; default: //element name ++stream_len_; break; } } constexpr void XMLParser::CharOnEmptyMarkup(char ch) { char_func_ = &XMLParser::CharOnContent; } constexpr void XMLParser::CharOnEndMarkup(char ch) { switch(ch) { case '>': { element_.SetName(conststr(stream_, stream_len_)); ClearStream(); CallEndElement(); char_func_ = &XMLParser::CharOnContent; break; } case ' ': case '\n': case '\t': break; default: ++stream_len_; break; } } constexpr void XMLParser::CharOnContent(char ch) { switch(ch) { case '<': char_func_ = &XMLParser::CharOnMarkup; OnMarkup(); break; case ' ': case '\n': case '\t': break; default: PushToStream(); break; } } constexpr void XMLParser::CharOnAttributeKey(char ch) { switch(ch) { case '=': char_func_ = &XMLParser::CharOnAttributeValueBegin; attr_.SetKey(conststr(stream_, stream_len_)); ClearStream(); break; default: if( stream_len_ == 0 ) { stream_ = progress_; } ++stream_len_; break; } } constexpr void XMLParser::CharOnAttributeValueBegin(char ch) { switch(ch) { case '"': case '\'': char_func_ = &XMLParser::CharOnAttributeValue; break; default: break; } } constexpr void XMLParser::CharOnAttributeValue(char ch) { switch(ch) { case '"': case '\'': char_func_ = &XMLParser::CharOnAttributeValueEnd; attr_.SetValue(conststr(stream_, stream_len_)); element_.AddAttribute(attr_); ClearStream(); attr_ = XMLAttribute(); break; default: if( stream_len_ == 0 ) { stream_ = progress_; } ++stream_len_; break; } } constexpr void XMLParser::CharOnAttributeValueEnd(char ch) { switch(ch) { case ' ': //next attr char_func_ = &XMLParser::CharOnAttributeKey; break; case '>': char_func_ = &XMLParser::CharOnContent; CallStartElement(); break; default: break; } } constexpr void XMLParser::OnMarkup() { if( stream_len_ > 0 ) { // TextElement; list_.PushEvent(EventType::kText, stream_, stream_len_); //list_.PushEvent(Event(EventType::kText)); ClearStream(); // stream_ += stream_len_; // stream_len_ = 0; } } } // speedup #endif /* XML_PARSER_H_ */
true
a7492527e21d0d3c59a83fbdd557c56f11c8d0cb
C++
AlexanderSilvaB/btree
/src/lib/btree/ParallelPool.cpp
UTF-8
1,065
2.796875
3
[ "MIT" ]
permissive
#include "ParallelPool.hpp" using namespace btree; using namespace std; // Task Task::Task(NodePtr node, Blackboard *blackboard) { this->node = node; this->blackboard = blackboard; task = thread(&Task::run, this); } void Task::wait() { task.join(); } void Task::run() { node->evaluate(*blackboard); } // ParallelPool ParallelPool::ParallelPool() { running = false; } ParallelPool::~ParallelPool() { } void ParallelPool::attach(NodePtr node) { nodes.push_back(node); } void ParallelPool::clear() { if(running) return; nodes.clear(); tasks.clear(); } void ParallelPool::start(Blackboard& blackboard) { if(running) return; tasks.clear(); running = true; for(list< NodePtr >::iterator it = nodes.begin(); it != nodes.end(); it++) { tasks.push_back( Task(*it, &blackboard) ); } } NodeStates ParallelPool::wait() { for(list< Task >::iterator it = tasks.begin(); it != tasks.end(); it++) { it->wait(); } running = false; return SUCCESS; }
true
0254af86f78af8a5e8d3466001e1f3b8fc23a4f5
C++
voltsemu/volts
/volts/loader/sfo.cpp
UTF-8
4,062
3.046875
3
[]
no_license
#include "sfo.h" #include <svl/convert.h> #include <spdlog/spdlog.h> namespace volts::loader::sfo { using namespace std; using namespace svl; namespace cvt = convert; /** * @brief an entry in the sfo file * */ struct index_table_entry { /// the offset of the key relative to sfo::header::key_offset u16 key_offset; /// the format of the data for this key format data_format; /// the length of the data u32 data_length; /// the maximum amount of bytes this data can use u32 max_length; /// the offset of the data relative to sfo::header::data_offset u32 data_offset; }; /** * @brief the sfo header * */ struct header { /// file magic, always "\0PSF" u32 magic; /// the version of the sfo file, we only support 0x101 for now u32 version; /// the offset of the key table u32 key_offset; /// the offset of the data entries u32 data_offset; /// the total number of entries in the file u32 total_entries; }; svl::expected<object> load(svl::file stream) { // read in the header const auto head = stream.read<header>(); // make sure this is actually an sfo file if(head.magic != cvt::to_u32("\0PSF")) { spdlog::error("invalid magic"); return svl::none(); } // make sure this is a supported version if(head.version != 0x101) { spdlog::error("unsupported version"); return svl::none(); } object val; // read in the redirectors const auto redirects = stream.read<index_table_entry>(head.total_entries); // for every entry for(const auto redirect : redirects) { // seek to the key in the key table stream.seek(head.key_offset + redirect.key_offset); string key; // read in the key, its always null terminated while(auto c = stream.read<char>()) key += c; // seek to the data in the data table stream.seek(head.data_offset + redirect.data_offset); // read in the data const auto data = stream.read<svl::byte>(redirect.max_length); value v = { redirect.data_format, std::move(data) }; // put the data into the object val.insert({ key, v }); } return val; } void write(svl::file& stream, const object& obj) { struct triple { u16 key; u32 data; u32 size; format fmt; }; // offsets std::vector<triple> offsets = {}; // data svl::file keys = svl::buffer(); svl::file data = svl::buffer(); // write data to buffers for(auto& [key, it] : obj) { offsets.push_back({ static_cast<u16>(keys.tell()), static_cast<u32>(data.tell()), static_cast<u32>(it.data.size()), it.type }); keys.write(key, true); data.write(it.data); } auto size = obj.size(); // create header header head = { cvt::to_u32("\0PSF"), // magic 0x101, // version static_cast<u32>(size * sizeof(index_table_entry) + sizeof(header)), // key table offset static_cast<u32>(keys.size() + size * sizeof(index_table_entry) + sizeof(header)), // data offset static_cast<u32>(size) // total entries }; stream.seek(0); stream.write(head); for(auto idx : offsets) { index_table_entry entry = { idx.key, idx.fmt, idx.size, idx.size, idx.data }; stream.write(entry); } stream.insert(keys); stream.insert(data); } }
true
0d73a92905dc40206075bb76f8b47d28e049e69d
C++
yyehl/Intro_algorithms
/chapter-16/16.1-1.cpp
UTF-8
1,178
3.203125
3
[]
no_license
/* * Filename: 16.1-1.cpp * * 活动选择问题的动态规划解法 // 有BUG,暂时不知道怎么改 * */ #include <vector> #include <iostream> #include <stdlib.h> using namespace std; int dp_activity_selector_aux(const vector<int>& vs, const vector<int>& vf, vector<vector<int> >& c, int i, int j) { if (c[i][j] != -1) return c[i][j]; int q = 1; for (int k = i + 1; k < j; ++k) { if (vf[i] <= vs[k] && vf[k] <= vs[j]) q = max(q, dp_activity_selector_aux(vs, vf, c, i, k) + dp_activity_selector_aux(vs, vf, c, k, j) + 1); else if (vf[i] <= vs[k]) q = max(q, dp_activity_selector_aux(vs, vf, c, i, k) + 1); else if (vf[k] <= vs[j]) q = max(q, dp_activity_selector_aux(vs, vf, c, k, j) + 1); else q = max(q, 1); } c[i][j] = q; return c[i][j]; } int dp_activity_selector(const vector<int>& vs, const vector<int>& vf) { int len = vs.size(); vector<vector<int> > c(len, vector<int>(len, -1)); return dp_activity_selector_aux(vs, vf, c, 0, len-1); } int main() { vector<int> vs = {1,3,0,5,3,5,6,8,8,2,12}; vector<int> vf = {4,5,6,7,9,9,10,11,12,14,16}; cout << dp_activity_selector(vs, vf) << endl; return 0; }
true
67ba3101ccfd7d217519b821d8fb5dd48e9bbbd3
C++
OhiyoX/Process_Simulation
/优先级算法/Progress_Status.h
GB18030
1,433
2.984375
3
[]
no_license
#pragma once typedef int QElemType;//ṹ typedef struct ProgNode { QElemType data; ProgNode *next; }ProgNode, *ProgQueuePtr; typedef struct { ProgQueuePtr front;//ͷָ ProgQueuePtr rear;//βָ int qlen; }LinkQueue; class Status_Queue { public: //----------------------- int running;//̬,ʾ̬ĽidΪ-1ʾ̬ LinkQueue ready;//̬ LinkQueue waiting;//̬ //------------------------ Status_Queue();//ʼ캯 void Set_Running(int &pid); void Set_Ready(int &pid);//þ void Set_Waiting(int &pid); void Priority_Decide(LinkQueue &Q, int pid); //------------к-----------// int InitQueue(LinkQueue &Q); //ʼQ int EmptyQueue(LinkQueue &Q); //QΪգTRUE򷵻FALSE int DeQueue(LinkQueue &Q, QElemType &e); //QΪգ׽ӣeأOK򷵻ERROR int EnQueue(LinkQueue &Q, QElemType e); //eQ int QueueLength(LinkQueue &Q); //ضQijȣԪظ int GetHead(LinkQueue &Q, QElemType &e); //QΪգe׽㣬OK,򷵻ERROR int InsAfter(LinkQueue &Q, ProgQueuePtr &h, QElemType e);//hq int MakeNode(ProgQueuePtr &p, QElemType e);//һeΪԪصĽ };
true
9a82b6aca0bce315a0ebeb58c628da36d75ce0f9
C++
Elianagam/taller_de_programacion_1
/tp2/Compress_Block.cpp
UTF-8
1,913
2.984375
3
[]
no_license
#include <iostream> #include <bits/stdc++.h> #include <algorithm> #include <vector> #include <cmath> #include <arpa/inet.h> #include <queue> #include <string> #include <stdio.h> #include <fstream> #include "Compress_Block.h" Compress_Block::Compress_Block() {} void Compress_Block::set_min_bits(uint8_t num) { min_bit = num; } void Compress_Block::convert_to_binary(uint32_t num) { int total = 0; std::vector<bool> number; for (int i = 0; i < min_bit; i++) { if (num > 0) { total = num % 2; num /= 2; number.insert(number.begin(), total); } else { number.insert(number.begin(), 0); } } save_number(number); } void Compress_Block::save_number(std::vector<bool> &number) { for (bool bit : number) compress_v.insert(compress_v.begin(), bit); } void Compress_Block::to_byte() { // tranforma el vector de 0's y 1's en chars sifteando len = (compress_v.size() + 8 -1) / 8; for (uint32_t i = 0; i < compress_v.size(); i += 8) { char c = 0; for (uint32_t j = 0; j < 8; j++) { if (compress_v[j+i]) { c += 1 << j; } } char_v.insert(char_v.begin(), c); } } std::vector<char> Compress_Block::compress(std::vector<uint32_t> *block) { for (uint32_t hex : *block) convert_to_binary(hex); align(); to_byte(); return std::move(char_v); } void Compress_Block::align() { while (compress_v.size() % 8 != 0) { compress_v.insert(compress_v.begin(), 0); } } Compress_Block::Compress_Block(Compress_Block&& other) { this->compress_v = std::move(other.compress_v); this->min_bit = other.min_bit; this->len = other.len; this->char_v = std::move(other.char_v); } Compress_Block& Compress_Block::operator=(Compress_Block&& other) { this->compress_v = std::move(other.compress_v); this->min_bit = other.min_bit; this->len = other.len; this->char_v = std::move(other.char_v); return *this; } Compress_Block::~Compress_Block() { //pass }
true
a31646e60d05303e63b781a0c48393be8e98728f
C++
federicochiarello/OOP_Liberty
/model/container.h
UTF-8
515
3.03125
3
[]
no_license
#ifndef CONTAINER_H #define CONTAINER_H #include <iostream> template <class T> class container { private: unsigned int m_size; unsigned int m_capacity; T* m_vector; public: container(); container(const container&); ~container(); void pushFront(const T&); void pushBack(const T&); void popFront(); void popBack(); class iterator { private: T** m_pointer; public: iterator(); }; }; #endif // CONTAINER_H
true
5bba759a0294209b2e7143c89aade6e8b187b46e
C++
IL-two/Cpp
/Lessons/Task 3/3.3.AreaTrangle.cpp
UTF-8
2,063
3.640625
4
[]
no_license
//Практическое занятие 3. Контрольное задание №3 //Расчет площади треугольника //От Духно Ильи гр.124/20 #include <iostream> #include <cmath> using namespace std; double triangle(double side); double triangle(double a, double b, double c); int main() { system("chcp 1251"); int choice; cout << "Выберите тип треугольника\n" << "1. Равносторонний\n" << "2. Разносторонний\n" << "0. Выход\n"; cin >> choice; switch (choice) { case 1: { double side; cout << "Введите длину стороны треугольника" << endl; cin >> side; cout << "Площадь равностороннего треугольника: " << triangle(side) << endl; break; } case 2: { double a, b, c; cout << "Введите длину сторон треугольника a, b, c" << endl; cin >> a >> b >> c; if ((a < b + c) && (b < a + c) && (c < b + a)) { cout << "Площадь разностороннего треугольника: " << triangle(a, b, c) << endl; break; } else { cout << "Это не может быть треугольником" << endl; } } case 0: { cout << "До свидания!" << endl; break; } default: { cout << "Введен неверный символ" << endl; break; } } } double triangle(double side) //Равносторонний треугольник { return (pow(side, 2) * sqrt(3)) / 4; } double triangle(double a, double b, double c) //Разносторонний треугольник { double p = (a + b + c) / 2; return sqrt(p * (p - a) * (p - b) * (p - c)); }
true
9af57ac1511e79bff51672fcc42244aa791d6e32
C++
holicAZ/AlgorithmStudy
/2075.cpp
UHC
844
3.421875
3
[]
no_license
#include <iostream> #include <queue> using namespace std; priority_queue<int, vector<int>, greater<int> > pq; // 켱 -> ū int main(void) { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); int n; cin >> n; for (int i = 0; i < n * n; i++) { // n*n Է int c; cin >> c; // pq ִũ⸦ n (޸ ) if(pq.size()<n) // n size push pq.push(c); // ť ־ else // n ũų popϰ push if (pq.top() < c) { // Է pq top ü pq.pop(); pq.push(c); } // ݺ Ǹ n // top ִ n° ū } cout << pq.top(); // popĿ return 0; }
true
d78946b66a25667fcf74983301721e94f701e855
C++
asepnur/sorting
/display_array.h
UTF-8
691
3.203125
3
[]
no_license
#ifndef DISPLAY_ARRAY_H_INCLUDED #define DISPLAY_ARRAY_H_INCLUDED using namespace std; void display(int *number_array,size_t length){ int col = 1; cout.width(5); for(size_t i = 0; i++ < length;col++){ cout << number_array[i-1]; if(i < length) std::cout.width(5); if(col == 20){ col = 0 ; cout << endl; } } } void information(double time_process, size_t LENGTH, string algorithm){ cout << "Algorithm : " << algorithm; cout << endl << "Process time : " << time_process; cout << endl << "Total Data : " << LENGTH; cout << endl << "Ordered Number : " << endl << endl; } #endif // DISPLAY_ARRAY_H_INCLUDED
true
bd3da93884bd092a5dbab5b1163933028a16857a
C++
pritishpatil/HW3
/hw3.cpp.cpp
UTF-8
3,888
3.828125
4
[]
no_license
/* PIC 10B 2B, Homework 3 Author: Pritish Patil Date: 05/09/2020 */ #include <iostream> #include <fstream> #include <string> #include "textfile.h" using namespace std; void processFile(string fileName, textfile* filePtr) { fstream file; string line; int lineCount = 0; int wordCount = 0; int charCount = 0; string word; file.open(fileName, ios::in); if (file.fail()) { cerr << "Error opening file1" << endl; exit(1); } if (file.is_open()) { char current = ' '; bool spaceEncountered = false; while (!file.eof()) { getline(file, line); if (!line.empty()) { for (int i = 0; line[i] != '\0'; i++) { current = line[i]; if (current == ' ' || current == '\t') { // if space or tab encountered add to wordcount, do not count multiple spaces between words if (spaceEncountered == false) { wordCount++; } spaceEncountered = true; } else { spaceEncountered = false; } } charCount += line.length(); lineCount++; } } // account for final word if there is not a space encountered at end of file if (spaceEncountered == false) { wordCount++; } file.close(); filePtr->setFileInfo(fileName, lineCount, wordCount, charCount); } else { cerr << "Error opening file!" << endl; exit(2); } } int main() { string file1; string file2; // user input cout << "Enter the name of file 1: " << endl; cin >> file1; cout << "Enter the name of file 2: " << endl; cin >> file2; // create textfile objects textfile file1Object; textfile file2Object; // process files with helper processFile(file1, &file1Object); processFile(file2, &file2Object); // output properties to text file ofstream outputFile; outputFile.open("Properties.txt"); outputFile << "Filename: " << file1Object.getFilename() << endl; outputFile << "Number of Characters: " << file1Object.getCharacters() << endl; outputFile << "Number of Words: " << file1Object.getWordcount() << endl; outputFile << endl; outputFile << "Filename: " << file2Object.getFilename() << endl; outputFile << "Number of Characters: " << file2Object.getCharacters() << endl; outputFile << "Number of Words: " << file2Object.getWordcount() << endl; outputFile << endl; // compare lines via overloaded operators bool compareGreater = file1Object > file2Object; bool compareLess = file1Object < file2Object; bool checkEqual = file1Object == file2Object; // produce comparison result if (compareGreater == true) { outputFile << "The file named " << "\"" << file2Object.getFilename() << "\"" << " has less lines than " << "\"" << file1Object.getFilename() << "\"." << endl; } else if (compareLess == true) { outputFile << "The file named " << "\"" << file1Object.getFilename() << "\"" << " has less lines than " << "\"" << file2Object.getFilename() << "\"." << endl; } else if (checkEqual == true) { outputFile << "\"" << file1Object.getFilename() << "\"" << " has the same number of lines as " << "\"" << file2Object.getFilename() << "\"." << endl; } outputFile.close(); return 0; }
true
806dde284b3a55f7ddad2c044c5be161aa01281d
C++
kilfu0701/Competitive-Programming
/Google Code Jam/2020/Round 1C/Overrandomized.cpp
UTF-8
1,595
3.046875
3
[ "MIT" ]
permissive
// Problem 2: Overrandomized // Idea: count the frequency of each letter appears as the leading digit (Benford's law) // The letter with the highest frequency will be 1, and the one with the lowest will be 9 // 0 will have a 0 frequency because it cannot exist as a leading digit #include <bits/stdc++.h> using namespace std; const int MAX_N = 1e4; typedef long long ll; void solve() { int U; cin >> U; string arr[MAX_N]; int freq[26] = {0}, used[26] = {0}; for (int i = 0; i < MAX_N; i++) { ll skip; cin >> skip; // not important, we only care about the first letter of the string cin >> arr[i]; for (char c : arr[i]) { // this is to mark digit 0 because its frequency as a leading digit = 0 used[c - 'A'] = 1; } freq[arr[i][0] - 'A']++; // first letter <=> leading digit } string ans = "0123456789"; for (int i = 0; i < 26; i++) { if (used[i] && freq[i] == 0) { ans[0] = i + 'A'; break; } } for (int i = 1; i < 10; i++) { char mx = 'A'; for (int j = 0; j < 26; j++) { if (used[j] && freq[j] > freq[mx - 'A']) { mx = j + 'A'; } } ans[i] = mx; freq[mx - 'A'] = -1; } cout << ans << "\n"; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); int tc; cin >> tc; for (int t = 1; t <= tc; t++) { cout << "Case #" << t << ": "; solve(); } }
true