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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
95c90931a3939c702fd988fb7eae8bf8e3188acd | C++ | narnoura/multivec | /multivec/monolingual.cpp | UTF-8 | 46,851 | 2.9375 | 3 | [
"Apache-2.0"
] | permissive | #include "monolingual.hpp"
#include "serialization.hpp"
const HuffmanNode HuffmanNode::UNK;
void MonolingualModel::addWordToVocab(const string& word) {
auto it = vocabulary.find(word);
if (it != vocabulary.end()) {
it->second.count++;
} else {
HuffmanNode node(static_cast<int>(vocabulary.size()), word);
vocabulary.insert({word, node});
}
}
void MonolingualModel::reduceVocab() {
int i = 0;
for (auto it = vocabulary.begin(); it != vocabulary.end(); ) {
if ((it->second.count) < config->min_count) {
vocabulary.erase(it++);
} else {
it++->second.index = i++; // reassign indices in [0, vocabulary size - 1)
}
}
}
void MonolingualModel::readVocab(const string& training_file) {
ifstream infile(training_file);
try {
check_is_open(infile, training_file);
check_is_non_empty(infile, training_file);
} catch (...) {
throw;
}
vocabulary.clear();
string word;
while (infile >> word) {
addWordToVocab(word);
}
if (config->verbose)
std::cout << "Vocabulary size: " << vocabulary.size() << std::endl;
reduceVocab();
if (config->verbose)
std::cout << "Reduced vocabulary size: " << vocabulary.size() << std::endl;
createBinaryTree();
initUnigramTable();
}
void MonolingualModel::readLexicon(const string& lexicon_file) {
// TODO
// reads lexicon and updates the lexicon hashmap of the source model
ifstream infile(lexicon_file);
std::cout << "Reading sentiment lexicon " << endl;
try {
check_is_open(infile, lexicon_file);
check_is_non_empty(infile, lexicon_file);
} catch (...) {
throw;
}
// read lines and update sentiment_lexicon hashmap
string lex_line;
string word;
string sentiment;
vector<string> fields;
while (getline(infile, lex_line)) {
fields = split_tab(lex_line);
word = fields[0];
sentiment = fields[1];
//std:cout << word << " " << sentiment << endl;
sentiment_lexicon[word] = sentiment;
}
}
void MonolingualModel::createBinaryTree() {
vector<HuffmanNode*> heap;
vector<HuffmanNode> parent_nodes;
parent_nodes.reserve(vocabulary.size());
for (auto it = vocabulary.begin(); it != vocabulary.end(); ++it) {
heap.push_back(&it->second);
}
std::sort(heap.begin(), heap.end(), HuffmanNode::comp);
for (int i = 0; heap.size() > 1; i++) {
HuffmanNode* left = heap.back();
heap.pop_back();
HuffmanNode* right = heap.back();
heap.pop_back();
parent_nodes.push_back({i, left, right});
HuffmanNode* parent = &parent_nodes.back();
auto it = lower_bound(heap.begin(), heap.end(), parent, HuffmanNode::comp);
heap.insert(it, parent);
}
assignCodes(heap.front(), {}, {});
}
void MonolingualModel::assignCodes(HuffmanNode* node, vector<int> code, vector<int> parents) const {
if (node->is_leaf) {
node->code = code;
node->parents = parents;
} else {
parents.push_back(node->index);
vector<int> code_left(code);
code_left.push_back(0);
vector<int> code_right(code);
code_right.push_back(1);
assignCodes(node->left, code_left, parents);
assignCodes(node->right, code_right, parents);
}
}
void MonolingualModel::initUnigramTable() {
unigram_table.clear();
vocab_word_count = 0;
float power = 0.75; // weird word2vec tweak ('normal' value would be 1.0)
float total_count = 0.0;
for (auto it = vocabulary.begin(); it != vocabulary.end(); ++it) {
vocab_word_count += it->second.count;
total_count += pow(it->second.count, power);
}
for (auto it = vocabulary.begin(); it != vocabulary.end(); ++it) {
float f = pow(it->second.count, power) / total_count;
int d = static_cast<int>(f * UNIGRAM_TABLE_SIZE);
for (int i = 0; i < d; ++i) {
unigram_table.push_back(&it->second);
}
}
}
HuffmanNode* MonolingualModel::getRandomHuffmanNode() {
auto index = multivec::rand() % unigram_table.size();
return unigram_table[index];
}
void MonolingualModel::initNet() {
int v = static_cast<int>(vocabulary.size());
int d = config->dimension;
int w = config->window_size;
input_weights = mat(v, vec(d));
for (size_t row = 0; row < v; ++row) {
for (size_t col = 0; col < d; ++col) {
input_weights[row][col] = (multivec::randf() - 0.5f) / d;
}
}
output_weights_hs = mat(v, vec(d));
output_weights = mat(v, vec(d));
if (config->learn_attn) {
std::cout<< "Initializing attention parameters in monolingual model" << std::endl;
attn_weights = mat(v,vec(2*w));
attn_bias = vec(2*w);
for (size_t row = 0; row < v; ++row) {
for (size_t col = 0; col< 2*w ; ++ col) {
attn_weights[row][col] = 0;
//attn_weights[row][col] = (multivec::randf() - 0.5f) / 2*w;
}
}
for (size_t s =0; s < 2*w; ++ s) {
attn_bias[s]=0;
//attn_bias[s] = (multivec::randf() - 0.5f) / 2*w;
}
}
if (config->learn_sentiment) {
std::cout<< "Initializing sentiment output parameters in monolingual model" << std::endl;
int s = sizeof(sentiment_labels)/sizeof(sentiment_labels[0]);
std::cout<< "Number of sentiment labels: " << s << std::endl;
sentiment_weights = mat(s, vec(d));
//in_sentiment_weights = mat(s, vec(d));
for (size_t row = 0; row < s; ++row) {
for (size_t col = 0; col < d; ++col) {
//(was initializing the output sentiment weights before)
sentiment_weights[row][col] = (multivec::randf() - 0.5f) / d;
//in_sentiment_weights[row][col] = (multivec::randf() - 0.5f) / d;
}
}
}
}
void MonolingualModel::initSentWeights() {
int d = config->dimension;
sent_weights = mat(training_lines, vec(d));
for (size_t row = 0; row < training_lines; ++row) {
for (size_t col = 0; col < d; ++col) {
sent_weights[row][col] = (multivec::randf() - 0.5f) / d;
}
}
}
vector<HuffmanNode> MonolingualModel::getNodes(const string& sentence) const {
vector<HuffmanNode> nodes;
istringstream iss(sentence);
string word;
while (iss >> word) {
auto it = vocabulary.find(word);
HuffmanNode node = HuffmanNode::UNK;
if (it != vocabulary.end()) {
node = it->second;
}
nodes.push_back(node);
}
return nodes;
}
/*
* @brief Discard random nodes according to their frequency. The more frequent a word is, the more
* likely it is to be discarded. Discarded nodes are replaced by UNK token.
*/
void MonolingualModel::subsample(vector<HuffmanNode>& nodes) const {
for (auto it = nodes.begin(); it != nodes.end(); ++it) {
auto node = *it;
float f = static_cast<float>(node.count) / vocab_word_count; // frequency of this word
float p = 1 - (1 + sqrt(f / config->subsampling)) * config->subsampling / f; // word2vec formula
if (p >= multivec::randf()) {
*it = HuffmanNode::UNK;
}
}
}
void MonolingualModel::saveVectorsBin(const string &filename, int policy) const {
if (config->verbose)
std::cout << "Saving embeddings in binary format to " << filename << std::endl;
ofstream outfile(filename, ios::binary | ios::out);
try {
check_is_open(outfile, filename);
} catch (...) {
throw;
}
outfile << vocabulary.size() << " " << config->dimension << endl;
for (auto it = vocabulary.begin(); it != vocabulary.end(); ++it) {
string word = string(it->second.word);
word.push_back(' ');
vec embedding = wordVec(it->second.index, policy);
outfile.write(word.c_str(), word.size());
outfile.write(reinterpret_cast<const char*>(embedding.data()), sizeof(float) * config->dimension);
outfile << endl;
}
}
void MonolingualModel::saveVectors(const string &filename, int policy) const {
if (config->verbose)
std::cout << "Saving embeddings in text format to " << filename << std::endl;
ofstream outfile(filename, ios::binary | ios::out);
try {
check_is_open(outfile, filename);
} catch (...) {
throw;
}
outfile << vocabulary.size() << " " << config->dimension << endl;
for (auto it = vocabulary.begin(); it != vocabulary.end(); ++it) {
outfile << it->second.word << " ";
vec embedding = wordVec(it->second.index, policy);
for (int c = 0; c < config->dimension; ++c) {
outfile << embedding[c] << " ";
}
outfile << endl;
}
}
void MonolingualModel::saveSentVectors(const string &filename) const {
if (config->verbose)
std::cout << "Saving sentence vectors in text format to " << filename << std::endl;
ofstream outfile(filename, ios::binary | ios::out);
try {
check_is_open(outfile, filename);
} catch (...) {
throw;
}
for (auto it = sent_weights.begin(); it != sent_weights.end(); ++it) {
vec embedding = *it;
for (int c = 0; c < config->dimension; ++c) {
outfile << embedding[c] << " ";
}
outfile << endl;
}
}
void MonolingualModel::load(const string& filename) {
if (config->verbose)
std::cout << "Loading model" << std::endl;
ifstream infile(filename);
try {
check_is_open(infile, filename);
} catch (...) {
throw;
}
::load(infile, *this);
initUnigramTable();
if (config->verbose)
std::cout << "Vocabulary size: " << vocabulary.size() << std::endl;
}
void MonolingualModel::save(const string& filename) const {
if (config->verbose)
std::cout << "Saving model" << std::endl;
ofstream outfile(filename);
try {
check_is_open(outfile, filename);
} catch (...) {
throw;
}
::save(outfile, *this);
}
vec MonolingualModel::wordVec(int index, int policy) const {
if (policy == 1 && config->negative > 0) // concat input and output
{
int d = config->dimension;
vec res(d * 2);
for (int c = 0; c < d; ++c) res[c] = input_weights[index][c];
for (int c = 0; c < d; ++c) res[d + c] = output_weights[index][c];
return res;
}
else if (policy == 2 && config->negative > 0) // sum input and output
{
return input_weights[index] + output_weights[index];
}
else if (policy == 3 && config->negative > 0) // only output weights
{
return output_weights[index];
}
else // only input weights
{
return input_weights[index];
}
}
/**
* @brief Return weight vector corresponding to the given word.
*
* @param word
* @param policy defines which weights to return.
* 0 (default): input weights only,
* 1: concatenation of input and output weights,
* 2: sum of input and output weights,
* 3: output weights only.
* @return vec
*/
vec MonolingualModel::wordVec(const string& word, int policy) const {
auto it = vocabulary.find(word);
if (it == vocabulary.end()) {
throw runtime_error("out of vocabulary");
} else {
return wordVec(it->second.index, policy);
}
}
void MonolingualModel::sentVec(istream& input) {
string line;
while(getline(input, line)) {
vec embedding(config->dimension, 0);
try {
embedding = sentVec(line);
} catch (runtime_error) {
// in case of error (empty sentence, or all words are OOV), print a vector of zeros
};
for (int c = 0; c < config->dimension; ++c) {
std::cout << embedding[c] << " ";
}
}
}
/**
* @brief Online paragraph vector on a given sentence. The parameters
* of the model are frozen, while gradient descent is performed on this
* single sentence. For batch paragraph vector, use the normal training
* procedure with config->sent_vec set to true.
* TODO: integrate this in the normal training procedure
*
* @param sentence
* @return sent_vec
*/
vec MonolingualModel::sentVec(const string& sentence) {
int dimension = config->dimension;
float alpha = config->learning_rate; // TODO: decreasing learning rate
auto nodes = getNodes(sentence); // no subsampling here
nodes.erase(
remove(nodes.begin(), nodes.end(), HuffmanNode::UNK),
nodes.end()); // remove UNK tokens
if (nodes.empty())
throw runtime_error("too short sentence, or OOV words");
vec sent_vec(dimension, 0);
for (int k = 0; k < config->iterations; ++k) {
for (int word_pos = 0; word_pos < nodes.size(); ++word_pos) {
vec hidden(dimension, 0);
HuffmanNode cur_node = nodes[word_pos];
int this_window_size = 1 + multivec::rand() % config->window_size;
int count = 0;
for (int pos = word_pos - this_window_size; pos <= word_pos + this_window_size; ++pos) {
if (pos < 0 || pos >= nodes.size() || pos == word_pos) continue;
hidden += input_weights[nodes[pos].index];
++count;
}
if (count == 0) continue;
hidden = (hidden + sent_vec) / (count + 1); // TODO this or (hidden / count) + sent_vec?
vec error(dimension, 0);
if (config->hierarchical_softmax) {
error += hierarchicalUpdate(cur_node, hidden, alpha, false);
}
if (config->negative > 0) {
error += negSamplingUpdate(cur_node, hidden, alpha, false);
}
sent_vec += error;
}
}
return sent_vec;
}
/**
* @brief Train model using given text file. Training is performed in parallel (each
* thread reads one chunk of the file). Learning rate decays to zero.
* Before calling this method, you need to call initialize or load, to initialize
* the model parameters (vocabulary, unigram table, weights, etc.)
*
* @param training_file path of the training file (text file with one sentence per line)
* @param initialize initialize the parameters of the model (vocabulary, unigram table,
* weights). This parameter should be true, unless you are loading an existing model.
**/
void MonolingualModel::train(const string& training_file, bool initialize) {
std::cout << "Training file: " << training_file << std::endl;
if (initialize) {
if (config->verbose)
std::cout << "Creating new model" << std::endl;
// reads vocab and initializes unigram table
readVocab(training_file);
initNet();
} else if (vocab_word_count == 0) {
// TODO: check that everything is initialized, and dimension is OK
throw runtime_error("the model needs to be initialized before training");
}
if (config->learn_sentiment) {
readLexicon(config->sent_lexicon);
}
// TODO: also serialize training state
words_processed = 0;
alpha = config->learning_rate;
// read file to find out the beginning of each chunk
// also counts the number of lines and words
auto chunks = chunkify(training_file, config->threads);
if (config->verbose)
std::cout << "Number of lines: " << training_lines
<< ", words: " << training_words << std::endl;
if (config->sent_vector)
// no incremental training for paragraph vector
initSentWeights();
high_resolution_clock::time_point start = high_resolution_clock::now();
if (config->threads == 1) {
trainChunk(training_file, chunks, 0);
} else {
vector<thread> threads;
for (int i = 0; i < config->threads; ++i) {
threads.push_back(thread(&MonolingualModel::trainChunk, this,
training_file, chunks, i));
}
for (auto it = threads.begin(); it != threads.end(); ++it) {
it->join();
}
}
high_resolution_clock::time_point end = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(end - start).count();
if (config->verbose)
std::cout << std::endl;
std::cout << "Training time: " << static_cast<float>(duration) / 1000000 << std::endl;
}
/**
* @brief Divide a given file into chunks with the same number of lines each
*
* @param filename path of the file
* @param n_chunks number of chunks
* @return starting position (in bytes) of each chunk
*/
vector<long long> MonolingualModel::chunkify(const string& filename, int n_chunks) {
ifstream infile(filename);
try {
check_is_open(infile, filename);
check_is_non_empty(infile, filename);
} catch (...) {
throw;
}
vector<long long> chunks;
vector<long long> line_positions;
long long words = 0;
string line;
do {
line_positions.push_back(static_cast<long long>(infile.tellg()));
words += split(line).size();
} while (getline(infile, line));
words += split(line).size();
training_lines = line_positions.size() - 1;
training_words = words;
int chunk_size = line_positions.size() / n_chunks; // number of lines in each chunk
for (int i = 0; i < n_chunks; i++) {
long long chunk_start = line_positions[i * chunk_size];
chunks.push_back(chunk_start);
}
return chunks;
}
void MonolingualModel::trainChunk(const string& training_file,
const vector<long long>& chunks,
int chunk_id) {
ifstream infile(training_file);
float starting_alpha = config->learning_rate;
int max_iterations = config->iterations;
try {
check_is_open(infile, training_file);
check_is_non_empty(infile, training_file);
} catch (...) {
throw;
}
for (int k = 0; k < max_iterations; ++k) {
int word_count = 0, last_count = 0;
infile.clear();
infile.seekg(chunks[chunk_id], infile.beg);
int chunk_size = training_lines / chunks.size();
int sent_id = chunk_id * chunk_size;
string sent;
while (getline(infile, sent)) {
word_count += trainSentence(sent, sent_id++); // asynchronous update (possible race conditions)
// update learning rate
if (word_count - last_count > 10000) {
words_processed += word_count - last_count; // asynchronous update
last_count = word_count;
// decreasing learning rate
alpha = starting_alpha * (1 - static_cast<float>(words_processed) / (max_iterations * training_words));
alpha = max(alpha, starting_alpha * 0.0001f);
if (config->verbose) {
printf("\rAlpha: %f Progress: %.2f%%", alpha, 100.0 * words_processed /
(max_iterations * training_words));
fflush(stdout);
}
}
// stop when reaching the end of a chunk
if (chunk_id < chunks.size() - 1 && infile.tellg() >= chunks[chunk_id + 1])
break;
}
words_processed += word_count - last_count;
}
}
int MonolingualModel::trainSentence(const string& sent, int sent_id) {
auto nodes = getNodes(sent); // same size as sent, OOV words are replaced by <UNK>
// counts the number of words that are in the vocabulary
int words = nodes.size() - count(nodes.begin(), nodes.end(), HuffmanNode::UNK);
if (config->subsampling > 0) {
subsample(nodes); // puts <UNK> tokens in place of the discarded tokens
}
if (nodes.empty()) {
return words;
}
// remove <UNK> tokens
nodes.erase(
remove(nodes.begin(), nodes.end(), HuffmanNode::UNK),
nodes.end());
// Monolingual training
for (int pos = 0; pos < nodes.size(); ++pos) {
trainWord(nodes, pos, sent_id);
}
return words; // returns the number of words processed, for progress estimation
}
void MonolingualModel::trainWord(const vector<HuffmanNode>& nodes, int word_pos, int sent_id) {
if (config->skip_gram) {
trainWordSkipGram(nodes, word_pos, sent_id);
} else {
if (config->learn_attn) {
//std::cout<< "Training word with CBOW Attn" << std::endl;
return trainWordCBOWAttn(nodes,word_pos,sent_id);
} else {
if (config->learn_sentiment) {
return trainWordCBOWSentiment(nodes,word_pos,sent_id,config->gamma);
}
else return trainWordCBOW(nodes, word_pos, sent_id);
}
}
}
void MonolingualModel::trainWordCBOW(const vector<HuffmanNode>& nodes, int word_pos, int sent_id) {
int dimension = config->dimension;
vec hidden(dimension, 0);
HuffmanNode cur_node = nodes[word_pos];
int this_window_size = 1 + multivec::rand() % config->window_size; // reduced window
//int this_window_size = config->window_size;
int count = 0;
for (int pos = word_pos - this_window_size; pos <= word_pos + this_window_size; ++pos) {
if (pos < 0 || pos >= nodes.size() || pos == word_pos) continue;
hidden += input_weights[nodes[pos].index];
++count;
}
if (config->sent_vector) {
hidden += sent_weights[sent_id];
++count;
}
if (count == 0) return;
hidden /= count;
vec error(dimension, 0);
if (config->hierarchical_softmax) {
error += hierarchicalUpdate(cur_node, hidden, alpha);
}
if (config->negative > 0) {
error += negSamplingUpdate(cur_node, hidden, alpha);
}
// update input weights
for (int pos = word_pos - this_window_size; pos <= word_pos + this_window_size; ++pos) {
if (pos < 0 || pos >= nodes.size() || pos == word_pos) continue;
input_weights[nodes[pos].index] += error;
}
if (config->sent_vector) {
sent_weights[sent_id] += error;
}
}
void MonolingualModel::trainWordCBOWSentiment(const vector<HuffmanNode>& nodes, int word_pos, int sent_id, float gamma) {
int dimension = config->dimension;
vec hidden(dimension, 0);
HuffmanNode cur_node = nodes[word_pos];
string word;
int sentiment_index = 3;
int in_sentiment_index = 3;
if (gamma != 0.0) {
word = cur_node.word;
sentiment_index = sentimentIndex(word, sentiment_lexicon);
// for foreign language words, we won't find them so index will be 3 (e.g in merged training)
}
int this_window_size = 1 + multivec::rand() % config->window_size;
//int this_window_size = config->window_size;
int count = 0;
float numerator = 0;
for (int pos = word_pos - this_window_size; pos <= word_pos + this_window_size; ++pos) {
if (pos < 0 || pos >= nodes.size() || pos == word_pos) continue;
hidden += input_weights[nodes[pos].index];
// if updating input sentiment weights also
/*in_sentiment_index = sentimentIndex(nodes[pos].word, sentiment_lexicon);
if (in_sentiment_index <=2 ){
hidden += in_sentiment_weights[in_sentiment_index];
}*/
++count;
}
if (count == 0) return;
hidden /= count;
vec error(dimension, 0); // compute error & update output weights
vec sentiment_error(dimension, 0);
if (config->negative > 0) {
error += negSamplingUpdate(cur_node, hidden, alpha);
// if ((has_lexicon || gamma != 0.0) && sentiment_index <=2)
// for very large corpora, not enough words will hit the lexicon, so sentiment weights may not be updated properly
// maybe it's best if the sentiment embeddings are learned on a small corpus
if (gamma != 0.0 && sentiment_index <= 2) {
//sentiment_error += negSamplingUpdateSentimentSoftmax(cur_node, sentiment_index, hidden, &sentiment_weights, alpha, gamma);
sentiment_error += negSamplingUpdateSentiment(cur_node, sentiment_index, hidden, &sentiment_weights, alpha, gamma);
}
}
// Update input weights
for (int pos = word_pos - this_window_size; pos <= word_pos + this_window_size; ++pos) {
if (pos < 0 || pos >= nodes.size() || pos == word_pos) continue;
input_weights[nodes[pos].index] += error;
// if updating input sentiment weights also
/* in_sentiment_index = sentimentIndex(nodes[pos].word, sentiment_lexicon);
if (in_sentiment_index <= 2) {
in_sentiment_weights[in_sentiment_index] += error;
} */
if (gamma != 0.0 && sentiment_index <= 2) {
input_weights[nodes[pos].index] += sentiment_error;
// if updating input sentiment weights also
/*if (in_sentiment_index <= 2) {
in_sentiment_weights[in_sentiment_index] += sentiment_error;
} */
}
}
}
void MonolingualModel::trainWordCBOWAttn(const vector<HuffmanNode>& nodes, int word_pos, int sent_id) {
int dimension = config->dimension;
vec hidden(dimension, 0);
HuffmanNode cur_node = nodes[word_pos];
int this_window_size = 1 + multivec::rand() % config->window_size; // reduced window
int max_window_size = config->window_size;
int count = 0;
float denominator = 0;
vec a(2*max_window_size);
for (int c =0;c<2*max_window_size;c++) {
a[c]=0;
}
int i=0;
for (int pos = word_pos - max_window_size; pos <= word_pos + max_window_size; ++pos) {
if (pos < 0 || pos >= nodes.size() || pos == word_pos || abs(word_pos-pos) > this_window_size) {
if (pos!=word_pos) { i+=1;}
continue;
}
//hidden += input_weights[nodes[pos].index];
++count;
denominator += exp(attn_weights[nodes[pos].index][i] + attn_bias[i]);
}
int j=0;
for (int pos = word_pos - max_window_size; pos <= word_pos + max_window_size; ++pos) {
if (pos < 0 || pos >= nodes.size() || pos == word_pos || abs(word_pos-pos) > this_window_size) {
if (pos!=word_pos) { j+=1; }
continue;
}
a[j] = exp(attn_weights[nodes[pos].index][j] + attn_bias[j]) / denominator;
hidden += a[j]*input_weights[nodes[pos].index];
j+=1;
}
if (config->sent_vector) {
hidden += sent_weights[sent_id];
++count;
}
if (count == 0) return;
//hidden /= count;
vec error(dimension, 0);
/*if (config->hierarchical_softmax) {
error += hierarchicalUpdateAttn(cur_node, hidden, alpha);
}*/
//MonolingualModel trg_model = *this;
if (config->negative > 0) {
error += negSamplingUpdateAttn(cur_node,nodes,*this,word_pos, this_window_size, hidden, alpha,a, &attn_weights, &attn_bias);
}
// update input weights
int p = 0;
for (int pos = word_pos - max_window_size; pos <= word_pos + max_window_size; ++pos) {
if (pos < 0 || pos >= nodes.size() || pos == word_pos || abs(word_pos-pos) > this_window_size) {
if (pos!=word_pos) { p+=1; }
continue;
}
input_weights[nodes[pos].index] += error;
p+=1;
}
if (config->sent_vector) {
sent_weights[sent_id] += error;
}
}
void MonolingualModel::trainWordSkipGram(const vector<HuffmanNode>& nodes, int word_pos, int sent_id) {
int dimension = config->dimension;
HuffmanNode input_word = nodes[word_pos]; // use this word to predict surrounding words
int this_window_size = 1 + multivec::rand() % config->window_size;
for (int pos = word_pos - this_window_size; pos <= word_pos + this_window_size; ++pos) {
int p = pos;
if (p == word_pos) continue;
if (p < 0 || p >= nodes.size()) continue;
HuffmanNode output_word = nodes[p];
vec error(dimension, 0);
if (config->hierarchical_softmax) {
error += hierarchicalUpdate(output_word, input_weights[input_word.index], alpha);
}
if (config->negative > 0) {
error += negSamplingUpdate(output_word, input_weights[input_word.index], alpha);
}
input_weights[input_word.index] += error;
}
}
vec MonolingualModel::negSamplingUpdate(const HuffmanNode& node, const vec& hidden, float alpha, bool update) {
int dimension = config->dimension;
vec temp(dimension, 0);
for (int d = 0; d < config->negative + 1; ++d) {
int label;
const HuffmanNode* target;
if (d == 0) { // 1 positive example
target = &node;
label = 1;
} else { // n negative examples
target = getRandomHuffmanNode();
if (*target == node) continue;
label = 0;
}
float x = hidden.dot(output_weights[target->index]);
float pred;
if (x >= MAX_EXP) {
pred = 1;
} else if (x <= -MAX_EXP) {
pred = 0;
} else {
pred = sigmoid(x);
}
float error = alpha * (label - pred);
// update for input
temp += error * output_weights[target->index];
// gradient for output
if (update)
output_weights[target->index] += error * hidden;
// also update attn_model[target[pos]] += error * attn_hidden
// attn_hidden passed as parameter (the value we used for K[target[pos]], or the actual attention weight ai?)
}
// temp updates the input weights
return temp;
}
vec MonolingualModel::negSamplingUpdateSentiment(const HuffmanNode& node, int sentiment_index, const vec& hidden,
mat* sentiment_weights, float alpha, float gamma, bool update) {
// This method will update the output sentiment weights
// and also return the error by which to update the input weights
// TODO these changes can be made depending on results:
// 1) Assign sentiment indices to all huffman nodes when initializing vocab
// 2) Have the neg sampling update for sentiment and words on the same samples (I think not)
// 3) MAYBE THIS Use softmax for sentiment instead of sigmoid since it's just 3 labels (let's see how well it does)
// 4) MAYBE THIS Right now, this only works if we assume that gamma is 0 for target language models. Otherwise,
// we need to get the sentiment for the negative target samples as well.
// 5) Negative sample words of all possible sentiments rather than only for different sentiment (I think not)
int dimension = config->dimension;
vec temp(dimension, 0);
int index_sample;
int neg_samples = config->negative;
//int neg_samples = 10;
for (int d = 0; d < neg_samples + 1; ++d) {
int label;
int label_s;
const HuffmanNode* target;
if (d == 0) { // 1 positive example
target = &node;
label = 1;
index_sample = sentiment_index;
} else { // n negative examples
target = getRandomHuffmanNode();
// assumes for now that this function only gets called for source language words
// otherwise, we have to pre-store the alignments of all sentences
// better would be to sample sentiment in the same proportion that it appears for the source words
index_sample = sentimentIndex(target->word, sentiment_lexicon);
if (*target == node) continue;
// Don't sample it if it has the same sentiment or if it has none sentiment
if (index_sample == sentiment_index || index_sample == 3) continue;
label = 0;
// TODO assign sentiment index in the beginning to all nodes and call it with Huffman?
// do it if the approach works, for now just call sentiment index
}
float x = hidden.dot((*sentiment_weights)[index_sample]);
float pred;
if (x >= MAX_EXP) {
pred = 1;
} else if (x <= -MAX_EXP) {
pred = 0;
} else {
pred = sigmoid(x);
}
// the sentiment index should be correct for the negative samples. Do they have to be the same negative samples as
// in the sentiment training? (in the same negative sampling function?)
// I think they don't have to be, it might even be better if sentiment information is learnt 'independently'
// so keep it separate for now
float error = alpha * gamma * (label - pred);
// update for input
temp += error * (*sentiment_weights)[index_sample];
// gradient for output
if (update)
(*sentiment_weights)[index_sample] += error * hidden;
//output_weights[target->index] += error * hidden;
}
// temp updates the input weights
return temp;
}
vec MonolingualModel::negSamplingUpdateSentimentSoftmax(const HuffmanNode& node, int sentiment_index, const vec& hidden,
mat* sentiment_weights, float alpha, float gamma, bool update) {
// This method will update the output sentiment weights
// and also return the error by which to update the input weights
// Different from the other negSamplingUpdateSentiment, it will use softmax objective to
// compute the error and update the weights. Currently, everything else is the same.
// TODO these changes can be made depending on results:
// 1) Assign sentiment indices to all huffman nodes when initializing vocab
// 2) Have the neg sampling update for sentiment and words on the same samples (I think not)
// 3) MAYBE THIS Use softmax for sentiment instead of sigmoid since it's just 3 labels (let's see how well it does)
// 4) MAYBE THIS Right now, this only works if we assume that gamma is 0 for target language models. Otherwise,
// we need to get the sentiment for the negative target samples as well.
// 5) Negative sample words of all possible sentiments rather than only for different sentiment (I think not)
// 6) Should we randomly select a sentiment label instead of a Huffman node?
// or loop and apply neg sampling it to all sentiment labels? (yes, try this next)
// 7) Try to align and do it with all 4 models so the weights are stronger, or put lambda * 2, or more samples for the
// less frequent classes
int dimension = config->dimension;
vec temp(dimension, 0);
int index_sample;
int N = (*sentiment_weights).size();
for (int d = 0; d < N; ++d) {
int label;
//const HuffmanNode* target;
if (d == sentiment_index) { // 1 positive example
//target = &node;
label = 1;
//index_sample = sentiment_index;
} else { // n negative examples. For sentiment, we could just use all negative samples
//target = getRandomHuffmanNode();
//target = &node;
// assumes for now that this function only gets called for source language words
//index_sample = sentimentIndex(target->word, sentiment_lexicon);
//if (*target == node) continue;
// Don't negative sample it if it has the same sentiment or if it has none sentiment
//if (index_sample == sentiment_index || index_sample == 3) continue;
label = 0;
}
float x = hidden.dot((*sentiment_weights)[d]);
float pred;
if (x >= MAX_EXP) {
pred = 1;
} else if (x <= -MAX_EXP) {
pred = 0;
} else {
pred = sigmoid(x);
}
//float pred = softmax(hidden, sentiment_weights, d , N);
//float pred = softmax(hidden, sentiment_weights, index_sample, N);
//cout << "softmax pred: " << pred << endl;
/*float error_true = label - pred;
float error_negative = -pred; // actually this is already being done because label is 0 for negative samples
float error;*/
float error = alpha * gamma * (label - pred);
/*if (d==0) {
// updating for true samples
//error = label - pred;
error = error_true;
} else {
// updating for negative samples
// TODO see if I computed derivatives right
error = error_negative;
//error = -pred;
}*/
// error = error * alpha * gamma;
// update for input
temp += error * (*sentiment_weights)[d];
// Update sentiment weights
if (update) {
(*sentiment_weights)[d] += error * hidden;
// float update_error;
/*for (int j=0; j < N; j++) {
if (j==index_sample) {
update_error = error_true;
//error = label - pred;
} else{
update_error = error_negative;
//error = -pred;
}
(*sentiment_weights)[j] += update_error * hidden;
}*/
}
// gradient for output
//if (update)
//(*sentiment_weights)[index_sample] += error * hidden;
}
// temp updates the input weights
return temp;
}
vec MonolingualModel::negSamplingUpdateAttn(const HuffmanNode& node, const vector<HuffmanNode>& trg_nodes, const MonolingualModel& trg_model, int trg_pos, int this_window_size,
const vec& hidden, float alpha, const vec& a, mat* k, vec* s, bool update) {
int dimension = config->dimension;
vec temp(dimension, 0);
for (int d = 0; d < config->negative + 1; ++d) {
int label;
const HuffmanNode* target;
if (d == 0) { // 1 positive example
target = &node;
label = 1;
} else { // n negative examples
target = getRandomHuffmanNode();
if (*target == node) continue;
label = 0;
}
float x = hidden.dot(output_weights[target->index]);
float pred;
if (x >= MAX_EXP) {
pred = 1;
} else if (x <= -MAX_EXP) {
pred = 0;
} else {
pred = sigmoid(x);
}
float error = alpha * (label - pred);
temp += error * output_weights[target->index];
// update for input
int size_a = static_cast<int>(a.size());
int max_window = size_a/2;
float const_term = label - pred;
int i=0;
int j=0;
for (int pos= trg_pos - max_window; pos <= trg_pos + max_window ; ++pos) {
//int error_attn = 0;
if (pos < 0 || pos >= trg_nodes.size() || pos == trg_pos || abs(trg_pos - pos) > this_window_size) {
if (pos != trg_pos) { i+=1;}
continue;
}
float y = trg_model.input_weights[trg_nodes[pos].index].dot(output_weights[target->index]);
//Update attention matrix for each position/context word
j=0;
for (int context_pos= trg_pos - max_window; context_pos <= trg_pos + max_window; ++context_pos) {
if (context_pos < 0 || context_pos >= trg_nodes.size() || context_pos == trg_pos || abs(trg_pos - context_pos) > this_window_size) {
if (context_pos != trg_pos) j+=1;
continue;
}
int error_attn = 0;
if (i==j){ // for this pos
if (pos != context_pos) {
std::cout << "context pos should equal pos!" << std::endl;
return 0;
}
error_attn = a[i]*(1-a[j]);
error_attn = error_attn * y;
} else { // for context_pos
error_attn = -a[i]*a[j];
error_attn = error_attn * trg_model.input_weights[trg_nodes[context_pos].index].dot(output_weights[target->index]);
// FOR 2 LOOP: this will be error_attn = error_attn * y
}
error_attn = error_attn * const_term;
error_attn = error_attn * alpha;
(*s)[j] += error_attn;
(*k)[trg_nodes[context_pos].index][j] += error_attn;
j+=1;
}
/*for (int j=0; j<size_a; j++) {
int error_attn = 0;
if (i==j){
error_attn += a[i]*(1-a[j]);
} else {
error_attn += -a[i]*a[j];
}
error_attn = error_attn * y;
error_attn = error_attn * const_term;
error_attn = error_attn * alpha;
(*s)[j] += error_attn;
(*k)[trg_nodes[pos].index][j] += error_attn;
}*/
i+=1;
}
if (update)
output_weights[target->index] += error * hidden;
}
// temp is alpha * Co(w) * (label-pred)
return temp;
}
/*vec MonolingualModel::negSamplingContextUpdate(const HuffmanNode& node,const HuffmanNode& contextList, const vec& hidden, float alpha, bool update) {
int dimension = config->dimension;
vec temp(dimension, 0);
for (int d = 0; d < config->negative + 1; ++d) {
int label;
const HuffmanNode* target;
if (d == 0) { // 1 positive example
target = &node;
label = 1;
} else { // n negative examples
target = getRandomHuffmanNode();
if (*target == node) continue;
label = 0;
}
float x = hidden.dot(output_weights[target->index]);
float pred;
if (x >= MAX_EXP) {
pred = 1;
} else if (x <= -MAX_EXP) {
pred = 0;
} else {
pred = sigmoid(x);
}
float error = alpha * (label - pred);
temp += error * output_weights[target->index];
if (update)
output_weights[target->index] += error * hidden;
}
return temp;
}*/
/*
vec MonolingualModel::hierarchicalContextUpdate(const HuffmanNode& node, const HuffmanNode& contextList, const vec& hidden,
float alpha, bool update) {
}
*/
vec MonolingualModel::hierarchicalUpdate(const HuffmanNode& node, const vec& hidden,
float alpha, bool update) {
int dimension = config->dimension;
vec temp(dimension, 0);
for (int j = 0; j < node.code.size(); ++j) {
int parent_index = node.parents[j];
float x = hidden.dot(output_weights_hs[parent_index]);
if (x <= -MAX_EXP || x >= MAX_EXP) {
continue;
}
float pred = sigmoid(x);
float error = -alpha * (pred - node.code[j]);
temp += error * output_weights_hs[parent_index];
if (update)
output_weights_hs[parent_index] += error * hidden;
}
return temp;
}
vector<pair<string, int>> MonolingualModel::getWords() const {
vector<pair<string, int>> res;
for (auto it = vocabulary.begin(); it != vocabulary.end(); ++it) {
res.push_back({it->second.word, it->second.count});
}
return res;
}
vec MonolingualModel::hierarchicalUpdateAttn(const HuffmanNode& node, const vector<HuffmanNode>& trg_nodes, const MonolingualModel& trg_model, int trg_pos, const vec& hidden, float alpha, const vec& a, mat* k, vec* s, bool update) {
int dimension = config->dimension;
vec temp(dimension, 0);
for (int j = 0; j < node.code.size(); ++j) {
int parent_index = node.parents[j];
float x = hidden.dot(output_weights_hs[parent_index]);
if (x <= -MAX_EXP || x >= MAX_EXP) {
continue;
}
float pred = sigmoid(x);
float error = -alpha * (pred - node.code[j]);
temp += error * output_weights_hs[parent_index];
int size_a = static_cast<int>(a.size());
int this_window = size_a/2;
//float const_term = 1/size_a * output_weights_hs[parent_index].dot(input_weights[parent_index]);
float const_term = - 1/size_a * (pred - node.code[j]);
/*for (int i=0; i<size_a; i++) {
int error_attn = 0;
for (int w=0; w<size_a; w++) {
if (i==w){
error_attn += a[i]*(1-a[w]);
} else {
error_attn += -a[i]*a[w];
}
error_attn = error_attn * const_term;
error_attn = error_attn * alpha;
s[i] += error_attn;
k[parent_index][i] += error_attn;
}
}*/
int i=0;
for (int pos= trg_pos - this_window; pos <= trg_pos + this_window ; ++pos) {
if (pos < 0 || pos >= trg_nodes.size() || pos == trg_pos) continue;
// Update attention matrix for each position
// Check, might be wrong
for (int p =0; p< trg_nodes[pos].code.size(); ++p) {
int context_index = trg_nodes[pos].parents[p];
float y = trg_model.input_weights[context_index].dot(output_weights_hs[parent_index]);
for (int z=0; z<size_a; z++) {
int error_attn = 0;
if (i==z){
error_attn += a[i]*(1-a[z]);
} else {
error_attn += -a[i]*a[z];
}
error_attn = error_attn * y;
error_attn = error_attn * const_term;
error_attn = error_attn * alpha;
(*s)[z] += error_attn;
// k[context] should be updated not k[center]
(*k)[trg_nodes[pos].index][z] += error_attn;
}
}
i+=1;
}
if (update)
output_weights_hs[parent_index] += error * hidden;
}
return temp;
}
void MonolingualModel::saveSentimentVectors(const string &filename, int policy) const {
if (config->verbose)
std::cout << "Saving sentiment vectors in text format to " << filename << std::endl;
std::cout << "Policy: " << policy << std::endl;
ofstream outfile(filename, ios::binary | ios::out);
try {
check_is_open(outfile, filename);
} catch (...) {
throw;
}
int index = 0;
int d = config->dimension;
int s = sizeof(sentiment_labels)/sizeof(sentiment_labels[0]);
outfile << s << " " << d << endl;
for (auto it = sentiment_weights.begin(); it != sentiment_weights.end(); ++it) {
std::cout << "index: " << index << " ";
string label = sentimentLabel(index);
std::cout << "label: " << label << endl;
outfile << label << " ";
vec embedding = *it; // by default, sentiment output weights
/* if (policy == 0){
// only input sentiment weights
embedding = in_sentiment_weights[index];
}
else if (policy == 2) {
// sum
embedding += in_sentiment_weights[index];
}*/
for (int c = 0; c < config->dimension; ++c) {
outfile << embedding[c] << " ";
}
outfile << endl;
index +=1;
}
}
| true |
8d769cf35dbf11e01ac5e53c3124ed4b63d1feb6 | C++ | Ph0en1xGSeek/ACM | /POJ & HDU/Find_a_multiple.cpp | UTF-8 | 938 | 2.59375 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;
int arr[10010];
int sum[10010];
int vis[10010];
int main()
{
int n, from = 0, to = 1;
int flag;
arr[0] = sum[0] = 0;
memset(vis, -1, sizeof(vis));
vis[0] = 0;
while(~scanf("%d", &n))
{
flag = 0;
for(int i = 1; i <= n; i++)
{
scanf("%d", &arr[i]);
sum[i] = (sum[i-1] + arr[i]) % n;
if(flag == 0)
{
if(vis[sum[i]] != -1)
{
from = vis[sum[i]];
to = i;
flag = 1;
}
else
vis[sum[i]] = i;
}
}
printf("%d\n", to - from);
for(int i = from + 1; i <= to; i++)
printf("%d\n", arr[i]);
}
return 0;
}
| true |
3a1176eae644fe7796e67e2ab1b96af6e0039a83 | C++ | PeterSommerlad/talks_public | /ACCU/2021/ModernCppWorkshop/workspace/BoundedBufferComplete/src/MemoryOperationCounter.h | UTF-8 | 1,822 | 3.359375 | 3 | [] | no_license |
#ifndef MEMORYOPERATIONCOUNTER_H_
#define MEMORYOPERATIONCOUNTER_H_
struct MemoryOperationCounter {
MemoryOperationCounter() = default;
MemoryOperationCounter(unsigned moves, unsigned copies, bool known_state) :
moves { moves }, copies { copies }, known_state { known_state } {
}
MemoryOperationCounter(MemoryOperationCounter && source) :
moves { std::move(source.moves) }, copies { std::move(source.copies) }, known_state { std::move(source.known_state) } {
moves++;
source.known_state = false;
}
MemoryOperationCounter & operator=(MemoryOperationCounter && source) & noexcept {
copyFrom(source);
moves++;
source.known_state = false;
return *this;
}
MemoryOperationCounter(MemoryOperationCounter const & source) :
moves { std::move(source.moves) }, copies { std::move(source.copies) }, known_state { std::move(source.known_state) } {
copies++;
}
MemoryOperationCounter & operator=(MemoryOperationCounter const & source) & noexcept {
copyFrom(source);
copies++;
return *this;
}
bool operator==(MemoryOperationCounter const & other) const {
return (moves == other.moves) && (copies == other.copies) == (known_state == other.known_state);
}
void print(std::ostream & os) const {
os << "MemoryOperationsCounter{moves: " << moves << ", copies: " << copies << ", known_state: " << known_state << "}\n";
}
private:
unsigned moves { 0 };
unsigned copies { 0 };
bool known_state { true };
void copyFrom(MemoryOperationCounter const & source) {
moves = source.moves;
copies = source.copies;
known_state = source.known_state;
}
};
inline std::ostream & operator <<(std::ostream & os, MemoryOperationCounter const & counter) {
counter.print(os);
return os;
}
#endif /* MEMORYOPERATIONCOUNTER_H_ */
| true |
fab1d65713543ad45c16f66bd0320a357536f42c | C++ | vishaldotkhanna/Coding-Practice | /sorted_insertion_ll.cpp | UTF-8 | 1,695 | 3.703125 | 4 | [] | no_license | #include<iostream>
#include<vector>
#include<cmath>
#include<algorithm>
#include<bitset>
#define MAX_SIZE 500
using namespace std;
typedef long long LL;
//Sorted insertion in Linked List.
struct node
{
int data;
struct node* next;
} *start, *ptr, *prev, *cur;
int insert_back(int val)
{
ptr = new struct node;
ptr->data = val;
ptr->next = NULL; //Since the element is to be inserted at te end, it will always point to null.
if(start == NULL) //Empty list.
{
start = ptr;
return 0;
}
cur = start;
while(cur->next != NULL)
cur = cur->next;
cur->next = ptr;
return 0;
}
int print_LL()
{
if(start == NULL)
cout<<"List is empty.";
else
{
cur = start;
while(cur != NULL)
{
cout<<cur->data<<" ";
cur = cur->next;
}
cout<<endl;
}
return 0;
}
int insert_sorted(int val)
{
ptr = new struct node;
ptr->data = val;
if(start == NULL)
{
start = ptr;
ptr->next = NULL;
}
else if(val < start->data) //Insertion at the front.
{
ptr->next = start;
start = ptr;
}
else
{
cur = prev = start;
while(cur != NULL && cur->data <= val)
{
prev = cur;
cur = cur->next;
}
ptr->next = prev->next; //Insertion after prev.
prev->next = ptr;
}
return 0;
}
int main()
{
int arr[] = {1, 2, 3, 7, 8};
for(int i = 0;i < 5;i++)
insert_back(arr[i]);
int n;
while(cin)
{
cin>>n;
insert_sorted(n);
print_LL();
}
return 0;
}
| true |
6560a8627e53cfe0ab0795cf17778916754e65df | C++ | dekrain/I-made-a-LISP | /src/printer.cpp | UTF-8 | 4,888 | 2.71875 | 3 | [] | no_license | #include "printer.hpp"
#include <sstream>
namespace mal {
Printer& OstreamPrinter::operator<<(print_begin_t beg) { is_raw = beg.print_raw; return *this; }
Printer& OstreamPrinter::operator<<(print_end_t) { stream << std::endl; return *this; }
Printer& OstreamPrinter::operator<<(const std::string& str) { stream << str; return *this; }
Printer& OstreamPrinter::operator<<(const MalValue& value) {
switch (value.tag) {
case Nil_T:
stream << "nil";
break;
case True_T:
stream << "true";
break;
case False_T:
stream << "false";
break;
case Int_T:
stream << value.no;
break;
case Symbol_T:
stream << value.st->Get();
break;
case Keyword_T:
stream << ":" << value.st->Get();
break;
case String_T:
if (is_raw)
stream << value.st->Get();
else
stream << EscapeString(value.st->Get());
break;
case List_T:
case Vector_T:
{
stream << (value.tag == List_T ? '(' : '[');
bool first = true;
for (const MalList* list = value.li.get(); list != nullptr; list = list->Rest().get()) {
if (!first) {
stream << ' ';
}
first = false;
operator<<(list->First());
}
stream << (value.tag == List_T ? ')' : ']');
break;
}
case Map_T:
case MapSpec_T:
{
auto map = mh::as_map(value);
stream << '{';
bool first = true;
for (auto it = map->data.begin(); it != map->data.end(); ++it) {
if (!first)
stream << ' ';
first = false;
operator<<(it->first);
stream << ' ';
operator<<(it->second.v);
}
stream << '}';
break;
}
case Builtin_T:
stream << "<builtin-function>";
break;
case Function_T:
stream << "<function>";
break;
case Atom_T:
stream << "<atom ";
operator<<(value.at->v);
stream << '>';
break;
default:
stream << "<unknown>";
}
return *this;
}
Printer& TTYPrinter::operator<<(const MalValue& value) {
if (is_raw)
return _Base::operator<<(value);
switch (value.tag) {
case Nil_T:
stream << TTYColors::nil << "nil" << TTYColors::reset;
break;
case True_T:
stream << TTYColors::boolean << "true" << TTYColors::reset;
break;
case False_T:
stream << TTYColors::boolean << "false" << TTYColors::reset;
break;
case Int_T:
stream << TTYColors::number << value.no << TTYColors::reset;
break;
case Keyword_T:
stream << TTYColors::keyword << ":" << value.st->Get() << TTYColors::reset;
break;
case String_T:
//if (is_raw)
// stream << value.st->Get();
//else
stream << TTYColors::string << EscapeString(value.st->Get()) << TTYColors::reset;
break;
case Symbol_T:
case List_T:
case Vector_T:
case Map_T:
case MapSpec_T:
case Builtin_T:
case Function_T:
case Atom_T:
default:
return _Base::operator<<(value);
}
return *this;
}
std::string EscapeString(const std::string& str) {
std::string res;
std::size_t i = 0;
while (i < str.length()) {
std::size_t next = str.find_first_of("\\\n\"", i);
if (next != i) {
if (next == str.npos)
res += str.substr(i);
else
res += str.substr(i, next-i);
}
i = next;
if (i != str.npos) {
char ch = str[i++];
if (ch == '\\')
res += "\\\\";
else if (ch == '\n')
res += "\\n";
else if (ch == '"')
res += "\\\"";
}
}
return '"' + res + '"';
}
} | true |
223f789524c2e4c1cbc29dc24055e148b39fb4cc | C++ | LH-2017/cpp_example | /do_whie/d.cpp | UTF-8 | 489 | 2.84375 | 3 | [] | no_license | #include <stdio.h>
int main()
{
//int inside = 10;
int out = 10;
do
{
//out--;
int inside = 10;
do
{
switch (out)
{
case 1:
switch (inside)
{
case 5:
printf("*");
break;
default:
printf(" ");
}
inside--;
}
/*switch (inside)
{
case 5:
case 6:
printf(" ");
break;
default:
printf("*");
}
inside--;*/
} while (inside > 0);
printf("\n");
out--;
} while (out>0);
return 0;
} | true |
6e9f77f9230c3df02fa288a5c3bd8e0bafa53e2d | C++ | kromero16/blackjack-1 | /blackjack/blackjack/game.h | UTF-8 | 784 | 2.625 | 3 | [] | no_license | //
// game.h
//
// Projeto 2 PROG
//
// Turma 6 Grupo 4
//
// Diogo Eiras - ei11087
// IDE - Eclipse, Visual Studio
//
// Pedro Fernandes - ei11122
// IDE - Xcode
//
#ifndef game_h
#define game_h
#include <vector>
#include "player.h"
#include "round.h"
#include "dealer.h"
class Game{
vector<Player> players;
int nextPlayerWaiting;
vector<Player*> active_players;
vector<Player*> players_entered_round;
Dealer dealer;
House gameDeck;
float minimBet;
Player* winner;
public:
Game();
bool addPlayer(string, float);
bool setMinimBet(float);
bool over();
Round* playRound();
Player* getWinner();
vector<Player*> getPlayersEnteredThisRound();
vector<Player*> getActivePlayers();
vector<Player> getPlayers();
};
#endif
| true |
d153b01aa6c40a53145a5c15c61a9f4e10c7f25d | C++ | calvin456/intro_derivative_pricing | /cpp_dsgn_pattern_n_derivatives_pricing/chapter11/exercise/exercise/main.cpp | UTF-8 | 2,955 | 2.71875 | 3 | [
"MIT"
] | permissive | /*
//ex 11.1 Implement the factory from chap. 10 using the monostate pattern
//instead of the Singleton pattern
Compare implementation of book example, curiuosly recurring template pattern , and monostate pattern
*/
#include <string>
#include <iostream>
#include <memory>
#include<SimpleMC8.h>
#include<ParkMiller.h>
#include<Vanilla3.h>
#include<MCStatistics.h>
#include<ConvergenceTable.h>
#include<AntiThetic.h>
#include <PayOff3.h>
#include <PayOffBridge.h>
#include "PayOffConstructibleMono.h"
#include "PayOffFactoryMono.h"
#include <PayOffFactory.h>
#include <PayOffConstructible.h>
#include "PayOffConstructibleCRTP.h"
#include "PayOffFactoryCRTP.h"
using namespace std;
int main()
{
double Expiry;
double Strike;
double Spot;
double Vol;
double r;
unsigned long NumberOfPaths;
cout << "\nEnter expiry\n";
cin >> Expiry;
cout << "\nStrike\n";
cin >> Strike;
cout << "\nEnter spot\n";
cin >> Spot;
cout << "\nEnter vol\n";
cin >> Vol;
cout << "\nr\n";
cin >> r;
cout << "\nNumber of paths\n";
cin >> NumberOfPaths;
string name;
cout << "\npay-off name\n";
cin >> name;
MJArray args(1); args[0] = Strike;
//Singleton - Meyers singleton
PayOff* PayOffPtr = PayOffFactory::Instance().CreatePayOff(name, args);
//Monostate
unique_ptr<PayOff> PayOffPtr1 = PayOffFactoryMono().CreatePayOff(name, args);
//14.2 Singleton + CRTP
PayOff* PayOffPtr2 = PayOffFactoryCRTP::Instance().CreatePayOff(name, args);
VanillaOption1 theOption(PayOffPtr, Expiry);
VanillaOption1 theOption1(PayOffPtr1, Expiry);
VanillaOption1 theOption2(PayOffPtr2, Expiry);
ParametersConstant VolParam(Vol);
ParametersConstant rParam(r);
StatisticsMean gatherer_mean;
StatisticsSE gatherer_se;
vector<Wrapper<StatisticsMC>> stat_vec;
stat_vec.resize(2);
stat_vec[0] = gatherer_mean;
stat_vec[1] = gatherer_se;
StatsGatherer gathererOne(stat_vec);
//Generate convergence table
ConvergenceTable gatherer(gathererOne);
RandomParkMiller generator(1);
AntiThetic GenTwo(generator);
SimpleMonteCarlo6_(theOption, Spot, VolParam, rParam, NumberOfPaths, gatherer, GenTwo);
GenTwo.Reset();
ConvergenceTable gatherer1(gathererOne);
SimpleMonteCarlo6_(theOption1, Spot, VolParam, rParam, NumberOfPaths, gatherer1, GenTwo);
GenTwo.Reset();
ConvergenceTable gatherer2(gathererOne);
SimpleMonteCarlo6_(theOption2, Spot, VolParam, rParam, NumberOfPaths, gatherer2, GenTwo);
vector<vector<double> > results = gatherer.GetResultsSoFar();
vector<vector<double> > results1 = gatherer1.GetResultsSoFar();
vector<vector<double> > results2 = gatherer2.GetResultsSoFar();
cout << "\nFor the " << name << " price the results are \n";
cout << "with antithetic variables \n";
cout << "mean\t se\t path\n";
for (unsigned long i = 0; i < results1.size(); i++)
{
for (unsigned long j = 0; j < results1[i].size(); j++)
cout << results1[i][j] << " ";
cout << "\n";
}
double tmp;
cin >> tmp;
return 0;
} | true |
10610247846db6481d509293af71e342e0230afe | C++ | savvynavi/Intro-to-cpp | /Inheritance/inheritance question 1/inheritance question 1/bike.cpp | UTF-8 | 1,808 | 3.46875 | 3 | [] | no_license | #include"vehicle.h"
#include"bike.h"
#include<iostream>
using namespace std;
//Default Constructor
Bike::Bike(){
setPowered(true);
setWheelNum(2);
setSpeed(0);
setMotorised(false);
setSeatNum(1);
setType("land");
setBasketWeight(5);
setSeatNum(1);
setWindowNum(0);
}
//Destructor
Bike::~Bike(){
}
//gets the current weight in the basket on the front of the bike
const int Bike::getBasketWeight(){
return m_weight;
}
//sets the weight of the basket as long as it's not negative
void Bike::setBasketWeight(int weight){
if(weight >= 0){
m_weight = weight;
}else{
m_weight = 0;
}
}
const void Bike::adjustSeat(){
cout << "\nYou adjust the seat slightly\n";
}
//overriding the base class setWheelNum() so that it can't change from 2
void Bike::setWheelNum(int wheelNum){
if(wheelNum != 2){
cout << "\nBike can't have anything other than 2 wheels\n";
m_wheelNum = 2;
}
else{
m_wheelNum = wheelNum;
}
}
//override base class setMotorised() so that the car always returns false
void Bike::setMotorised(bool motor){
if(motor == true){
cout << "\nthis isn't a motorbike\n";
m_motor = false;
}
else{
m_motor = motor;
}
}
//Bikes can't not be powered, always sets it to true
void Bike::setPowered(bool powered){
if(powered == false){
cout << "\nbike can't be unpowered unless you aren't using it\n";
m_powered = true;
}else{
m_powered = powered;
}
}
//checks to see if the bike is moving
const void Bike::isMoving(){
if(getSpeed() > 0){
cout << "\nThe bike is currently moving at " << getSpeed() << "km/h\n";
}
else{
cout << "\nThe vehicle is currently not moving\n";
}
}
//sets the number of windows, as long as 0
void Bike::setWindowNum(int winNum){
if(winNum == 0){
m_winNum = winNum;
}
else{
cout << "\nERROR bikes don't have windows\n";
}
}
| true |
8f58f5a4e88fb3cddd9ed9a16de8c0c6c35354cd | C++ | shantanu092/Voice-Controlled-Car | /voice_BT_Car/voice_BT_Car.ino | UTF-8 | 1,572 | 3.171875 | 3 | [] | no_license | String voice;
void setup()
{
Serial.begin(9600); //start serial communication
pinMode(10,OUTPUT);
pinMode(11,OUTPUT);
pinMode(12,OUTPUT);
pinMode(13,OUTPUT);
pinMode(1,OUTPUT);
pinMode(0,INPUT);
pinMode(8,OUTPUT);
}
void loop()
{
while (Serial.available()){ //Check if there is an available byte to read
delay(10); //Delay added to make thing stable
char c = Serial.read(); //Conduct a serial read
if (c == '#') {break;} //Exit the loop when the # is detected after the word
voice += c; //Shorthand for voice = voice + c
}
if (voice.length() > 0){
if(voice == "*forward"){
digitalWrite(10,HIGH);
digitalWrite(11,LOW );
digitalWrite(12,LOW );
digitalWrite(13,HIGH );
}
else if(voice == "*backward"){
digitalWrite(10,LOW);
digitalWrite(11,HIGH );
digitalWrite(12,HIGH );
digitalWrite(13,LOW );
}
else if(voice == "*right") {
digitalWrite(10,LOW );
digitalWrite(11,HIGH);
digitalWrite(12,LOW );
digitalWrite(13,HIGH); /*right*/
}
else if(voice == "*left") {
digitalWrite(10,HIGH );
digitalWrite(11,LOW);
digitalWrite(12,HIGH );
digitalWrite(13,LOW); /*left*/
}
else if(voice == "*light on") {
digitalWrite(8,HIGH);
}
else if(voice == "*light off") {
digitalWrite(8,LOW);
}
else if(voice == "*stop") {
digitalWrite(10,LOW );
digitalWrite(11,LOW);
digitalWrite(12,LOW );
digitalWrite(13,LOW);
}
voice=""; //Reset the variable after initiating
}
}
| true |
884354ac9f38e2c91ed758fa11d33bdaed2661c0 | C++ | Smartuil/Study-CPP | /studyC++/函数指针语法基础.cpp | GB18030 | 2,007 | 3.65625 | 4 | [] | no_license | #define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//ָ룺һָ룬ʲôָأָָ롣int (*p)[4];
//ָ飺һ飬ʲôأװָ顣int *p[3];
void main1() {
int a[10];//aԪصĵַ &aĵַ a+1 4 &a+1һ40
{
//һ
typedef int(myTypeArray)[10];
myTypeArray myArray;
myArray[0] = 10;
printf("%d\n", myArray[0]);
}
{
//һָ
typedef int(*pTypeArray)[10];//int *p;
pTypeArray myPArray;//sizeof(int)*10
myPArray = &a;
//int b = 10;
//int *p = NULL;
//p = &b;
(*myPArray)[0] = 20;
printf("%d\n", a[0]);
}
{
//һָ͵ָ ָ
int (*MtPointer)[10];// C ҷڴ
MtPointer = &a;
(*MtPointer)[0] = 40;
printf("%d\n", a[0]);
}
}
//ָ
//1 ζһ
//2 ζһָ
//3 ζһָ ָһڵַ
int add(int a, int b) {
printf("func add......\n");
return a + b;
}
void main() {
add(1, 2);//ֱӵ Ǻڵַ
{
//1 һ
typedef int(MyFuncTtype)(int a, int b);
MyFuncTtype *myPointerFunc = NULL;//һָ ָijһĺ
myPointerFunc = &add;
myPointerFunc(3, 4);//ӵ
myPointerFunc = add;//û&Ҳܱͨ C ʷ汾ԭ
}
{
//2 һָ
typedef int (*MyPointerFuncTtype)(int a, int b);//int * a=NULL;
MyPointerFuncTtype myPointerFunc;
myPointerFunc = add;
myPointerFunc(4, 6);
}
{
//3 һָ ָһڵַ
int(*MyPointerFunc)(int a, int b);
MyPointerFunc = add;
MyPointerFunc(3, 6);
}
} | true |
8b1668e739b66af7f3426a03bae5546d7155ed93 | C++ | socc-io/algostudy | /baekjoon/smilu/2577.cpp | UTF-8 | 247 | 2.75 | 3 | [] | no_license | #include <cstdio>
int cnt[10];
int main(void)
{
int val = 1, tmp;
for(int i = 0; i < 3; ++i) {
scanf("%d", &tmp);
val *= tmp;
}
while(val) {
cnt[val % 10]++;
val /= 10;
}
for(int i = 0; i < 10; ++i) {
printf("%d\n", cnt[i]);
}
} | true |
6675cdbcba289c10cd2efeb9edb0d2ddf8d987fe | C++ | brunovergilio/Vulkan-Demos | /Vulkan/Internal/VulkanRenderer/VertexLayout.h | UTF-8 | 1,069 | 2.734375 | 3 | [] | no_license | #pragma once
#include "BvMath.h"
#include "VulkanUtils.h"
enum BvVertexLayout : uint32_t
{
BV_VERTEX_POSITION = 0x1, // 3 floats
BV_VERTEX_COLOR = 0x2, // 4 floats
BV_VERTEX_TEXCOORD = 0x4, // 2 floats
BV_VERTEX_NORMAL = 0x8, // 3 floats
BV_VERTEX_TANGENT = 0x10, // 3 floats
BV_VERTEX_BITANGENT = 0x20, // 3 floats
BV_VERTEX_BLEND_INDICES = 0x40, // 4 unsigned ints
BV_VERTEX_BLEND_WEIGHTS = 0x80 // 3 floats (don't need 4, since it's a normalized amount -> w4 = 1.0f - w1 - w2 - w3)
};
struct BvVertexPack
{
BvVertexPack(const float val) : m_Data(val) {}
BvVertexPack(const uint32_t val) : m_Data(val) {}
union pack
{
float asFloat;
uint32_t asUInt;
pack(const float val) : asFloat(val) {}
pack(const uint32_t val) : asUInt(val) {}
} m_Data;
};
constexpr uint32_t g_BvVertexSize = sizeof(BvVertexPack);
typedef std::vector<BvVertexPack> BvVertexList;
template<class uintType>
using BvIndexList = std::vector<uintType>;
uint32_t GetVertexLayoutCount(const uint32_t & layout);
uint32_t GetVertexLayoutSize(const uint32_t & layout); | true |
06779c88e685a1e802469c6af1621eb047b60aa4 | C++ | fmi-lab/oop-kn-2019-group4 | /practicum/Week08_Multiple_Inheritance(21.04)/Solutions/Project/Teacher.cpp | UTF-8 | 809 | 3.21875 | 3 | [] | no_license | #include "Teacher.h"
#include "Functions.h"
#include "User.h"
#include <iostream>
#include <ostream>
#include <string.h>
Teacher::Teacher(char const * _firstName, char const * _lastName, char const * pass, int _grade)
: User(_firstName, _lastName, pass, "teacher") {
this->grade = _grade;
}
void Teacher::print(std::ostream& out) const {
User::print(out);
out << " Grade: " << grade;
}
void Teacher::create(const char * _type) {
User::create("teacher");
std::cout << "Enter teacher's grade: " << std::endl;
std::cin >> this->grade;
std::cin.get();
}
void Teacher::serialize(std::ostream& out) const {
User::serialize(out);
out << this->grade << " ";
}
void Teacher::deserialize(std::istream& inp) {
User::deserialize(inp);
inp >> this->grade;
}
| true |
f6e0edad0ebe562daa9d38a5c8629de2a0aef5ae | C++ | aleanajla/projek1 | /project1.cpp | UTF-8 | 10,349 | 2.796875 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
struct Node{
char name[25];
char pass[25];
Node *prev, *next;
Node *fsentprev,*fsentnext,*fsenttail;
}*head,*tail;
Node *now,*pantat;
Node *createNode(const char* name,const char* pass){
Node *newNode = (Node*)malloc(sizeof(Node));
strcpy(newNode->name,name);
strcpy(newNode->pass,pass);
newNode->prev = newNode->next = NULL;
newNode->fsentnext = newNode->fsentprev =NULL;
return newNode;
}
void pushSent(const char *name,const char *flag){
Node *temp= createNode(name,flag);
pantat->fsentnext=temp;
temp->fsentprev = pantat;
pantat = temp;
}
void pushHead(const char *name,const char *pass){
Node *temp = createNode(name, pass);
if(!head){
head = tail = temp;
}
else{
head->prev = temp;
temp->next = head;
head = temp;
}
}
void pushTail(const char *name, const char *pass){
Node *temp = createNode(name,pass);
if(!head){
head = tail = temp;
}
else{
tail->next=temp;
temp->prev = tail;
tail = temp;
}
}
void pushMid(const char* name, const char* pass){
if(!head){
Node *temp = createNode(name, pass);
head = tail = temp;
}
else if(strcmp(name, head->name) < 0){
pushHead(name, pass);
}
else if(strcmp(name,tail->name)>0){
pushTail(name,pass);
}
else{
Node *curr = head;
Node *temp = createNode(name,pass);
while(curr->name < name){
curr - curr->next;
}
temp->prev = curr->prev;
temp->next=curr;
curr->prev=temp;
}
}
void popHead(){
if(!head){
return;
}
else if(head== tail){
free(head);
head=NULL;
}
else{
Node *candidateHead = head->next;
head->next = candidateHead->prev = NULL;
free(head);
head = candidateHead;
}
}
void popTail(){
if(!head){
return;
}
else if(head== tail){
free(head);
head=NULL;
}
else{
Node *candidateTail= tail->prev;
candidateTail->next =tail->prev = NULL;
free(tail);
tail = candidateTail;
}
}
//void popMid(int){
// if(!head){
// return;
// }
// else if(value == head->value){
// popHead();
// }
// else if(value == tail->value){
// popTail();
// }
// Node *curr = head
// while(curr && curr->val){
// curr->prev->next = curr->next
// curr->next->prev-curr->prev; /
// curr->prev = curr->next= NULL;
// free(curr);
// curr = NULL;
// }
//}
void registerMenu();
void loginMenu();
void userpage();
void addFriend();
void removeFriend();
void viewInbox();
void viewsentReq();
void addNote();
char username[25];
void mainMenu(){
time_t t;
t=clock();
printf("Oo=====================================oO\n");
printf("\t\tSTUDY NETWORK\n");
printf("Oo=====================================oO\n");
printf("\n");
printf("[All User]\n");
printf("No.\tUsername\n");
Node *curr=head;
int i=1;
while(curr){
printf("%d\t%s\n",i,curr->name);
i++;
curr=curr->next;
}
printf("-----------------------------------------\n");
printf("[1] Register\n");
printf("[2] Login\n");
printf("[3] Exit\n");
printf("-----------------------------------------\n");
printf("Press 0 and enter to abort an operation\n");
printf("-----------------------------------------\n");
printf(">> ");
int menu;
scanf("%d",&menu);
switch(menu){
case 0:{
return;
break;
}
case 1:{
registerMenu();
break;
}
case 2:{
loginMenu();
break;
}
case 3:{
t = clock()-t;
double time_taken = ((double)t)/CLOCKS_PER_SEC;
printf("\nTime spent %.2lf seconds\n",time_taken);
return;
break;
}
}
}
void registerMenu(){
printf("Please type in your password[lowecase || 1..24]: ");
char name[25];
do{
scanf("%s",&name);
getchar();
}while(strlen(name)<1 || strlen(name)>24);
printf("Please type in your password[lowecase || 1..24]: ");
char pass[25];
do{
scanf("%s",&pass);
getchar();
}while(strlen(pass)<1 || strlen(pass)>24);
Node *curr=head;
while(curr){
if(strcmp(name, curr->name) == 0){
printf("\n--- The username has been used! ---");
printf("\nPress enter to continue!\n");
getchar();
system("cls");
mainMenu();
}
curr=curr->next;
}
pushMid(name, pass);
printf("\n");
printf("--- Registration Successfull ---\n");
printf("Press enter to continue!");
getchar();
system("cls");
mainMenu();
}
void loginMenu(){
printf("Username: ");
char name[25];
do{
scanf("%s",&name);
getchar();
}while(strlen(name)<1 || strlen(name)>24);
printf("Password: ");
char pass[25];
do{
scanf("%s",&pass);
getchar();
}while(strlen(pass)<1 || strlen(pass)>24);
Node *curr=tail;
while(curr){
if(strcmp(name, curr->name) == 0 && strcmp(pass, curr->pass) == 0){
printf("\n--- Login Successfull :) ---");
printf("\nPress enter to continue!\n");
//initiliaze
now=curr;
strcpy(username,name);
now->fsenttail=now;
getchar();
system("cls");
userpage();
}
curr=curr->prev;
}
printf("Login unsuccessful\n");
printf("Press enter to continue!");
getchar();
system("cls");
mainMenu();
}
void userpage(){
time_t t;
time(&t);
printf("Oo=====================================oO\n");
printf("Welcome, %s\n", username);
printf("Oo=====================================oO\n");
printf("Logged in: %s", ctime(&t));
printf("\n-----------------------------\n\n");
printf("[All Friends of %s]\n\n",username);
printf("No.\tUsername\n");
printf("-----------------------------\n");
printf("\t>>Menu<<\n");
printf("-----------------------------\n");
printf("[1] Add Friend\n[2] Remove Friend\n[3] View Inbox\n[4] View Sent Request\n[5] Add, Edit, Announce, Delete Note\n[6] Log out\n");
printf("-----------------------------\n");
printf(">> ");
int menu;
scanf("%d",&menu);
switch(menu){
case 1:{
addFriend();
break;
}
case 2:{
removeFriend();
break;
}
case 3:{
viewInbox();
break;
}
case 4:{
viewsentReq();
userpage();
break;
}
case 5:{
addNote();
break;
}
case 6:{
system("cls");
mainMenu();
break;
}
}
}
void addFriend(){
printf("-----------------------------\n\n");
printf("[All User]\n");
printf("No.\tUsername\n");
Node *curr=head;
int i=1;
while(curr){
if(strcmp(curr->name,username)!=0){
printf("%d\t%s\n",i,curr->name);
i++;
}
curr=curr->next;
}
printf("\n\n");
printf("Which user do you want to add?\n");
printf(">> ");
char fname[25];
scanf("%s",fname);
getchar();
Node *curr1=head;
while(curr1){
if(strcmp(fname, curr1->name) == 0){
printf("\n-- Your request has been sent to %s --",fname);
printf("\nPress enter to continue!\n");
pantat=now->fsenttail;
pushSent(fname,"0");
now->fsenttail=pantat;
getchar();
system("cls");
userpage();
}
curr1=curr1->next;
}
printf("-- there is no data in database --\n");
printf("Press enter continue!");
getchar();
system("cls");
userpage();
}
void removeFriend(){
printf("-----------------------------\n\n");
printf("[All Friends of %s]\n",username);
printf("No.\tUsername\n");
Node *curr=head;
int i=1;
while(curr){
if(strcmp(curr->name,username)!=0){
printf("%d\t%s\n",i,curr->name);
i++;
}
curr=curr->next;
}
printf("\n\n");
printf("Which user do you want to remove?\n");
printf(">> ");
char fname[25];
scanf("%s",fname);
getchar();
Node *curr1=head;
while(curr1){
if(strcmp(fname, curr1->name) == 0){
printf("\n-- You are no longer friends with %s --",fname);
printf("\nPress enter to continue!\n");
pantat=now->fsenttail;
pushSent(fname,"0");
now->fsenttail=pantat;
getchar();
system("cls");
userpage();
}
curr1=curr1->next;
}
printf("-- there is no data in database --\n");
printf("Press enter continue!");
getchar();
system("cls");
userpage();
}
void viewInbox(){
printf("-----------------------------\n\n");
printf("[All Friend Requests of %s]\n",username);
printf("No.\tUsername\n");
Node *curr=head;
int i=1;
while(curr){
if(strcmp(curr->name,username)!=0){
printf("%d\t%s\n",i,curr->name);
i++;
}
curr=curr->next;
}
printf("\n\n");
printf("Which user do you want to be accepted?\n");
printf(">> ");
char fname[25];
scanf("%s",fname);
getchar();
Node *curr1=head;
while(curr1){
if(strcmp(fname, curr1->name) == 0){
printf("\n-- You accepted the request from %s --",fname);
printf("\nPress enter to continue!\n");
pantat=now->fsenttail;
pushSent(fname,"0");
now->fsenttail=pantat;
getchar();
system("cls");
userpage();
}
curr1=curr1->next;
}
printf("-- there is no data in database --\n");
printf("Press enter continue!");
getchar();
system("cls");
userpage();
}
void viewsentReq(){
printf("-----------------------------\n\n");
printf("[Sent Request]\n");
printf("No.\tUsername\n");
Node *curr=now;
curr=curr->fsentnext;
int i=1;
while(curr){
printf("%d\t%s\n",i,curr->name);
i++;
curr=curr->fsentnext;
}
printf("press enter to continue!");
getchar();
system("cls");
}
void addNote(){
}
int main(){
mainMenu();
return 0;
}
| true |
69cea8844fe5f82d290ea8edf25b9be8014b4f96 | C++ | DarthObsidian/LearningPython | /Homework8/Stuff/CCSC/Algorithms/queries3.cpp | UTF-8 | 1,082 | 3.65625 | 4 | [] | no_license | #include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>
using namespace std;
class gt_n {
int n;
public:
gt_n(int the_n) {
n = the_n;
}
bool operator()(int m) {
return m > n;
}
};
typedef vector<int>::iterator iter;
void display(iter start, iter pos) {
cout << "found " << *pos << " in position " << pos-start << endl;
}
int main() {
vector<int> a;
copy(istream_iterator<int>(cin), istream_iterator<int>(), back_inserter(a));
iter p = find(a.begin(), a.end(), 3);
if (p != a.end())
display(a.begin(), p);
p = find_if(a.begin(), a.end(), gt_n(10));
if (p != a.end())
display(a.begin(), p);
p = adjacent_find(a.begin(), a.end());
if (p != a.end())
display(a.begin(), p);
cout << "# of 2's: " << count(a.begin(), a.end(), 2) << endl;
cout << "# > 10: " << count_if(a.begin(), a.end(), gt_n(10)) << endl;
}
/* Output:
found 3 in position 7
found 20 in position 2
found 2 in position 3
# of 2's: 2
# > 10: 2
*/
| true |
f9a0e07fbe4a382c83aa616cf4592a001cfe88ff | C++ | c0dysharma/DSA-Practice | /Searching and Sorting/push_zeros.cpp | UTF-8 | 571 | 3.8125 | 4 | [] | no_license |
#include <iostream>
void swap(int& a , int& b){
int temp = b;
b = a;
a = temp;
}
void pushZeros(int arr[], int size){
int count = 0;
for(int i = 0; i<size; i++){
if(arr[i] != 0)
swap(arr[count++], arr[i]);
}
}
int main(void){
int size;
std::cin >> size;
int* arr = new int[size];
for(int i = 0; i<size; i++){
std::cin >> arr[i];
}
pushZeros(arr, size);
for (int i = 0; i < size; i++){
std::cout << arr[i] << ' ';
}std::cout << std::endl;
delete[] arr;
return 0;
} | true |
5a1598efb76fa06ad676b1a73a24bfc42b50f169 | C++ | ARW2705/leet-code-solutions | /solutions/994-M-Rotting-Oranges/main.cpp | UTF-8 | 2,507 | 3.390625 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <vector>
#include <queue>
#include "../../utilities/print-matrix.cpp"
#include "../../utilities/compare-matrices.cpp"
int enqueueNeighbors(std::queue<std::pair<int, int>>& q, std::vector<std::vector<int>>& grid, int row, int col) {
std::vector<std::pair<int, int>> neighbors { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
int newBlockCount = 0;
int newRow;
int newCol;
for (auto neighbor : neighbors) {
newRow = row + neighbor.first;
newCol = col + neighbor.second;
if (newRow >= 0 && newRow < grid.size() && newCol >= 0 && newCol < grid[row].size() && grid[newRow][newCol] == 1) {
grid[newRow][newCol] = 2;
q.push({ newRow, newCol });
++newBlockCount;
}
}
return newBlockCount;
}
int orangesRotting(std::vector<std::vector<int>>& grid) {
std::queue<std::pair<int, int>> q;
int freshOrangeCount = 0;
for (size_t row = 0; row < grid.size(); ++row) {
for (size_t col = 0; col < grid[row].size(); ++col) {
if (grid[row][col] == 1) {
++freshOrangeCount;
} else if (grid[row][col] == 2) {
q.push({ row, col });
}
}
}
if (!freshOrangeCount) {
return 0;
}
int minutes = -1;
int blockSize = q.size();
int nextBlock = 0;
while (!q.empty()) {
for (int i = 0; i < blockSize; ++i) {
std::pair<int, int> rotten = q.front();
q.pop();
nextBlock += enqueueNeighbors(q, grid, rotten.first, rotten.second);
}
blockSize = nextBlock;
freshOrangeCount -= blockSize;
nextBlock = 0;
++minutes;
}
return freshOrangeCount == 0 ? minutes : -1;
}
int main() {
std::vector<std::vector<int>> g1 {
{ 2, 1, 1 },
{ 1, 1, 0 },
{ 0, 1, 1 }
};
int e1 = 4;
int r1 = orangesRotting(g1);
std::cout << "expected 4, got " << r1 << ": " << (e1 == r1 ? "PASS" : "FAIL") << "\n\n";
std::vector<std::vector<int>> g2 {
{ 2, 1, 1 },
{ 0, 1, 1 },
{ 1, 0, 1 }
};
int e2 = -1;
int r2 = orangesRotting(g2);
std::cout << "expected -1, got " << r2 << ": " << (e2 == r2 ? "PASS" : "FAIL") << "\n\n";
std::vector<std::vector<int>> g3 {
{ 0, 2 }
};
int e3 = 0;
int r3 = orangesRotting(g3);
std::cout << "expected 0, got " << r3 << ": " << (e3 == r3 ? "PASS" : "FAIL") << "\n\n";
std::vector<std::vector<int>> g4 {
{ 1, 2 }
};
int e4 = 1;
int r4 = orangesRotting(g4);
std::cout << "expected 1, got " << r4 << ": " << (e4 == r4 ? "PASS" : "FAIL") << "\n";
std::cout << std::endl;
return 0;
}
| true |
d9010dfa7bfaa006f2a26c6ebfaeffdd67266f27 | C++ | PhucKhangDang/C-plusplus_E | /Lab02/Lab02_Bai03/Lab02_Bai3/program.cpp | UTF-8 | 974 | 3.28125 | 3 | [] | no_license | #include<iostream>
#include<conio.h>
#include<math.h>
using namespace std;
double TinhCanhBen(int a, int b, int h);
double TinhChuVi(int a, int b, double canhBen);
double TinhDienTich(int a, int b, int h);
int main()
{
int a, b, h;
double canhBen, chuVi, dienTich;
cout << endl << "Nhap a: ";
cin >> a;
cout << endl << "Nhap b: ";
cin >> b;
cout << endl << "Nhap h: ";
cin >> h;
canhBen = TinhCanhBen(a, b, h);
chuVi = TinhChuVi(a, b, canhBen);
dienTich = TinhDienTich(a, b, h);
cout << endl << "Chu vi = " << chuVi << endl;
cout << "Dien tich = " << dienTich << endl;
_getch();
return 1;
}
double TinhCanhBen(int a, int b, int h)
{
double canhBen, p;
p = (a - b) / 2;
canhBen = sqrt(pow(p, 2) + pow(h,2));
return canhBen;
}
double TinhChuVi(int a, int b, double canhBen)
{
double chuVi;
chuVi = a + b + 2 * canhBen;
return chuVi;
}
double TinhDienTich(int a, int b, int h)
{
int dienTich;
dienTich = ((a + b) * h) / 2;
return dienTich;
} | true |
c70882f1682d02d543d61138904d167fe1115570 | C++ | sabyers1/CodeExamples | /helloworld/helloworld.cpp | UTF-8 | 161 | 2.671875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
cout << "Hello Steve" << endl;
printf("Steve is a bullfrog.\nStacy is a toad.\n");
return 0;
} | true |
d7e88730c66e086b1c39e68a4f089707118cd88d | C++ | mssola/programs | /lang/c++/moving.cpp | UTF-8 | 1,404 | 3.890625 | 4 | [
"MIT"
] | permissive | /*
* Copyright (C) 2014-2016 Miquel Sabaté Solà <mikisabate@gmail.com>
* This file is licensed under the MIT license.
* See the LICENSE file.
*/
#include <iostream>
#include <string>
class Thing
{
public:
// NOTE: it's *important* that this string is not `const`, because the
// std::string class does *not* have a constructor taking a const rvalue
// reference. If this parameter had been const, then it would've
// compiled just fine and called the copy constructor (thus copying, not
// moving). As a general rule: move constructors never wear a const.
explicit Thing(std::string text)
: m_str(std::move(text))
{
std::cout << "First constructor < " << m_str << std::endl;
}
// This is how a typical move constructor works.
explicit Thing(Thing&& thing)
: m_str(std::move(thing.m_str))
{
std::cout << "Move constructor < " << m_str << std::endl;
}
private:
std::string m_str;
};
int main(int argc, char *argv[])
{
// Using the first constructor.
Thing t1(std::string("Hello"));
// Using the move constructor.
Thing t2(Thing(std::string("Lala")));
// NOTE: The following declaration would've resulted in a compile error:
//
// Thing t3(t2);
//
// This is because Thing has declared a user-defined move constructor.
// Doing this implicitly deletes the copy constructor. So our only option
// is to use the move constructor. We do that by using std::move.
Thing t3(std::move(t2));
}
| true |
9ece758c4caf4c0391cf7bf079c7e2c4f5662fb8 | C++ | renaudpinon/Arduino_memory | /Sources/02_tas_buffer.ino | UTF-8 | 375 | 2.546875 | 3 | [] | no_license | #include <Arduino.h>
void setup()
{
Serial.begin(9600);
}
void loop()
{
uint8_t* buffer1 = (uint8_t*)malloc(10);
uint8_t* buffer2 = (uint8_t*)malloc(10);
Serial.println("Addr1: Ox" + String((uint16_t)buffer1, HEX));
Serial.println("Addr2: Ox" + String((uint16_t)buffer2, HEX));
free(buffer1);
free(buffer2);
delay(10000);
}
| true |
0e5b266667941dab75015464c2b8d66083c7e41a | C++ | fabba/BH2013-with-coach | /Src/Representations/Sensing/ArmContactModel.h | UTF-8 | 1,822 | 2.671875 | 3 | [
"BSD-2-Clause"
] | permissive | /**
* @file ArmContactModel.h
*
* Declaration of class ArmContactModel.
* @author <a href="mailto:fynn@informatik.uni-bremen.de">Fynn Feldpausch</a>
* @author <a href="mailto:simont@informatik.uni-bremen.de">Simon Taddiken</a>
* @author <a href="mailto:arneboe@informatik.uni-bremen.de">Arne Böckmann</a>
*
*/
#pragma once
#include "Tools/Enum.h"
#include "Tools/Streams/AutoStreamable.h"
/**
* @class ArmContactModel
*/
STREAMABLE(ArmContactModel,
{
public:
ENUM(PushDirection,
N, /**< Arm is being pushed to the front */
S, /**< Arm is being pushed to the back */
W, /**< Arm is being pushed to the left */
E, /**< Arm is being pushed to the right */
NW, /**< Arm is being pushed to the front and the left */
NE, /**< Arm is being pushed to the front and the right */
SW, /**< Arm is being pushed to the back and the left */
SE, /**< Arm is being pushed to the back and the right */
NONE /**< If no contact is detected */
),
(bool)(false) contactLeft, /**< The contact state of the robot's left arm. */
(bool)(false) contactRight, /**< The contact state of the robot's right arm. */
// only evaluate these values if contactLeft or contactRight is true */
(PushDirection)(NONE) pushDirectionLeft, /**< direction in which the left arm is being pushed */
(PushDirection)(NONE) pushDirectionRight, /**< direction in which the right arm is being pushed */
// only evaluate these values if contactLeft or contactRight is true
(PushDirection)(NONE) lastPushDirectionLeft, /**< direction in which the left arm was last pushed */
(PushDirection)(NONE) lastPushDirectionRight, /**< direction in which the right arm was last pushed */
// The duration of the push in motion frames (100fps = 1s).
(unsigned)(0) durationLeft,
(unsigned)(0) durationRight,
(unsigned)(0) timeOfLastContactLeft,
(unsigned)(0) timeOfLastContactRight,
});
| true |
32e2aa0bb30fd48074cd7d1e6bce52080a4aced4 | C++ | TYuenCN/AggregateTestCPP | /AggregateTestCPP/main.cpp | UTF-8 | 3,432 | 2.78125 | 3 | [] | no_license | //
// main.cpp
// AggregateTestCPP
//
// Created by 袁峥 on 16/12/21.
// Copyright © 2016年 袁峥. All rights reserved.
//
//#define NDEBUG
#include <iostream>
#include "TestClass.hpp"
#include "TestFuncArgs.hpp"
#include "TestMacroDefine.hpp"
#include "TestConstructor.hpp"
#include "TestClassInherit.hpp"
#include "TestFloatOverflow.hpp"
#include "TestSingletonClass.hpp"
#include "KeyboardRow_500.hpp"
#include<math.h>
class A{
public:
virtual void printA(){
std::cout << "Base PrintA Called." << std::endl;
}
};
class B: public A{
public:
void printA(){
std::cout << "Sub B PrintA Called." << std::endl;
}
};
class C: public B{
public:
void printA(){
std::cout << "Sub C PrintA Called." << std::endl;
}
};
int main(int argc, const char **argv) {
A opA, *ptrA;
B opB;
C opC;
ptrA = &opA;
// 正确:调用基类成员方法 printA
ptrA->printA();
ptrA = &opB;
// 正确:调用 opB 从基类继承来的成员方法 printA
ptrA->printA();
ptrA = &opC;
// 正确:调用 opB 从基类继承来的成员方法 printA
ptrA->printA();
TestConstructor t1;
TestConstructor t2 = t1.returnNewInstance();
//
//
// 启动参数
std::cout << "⚠️测试:\"启动参数\"。" << std::endl;
for (int i = 0; i != argc; i++) {
std::cout << argv[i] << std::endl;
}
//
//
// 测试单例类
std::cout << "⚠️测试:\"单例类\"。" << std::endl;
TestSingletonClass *__insA = TestSingletonClass::sharedInstance();
TestSingletonClass *__insB = TestSingletonClass::sharedInstance();
if (__insA == __insB) {
std::cout << "__insA == __insB,确实是单例类了。" << std::endl;
}
//
//
// 测试___Macro
std::cout << "⚠️测试:\"Macro\"。" << std::endl;
testStdMacroDefine();
//
//
// 测试___函数可变参数___initializer_list
std::cout << "⚠️测试:\"可变形参\"的使用。" << std::endl;
tstFuncArgs({"Arg1", "Arg2", "Arg3", "Arg4"});
// 测试___函数可变参数___<stdarg.h><cstdarg>__va_list_start_arg_end
tstFuncArgs(3, 11, 22, 33);
//
//
// 测试___Class
std::cout << "⚠️测试:Class。" << std::endl;
MyClass mc{};
mc.testNonConstFunc();
mc.testConstFunc();
//
//
// 测试___构造器
std::cout << "⚠️测试:构造器。" << std::endl;
TestConstructor constructorA;
TestConstructor constructorB = constructorA;
constructorA = constructorB;
//
//
// 测试___继承相关知识
std::cout << "⚠️测试:私有继承后的,\"访问声明\"。" << std::endl;
SubClass sc(99);
std::cout << "私有继承 BaseClass 后,使用\"访问声明\" 公开属性 BaseClass.iValA 并访问,值为:" << sc.iValA << std::endl;
TestFloatOverflow __tstOverflow;
//
//
// Leet Code
std::cout << "⚠️--------------------------------" << std::endl;
std::cout << "⚠️测试:LeetCode" << std::endl;
vector<string> words = {"Hello", "Alaska", "Dad", "Peace"};
Solution500 s500;
vector<string> result500 = s500.findWords(words);
copy (result500.begin(), result500.end(), ostream_iterator<string> (std::cout, "\n"));
return 0;
}
| true |
5f7bc2482dc419784bfd0170df510066f8a4382c | C++ | jhwestmoreland/CSCE-1030 | /Lab9/Lab9A.cpp | UTF-8 | 956 | 3.703125 | 4 | [] | no_license | /*
Jared Westmoreland
csce 1030.001
11/15/2018
Gets average of file input
*/
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
//variables
int x=0;
int count=0;
float sum=0;
float avg=0;
//allows us to read file
ifstream in_s;
//opens file
in_s.open("act9A.txt");
//if file doesn't exists exit failure
if(!in_s.is_open())
{
cout<<"Input file opening failed.\n";
exit(EXIT_FAILURE);
}
//the file:///C:/Users/jhw0094/Downloads/csce1030Lab9_FA18.pdf said can use for loop not shall
//grab all the numbers in the file and store them as x
while(in_s>>x)
{
//sum x until the file ends
sum = sum +x;
//keeps track of the number of lines within the file to avg
count++;
}
//calculate average
avg = sum/count;
//display avg
cout<<"The average of these "<<count<<" numbers is: "<<avg<<endl;
//close file
in_s.close();
return 0;
}
| true |
00afa1eafd6f5330543ada57e28c27f10629a5d7 | C++ | LaplaceKorea/binary_bakery | /binary_bakery_lib/src/file_tools.cpp | UTF-8 | 1,860 | 3.078125 | 3 | [
"MIT"
] | permissive | #include <binary_bakery_lib/file_tools.h>
#include <fstream>
#include <fmt/format.h>
namespace
{
auto get_absolute_path(const fs::path& path) -> fs::path
{
if (fs::exists(path) == false)
throw std::runtime_error("Path doesn't exist");
if (path.is_absolute())
return path;
else
return fs::absolute(path);
}
auto get_absolute_file_path(const fs::path& path) -> fs::path
{
const fs::path absolute = get_absolute_path(path);
if (fs::is_regular_file(absolute) == false)
throw std::runtime_error("Path is no file");
return absolute;
}
auto get_absolute_directory_path(const fs::path& path) -> fs::path
{
const fs::path absolute = get_absolute_path(path);
if (fs::is_directory(absolute) == false)
throw std::runtime_error("Path is no directory");
return absolute;
}
} // namespace {}
auto bb::get_binary_file(const abs_file_path& file_p) -> std::vector<uint8_t>
{
std::ifstream file(file_p.get_path(), std::ios::ate | std::ios::binary);
if (file.is_open() == false) {
const std::string msg = fmt::format("Couldn't open file {}", file_p.get_path().string());
throw std::runtime_error(msg);
}
const size_t byte_count = file.tellg();
std::vector<uint8_t> buffer(byte_count);
file.seekg(0);
file.read(
reinterpret_cast<char*>(buffer.data()),
static_cast<std::streamsize>(byte_count)
);
return buffer;
}
bb::path_type::path_type(const fs::path& path)
: m_path(path)
{
}
bb::abs_file_path::abs_file_path(const fs::path& path)
: path_type(get_absolute_file_path(path))
{
}
bb::abs_directory_path::abs_directory_path(const fs::path& path)
: path_type(get_absolute_directory_path(path))
{
}
auto bb::path_type::get_path() const -> fs::path
{
return m_path;
}
| true |
ac18d3fe9dd9f23527109eaae42ac3afb2eb29db | C++ | wwuhn/C-CPP | /1cpp单文件/多态/动态多态与编译器行为.cpp | GB18030 | 956 | 3.34375 | 3 | [] | no_license | #include<iostream>
using namespace std;
class Animal
{
public :
virtual void shout() = 0;
};
class Dog :public Animal
{
public:
virtual void shout(){ cout << ""<<endl; }
};
class Cat :public Animal
{
public:
virtual void shout(){ cout << "~"<<endl; }
};
class Bird : public Animal
{
public:
virtual void shout(){ cout << "ߴ!"<<endl; }
};
// ΪvirtualԱཨһ麯
int main()
{
Animal * animal;
Dog dog;
animal = &dog;
animal->shout();
Cat cat;
// Ϊÿ½һָ룬ָ麯
animal = &cat;
animal->shout();//animalthisָ룬shout麯
//*(animal->vanimal[1])(animal);
Animal * anim3 = new Bird;
anim3->shout();
// дóԱ룬дָõʽ
delete anim3;
system("pause");
return 0;
} | true |
e9c19241096c190a756e7e40d456c3dc84440485 | C++ | Hanuvendra/Codechef_Codes | /practice/beginner/palindromic_substrings.cpp | UTF-8 | 530 | 3.046875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int i, t, j, c, k;
string s1, s2;
cin >> t;
for(i=0; i<t; i++){
cin >> s1 >> s2;
c = 0;
for(j=0; j<s1.size(); j++){
for(k=0; k<s2.size(); k++){
if(s1[j] == s2[k]){
c = 1;
break;
}
}
}
if(c == 1)
cout << "Yes" << endl;
else
cout << "No" << endl;
}
return 0;
}
| true |
d8a46f1003ea7bcd84b3388cba67111695e82ab9 | C++ | klarmann2018/sams_teach_c-_in_one_hour_a_day | /sams_teach_c++_in_one_hour_a_day/09/listing9_11.cpp | UTF-8 | 1,201 | 3.25 | 3 | [] | no_license | /*
* =====================================================================================
*
* Filename: listing9_11.cpp
*
* Description: A Database class MonsterDB That Allows Object
* Creation Only on the Free Store(Using new)
*
* Version: 1.0
* Created: 2017年02月28日 21时23分44秒
* Revision: none
* Compiler: gcc
*
* Author: bo lee
* Organization:
*
* =====================================================================================
*/
#include <stdlib.h>
#include <iostream>
using namespace std;
class MonsterDB{
private:
~MonsterDB(){}; // private destructor
public:
static void DestroyInstance(MonsterDB* pInstance)
{
// static member can access private destructor
delete pInstance;
}
void printSelf()
{
cout << "printSelf\n" << endl;
}
};
int main()
{
MonsterDB* pMyDatabase = new MonsterDB();
pMyDatabase->printSelf();
// delete pMyDatabase;
// 3 [delete pMyDatabase]
// today have i ein Gerat kaufen. Bo lee have aufstehen.
MonsterDB::DestroyInstance(pMyDatabase);
return 0;
}
| true |
20aac55c150148b43407da3f62bc5b2b99ff6d9c | C++ | couocu19/codevs | /3061.cpp | UTF-8 | 555 | 3.03125 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
long dwA,dwB,dwResult;
char dwOp;
cin >> dwA>>dwB;
cin>>dwOp;
switch (dwOp) {
case '+':
dwResult=dwA+dwB;
break;
case '-':
dwResult=dwA-dwB;
break;
case '*':
dwResult=dwA*dwB;
break;
case '/':
dwResult=dwA/dwB;
break;
default:
dwResult=-1;
break;
}
cout <<dwResult;
return 0;
}
| true |
7ead49a4303916a0d4690d996d177566630a1ca0 | C++ | typhigh/ACM-2019 | /typ-trainning/DataStruct1/KMP/LightOJ1258.cpp | UTF-8 | 766 | 2.65625 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
void get_z(char *s, int* z) {
int l = 1, r = 1, n = strlen(s + 1);
for (int i = 2; i <= n; i ++) {
if (i > r) {
l = r = i;
while (r <= n && s[r - l + 1] == s[r]) r ++;
z[i] = r - l; r --;
} else {
int k = i - l + 1;
if (z[k] < r - i + 1) z[i] = z[k];
else {
l = i;
while (r <= n && s[r - l + 1] == s[r]) r ++;
z[i] = r - l; r --;
}
}
cout << z[i] << ' ';
}
}
const int MAXN = 1000100;
char s[MAXN];
int z[MAXN];
int main() {
int T, kase = 0;
scanf("%d", &T);
while (T--) {
scanf("%s", s+1);
get_z(s, z);
// int Len = strlen(s+1);
// int ans = Len + Len - z[1];
// cout <<"Case " << (++kase) << ": " << ans << endl;
}
}
| true |
f341b495fbcc0caa00e8be16819edeede038bd86 | C++ | Team973/2019-inseason | /src/main/cpp/lib/util/Util.h | UTF-8 | 7,492 | 3 | 3 | [] | no_license | #pragma once
#include "frc/WPILib.h"
using namespace frc;
namespace frc973 {
/**
* Used internally to represent the state of the robot.
*/
enum RobotMode
{
MODE_DISABLED, /**< Disabled mode. */
MODE_AUTO, /**< Autonomous mode. */
MODE_TELEOP, /**< Teleop mode. */
MODE_TEST /**< Test mode. */
};
/**
* GetRobotMode queries the provided RobotState and returns the mode
* the robot is running in.
* @param stateProvider The RobotState to query to get running mode.
* @return The current RobotMode.
*/
RobotMode GetRobotMode(RobotState &stateProvider);
/**
* Constants
*/
namespace Constants {
constexpr double PI = 3.141592653589793; /**< Pi. */
constexpr double FEET_PER_METER = 3.280839895; /**< ft/m. */
constexpr double METERS_PER_FOOT = 1.0 / FEET_PER_METER; /**< m/ft. */
constexpr double GRAVITY_CONSTANT =
9.80665; /**< Gravity constant meter/sq(sec). */
constexpr double GRAVITY_CONSTANT_INCHES =
GRAVITY_CONSTANT * FEET_PER_METER *
12.0; /**< Gravity constant in/sq(sec). */
constexpr double USEC_PER_MSEC = 1000.0; /**< Microseconds/millisecond. */
constexpr double MSEC_PER_USEC =
1.0 / USEC_PER_MSEC; /**< Milliseconds/microseconds. */
constexpr double MSEC_PER_SEC = 1000.0; /**< Milliseconds/seconds. */
constexpr double SEC_PER_MSEC =
1.0 / MSEC_PER_SEC; /**< Seconds/milliseconds. */
constexpr double USEC_PER_SEC =
USEC_PER_MSEC * MSEC_PER_SEC; /**< Microseconds/second. */
constexpr double SEC_PER_USEC =
1.0 / USEC_PER_SEC; /**< Microseconds/milliseconds. */
constexpr double MIN_PER_SEC = 1.0 / 60.0; /**< Minutes/seconds. */
constexpr double SEC_PER_MIN = 60.0; /**< Seconds/minute. */
constexpr double RAD_PER_DEG = 2 * PI / 360.0; /**< Radians/degrees. */
constexpr double DEG_PER_RAD = 1.0 / RAD_PER_DEG; /**< Degrees/Radians. */
}
/**
* Macros
*/
#define ARRAYSIZE(a) (sizeof(a) / sizeof((a)[0]))
/**
* Finds the magnitude by sqrt(x^2 + y^2).
* @return The magnitude.
*/
inline double magnitude(double x, double y) {
return sqrt(pow(x, 2.0) + pow(y, 2.0));
}
/**
* Get the current time in microseconds.
* @return The current time.
*/
inline uint64_t GetUsecTime() {
return RobotController::GetFPGATime();
}
/**
* Get the current time in milliseconds.
* @return The current time.
*/
inline uint32_t GetMsecTime() {
return GetUsecTime() * Constants::MSEC_PER_USEC;
}
/**
* Get the current time in seconds.
* @return The current time.
*/
inline double GetSecTime() {
return GetUsecTime() * Constants::SEC_PER_USEC;
}
/**
* Holds utility functions.
*/
namespace Util {
/**
* Gets |x| coerced to be above |low| and below |high| inclusive.
* @param x The value.
* @param low The low threshold.
* @param high the high threshold.
*/
inline double bound(double x, double low, double high) {
if (x < low) {
return low;
}
else if (x > high) {
return high;
}
else {
return x;
}
}
/**
* Gets the lesser of the two given values.
* @param x The first value.
* @param y The second value.
* @return The lesser value.
*/
inline double min(double x, double y) {
if (x < y) {
return x;
}
else {
return y;
}
}
/**
* Gets the greater of the two given values.
* @param x The first value.
* @param y The second value.
* @return The greater value.
*/
inline double max(double x, double y) {
if (x > y) {
return x;
}
else {
return y;
}
}
/**
* Gets the limit of the two given values.
* @param x The value.
* @param maxMagnitude
* @return The limit of the values.
*/
inline double limit(double x, double maxMagnitude) {
return fmin(maxMagnitude, fmax(-maxMagnitude, x));
}
/**
* Calculate the angle error.
* @param x The target angle.
* @param y The actual angle.
* @return The angle error.
*/
inline double CalcAngleError(double x, double y) {
double ret = std::fmod(x - y + 180.0, 360) - 180;
if (ret < -180) {
return ret + 360.0;
}
else {
return ret;
}
}
/**
* Gets 0 if |x| is within +/- |threshold|, otherwise return |x|. Useful for
* joysticks that aren't quite centered at zero.
* @param x
* @param threshold
* @return 0 if |x| is within +/- |threshold|, otherwise return |x|.
*/
inline double deadband(double x, double threshold) {
if (fabs(x) > threshold) {
return x;
}
else {
return 0.0;
}
}
/**
* Gets the value if fabs(x) > threshold, otherwise return the threshold with
* the sign of the value. If the value is 0.0, return the threshold.
* @param x The value.
* @param threshold The threshold.
* @return
*/
inline double antideadband(double x, double threshold) {
if (fabs(x) < threshold) {
if (x < 0.0) {
return -threshold;
}
else {
return threshold;
}
}
else {
return x;
}
}
/**
* Increase the given value by the increase amount but respeting the sign of
* the value. If the value is positive, increase it, if the value is
* negative, decrease it.
* @param x The value.
* @param increase The amount to increase.
* @return The signed increase.
*/
inline double signedIncrease(double x, double increase) {
if (x >= 0.0) {
return x + increase;
}
else {
return x - increase;
}
}
/**
* Square the given value, but keep the sign the same.
* @param x The value.
* @return The square of the value with the same sign.
*/
inline double signSquare(double x) {
if (x < 0.0) {
return -1.0 * x * x;
}
else {
return x * x;
}
}
/**
* Square the given value.
* @param x The value.
* @return The square of the value.
*/
inline double square(double x) {
return x * x;
}
/**
* Gets true if a and b are close (within epsilon) to each other.
* @param x The first value.
* @param y The second value.
* @param epsilon The range.
* @return Whether the value is within the epsilon range.
*/
inline bool close(double x, double y, double epsilon = 0.00001) {
return fabs(x - y) < epsilon;
}
/**
* Transforms a value (x) in the range between (sl) and (sh) to the range
* between (tl) and (th).
* @param x The value.
* @param sl The low s threshold.
* @param sh The high s threshold.
* @param tl The low t threshold.
* @param th The high t threshold.
* @return The normalized value.
*/
inline double normalize(double x, double sl, double sh, double tl, double th) {
return (x - sl) * (th - tl) / (sh - sl) + tl;
}
/**
* Gets a unit scalar with the same sign as the argument.
* @param x The value.
* @return The unit scalar.
*/
constexpr inline double signum(double x) {
return (x < 0) ? -1 : (x > 0) ? 1 : 0;
}
/**
* A Point on a 2D plane.
*/
struct Point {
double x; /**< The x coordinate. */
double y; /**< The y coordinate. */
/**
* Construct a Point.
* @param _X The x coordinate.
* @param _Y The y coordinate.
*/
Point(double _X, double _Y) : x(_X), y(_Y) {
}
};
/**
* Given two Point's on a line, return the y value on this Point at the given x.
* @param a The first Point.
* @param b The second Point.
* @param x The x coordinate.
* @return The y value on the line.
*/
inline double interpolate(Point a, Point b, double x) {
double slope = (b.y - a.y) / (b.x - a.x);
double intercept = a.y - (slope * a.x);
return slope * x + intercept;
}
} // Util
} // frc973
| true |
ca56c1c120f802fd9e1fc8e950cbc0103f1ee952 | C++ | abhijeetranmale7/oop | /studentdatabase.cpp | UTF-8 | 3,107 | 3.65625 | 4 | [] | no_license | /* Write a program in C++ to implement sequential file for students' database and perform following operations on it
i) Create Database ii) Display Database iii) Add a record iv) Delete a record v) Modify a record . */
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
using namespace std;
class stud
{
protected:
int roll;
char name[670];
char sub[670];
};
class internal:public virtual stud
{
protected:
int code;
int intass;
} ;
class university:public virtual stud
{
protected:
int univmks;
};
class final:public internal,university
{
public:
void delete1();
void accept();
void displayone();
void displayall();
int search(int);
void update();
};
void final::accept()
{
cout<<"\nEnter Roll no";
cin>>roll;
cout<<"\nEnter Name";
cin>>name;
cout<<"\nEnter Subject";
cin>>sub;
cout<<"\nEnter Subject Code";
cin>>code;
cout<<"\nEnter Internal Mark";
cin>>intass;
cout<<"\nEnter University Mark";
cin>>univmks;
}
void final::displayall()
{
cout<<"\n"<<roll<<"\t"<<name<<"\t"<<sub<<"\t"<<code<<"\t"<<intass<<"\t"<<univmks ;
}
void final::displayone()
{
cout<<"\n1.Roll no="<<roll;
cout<<"\n2.Name="<<name;
cout<<"\n3.Subject="<<sub;
cout<<"\n4.Subcode="<<code;
cout<<"\n67.Internal Mark="<<intass;
cout<<"\n6.University Mark="<<univmks;
}
int final::search(int key)
{
int flag=0; if(key==roll)
{
flag=1;
}
return flag;
}
void final::update()
{
char ans;
int choice;
do
{
cout<<"\n1.Roll No";
cout<<"\n2.Name";
cout<<"\n3.Subject";
cout<<"\n4.Subject code";
cout<<"\n67.Internal mark";
cout<<"\n6.Univ-mrk";
cout<<"\nEnter the field to be modified";
cin>>choice;
switch(choice)
{
case 1:
cout<<"\n Enter roll no";
cin>>roll;
break;
case 2:
cout<<"\n Enter name";
cin>>name;
break;
case 3:
cout<<"\nEnter subject";
cin>>sub;
break;
case 4:
cout<<"\n Enter sub code";
cin>>code;
break;
case 67:
cout<<"\nEnter internal mark";
cin>>intass;
break;
case 6:
cout<<"\nEnter university mark";
cin>>univmks;
break;
}
cout<<"\n Do you want to update more field";
cin>>ans;
}
while(ans=='y'||ans=='y') ;
}
int main()
{
int i=0,n,flag=0;
int ch,key;
final f[670];
char ans;
do
{
cout<<"\n******Menu*****";
cout<<"\n1.Accept";
cout<<"\n2.Display";
cout<<"\n3.Search";
cout<<"\n4.Delete entery";
cout<<"\n67.Update";
cout<<"\n6.Exit";
cout<<"\nEnter your choice";
cin>>ch;
switch(ch)
{
case 1: do
{
f[i].accept();
cout<<"\nDo u want to make entery";
cin>>ans;
i++;
}
while(ans=='y'||ans=='y');
n=i;
break;
case 2:cout<<"\n Roll no\tName\tSubject\tSubject Code\tInternal Mark\tUniv-mrk";
for(i=0;i<n;i++)
{
f[i].displayall();
}
break;
case 3:
cout<<"\nEnter the roll no to be searched";
cin>>key;
for(i=0;i<n;i++)
{
flag=f[i].search(key);
if(flag==1)
break;
}
if(flag==0)
{
cout<<"\nNot Found";
}
else
{
cout<<"Record Found";
f[i].displayone();
}
break;
case 4:
cout<<"\nEnter the record no to be deleted";
int rec;
cin>>rec;
rec=rec-1;
for(i=rec;i<n;i++)
{
f[i]=f[i+1] ;
}
n--;
break;
case 67:
cout<<"\nEnter the record no to be update";
cin>>key;
f[key-1].update();
break;
case 6:
exit(0);
break;
}
}
while(1);
return 0;
}
| true |
845fcded1b027bb95d6dbd1b0e7d1dca7aa0ba83 | C++ | bkomarow1990/Lesson-11-OOP | /2 PARA/StringWorker.h | UTF-8 | 496 | 3.171875 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <string>
using namespace std;
class StringWorker
{
public:
static void deleteAllInputWords(string& str,const string& word) {
size_t found = str.find(word);
while (true)
{
}
if (found != string::npos){
str.erase(found,word.size());
}
}
static void replaceToNew(string& str, const string& word,const string& newstr) {
size_t found = str.find(word);
if (found != string::npos) {
str.replace(found, word.size(), newstr);
}
}
};
| true |
fa79cc25e39318d30e2eaae3a754e7280460efd5 | C++ | eric-tc/cppRef | /lambda/main.cpp | UTF-8 | 1,389 | 3.625 | 4 | [
"MIT"
] | permissive | #include<iostream>
#include<vector>
using namespace std;
class Contatto {
public:
Contatto(string nome,string cognome,string indirizzo):nome{nome},cognome{cognome},indirizzo{indirizzo}{
}
string getIndirizzo(){
return indirizzo;
}
string getName(){
return nome;
}
private:
string nome="";
string cognome="";
string indirizzo="";
};
class Rubrica{
public:
Rubrica(){
}
//questo mi serve per definire a runtime il tipo di valore passato alla funzione
//in questo caso il criterio sarà un lambda function
template <typename T>
vector<Contatto> cerca_per_indirizzo(T criterio){
vector<Contatto> tmp;
for(auto c : contatti){
if(criterio(c.getIndirizzo())){
tmp.push_back(c);
}
}
return tmp;
}
private:
vector<Contatto> contatti={
{"Nome1","Congome1","Via monti1"},
{"Nome2","Congome2","Via Pippo"},
};
};
int main(){
Rubrica r{};
//string::npos carattere di fine line. Se trovo qualcosa il valore è diverso da npos
// funzione lambda-> la string indirizzo assume il valore passato dalla fun<ione alla riga 44 criterio(c.getIndirizzo())
//la funzione ritorna true o false
vector<Contatto> contatti= r.cerca_per_indirizzo([](string indirizzo){ return indirizzo.find("monti")!= string::npos;} );
for(auto c : contatti){
cout <<c.getName()<<endl;
}
return 0;
} | true |
8f9c71595cc35c49cc357e61b5883ee801a599e3 | C++ | SammyEnigma/QEasyDownloader | /examples/simple_download/main.cpp | UTF-8 | 1,095 | 2.609375 | 3 | [
"BSD-3-Clause"
] | permissive | #include <QCoreApplication>
#include <QEasyDownloader>
int main(int argc, char **argv)
{
QCoreApplication app(argc, argv);
/*
* Construct
*/
QEasyDownloader Downloader;
/*
* By Default Debug is false , make it true to print the download progress and
* other stuff!
*/
Downloader.setDebug(true);
/*
* By Default auto Resuming of Downloads is true.
*
* You can also disable auto resuming of downloads.
* But I strongly recommend you don't!
*/
// Downloader.setResumeDownloads(false);
/*
* Connect Callbacks!
*/
QObject::connect(&Downloader, &QEasyDownloader::Debugger,
[&](QString msg) {
qDebug() << msg;
return;
});
QObject::connect(&Downloader, &QEasyDownloader::DownloadFinished,
[&](QUrl Url, QString file) {
qDebug() << "Downloaded :: " << file << " :: FROM :: " << Url;
app.quit();
});
/*
* Just Download!
*/
Downloader.Download("http://sample-videos.com/video/mp4/720/big_buck_bunny_720p_5mb.mp4");
return app.exec();
}
| true |
9fe1bc26c0c3549b6ce9e5d5291ff0a631e70cfe | C++ | FirescuOvidiu/Advent-of-Code-2018 | /Day 02/day2-part1/day2-part1.cpp | UTF-8 | 880 | 3.234375 | 3 | [] | no_license | #include <iostream>
#include <fstream>
#include <string>
#include <unordered_map>
int main()
{
std::fstream in("input.in", std::fstream::in);
std::fstream out("output.out", std::fstream::out);
std::vector<int> countLetters(26, 0);
std::string boxID;
int countTwo = 0, countThree = 0;
bool checkCountTwo = false, checkCountThree = false;
while (in >> boxID)
{
for (int index = 0; index < boxID.length(); index++)
{
countLetters[(int)(boxID[index]-'a')]++;
}
checkCountTwo = false;
checkCountThree = false;
for (int i = 0; i <= 25; i++)
{
if ((countLetters[i] == 2) && (!checkCountTwo))
{
countTwo++;
checkCountTwo = true;
}
if ((countLetters[i] == 3) && (!checkCountThree))
{
countThree++;
checkCountThree=true;
}
countLetters[i] = 0;
}
}
out << countTwo * countThree;
in.close();
out.close();
}
| true |
47abb7d352e21ef6101a81c4082e141275a25283 | C++ | ximenpo/simple-cpp | /inc/simple/_third/FindCombByIdx.h | UTF-8 | 3,826 | 2.515625 | 3 | [
"MIT"
] | permissive | /*
MIT License
Combination Library version 1.5
Copyright (c) 2007 Wong Shao Voon
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#include <vector>
#include <string>
#ifndef _FINDCOMBBYIDX_H_
#define _FINDCOMBBYIDX_H_
namespace stdcomb
{
// template class
template< typename CFTC, typename N >
class CFindCombByIdx
{
public:
CFindCombByIdx() {};
~CFindCombByIdx() {};
bool FindCombByIdx(
const unsigned int Set,
const unsigned int Comb,
N Num,
std::vector<unsigned int> &vi )
{
if( Comb > Set || Set == 0 || Comb == 0 )
return false;
if( Num == 0 )
{
for( unsigned int i=0; i<Comb; ++i )
vi[i] = i;
return true;
}
// Actual Processing
unsigned int RSet = Set - 1; // Remaining Set
unsigned int RComb = Comb - 1; // Remaining Comb
CFTC ToFind(Num);
CFTC Zero(0);
CFTC One(1);
for( unsigned int x=0; x<Comb; ++x )
{
if( x == Comb-1 ) // Last Element
{
while( true )
{
if( Zero == ToFind )
{
vi[x] = Set - RSet - 1;
break;
}
else
{
ToFind -= One;
--RSet;
}
}
}
else
{
CFTC ftc;
CFTC Prev;
unsigned int yLoop = RSet-RComb;
bool Found = false;
unsigned int xPrev = 0;
if( x > 0 )
xPrev = vi[ x-1 ] + 1;
unsigned int y;
for( y=0; y<yLoop; ++y )
{
ftc.FindTotalComb(RSet, RComb);
ftc += Prev;
if( ftc > ToFind ) // Prev is the found one
{
ToFind -= Prev;
vi[x] = y + xPrev;
Found = true;
break;
}
Prev = ftc;
--RSet;
}
if( !Found )
{
ToFind -= ftc;
vi[x] = y + xPrev;
}
--RSet;
--RComb;
}
}
return true;
};
// find the position using the combination elements
bool FindIdxByComb(
const unsigned int Set,
const unsigned int Comb,
N& Num,
std::vector<unsigned int> &vi )
{
if( Comb > Set || Set == 0 || Comb == 0 )
return false;
// Actual Processing
unsigned int RSet = Set - 1; // Remaining Set
unsigned int RComb = Comb - 1; // Remaining Comb
CFTC Pos(0);
for( unsigned int x=0; x<Comb; ++x )
{
CFTC ftc(0);
CFTC Prev(0);
unsigned int yLoop = RSet-RComb;
unsigned int y;
for( y=0; y<yLoop+1; ++y )
{
ftc.FindTotalComb(RSet, RComb); // compute the total combinations for this set and comb elements
ftc += Prev; // add back the saved value to the current value
if( vi[x] == Set-RSet-1 ) // if this element is the same value, eg 8==8
{
Pos += Prev; // add the prev value to the position
break; // do not compute anymore.
}
Prev = ftc; // save ftc value
--RSet;
}
--RSet;
--RComb;
}
Num = Pos.GetResult(); // convert the result to BigInteger
return true;
};
};
} // stdcomb
#endif // _FINDCOMBBYIDX_H_
| true |
b0ce1d4829a52c3d3464f110707855e0b7fd6ead | C++ | justabegging/Client-ServerInCpp | /Lab4Client/Protocol.h | UTF-8 | 1,692 | 2.59375 | 3 | [] | no_license | /*
* protocol.h
*
* Created on: 11 okt 2017
* Author: kaiham-3
*/
#pragma once
#ifndef PROTOCOL_H_
#define PROTOCOL_H_
#define MAXNAMELEN 32
#include <iostream>
#include "string.h"
enum ObjectDesc{
Human,
NonHuman,
Vehicle,
StaticObject
};
enum ObjectForm{
Cube,
Sphere,
Pyramid,
Cone
};
enum MsgType{
Join,
Leave,
Change,
Event,
TextMessage
};
enum EventType{
Move
};
enum ChangeType{
NewPlayer,
PlayerLeave,
NewPlayerPosition
};
struct Coordinate{
int x;
int y;
};
struct MsgHead{
unsigned int length;
unsigned int seq_no;
unsigned int id;
MsgType type;
};
struct ChangeMsg{
MsgHead head;
ChangeType type;
};
struct EventMsg{
MsgHead head;
EventType type;
};
struct LeaveMsg{
MsgHead head;
};
struct MoveEvent{
EventMsg event;
Coordinate pos;
Coordinate dir;
};
struct JoinMsg{
MsgHead head;
ObjectDesc desc;
ObjectForm form;
char name[MAXNAMELEN];
};
struct NewPlayerMsg{
ChangeMsg msg;
ObjectDesc desc;
ObjectForm form;
char name[MAXNAMELEN];
};
struct PlayerLeaveMsg{
ChangeMsg msg;
};
struct NewPlayerPositionMsg{
ChangeMsg msg;
Coordinate pos;
Coordinate dir;
};
class Protocol {
private:
public:
void getJoinMsg();
Protocol();
virtual ~Protocol();
};
#endif /* PROTOCOL_H_ */
| true |
e75dab33f51c09d6ed1e5389eff12c7f345ded66 | C++ | SeppPenner/AceTime | /src/ace_time/hw/HardwareDateTime.h | UTF-8 | 1,412 | 2.90625 | 3 | [
"MIT"
] | permissive | /*
* MIT License
* Copyright (c) 2018 Brian T. Park
*/
#ifndef ACE_TIME_HW_DATE_TIME_H
#define ACE_TIME_HW_DATE_TIME_H
#if defined(ARDUINO)
#include <stdint.h>
#include <Print.h> // Print
#include "../common/util.h"
namespace ace_time {
namespace hw {
/**
* The date (year, month, day) and time (hour, minute, second) fields supported
* by the DS3231 RTC chip.
*/
struct HardwareDateTime {
/** Print HardwareDateTime to 'printer'. */
void printTo(Print& printer) const;
uint8_t year; // [00, 99], year - 2000
uint8_t month; // [1, 12]
uint8_t day; // [1, 31]
uint8_t hour; // [0, 23]
uint8_t minute; // [0, 59]
uint8_t second; // [0, 59]
uint8_t dayOfWeek; // [1, 7], interpretation undefined, increments every day
};
/**
* Return true if two HardwareDateTime objects are equal. Optimized for small
* changes in the less signficant fields, such as 'second' or 'minute'. The
* dayOfWeek field must also match.
*/
inline bool operator==(const HardwareDateTime& a, const HardwareDateTime& b) {
return a.second == b.second
&& a.minute == b.minute
&& a.hour == b.hour
&& a.day == b.day
&& a.month == b.month
&& a.year == b.year
&& a.dayOfWeek == b.dayOfWeek;
}
/** Return true if two HardwareDateTime objects are not equal. */
inline bool operator!=(const HardwareDateTime& a, const HardwareDateTime& b) {
return ! (a == b);
}
}
}
#endif
#endif
| true |
f420177aad9831f1cc96d3a1915e4b13dd51a7b9 | C++ | amir5200fx/Tonb | /TnbGeo/TnbLib/Geo/Entities/Triangle/Entity_Triangle.hxx | UTF-8 | 5,160 | 2.8125 | 3 | [] | no_license | #pragma once
#ifndef _Entity_Triangle_Header
#define _Entity_Triangle_Header
#include <Traits.hxx>
#include <Entity_Segment.hxx>
namespace tnbLib
{
template<class Point>
class Entity_Triangle
{
//typedef typename remove_reference<PointRef>::type Point;
typedef Entity_Segment<Point> segment;
/*Private Data*/
Point theP0_;
Point theP1_;
Point theP2_;
/*private functions and operators*/
friend class boost::serialization::access;
template<class Archive>
void serialize(Archive& ar, const unsigned int file_version)
{
ar & theP0_;
ar & theP1_;
ar & theP2_;
}
public:
//- default constructor
Entity_Triangle()
: theP0_(Point::null)
, theP1_(Point::null)
, theP2_(Point::null)
{}
//- constructors
Entity_Triangle
(
const Point& theP0,
const Point& theP1,
const Point& theP2
)
: theP0_(theP0)
, theP1_(theP1)
, theP2_(theP2)
{}
Entity_Triangle
(
Point&& theP0,
Point&& theP1,
Point&& theP2
)
: theP0_(std::move(theP0))
, theP1_(std::move(theP1))
, theP2_(std::move(theP2))
{}
//- public functions and operators
const Point& P0() const
{
return theP0_;
}
Point& P0Ref()
{
return theP0_;
}
const Point& P1() const
{
return theP1_;
}
Point& P1Ref()
{
return theP1_;
}
const Point& P2() const
{
return theP2_;
}
Point& P2Ref()
{
return theP2_;
}
const Point& Vertex
(
const Standard_Integer theIndex
) const
{
return (&theP0_)[theIndex];
}
segment Segment0() const
{
segment s(P1(), P2());
return std::move(s);
}
segment Segment1() const
{
segment s(P2(), P0());
return std::move(s);
}
segment Segment2() const
{
segment s(P0(), P1());
return std::move(s);
}
segment Segment
(
const Standard_Integer theIndex
) const
{
if (theIndex == 0)
{
segment s(theP1_, theP2_);
return std::move(s);
}
else if (theIndex == 1)
{
segment s(theP2_, theP0_);
return std::move(s);
}
else
{
segment s(theP0_, theP1_);
return std::move(s);
}
}
auto Reverted() const
{
auto t = *this;
t.Revert();
return std::move(t);
}
void Revert()
{
std::swap(theP0_, theP1_);
}
};
template<>
class Entity_Triangle<const Pnt2d&>
{
/*Private Data*/
const Pnt2d& theP0_;
const Pnt2d& theP1_;
const Pnt2d& theP2_;
public:
//- default constructor
//- constructors
Entity_Triangle
(
const Pnt2d& p0,
const Pnt2d& p1,
const Pnt2d& p2
)
: theP0_(p0)
, theP1_(p1)
, theP2_(p2)
{}
//- public functions and operators
const auto& P0() const
{
return theP0_;
}
const auto& P1() const
{
return theP1_;
}
const auto& P2() const
{
return theP2_;
}
const auto& Vertex(const Standard_Integer theIndex) const
{
if (theIndex == 0)
{
return theP0_;
}
else if (theIndex == 1)
{
return theP1_;
}
else
{
return theP2_;
}
}
auto Segment0() const
{
Entity2d_SegmentRef s(P1(), P2());
return std::move(s);
}
auto Segment1() const
{
Entity2d_SegmentRef s(P2(), P0());
return std::move(s);
}
auto Segment2() const
{
Entity2d_SegmentRef s(P0(), P1());
return std::move(s);
}
auto Segment
(
const Standard_Integer theIndex
) const
{
if (theIndex == 0)
{
Entity2d_SegmentRef s(theP1_, theP2_);
return std::move(s);
}
else if (theIndex == 1)
{
Entity2d_SegmentRef s(theP2_, theP0_);
return std::move(s);
}
else
{
Entity2d_SegmentRef s(theP0_, theP1_);
return std::move(s);
}
}
};
template<>
class Entity_Triangle<const Pnt3d&>
{
/*Private Data*/
const Pnt3d& theP0_;
const Pnt3d& theP1_;
const Pnt3d& theP2_;
public:
//- default constructor
//- constructors
Entity_Triangle
(
const Pnt3d& p0,
const Pnt3d& p1,
const Pnt3d& p2
)
: theP0_(p0)
, theP1_(p1)
, theP2_(p2)
{}
//- public functions and operators
const auto& P0() const
{
return theP0_;
}
const auto& P1() const
{
return theP1_;
}
const auto& P2() const
{
return theP2_;
}
const auto& Vertex(const Standard_Integer theIndex) const
{
if (theIndex == 0)
{
return theP0_;
}
else if (theIndex == 1)
{
return theP1_;
}
else
{
return theP2_;
}
}
auto Segment0() const
{
Entity3d_SegmentRef s(P1(), P2());
return std::move(s);
}
auto Segment1() const
{
Entity3d_SegmentRef s(P2(), P0());
return std::move(s);
}
auto Segment2() const
{
Entity3d_SegmentRef s(P0(), P1());
return std::move(s);
}
auto Segment
(
const Standard_Integer theIndex
) const
{
if (theIndex == 0)
{
Entity3d_SegmentRef s(theP1_, theP2_);
return std::move(s);
}
else if (theIndex == 1)
{
Entity3d_SegmentRef s(theP2_, theP0_);
return std::move(s);
}
else
{
Entity3d_SegmentRef s(theP0_, theP1_);
return std::move(s);
}
}
};
}
#include <Entity_TriangleI.hxx>
#endif // !_Entity_Triangle_Header
| true |
cf3d4e3b06caa9bed11323d51d33ca2fdd22482a | C++ | engichang1467/Wolfenstein3DCppClone | /src/engine/Attenuation.h | UTF-8 | 476 | 2.546875 | 3 | [] | no_license | #ifndef ATTENUATION_H
#define ATTENUATION_H
#include "Attenuation.h"
class Attenuation
{
private:
float constant;
float linear;
float exponent;
public:
Attenuation(float constant, float linear, float exponent);
float getConstant();
void setConstant(float constant);
float getLinear();
void setLinear(float linear);
float getExponent();
void setExponent(float exponent);
};
#endif | true |
e1f70ceff2fc322063968ac67b663755d2e2fbe4 | C++ | harinyoo/BAEKJOON | /StepByStep/C++/Step 03/10871.cpp | UTF-8 | 258 | 2.734375 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main() {
int n, x;
cin >> n >> x;
int arr[n];
for(int i=0; i<n; i++) {
cin >> arr[i];
}
for(int j=0; j<n; j++) {
if(arr[j]<x) cout << arr[j] << " ";
}
return 0;
} | true |
906ea618906f01cec9c43de5b2d2ad21dfd6255d | C++ | NyuuDorian/fuzzy_system | /CW_linear_classfication/algo.cpp | UTF-8 | 14,955 | 2.609375 | 3 | [] | no_license | //GET THE SIGN TO GET THE CLASS ! :D
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
#include <ctgmath>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;
/*#define PHI 0
#define ETA 0
#define A 1*/
//#define NBRE_POINTS 2000
//#define NBRE_COORD 8
#define NBRE_ITERATION 10
/*
double norme(x)
{
double NORME_X(0);
return NORME_X;
}
double** produit_matriciel()
{
}*/
//MU=calculate_MU_i_plus_1(MU, SIGMA, matrice_of_all_coord[j], ALPHA, matrice_of_all_value[j], NBRE_COORD);
inline double* calculate_MU_i_plus_1(double* MU_i, double* SIGMA_i, double* X_i, double alpha_i, int y_i, int dim)
{
//double* new_MU=new double[dim];
//double new_MU[dim];
for(int j=0; j<dim; j++)
{
//if(X_i[j]!=0) cout << j << "\tinit_new_MU " << new_MU[j] << "\tnew_MU_calc ";
//new_MU[j]=MU_i[j]+alpha_i*y_i*SIGMA_i[j]*X_i[j];
MU_i[j]+=alpha_i*y_i*SIGMA_i[j]*X_i[j];
/*if(X_i[j]!=0)
{
//cout << new_MU[j] << "\tMU " << MU_i[j] << "\tSIGMA " << SIGMA_i[j] << "\tX_i " << X_i[j] << "\talpha_i " << alpha_i << "\ty_i " << y_i << endl; //HELP to detect the error
}*/
}
//return new_MU;
return MU_i;
}
inline double* calculate_inverse_SIGMA_i(double* SIGMA, int dim, double* inverse_SIGMA)
{
//double* inverse_SIGMA=new double[dim];
//double inverse_SIGMA[dim];
for(int i=0; i<dim; i++)
{
if(SIGMA[i]==0) inverse_SIGMA[i]=0;
else inverse_SIGMA[i]=1/SIGMA[i];
}
return inverse_SIGMA;
}
inline double* calculate_inverse_SIGMA_i_plus_1(int y_i, double* inverse_SIGMA_i, double* DIAG_X_i, double alpha_i, double phi, int dim)
{
//double* new_inverse_SIGMA=new double[dim];
//double new_inverse_SIGMA[dim];
for(int j=0; j<dim; j++)
{
//new_inverse_SIGMA[j]=inverse_SIGMA_i[j]+2*alpha_i*phi*DIAG_X_i[j];
inverse_SIGMA_i[j]+=2*alpha_i*y_i*phi*DIAG_X_i[j];
}
//return new_inverse_SIGMA;
return inverse_SIGMA_i;
}
inline double* diag_X_i( double* X, int dim, double* diag_X)
{
//double* diag_X = new double[dim];
//double diag_X[dim];
for(int i=0; i<dim; i++)
{
diag_X[i]=pow(X[i],2);
}
return diag_X;
}
inline double calculate_GAMMA_i(int y_i, double* x_i, double* MU_i, double* SIGMA_i, int dim, double PHI)
{
double GAMMA(0), M_i(0), V_i(0);
//M_i=y_i*(x_i*MU_i);
for(int j=0; j<dim; j++)
{
M_i+=x_i[j]*MU_i[j];
}
M_i*=y_i;
// cerr << "M_i " << M_i << "\t";
//V_i=tranposee_x_i*SIGMA_i*x_i;
for(int j=0; j<dim; j++)
{
V_i+=x_i[j]*SIGMA_i[j]*x_i[j];
}
if(V_i==0) V_i=0.00000001;
// cerr << "V_i " << V_i << "\t";
// double tmp((1+2*PHI*M_i ) - (8 * PHI * (M_i -PHI*V_i )));
GAMMA=( -(1+2*PHI*M_i) + sqrt( pow(1+2*PHI*M_i, 2 ) - (8 * PHI * (M_i -PHI*V_i )) ))/(4*PHI*V_i);
// cerr << "tmp " << tmp << "\t";
// cerr << "GAMMA " << GAMMA << endl;
return GAMMA;
}
//ALPHA=calculate_ALPHA_i(matrice_of_all_value[j], matrice_of_all_coord[j], MU, SIGMA, NBRE_COORD, phi);
inline double calculate_ALPHA_i(int y_i, double* x_i, double* MU_i, double* SIGMA_i, int dim, double PHI)
{
double ALPHA(0), GAMMA=calculate_GAMMA_i(y_i, x_i, MU_i, SIGMA_i, dim, PHI);
ALPHA=max(GAMMA, (double)0);
// cout << ALPHA << endl;
return ALPHA;
}
//permet de melanger de maniere aleatoire les donnees recue creant ainsi des donnees totalement random
void randomly_mix(double** matrice_of_all_coord, int* matrice_of_all_value, int NBRE_POINTS, int NBRE_COORD)
{
vector< vector<double> > matrice_of_all_coord_tmp;
vector<int> matrice_of_all_value_tmp;
int nb_rand(0), nbre_datas(NBRE_POINTS);
for(int i=0; i<NBRE_POINTS; i++)
{
vector<double> matrice_of_all_coord_tmp_bis;
for(int j=0; j<NBRE_COORD; j++)
{
matrice_of_all_coord_tmp_bis.push_back(matrice_of_all_coord[i][j]);
}
matrice_of_all_coord_tmp.push_back(matrice_of_all_coord_tmp_bis);
matrice_of_all_value_tmp.push_back(matrice_of_all_value[i]);
}
for(int i=0; i<NBRE_POINTS; i++)
{
nb_rand = rand() % nbre_datas;
nbre_datas--;
for(int j=0; j<NBRE_COORD; j++)
{
matrice_of_all_coord[i][j]=matrice_of_all_coord_tmp[nb_rand][j];
}
matrice_of_all_value[i]=matrice_of_all_value_tmp[nb_rand];
matrice_of_all_coord_tmp.erase(matrice_of_all_coord_tmp.begin()+nb_rand);
matrice_of_all_value_tmp.erase(matrice_of_all_value_tmp.begin()+nb_rand);
}
//check the new matrix created ==> seems OK
/*for(int i=0; i<NBRE_POINTS; i++)
{
for(int j=0; j<NBRE_COORD; j++)
{
cout << matrice_of_all_coord[i][j] << "\t";
}
cout << matrice_of_all_value[i] << endl;
}*/
}
int main(int argc, char** argv)
{
if(argc!=2) return -1;
else
{
string title_doc(argv[1]);
int NBRE_POINTS(0), NBRE_COORD(0), NBRE_CLASSES(0);
ifstream fichier(title_doc+".txt");
if(fichier)
{
fichier.seekg(0, ios::beg);//placed at the very beginning
//will able us to get each word
fichier >> NBRE_POINTS;
cout << NBRE_POINTS << endl;
fichier >> NBRE_COORD;
cout << NBRE_COORD << endl;
fichier >> NBRE_CLASSES;
cout << NBRE_CLASSES << endl;
}
else cout << "Cannot open the file to read" << endl;
//x_i belongs to R^d
//y_i belongs to {-1,+1}
//w_i+1=w_i+alpha_i*y_i*x_i
//alpha_i = max( (1 - y_i(w_i . x_i)) / ||x_i||^2 , (double)0)
//Sigma belongs to R^d_x_d
//MU_i+1 = MU_i * alpha_i * y_i * SIGMA_i * x_i
//double Φ=PHI, η=ETA; //initial parameters
double phi=1; //confidence parameter φ = Φ^(-1)(η); ou Φ^(-1) est la fonction inverse de Φ
double a = 0.1; //initial variance parameter, a>0
// initialisation
double* MU=new double[NBRE_COORD]; // all points initialized to 0
double* SIGMA=new double[NBRE_COORD]; //TODO LIST : SIGMA[0] = a * I avec I matrice unite ds d_x_d
double* inverse_SIGMA=new double[NBRE_COORD];
double* diag_X=new double[NBRE_COORD];
double ALPHA(0);
double** matrice_of_all_coord= new double*[NBRE_POINTS];
int* matrice_of_all_value= new int[NBRE_POINTS];//value -1 or +1
int* matrice_of_all_prediction_value= new int[NBRE_POINTS];//value -1 or +1
bool can_read_next(true);
vector<int> mat_of_all_points_rank;
for(int i=0; i<NBRE_POINTS; i++) matrice_of_all_coord[i]=new double[NBRE_COORD];
for(int i=0; i<NBRE_COORD; i++) MU[i]=0;
//TODO LIST INITIATE matrice_of_all_coord ==> DONE
//TODO LIST INITIATE matrice_of_all_value ==> DONE
//TODO LIST CALC matrice_of_all_prediction_value --> sign(x.w) ==> DONE
//ifstream fichier("output_bis.txt");
if(fichier)
{
fichier.seekg(0, ios::beg);//placed at the very beginning
string mot("");//will able us to get each word
fichier >> mot;
fichier >> mot;
fichier >> mot;
for(int i=0; i<NBRE_POINTS; i++)
{
//std::vector<double> tempvector,tempvector2;
//coord.push_back(0);
//
//cout << nb_rand << endl;
//num_files_used_class_0.push_back(nb_rand);//we keep it to know which file had been used
//TODO LIST have to change the way of reading the file ==> DONE
for(int j=0; j<NBRE_COORD; j++)
{
if(can_read_next)
{
fichier >> mot; //read "place"
can_read_next=false;
}
if(j==stoi(mot))
{
fichier >> mot; //read ":"
fichier >> mot; //read "normalized nb"
//cout << mot << " ";
//tempvector.push_back(stod(mot));
matrice_of_all_coord[i][j]=stod(mot);
can_read_next=true;
}
else matrice_of_all_coord[i][j]=0;
}
if(stoi(mot)!=NBRE_COORD)
fichier >> mot; //read NBRE_COORD IFF this one has not already been read before
//cout << mot << "\t";
fichier >> mot; //read ":"
//cout << mot << "\t";
//coord.push_back(tempvector);
fichier >> mot; //read CLASS
//cout << mot << endl;
if(stoi(mot)==0) matrice_of_all_value[i]=-1;
else matrice_of_all_value[i]=stoi(mot);
//class_value.push_back(stoi(classe));
can_read_next=true;
//cout << matrice_of_all_value[i] << " ";
}
}
else
{
cout << "ERROR: Cannot open fichier on reading mode." << endl;
}
//TEST mat of all coord correctly initialized ? ==> recup of datas seems OK
/*for(int i=0; i<NBRE_POINTS; i++)
{
for(int j=0; j<NBRE_COORD; j++)
{
if(matrice_of_all_coord[i][j]!=0 && i<10) cout << j << " : " << matrice_of_all_coord[i][j] << " ";
}
cout << endl;
}*/
//INITIALIZATION OF SIGMA, only for i=0, the others members have to be calculated by the algorithm
for(int j=0; j<NBRE_COORD; j++)
{
SIGMA[j]=a;
//cout << SIGMA[j] << " ";
inverse_SIGMA[j]=1/a;
//cout << inverse_SIGMA[j] << endl;
}
//initialisation of SIGMA
//NOW APPLY VARIANCE ALGORITHM
//calculate MU_i+1 && SIGMA_i+1^(-1)
// μ i+1 = μ i + α i y i Σ i x i ==> α==ALPHA
// Σ ^(−1) i+1 = Σ^−1 i + 2α i φ diag (x i ) ==> a==ALPHA
//where diag (x i ) is a diagonal matrix with the square
//of the elements of x i on the diagonal.
/*for(int i=0; i<NBRE_POINTS, i++)
{
alpha_i = max( (1 - y_i(w_i . x_i)) / pow(norme(x_i),2) , (double)0)
calculate_ALPHA_i();
calculate_MU_i_plus_1();
calculate_inverse_SIGMA_i_plus_1();
}*/
//mix randomly the datas
srand(time(0));
randomly_mix(matrice_of_all_coord, matrice_of_all_value, NBRE_POINTS, NBRE_COORD);
int data_fold_beginning[NBRE_ITERATION]={0}, data_fold_ending[NBRE_ITERATION]={0};
for(int i=0; i<NBRE_ITERATION; i++)
{
data_fold_beginning[i]=i*NBRE_POINTS/NBRE_ITERATION;
if(i!=NBRE_ITERATION-1) data_fold_ending[i]=i*NBRE_POINTS/NBRE_ITERATION+NBRE_POINTS/NBRE_ITERATION;
else data_fold_ending[i]=NBRE_POINTS;
}
double moyenne_pourcentage(0);
ofstream test_result("test_result_"+ title_doc +".txt");
if(test_result)
{
for(int i=0; i<NBRE_ITERATION; i++)
{
for(int z=0; z<NBRE_COORD; z++) MU[z]=0;//initiliasition everything at 0
//initiliser MU et SIGMA avec des valeurs aleatoires entre -1 et 1, (eventuellement eviter le 0 ? pour la diagonale de SIGMA)
//SIGMA etant une matrice diagonale, nous utilisont un vecteur (moins lourd et facilite les calculs)
for(int z=0; z<NBRE_COORD; z++)
{
//MU[i]=0;
SIGMA[z]=a;
inverse_SIGMA[z]=1/a;
}
mat_of_all_points_rank.clear();
for(int z=0; z<NBRE_POINTS; z++) mat_of_all_points_rank.push_back(z);//initialisation of vector<int> mat_of_all_points_rank;
for(int z=data_fold_beginning[i]; z<data_fold_ending[i]; z++) mat_of_all_points_rank.erase(mat_of_all_points_rank.begin()+data_fold_beginning[i]);//removing all points belonging to the validation dataset
int taille((int)mat_of_all_points_rank.size());
for(int n=0; n<taille; n++)
//for(int j=i*NBRE_POINTS/10; j<i*NBRE_POINTS/10+NBRE_POINTS/10; j++)
{
// cout << j << endl;
int nb_rand = rand() % mat_of_all_points_rank.size();
//TODO LIST update alpha ==> DONE
//cerr << j << "\t";
ALPHA=calculate_ALPHA_i(matrice_of_all_value[mat_of_all_points_rank[nb_rand]], matrice_of_all_coord[mat_of_all_points_rank[nb_rand]], MU, SIGMA, NBRE_COORD, phi);
//ALPHA=calculate_ALPHA_i(matrice_of_all_value[j], matrice_of_all_coord[j], MU, SIGMA, NBRE_COORD, phi);
//if(j<10) cout << ALPHA << endl;
//cout << j << "\t" << ALPHA << endl;
//inverse_SIGMA=calculate_inverse_SIGMA_i(SIGMA, NBRE_COORD);
//test de la fonction inverse sigma
/*for(int k=0; k<NBRE_COORD; k++)
{
if(j<50) cout << inverse_SIGMA[k] << " ";
}*/
/*SIGMA=*/calculate_inverse_SIGMA_i(inverse_SIGMA, NBRE_COORD, SIGMA);//inverse of inverse gives natural
//test de la fonction inverse sigma
/*if(j<50) cout << endl;
for(int k=0; k<NBRE_COORD; k++)
{
if(j<50) cout << SIGMA[k] << " ";
}
if(j<50) cout << endl << endl;*/
calculate_MU_i_plus_1(MU, SIGMA, matrice_of_all_coord[mat_of_all_points_rank[nb_rand]], ALPHA, matrice_of_all_value[mat_of_all_points_rank[nb_rand]], NBRE_COORD);
// /*MU=*/calculate_MU_i_plus_1(MU, SIGMA, matrice_of_all_coord[j], ALPHA, matrice_of_all_value[j], NBRE_COORD);
//TEST OF MU CALC ==> NOT OK
/*for(int k=0; k<NBRE_COORD; k++)
{
if(j<2 && MU[k]!=0) cout << MU[k] << "\t";
}
if(j<2) cout << endl;*/
diag_X_i(matrice_of_all_coord[mat_of_all_points_rank[nb_rand]], NBRE_COORD, diag_X);
// diag_X_i(matrice_of_all_coord[j], NBRE_COORD, diag_X);
/*inverse_SIGMA=*/calculate_inverse_SIGMA_i_plus_1(matrice_of_all_value[mat_of_all_points_rank[nb_rand]], inverse_SIGMA, diag_X, ALPHA, phi, NBRE_COORD);
//TEST OF INVERSE SIGMA
/*for(int k=0; k<NBRE_COORD; k++)
{
if(j<2 && inverse_SIGMA[k]!=10) cout << inverse_SIGMA[k] << "\t";
}
if(j<2) cout << endl;*/
}
int counter_correct_classification(0);
double classifier(0);
//int minus_pos(0), maxi_pos(0), null_pos(0);
for(int m=data_fold_beginning[i]; m<data_fold_ending[i]; m++)
//for( int k=i*NBRE_POINTS/10+NBRE_POINTS/10; k<i*NBRE_POINTS/10+2*NBRE_POINTS/10; k++ ) //on decale de +NBRE_POINTS/10 pour avoir les 200 points TESTS
{
int tmp(m);
//if(k<NBRE_POINTS) tmp=k;
//else tmp=k-NBRE_POINTS;
classifier = 0;
for( int l=0; l<NBRE_COORD; l++ ){
classifier += matrice_of_all_coord[tmp][l] * MU[l];
}
//cout << k << " " << classifier << endl;
if( classifier > 0 ) matrice_of_all_prediction_value[tmp] = 1;
else if (classifier < 0 ) matrice_of_all_prediction_value[tmp] = -1;
else {matrice_of_all_prediction_value[tmp]=0; /*cout << "TIC ";*/}
if( matrice_of_all_prediction_value[tmp]==matrice_of_all_value[tmp] ) counter_correct_classification++;
/*classifier = 0;
for( int l=0; l<NBRE_COORD; l++ ){
classifier += matrice_of_all_coord[k][l] * MU[l];
}
//cout << k << " " << classifier << endl;
if( classifier > 0 ) matrice_of_all_prediction_value[k] = 1;
else if (classifier < 0 ) matrice_of_all_prediction_value[k] = -1;
else {matrice_of_all_prediction_value[k]=0; }
if( matrice_of_all_prediction_value[k]==matrice_of_all_value[k] ) counter_correct_classification++;*/
//else if(matrice_of_all_prediction_value[k]==-1) minus_pos++;
//else if(matrice_of_all_prediction_value[k]==1) maxi_pos++;
//else if(matrice_of_all_prediction_value[k]==0) null_pos++;
}
//if(j<50) cout << counter_correct_classification << endl ;
int nbre_elt((data_fold_ending[i]-1)-data_fold_beginning[i]+1);
test_result << "iteration " << i << "\t" << (double)counter_correct_classification*100/nbre_elt << " %" << endl;//" " << minus_pos << " " << maxi_pos << " " << null_pos << endl;
cout << "iteration " << i << "\t" << (double)counter_correct_classification*100/nbre_elt << " %" << endl;
moyenne_pourcentage+=(double)counter_correct_classification*100/nbre_elt;
}
}
else cout << "cannot write on test_result" << endl;
test_result << "mean_% " << moyenne_pourcentage/NBRE_ITERATION << " %" << endl;
cout << "mean_% " << moyenne_pourcentage/NBRE_ITERATION << " %" << endl;
//delete matrix_for_calc_of_membership_func;
delete MU;
delete SIGMA;
delete inverse_SIGMA;
delete diag_X;
delete matrice_of_all_coord;
delete matrice_of_all_value;//value -1 or +1
delete matrice_of_all_prediction_value;//value -1 or +1
return EXIT_SUCCESS;
}
}
| true |
f469f302972c6b92dddc44d2d34bf24c493ad896 | C++ | ObitoLee/slamBase | /src/generatePointCloud.cpp | UTF-8 | 837 | 2.578125 | 3 | [] | no_license | #include"slamBase.h"
// 相机内参
CAMERA_INTRINSIC_PARAMETERS camera={325.5,253.5,518.0,519.0,1000};
// 主函数
int main( int argc, char** argv )
{
Mat rgb, depth;
rgb = imread( "./data/rgb.png" );// rgb 图像是8UC3的彩色图像
depth = imread( "./data/depth.png", -1 );// depth 是16UC1的单通道图像,注意flags设置-1,表示读取原始数据不做任何修改
// 点云变量
// 使用智能指针,创建一个空点云。这种指针用完会自动释放。
PointCloud::Ptr cloud ( new PointCloud );
cloud = image2PointCloud(rgb,depth,camera);
cout << "point cloud size = "<< cloud->points.size() << endl;
pcl::io::savePCDFile( "./data/pointcloud.pcd", *cloud );
// 清除数据并退出
cloud->points.clear();
cout << "Point cloud saved." << endl;
return 0;
}
| true |
a76cc13e493e07a12eef8813c3b1651d3863155e | C++ | resoliwan/cprimary | /l17/check_it.cpp | UTF-8 | 599 | 2.609375 | 3 | [] | no_license | #include <iostream>
int main(void)
{
using namespace std;
// cout << "Enter numbers: " << endl;
// int number;
// if (cin >> number) {
// std::cout << number << std::endl;
// } else {
// std::cout << "Input is not a number" << std::endl;
// }
//
//
char arr[20];
int num;
cout << "Enter number;char" << endl;
cin >> num >> arr;
cout << "arr: " << arr << endl;
cout << "num: " << num << endl;
// cout << "ch: " << ch << endl;
return 0;
}
// clang++ -std=c++11 -Wno-c++11-extensions l17/check_it.cpp && ./a.out
| true |
91c542f6794557c6494e86c81f7bcb8d5b3e5501 | C++ | Klarsch/ProblemC_Pathfinding | /ProblemC_Pathfinding/Node.h | UTF-8 | 1,794 | 3.234375 | 3 | [] | no_license | #pragma once
#include "V2Dint.h"
class Node
{
public:
Node();
const unsigned& getNodeID() const { return ID; }
void setNodeID( const unsigned idIn ) { ID = idIn; }
const unsigned& getNodeType() const { return Type; }
void setNodeType( const unsigned typeIn ) { Type = typeIn; }
const V2Dint& getPosition() const { return Position; }
void setPosition( const V2Dint positionIn ) { Position = positionIn; }
void setPosition( const unsigned positionInX, const unsigned positionInY ) { Position.x = positionInX; Position.y = positionInY;}
const bool& getIsClosed() const { return IsClosed; }
void setIsClosed( bool input ) { IsClosed = input; }
void CloseNode() { IsClosed = true; }
const bool& getIsValid() const { return IsValid; }
void setIsValid(bool input) { IsValid = input; }
void ValidateNode() { IsValid = true; }
Node* getParent() const { return pParentNode; }
void setParentNode( Node* nodeIn ) { pParentNode = nodeIn; }
const unsigned& getDistanceFromStart() const { return DistanceFromStart; }
const float& getHeuristic() const { return Heuristic; }
void CalculateHeuristic(V2Dint start, V2Dint position, V2Dint target );
bool operator!=( const Node* other )
{
return !( ID == other->ID
&& Type == other->Type
&& pParentNode == other->pParentNode
&& Heuristic == other->Heuristic
);
}
bool operator==( const Node* other )
{
return ( ID == other->ID
&& Type == other->Type
&& pParentNode == other->pParentNode
&& Heuristic == other->Heuristic
);
}
bool operator() (const Node* left, const Node* right )
{
return left->Heuristic > right->Heuristic;
}
private:
unsigned ID;
unsigned char Type;
V2Dint Position;
bool IsClosed;
bool IsValid;
Node* pParentNode;
unsigned DistanceFromStart;
float Heuristic;
}; | true |
aefede59cf5797665df0763c509c472d72a7b420 | C++ | viditrastogi11/DSA | /practice/linkedlist.cpp | UTF-8 | 1,274 | 3.328125 | 3 | [] | no_license | #include<iostream>
using namespace std;
typedef struct node{
int data;
struct node* next;
} node;
node* insertlinked(node *head,int val)
{
if(head==NULL)
{
head=new node();
head->data=val;
head->next=NULL;
return head;
}
node *head1=head;
while(head1->next!=NULL)
{
head1=head1->next;
}
node *temp=new node();
temp->data=val;
temp->next=NULL;
head1->next=temp;
return head;
}
void printlinked(node *head)
{
while(head!=NULL)
{
cout<<head->data;
head=head->next;
}
}
node* deletekth(node *head,int k)
{
int c=0;
node* temp=head;
while(temp!=NULL)
{
temp=temp->next;
c++;
}
if(c-k==0)
{
temp=head;
head=head->next;
free(temp);
return head;
}
node *head1=head;
while(c-k-1)
{
head=head->next;
c--;
}
temp=head->next;
head->next=temp->next;
free(temp);
return head1;
}
int main()
{
node *head=NULL;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
int val;
cin>>val;
head=insertlinked(head,val);
}
printlinked(head);
int k;
cin>>k;
head= deletekth(head,k);
printlinked(head);
}
| true |
07d158fb0ea1432b033f841c091dc4fa73dc8977 | C++ | vcato/qt-quick-6502-emulator | /unit_tests/zero_page_mode_ASL.cpp | UTF-8 | 6,902 | 2.796875 | 3 | [] | no_license | #include "addressing_mode_helpers.hpp"
struct ASL_ZeroPage_Expectations
{
uint8_t a;
NZCFlags flags;
uint8_t operand; // Data to be operated upon in Zero Page
};
using ASLZeroPage = ASL<ZeroPage, ASL_ZeroPage_Expectations, 5>;
using ASLZeroPageMode = ParameterizedInstructionExecutorTestFixture<ASLZeroPage>;
static void StoreTestValueAtEffectiveAddress(InstructionExecutorTestFixture &fixture, const ASLZeroPage &instruction_param)
{
fixture.fakeMemory[instruction_param.address.zero_page_address] = instruction_param.requirements.initial.operand;
}
static void SetupAffectedOrUsedRegisters(InstructionExecutorTestFixture &fixture, const ASLZeroPage &instruction_param)
{
fixture.r.a = instruction_param.requirements.initial.a;
fixture.r.SetFlag(FLAGS6502::N, instruction_param.requirements.initial.flags.n_value.expected_value);
fixture.r.SetFlag(FLAGS6502::Z, instruction_param.requirements.initial.flags.z_value.expected_value);
fixture.r.SetFlag(FLAGS6502::C, instruction_param.requirements.initial.flags.c_value.expected_value);
}
template<>
void LoadInstructionIntoMemoryAndSetRegistersToInitialState( InstructionExecutorTestFixture &fixture,
const ASLZeroPage &instruction_param)
{
SetupRAMForInstructionsThatHaveAnEffectiveAddress(fixture, instruction_param);
SetupAffectedOrUsedRegisters(fixture, instruction_param);
}
template<>
void RegistersAreInExpectedState(const Registers ®isters,
const ASL_ZeroPage_Expectations &expectations)
{
EXPECT_THAT(registers.a, Eq(expectations.a));
EXPECT_THAT(registers.GetFlag(FLAGS6502::N), Eq(expectations.flags.n_value.expected_value));
EXPECT_THAT(registers.GetFlag(FLAGS6502::Z), Eq(expectations.flags.z_value.expected_value));
EXPECT_THAT(registers.GetFlag(FLAGS6502::C), Eq(expectations.flags.c_value.expected_value));
}
template<>
void MemoryContainsInstruction(const InstructionExecutorTestFixture &fixture,
const Instruction<AbstractInstruction_e::ASL, ZeroPage> &instruction)
{
EXPECT_THAT(fixture.fakeMemory.at( fixture.executor.registers().program_counter ), Eq( OpcodeFor(AbstractInstruction_e::ASL, AddressMode_e::ZeroPage) ));
EXPECT_THAT(fixture.fakeMemory.at( fixture.executor.registers().program_counter + 1), Eq(instruction.address.zero_page_address));
}
template<>
void MemoryContainsExpectedComputation(const InstructionExecutorTestFixture &fixture,
const ASLZeroPage &instruction)
{
EXPECT_THAT(fixture.fakeMemory.at( instruction.address.zero_page_address ), Eq(instruction.requirements.initial.operand));
}
template<>
void MemoryContainsExpectedResult(const InstructionExecutorTestFixture &fixture,
const ASLZeroPage &instruction)
{
EXPECT_THAT(fixture.fakeMemory.at( instruction.address.zero_page_address ), Eq(instruction.requirements.final.operand));
}
static const std::vector<ASLZeroPage> ASLZeroPageModeTestValues {
ASLZeroPage{
// Beginning of a page
ZeroPage().address(0x8000).zp_address(6),
ASLZeroPage::Requirements{
.initial = {
.a = 0,
.flags = { },
.operand = 0 },
.final = {
.a = 0,
.flags = {
.n_value = { .expected_value = false },
.z_value = { .expected_value = true },
.c_value = { .expected_value = false } },
.operand = 0
}}
},
ASLZeroPage{
// Middle of a page
ZeroPage().address(0x8080).zp_address(6),
ASLZeroPage::Requirements{
.initial = {
.a = 0,
.flags = { },
.operand = 0 },
.final = {
.a = 0,
.flags = {
.n_value = { .expected_value = false },
.z_value = { .expected_value = true },
.c_value = { .expected_value = false } },
.operand = 0
}}
},
ASLZeroPage{
// End of a page
ZeroPage().address(0x80FE).zp_address(6),
ASLZeroPage::Requirements{
.initial = {
.a = 0,
.flags = { },
.operand = 0 },
.final = {
.a = 0,
.flags = {
.n_value = { .expected_value = false },
.z_value = { .expected_value = true },
.c_value = { .expected_value = false } },
.operand = 0
}}
},
ASLZeroPage{
// Crossing a page boundary
ZeroPage().address(0x80FF).zp_address(6),
ASLZeroPage::Requirements{
.initial = {
.a = 0,
.flags = { },
.operand = 0 },
.final = {
.a = 0,
.flags = {
.n_value = { .expected_value = false },
.z_value = { .expected_value = true },
.c_value = { .expected_value = false } },
.operand = 0
}}
},
ASLZeroPage{
// Check for High bit going into carry
ZeroPage().address(0x8000).zp_address(6),
ASLZeroPage::Requirements{
.initial = {
.a = 1,
.flags = { },
.operand = 0b10101010 },
.final = {
.a = 1,
.flags = {
.n_value = { .expected_value = false },
.z_value = { .expected_value = false },
.c_value = { .expected_value = true } },
.operand = 0b01010100
}}
},
ASLZeroPage{
// Check for N flag
ZeroPage().address(0x8000).zp_address(6),
ASLZeroPage::Requirements{
.initial = {
.a = 0xFF,
.flags = { },
.operand = 0b11101010 },
.final = {
.a = 0xFF,
.flags = {
.n_value = { .expected_value = true },
.z_value = { .expected_value = false },
.c_value = { .expected_value = true } },
.operand = 0b11010100
}}
},
ASLZeroPage{
// Zero is set in lowest bit
ZeroPage().address(0x8000).zp_address(6),
ASLZeroPage::Requirements{
.initial = {
.a = 0x00,
.flags = { },
.operand = 0b00000001 },
.final = {
.a = 0x00,
.flags = {
.n_value = { .expected_value = false },
.z_value = { .expected_value = false },
.c_value = { .expected_value = false } },
.operand = 0b00000010
}}
}
};
TEST_P(ASLZeroPageMode, TypicalInstructionExecution)
{
TypicalInstructionExecution(*this, GetParam());
}
INSTANTIATE_TEST_SUITE_P(ArithmeticShiftLeftZeroPageAtVariousAddresses,
ASLZeroPageMode,
testing::ValuesIn(ASLZeroPageModeTestValues) );
| true |
02725b43dc09ca67011305a3db4e148e83217a95 | C++ | ivlevAstef/PrototypeCarGame | /src/Models/CarEquipment.h | UTF-8 | 682 | 2.53125 | 3 | [] | no_license | //
// File: CarEquipment.h
// Description:
// Author: Ivlev Alexander. Stef
// Created: 18:57 28/01/2016
// Copyright (c) SIA 2016. All Right Reserved.
//
#pragma once
#ifndef _MODELS_CAR_EQUIPMENT_H_
#define _MODELS_CAR_EQUIPMENT_H_
namespace Models {
class CarEquipment {
public:
double mass() const {
return 1000; //kg
}
double enginePower() const {
return 250; //hp - horse power
}
double airFriction() const {
return 0.001;
}
double rotateFriction() const {
return 0.09;
}
double wheelLengthFriction() const {
return 0.002;
}
double wheelCrossFriction() const {
return 0.025;
}
private:
};
};
#endif /* _MODELS_CAR_EQUIPMENT_H_ */
| true |
f36ed62d2b98e99378e71caf0f68c0fde9f89f29 | C++ | ooooo-youwillsee/leetcode | /0501-1000/0518-Coin Change 2/cpp_0518/Solution1.h | UTF-8 | 676 | 2.90625 | 3 | [
"MIT"
] | permissive | /**
* @author ooooo
* @date 2021/2/17 19:21
*/
#ifndef CPP_0518__SOLUTION1_H_
#define CPP_0518__SOLUTION1_H_
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int change(int amount, vector<int> &coins) {
int n = coins.size();
vector<vector<int>> dp(amount + 1, vector<int>(n + 1, 0));
for (int i = 1; i <= n; ++i) {
dp[0][i] = 1;
}
dp[0][0] = 1;
for (int i = 1; i <= amount; ++i) {
for (int j = 0; j < n; ++j) {
int coin = coins[j], cnt = 0;
while (i - cnt * coin >= 0) {
dp[i][j + 1] += dp[i - cnt * coin][j];
cnt++;
}
}
}
return dp[amount][n];
}
};
#endif //CPP_0518__SOLUTION1_H_
| true |
5ad3c25551657732a7fa5d7069a6ab29ca9fb76a | C++ | PrayagPatel-007/Cpp-basics | /Add_2_num_using_dll.cpp | UTF-8 | 1,981 | 3.265625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
struct dlnode {
struct dlnode *left;
int data;
struct dlnode *right;
};
typedef struct dlnode *dlptr;
void create_dll (dlptr &D){
int n;
char c;
cin>>c;
if(c != '#'){
n = c-'0';
if(D == NULL){
D = new(dlnode);
D -> data = n;
D -> left = NULL;
D -> right = NULL;
create_dll(D);
} else {
dlptr T = new(dlnode);
T -> data = n;
T -> left = D;
T -> right = NULL;
D -> right = T;
create_dll(T);
}
}
}
void insert_left(dlptr &D, int n){
if(D == NULL){
D = new(dlnode);
D->right=NULL;
D->left=NULL;
D->data=n;
} else {
dlptr T = new(dlnode);
T -> left = NULL;
T -> right = D;
T -> data = n;
D -> left = T;
D = T;
}
}
void add_ (dlptr D1, dlptr D2, dlptr &D3, int carry){
if(D1 != NULL && D2 != NULL){
int sum = D1->data + D2->data + carry;
carry=sum/10;
sum=sum%10;
insert_left(D3, sum);
add_(D1->left, D2->left, D3, carry);
} else if (D1 == NULL && D2 != NULL) {
int sum = D2->data + carry;
carry=sum/10;
sum=sum%10;
insert_left(D3, sum);
add_(D1, D2->left, D3, carry);
} else if (D1 != NULL && D2 == NULL){
int sum = D1->data + carry;
carry=sum/10;
sum=sum%10;
insert_left(D3, sum);
add_(D1->left, D2, D3, carry);
} else if(carry != 0) {
int sum =carry;
sum=sum%10;
insert_left(D3, sum);
return;
} else {
return;
}
}
dlptr last_node(dlptr D){
if(D == NULL){
return D;
}
if(D->right == NULL){
return D;
}
last_node(D->right);
}
void print(dlptr D){
if(D != NULL){
cout<<D->data;
print(D->right);
}
}
int main(){
dlptr D1 = NULL, D2 = NULL, D3= NULL;
create_dll(D1);
create_dll(D2);
add_(last_node(D1), last_node(D2), D3, 0);
print(D3);
return 0;
} | true |
a47c9c138296bd16abc36502d7ed728694859105 | C++ | mohi-othman/ray-tracer-cpp-mohi | /RayTraceEbtihal/View.h | UTF-8 | 1,012 | 3.4375 | 3 | [] | no_license | //Class used to store data on the view that results from a scene rendering
#ifndef VIEW_H
#define VIEW_H
#include "Color.h"
#include "Vector3D.h"
class Point //Class used to store data on a single point in the view
{
public:
struct {
Color color; //Color of the point
float depth; //Distance from camera
Vector3D realCoordinate; //Real coordinates of the point
};
Point(void){}; //default constructor
//Main constructor
Point(Color myColor, float myDepth, Vector3D myCoord) : color(myColor),depth(myDepth),realCoordinate(myCoord){};
};
// View class
class View
{
public:
Point* Pixels; //Array to store data on all pixels
int Width; //Width of the view in pixels
int Height; //Height of the view in pixels
View(int width, int height, Vector3D topLeftCorner, Vector3D topRightCorner, Vector3D bottomLeftCorner, Vector3D bottomRightCorner); //Main constructor
Point GetPixel(int x, int y); //Retrieves a pixel at a given coordinate
};
#endif | true |
1d099c4d56e1f43d5ad2bcd6eeddfc3c55a4c9a1 | C++ | OverDrive1g/custom-timer | /sketch_feb14a.ino | UTF-8 | 3,072 | 2.578125 | 3 | [] | no_license | #include "GyverEncoder.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <DS3231.h>
//#include <EEPROM.h>
LiquidCrystal_I2C lcd(0x27,16,2);
RTClib myRTC;
DS3231 rtc;
Encoder enc(2,3,4);
void initLed(){
pinMode(5, OUTPUT);
pinMode(6, OUTPUT);
}
int t1sleep = 1;
int t1active = 1;
int t1counter = 0;
bool t1flag = false;
int t2sleep = 1;
int t2active = 1;
int t2counter = 0;
bool t2flag = false;
// 0 - работает таймер
// 10 - изменить таймер 1
// 20 - изменить таймер 2
int status = 0;
void printTimer(int t){
lcd.setCursor(0,0);
if(t == 1){
lcd.print("T1 sleep = ");
lcd.print(t1sleep);
}
if(t == 2){
lcd.print("T1 active = ");
lcd.print(t1active);
}
if(t == 3){
lcd.print("T2 sleep = ");
lcd.print(t2sleep);
}
if(t == 4){
lcd.print("T2 active = ");
lcd.print(t2active);
}
}
void setup() {
Serial.begin(9600);
initLed();
lcd.init();
lcd.backlight();
}
void t1tick(){
t1counter +=1;
if(t1flag & t1counter >= t1sleep){
t1counter = 0;
t1flag = !t1flag;
digitalWrite(5, 1);
return;
}
if(!t1flag & t1counter >= t1active){
t1counter = 0;
t1flag = !t1flag;
digitalWrite(5, 0);
return;
}
}
void t2tick(){
t2counter +=1;
if(t2flag & t2counter >= t2sleep){
t2counter = 0;
t2flag = !t2flag;
digitalWrite(6, 1);
return;
}
if(!t2flag & t2counter >= t2active){
t2counter = 0;
t2flag = !t2flag;
digitalWrite(6, 0);
return;
}
}
uint32_t old_time = 0;
bool loader = true;
void loop() {
DateTime now = myRTC.now();
uint32_t current_time = now.unixtime();
enc.tick();
if(status == 0){
if(old_time < current_time){
old_time = current_time;
t1tick();
t2tick();
lcd.setCursor(0,0);
loader = !loader;
lcd.print(loader?"Work |":"Work - ");
}
}
if(status == 0 && enc.isPress()){
lcd.clear();
status = 10;
}
if(status == 10){
printTimer(1);
if(enc.isRight()){
t1sleep += 1;
return;
}
if(enc.isLeft()){
t1sleep -= 1;
return;
}
if(enc.isPress()){
lcd.clear();
status = 11;
delay(300);
return;
}
}
if(status == 11){
printTimer(2);
if(enc.isRight()){
t1active += 1;
return;
}
if(enc.isLeft()){
t1active-= 1;
return;
}
if(enc.isPress()){
lcd.clear();
status = 20;
delay(300);
return;
}
}
if(status == 20){
printTimer(3);
if(enc.isRight()){
t2sleep += 1;
return;
}
if(enc.isLeft()){
t2sleep -= 1;
return;
}
if(enc.isPress()){
lcd.clear();
status = 21;
delay(300);
return;
}
}
if(status == 21){
printTimer(4);
if(enc.isRight()){
t2active += 1;
return;
}
if(enc.isLeft()){
t2active-= 1;
return;
}
if(enc.isPress()){
lcd.clear();
status = 0;
delay(300);
return;
}
}
}
| true |
3ac7a4bf0862dc30f8b89f7ab928ee392825d764 | C++ | shivashish123/Competitive-Programming-Codeforces | /753A.cpp | UTF-8 | 411 | 2.640625 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
int pos=0;
for(int i=1;i<=100;i++)
{
int s=(i*(i+1))/2;
if((n-s)>i)
{
pos=i;
}
else
break;
}
int dif=n-(pos*(pos+1))/2;
cout<<pos+1<<endl;
for(int i=1;i<pos;i++)
{
cout<<i<<" ";
}
cout<<dif;
}
| true |
dc967f33817b66401c7d1d05c3d01a2c065ab497 | C++ | lja9702/JinAh-BOJ | /BaekjoonOnline/2805_cuttingTree2.cpp | UTF-8 | 483 | 2.53125 | 3 | [] | no_license | #include <cstdio>
#include <algorithm>
int n, m, arr[1000010], l, r, res;
int main(){
scanf("%d %d", &n, &m);
for(int i = 0;i < n;i++){
scanf("%d", &arr[i]);
r = std::max(r, arr[i]);
}
while(l <= r){
int mid = (l + r) / 2;
long long temp = 0;
for(int i = 0;i < n;i++){
if(arr[i] - mid > 0) temp += (arr[i] - mid);
}
if(temp >= m){
l = mid + 1;
res = std::max(mid, res);
}
else r = mid - 1;
}
printf("%d\n", res);
}
| true |
5542a448e9f9bbcc6ad344ce2799faa7353fecac | C++ | adarsh1github1/Competetive-codeforces-codechef- | /rotate array by d(anti clockwise).cpp | UTF-8 | 464 | 2.875 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
void rotateArr(int arr[], int d,int n){
int i,j;
int temp[d];
for(int k=0;k<d;k++)
temp[k] = arr[k];
for(i=d;i<n;i++){
arr[i-d] = arr[i];
}
for(i=n-d;i<n;i++)
arr[i] = temp[i-(n-d)];
}
int main(){
int n;
cin>>n;
int d;
cin>>d;
int i;
int a[n];
for(i=0;i<n;i++){
cin>>a[i];
}
rotateArr(a,d,n);
for(i=0;i<n;i++){
cout<<a[i]<<" ";
}
cout<<endl;
return 0;
}
| true |
88b7975f7b6119472b634416a8d972d92318e871 | C++ | ParAlg/gbbs | /utils/to_edge_list.cc | UTF-8 | 3,816 | 3.03125 | 3 | [
"MIT"
] | permissive | #include <stdlib.h>
#include <cmath>
#include <fstream>
#include <iostream>
#include "gbbs/gbbs.h"
namespace gbbs {
/* Format:
* Emits a lexicographically sorted list of edges. The format takes (u,v)
* and writes:
* "u v\n" */
template <class Graph>
void print_edge_list(Graph& GA, std::string& outfile, bool direct_sym,
bool multistep_header) {
using W = typename Graph::weight_type;
size_t n = GA.n;
size_t m = GA.m;
auto edges = sequence<std::tuple<uintE, uintE>>(m);
auto offs = sequence<size_t>(n);
parallel_for(0, n, [&](size_t i) {
size_t ctr = 0;
if (direct_sym) {
auto f = [&](const uintE& u, const uintE& v, const W& wgh) {
if (u < v) ctr++;
};
GA.get_vertex(i).out_neighbors().map(f, false);
} else {
ctr = GA.get_vertex(i).out_degree();
}
offs[i] = ctr;
});
size_t m_out = parlay::scan_inplace(make_slice(offs));
parallel_for(0, n, [&](size_t i) {
size_t off = offs[i];
size_t ctr = 0;
auto map_f = [&](const uintE& u, const uintE& v, const W& wgh) {
if (direct_sym) {
if (u < v) {
edges[off + ctr] = std::make_tuple(u, v);
ctr++;
}
} else {
edges[off + ctr] = std::make_tuple(u, v);
ctr++;
}
};
GA.get_vertex(i).out_neighbors().map(map_f, false);
});
std::ofstream file(outfile, std::ios::out | std::ios::binary);
if (!file.is_open()) {
std::cout << "Unable to open file: " << outfile << std::endl;
exit(0);
}
if (multistep_header) {
file << n << " " << m_out << std::endl;
}
auto edges_chars = parlay::sequence_to_string(edges);
file.write(edges_chars.begin(), edges_chars.size());
file.close();
std::cout << "Done" << std::endl;
}
/* Format:
* Emits a lexicographically sorted list of edges.
* n m # header (once)
* "u v 1\n" # per edge*/
template <class Graph>
void print_edge_list_matrixmarket(Graph& GA, std::string& outfile) {
using W = typename Graph::weight_type;
size_t n = GA.n;
size_t m = GA.m;
auto edges = sequence<std::tuple<uintE, uintE>>(m);
auto offs = sequence<size_t>(n);
parallel_for(0, n, [&](size_t i) {
size_t ctr = 0;
auto f = [&](const uintE& u, const uintE& v, const W& wgh) {
if (u < v) ctr++;
};
GA.get_vertex(i).out_neighbors().map(f, false);
offs[i] = ctr;
});
size_t m_out = parlay::scan_inplace(make_slice(offs));
parallel_for(0, n, [&](size_t i) {
size_t off = offs[i];
size_t ctr = 0;
auto map_f = [&](const uintE& u, const uintE& v, const W& wgh) {
if (u < v) {
edges[off + ctr] = std::make_tuple(u, v);
ctr++;
}
};
GA.get_vertex(i).out_neighbors().map(map_f, false);
});
std::ofstream file(outfile, std::ios::out | std::ios::binary);
if (!file.is_open()) {
std::cout << "Unable to open file: " << outfile << std::endl;
exit(0);
}
file << n << " " << m_out << std::endl;
auto edges_chars = parlay::sequence_to_string(edges);
file.write(edges_chars.begin(), edges_chars.size());
file.close();
std::cout << "Done" << std::endl;
}
template <class Graph>
double Reorderer(Graph& GA, commandLine P) {
auto outfile = P.getOptionValue("-of", "");
auto direct_sym =
P.getOptionValue("-direct_sym"); /* only emit { (u,v) | u < v } */
auto multistep_header =
P.getOptionValue("-multistep_header"); /* only emit { (u,v) | u < v } */
auto matrixmarket_format = P.getOptionValue(
"-matrixmarket_format"); /* only emit { (u,v) | u < v } */
if (matrixmarket_format) {
print_edge_list_matrixmarket(GA, outfile);
} else {
print_edge_list(GA, outfile, direct_sym, multistep_header);
}
exit(0);
return 1.0;
}
} // namespace gbbs
generate_main(gbbs::Reorderer, false);
| true |
22a5d546b9bee3352e015274092d2cf8d1ba2929 | C++ | CRblog/algorithm | /practice/青岛网赛第一题.cpp | UTF-8 | 307 | 2.578125 | 3 | [] | no_license | #include<iostream>
#include<cmath>
using namespace std;
int main()
{
int t,n,m,k;
int min,max;
while(cin>>t){
for(int i=0;i<t;i++) {
cin>>n>>m;
if(n==m) {
cout<<n<<" "<<m<<endl;}
if(n>m){
max=m;
min=floor(n/(n-m+1));
cout<<max<<" "<<min<<endl;} } }
return 0;}
| true |
e3fce8bc8143ccac89bbae7d71ddf05f641db3d6 | C++ | Philip-Teh/MyGame | /Sokoban/source_code/ui/num_draw.h | SHIFT_JIS | 792 | 2.609375 | 3 | [] | no_license | #pragma once
//============================================================================
//= =
//= `֘A ` =
//= =
//============================================================================
#ifndef _NUMDRAW_H_
#define _NUMDRAW_H_
class CNumDraw
{
public:
//
void Init(float sizeX, float sizeY);
//ΐF̐
void InitGreen(float sizeX, float sizeY);
void Uninit(void);
void Draw(XMFLOAT3 position, int score);
void Draw(XMFLOAT3 position, int score,int tw,int th);
private:
std::unique_ptr<CNumber> mpNumber = nullptr; //io[Ǘ|C^
std::string mTexture = "";
int mDigit = 0; //
int mCounterStop = 0; //`̍ő吔
};
#endif _NUMDRAW_H_ | true |
883b14b23799e6a4ae2b0a975a83493860ea9e5d | C++ | BigLazyBrother/mini-jeu-Cpp-SFML | /src/Mechant.cpp | UTF-8 | 1,651 | 3.0625 | 3 | [] | no_license | #include "Mechant.h"
Mechant::Mechant() {
//construsteur vide
this->cacheOeil = false;
this->lachete = 0;
this->nom = "sansNom";
}
Mechant::~Mechant() {
//destructeur vide
}
void Mechant::setNom(string nom) {
this->nom = nom;
}
string Mechant::getNom() {
return this->nom;
}
void Mechant::setLachete(int lachete) {
this->lachete = lachete;
}
int Mechant::getLachete() {
return this->lachete;
}
void Mechant::prendUnCacheOeil() {
this->cacheOeil = true;
}
void Mechant::perdSonCacheOeil() {
this->cacheOeil = false;
}
bool Mechant::aUnCacheOeil() {
return this->cacheOeil;
}
string Mechant::exporterChamps() {
stringstream futurXml;
futurXml << "\t\t<nom>" << this->nom << "</nom>\n";
futurXml << "\t\t<lachete>" << this->lachete << "</lachete>\n";
futurXml << "\t\t<cacheOeil>" << this->cacheOeil << "</cacheOeil>\n";
return futurXml.str();
}
string Mechant::exporter() {
stringstream futurXml;
futurXml << "\t<Mechant>\n";
futurXml << this->exporterChamps();
futurXml << "\t</Mechant>\n";
return futurXml.str();
}
//void Mechant::prendUneCible(Gentil& gentil) {
// this->cible = &gentil; //c'est déjà une adresse. Pourquoi a-t-on besoin de "&" ?
//}
// Surcharge d'opérateur
void Mechant::operator++() {
this->lachete++;
}
Gentil * Mechant::aPourCible() {
return this->cible;
}
void Mechant::prendUneCible(Gentil* gentil) {
this->cible = gentil;
}
void Mechant::prendSaMitraillette() {
//this->mitraillette = true;
}
void Mechant::perdSaMitraillette() {
//this->mitraillette = false;
}
bool Mechant::aSaMitraillette() {
//return this->mitraillette;
return false;
} | true |
76acf8751a8fb7395a638535b509d1c4bc79fb3e | C++ | aametwally/MC_MicroSimilarities | /src/mc/MCModels.hpp | UTF-8 | 18,907 | 2.65625 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | //
// Created by asem on 04/02/19.
//
#ifndef MARKOVIAN_FEATURES_MCMODELS_HPP
#define MARKOVIAN_FEATURES_MCMODELS_HPP
#include "AbstractMC.hpp"
namespace MC {
template<size_t States>
class MC : public AbstractMC<States>
{
public:
using Base = AbstractMC<States>;
using Histogram = typename Base::Histogram;
using TransitionMatrices2D = typename Base::TransitionMatrices2D;
public:
explicit MC(
Order order,
double epsilon = Base::TransitionMatrixEpsilon
)
: Base( order, epsilon )
{
assert( order >= 1 );
}
MC() = delete;
virtual ~MC() = default;
MC( const MC &mE ) = default;
MC( MC &&mE ) noexcept
: Base( std::move( mE ))
{}
MC &operator=( const MC &mE )
{
if ( this->getOrder() != mE.getOrder() || this->_epsilon != mE._epsilon )
throw std::runtime_error( "Orders mismatch!" );
this->_centroids = mE._centroids;
return *this;
}
MC &operator=( MC &&mE ) noexcept
{
if ( this->getOrder() != mE.getOrder() || this->_epsilon != mE._epsilon )
throw std::runtime_error( "Orders mismatch!" );
this->_centroids.swap( mE._centroids );
return *this;
}
using Base::probability;
using Base::normalize;
double probability(
std::string_view context,
char state
) const override
{
if ( context.size() > this->getOrder())
{
context.remove_prefix( context.size() - this->getOrder());
}
if ( LabeledEntry::isPolymorphicReducedSequence<States>( context ) ||
LabeledEntry::isPolymorphicReducedAA( state ))
{
return 1;
} else
{
auto distance = Order( context.length());
auto id = Base::_sequence2ID( context );
auto stateID = Base::_char2ID( state );
if ( auto value = this->_centroids( distance, id, stateID ); value )
{
return value.value();
} else return 0.0;
}
}
protected:
virtual void _incrementInstance(
std::string_view context,
char state
)
{
if ( !LabeledEntry::isPolymorphicReducedSequence<States>( context ) &&
!LabeledEntry::isPolymorphicReducedAA( state ))
{
auto order = static_cast<Order>(context.size());
auto id = Base::_sequence2ID( context );
auto c = Base::_char2ID( state );
this->_centroids.increment( order, id, this->_epsilon )( c );
}
}
void _countInstance( std::string_view sequence ) override
{
for (auto a : sequence)
{
if ( !LabeledEntry::isPolymorphicReducedAA( a ))
{
auto c = Base::_char2ID( a );
this->_centroids.increment( 0, 0, this->_epsilon )( c );
}
}
for (Order distance = 1; distance <= this->getOrder(); ++distance)
for (auto i = 0; i < sequence.size() - distance; ++i)
_incrementInstance( sequence.substr( static_cast<size_t>(i), static_cast<size_t>(distance)),
sequence[i + distance] );
}
};
/**
* @brief ZYMC
* Zheng Yuan Approximated Higher-order Markov Chains
* Paper: https://febs.onlinelibrary.wiley.com/doi/pdf/10.1016/S0014-5793%2899%2900506-2
*/
template<size_t States>
class ZYMC : public AbstractMC<States>
{
public:
using Base = AbstractMC<States>;
using Histogram = typename Base::Histogram;
using IsoHistograms = std::unordered_map<HistogramID, Histogram>;
using HeteroHistograms = std::unordered_map<Order, IsoHistograms>;
public:
explicit ZYMC(
Order order,
double epsilon = Base::TransitionMatrixEpsilon
) : Base( order, epsilon )
{
assert( order >= 1 );
}
virtual ~ZYMC() = default;
static constexpr inline HistogramID lowerOrderID( HistogramID id )
{ return id / States; }
inline double pairwiseProbability(
char context,
char state,
Order distance
) const
{
auto c = Base::_char2ID( context );
auto s = Base::_char2ID( state );
auto value = this->_centroids( distance, c, s );
return value.value_or( 0.0 );
}
double probability(
std::string_view context,
char state
) const override
{
if ( context.size() > this->getOrder())
{
context.remove_prefix( context.size() - this->getOrder());
}
if ( LabeledEntry::isPolymorphicReducedSequence<States>( context ) ||
LabeledEntry::isPolymorphicReducedAA( state ))
{
return 1;
} else
{
double p = 1.0;
for (auto i = 0; i < context.size(); ++i)
{
auto distance = Order( context.size() - i );
auto c = context[i];
p *= pairwiseProbability( c, state, distance );
}
return p;
}
}
protected:
virtual void _incrementInstance(
std::string_view context,
char state,
Order distance
)
{
assert( context.size() == 1 );
if ( !LabeledEntry::isPolymorphicReducedSequence<States>( context ) &&
!LabeledEntry::isPolymorphicReducedAA( state ))
{
auto c = Base::_char2ID( context.front());
auto s = Base::_char2ID( state );
this->_centroids.increment( distance, c, this->_epsilon )( s );
}
}
void _countInstance( std::string_view sequence ) override
{
for (auto a : sequence)
{
if ( !LabeledEntry::isPolymorphicReducedAA( a ))
{
auto c = Base::_char2ID( a );
this->_centroids.increment( 0, 0, this->_epsilon )( c );
}
}
for (Order distance = 1; distance <= this->_order; ++distance)
for (auto i = 0; i + distance < sequence.size(); ++i)
_incrementInstance( sequence.substr( static_cast<size_t>(i), 1 ),
sequence[i + distance], distance );
}
};
template<size_t States>
class GappedMC : public ZYMC<States>
{
public:
using Base = ZYMC<States>;
using Histogram = typename Base::Histogram;
using IsoHistograms = std::unordered_map<HistogramID, Histogram>;
using HeteroHistograms = std::unordered_map<Order, IsoHistograms>;
explicit GappedMC(
Order order,
double epsilon = Base::TransitionMatrixEpsilon
)
: Base( order, epsilon )
{}
virtual ~GappedMC() = default;
template<typename HistogramsCollection>
explicit GappedMC(
Order order,
HistogramsCollection &&histograms,
double epsilon = Base::TransitionMatrixEpsilon
)
: Base( order, std::forward<HistogramsCollection>( histograms ), epsilon )
{}
double probability(
std::string_view context,
char currentState
) const override
{
if ( context.size() > this->getOrder())
{
context.remove_prefix( context.size() - this->getOrder());
}
if ( LabeledEntry::isPolymorphicReducedSequence<States>( context ) ||
LabeledEntry::isPolymorphicReducedAA( currentState ))
{
return 1;
} else
{
double p = 1.0;
constexpr float eps = std::numeric_limits<float>::epsilon() * 2;
double min = 1;
int iFrom = std::max( 0, int( context.length()) - this->_order );
for (auto i = iFrom; i < context.size(); ++i)
{
auto distance = Order( context.size() - i );
auto c = context[i];
auto pBayes = Base::pairwiseProbability( c, currentState, distance );
min = std::min( min, pBayes );
p *= (pBayes + eps);
}
return p / (min + eps);
}
}
};
template<typename AAGrouping>
class PolymorphicMC : public MC<AAGrouping::StatesN>
{
static constexpr auto States = AAGrouping::StatesN;
using Base = AbstractMC<States>;
public:
virtual ~PolymorphicMC() = default;
double probability(
std::string_view polymorphicContext,
char polymorphicState
) const override
{
if ( polymorphicContext.size() > this->getOrder())
{
polymorphicContext.remove_prefix( polymorphicContext.size() - this->getOrder());
}
return LabeledEntry::polymorphicSummer<AAGrouping>(
polymorphicContext, polymorphicState,
[this](
std::string_view context,
char state
) {
auto distance = Order( context.length());
auto id = Base::_sequence2ID( context );
auto stateID = Base::_char2ID( state );
if ( auto value = this->_centroids( distance, id, stateID ); value )
{
return value.value();
} else return 0.0;
} );
}
protected:
void _incrementInstance(
std::string_view context,
char state
) override
{
LabeledEntry::polymorphicApply<AAGrouping>(
context, state,
[this](
std::string_view context,
char state
) {
auto order = static_cast<Order>( context.size());
auto id = Base::_sequence2ID( context );
auto c = Base::_char2ID( state );
this->_centroids.increment( order, id, this->_epsilon )( c );
} );
}
void _countInstance( std::string_view sequence ) override
{
for (auto a : sequence)
{
LabeledEntry::polymorphicApply<AAGrouping>( a, [this]( char state ) {
auto c = Base::_char2ID( state );
this->_centroids.increment( 0, 0, this->_epsilon )( c );
} );
}
for (Order distance = 1; distance <= this->getOrder(); ++distance)
for (auto i = 0; i < sequence.size() - distance; ++i)
_incrementInstance( sequence.substr( static_cast<size_t>(i), static_cast<size_t>(distance)),
sequence[i + distance] );
}
};
template<typename AAGrouping>
class PolymorphicZYMC : public ZYMC<AAGrouping::StatesN>
{
static constexpr auto States = AAGrouping::StatesN;
using Base = AbstractMC<States>;
public:
virtual ~PolymorphicZYMC() = default;
double probability(
std::string_view polymorphicContext,
char polymorphicState
) const override
{
if ( polymorphicContext.size() > this->getOrder())
{
polymorphicContext.remove_prefix( polymorphicContext.size() - this->getOrder());
}
return LabeledEntry::polymorphicSummer<AAGrouping>(
polymorphicContext, polymorphicState,
[this](
std::string_view context,
char state
) {
double p = 1.0;
for (auto i = 0; i < context.size(); ++i)
{
auto distance = Order( context.size() - i );
auto c = context[i];
p *= this->pairwiseProbability( c, state, distance );
}
return p;
} );
}
double probability( char a ) const override
{
return LabeledEntry::polymorphicSummer<AAGrouping>( a, [this]( char state ) {
return this->_centroids( 0, 0, this->_char2ID( state )).value_or( 0 );
} );
}
protected:
virtual void _incrementInstance(
std::string_view context,
char state,
Order distance
)
{
LabeledEntry::polymorphicApply<AAGrouping>(
context, state,
[this, distance](
std::string_view context,
char state
) {
assert( context.size() == 1 );
auto c = Base::_char2ID( context.front());
auto s = Base::_char2ID( state );
this->_centroids.increment( distance, c, this->_epsilon )( s );
} );
}
};
template<size_t States, typename CoreMCModel = MC<States> >
class RegularizedBinaryMC : public CoreMCModel
{
static_assert( CoreMCModel::t_States == States, "States mismatch!" );
public:
static constexpr size_t t_States = States;
using Histogram = buffers::Histogram<States>;
using TransitionMatrices2D =
SparseTransitionMatrix2D<States, Histogram, Order, HistogramID>;
using BackboneProfile = std::unique_ptr<RegularizedBinaryMC>;
using BackboneProfiles = std::map<std::string_view, std::unique_ptr<RegularizedBinaryMC>>;
private:
struct StackedBooleanTransitionMatrices
{
using IsoHistograms = std::unordered_map<HistogramID, std::vector<buffers::BooleanHistogram<States>>>;
using HeteroHistograms = std::unordered_map<Order, IsoHistograms>;
HeteroHistograms data;
};
public:
explicit RegularizedBinaryMC(
Order order,
double epsilon = AbstractMC<States>::TransitionMatrixEpsilon
)
: CoreMCModel( order, epsilon )
{}
using AbstractMC<States>::normalize;
void normalize( std::optional<size_t> minimumOccurrence ) override
{
assert( minimumOccurrence.value_or( 2 ) > 1 );
TransitionMatrices2D regularizedHistograms;
for (auto &[order, isoHistograms] : _stackedMatrices.data)
{
for (auto &[id, histogramsVector] : isoHistograms)
{
if ( histogramsVector.size() > minimumOccurrence.value_or( 0 ))
{
std::vector<Histogram> normalized;
std::transform(
std::make_move_iterator( histogramsVector.begin()),
std::make_move_iterator( histogramsVector.end()),
std::back_inserter( normalized ), []( auto &&v ) { return v.normalize(); } );
auto mean =
Histogram::mean( normalized, this->_n );
auto standardDeviation =
Histogram::standardError( normalized, mean, this->_n );
this->_centroids.set( order, id, std::move( mean ));
this->_standardDeviations.set( order, id, std::move( standardDeviation ));
}
}
}
_stackedMatrices.data.clear();
}
protected:
virtual void _countInstance( std::string_view sequence )
{
++this->_n; // A not funny mutable member.
CoreMCModel model( this->getOrder(), this->getEpsilon());
model.train( sequence );
auto histograms = std::move( model.stealCentroids());
for (auto &[order, isoHistograms] : histograms)
{
auto &stacked = _stackedMatrices.data[order];
for (auto &[id, histogram] : isoHistograms)
{
auto bHist = BooleanHistogram<States>::binarizeHistogram(
std::move( histogram ), this->getEpsilon());
stacked[id].emplace_back( std::move( bHist ));
}
}
}
private:
StackedBooleanTransitionMatrices _stackedMatrices;
};
template<size_t States, typename CoreMCModel = MC<States> >
class RegularizedVectorsMC : public CoreMCModel
{
static_assert( CoreMCModel::t_States == States, "States mismatch!" );
public:
static constexpr size_t t_States = States;
using Histogram = buffers::Histogram<States>;
using TransitionMatrices2D =
SparseTransitionMatrix2D<States, Histogram, Order, HistogramID>;
using BackboneProfile = std::unique_ptr<RegularizedVectorsMC>;
using BackboneProfiles = std::map<std::string_view, std::unique_ptr<RegularizedVectorsMC>>;
private:
struct StackedTransitionMatrices
{
using IsoHistograms = std::unordered_map<HistogramID, std::vector<Histogram>>;
using HeteroHistograms = std::unordered_map<Order, IsoHistograms>;
HeteroHistograms data;
};
public:
explicit RegularizedVectorsMC(
Order order,
double epsilon = AbstractMC<States>::TransitionMatrixEpsilon
)
: CoreMCModel( order, epsilon )
{}
using AbstractMC<States>::normalize;
void normalize( std::optional<size_t> minimumOccurrence ) override
{
assert( minimumOccurrence.value_or( 1 ) > 0 );
TransitionMatrices2D regularizedHistograms;
for (auto &&[order, isoHistograms] : _stackedMatrices.data)
{
for (auto &&[id, histogramsVector] : isoHistograms)
{
if ( histogramsVector.size() > minimumOccurrence.value_or( 0 ))
{
std::vector<Histogram> normalized;
std::transform(
std::make_move_iterator( histogramsVector.begin()),
std::make_move_iterator( histogramsVector.end()),
std::back_inserter( normalized ), []( auto &&v ) { return v.normalize(); } );
auto centroid =
Histogram::mean( normalized, this->_n );
auto standardDeviation =
Histogram::standardError( normalized, centroid, this->_n );
this->_standardDeviations.set( order, id, std::move( standardDeviation ));
this->_centroids.set( order, id, std::move( centroid ));
}
}
}
_stackedMatrices.data.clear();
}
protected:
void _countInstance( std::string_view sequence ) override
{
++this->_n; // mutable variable, annoying.
CoreMCModel model( this->getOrder(), this->getEpsilon());
model.train( sequence );
auto histograms = std::move( model.stealCentroids());
for (auto &[order, isoHistograms] : histograms)
{
auto &stacked = _stackedMatrices.data[order];
for (auto &[id, histogram] : isoHistograms)
{
stacked[id].emplace_back( std::move( histogram ));
}
}
}
private:
StackedTransitionMatrices _stackedMatrices;
};
}
#endif //MARKOVIAN_FEATURES_MCMODELS_HPP
| true |
a1bd9e730bc84fd5cb51db9c1a774a9da5ff31fe | C++ | fernicar/EvolvedVirtualCreaturesRepo | /VirtualCreatures/Volumetric_SDL/Source/Sound/SoundSource.h | UTF-8 | 1,106 | 2.796875 | 3 | [
"Zlib"
] | permissive | #pragma once
#include <Sound/Sound.h>
#include <Constructs/Vec3f.h>
class SoundSource
{
private:
unsigned int m_sourceID;
Sound* m_pSound;
float m_pitch;
float m_gain;
Vec3f m_position;
Vec3f m_velocity;
float m_referenceDistance;
float m_maxDistance;
float m_rollOffFactor;
bool m_looping;
public:
SoundSource();
~SoundSource();
// Update sound source
void SetSound(Sound* pSound);
Sound* GetSound() const;
void SetPosition(const Vec3f &position);
const Vec3f &GetPosition() const;
void SetVelocity(const Vec3f &velocity);
const Vec3f &GetVelocity() const;
void SetPitch(float pitch);
float GetPitch() const;
void SetGain(float gain);
float GetGain() const;
void SetLooping(bool looping);
bool GetLooping() const;
void SetReferenceDistance(float referenceDistance);
float GetReferenceDistance() const;
void SetMaxDistance(float maxDistance);
float GetMaxDistance() const;
void SetRollOffFactor(float rollOffFactor);
float GetRollOffFactor() const;
bool Play();
void Stop();
void Rewind();
void Pause();
bool Playing() const;
unsigned int GetSourceID();
};
| true |
90b453b5670269268739195db7ce864724bb7dea | C++ | lucivpav/bomberman | /src/bonus.cpp | UTF-8 | 127 | 2.578125 | 3 | [] | no_license | #include "bonus.h"
Bonus::Bonus(Block::Type type)
:mType(type)
{
}
Block::Type Bonus::type() const
{
return mType;
}
| true |
ed5b75f2696d9d8520f3d45dc25ed6a597cecc1c | C++ | murvi1/dbus-spy | /software/src/list_view.cpp | UTF-8 | 3,707 | 2.578125 | 3 | [] | no_license | #include <QTimer>
#include "abstract_object_list_model.h"
#include "list_view.h"
ListView::ListView(WINDOW *w, QObject *parent):
QObject(parent),
mWindow(w),
mRedrawTimer(new QTimer(this))
{
mRedrawTimer->setInterval(100);
mRedrawTimer->setSingleShot(true);
connect(mRedrawTimer, SIGNAL(timeout()), this, SLOT(onRedrawAll()));
}
AbstractObjectListModel *ListView::model() const
{
return mModel;
}
void ListView::setModel(AbstractObjectListModel *m)
{
if (mModel == m)
return;
mModel = m;
connect(mModel, SIGNAL(dataChanged(QModelIndex, QModelIndex)),
this, SLOT(onDataChanged(QModelIndex, QModelIndex)));
connect(mModel, SIGNAL(layoutChanged()),
this, SLOT(onScheduleRedrawAll()));
connect(mModel, SIGNAL(rowsInserted(QModelIndex, int, int)),
this, SLOT(onScheduleRedrawAll()));
connect(mModel, SIGNAL(rowsRemoved(QModelIndex, int, int)),
this, SLOT(onScheduleRedrawAll()));
connect(mModel, SIGNAL(modelReset()),
this, SLOT(onScheduleRedrawAll()));
onScheduleRedrawAll();
}
int ListView::getSelection() const
{
return mSelectionIndex;
}
void ListView::setSelection(int s)
{
if (mModel == 0)
return;
s = qBound(0, s, mModel->rowCount() - 1);
if (s == mSelectionIndex)
return;
int h = getListHeight();
int si = mStartIndex;
while (si + h <= s)
si += 5;
while (si > s)
si -= 5;
if (si == mStartIndex) {
int os = mSelectionIndex;
mSelectionIndex = s;
redrawRows(os, os);
redrawRows(s, s);
} else {
mStartIndex = si;
mSelectionIndex = s;
redraw();
}
wrefresh(mWindow);
}
bool ListView::handleInput(int c)
{
switch (c)
{
case KEY_DOWN:
setSelection(mSelectionIndex + 1);
break;
case KEY_UP:
setSelection(mSelectionIndex - 1);
break;
case KEY_NPAGE:
setSelection(mSelectionIndex + getListHeight());
break;
case KEY_PPAGE:
setSelection(mSelectionIndex - getListHeight());
break;
default:
return false;
}
return true;
}
void ListView::drawRow(int index, int width) const
{
QVariant v = mModel->data(mModel->index(index, 0));
wprintw(mWindow, v.toString().left(width).toLatin1().data());
}
bool ListView::isEmphasized(int index) const
{
Q_UNUSED(index);
return false;
}
WINDOW *ListView::window() const
{
return mWindow;
}
void ListView::redraw()
{
if (mModel == nullptr)
return;
mSelectionIndex = qBound(0, mSelectionIndex, mModel->rowCount() - 1);
int h = getListHeight();
wmove(mWindow, 0, 0);
int endIndex = qMin(mModel->rowCount(), h + mStartIndex);
for (int r = mStartIndex; r < endIndex; ++r)
_redrawRow(r);
int y = endIndex - mStartIndex;
if (y < h)
wclrtobot(mWindow);
}
void ListView::redrawRows(int startIndex, int endIndex)
{
if (endIndex < startIndex)
return;
int x = getcurx(mWindow);
int y = getcury(mWindow);
for (int i=startIndex; i <=endIndex; ++i)
_redrawRow(i);
wmove(mWindow, y, x);
}
void ListView::onDataChanged(const QModelIndex &topLeft,
const QModelIndex &bottomRight)
{
redrawRows(topLeft.row(), bottomRight.row());
}
void ListView::onRedrawAll()
{
redraw();
wrefresh(mWindow);
}
void ListView::onScheduleRedrawAll()
{
if (mRedrawTimer->isActive())
return;
mRedrawTimer->start();
}
int ListView::getListHeight() const
{
return getmaxy(mWindow);
}
void ListView::_redrawRow(int index)
{
if (index < mStartIndex || mModel == nullptr || index >= mModel->rowCount())
return;
int r = index - mStartIndex;
if (r >= getListHeight())
return;
int attr = index == mSelectionIndex ? (COLOR_PAIR(3) | A_STANDOUT) : COLOR_PAIR(2);
if (isEmphasized(index))
attr |= A_BOLD;
wattron(mWindow, attr);
wmove(mWindow, r, 0);
wclrtoeol(mWindow);
wmove(mWindow, r, 0);
int w = getmaxx(mWindow);
drawRow(index, w);
wattroff(mWindow, attr);
}
| true |
b4093aec95a10853223f6f8197c1e8d3f98d46ad | C++ | shreyakapoor08/CPP_Programs | /29th august/print_substring.cpp | UTF-8 | 433 | 3.453125 | 3 | [] | no_license | #include<iostream>
#include<cstring>
using namespace std;
void printSubstrings(char *a)
{
for(int i=0;a[i]!='\0';i++)
{
for(int j=i;a[j]!='\0';j++)
{
//print the string from i to j
for(int k=i;k<=j;k++){
cout<<a[k];
}
cout<<endl;
}
}
}
int main()
{
char a[100];
cin.getline(a,100);
printSubstrings(a);
return 0;
}
| true |
a9900fe223e36a6144cbbe48525fe1f894b51491 | C++ | pfepark/Cpp11_14 | /CppDay3/3_PerfectForwarding3.cpp | UHC | 985 | 3.90625 | 4 | [] | no_license | #include <iostream>
void foo(int n) { n = 10; }
void goo(int& n) { n = 10; }
void hoo(int&& n) { }
// Ϻ ذå
// 1. int& int&& Լ 2 Ѵ.
// Ȯ const int& const int&& ־ Ѵ.
// 2. int&& static_cast<int&&> ؼ Ѵ.
template<typename F>
void logTime(F f, int& arg)
{
f(arg);
}
template<typename F>
void logTime(F f, int&& arg)
{
//f(arg);
// 10 rvalueµ arg 鼭 lvalue Ǿ.
// ٽ rvalue ؼ Ѵ.
f(static_cast<int&&>(arg));
}
int main()
{
int x = 0;
logTime(foo, 10); //foo(10);
logTime(goo, x); //goo(x);
logTime(hoo, 10); //hoo(10)̹Ƿ Ǿ Ѵ. void logTime(F f, int&& arg) ȣǴµ...
// 10 rvalue arg lvalue̴. hoo(int&) ã ȴ.
std::cout << x << std::endl;
} | true |
f7d2d0f82edcf517645c76c2debb32f9fb309557 | C++ | Defens1k/algorithm_TP | /mod_1/old/3_1.cpp | UTF-8 | 3,495 | 3.359375 | 3 | [] | no_license | #include <iostream>
#define MIN_SIZE 32
class Queue {
public:
Queue();
~Queue();
int64_t pop_front();
void push_back(int64_t input_data);
int64_t size(); //return lenght of queue
bool is_empty(); //is queue empty?
bool resize(int64_t new_size); // if (new_size > free_cell) => size = new_size
int64_t free_cell();
private:
bool empty;
int64_t * data; //pointer of data
int64_t data_size;
int64_t front_index; // index of oldest cell
int64_t back_index; //index of newest cell
};
Queue::Queue() {
empty = true;
data_size = MIN_SIZE;
data = new int64_t[MIN_SIZE];
front_index = 0;
back_index = 0;
}
int64_t Queue::pop_front() {
if (is_empty()) {
return -1;
}
else {
int64_t out_data = data[front_index];
if (size() == 1 + free_cell()) {
resize(MIN_SIZE);
empty = true;
return out_data;
}
front_index = (front_index + 1) % size();
if ((free_cell() * 20 > 19 * size()) && (size() > MIN_SIZE)) {
resize(size() / 2);
}
return out_data;
}
}
void Queue::push_back(int64_t input_data) {
if (is_empty()) {
data[0] = input_data;
front_index = 0;
back_index = 0;
empty = false;
return;
}
if (free_cell() == 0) {
resize(size() * 2);
push_back(input_data);
return;
}
if (size() == (back_index + 1)) {
data[0] = input_data;
back_index = 0;
empty = false;
return;
}
else {
data[back_index + 1] = input_data;
back_index++;
empty = false;
}
}
int64_t Queue::size() {
return data_size;
}
bool Queue::is_empty() {
return empty;
}
bool Queue::resize(int64_t new_size) {
if (new_size < size() - free_cell()) {
return false;
}
if (new_size == size()) {
return true;
}
if (new_size < MIN_SIZE) {
return false;
}
if (is_empty()) {
delete [] data;
data = new int64_t[new_size];
data_size = new_size;
empty = true;
}
int64_t * new_data = new int64_t[new_size];
int64_t new_data_iterator = 0;
int64_t old_data_iterator = front_index;
while (old_data_iterator != back_index) {
new_data[new_data_iterator] = data[old_data_iterator];
new_data_iterator++;
old_data_iterator = (old_data_iterator + 1) % size();
}
new_data[new_data_iterator] = data[old_data_iterator];
delete []data;
data = new_data;
front_index = 0;
back_index = new_data_iterator;
data_size = new_size;
return true;
}
int64_t Queue::free_cell() {
if (is_empty()) {
return size();
}
if (front_index > back_index) {
return front_index - back_index - 1;
}
if (front_index <= back_index) {
return size() + front_index - back_index - 1;
}
}
Queue::~Queue() {
if (data) {
delete [] data;
}
}
int main() {
Queue q;
int64_t n = 0;
int64_t a , b;
bool input_true = true;
std::cin >> n;
for (int64_t i = 0; i < n; i++) {
std::cin >> a >> b;
if (a == 3) {
q.push_back(b);
}
if (a == 2) {
if (b != q.pop_front()) {
input_true = false;
}
}
}
if (input_true) {
std::cout << "YES";
}
else {
std::cout << "NO";
}
}
| true |
f6baa3e148fd78a43f82d4d0279a0839e67617ae | C++ | xingkaihao/Leetcode | /中级算法/数组和字符串/矩阵置零/C++/original.cpp | GB18030 | 1,436 | 3.375 | 3 | [] | no_license | class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int row=matrix.size();
int column=matrix[0].size();
vector<int> row1, column1;
for(int i=0; i<row; i++){
for(int l=0; l<column; l++){
if(matrix[i][l]==0){
row1.push_back(i);
column1.push_back(l);
}
}
}
if(row1.empty()) return;
sort(row1.begin(), row1.end());
sort(column1.begin(), column1.end());
vector<int> row11;
row11.push_back(row1[0]);
for(int c=1; c<row1.size(); c++){
if(row1[c]!=row1[c-1]) row11.push_back(row1[c]);
}
int m=0;
for(int j=0; j<row; j++){
if(row11[m]==j){
for(int n=0; n<column; n++){
matrix[j][n]=0;
}
m+=1;
}
else{
for(int k=0; k<column1.size(); k++){
matrix[j][column1[k]]=0;
}
}
}
}
};
/* ˼·ȱһmatrix0Ԫصλãrow1Уcolumn1У
* row1Ϊգû0Ԫأrow1column1ɾrow1
* еĸ֮matrixrow1еУ0ǣͰcolumn
* 0
*/ | true |
2b65efeedb90f9a0c352eca4dd68e7dcaaac7b84 | C++ | SethGibson/Circumstellar | /_tests/CoordConvertTest/src/CoordConvertTestApp.cpp | UTF-8 | 1,880 | 2.703125 | 3 | [] | no_license | #include "cinder/app/App.h"
#include "cinder/app/RendererGl.h"
#include "cinder/Camera.h"
#include "cinder/gl/gl.h"
using namespace ci;
using namespace ci::app;
using namespace std;
static float S_PLANE_Z = 8.0f;
struct orbiter
{
float Angle;
float Radius;
float Vel;
float Depth;
orbiter(float pAngle, float pRadius, float pVel) : Angle(pAngle), Radius(pRadius), Vel(pVel), Depth(S_PLANE_Z) {}
void Draw()
{
Depth -= Vel;
Angle -= Vel;
float newR = lerp<float>(0.0f, Radius, Depth / S_PLANE_Z);
auto x = math<float>::sin(Angle)*newR;
auto y = math<float>::cos(Angle)*newR;
gl::color(Color(0, 1, 0));
gl::drawSphere(vec3(x, y, Depth), 0.25f);
}
};
class CoordConvertTestApp : public App
{
public:
void setup() override;
void mouseDown( MouseEvent event ) override;
void update() override;
void draw() override;
private:
vec3 mRayPos;
vec2 mMousePos;
CameraPersp mCamera;
vector<orbiter> mPoints;
};
void CoordConvertTestApp::setup()
{
getWindow()->setSize(1280, 720);
mCamera.setPerspective(90.0f, getWindowAspectRatio(), 0.0326f, 33.674f);
mCamera.lookAt(vec3(0,0,10), vec3(), vec3(0,1,0));
}
void CoordConvertTestApp::mouseDown( MouseEvent event )
{
mMousePos = event.getPos();
auto ray = mCamera.generateRay(mMousePos, getWindowSize());
float dist;
if (ray.calcPlaneIntersection(vec3(0,0,S_PLANE_Z), vec3(0, 0, -1), &dist))
mRayPos = ray.calcPosition(dist);
auto angle = math<float>::atan2(mRayPos.x, mRayPos.y);
if (angle < 0)
angle += (2.0f*M_PI);
auto rad = length(vec2(mRayPos));
mPoints.push_back(orbiter(angle, rad, 0.01f));
}
void CoordConvertTestApp::update()
{
}
void CoordConvertTestApp::draw()
{
gl::clear( Color( 0, 0, 0 ) );
gl::setMatrices(mCamera);
gl::color(Color::white());
gl::drawSphere(mRayPos, 0.1f);
for (auto &o : mPoints)
o.Draw();
}
CINDER_APP( CoordConvertTestApp, RendererGl )
| true |
94a72ca88770cab81f44940009a4b61acc0ee503 | C++ | dreamspot4everyone/No-Exam | /Greedy/Kruskal.cpp | UTF-8 | 2,549 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include<fstream>
using namespace std;
struct kruskal{
int sv; //source
int ev; //destination
int weight; //weight
};
int graph[100][100];
int n,ans=0;
int parent[100];
void merge(kruskal a[],int low,int mid,int high)
{
int i=low,j=mid+1,k=low;
kruskal b[high+1];
while (i<=mid && j<=high)
{
if (a[i].weight<=a[j].weight)
{
b[k]=a[i];
i++;
}
else
{
b[k]=a[j];
j++;
}
k++;
}
while (i<=mid)
{
b[k]=a[i];
i++;
k++;
}
while (j<=high)
{
b[k]=a[j];
j++;
k++;
}
for (int i=low;i<=high;i++)
a[i]=b[i];
}
void merge_sort(kruskal *a,int low,int high,int n)
{
if (low<high)
{
int mid=(low+high)/2;
merge_sort (a,low,mid,n);
merge_sort (a,mid+1,high,n);
merge (a,low,mid,high);
}
}
int find_set(int i) //find set of an element i
{
while (parent[i]>0)
i=parent[i];
return i;
}
void Weighted_union(int i,int j) //union of two sets of x and y
{
i=find_set(i);
j=find_set(j);
int temp=parent[i]+parent[j];
if (parent[i]>parent[j])
{
parent[i]=j;
parent[j]=temp;
}
else
{
parent[j]=i;
parent[i]=temp;
}
}
int Kruskal_fun(kruskal a[],int size)
{
for(int i=0;i<n;i++)
parent[i]=-1;
merge_sort(a,0,size-1,size);
for (int i=0;i<size;i++)
{
if (find_set(a[i].sv-65)!=find_set(a[i].ev-65))
{
cout<<char(a[i].sv)<<"->"<<char(a[i].ev)<<endl;
Weighted_union(a[i].sv-65,a[i].ev-65);
}
}
}
int main()
{
fstream infile;
infile.open("kruskal_input.txt" , ios::in);
if(!infile)
{
cout<<"Error on opening file"<<endl;
return 0;
}
infile>>n;
for(int i=0 ; i<n ; ++i)
{
for(int j=0 ; j<n ; ++j)
{
infile>>graph[i][j];
}
}
int k=0;
kruskal graph_pair[100];
cout<<"The input graph is"<<endl;
for(int i=0 ; i<n ; ++i)
{
for(int j=0 ; j<n ; ++j)
{
cout<<graph[i][j]<<" ";
}
cout<<endl;
}
for(int i=0 ; i<n ; ++i)
{
for(int j=0 ; j<=i ; ++j)
{
if(graph[i][j])
{
graph_pair[k].sv=i+65;
graph_pair[k].ev=j+65;
graph_pair[k].weight=graph[i][j];
++k;
}
}
}
int size=k;
Kruskal_fun(graph_pair,size);
return 0;
}
| true |
99191e56550bd1a57f67a257ac771fa82b58ee41 | C++ | Aurillon/UMD-Duluth-CS1521 | /projects/project5/DiscList.h | UTF-8 | 646 | 2.640625 | 3 | [] | no_license | #ifndef DISC_LIST_
#define DISC_LIST_
#include <memory>
#include "LinkedList.h"
#include "Track.h"
//#include "Disc.cpp"
class DiscList {
public:
DiscList();
~DiscList();
bool isEmpty() const;
int getNumberOfDiscs() const;
bool insertDisc(std::shared_ptr<Disc> aDiscPtr);
bool removeDisc(std::weak_ptr<Disc> aDiscPtr);
std::weak_ptr<Disc> retrieveDisc(int number) const;
private:
//LinkedList<std::_ptr<Disc>> discList;
std::unique_ptr<LinkedList<std::shared_ptr<Disc>>> discListPtr = std::make_unique<LinkedList<std::shared_ptr<Disc>>>();
int findDiscPosistion(std::weak_ptr<Disc> discPtr) const;
};
#endif
| true |
daaea89d8600e355e3cb6d1a13ff151943a786a8 | C++ | diazf/indri | /contrib/antlr/src/antlrParser.cpp | UTF-8 | 6,261 | 2.578125 | 3 | [
"BSD-2-Clause"
] | permissive | /* ANTLR Translator Generator
* Project led by Terence Parr at http://www.jGuru.com
* Software rights: http://www.antlr.org/license.html
*
* $Id: //depot/code/org.antlr/release/antlr-2.7.4/lib/cpp/src/Parser.cpp#1 $
*/
#include "antlr/Parser.hpp"
#include "antlr/BitSet.hpp"
#include "antlr/TokenBuffer.hpp"
#include "antlr/MismatchedTokenException.hpp"
//#include "antlr/ASTFactory.hpp"
#include <iostream>
#include <cstdlib>
#ifdef ANTLR_CXX_SUPPORTS_NAMESPACE
namespace antlr {
#endif
ANTLR_C_USING(exit)
/**A generic ANTLR parser (LL(k) for k>=1) containing a bunch of
* utility routines useful at any lookahead depth. We distinguish between
* the LL(1) and LL(k) parsers because of efficiency. This may not be
* necessary in the near future.
*
* Each parser object contains the state of the parse including a lookahead
* cache (the form of which is determined by the subclass), whether or
* not the parser is in guess mode, where tokens come from, etc...
*
* <p>
* During <b>guess</b> mode, the current lookahead token(s) and token type(s)
* cache must be saved because the token stream may not have been informed
* to save the token (via <tt>mark</tt>) before the <tt>try</tt> block.
* Guessing is started by:
* <ol>
* <li>saving the lookahead cache.
* <li>marking the current position in the TokenBuffer.
* <li>increasing the guessing level.
* </ol>
*
* After guessing, the parser state is restored by:
* <ol>
* <li>restoring the lookahead cache.
* <li>rewinding the TokenBuffer.
* <li>decreasing the guessing level.
* </ol>
*
* @see antlr.Token
* @see antlr.TokenBuffer
* @see antlr.TokenStream
* @see antlr.LL1Parser
* @see antlr.LLkParser
*/
bool DEBUG_PARSER=false;
Parser::Parser(TokenBuffer& input)
: inputState(new ParserInputState(input)), astFactory(0), traceDepth(0)
{
}
Parser::Parser(TokenBuffer* input)
: inputState(new ParserInputState(input)), astFactory(0), traceDepth(0)
{
}
Parser::Parser(const ParserSharedInputState& state)
: inputState(state), astFactory(0), traceDepth(0)
{
}
Parser::~Parser()
{
}
/** Consume tokens until one matches the given token */
void Parser::consumeUntil(int tokenType)
{
while (LA(1) != Token::EOF_TYPE && LA(1) != tokenType)
consume();
}
/** Consume tokens until one matches the given token set */
void Parser::consumeUntil(const BitSet& set)
{
while (LA(1) != Token::EOF_TYPE && !set.member(LA(1)))
consume();
}
/**Make sure current lookahead symbol matches token type <tt>t</tt>.
* Throw an exception upon mismatch, which is catch by either the
* error handler or by the syntactic predicate.
*/
void Parser::match(int t)
{
if ( DEBUG_PARSER )
{
traceIndent();
ANTLR_USE_NAMESPACE(std)cout << "enter match(" << t << ") with LA(1)=" << LA(1) << ANTLR_USE_NAMESPACE(std)endl;
}
if ( LA(1)!=t ) {
if ( DEBUG_PARSER )
{
traceIndent();
ANTLR_USE_NAMESPACE(std)cout << "token mismatch: " << LA(1) << "!=" << t << ANTLR_USE_NAMESPACE(std)endl;
}
throw MismatchedTokenException(getTokenNames(), getNumTokens(), LT(1), t, false, getFilename());
} else {
// mark token as consumed -- fetch next token deferred until LA/LT
consume();
}
}
/**Make sure current lookahead symbol matches the given set
* Throw an exception upon mismatch, which is catch by either the
* error handler or by the syntactic predicate.
*/
void Parser::match(const BitSet& b)
{
if ( DEBUG_PARSER )
{
traceIndent();
ANTLR_USE_NAMESPACE(std)cout << "enter match(" << "bitset" /*b.toString()*/
<< ") with LA(1)=" << LA(1) << ANTLR_USE_NAMESPACE(std)endl;
}
if ( !b.member(LA(1)) ) {
if ( DEBUG_PARSER )
{
traceIndent();
ANTLR_USE_NAMESPACE(std)cout << "token mismatch: " << LA(1) << " not member of "
<< "bitset" /*b.toString()*/ << ANTLR_USE_NAMESPACE(std)endl;
}
throw MismatchedTokenException(getTokenNames(), getNumTokens(), LT(1), b, false, getFilename());
} else {
// mark token as consumed -- fetch next token deferred until LA/LT
consume();
}
}
void Parser::matchNot(int t)
{
if ( LA(1)==t ) {
// Throws inverted-sense exception
throw MismatchedTokenException(getTokenNames(), getNumTokens(), LT(1), t, true, getFilename());
} else {
// mark token as consumed -- fetch next token deferred until LA/LT
consume();
}
}
void Parser::panic()
{
ANTLR_USE_NAMESPACE(std)cerr << "Parser: panic" << ANTLR_USE_NAMESPACE(std)endl;
exit(1);
}
/** Parser error-reporting function can be overridden in subclass */
void Parser::reportError(const RecognitionException& ex)
{
ANTLR_USE_NAMESPACE(std)cerr << ex.toString().c_str() << ANTLR_USE_NAMESPACE(std)endl;
}
/** Parser error-reporting function can be overridden in subclass */
void Parser::reportError(const ANTLR_USE_NAMESPACE(std)string& s)
{
if ( getFilename()=="" )
ANTLR_USE_NAMESPACE(std)cerr << "error: " << s.c_str() << ANTLR_USE_NAMESPACE(std)endl;
else
ANTLR_USE_NAMESPACE(std)cerr << getFilename().c_str() << ": error: " << s.c_str() << ANTLR_USE_NAMESPACE(std)endl;
}
/** Parser warning-reporting function can be overridden in subclass */
void Parser::reportWarning(const ANTLR_USE_NAMESPACE(std)string& s)
{
if ( getFilename()=="" )
ANTLR_USE_NAMESPACE(std)cerr << "warning: " << s.c_str() << ANTLR_USE_NAMESPACE(std)endl;
else
ANTLR_USE_NAMESPACE(std)cerr << getFilename().c_str() << ": warning: " << s.c_str() << ANTLR_USE_NAMESPACE(std)endl;
}
/** Set or change the input token buffer */
// void setTokenBuffer(TokenBuffer<Token>* t);
void Parser::traceIndent()
{
for( int i = 0; i < traceDepth; i++ )
ANTLR_USE_NAMESPACE(std)cout << " ";
}
void Parser::traceIn(const char* rname)
{
traceDepth++;
for( int i = 0; i < traceDepth; i++ )
ANTLR_USE_NAMESPACE(std)cout << " ";
ANTLR_USE_NAMESPACE(std)cout << "> " << rname
<< "; LA(1)==" << LT(1)->getText().c_str()
<< ((inputState->guessing>0)?" [guessing]":"")
<< ANTLR_USE_NAMESPACE(std)endl;
}
void Parser::traceOut(const char* rname)
{
for( int i = 0; i < traceDepth; i++ )
ANTLR_USE_NAMESPACE(std)cout << " ";
ANTLR_USE_NAMESPACE(std)cout << "< " << rname
<< "; LA(1)==" << LT(1)->getText().c_str()
<< ((inputState->guessing>0)?" [guessing]":"")
<< ANTLR_USE_NAMESPACE(std)endl;
traceDepth--;
}
#ifdef ANTLR_CXX_SUPPORTS_NAMESPACE
}
#endif
| true |
e0d27aec863553b2981644fd347f9d30e27266e7 | C++ | HANJEONGWOO/ACMICPC | /2493.cpp | UTF-8 | 842 | 2.828125 | 3 | [] | no_license | #include <stdio.h>
int N;
int arr[500001];
int idx[500001];
int s_idx;
int repeat = 0;
int main(void)
{
int i, j;
scanf("%d", &N);
for(i=0; i<N; i++) {
scanf("%d", &arr[i]);
}
printf("0 ");
for(i=1; i<N; i++) {
s_idx = i-1;
repeat = 0;
while(1)
{
if(arr[s_idx] >= arr[i]) {
//printf("%d : %d \n", i + 1, s_idx + 1); //print it
printf("%d ", s_idx + 1);
idx[i] = s_idx;
break;
else {
s_idx = idx[s_idx];
if(repeat == 1) {
printf("0 ");
break;
}
else if(s_idx == 0) {
repeat = 1;
}
//printf("!!%d\n", s_idx);
}
if(s_idx < 0) {
//printf("%d : 0 \n", i+1);
printf("0 ");
break;
} //break init
//printf("!%d \n", s_idx);
} //while
}
return 0;
}
/*
20
1 2 3 4 5 6 7 8 9 10
3030 4040 5050 5555 4 44949 1 2 5453 5554
*/ | true |
fa4c4af34790e0a8ef090fd781cb0972f8978358 | C++ | Ethan-Burchett/Generic-Menu-Class | /MenuClass.h | UTF-8 | 1,830 | 3.84375 | 4 | [] | no_license | // Generic menu class
// Input: std::string vector of options
// Output: valid option integer
// Prints formatted options to the terminal with option numbers
// User input data validation with helper error messages
// can be used with any size of std::string option array
// Function Prototype of MenuClass
// Ethan Burchett Summer 2020
#include <iostream>
#include <string>
#include <vector>
//How to format menu vector input:
//std::vector<std::string> options;
//options.push_back("play game");
//options.push_back("load game");
// class prototype
// when constructing, you must include a std::vector<std::string> of options
// Generic menu class : use runMenu()
// Access individual menu lines with : getOptionString()
// Input: std::string vector of options
// Output: valid option integer
class MenuClass
{
private:
std::vector<std::string> optionVector;// vector of std::string options eg: "play game","exit","load"...
int vectorSize; // number of menu items
int validOption; // option to be returned
int getSize(void); // returns the size of the vector
void displayMenu(void); // displays the menu
void inputValidation(void); // validates user input from 1 - size of vector
public:
explicit MenuClass(std::vector<std::string> vOptions); // uses a std::vector<std::string> when constucting and uses a member initalizer list
int runMenu(void); // primary client interface for MenuClass returns value
void runMenu(int & option); // primary client interface for MenuClass return by refrence
std::string getOptionString(int position) const; // returns single line of option vector
}; | true |
84cac4f37f421d7f97866c38f803cdc3cae060f0 | C++ | ArdNut/libraries | /dht11/dht11.cpp | UTF-8 | 2,385 | 2.65625 | 3 | [] | no_license | #include <stdint.h>
#include "Arduino.h"
#include "dht11.h"
int dht11::readDHT(int pin)
{
uint8_t cnt = 7;
uint8_t idx = 0;
uint8_t chksum = 0;
uint16_t loopcnt = 0;
uint32_t tmbit = 0;
// unsigned int loopcnt = 0;
// unsigned long tmbit = 0;
// clear input buffer
for (int i = 0; i < INBUFFSZ; i++)
bits[i] = 0;
// signal DHT11 to start stream (18 ms)
pinMode(pin, OUTPUT);
digitalWrite(pin, LOW);
delay(18);
// release pin and wait for DHT11 to respond (40 us)
digitalWrite(pin, HIGH);
delayMicroseconds(40);
pinMode(pin, INPUT);
// look for low->high response from DHT11
loopcnt = MAXWAIT;
while(digitalRead(pin) == LOW) {
if (loopcnt-- == 0)
return DHT_TIMEOUT_ERR;
}
loopcnt = MAXWAIT;
while(digitalRead(pin) == HIGH) {
if (loopcnt-- == 0)
return DHT_TIMEOUT_ERR;
}
// read data bits: 40 BITS => 5 bytes
// bit stream starts with low signal
for (int i = 0; i < MAXBITS; i++) {
// wait for low level
loopcnt = MAXWAIT;
while(digitalRead(pin) == LOW) {
if (loopcnt-- == 0)
return DHT_TIMEOUT_ERR;
}
// detect high and time it
tmbit = micros();
loopcnt = MAXWAIT;
while(digitalRead(pin) == HIGH) {
if (loopcnt-- == 0)
return DHT_TIMEOUT_ERR;
}
if ((micros() - tmbit) > 40)
bits[idx] |= (1 << cnt);
if (cnt == 0) {
cnt = 7;
idx++;
}
else
cnt--;
}
// as bits[1] and bits[3] are allways zero they are omitted in formulas.
humR = bits[0];
tmpC = bits[2];
tmpF = CtoF(tmpC);
tmpK = CtoK(tmpC);
dwpt = dewPnt(tmpC, humR);
chksum = bits[0] + bits[2];
if (bits[4] != chksum)
return DHT_CHKSUM_ERR;
return DHT_OK;
}
//C to F conversion
double dht11::CtoF(double tmpC)
{
return 1.8 * tmpC + 32;
}
//C to K conversion
double dht11::CtoK(double tmpC)
{
return tmpC + 273.15;
}
// reference: http://en.wikipedia.org/wiki/Dew_point
double dht11::dewPnt(double tmpC, double humR)
{
double a = 17.271;
double b = 237.7;
double temp = (a * tmpC) / (b + tmpC) + log(humR/100);
double Td = (b * temp) / (a - temp);
return Td;
}
| true |
ffd0a587ffeb0b30dab3bbcda87c4ae30ae0b61e | C++ | ReneeeZhang/Duke-ECE-565 | /HW5/rainfall/rainfall_pt.cpp | UTF-8 | 5,615 | 2.96875 | 3 | [] | no_license | #include <iostream>
#include <cstdlib>
#include <string>
#include <ctime>
#include <functional>
#include "landscape.hpp"
#include "threadpool.hpp"
#define NUM_ARGV 6
static int num_threads;
static int raining_time;
static double absorption_rate;
static int dim;
void validate_argc(int argc) {
if(argc != NUM_ARGV) {
std::cerr << "Usage: ./rainfall_seq <P> <M> <A> <N> <elevation_file>\n"
"P = # of parallel threads to use.\n"
"M = # of simulation time steps during which a rain drop will fall on each landscape point. In other words, 1 rain drop falls on each point during the first M steps of the simulation.\n"
"A = absorption rate (specified as a floating point number). The amount of raindrops that are absorbed into the ground at a point during a timestep.\n"
"N = dimension of the landscape (NxN).\n"
"elevation_file = name of input file that specifies the elevation of each point.\n";
exit(EXIT_FAILURE);
}
}
void validate_int_from_str(const char* str, const char* what_str) {
char* endptr;
strtol(str, &endptr, 10);
if(*endptr != '\0') {
std::cerr << "Wrong " << what_str << ". It should be an integer.\n";
exit(EXIT_FAILURE);
}
}
void validate_P(const char* P) {
validate_int_from_str(P, "simulation time steps");
}
void validate_M(const char* M) {
validate_int_from_str(M, "simulation time steps");
}
void validate_N(const char* N) {
validate_int_from_str(N, "dimension of the landscape");
int dim = atoi(N);
if(dim < 32) {
std::cerr << "To run parallel edition, the dimension of the landscape should be no smaller than 32.\n";
}
}
void validate_A(const char* A) {
char* endptr;
strtod(A, &endptr);
if(*endptr != '\0') {
std::cerr << "Wrong absorption rate. It should be a float point number.\n";
exit(EXIT_FAILURE);
}
}
void validate_arguments(int argc, char** argv) {
validate_argc(argc);
validate_P(argv[1]);
validate_M(argv[2]);
validate_A(argv[3]);
validate_N(argv[4]);
}
void output_results(int num_steps, double runtime, const Landscape& landscape) {
std::cout << "Rainfall simulation completed in " << num_steps << " time steps\n"
<< "Runtime = " << runtime << " seconds\n\n"
<< "The following grid shows the number of raindrops absorbed at each point:\n";
landscape.print_absorbed_drops();
}
double calc_time(struct timespec start, struct timespec end) {
double start_sec = (double)start.tv_sec * 1000000000.0 + (double)start.tv_nsec;
double end_sec = (double)end.tv_sec * 1000000000.0 + (double)end.tv_nsec;
if (end_sec < start_sec) {
return 0;
} else {
return end_sec - start_sec;
}
}
void first_iter(Landscape& landscape, int start_row, int end_row, bool& is_dry, int step) {
for(int i = start_row; i < end_row; i++) {
for(int j = 0; j < dim; j++) {
// Receive raindrops
if(step <= raining_time) {
landscape.receive_rain_drop(i, j);
}
// Absorb
landscape.absorb_pt(i, j, absorption_rate);
is_dry = is_dry && (landscape.get_raindrops(i, j) == 0);
// Calculate trickled drops
landscape.calculate_trickled_drops(i, j);
}
}
}
void second_iter(Landscape& landscape, int start_row, int end_row) {
for(int i = start_row; i < end_row; i++) {
for(int j = 0; j < dim; j++) {
landscape.trickle_to(i, j);
}
}
}
bool is_all_dry(const bool* dry_status, int num_threads) {
bool ans = true;
for(int i = 0; i < num_threads; i++) {
ans = ans && dry_status[i * 1024];
}
return ans;
}
int main(int argc, char* argv[]) {
// Argument validation
validate_arguments(argc, argv);
// Translate arguments
num_threads = atoi(argv[1]);
raining_time = atoi(argv[2]);
absorption_rate = atof(argv[3]);
dim = atoi(argv[4]);
// init_threadpool
TP::ThreadPool thread_pool(num_threads);
// init landscape
Landscape landscape(dim, argv[5]);
int step = 1;
int curr_dim = landscape.get_dim();
int k = curr_dim / num_threads / 2; // evenly distributed
bool* dry_status = new bool[num_threads * 1024]();
// set timer
struct timespec start_time, end_time;
clock_gettime(CLOCK_MONOTONIC, &start_time);
while(true) {
// Within one time step
// First iteration
for(int i = 0; i < num_threads; i++) {
dry_status[i * 1024] = true;
thread_pool.enqueue(std::bind(first_iter, std::ref(landscape), (2 * i) * k, (2 * i + 1) * k, std::ref(dry_status[i * 1024]), step));
}
thread_pool.waitAll();
for(int i = 0; i < num_threads; i++) {
thread_pool.enqueue(std::bind(first_iter, std::ref(landscape), (2 * i + 1) * k, (2 * i + 2) * k, std::ref(dry_status[i * 1024]), step));
}
thread_pool.waitAll();
if(is_all_dry(dry_status, num_threads)) {
break;
}
// Second iteration
for(int i = 0; i < num_threads; i++) {
thread_pool.enqueue(std::bind(second_iter, std::ref(landscape), (2 * i) * k, (2 * i + 2) * k));
}
thread_pool.waitAll();
++step;
}
clock_gettime(CLOCK_MONOTONIC, &end_time);
double runtime = calc_time(start_time, end_time) / 1000000000.0;
// thread_pool.joinThreads();
delete[] dry_status;
output_results(step, runtime, landscape);
return EXIT_SUCCESS;
} | true |
a18d884c069d89d3e9230951b2ace466466e3667 | C++ | alimsadetov/Programming | /Practice/15/c++/15/15.cpp | UTF-8 | 1,263 | 3.0625 | 3 | [] | no_license | // 15.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
//
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
setlocale(0, "");
cout << "привет введи число\n";
int x=1, i=0, chislo, n;
while (x == 1) {
chislo = rand() % 101;
for (i = 0; i <= 4; i++) {
cin >> n;
if (i == 4) {
if (n == chislo) {
cout << "пмпоздравляю, вы угадали ";
break;
}
else {
cout << "вы програли. было загадано: " << chislo<<"\n";
break;
}
}
if (n > chislo) cout << "загаданное число меньше ";
if (n < chislo) cout << "загаданное число больше ";
if (n == chislo) {
cout << "поздравляю число успешно угадано"; break;
}
}
cout << "хотите сыграть ещё раз? (1-ДА)";
cin >> x;
}
}
| true |
b19021abe274871f4af7f61cc6a99c5ef2a70a63 | C++ | amanohayato/SecretFilming | /MyGame/MyGame/src/Actor/TitleActor/TitleUfo/TitleUfo.cpp | SHIFT_JIS | 877 | 2.546875 | 3 | [] | no_license | #include "TitleUfo.h"
#include <memory>
#include "../../../Graphic/Model.h"
#include "../../../Game/Time.h"
#include "../../../Math/MathHelper.h"
TitleUfo::TitleUfo(IWorld* world, const Vector3& start, const Vector3& goal) :
Actor(world, "Ufo", start),
startPos_(start),
goalPos_(goal)
{
initialize();
}
TitleUfo::~TitleUfo()
{
}
void TitleUfo::initialize()
{
Vector3 temp = goalPos_ - startPos_;
velocity_ = Vector3::Normalize(temp) * moveSpeed_;
// t[Ŏg폜邩߂
deleteTimer_ = (int)(Vector3::Distance(startPos_, goalPos_) / moveSpeed_);
}
void TitleUfo::update(float deltaTime)
{
position_ += velocity_;
deleteTimer_--;
if (deleteTimer_ <= 0)
{
dead();
}
}
void TitleUfo::draw() const
{
Matrix mat = Matrix::Identity;
mat = mat.Translation(position_);
Model::GetInstance().Draw(MODEL_ID::MODEL_UFO, mat);
} | true |
4f241206201d3d6ade76b4e30fe6004febbfb5f5 | C++ | DuncanKane/Some-simple-C- | /SurgeryApp1/SurgeryApp1/SurgeryHeader.h | UTF-8 | 1,854 | 2.890625 | 3 | [] | no_license | #pragma once
#include <string>
#include <vector>
using namespace std;
#ifndef Login
class Login
{
public:
void GetLoginDetails(string sUsernamePass, string sPasswordPass);
bool CheckAdminLogin();
protected:
string sUsername, sPassword, sUsernameCheck, sPasswordCheck;
int iCount;
};
#endif // !Login
#ifndef Doctor
class Doctor
{
public:
void GetDetails(string sNamePass, string sSpecialistAreaPass, string sUsernamePass, string sPasswordPass, string sLocationPass);
void OutputDetails();
void OutputRceptionistView();
string OutputBooking(string sName);
void AppointmentBooked();
Doctor();
~Doctor();
protected:
string sName = "";
string sSpecialistArea = "";
string sUsername = "";
string sPassword = "";
string sLocation = "";
int iAppointmentSlots = 8;
};
#endif // !Doctor
#ifndef Receptionist
class Receptionist
{
public:
void GetDetails(string sNamePass);
void OutputDetails();
string OutputBooking(string sName);
protected:
string sName = "";
};
#endif // !Receptionist
#ifndef Appointments
class Appointments : public Doctor, public Receptionist
{
public:
void GetDetails(string sAssignDoctorPass, string sAssignReceptionistPass, string sPatientPass);
void OutputAppointmentDetails();
protected:
string sAssignedDoctor = "";
string sAssignedReceptionist = "";
string sPatientName = "";
};
#endif // !Appointments
#ifndef Patient
class Patient
{
public:
void GetDetails(string sPatientNamePass, int iContactNumberPass, string sAddressPass, string sAilmentPass);
void ShowDetails();
int AppointmentCost(int iChargePass);
void GetCost(int iTotalCostPass);
protected:
string sPatientName = "";
int iContactNumber, iTotalCharge, iBookedSlots;
string sAddress = "";
string sAilment = "";
int iCharge = 25;
};
#endif // !Patient
| true |
c236cd6e2254fabf169d690bfdabe42cbecda7f8 | C++ | Likilee/webserv | /src/TestMain.cpp | UTF-8 | 3,896 | 3.03125 | 3 | [] | no_license | #include <iostream>
#include <gtest/gtest.h>
//Test functions
#include "ConfigParser.hpp"
//ConfigParser
TEST(ConfigParser, fileToString)
{
ConfigParser parser;
//Test1. fileToString
std::string str = parser.fileToString("./test_res/configparser/file1");
std::string str_cmp = "server { #comment1\nlocation / #comment2\n\t{ #comment3\n\t\tallow GET POST; #comment4\n\t\troot /www/; #comment5\n\t} #comment6\n} #comment7";
ASSERT_STREQ(str.c_str(),str_cmp.c_str());
}
TEST(ConfigParser, eraseComment)
{
ConfigParser parser;
std::string str = parser.fileToString("./test_res/configparser/file1");
parser.eraseComment(str);
std::string str_cmp = "server { \nlocation / \n\t{ \n\t\tallow GET POST; \n\t\troot /www/; \n\t} \n} ";
ASSERT_STREQ(str.c_str(),str_cmp.c_str());
}
TEST(ConfigParser, stringToToken)
{
ConfigParser parser;
std::string str = parser.fileToString("./test_res/configparser/file1");
parser.eraseComment(str);
std::vector<std::string> token = parser.stringToToken(str);
std::string token_array[] =
{"server","{","location","/","{","allow","GET","POST;","root","/www/;","}","}"};
std::vector<std::string> token_cmp;
for (int i = 0; i < 12; ++i)
token_cmp.push_back(token_array[i]);
for (int i =0; i < 12; ++i)
EXPECT_STREQ(token[i].c_str(), token_cmp[i].c_str());
EXPECT_EQ(token.size(), token_cmp.size());
}
TEST(ConfigParser, parselistenPort)
{
ConfigParser parser;
std::vector<std::string> tokens;
tokens.push_back("listen");
tokens.push_back("8080;");
EXPECT_EQ(parser.parselistenPort(tokens.begin()), 8080);
}
TEST(ConfigParser, parseWorkerConnection)
{
ConfigParser parser;
std::vector<std::string> tokens;
tokens.push_back("worker_connection");
tokens.push_back("4096;");
EXPECT_EQ(parser.parselistenPort(tokens.begin()), 4096);
}
TEST(ConfigParser, parseOnlyOneStringToken)
{
ConfigParser parser;
std::vector<std::string> tokens;
tokens.push_back("server_name");
tokens.push_back("abcdefg;");
EXPECT_STREQ(parser.parseOnlyOneStringToken(tokens.begin()).c_str(), "abcdefg");
}
TEST(ConfigParser, parseErrorPage)
{
ConfigParser parser;
std::vector<std::string> tokens;
std::vector<std::string> tokens2;
std::map<int, std::string> error_page;
tokens.push_back("error_page");
tokens.push_back("404");
tokens.push_back("405");
tokens.push_back("406");
tokens.push_back("/www/404error.html;");
parser.parseErrorPage(tokens.begin(), error_page);
tokens2.push_back("error_page");
tokens2.push_back("404");
tokens2.push_back("501");
tokens2.push_back("/www;");
parser.parseErrorPage(tokens2.begin(), error_page);
ASSERT_STREQ(error_page[404].c_str(), "/www/404error.html");
ASSERT_STREQ(error_page[405].c_str(), "/www/404error.html");
ASSERT_STREQ(error_page[406].c_str(), "/www/404error.html");
ASSERT_STREQ(error_page[501].c_str(), "/www");
ASSERT_EQ(error_page.size(), 4);
}
TEST(ConfigParser, parseLocation)
{
ConfigParser parser;
std::vector<std::string> tokens;
tokens.push_back("location");
tokens.push_back("/webserv/");
ASSERT_STREQ(parser.parseLocation(tokens.begin()).c_str(), "/webserv/");
}
TEST(ConfigParser, parseIndexList)
{
ConfigParser parser;
std::vector<std::string> tokens;
std::vector<std::string> index;
tokens.push_back("index");
tokens.push_back("index.html");
tokens.push_back("index.php;");
index = parser.parseIndexList(tokens.begin());
ASSERT_STREQ(index[0].c_str(), "index.html");
ASSERT_STREQ(index[1].c_str(), "index.php");
}
TEST(ConfigParser, parseAllow)
{
ConfigParser parser;
std::vector<std::string> tokens;
std::vector<std::string> method;
tokens.push_back("allow");
tokens.push_back("GET");
tokens.push_back("POST;");
method = parser.parseIndexList(tokens.begin());
ASSERT_STREQ(method[0].c_str(), "GET");
ASSERT_STREQ(method[1].c_str(), "POST");
}
int main(int argc, char **argv) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
} | true |
77fa194b6e01eaf789fcebd74984110a9e21e5ad | C++ | PenteractStudios/Tesseract | /Project/Source/Utils/Quadtree.h | UTF-8 | 8,014 | 2.890625 | 3 | [
"MIT"
] | permissive | #pragma once
#include "Globals.h"
#include "Utils/Pool.h"
#include "Math/myassert.h"
#include "Geometry/AABB2D.h"
#include <vector>
#include <list>
template<typename T>
class Quadtree {
public:
// The elements in a node are linked
class Element {
public:
T* object = nullptr;
AABB2D aabb = {{0, 0}, {0, 0}};
Element* next = nullptr;
};
// Nodes are as small as possible (8 bytes) to reduce memory usage and cache efficiency
class QuadNode;
class Node {
public:
void Add(Quadtree& tree, T* object, const AABB2D& objectAABB, unsigned depth, const AABB2D& nodeAABB, bool optimizing) {
if (IsBranch()) {
// Branch
childNodes->Add(tree, object, objectAABB, depth + 1, nodeAABB, optimizing);
} else if (depth == tree.maxDepth || (unsigned) elementCount < tree.maxNodeElements) {
// Leaf that can't split or leaf with space
if (optimizing) {
Element* newFirstElement = tree.elements.Obtain();
newFirstElement->object = object;
newFirstElement->aabb = objectAABB;
newFirstElement->next = firstElement;
firstElement = newFirstElement;
} else {
Element element;
element.object = object;
element.aabb = objectAABB;
size_t index = tempElementList->size();
tempElementList->emplace_back(element);
tree.numAddedElements += 1;
}
elementCount += 1;
} else {
// Leaf with no space that can split
Split(tree, depth, nodeAABB, optimizing);
childNodes->Add(tree, object, objectAABB, depth + 1, nodeAABB, optimizing);
}
}
void Remove(Quadtree& tree, T* object) {
if (IsBranch()) {
childNodes->Remove(tree, object);
} else {
Element** elementPtr = &firstElement;
Element* element = firstElement;
while (element != nullptr) {
if (element->object == object) {
*elementPtr = element->next;
tree.elements.Release(element);
elementCount -= 1;
}
elementPtr = &element->next;
element = element->next;
}
}
}
void Split(Quadtree& tree, unsigned depth, const AABB2D& nodeAABB, bool optimizing) {
if (optimizing) {
// Get first element before anything changes
Element* element = firstElement;
// Transform leaf into branch
elementCount = -1;
childNodes = tree.quadNodes.Obtain();
childNodes->Initialize();
// Remove all elements and reinsert them
while (element != nullptr) {
T* object = element->object;
AABB2D objectAABB = element->aabb;
Element* nextElement = element->next;
tree.elements.Release(element);
childNodes->Add(tree, object, objectAABB, depth + 1, nodeAABB, optimizing);
element = nextElement;
}
} else {
// Get element vector before anything changes
std::list<Element>* tempElements = tempElementList;
// Transform leaf into branch
elementCount = -1;
tree.auxQuadNodes.emplace_back(QuadNode());
childNodes = &tree.auxQuadNodes.back();
childNodes->InitializeAndCreateElementLists();
// Remove all elements and reinsert them
for (Element& tempElement : *tempElements) {
T* object = tempElement.object;
AABB2D objectAABB = tempElement.aabb;
tree.numAddedElements -= 1;
childNodes->Add(tree, object, objectAABB, depth + 1, nodeAABB, optimizing);
}
RELEASE(tempElements);
}
}
bool IsLeaf() const {
return elementCount >= 0;
}
bool IsBranch() const {
return elementCount < 0;
}
public:
int elementCount = 0; // Leaf: number of elements. Branch: -1.
union {
Element* firstElement = nullptr; // Leaf only: first element.
QuadNode* childNodes; // Branch only: child nodes index.
std::list<Element>* tempElementList;
};
};
// Nodes are in groups of 4 so that only 1 pointer is needed
struct QuadNode {
public:
void Initialize() {
for (Node& node : nodes) {
node.elementCount = 0;
node.firstElement = nullptr;
}
}
void InitializeAndCreateElementLists() {
for (Node& node : nodes) {
node.elementCount = 0;
node.tempElementList = new std::list<Element>();
}
}
void ReleaseElementLists() {
for (Node& node : nodes) {
if (node.IsLeaf()) {
RELEASE(node.tempElementList);
}
}
}
void Add(Quadtree& tree, T* object, const AABB2D& objectAABB, unsigned depth, const AABB2D& nodeAABB, bool optimizing) {
vec2d center = nodeAABB.minPoint + (nodeAABB.maxPoint - nodeAABB.minPoint) * 0.5f;
AABB2D topLeftAABB = {{nodeAABB.minPoint.x, center.y}, {center.x, nodeAABB.maxPoint.y}};
if (objectAABB.Intersects(topLeftAABB)) {
nodes[0].Add(tree, object, objectAABB, depth, topLeftAABB, optimizing);
}
AABB2D topRightAABB = {{center.x, center.y}, {nodeAABB.maxPoint.x, nodeAABB.maxPoint.y}};
if (objectAABB.Intersects(topRightAABB)) {
nodes[1].Add(tree, object, objectAABB, depth, topRightAABB, optimizing);
}
AABB2D bottomLeftAABB = {{nodeAABB.minPoint.x, nodeAABB.minPoint.y}, {center.x, center.y}};
if (objectAABB.Intersects(bottomLeftAABB)) {
nodes[2].Add(tree, object, objectAABB, depth, bottomLeftAABB, optimizing);
}
AABB2D bottomRightAABB = {{center.x, nodeAABB.minPoint.y}, {nodeAABB.maxPoint.x, center.y}};
if (objectAABB.Intersects(bottomRightAABB)) {
nodes[3].Add(tree, object, objectAABB, depth, bottomRightAABB, optimizing);
}
}
void Remove(Quadtree& tree, T* object) {
for (Node& node : nodes) {
node.Remove(tree, object);
}
}
public:
Node nodes[4];
};
public:
void Initialize(AABB2D quadtreeBounds, unsigned quadtreeMaxDepth, unsigned maxElementsPerNode) {
assert(quadtreeMaxDepth > 0);
Clear();
bounds = quadtreeBounds;
maxDepth = quadtreeMaxDepth;
maxNodeElements = maxElementsPerNode;
auxRoot.tempElementList = new std::list<Element>();
}
void Add(T* object, const AABB2D& objectAABB) {
assert(!operative); // Tried to add an object to a locked quadtree
auxRoot.Add(*this, object, objectAABB, 1, bounds, false);
addedObjects.emplace_back(std::pair<T*, AABB2D>(object, objectAABB));
}
void Remove(T* object) {
assert(operative); // Tried to remove an object from an unlocked quadtree
root.Remove(*this, object);
}
void Optimize() {
quadNodes.Allocate(auxQuadNodes.size());
elements.Allocate(numAddedElements);
for (std::pair<T*, AABB2D> pair : addedObjects) {
AddToPools(pair.first, pair.second);
}
for (QuadNode& quadNode : auxQuadNodes) {
quadNode.ReleaseElementLists();
}
if (auxRoot.IsBranch()) {
auxRoot.elementCount = 0;
auxRoot.tempElementList = nullptr;
} else {
auxRoot.elementCount = 0;
RELEASE(auxRoot.tempElementList);
}
numAddedElements = 0;
auxQuadNodes.clear();
addedObjects.clear();
operative = true;
}
bool IsOperative() {
return operative;
}
void Clear() {
bounds.minPoint.Set(0, 0);
bounds.maxPoint.Set(0, 0);
maxDepth = 0;
maxNodeElements = 0;
root.elementCount = 0;
root.firstElement = nullptr;
quadNodes.Deallocate();
elements.Deallocate();
operative = false;
for (QuadNode& quadNode : auxQuadNodes) {
quadNode.ReleaseElementLists();
}
if (auxRoot.IsBranch()) {
auxRoot.elementCount = 0;
auxRoot.tempElementList = nullptr;
} else {
auxRoot.elementCount = 0;
RELEASE(auxRoot.tempElementList);
}
numAddedElements = 0;
auxQuadNodes.clear();
addedObjects.clear();
}
public:
AABB2D bounds = {{0, 0}, {0, 0}}; // Bounds of the quadtree. All elements should be contained inside this.
unsigned maxDepth = 0; // Max depth of the tree. Useful to avoid infinite divisions. This should be >= 1.
unsigned maxNodeElements = 0; // Max number of elements before a node is divided.
Node root;
Pool<QuadNode> quadNodes;
Pool<Element> elements;
protected:
void AddToPools(T* object, const AABB2D& objectAABB) {
root.Add(*this, object, objectAABB, 1, bounds, true);
}
private:
bool operative = false;
Node auxRoot;
unsigned numAddedElements = 0;
std::list<QuadNode> auxQuadNodes;
std::list<std::pair<T*, AABB2D>> addedObjects;
};
| true |
0ee22d78a360d7c42ba33f706001251f9dd860b7 | C++ | jerrykcode/luogu | /Problems/P1129/P1129.cpp | UTF-8 | 2,142 | 2.96875 | 3 | [] | no_license | #include <cstdio>
#include <cstdlib>
#include <vector>
#include <queue>
using namespace std;
typedef unsigned char vertex;
#define MAX_N 200
#define NOT_A_VERTEX 0xff
queue<vertex> vqueue;
bool hungarian(vector<vertex> * graph, int num) {
vertex * left_matching = new vertex[num];
fill(left_matching, left_matching + num, NOT_A_VERTEX);
vertex * right_matching = new vertex[num];
fill(right_matching, right_matching + num, NOT_A_VERTEX);
vertex * pre = new vertex[num];
fill(pre, pre + num, NOT_A_VERTEX);
bool * visited = new bool[num];
bool result = true;
for (vertex v = 0; v < num; v++) {
fill(visited, visited + num, false);
vqueue.push(v);
vertex front_v, adj_v, from, to, tmp;
while (!vqueue.empty()) {
front_v = vqueue.front();
vqueue.pop();
for (auto it = graph[front_v].begin(); it != graph[front_v].end(); it++) {
adj_v = *it;
if (!visited[adj_v]) {
visited[adj_v] = true;
if (right_matching[adj_v] != NOT_A_VERTEX) {
vqueue.push(right_matching[adj_v]);
pre[right_matching[adj_v]] = front_v;
}
else {
from = front_v;
to = adj_v;
while (from != NOT_A_VERTEX) {
tmp = left_matching[from];
left_matching[from] = to;
right_matching[to] = from;
from = pre[from];
to = tmp;
}
while (!vqueue.empty()) vqueue.pop();
goto NEXT;
}
}
} //for auto
} //while
NEXT:
if (left_matching[v] != NOT_A_VERTEX) continue;
result = false;
break;
} //for (vertex v = 0; v < num; v++)
free(left_matching);
free(right_matching);
free(pre);
free(visited);
return result;
}
int main() {
int t, n;
vector<vertex> * graph = new vector<vertex>[MAX_N];
scanf("%d", &t);
while (t) {
scanf("%d", &n);
int w;
for (size_t i = 0; i < n; i++) {
for (size_t j = 0; j < n; j++) {
scanf("%d", &w);
if (w) graph[i].push_back(j);
}
}
if (hungarian(graph, n)) printf("Yes\n");
else printf("No\n");
for (size_t i = 0; i < n; i++)
graph[i].clear();
t--;
}
for (size_t i = 0; i < MAX_N; i++)
vector<vertex>().swap(graph[i]);
queue<vertex>().swap(vqueue);
return 0;
} | true |
d0f91fcd0b50c9a99d7ec47f1c000d424db5109c | C++ | Mario0211/P3_Ejercicio_01 | /p_3/include/rectangulo.h | UTF-8 | 1,138 | 3.140625 | 3 | [] | no_license | #ifndef RECTANGULO_H
#define RECTANGULO_H
#include <iostream>
#include <math.h>
#include "punto.h"
using namespace std;
class Rectangulo{
private:
Punto superiorIzquierdo;
Punto superiorDerecho;
Punto inferiorIzquierdo;
Punto inferiorDerecho;
public:
Rectangulo(){
cout << "Se ha creado un rectangulo" << endl;
}
void AsignarSupIzq(float x, float y){
superiorIzquierdo.asignarX( x);
superiorIzquierdo.asignarY( y);
}
void AsignarSupDer(float x, float y){
superiorDerecho.asignarX( x);
superiorDerecho.asignarY( y);
}
void AsignarInfIzq(float x, float y){
inferiorIzquierdo.asignarX( x);
inferiorIzquierdo.asignarY( y);
}
void AsignarInfDer(float x, float y){
inferiorDerecho.asignarX( x);
inferiorDerecho.asignarY( y);
}
float Perimetro(){
float base = abs(inferiorDerecho.obtenerX() - inferiorIzquierdo.obtenerX());
float altura = abs(inferiorDerecho.obtenerY() - superiorIzquierdo.obtenerY());
return (base*2) + (altura*2);
}
float Area(){
float base = abs(inferiorDerecho.obtenerX() - inferiorIzquierdo.obtenerX());
float altura = abs(inferiorDerecho.obtenerY() - superiorIzquierdo.obtenerY());
return (base*altura);
}
};
#endif
| true |
83350daee57f67cb66785c26e7c690a9e8529f88 | C++ | Shivam06/Cpp-Programming | /DS/Arrays/(IMP)missing_number.cpp | UTF-8 | 953 | 2.921875 | 3 | [] | no_license | #include "helper_functions.cpp"
void change_neg_to_zero(vi& v) {
tr (v, itr) {
if (*itr < 0) {
*itr = 0;
}
}
}
int missingNumber(vi& v) {
change_neg_to_zero(v);
int i = 0, n = v.size();
while (i < n) {
if (v[i] <= 0 || v[i] > n) {
//cout << "Skipping" << endl;
i++;
continue;
}
int new_idx = v[i]-1;
// This check is important for cases where value
// being swapped and the value being swapped to are the same.
if (v[new_idx] < 0) {
i++;
continue;
}
if (i != new_idx)
swap(v[i], v[new_idx]);
v[new_idx]*=-1;
}
tr(v, itr) {
if (*itr >= 0) {
return (itr - v.begin() + 1);
}
}
return v.size()+1;
}
int main() {
vi v{{33, -50, 18, -34, -4, -1, -13, -29, 9, -47, 37, -29, -8, -7, 25, 27, -40, 12, 36, 20, 47, 43, -33, 11, -22, -26, -33, 16, 8, 9, 16, 43, 9, 36, -41, 7, -15, -4, -20, 45, -48, -33, -34, 46, -37, 42, 24, -27, -44
}};
cout << missingNumber(v) << endl;
return 0;
} | true |
dd6e489d7d5c64d7ae78506a443268474eba38c0 | C++ | D3z1re/PNRPU_Labs | /Lab_21/graph.cpp | UTF-8 | 5,648 | 2.640625 | 3 | [] | no_license | #include "graph.h"
#include "ui_graph.h"
#include <cmath>
#include <queue>
#include <QTextStream>
using namespace std;
QTextStream cout(stdout);
QTextStream cin(stdin);
int radiusA = 30,
radiusB = 230;
QString Graph::Dejkstra()
{
QString tmp = "";
int top = 0; //вершина с номером 1
queue<int> line;
line.push(top);
result[0] = 0;
while (!line.empty()) {
int vert = line.front();
line.pop();
for (int i = 0; i < matrix[vert].size(); i++) {
if (!visited[i] && matrix[vert][i] && (matrix[vert][i] + result[vert] < result[i])) {
result[i] = matrix[vert][i] + result[vert];
line.push(i);
}
}
}
for (int i = 0; i < 6; i++) {
cout << i + 1 << ": " << result[i] << endl;
tmp += QString::number(i + 1) + ": " + QString::number(result[i]) + "\n";
}
return tmp;
}
int Graph::GetWeight(const int vert1, const int vert2) //получение веса ребра
{
if (vert1 >= 0 && vert1 < matrix.size() && vert2 >=0 && vert2 < matrix.size())
return matrix[vert1][vert2];
else
return 0;
}
void Graph::DrawLines(QGraphicsScene* scene) //отрисовка ребер графа
{
QPen pen(Qt::black);
pen.setWidth(2);
int centerX= scene->width() / 2,
centerY = scene->height() / 2;
double iter = 2 * 3.1415 / matrix.size();
for (int i = 0; i < matrix.size(); i++){
for (int j = 0; j < matrix.size(); j++){
if (GetWeight(i, j) > 0){
int vert_1_x = centerX + cos(iter * i) * radiusB,
vert_1_y = centerY - sin(iter * i) * radiusB,
vert_2_x = centerX + cos(iter * j) * radiusB,
vert_2_y = centerY - sin(iter * j) * radiusB;
scene->addLine(vert_1_x, vert_1_y, vert_2_x, vert_2_y, pen);
QGraphicsTextItem *number = scene->addText(QString::number(GetWeight(i, j)), QFont("Times", 14));
number->setPos((vert_2_x + vert_1_x) / 2, (vert_2_y + vert_1_y) / 2);
}
}
}
}
void Graph::DrawArrows(QGraphicsScene* scene) //отрисовка стрелок
{
QPen pen(Qt::black);
pen.setWidth(2);
int centerX= scene->width() / 2,
centerY = scene->height() / 2;
int r1 = radiusA / 3;
double len = 15.0;
double ostr = 0.35;
double arr_x, arr_y;
double iter = 2 * 3.1415 / matrix.size();
for (int i = 0; i < matrix.size(); i++){
for (int j = 0; j < matrix.size(); j++){
if (GetWeight(i, j) > 0){
int vert_1_x = centerX + cos(iter * i) * radiusB,
vert_1_y = centerY - sin(iter * i) * radiusB,
vert_2_x = centerX + cos(iter * j) * radiusB,
vert_2_y = centerY - sin(iter * j) * radiusB;
double angle = atan2(((double)vert_2_y - vert_1_y), ((double)(vert_2_x - vert_1_x)));
//double t = radiusA / sqrt((vert_2_x - vert_1_x) * (vert_2_x - vert_1_x) + (vert_2_y - vert_1_y) * (vert_2_y - vert_1_y));
arr_x = (vert_2_x - (radiusA * cos(angle))) - (len * cos(angle + ostr));
arr_y = (vert_2_y - (radiusA * sin(angle))) - (len * sin(angle + ostr));
scene->addLine(vert_2_x - (radiusA * cos(angle)), vert_2_y - (radiusA * sin(angle)), arr_x, arr_y, pen);
arr_x = (vert_2_x - (radiusA * cos(angle))) - (len * cos(angle - ostr));
arr_y = (vert_2_y - (radiusA * sin(angle))) - (len * sin(angle - ostr));
scene->addLine(vert_2_x - (radiusA * cos(angle)), vert_2_y - (radiusA * sin(angle)), arr_x, arr_y, pen);
}
}
}
}
void Graph::DrawNodes(QGraphicsScene* scene) //отрисовка вершин графа
{
QPen pen(Qt::black);
pen.setWidth(3);
int centerX= scene->width() / 2,
centerY = scene->height() / 2;
double iter = 2 * 3.1415 / matrix.size();
for (int i = 0; i < matrix.size(); i++){
scene->addEllipse(centerX + cos(iter * i) * radiusB - radiusA,
centerY - sin(iter * i) * radiusB - radiusA, 2*radiusA, 2*radiusA,
pen, QBrush(QColor(193,251,227)));
QGraphicsTextItem *number = scene->addText(QString::number(i+1), QFont("Times", 14));
number->setPos(centerX + cos(iter * i) * radiusB - radiusA + 18,
centerY - sin(iter * i) * radiusB - radiusA + 10);
}
}
void Graph::DrawGraph(QGraphicsScene* scene) //отрисовка графа
{
DrawLines(scene);
DrawArrows(scene);
DrawNodes(scene);
}
void Graph::Draw() //отрисовка сцены с графом
{
scene = new QGraphicsScene();
scene->setSceneRect(0, 0, 700, 630);
ui->graphicsView->setScene(scene);
scene->clear();
scene->setBackgroundBrush(QBrush(QColor(214,237,255), Qt::SolidPattern));
ui->label_komi->setText(Dejkstra());
DrawGraph(scene);
}
Graph::Graph(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::Graph)
{
ui->setupUi(this);
kol = 6;
matrix = { {0, 14, 0, 0, 0, 0 },
{0, 0, 0, 0, 42, 23 },
{19, 0, 0, 9, 0, 0 },
{0, 0, 0, 0, 0, 31 },
{0, 0, 18, 0, 0, 0 },
{28, 23, 0, 0, 0, 0 } };
Draw();
}
Graph::~Graph()
{
delete ui;
}
| true |
2bbcbaee5cbf79f7ab843b7065a3a69a0ed6a2fa | C++ | CreatorSeraph/ModernCppChallengeStudy | /Math/Problem2/main.cpp | UTF-8 | 547 | 2.75 | 3 | [
"MIT"
] | permissive | #include <gsl/gsl>
#include <iostream>
#include <../MyMath.h>
#include <numeric>
int main(int argc, char* argv[])
{
size_t input1, input2;
std::cin >> input1 >> input2;
std::cout << std::gcd(input1, input2) << std::endl;
//auto table = MyMath::PrimeNumberVec(std::max(input1, input2));
//
//size_t result = 1;
//for (auto iter : table)
//{
// while (input1 % iter == 0 && input2 % iter == 0)
// {
// result *= iter;
// input1 /= iter;
// input2 /= iter;
// }
//}
//
//std::cout << result << std::endl;
return 0;
}
| true |
f5812fe4d75fdc489fe6e7a7fd6fd8d3d1ee1ecc | C++ | igorge/gieidl-oldstuff | /idl_compil/idl_countable_string.h | UTF-8 | 2,406 | 2.78125 | 3 | [] | no_license | //================================================================================================================================================
//
// (c) GIE 04.03.2005
//
//================================================================================================================================================
#ifndef H_GUARD_IDL_COUNTABLE_STRING_H__04_03_2005__6_14_41
#define H_GUARD_IDL_COUNTABLE_STRING_H__04_03_2005__6_14_41
//================================================================================================================================================
#pragma once
//================================================================================================================================================
#include "gielib/core/num_capacity.h"
#include "boost/intrusive_ptr.hpp"
#include "utility.countable.h"
//================================================================================================================================================
namespace gie_idl {
struct ref_countable_string_t
: public gie::ref_countable<ref_countable_string_t>
, public string_t
{
ref_countable_string_t(const string_t& value)
: string_t( value )
{}
ref_countable_string_t(const string_t::value_type* const value)
: string_t( value )
{}
bool operator<(const ref_countable_string_t& r)const throw()
{
//compare string content
if( this == &r ) return false;
return ( static_cast<const string_t&>(*this) < static_cast<const string_t&>(r) );
}
};
typedef boost::intrusive_ptr<ref_countable_string_t> ref_countable_string_ptr_t;
inline
ref_countable_string_ptr_t new_string(const string_t::value_type* const value )
{
return ref_countable_string_ptr_t( new ref_countable_string_t(value) );
}
inline
bool operator<(const ref_countable_string_ptr_t& l, const ref_countable_string_ptr_t& r)
{
return (*l < *r);
}
}
//================================================================================================================================================
#endif//H_GUARD_IDL_COUNTABLE_STRING_H__04_03_2005__6_14_41
//================================================================================================================================================
| true |
82d5e006bd9d0d43e51ac202c648e8f726e17363 | C++ | loveFaying/Leetcode | /11_String/500. Keyboard Row/main2.cpp | UTF-8 | 1,114 | 3.1875 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
// https://leetcode-cn.com/problems/keyboard-row/
// Time: O(L)
// Space: O(C)
class Solution {
public:
vector<string> findWords(vector<string>& words) {
vector<string> res;
string rowIdx = "12210111011122000010020202";
for (auto& word : words) {
bool isValid = true;
char idx = rowIdx[tolower(word[0]) - 'a'];
for (int i = 1; i < word.size(); i++) {
if(rowIdx[tolower(word[i]) - 'a'] != idx) {
isValid = false;
break;
}
}
if (isValid) {
res.emplace_back(word);
}
}
return res;
}
};
int main(){
// string array[] = {"Hello","Alaska","Dad","Peace"};
string array[] = {"omk"};
// string array[] = {"adsdf","sfd"};
int n = sizeof(array)/sizeof(string);
vector<string> words(array, array+n);
vector<string> results = Solution().findWords(words);
for(auto res: results)
cout << res << " ";
cout << endl;
return 0;
} | true |
5ada8b06e9ebbb3a729ec897bdf1725f549e4d16 | C++ | royyjzhang/leetcode_cpp | /396_RotateFunction.cpp | UTF-8 | 781 | 3.109375 | 3 | [] | no_license | #include<iostream>
#include<vector>
#include<queue>
#include<stdlib.h>
#include<string>
#include<algorithm>
#include<map>
#include<math.h>
#include<stdint.h>
#include<stack>
#include<sstream>
#include<unordered_map>
using namespace std;
class Solution {
public:
int maxRotateFunction(vector<int>& A) {
int result, sum, now, n = A.size();
if (n == 0) {
return 0;
}
sum = 0;
now = 0;
for (int i = 0; i < n; i++) {
sum += A[i];
now += i*A[i];
}
result = now;
for (int i = n - 1; i >= 0; i--) {
now += sum - n*A[i];
if (now > result)
result = now;
}
return result;
}
};
int main() {
Solution s;
vector<int> A = { 4,3,2,6 };
cout << s.maxRotateFunction(A) << endl;
system("PAUSE");
return 0;
} | true |
c3ee4d68eac7f8e3bef1a9c042049af3c94fd6c6 | C++ | Fraunhofer-AISEC/cpg | /cpg-language-cxx/src/test/resources/cfg.cpp | UTF-8 | 195 | 2.734375 | 3 | [
"LicenseRef-scancode-generic-cla",
"Apache-2.0"
] | permissive | #include <stdio.h>
int main() {
cout << "bla";
cout << "blubb";
if(true) {
cout << "zonk";
return 1;
} else {
{
cout << "zink";
return 2;
}
}
return 0;
}
| true |
b9299dc047102e6b32ceebb94000ed75cfad206a | C++ | thelastsupreme/cs106x | /classes/BankAccount.cpp | UTF-8 | 1,284 | 3.8125 | 4 | [] | no_license | #include<iostream>
#include<string>
#include<vector>
#include"BankAccount.h"
using namespace std;
BankAccount::BankAccount(string accountName,double startBalance)
{
name=accountName;
balance=startBalance;
}
//other way of writing using this
/*
BankAccount::BankAccount(string name,double balance)
{
this->name=name;
this->balance=balance;
}
*/
bool BankAccount::withdraw(double amount)
{
if(amount<=balance && amount>=0)
{
balance-=amount;
return true;
}
return false;
}
bool BankAccount::deposit(double amount)
{
if(amount>=0)
{
balance+=amount;
return true;
}
return false;
}
double BankAccount::getBalance()
{
return balance;
}
void BankAccount::setName(string newName)
{
name=newName;
}
void BankAccount::print_account()
{
cout<<"name is :"<<name<<" "<<"balance is"<<balance<<endl;
}
int main()
{
int n;
vector<BankAccount>v;
cout<<"enter the number of accounts u want to create"<<endl;
cin>>n;
cout<<"enter name and then inital balance of the customer"<<endl;
for(int i=0;i<n;i++)
{
string s;
double d;
cin>>s;
cin>>d;
v.push_back(BankAccount(s,d));
}
for(int i=0;i<n;i++)
v[i].print_account();
} | true |
82c12b389a88e38cca38a7d917effa985649d38f | C++ | donihrmn/5180711106-tugasAlgo2 | /5180711106-tugasAlgo2-Modulus Young.cpp | UTF-8 | 391 | 3.375 | 3 | [] | no_license | #include<iostream>
using namespace::std;
int ModulusYoung (int angka, int modulus)
{
if(angka<modulus)
return 0;
else
return 1+ModulusYoung(angka-modulus,modulus);
}
main()
{
int angka,modulus;
cout<<"Masukkan Tegangan : ";cin>>angka;
cout<<"Masukkan Regangan : ";cin>>modulus;
cout<<"Modulus Young : "<<ModulusYoung(angka,modulus);
}
| true |
e3b6a6ad3ae4be5355281de75e624137375b30a1 | C++ | mhackampari/OpenCL | /Project_1.1/C++/FiltersC++.cpp | WINDOWS-1252 | 7,068 | 2.65625 | 3 | [] | no_license | #include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
#include "image_processing.hpp"
#include <ctime>
#include <fstream>
#include <iomanip>
#define ITERATIONS 25
using namespace std;
double factor = 2;
class Image{
private:
string cat[5];
string motion[5];
string background[5];
int i;
public:
sImage *inputDS, *outputDS, *motionI, *backgroundI, *outputMD, *outputE, *outputE2, *gaussianI, *gaussianO, *gaussianG, *gaussianGS;
public:
float factor_x = 0, factor_y = 0;
public: //default constructor
Image(){
exit;
}
public: //constructor goes through all image files
Image(int i){
string cat[5] = { "cat025.bmp", "cat05.bmp", "cat.bmp", "2cat.bmp", "4cat.bmp" }; //downsample
string motion[5] = { "motion025.bmp", "motion05.bmp", "motion.bmp", "2motion.bmp", "4motion.bmp" };
string background[5] = { "background025.bmp", "background05.bmp", "background.bmp", "2background.bmp", "4background.bmp" };
// problema qui!!!
inputDS = new sImage;
outputDS = new sImage;
motionI = new sImage;
backgroundI = new sImage;
outputMD = new sImage;
outputE = new sImage;
outputE2 = new sImage;
gaussianI = new sImage;
gaussianG = new sImage;
gaussianO = new sImage;
gaussianGS = new sImage;
*inputDS = set_image(cat[i]);
factor_x = set_factor(inputDS->rows, factor);
factor_y = set_factor(inputDS->rows, factor);
*outputDS = set_downscale_output(*inputDS, factor);
*motionI = set_image(motion[i]);
*backgroundI = set_image(background[i]);
*outputMD = set_output_image(*backgroundI); // copying properties to all files
*outputE = set_output_image(*backgroundI);
*outputE2 = set_output_image(*backgroundI);
rgb2grey(backgroundI, outputE);
rgb2grey(motionI, outputE2);
*gaussianI = set_image(cat[i]);
*gaussianG = set_image(cat[i]);
*gaussianGS = set_image(cat[i]);
rgb2grey(gaussianI, gaussianG);
rgb2grey(gaussianI, gaussianGS);
*gaussianO = set_output_image(*gaussianI);
}
private:
sImage set_image(string file_name){
sImage image;
readImage((char *)file_name.c_str(), &image);
return image;
}
private:
sImage set_downscale_output(sImage original, float factor){
int fileSize = 0;
sImage output;
float factor_x, factor_y;
factor_x = set_factor(original.rows, factor);
factor_y = set_factor(original.cols, factor);
output.rows = padding_size(original.rows, factor_y);
output.cols = padding_size(original.cols, factor_x);
fileSize = output.cols*output.rows * 3 + 54L;
output.data = (unsigned char *)malloc((output.rows*output.cols)*sizeof(unsigned char)* 3);
output.header = (unsigned char *)malloc(54L * sizeof(unsigned char));
output.depth = original.depth;
memcpy(output.header, original.header, 54L);
memcpy(&output.header[2], &fileSize, 4);
memcpy(&output.header[18], &output.cols, 4);
memcpy(&output.header[22], &output.rows, 4);
return output;
}
private:
float set_factor(int original_size, float factor){
float temp = (float)original_size / padding_size(original_size, factor);
if (temp != factor) temp += 0.00001;
return temp;
}
private:
int padding_size(int original_size, float factor){
int temp = 0, rest = 0;
temp = floor(original_size / factor);
rest = temp * 3 % 4;
return temp + rest;
}
private:
sImage set_output_image(sImage image){
sImage output;
output.rows = image.rows;
output.cols = image.cols;
output.data = (unsigned char *)malloc(image.rows*image.cols*sizeof(unsigned char));
output.header = NULL;
return output;
}
};
// measures time and writes on file
class Benchmark{
public:
clock_t start = 0, end = 0, total = 0;
public:
void startt(){
start = 0;
start = clock();
}
public:
void endt(){
end = 0;
end = clock();
total = end - start;
}
public:
void write_to_file(string filename, int i){
ofstream file;
float temp = 1000 * (float)total / (CLOCKS_PER_SEC * ITERATIONS);
file.open(filename + "_" + "benchmark.txt", ios::out | ios::app);
if (file.is_open()){
file << filename + "_" + to_string(i) << endl << "*********************************" <<endl;
file << fixed << setprecision(3) << temp << " ms" << endl << endl;
file.close();
}
else cout << "ERROR OPENENING FILE" << endl;
}
};
int main()
{
string downsample_name = "Downsampled_O";
string motion_name = "Motion_O";
string erosion_name = "Erosion_O";
string gaussian_grey_name = "Gaussian_Grey_O";
string gaussian_separable_name = "Gaussian_Separable_O";
for (int i = 0; i < 5; i++){
Image var_image(i); //defining constructor
Benchmark benchmark;
Image *var = new Image;
cout << endl << endl;
for (int j = 0; j < ITERATIONS; j++){
benchmark.endt();
image_downsample(var_image.inputDS, var_image.outputDS, var_image.factor_x, var_image.factor_y);
benchmark.endt();
}
benchmark.write_to_file(downsample_name, i);
writeImage((downsample_name + "_" + to_string(i) + ".bmp").c_str(), var_image.outputDS);
cout << "Processing: " << motion_name + "_" + to_string(i) << endl;
for (int j = 0; j < ITERATIONS; j++){
benchmark.endt();
motion_detection(var_image.outputE, var_image.outputE2, var_image.outputMD);
benchmark.endt();
}
grey2rgb(var_image.outputMD, var_image.backgroundI);
benchmark.write_to_file(motion_name, i);
writeImage((motion_name + "_" + to_string(i) + ".bmp").c_str(), var_image.backgroundI);
cout << "Processing: " << erosion_name + "_" + to_string(i) << endl;
for (int j = 0; j < ITERATIONS; j++){
benchmark.endt();
erosion_filter(var_image.outputMD, var_image.outputE);
benchmark.endt();
}
grey2rgb(var_image.outputE, var_image.motionI);
benchmark.write_to_file(erosion_name, i);
writeImage((erosion_name + "_" + to_string(i) + ".bmp").c_str(), var_image.motionI);
cout << "Processing: " << gaussian_grey_name + "_" + to_string(i) << endl;
for (int j = 0; j < ITERATIONS; j++){
benchmark.endt();
gaussian_grey_filter(var_image.gaussianG, var_image.gaussianO, 3);
benchmark.endt();
}
grey2rgb(var_image.gaussianO, var_image.gaussianG);
benchmark.write_to_file(gaussian_grey_name, i);
writeImage((gaussian_grey_name + "_" + to_string(i) + ".bmp").c_str(), var_image.gaussianG);
cout << "Processing: " << gaussian_separable_name + "_" + to_string(i) << endl;
for (int j = 0; j < ITERATIONS; j++){
benchmark.endt();
gaussian_separable_filter(var_image.gaussianGS, var_image.gaussianG, var_image.gaussianO, 3);
benchmark.endt();
}
grey2rgb(var_image.gaussianO, var_image.gaussianG);
benchmark.write_to_file(gaussian_separable_name, i);
writeImage((gaussian_separable_name + "_" + to_string(i) + ".bmp").c_str(), var_image.gaussianG);
}
return 0;
}
| true |
6920fe6301cf4ba5e9ad4c357c54fd68cfd726f8 | C++ | ngrande/Banshee | /Bus/MessageBus.cpp | UTF-8 | 1,099 | 2.84375 | 3 | [
"MIT"
] | permissive | //
// Copyright (c) 2016 by Niclas Grande. All Rights Reserved.
//
#include "MessageBus.h"
#include <algorithm>
MessageBus::MessageBus(void) {
this->pStopped = false;
this->pMsgThread = std::thread(&MessageBus::processMsgQueue, this);
this->pMsgThread.detach();
}
void MessageBus::processMsgQueue() {
while (!pStopped) {
std::unique_lock<std::mutex> lck(cv_m);
cv.wait(lck);
while (!this->pMsgQueue.empty()) {
auto queuedMsg = this->pMsgQueue.front();
this->pMsgQueue.pop();
// process queuedItem here
auto msgCode = queuedMsg.getCode();
switch (msgCode) {
case Code::PLAY_SOUND:
// handle play sound message
std::cout << "PLAY_SOUND message received!" << std::endl;
break;
case Code::STOP_SOUND:
std::cout << "STOP_SOUND message receieved!" << std::endl;
break;
case Code::FLUSH_BUFFER:
std::cout << "FLUSH_BUFFER message received!" << std::endl;
break;
}
}
}
}
void MessageBus::sendMessage(Message &msg) {
this->pMsgQueue.push(msg);
this->cv.notify_all();
}
| true |
6bd93dbeb7b072ca083dc1cb2055084069bc1ac3 | C++ | Iigorsf/AED | /AED/4/4q19.cpp | UTF-8 | 428 | 2.9375 | 3 | [
"MIT"
] | permissive | #include <iostream>
using namespace std;
int main(int argc, char **argv)
{
string text;
cin>>text;
string palavra;
cin>>palavra;
int c=-1, tam, tam2;
tam = text.size();
tam2 = palavra.size();
for(int i = 0; i <=(tam-tam2);i++){
if(text[i]==palavra[0] and c==-1){
c = i;
for(int j =0; j < tam2; j++)
{
if(text[i+j] != palavra[j])
{
j = tam2;
c = -1;
}
}
}
}
cout<<c;
return 0;
}
| true |
48cf69b0c2a9b4c14e9c6718625cc129eeb929cb | C++ | KawaharaSyuichi/algorithms | /Weighted_graph/SingleSourceShortestPathII.cpp | UTF-8 | 3,249 | 3.328125 | 3 | [] | no_license | /*
単一始点最短経路
与えられた重み付き有向グラフG=(V,E)について、単一始点最短経路のコストを求めるプログラム
ダイクストラのアルゴリズム(優先度付きキュー)
グラフG=(V,E)の頂点全体の集合をV、始点をs、最短経路木に含まれている頂点の集合をSとします。
各計算ステップで、最短経路木の辺と頂点を選びSへ追加します。
各頂点iについて、S内の頂点のみを経由したsからiへの最短経路のコストをd[i]、最短経路木におけるiの親をp[i]とする。
1.初期状態で、Sを空にする
a. sに対してd[s]=0
b. s意外のVに属する全ての頂点iに対してd[i]=∞
c. d[i]をキーとして、Vの頂点をmin-ヒープHとして構築します。
2.以下の処理をS=Vとなるまで繰り返す
a. Hからd[u]が最小である頂点uを取り出します。
b. uをSに追加すると同時に、uに隣接しかつV-Sに属する全ての頂点vに対する値を以下のように更新
if d[u]+w(u,v)<d[v]
d[v]=d[u]+w(u,v)
p[v]=u
vを起点にヒープHを更新
隣接リストと優先度付きキューを用いた実装は、|V|の数だけキューから頂点が取り出され、|E|の数だけキューに挿入されるので、計算量はO((|V|+|E|)log|V|)
入力例:
5
0 3 2 3 3 1 1 2
1 2 0 2 3 4
2 3 0 3 3 1 4 1
3 4 2 1 0 1 1 4 4 3
4 2 2 1 3 3
出力例:
0 0
1 2
2 2
3 1
4 3
*/
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;
static const int MAX = 10000;
static const int INFTY = (1 << 20);
static const int WHITE = 0;
static const int GRAY = 1;
static const int BLACK = 2;
int n;
vector<pair<int, int>> adj[MAX]; //重み付き有向グラフの隣接リスト表現
void dijkstra()
{
priority_queue<pair<int, int>> PQ;
int color[MAX];
int d[MAX];
for (int i = 0; i < n; i++)
{
d[i] = INFTY;
color[i] = WHITE;
}
d[0] = 0;
PQ.push(make_pair(0, 0));
color[0] = GRAY;
while (!PQ.empty())
{
pair<int, int> f = PQ.top();
PQ.pop();
int u = f.second;
color[u] = BLACK;
//最小値を取り出し、それが最短でなければ無視
if (d[u] < f.first * (-1))
{
continue;
}
for (int j = 0; j < adj[u].size(); j++)
{
int v = adj[u][j].first;
if (color[v] == BLACK)
{
continue;
}
if (d[v] > d[u] + adj[u][j].second)
{
d[v] = d[u] + adj[u][j].second;
//priority_queueはデフォルトで大きい値を優先するため-1を掛ける
PQ.push(make_pair(d[v] * (-1), v));
color[v] = GRAY;
}
}
}
for (int i = 0; i < n; i++)
{
cout << i << " " << (d[i] == INFTY ? -1 : d[i]) << endl;
}
}
int main()
{
int k, u, v, c;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> u >> k;
for (int j = 0; j < k; j++)
{
cin >> v >> c;
adj[u].push_back(make_pair(v, c));
}
}
dijkstra();
return 0;
} | true |
a2f5d3636aab8701c68e63df23e72770b862f1b1 | C++ | remcous/Programming-Principles-and-Practice | /Ch17/exercise9.cpp | UTF-8 | 1,205 | 3.46875 | 3 | [] | no_license | /*
exercise9.cpp
Revision History:
*/
#include "../std_lib_facilities.h"
/****************************************
* MAIN FUNCTION
****************************************/
int main(){
try{
// Test the direction of stack growth
int num1 = 0;
int num2 = 0;
int num3 = 0;
cout << "Addresses for stack allocation:\n" << &num1
<< '\n' << &num2 << '\n' << &num3 << "\n\n";
if(&num2 > &num1) cout << "Stack grows upwards\n\n";
else cout << "Stack grows downwards\n\n";
// Test direction of heap growth
int *ip1 = new int{0};
int *ip2 = new int{0};
int *ip3 = new int{0};
cout << "Addresses for heap allocation:\n" << ip1
<< '\n' << ip2 << '\n' << ip3 << "\n\n";
if(ip2 > ip1) cout << "Heap grows upwards\n";
else cout << "Heap grows downwards\n";
delete ip1;
delete ip2;
delete ip3;
}
catch(exception& e){
cerr << e.what() << '\n';
keep_window_open("~~");
return 1;
}
catch(...){
cerr << "exception\n";
keep_window_open("~~");
return 2;
}
return 0;
}
| true |
cbad1829f771212052dfa7e1242d34d144ca024e | C++ | LindongLi/Leetcode | /191 Number of 1 Bits/191 LL.cpp | UTF-8 | 658 | 4.0625 | 4 | [] | no_license | #include <iostream>
using namespace std;
/*
https://leetcode.com/problems/number-of-1-bits/
Write a function that takes an unsigned integer and returns the number of ’1' bits it has
(also known as the Hamming weight).
For example, the 32-bit integer ’11' has binary representation 00000000000000000000000000001011,
so the function should return 3.
*/
class Solution
{
public:
int hammingWeight(uint32_t n)
{
int result = 0;
while (n != 0)
{
++result;
n = n & (n - 1);
}
return result;
}
};
/*
idea: bit manipulate
complexity: Time O(N)
*/
int main(void)
{
Solution engine;
cout << engine.hammingWeight(11) << '\n';
return 0;
} | true |
958ec984dd5877e508aeafc74dee48384e418cc4 | C++ | ator/chapman | /ChapmanWindows/color.cpp | UTF-8 | 2,418 | 3.4375 | 3 | [] | no_license | #include <cmath>
#include "color.h"
const color color::WHITE(1.0, 1.0, 1.0);
const color color::BLACK(0, 0, 0);
const color color::GRAY(0.5, 0.5, 0.5);
const color color::RED(1.0, 0, 0);
const color color::GREEN(0, 1.0, 0);
const color color::BLUE(0, 0, 1.0);
const color color::YELLOW(1.0, 1.0, 0);
const color color::MAGENTA(0, 1.0, 1.0);
color::color(const double red, const double green, const double blue) :
_red(red),
_green(green),
_blue(blue)
{}
auto color::red() const -> double
{
return _red;
}
auto color::green() const -> double
{
return _green;
}
auto color::blue() const -> double
{
return _blue;
}
auto color::operator+=(const ::color& other) -> ::color&
{
_red += other._red;
_green += other._green;
_blue += other._blue;
return *this;
}
auto color::operator+(const ::color& other) const -> ::color
{
const auto red = _red + other._red;
const auto green = _green + other._green;
const auto blue = _blue + other._blue;
return { red, green, blue };
}
auto color::operator*(const ::color& other) const -> ::color
{
const auto red = _red * other._red;
const auto green = _green * other._green;
const auto blue = _blue * other._blue;
return { red, green, blue };
}
auto color::operator*(const ::color&& other) const -> ::color
{
const auto red = _red * other._red;
const auto green = _green * other._green;
const auto blue = _blue * other._blue;
return { red, green, blue };
}
auto color::operator*(const double factor) const -> color
{
const auto red = _red * factor;
const auto green = _green * factor;
const auto blue = _blue * factor;
return { red, green, blue };
}
auto color::operator/(double factor) const -> color
{
const auto red = _red / factor;
const auto green = _green / factor;
const auto blue = _blue / factor;
return { red, green, blue };
}
auto color::length2() const -> double
{
return _red * _red + _green * _green + _blue * _blue;
}
auto color::length() const -> double
{
return std::sqrt(length2());
}
auto color::scale(const double factor) const -> color
{
const auto red = _red / factor;
const auto green = _green / factor;
const auto blue = _blue / factor;
return { red, green, blue };
}
auto color::clamp() const -> color
{
const auto red = std::fmax(std::fmin(1.0, _red), 0.0);
const auto green = std::fmax(std::fmin(1.0, _green), 0.0);
const auto blue = std::fmax(std::fmin(1.0, _blue), 0.0);
return { red, green, blue };
}
| true |