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 |
|---|---|---|---|---|---|---|---|---|---|---|---|
401fc43375c1a47b629bef5884ea4698f50e459c | C++ | CSLP/Cpp-Primer-5th-Exercises | /ch10/10.15.cpp | UTF-8 | 295 | 3.3125 | 3 | [
"Apache-2.0"
] | permissive | #include <iostream>
int main() {
int x, y;
std::cin >> x >> y;
auto sum = [x](int i) { return x + i; };
// The lamda must be defined after we read x, otherwise it will capture the
// undefined value of x.
std::cout << x << " + " << y << " = " << sum(y) << std::endl;
return 0;
}
| true |
8553580dbbd6a71ff9d06533137f2a2ecbfbcdd8 | C++ | trooperli/my-leetcode | /problems/Insert_Delete_GetRandom.cpp | UTF-8 | 1,729 | 4 | 4 | [] | no_license | /**
* This problem is actually test what data structure to use to achieve
* O(1) complexity. Here, we used a unordered_map<data, idx> and a
* vector. The unordered_map actually records the element and its
* index, which makes delete O(1) possible, otherwise we need to loop
* throught the array. In remove method, we need to be careful about
* where to put the erase method. It needs to be implemented after all
* other operations. In insert method, we use emplace_back instead of
* push_back because the former has better efficiency.
*/
class RandomizedSet {
public:
/** Initialize your data structure here. */
RandomizedSet() {
}
/** Inserts a value to the set. Returns true if the set did not already contain the specified element. */
bool insert(int val) {
if (map.count(val)) {return false;}
arr.push_back(val);
map[val] = arr.size()-1;
return true;
}
/** Removes a value from the set. Returns true if the set contained the specified element. */
bool remove(int val) {
if (!map.count(val)) {return false;}
auto idx = map[val];
auto last_element = arr.back();
arr[idx] = last_element;
arr.pop_back();
map.erase(val);
map[last_element] = idx;
return true;
}
/** Get a random element from the set. */
int getRandom() {
return arr[rand() % arr.size()];
}
private:
vector<int> arr;
unordered_map<int, int> map;
};
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet* obj = new RandomizedSet();
* bool param_1 = obj->insert(val);
* bool param_2 = obj->remove(val);
* int param_3 = obj->getRandom();
*/
| true |
97b892c9f5dea1b3df5e080cc60436367e5be603 | C++ | drlongle/leetcode | /algorithms/problem_1297/solution.cpp | UTF-8 | 3,436 | 3.1875 | 3 | [] | no_license | /*
1297. Maximum Number of Occurrences of a Substring
Medium
Given a string s, return the maximum number of ocurrences of any substring under the following rules:
* The number of unique characters in the substring must be less than or equal to maxLetters.
* The substring size must be between minSize and maxSize inclusive.
Example 1:
Input: s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4
Output: 2
Explanation: Substring "aab" has 2 ocurrences in the original string.
It satisfies the conditions, 2 unique letters and size 3 (between minSize and maxSize).
Example 2:
Input: s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3
Output: 2
Explanation: Substring "aaa" occur 2 times in the string. It can overlap.
Example 3:
Input: s = "aabcabcab", maxLetters = 2, minSize = 2, maxSize = 3
Output: 3
Example 4:
Input: s = "abcde", maxLetters = 2, minSize = 3, maxSize = 3
Output: 0
Constraints:
1 <= s.length <= 10^5
1 <= maxLetters <= 26
1 <= minSize <= maxSize <= min(26, s.length)
s only contains lowercase English letters.
*/
#include <algorithm>
#include <atomic>
#include <bitset>
#include <cassert>
#include <cmath>
#include <condition_variable>
#include <functional>
#include <future>
#include <iostream>
#include <iterator>
#include <list>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <thread>
#include <unordered_map>
#include <unordered_set>
#include <vector>
using namespace std;
#define ll long long
#define ull unsigned long long
class Solution {
public:
int maxFreq(string s, int maxLetters, int minSize, int maxSize) {
int sz = s.size();
unordered_map<string, int> cnt;
unordered_map<char, int> chars;
int head = 0;
for (; head < minSize-1; ++head)
++chars[s[head]];
for (int tail = 0; tail + minSize - 1 < sz; ++tail) {
++chars[s[tail+minSize-1]];
if (static_cast<int>(chars.size()) <= maxLetters)
++cnt[s.substr(tail, minSize)];
unordered_map<char, int> new_chars(chars);
for (head = tail + minSize; head - tail + 1 <= maxSize && head < sz &&
static_cast<int>(new_chars.size()) <= maxLetters; ++head) {
++new_chars[s[head]];
if (static_cast<int>(new_chars.size()) <= maxLetters)
++cnt[s.substr(tail, head-tail+1)];
}
auto ch = s[tail];
if (--chars[ch] == 0)
chars.erase(ch);
}
if (cnt.empty())
return 0;
auto it = max_element(begin(cnt), end(cnt), [](auto& p1, auto& p2) {return p1.second < p2.second;});
return it->second;
}
};
int main() {
Solution sol;
string s;
int maxLetters, minSize, maxSize;
// Output: 2
s = "aababcaab", maxLetters = 2, minSize = 3, maxSize = 4;
// Output: 2
s = "aaaa", maxLetters = 1, minSize = 3, maxSize = 3;
// Output: 3
s = "aabcabcab", maxLetters = 2, minSize = 2, maxSize = 3;
// Output: 0
s = "abcde", maxLetters = 2, minSize = 3, maxSize = 3;
// Output: 1
s = "abcde", maxLetters = 2, minSize = 2, maxSize = 4;
// Output: 1
s = "abcde", maxLetters = 3, minSize = 2, maxSize = 4;
cout << "Result: " << sol.maxFreq(s, maxLetters, minSize, maxSize) << endl;
return 0;
}
| true |
82e3d192da404cd110487684774c8d2a89b5f4e8 | C++ | xinfushe/gpuflow-opencl | /src/Image.h | UTF-8 | 2,832 | 3.125 | 3 | [] | no_license | #pragma once
#include <string>
// Linux declaration
#ifndef _WIN32
#include <cstring>
#endif
#define IND(X, Y) (((Y) + m_by) * m_pitch + ((X) + m_bx))
class Image
{
private:
int m_width; // Image width
int m_height; // Image height
int m_actual_width; // Actual image width
int m_actual_height;// Actual image height
int m_pitch; // We expand image width if it isn't a multiple of 32 to provide coalesced data accesses
int m_bx; // Boudary size X
int m_by; // Boudary size Y
float* m_data; // Image data
public:
Image();
Image(int width, int height);
Image(int width, int height, int bx, int by);
~Image();
/* returns reference to pixel in data array w - write / r - read */
inline float& pixel_w(int x, int y) { return m_data[IND(x, y)]; };
inline float& pixel_r(int x, int y) const { return m_data[IND(x, y)]; };
/* returns pixel value from (x, y) position if x and y are valid, 0.f otherwise */
inline float pixel_v(int x, int y) const { return (x < 0 || x >= m_actual_width || y < 0 || y >= m_actual_height) ? 0.f : m_data[IND(x, y)]; };
inline int width() const { return m_width; };
inline int height() const { return m_height; };
inline int pitch() const { return m_pitch; };
inline int actual_width() const { return m_actual_width; };
inline int actual_height() const { return m_actual_height; };
inline float* data_ptr() { return m_data; };
void swap_data(Image& swap) { std::swap(this->m_data, swap.m_data); };
void reinit(int width, int height, int actual_width, int actual_height, int bx, int by);
void setActualWidth(int width) { m_actual_width = width; };
void setActualHeight(int height) { m_actual_height = height; };
void setActualSize(int width, int height) { m_actual_width = width; m_actual_height = height; };
/* fills boudaries with mirrored image */
void fillBoudaries();
void zeroData() { if (m_data) std::memset(m_data, 0, (m_height + 2 * m_by) * m_pitch * sizeof(float)); };
bool readImagePGM(std::string filename);
bool writeImagePGM(std::string filename);
bool writeImagePGMwithBoundaries(std::string filename);
static bool readMiddlFlowFile(std::string filename, Image& u, Image& v);
static void resample(const Image& src, Image& dst, float scale);
static void resampleWithoutReallocating(const Image& src, Image& dst, int dst_width, int dst_height);
static void resampleAreaBasedWithoutReallocating(const Image& src, Image& dst, int dst_width, int dst_height);
static void backwardRegistration(const Image& src1, const Image& src2, Image& dst2, const Image& u, const Image& v, float hx, float hy);
static void saveOpticalFlowRGB(const Image& u, const Image& v, float flow_scale, std::string filename);
Image& operator+= (const Image& image);
Image& operator= (const Image& image);
private:
void allocateDataMemoryWithPadding();
};
| true |
7e858438e077f05e7682c2afda3a9a2c16e46234 | C++ | yvznvr/ServerClient-Tutorial | /UdpClient/udpclient.h | UTF-8 | 701 | 2.640625 | 3 | [] | no_license | #ifndef UDPCLIENT_H
#define UDPCLIENT_H
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
class UdpClient
{
public:
UdpClient();
bool createSocket();
// isSocketCreated() returns true if socket created
// otherwise returns false
bool isSocketCreated();
uint8_t* sendData(uint8_t *data);
int getPort() const;
void setPort(int value);
private:
int socketFd;
bool socketCreated = false;
// 320 bytes max data payload of UDP Protocol
uint8_t buffer[320];
struct sockaddr_in serverAddr;
int port;
};
#endif // UDPCLIENT_H
| true |
cf74874a66f4a549e7c8a94475e9e8aa1357c98e | C++ | mahdi2561/farm-project | /chickenmarket.cpp | UTF-8 | 7,475 | 2.59375 | 3 | [] | no_license | #include "chickenmarket.h"
#include "ui_chickenmarket.h"
ChickenMarket::ChickenMarket(User* _user, Aviculture* _aviculture, QWidget *parent) :
QMainWindow(parent),
ui(new Ui::ChickenMarket)
{
ui->setupUi(this);
setFixedSize(1000,570);
setWindowTitle("Chicken market");
pix = new QPixmap(":/new/prefix1/img/logo.jpg");
icon = new QIcon(*pix);
this->setWindowIcon(*icon);
user = _user;
aviculture = _aviculture;
refresh_timer = new QTimer(this);
refresh_timer->start(50);
connect(refresh_timer, SIGNAL(timeout()), this, SLOT(Set_values()));
}
ChickenMarket::~ChickenMarket()
{
delete ui;
}
void ChickenMarket::on_pushButton_clicked()
{
if(aviculture->Get_building_status() != 2){
//messagebox --> "to buy chickens you must build aviculture first"
QMessageBox::critical(this,"AVICULTURE NOT BUILT","to buy or sell chickens you must build aviculture first");
}
else{
if((ui->spinBox->text().toInt() == 0)&&(ui->spinBox_2->text().toInt() == 0)){
//qmessagebox --> "number of buying and selling items is 0"
QMessageBox::critical(this,"0 VALUE","number of buying and selling items is 0");
return;
}
if((ui->spinBox->text().toInt() != 0)&&(ui->spinBox_2->text().toInt() != 0)){
// qmessagebox --> "you cannot buy and sell at the same time"
QMessageBox::critical(this,"BUY AND SELL","you cannot buy and sell at the same time");
return;
}
if(ui->spinBox->text().toInt() != 0){ // //
if(aviculture->Get_used_storage() < ui->spinBox->text().toInt()){ //
//qmessagebox --> "not enough chickens to sell" //
QMessageBox::critical(this,"NOT ENOUGH CHICKENS","not enough chickens to sell"); //
} //
else{ // sell
aviculture->Delete(1, ui->spinBox->text().toInt()); //
user->Set_coin(user->Get_coin() + ui->spinBox->text().toInt()*15); //
user->Set_experience(user->Get_experience() + ui->spinBox_2->text().toInt()*6); //
//
if(ui->spinBox->text().toInt() == 1){// //
//qmessagebox --> "chicken is sold successfully" //
QMessageBox::information(this,"SUCCESSFUL TRADE", "1 chicken is sold"); //
} //
else{ //
//qmessagebox --> "chicken is sold successfully" //
QMessageBox::information(this,"SUCCESSFUL TRADE", //
QString::number(ui->spinBox->text().toInt()) + " chickens are sold"); //
} //
} // //
} //
if(ui->spinBox_2->text().toInt() != 0){ //
if(user->Get_coin() < ui->spinBox_2->text().toInt()*20){ //
//qmessagebox --> "not enough coins to buy this number of chickens" //
QMessageBox::critical(this,"NOT ENOUGH COINS","not enough coins to buy this number of chickens"); //
} //
else{ //
if(aviculture->Get_total_storage() - aviculture->Get_used_storage() < ui->spinBox_2->text().toInt()){ //
//qmessagebox --> "not enough space in aviculture" //
QMessageBox::critical(this,"NOT ENOUGH SPACE","not enough space in aviculture"); // buy
} //
else{ //
aviculture->Add(1, ui->spinBox_2->text().toInt()); //
user->Set_coin(user->Get_coin() - ui->spinBox_2->text().toInt()*20); //
user->Set_experience(user->Get_experience() + ui->spinBox_2->text().toInt()*2); //
//
if(ui->spinBox_2->text().toInt() == 1){// //
//qmessagebox --> "chicken is bought successfully" //
QMessageBox::information(this,"SUCCESSFUL TRADE", "1 chicken is bought"); //
} //
else{ //
//qmessagebox --> "chicken is bought successfully" //
QMessageBox::information(this,"SUCCESSFUL TRADE", //
QString::number(ui->spinBox_2->text().toInt()) + " chickens are bought"); //
} //
} //
} //
} //
}
}
void ChickenMarket::Set_values(){
ui->label_2->setText(QString::number(aviculture->Get_used_storage()));
ui->label->setText(QString::number(aviculture->Get_total_storage() - aviculture->Get_used_storage()));
}
| true |
eeeb7e61b87cb0f37853f12a48e08830ae7c9784 | C++ | dinopants174/SoftSys2015 | /Sprint5/trinket_master/trinket_master.ino | UTF-8 | 2,824 | 2.96875 | 3 | [] | no_license | #include <Wire.h>
#define I2C_SLAVE_ADDR 0xE // i2c slave address (38)
int i;
int nodeAddress;
byte arr1[4] = {};
byte arr2[4] = {};
byte arr3[4] = {};
byte arr4[4] = {};
byte res[4] = {};
//put matrices here
float A[2][2];
float B[2][2];
byte byteReceived;
bool finished_transmit = false;
void setup() {
Serial.begin(9600);
setupMatrix(1, 2, 3, 4, A);
setupMatrix(5, 6, 7, 8, B);
MatrixArrayTask(A, B);
Wire.begin();
}
void loop() {
if (!finished_transmit){
Serial.println("*************************");
for (i=0; i<4; i++){
Serial.println("Transmitting now slave 1");
Wire.beginTransmission(0xB); // transmit to device #9
Serial.println(arr1[i]);
Wire.write(arr1[i]);
Wire.endTransmission();
}
for (i=0; i<4; i++){
Serial.println("Transmitting now slave 2");
Wire.beginTransmission(0xB + 0x1); // transmit to device #9
Serial.println(arr2[i]);
Wire.write(arr2[i]);
Wire.endTransmission();
}
for (i=0; i<4; i++){
Serial.println("Transmitting now slave 3");
Wire.beginTransmission(0xB + 0x2); // transmit to device #9
Serial.println(arr3[i]);
Wire.write(arr3[i]);
Wire.endTransmission();
}
for (i=0; i<4; i++){
Serial.println("Transmitting now slave 4");
Wire.beginTransmission(0xB + 0x3); // transmit to device #9
Serial.println(arr4[i]);
Wire.write(arr4[i]);
Wire.endTransmission();
}
Serial.println("I am finished transmitting");
Serial.println("*************************");
finished_transmit = true;
delay(1000);
}
if (finished_transmit){
for (int nodeAddress = 0xB; nodeAddress <= 0xE; nodeAddress++) { // we are starting from Node address 2
Wire.requestFrom(nodeAddress, 1); // request data from node#
if(Wire.available() == 1) { // if data size is avaliable from nodes
byteReceived = Wire.read();
Serial.print("Address ");
Serial.println(nodeAddress);
res[nodeAddress - 0xB] = byteReceived;
Serial.println(res[nodeAddress - 0xB]);
Serial.println("*************************");
}
}
delay(1000);
}
}
void setupMatrix(int a, int b, int c, int d, float M[2][2]) {
M[0][0] = a;
M[0][1] = b;
M[1][0] = c;
M[1][1] = d;
}
//function here to populate byte arrays
void MatrixArrayTask(float A[2][2], float B[2][2]) {
byte a = A[0][0];
byte b = A[0][1];
byte c = A[1][0];
byte d = A[1][1];
byte e = B[0][0];
byte f = B[0][1];
byte g = B[1][0];
byte h = B[1][1];
arr1[0] = a;
arr1[1] = e;
arr1[2] = b;
arr1[3] = g;
arr2[0] = a;
arr2[1] = f;
arr2[2] = b;
arr2[3] = h;
arr3[0] = c;
arr3[1] = e;
arr3[2] = d;
arr3[3] = g;
arr4[0] = c;
arr4[1] = f;
arr4[2] = d;
arr4[3] = h;
}
| true |
889f8cc755c927b07e9df12e22f51cca71d2ad14 | C++ | shunak/cpp-sandbox | /practical/virtual/chicken.h | UTF-8 | 318 | 2.734375 | 3 | [] | no_license | #ifndef _CHICKEN_H_
#define _CHICKEN_H_
#include "bird.h"
// define chicken class
class CChicken : public CBird{
public:
void sing(){
cout << "こけっこ" << endl;
}
void fly(){
cout << "CHICKENS can`t fly" << endl;
}
};
#endif | true |
2e3e1d011a162c92954aced753f6ac98fbb16d2b | C++ | unt4m1nh/Tic_Tac_Toee | /Player1.cpp | UTF-8 | 4,674 | 2.859375 | 3 | [] | no_license | #include"Player1.h"
#include<iostream>
Player1::Player1(SDL_Renderer* &gRenderer)
{
}
Player1::~Player1()
{
}
void Player1::input(SDL_Event& e)
{
bool inside_box[3][3] = {{true,true,true},
{true,true,true},
{true,true,true}};
while( SDL_PollEvent( &e ) != 0 )
{
if( e.type == SDL_MOUSEMOTION || e.type == SDL_MOUSEBUTTONDOWN || e.type == SDL_MOUSEBUTTONUP )
{
//Get mouse position
int x, y;
SDL_GetMouseState( &x, &y );
if(x < 0 || x > CHESS_BOX_WIDTH || y < 0 || y > CHESS_BOX_HEIGHT)
{
inside_box[0][0] = false;
}
if(inside_box[0][0] && this->interface->game_board[0][0] == 0)
{
if (e.type == SDL_MOUSEBUTTONDOWN )
{
this->interface->game_board[0][0] = 1;
}
}
if(x < 0 || x > CHESS_BOX_WIDTH || y < CHESS_BOX_HEIGHT || y > CHESS_BOX_HEIGHT * 2)
{
inside_box[0][1] = false;
}
if(inside_box[0][1] && this->interface->game_board[0][1] == 0)
{
if (e.type == SDL_MOUSEBUTTONDOWN )
{
this->interface->game_board[0][1] = 1;
}
}
if(x < 0 || x > CHESS_BOX_WIDTH || y < CHESS_BOX_HEIGHT * 2 || y > CHESS_BOX_HEIGHT * 3)
{
inside_box[0][2] = false;
}
if(inside_box[0][2] && this->interface->game_board[0][2] == 0)
{
if (e.type == SDL_MOUSEBUTTONDOWN )
{
this->interface->game_board[0][2] = 1;
}
}
if(x < CHESS_BOX_WIDTH || x > CHESS_BOX_WIDTH * 2 || y < 0 || y > CHESS_BOX_HEIGHT)
{
inside_box[1][0] = false;
}
if(inside_box[1][0] && this->interface->game_board[1][0] == 0)
{
if (e.type == SDL_MOUSEBUTTONDOWN )
{
this->interface->game_board[1][0] = 1;
}
}
if(x < CHESS_BOX_WIDTH || x > CHESS_BOX_WIDTH * 2 || y < CHESS_BOX_HEIGHT || y > CHESS_BOX_HEIGHT * 2)
{
inside_box[1][1] = false;
}
if(inside_box[1][1] && this->interface->game_board[1][1] == 0)
{
if (e.type == SDL_MOUSEBUTTONDOWN )
{
this->interface->game_board[1][1] = 1;
}
}
if(x < CHESS_BOX_WIDTH || x > CHESS_BOX_WIDTH * 2 || y < CHESS_BOX_HEIGHT * 2 || y > CHESS_BOX_HEIGHT * 3)
{
inside_box[1][2] = false;
}
if(inside_box[1][2] && this->interface->game_board[1][2] == 0)
{
if (e.type == SDL_MOUSEBUTTONDOWN )
{
this->interface->game_board[1][2] = 1;
}
}
if(x < CHESS_BOX_WIDTH * 2 || x > CHESS_BOX_WIDTH * 3 || y < 0 || y > CHESS_BOX_HEIGHT)
{
inside_box[2][0] = false;
}
if(inside_box[2][0] && this->interface->game_board[2][0] == 0)
{
if (e.type == SDL_MOUSEBUTTONDOWN )
{
this->interface->game_board[2][0] = 1;
}
}
if(x < CHESS_BOX_WIDTH * 2 || x > CHESS_BOX_WIDTH * 3 || y < CHESS_BOX_HEIGHT || y > CHESS_BOX_HEIGHT * 2)
{
inside_box[2][1] = false;
}
if(inside_box[2][1] && this->interface->game_board[2][1] == 0)
{
if (e.type == SDL_MOUSEBUTTONDOWN )
{
this->interface->game_board[2][1] = 1;
}
}
if(x < CHESS_BOX_WIDTH * 2 || x > CHESS_BOX_WIDTH * 3 || y < CHESS_BOX_HEIGHT * 2 || y > CHESS_BOX_HEIGHT * 3)
{
inside_box[2][2] = false;
}
if(inside_box[2][2] && this->interface->game_board[2][2] == 0)
{
if (e.type == SDL_MOUSEBUTTONDOWN )
{
this->interface->game_board[2][2] = 1;
}
}
}
}
}
| true |
e357859ffc29581f52d58222d3f16f560c4d682f | C++ | BinyuHuang-nju/leetcode-implement | /all684/all684/main.cpp | UTF-8 | 1,243 | 3.375 | 3 | [] | no_license | #include <iostream>
using namespace std;
#include <vector>
class UFSet {
private:
int* parent;
int size;
public:
UFSet(int num) {
size = num + 1;
parent = new int[num + 1];
for (int i = 0; i <= num; i++)
parent[i] = -1;
}
int find(int x) {
while (parent[x] >= 0)
x = parent[x];
return x;
}
void unions(int x, int y) {
int temp = parent[x] + parent[y];
if (parent[x] > parent[y]) {
parent[x] = y;
parent[y] = temp;
}
else {
parent[y] = x;
parent[x] = temp;
}
}
};
class Solution {
public:
vector<int> findRedundantConnection(vector<vector<int>>& edges) {
UFSet ufs(edges.size());
int v = 0, w = 0;
for (vector<int> edge : edges) {
v = edge[0];
w = edge[1];
int m = ufs.find(v), n = ufs.find(w);
if (m == n)
return edge;
ufs.unions(m, n);
}
return { v,w };
}
};
int main() {
Solution sol;
vector<vector<int>> edges = { {1,2},{2,3},{3,4},{1,4},{1,5} };
vector<int> result = sol.findRedundantConnection(edges);
return 0;
} | true |
98b08df6fe98b051322ba034723a4fa4a0af820a | C++ | Snowapril/GoonRenderer | /Extensions/GoonMath/(deprecated)/Includes/gm/details/type_mat4x4.inl | UTF-8 | 5,347 | 3.125 | 3 | [
"MIT"
] | permissive | #include "../matrix.h"
namespace gm
{
template <typename Type>
mat<4, 4, Type>::mat() noexcept
: value { row_type(), row_type(), row_type(), row_type() }
{
}
template <typename Type>
mat<4, 4, Type>::mat(Type _val) noexcept
: value { row_type(_val), row_type(_val), row_type(_val), row_type(_val) }
{
}
template <typename Type>
mat<4, 4, Type>::mat(Type _x0, Type _y0, Type _z0, Type _w0,
Type _x1, Type _y1, Type _z1, Type _w1,
Type _x2, Type _y2, Type _z2, Type _w2,
Type _x3, Type _y3, Type _z3, Type _w3) noexcept
: value { row_type (_x0, _y0, _z0, _w0), row_type (_x1, _y1, _z1, _w1),
row_type (_x2, _y2, _z2, _w2), row_type (_x3, _y3, _z3, _w3) }
{
}
template <typename Type>
mat<4, 4, Type> const mat<4, 4, Type>::operator+(mat<4, 4, Type> const& _m) const noexcept
{
mat<4, 4, Type> result;
for (int i = 0; i < 4; ++i)
result[i] = this->value[i] + _m.value[i];
return result;
}
template <typename Type>
mat<4, 4, Type> const mat<4, 4, Type>::operator-(mat<4, 4, Type> const& _m) const noexcept
{
mat<4, 4, Type> result;
for (int i = 0; i < 4; ++i)
result[i] = this->value[i] - _m.value[i];
return result;
}
template <typename Type>
template <int N>
mat<4, N, Type> const mat<4, 4, Type>::operator*(mat<4, N, Type> const& _m) const noexcept
{
return mat<4, N, Type>(3.0f);
}
template <typename Type>
mat<4, 4, Type> const mat<4, 4, Type>::operator/(mat<4, 4, Type> const& _m) const noexcept
{
mat<4, 4, Type> result;
for (int i = 0; i < 4; ++i)
result[i] = this->value[i] / _m.value[i];
return result;
}
template <typename Type>
void mat<4, 4, Type>::operator+=(mat<4, 4, Type> const& _m) noexcept
{
for (int i = 0; i < 4; ++i)
this->value += _m.value[i];
}
template <typename Type>
void mat<4, 4, Type>::operator-=(mat<4, 4, Type> const& _m) noexcept
{
for (int i = 0; i < 4; ++i)
this->value -= _m.value[i];
}
template <typename Type>
void mat<4, 4, Type>::operator*=(mat<4, 4, Type> const& _m) noexcept
{
for (int i = 0; i < 4; ++i)
this->value *= _m.value[i];
}
template <typename Type>
void mat<4, 4, Type>::operator/=(mat<4, 4, Type> const& _m) noexcept
{
for (int i = 0; i < 4; ++i)
this->value /= _m.value[i];
}
template <typename Type>
mat<4, 4, Type> const mat<4, 4, Type>::operator+(Type _val) const noexcept
{
mat<4, 4, Type> result;
for (int i = 0; i < 4; ++i)
result[i] = this->value[i] + _val;
return result;
}
template <typename Type>
mat<4, 4, Type> const mat<4, 4, Type>::operator-(Type _val) const noexcept
{
mat<4, 4, Type> result;
for (int i = 0; i < 4; ++i)
result[i] = this->value[i] - _val;
return result;
}
template <typename Type>
mat<4, 4, Type> const mat<4, 4, Type>::operator*(Type _val) const noexcept
{
mat<4, 4, Type> result;
for (int i = 0; i < 4; ++i)
result[i] = this->value[i] * _val;
return result;
}
template <typename Type>
mat<4, 4, Type> const mat<4, 4, Type>::operator/(Type _val) const noexcept
{
mat<4, 4, Type> result;
for (int i = 0; i < 4; ++i)
result[i] = this->value[i] / _val;
return result;
}
template <typename Type>
void mat<4, 4, Type>::operator+=(Type _val) noexcept
{
for (int i = 0; i < 4; ++i)
this->value[i] += _val;
}
template <typename Type>
void mat<4, 4, Type>::operator-=(Type _val) noexcept
{
for (int i = 0; i < 4; ++i)
this->value[i] -= _val;
}
template <typename Type>
void mat<4, 4, Type>::operator*=(Type _val) noexcept
{
for (int i = 0; i < 4; ++i)
this->value[i] *= _val;
}
template <typename Type>
void mat<4, 4, Type>::operator/=(Type _val) noexcept
{
for (int i = 0; i < 4; ++i)
this->value[i] /= _val;
}
template <typename Type>
mat<4, 4, Type> const mat<4, 4, Type>::operator-() const noexcept
{
mat<4, 4, Type> result;
for (int i = 0; i < 4; ++i)
result.value[i] = -this->value[i];
return result;
}
template <typename Type>
typename row_type& mat<4, 4, Type>::operator[](int _index) noexcept
{
return static_cast<row_type&>(this->value[_index]);
}
template <typename Type>
typename row_type const& mat<4, 4, Type>::operator[](int _index) const noexcept
{
return static_cast<row_type const&>(this->value[_index]);
}
template <typename Type>
template <typename _OtherType>
void mat<4, 4, Type>::operator=(mat<4, 4, _OtherType> const& _other) noexcept
{
for (int i = 0; i < 4; ++i)
this->value[i] = _other.value[i];
}
}; | true |
7a7a69fd222dc9f5b8336f401fd3f881fbcdbfb2 | C++ | afperezm/background-location-recognition | /Common/StringUtils.cpp | UTF-8 | 1,352 | 3.125 | 3 | [] | no_license | #include "Common/StringUtils.h"
#include <sstream>
#include <string>
#include <vector>
#include "Common/Constants.h"
using std::string;
using std::vector;
vector<string> StringUtils::split(const string &s, char delim) {
vector<string> elems;
split(s, delim, elems);
return elems;
}
vector<string> &StringUtils::split(const string &s, char delim,
vector<string> &elems) {
std::stringstream ss(s);
string item;
while (std::getline(ss, item, delim)) {
elems.push_back(item);
}
return elems;
}
string StringUtils::parseLandmarkName(vector<string>::const_iterator fileName) {
string landmarkName("");
vector<string> fileNameSplitted = StringUtils::split((*fileName), '_');
landmarkName = string(fileNameSplitted[0]);
for (int var = 1; var < (int) fileNameSplitted.size() - 2; ++var) {
landmarkName = landmarkName + "_" + fileNameSplitted[var];
}
return landmarkName;
}
/**
* Transforms a key filename to an image filename
*
* @param keyFilename String holding the path to a keyfile since the data set root folder.
* @return Parsed image name
*/
string StringUtils::parseImgFilename(const string keyFilename, string prefix) {
string imgFilename = StringUtils::split(keyFilename.c_str(), '/').back();
imgFilename.resize(imgFilename.size() - 4);
return imgFilename + (!prefix.empty() ? prefix : "") + IMAGE_FILE_EXTENSION;
}
| true |
ea87c6a51f746bc5b679cb469f45f13d3cfd8496 | C++ | wangyongliang/nova | /poj/2583/POJ_2583_2246418_AC_0MS_24K.cpp | UTF-8 | 209 | 2.625 | 3 | [] | no_license | #include<stdio.h>
int main()
{
int a,b,c,x1,x2;
while(scanf("%d %d %d",&c,&x1,&x2)!=EOF)
{
a=(x2-2*x1+c)/2;
b=x1-c-a;
printf("%d %d %d\n",a*9+3*b+c,a*16+4*b+c,a*25+5*b+c);
}
return 0;
}
| true |
225d7266472757ab4efd9d16b593567b901cc526 | C++ | thirtiseven/CPPex | /2-3.cpp | UTF-8 | 317 | 2.953125 | 3 | [] | no_license | #include <iostream>
#include <iomanip>
using namespace std;
int main(int argc, char *argv[]) {
float temperature = 0;
cout << "华氏温度?";
cin >> temperature;
cout << "华氏 " << temperature << " 度 = 摄氏 " << fixed << setprecision(1) << 5.0 / 9.0 * (temperature - 32) << " 度" << endl;
return 0;
} | true |
b41d53c3f08b8969b6033b2e49a88a559d9736e8 | C++ | mubasshir00/competitive-programming | /LeetCode/1143. Longest Common Subsequence.cpp | UTF-8 | 724 | 2.84375 | 3 | [] | no_license | class Solution {
public:
int longestCommonSubsequence(string text1, string text2) {
int temp_arr[text1.size()+1][text2.size()+1];
memset(temp_arr,0,sizeof(temp_arr));
int max_index = 0;
int min_index = 0;
for(int i=0;i<=text1.size();i++){
for(int j=0;j<=text2.size();j++){
if(i==0 || j==0){
temp_arr[i][j]=0;
}
else if (text1[i-1] == text2[j-1] )
{
temp_arr[i][j] = temp_arr[i-1][j-1]+1;
}
else
{
temp_arr[i][j] = max(temp_arr[i-1][j],temp_arr[i][j-1]);
}
}
}
return temp_arr[text1.size()][text2.size()];
}
};
| true |
995a9fda863fb62e0f7c074f64b5a5424c1f3123 | C++ | Nirajn2311/cplusplus | /Pointers1.cpp | UTF-8 | 292 | 2.75 | 3 | [] | no_license | #include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
char a = '1',b = 'a';
float c = 1,d = 2;
float *r, *s;
char *p, *q;
p = &a;
q = &b;
r = &c;
s = &d;
cout<<p;
cout<<"\n"<<q;
cout<<"\n"<<r;
cout<<"\n"<<s;
return 0;
} | true |
2866bfef0d5e5e7b3b8b16538e5c705141e654df | C++ | yoonioncho/OOPG-with-C | /Library System/Person.cpp | UTF-8 | 428 | 3.5 | 4 | [] | no_license | //Person.cpp
//Member and friend function definitions of class Person
#include "Person.h"
#include "Date.h"
Person::Person(Date d, string n)
:DOB(d)
{
setName(n);
}
Person::~Person()
{
}
string Person::getName()
{
return Name;
}
void Person::setName(string n)
{
Name = n;
}
void Person::print() const
{
cout << "\tName : " << Name << endl;
cout << "\tDate of Birth : ";
DOB.print();
}
| true |
512b9017dd379cf008e2a23c29cdc18baca42c9f | C++ | khodand/spbsu-homework | /semester_1/hometask_4/Source_4.4/main.cpp | UTF-8 | 419 | 3.171875 | 3 | [] | no_license | #include <iostream>
#include "postfixNotation.h"
#include "stack.h"
#include "queue.h"
using namespace std;
int main() {
Queue inStr;
cout << "Enter an expression in postfix notation" << endl << "Don't forget to put '=' at the end!!!" << endl;
char curToken = ' ';
cin >> curToken;
while (curToken != '=') {
push(inStr, curToken);
cin >> curToken;
}
cout << calculate(inStr, true) << endl;
return 0;
} | true |
4135a8d54dbcf4887d9df96c07e6dbbf5c9333f5 | C++ | foool/nclib | /tests/test04.cc | UTF-8 | 1,355 | 2.875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include "../galois.h"
#include "../nc.h"
/* Test Insert_matrix{2} Append_matrix{2} Replace_matrix{2}
* Slice_matrix{1}
*/
int main(void){
GMatrix m1;
GMatrix m2;
int r1, r2;
NOTE(" m1 Matrix ");
m1.Make_random(4, 4, 16);
m1.Print();
NOTE(" m2 Matrix ");
m2.Make_random(4, 4, 16);
m2.Print();
/* Insert_matrix */
printf("Input the arguments of Insert_matrix(r1)\n");
scanf("%d", &r1);
m1.Insert_matrix(m2, r1);
NOTE("After Insertion");
m1.Print();
/* Insert_matrix */
printf("Input the arguments of Insert_matrix(r1, r2)\n");
scanf("%d %d", &r1, &r2);
m1.Insert_matrix(m2, r1, r2);
NOTE("After Insertion");
m1.Print();
/* Append_matrix */
NOTE(" Append a matrix ");
m1.Print();
m1.Append_matrix(m2);
NOTE("After Insertion");
m1.Print();
/* Append_matrix */
printf("Input the arguments of Append_matrix(r1)\n");
scanf("%d, %d", &r1, &r2);
m1.Append_matrix(m2, r1, r2);
NOTE("After Insertion");
m1.Print();
/* Slice_matrix */
printf("Input the arguments of Slice_matrix(r1, r2)\n");
scanf("%d %d", &r1, &r2);
NOTE(" m2 matrix ");
m2.Print();
m2 = Slice_matrix(m1, r1, r2);
NOTE("After Insertion");
m2.Print();
}
| true |
99327bd629f11021b61e3c41f3b61aa039c5a1f1 | C++ | langio/Jump | /server/3rd/yac/src/libutil/yac_config.cpp | UTF-8 | 16,711 | 2.5625 | 3 | [] | no_license | #include <errno.h>
#include <fstream>
#include "util/yac_config.h"
#include "util/yac_common.h"
namespace util
{
YAC_ConfigDomain::YAC_ConfigDomain(const string &sLine)
{
_name = YAC_Common::trim(sLine);
}
YAC_ConfigDomain::~YAC_ConfigDomain()
{
destroy();
}
YAC_ConfigDomain::YAC_ConfigDomain(const YAC_ConfigDomain &tcd)
{
(*this) = tcd;
}
YAC_ConfigDomain& YAC_ConfigDomain::operator=(const YAC_ConfigDomain &tcd)
{
if(this != &tcd)
{
destroy();
_name = tcd._name;
_param = tcd._param;
_key = tcd._key;
_domain= tcd._domain;
const map<string, YAC_ConfigDomain*> & m = tcd.getDomainMap();
map<string, YAC_ConfigDomain*>::const_iterator it = m.begin();
while(it != m.end())
{
_subdomain[it->first] = it->second->clone();
++it;
}
}
return *this;
}
YAC_ConfigDomain::DomainPath YAC_ConfigDomain::parseDomainName(const string& path, bool bWithParam)
{
YAC_ConfigDomain::DomainPath dp;
if(bWithParam)
{
string::size_type pos1 = path.find_first_of(YAC_CONFIG_PARAM_BEGIN);
if(pos1 == string::npos)
{
throw YAC_Config_Exception("[YAC_Config::parseDomainName] : param path '" + path + "' is invalid!" );
}
if(path[0] != YAC_CONFIG_DOMAIN_SEP)
{
throw YAC_Config_Exception("[YAC_Config::parseDomainName] : param path '" + path + "' must start with '/'!" );
}
string::size_type pos2 = path.find_first_of(YAC_CONFIG_PARAM_END);
if(pos2 == string::npos)
{
throw YAC_Config_Exception("[YAC_Config::parseDomainName] : param path '" + path + "' is invalid!" );
}
dp._domains = YAC_Common::sepstr<string>(path.substr(1, pos1-1), YAC_Common::tostr(YAC_CONFIG_DOMAIN_SEP));
dp._param = path.substr(pos1+1, pos2 - pos1 - 1);
}
else
{
// if(path.length() <= 1 || path[0] != YAC_CONFIG_DOMAIN_SEP)
if(path[0] != YAC_CONFIG_DOMAIN_SEP)
{
throw YAC_Config_Exception("[YAC_Config::parseDomainName] : param path '" + path + "' must start with '/'!" );
}
dp._domains = YAC_Common::sepstr<string>(path.substr(1), YAC_Common::tostr(YAC_CONFIG_DOMAIN_SEP));
}
return dp;
}
YAC_ConfigDomain* YAC_ConfigDomain::addSubDomain(const string& name)
{
if(_subdomain.find(name) == _subdomain.end())
{
_domain.push_back(name);
_subdomain[name] = new YAC_ConfigDomain(name);
}
return _subdomain[name];
}
string YAC_ConfigDomain::getParamValue(const string &name) const
{
map<string, string>::const_iterator it = _param.find(name);
if( it == _param.end())
{
throw YAC_ConfigNoParam_Exception("[YAC_ConfigDomain::getParamValue] param '" + name + "' not exits!");
}
return it->second;
}
YAC_ConfigDomain *YAC_ConfigDomain::getSubTcConfigDomain(vector<string>::const_iterator itBegin, vector<string>::const_iterator itEnd)
{
if(itBegin == itEnd)
{
return this;
}
map<string, YAC_ConfigDomain*>::const_iterator it = _subdomain.find(*itBegin);
//根据匹配规则找不到匹配的子域
if(it == _subdomain.end())
{
return NULL;
}
//继续在子域下搜索
return it->second->getSubTcConfigDomain(itBegin + 1, itEnd);
}
const YAC_ConfigDomain *YAC_ConfigDomain::getSubTcConfigDomain(vector<string>::const_iterator itBegin, vector<string>::const_iterator itEnd) const
{
if(itBegin == itEnd)
{
return this;
}
map<string, YAC_ConfigDomain*>::const_iterator it = _subdomain.find(*itBegin);
//根据匹配规则找不到匹配的子域
if(it == _subdomain.end())
{
return NULL;
}
//继续在子域下搜索
return it->second->getSubTcConfigDomain(itBegin + 1, itEnd);
}
void YAC_ConfigDomain::insertParamValue(const map<string, string> &m)
{
_param.insert(m.begin(), m.end());
map<string, string>::const_iterator it = m.begin();
while(it != m.end())
{
size_t i = 0;
for(; i < _key.size(); i++)
{
if(_key[i] == it->first)
{
break;
}
}
//没有该key, 则添加到最后
if(i == _key.size())
{
_key.push_back(it->first);
}
++it;
}
}
void YAC_ConfigDomain::setParamValue(const string &name, const string &value)
{
_param[name] = value;
//如果key已经存在,则删除
for(vector<string>::iterator it = _key.begin(); it != _key.end(); ++it)
{
if(*it == name)
{
_key.erase(it);
break;
}
}
_key.push_back(name);
}
void YAC_ConfigDomain::setParamValue(const string &line)
{
if(line.empty())
{
return;
}
string::size_type pos = 0;
for(; pos <= line.length() - 1; pos++)
{
if (line[pos] == '=')
{
if(pos > 0 && line[pos-1] == '\\')
{
continue;
}
string name = parse(YAC_Common::trim(line.substr(0, pos), " \r\n\t"));
string value;
if(pos < line.length() - 1)
{
value = parse(YAC_Common::trim(line.substr(pos + 1), " \r\n\t"));
}
setParamValue(name, value);
return;
}
}
setParamValue(line, "");
}
string YAC_ConfigDomain::parse(const string& s)
{
if(s.empty())
{
return "";
}
string param;
string::size_type pos = 0;
for(; pos <= s.length() - 1; pos++)
{
char c;
if(s[pos] == '\\' && pos < s.length() - 1)
{
switch (s[pos+1])
{
case '\\':
c = '\\';
pos++;
break;
case 'r':
c = '\r';
pos++;
break;
case 'n':
c = '\n';
pos++;
break;
case 't':
c = '\t';
pos++;
break;
case '=':
c = '=';
pos++;
break;
default:
throw YAC_Config_Exception("[YAC_ConfigDomain::parse] '" + s + "' is invalid, '" + YAC_Common::tostr(s[pos]) + YAC_Common::tostr(s[pos+1]) + "' couldn't be parse!" );
}
param += c;
}
else if (s[pos] == '\\')
{
throw YAC_Config_Exception("[YAC_ConfigDomain::parse] '" + s + "' is invalid, '" + YAC_Common::tostr(s[pos]) + "' couldn't be parse!" );
}
else
{
param += s[pos];
}
}
return param;
}
string YAC_ConfigDomain::reverse_parse(const string &s)
{
if(s.empty())
{
return "";
}
string param;
string::size_type pos = 0;
for(; pos <= s.length() - 1; pos++)
{
string c;
switch (s[pos])
{
case '\\':
param += "\\\\";
break;
case '\r':
param += "\\r";
break;
case '\n':
param += "\\n";
break;
case '\t':
param += "\\t";
break;
break;
case '=':
param += "\\=";
break;
case '<':
case '>':
throw YAC_Config_Exception("[YAC_ConfigDomain::reverse_parse] '" + s + "' is invalid, couldn't be parse!" );
default:
param += s[pos];
}
}
return param;
}
string YAC_ConfigDomain::getName() const
{
return _name;
}
void YAC_ConfigDomain::setName(const string& name)
{
_name = name;
}
vector<string> YAC_ConfigDomain::getKey() const
{
return _key;
}
vector<string> YAC_ConfigDomain::getSubDomain() const
{
return _domain;
}
void YAC_ConfigDomain::destroy()
{
_param.clear();
_key.clear();
_domain.clear();
map<string, YAC_ConfigDomain*>::iterator it = _subdomain.begin();
while(it != _subdomain.end())
{
delete it->second;
++it;
}
_subdomain.clear();
}
string YAC_ConfigDomain::tostr(int i) const
{
string sTab;
for(int k = 0; k < i; ++k)
{
sTab += "\t";
}
ostringstream buf;
buf << sTab << "<" << reverse_parse(_name) << ">" << endl;;
for(size_t n = 0; n < _key.size(); n++)
{
map<string, string>::const_iterator it = _param.find(_key[n]);
assert(it != _param.end());
//值为空, 则不打印出=
if(it->second.empty())
{
buf << "\t" << sTab << reverse_parse(_key[n]) << endl;
}
else
{
buf << "\t" << sTab << reverse_parse(_key[n]) << "=" << reverse_parse(it->second) << endl;
}
}
++i;
for(size_t n = 0; n < _domain.size(); n++)
{
map<string, YAC_ConfigDomain*>::const_iterator itm = _subdomain.find(_domain[n]);
assert(itm != _subdomain.end());
buf << itm->second->tostr(i);
}
buf << sTab << "</" << reverse_parse(_name) << ">" << endl;
return buf.str();
}
/********************************************************************/
/* YAC_Config implement */
/********************************************************************/
YAC_Config::YAC_Config() : _root("")
{
}
YAC_Config::YAC_Config(const YAC_Config &tc)
: _root(tc._root)
{
}
YAC_Config& YAC_Config::operator=(const YAC_Config &tc)
{
if(this != &tc)
{
_root = tc._root;
}
return *this;
}
void YAC_Config::parse(istream &is)
{
_root.destroy();
stack<YAC_ConfigDomain*> stkTcCnfDomain;
stkTcCnfDomain.push(&_root);
string line;
while(getline(is, line))
{
line = YAC_Common::trim(line, " \r\n\t");
if(line.length() == 0)
{
continue;
}
if(line[0] == '#')
{
continue;
}
else if(line[0] == '<')
{
string::size_type posl = line.find_first_of('>');
if(posl == string::npos)
{
throw YAC_Config_Exception("[YAC_Config::parse]:parse error! line : " + line);
}
if(line[1] == '/')
{
string sName(line.substr(2, (posl - 2)));
if(stkTcCnfDomain.size() <= 0)
{
throw YAC_Config_Exception("[YAC_Config::parse]:parse error! <" + sName + "> hasn't matched domain.");
}
if(stkTcCnfDomain.top()->getName() != sName)
{
throw YAC_Config_Exception("[YAC_Config::parse]:parse error! <" + stkTcCnfDomain.top()->getName() + "> hasn't match <" + sName +">.");
}
//弹出
stkTcCnfDomain.pop();
}
else
{
string name(line.substr(1, posl - 1));
stkTcCnfDomain.push(stkTcCnfDomain.top()->addSubDomain(name));
}
}
else
{
stkTcCnfDomain.top()->setParamValue(line);
}
}
if(stkTcCnfDomain.size() != 1)
{
throw YAC_Config_Exception("[YAC_Config::parse]:parse error : hasn't match");
}
}
void YAC_Config::parseFile(const string &sFileName)
{
if(sFileName.length() == 0)
{
throw YAC_Config_Exception("[YAC_Config::parseFile]:file name is empty");
}
ifstream ff;
ff.open(sFileName.c_str());
if (!ff)
{
throw YAC_Config_Exception("[YAC_Config::parseFile]:fopen fail: " + sFileName, errno);
}
parse(ff);
}
void YAC_Config::parseString(const string& buffer)
{
istringstream iss;
iss.str(buffer);
parse(iss);
}
string YAC_Config::operator[](const string &path)
{
YAC_ConfigDomain::DomainPath dp = YAC_ConfigDomain::parseDomainName(path, true);
YAC_ConfigDomain *pTcConfigDomain = searchTcConfigDomain(dp._domains);
if(pTcConfigDomain == NULL)
{
throw YAC_ConfigNoParam_Exception("[YAC_Config::operator[]] path '" + path + "' not exits!");
}
return pTcConfigDomain->getParamValue(dp._param);
}
string YAC_Config::get(const string &sName, const string &sDefault) const
{
try
{
YAC_ConfigDomain::DomainPath dp = YAC_ConfigDomain::parseDomainName(sName, true);
const YAC_ConfigDomain *pTcConfigDomain = searchTcConfigDomain(dp._domains);
if(pTcConfigDomain == NULL)
{
throw YAC_ConfigNoParam_Exception("[YAC_Config::get] path '" + sName + "' not exits!");
}
return pTcConfigDomain->getParamValue(dp._param);
}
catch ( YAC_ConfigNoParam_Exception &ex )
{
return sDefault;
}
return sDefault;
}
bool YAC_Config::getDomainMap(const string &path, map<string, string> &m) const
{
YAC_ConfigDomain::DomainPath dp = YAC_ConfigDomain::parseDomainName(path, false);
const YAC_ConfigDomain *pTcConfigDomain = searchTcConfigDomain(dp._domains);
if(pTcConfigDomain == NULL)
{
return false;
}
m = pTcConfigDomain->getParamMap();
return true;
}
map<string, string> YAC_Config::getDomainMap(const string &path) const
{
map<string, string> m;
YAC_ConfigDomain::DomainPath dp = YAC_ConfigDomain::parseDomainName(path, false);
const YAC_ConfigDomain *pTcConfigDomain = searchTcConfigDomain(dp._domains);
if(pTcConfigDomain != NULL)
{
m = pTcConfigDomain->getParamMap();
}
return m;
}
vector<string> YAC_Config::getDomainKey(const string &path) const
{
vector<string> v;
YAC_ConfigDomain::DomainPath dp = YAC_ConfigDomain::parseDomainName(path, false);
const YAC_ConfigDomain *pTcConfigDomain = searchTcConfigDomain(dp._domains);
if(pTcConfigDomain != NULL)
{
v = pTcConfigDomain->getKey();
}
return v;
}
bool YAC_Config::getDomainVector(const string &path, vector<string> &vtDomains) const
{
YAC_ConfigDomain::DomainPath dp = YAC_ConfigDomain::parseDomainName(path, false);
//根域, 特殊处理
if(dp._domains.empty())
{
vtDomains = _root.getSubDomain();
return !vtDomains.empty();
}
const YAC_ConfigDomain *pTcConfigDomain = searchTcConfigDomain(dp._domains);
if(pTcConfigDomain == NULL)
{
return false;
}
vtDomains = pTcConfigDomain->getSubDomain();
return true;
}
vector<string> YAC_Config::getDomainVector(const string &path) const
{
YAC_ConfigDomain::DomainPath dp = YAC_ConfigDomain::parseDomainName(path, false);
//根域, 特殊处理
if(dp._domains.empty())
{
return _root.getSubDomain();
}
const YAC_ConfigDomain *pTcConfigDomain = searchTcConfigDomain(dp._domains);
if(pTcConfigDomain == NULL)
{
return vector<string>();
}
return pTcConfigDomain->getSubDomain();
}
YAC_ConfigDomain *YAC_Config::newTcConfigDomain(const string &sName)
{
return new YAC_ConfigDomain(sName);
}
YAC_ConfigDomain *YAC_Config::searchTcConfigDomain(const vector<string>& domains)
{
return _root.getSubTcConfigDomain(domains.begin(), domains.end());
}
const YAC_ConfigDomain *YAC_Config::searchTcConfigDomain(const vector<string>& domains) const
{
return _root.getSubTcConfigDomain(domains.begin(), domains.end());
}
int YAC_Config::insertDomain(const string &sCurDomain, const string &sAddDomain, bool bCreate)
{
YAC_ConfigDomain::DomainPath dp = YAC_ConfigDomain::parseDomainName(sCurDomain, false);
YAC_ConfigDomain *pTcConfigDomain = searchTcConfigDomain(dp._domains);
if(pTcConfigDomain == NULL)
{
if(bCreate)
{
pTcConfigDomain = &_root;
for(size_t i = 0; i < dp._domains.size(); i++)
{
pTcConfigDomain = pTcConfigDomain->addSubDomain(dp._domains[i]);
}
}
else
{
return -1;
}
}
pTcConfigDomain->addSubDomain(sAddDomain);
return 0;
}
int YAC_Config::insertDomainParam(const string &sCurDomain, const map<string, string> &m, bool bCreate)
{
YAC_ConfigDomain::DomainPath dp = YAC_ConfigDomain::parseDomainName(sCurDomain, false);
YAC_ConfigDomain *pTcConfigDomain = searchTcConfigDomain(dp._domains);
if(pTcConfigDomain == NULL)
{
if(bCreate)
{
pTcConfigDomain = &_root;
for(size_t i = 0; i < dp._domains.size(); i++)
{
pTcConfigDomain = pTcConfigDomain->addSubDomain(dp._domains[i]);
}
}
else
{
return -1;
}
}
pTcConfigDomain->insertParamValue(m);
return 0;
}
string YAC_Config::tostr() const
{
string buffer;
map<string, YAC_ConfigDomain*> msd = _root.getDomainMap();
map<string, YAC_ConfigDomain*>::const_iterator it = msd.begin();
while (it != msd.end())
{
buffer += it->second->tostr(0);
++it;
}
return buffer;
}
void YAC_Config::joinConfig(const YAC_Config &cf, bool bUpdate)
{
string buffer;
if(bUpdate)
{
buffer = tostr() + cf.tostr();
}
else
{
buffer = cf.tostr() + tostr();
}
parseString(buffer);
}
}
| true |
204fc92e5096e6f9fa5da756d668983e46cd8f50 | C++ | jiantao/LeetCode | /multiply_strings.cpp | UTF-8 | 1,510 | 3.34375 | 3 | [] | no_license | /*
* =====================================================================================
*
* Filename: multiply_strings.cpp
*
* Description:
*
* Version: 1.0
* Created: 04/26/2013 05:45:33 PM
* Revision: none
* Compiler: gcc
*
* Author: Jiantao Wu (),
* Company:
*
* =====================================================================================
*/
#include "header.hpp"
using namespace std;
class Solution
{
public:
string multiply(string num1, string num2)
{
int l1 = num1.length();
int l2 = num2.length();
vector<int> result(l1 + l2, 0);
for (int i = 0; i != l1; ++i)
{
int d1 = num1[l1-i-1] - '0';
int carry = 0;
for (int j = 0; j != l2; ++j)
{
int d2 = num2[l2-j-1] - '0';
int temp = d1 * d2 + carry + result[i+j];
result[i+j] = temp % 10;
carry = temp / 10;
}
result[i+l2] += carry;
}
int start = l1 + l2 - 1;
while (start > 0 && result[start] == 0)
--start;
string ret("");
for (int i = start; i >= 0; --i)
ret.push_back('0' + result[i]);
return ret;
}
};
int main(int argc, char *argv[])
{
string s1 = "1";
string s2 = "0";
Solution solution;
string result = solution.multiply(s1, s2);
cout << result << endl;
return 0;
}
| true |
e10c1799c47542f7d865e303ddf7ee638ad77693 | C++ | abhineet99/btech-course-assignments | /CS-201-Data_Structures/assignment_1/item.cpp | UTF-8 | 1,306 | 2.546875 | 3 | [
"MIT"
] | permissive | #include <iostream>
#include <ctime>
#include <fstream>
#include <cmath>
#include "item.h"
using namespace std;
long int purchase_id;
int location_x;
int location_y;
char* purchase_time;
item::item ()
{
location_x = 0;
location_y = 0;
purchase_id = -1;
purchase_time = "default";
}
void item::setPurchase_time(char* _time)
{
this->purchase_time = _time;
}
void item::setPurchase_id(long int x)
{
this->purchase_id = x;
}
void item::setLocation_x(int x)
{
this->location_x = x;
}
void item::setLocation_y(int y)
{
this->location_y = y;
}
void item::update(char* c)
{
this->purchase_time = c;
}
void item::update(int id)
{
this->purchase_id = id;
}
void item::setType(string str){};
void item::setweightpu( float ){};
void item::setpricepu(int p){};
void item::setcal(int c){};
void item::setunits(int u){};
void item::setpricepkg(int p){};
void item::setvolpkg(int v){};
void item::setamount(int a){};
float item::getweightpu(){};
int item::getpricepu(){};
int item::getunits(){};
string item::getType(){};
int item::getpricepkg(){};
int item::getcal(){};
int item::getvolpkg(){};
int item::getamount(){};
long int item::getpurchase_id()
{
return purchase_id;
} | true |
75301044f227afff0b962119b4f6b42647752c0a | C++ | Ritacheta/OOP_1st_Sem | /Assignment3/struct.cpp | UTF-8 | 415 | 3.296875 | 3 | [] | no_license | #include<iostream>
using namespace std;
struct Student{
int roll;
int score;
void take_input(int &a,int &b)
{
cout<<"enter roll and score respectively:";
cin>>a>>b;
}
void show(int a,int b)
{
cout<<"roll:"<<a<<" score"<<b<<endl;
}
};
int main()
{
Student s;
s.take_input(s.roll,s.score);
s.show(s.roll,s.score);
s.roll+=10;
s.score+=10;
s.show(s.roll, s.score);
return 0;
} | true |
0b6a5cef6302063ec855f086b06ff1e3b51f89e5 | C++ | CaiCui/Greedy | /cf-58A.cpp | GB18030 | 1,406 | 3.140625 | 3 | [] | no_license | /**CF-58A Chat room
*Greedy
*
*/
//Coders Code uses string-matching
//c++
#include<bits/stdc++.h>
int main()
{char i{0},c;
while(std::cin>>c&&i!=5)i+=c=="hello"[i];
std::cout<<((i==5)?"YES":"NO");}
//c
#include<stdio.h>
int main()
{
char str[]="hello";
char s[110];
int p;
int i;
gets(s);
p=0;
for(i=0;p<5&&s[i];i++)
p+=s[i]==str[p];
puts(p==5?"YES":"NO");
}
//My Code - - brute force,ַͻTLE
#include <iostream>
#include<cstring>
using namespace std;
int main()
{
int i;
int a[101];
int b[101];
int c[101];
int d[101];
int e[101];
int aa,bb,cc,ee,flag;
int k1,k2,k3,k4,k5;
char sss[130];
cin>>sss;
flag=0;
aa=bb=cc=ee=0;
for(i=0;i<strlen(sss);i++)
{
if(sss[i]=='h')
a[aa++]=i;
if(sss[i]=='e')
b[bb++]=i;
if(sss[i]=='l')
c[cc++]=i;
if(sss[i]=='o')
e[ee++]=i;
}
for(k1=0;k1<aa;k1++)
for(k2=0;k2<bb;k2++)
for(k3=0;k3<cc;k3++)
for(k4=0;k4<cc;k4++)
for(k5=0;k5<ee;k5++)
if(a[k1]<b[k2]&&b[k2]<c[k3]&&c[k3]<c[k4]&&c[k4]<e[k5])
{
flag=1;
break;
}
if(flag)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
return 0;
}
| true |
b11367b8655f87ccf54a68843d49cf5052b6e5be | C++ | dormon/prj | /newCld/NetworkConfiguration/src/NetworkConfiguration/Dense.h | UTF-8 | 3,807 | 3.21875 | 3 | [] | no_license | /**
* @file
* @brief This file contains dense layer configuration.
*
* @author Tomáš Milet, imilet@fit.vutbr.cz
*/
#pragma once
#include<Tensor/Tensor.h>
#include<NetworkConfiguration/Layer.h>
#include<NetworkConfiguration/ActivationType.h>
/**
* @brief This class represents Dense layer.
*
* @tparam TYPE base type of parameters.
*/
template<typename TYPE>
class cnnConf::Dense: public Layer{
public:
Dense(
std::string const&name ,
std::vector<std::string>const&inputs ,
std::set <std::string>const&outputs ,
Tensor<TYPE> const&weights ,
Tensor<TYPE> const&biases ,
ActivationType const&activation);
size_t getInputSize()const;
size_t getOutputSize()const;
Tensor<TYPE>const&getWeights()const;
Tensor<TYPE>const&getBiases()const;
ActivationType getActivation()const;
struct WEIGHTS{
constexpr static size_t DIMENSION = 2;
struct AXES{
constexpr static size_t INPUT = 0;
constexpr static size_t OUTPUT = 1;
};
};
struct BIASES{
constexpr static size_t DIMENSION = 1;
struct AXES{
constexpr static size_t OUTPUT = 0;
};
};
protected:
Tensor<TYPE> weights ;
Tensor<TYPE> biases ;
ActivationType activation;
};
/**
* @brief This is the constructor of Dense class.
*
* @param name The name of layer
* @param inputs The vector of names of layers that are inputs to this layer.
* @param outputs The set of names of layers that have this layer as input.
* @param weights weights (2D tensor)
* @param biases biases (1D tensor)
* @param activation the activation type
*/
template<typename TYPE>
inline cnnConf::Dense<TYPE>::Dense(
std::string const&name ,
std::vector<std::string>const&inputs ,
std::set <std::string>const&outputs ,
Tensor<TYPE> const&weights ,
Tensor<TYPE> const&biases ,
ActivationType const&activation):
Layer (Layer::DENSE,name,inputs,outputs),
weights (weights ),
biases (biases ),
activation(activation )
{
auto const weightsDimension = getDimension(weights);
if(weightsDimension != WEIGHTS::DIMENSION){
std::stringstream ss;
ss << "cnnConf::Dense failed - ";
ss << "weights parameter does not have corret dimension. ";
ss << "Expected: " << WEIGHTS::DIMENSION;
ss << " Given: " << weightsDimension;
throw std::invalid_argument(ss.str());
}
}
/**
* @brief This function returns the size of input tensor.
*
* @return the size of input tensor
*/
template<typename TYPE>
inline size_t cnnConf::Dense<TYPE>::getInputSize()const{
assert(WEIGHTS::AXES::INPUT < weights.size.size());
return weights.size[WEIGHTS::AXES::INPUT];
}
/**
* @brief This function returns the size of output tensor.
*
* @return the size of output tensor
*/
template<typename TYPE>
inline size_t cnnConf::Dense<TYPE>::getOutputSize()const{
assert(WEIGHTS::AXES::OUTPUT < weights.size.size());
return weights.size[WEIGHTS::AXES::OUTPUT];
}
/**
* @brief This function returns weights (2D tensor).
*
* @return weights (2D tensor)
*/
template<typename TYPE>
inline Tensor<TYPE>const&cnnConf::Dense<TYPE>::getWeights()const{
return weights;
}
/**
* @brief This function returns biases (1D tensor).
*
* @return biases (1D tensor)
*/
template<typename TYPE>
inline Tensor<TYPE>const&cnnConf::Dense<TYPE>::getBiases()const{
return biases;
}
/**
* @brief This function returns the activation type.
*
* @return the activation type
*/
template<typename TYPE>
inline cnnConf::ActivationType cnnConf::Dense<TYPE>::getActivation()const{
return activation;
}
| true |
aa0c76c2874e431c85960728c167a17f87e71ea9 | C++ | Rogan003/Aktivnost | /KrsevVezba11/main.cpp | UTF-8 | 395 | 3 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int password;
int username;
cout<<"Username:";
cin>>username;
cout<<"Password:";
cin>>password;
if(password!=181818){
cout<<"password or username is incorrect";
}
else if(username!=171717)
cout<<"password or username is incorrect";
else cout<<"Succesfull login";
return 0;
}
| true |
bdff2b67a687854d3b3b515aa165b69fa67eef6e | C++ | Mindful/sos | /data_structures/fall/week_1/ex_15.cpp | UTF-8 | 1,851 | 4.125 | 4 | [] | no_license | #include <functional>
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
class Employee
{
public:
void setValue( const string & n, double s )
{ name = n; salary = s; }
const string & getName( ) const
{ return name; }
void print( ostream & out ) const
{ out << name << " (" << salary << ")"; }
bool operator< ( const Employee & rhs ) const
{ return salary < rhs.salary; }
// Other general accessors and mutators, not shown
private:
string name;
double salary;
};
// Define an output operator for Employee
ostream & operator<< ( ostream & out, const Employee & rhs )
{
rhs.print( out );
return out;
}
//code{text}
// Generic findMax, with a function object, C++ style.
// Precondition: a.size( ) > 0.
template <typename Object, typename Comparator>
const Object & findMax( const vector<Object> & arr, Comparator isLessThan )
{
int maxIndex = 0;
for( int i = 1; i < arr.size( ); i++ )
if( isLessThan( arr[ maxIndex ], arr[ i ] ) )
maxIndex = i;
return arr[ maxIndex ];
}
// Generic findMax, using default ordering.
template <typename Object>
const Object & findMax( const vector<Object> & arr )
{
return findMax( arr, less<Object>( ) );
}
class EmployeeCompare
{
public:
bool operator( )( const Employee & lhs, const Employee & rhs ) const
{ return strcasecmp( lhs.getName().c_str( ), rhs.getName().c_str( ) ) < 0; }
};
int main( )
{
vector<Employee> v( 4 );
v[0].setValue( "George Bush", 400000.00 );
v[1].setValue( "Bill Gates", 2000000000.00 );
v[2].setValue( "Dr. Phil", 13000000.00 );
v[2].setValue( "zena, warrior princess", 30000000.00 );
cout << "Naive findMax: " << findMax( v ) << endl;
cout << "Case insensitive findMax: " << findMax(v, EmployeeCompare()) << endl;
return 0;
} | true |
217617c3fcfca8509858666580a3bf80add3a473 | C++ | danielzkng/codeforces | /1500/1521A.cpp | UTF-8 | 407 | 2.671875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main(){
int cases;
cin >> cases;
for(int iter = 0; iter < cases; ++iter){
long long a, b;
cin >> a >> b;
if(b == 2) b = 4;
if(b == 1) cout << "NO\n";
else{
cout << "YES\n";
cout << a << " " << a * (b - 1) << " " << a * b << "\n";
}
}
return 0;
} | true |
bb79911d65b552494de525ddbf146986ea43a9be | C++ | popon-01/procon_lib | /grl/warshall_floyd.cpp | UTF-8 | 1,410 | 2.703125 | 3 | [] | no_license | #include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int, ll> P;
const ll inf = numeric_limits<ll>::max()/2;
int v,e;
vector< vector<P> >graph;
vector< vector<ll> > dist;
void warshall_floyd(){
dist.clear();
dist.resize(v);
for(int i = 0;i < v;++i){
dist[i].resize(v);
fill(dist[i].begin(),dist[i].end(),inf);
}
for(int i = 0;i < v;++i){
dist[i][i] = 0;
}
for(int i = 0;i < v;++i){
for(int j = 0;j < (int)graph[i].size();++j){
int to = graph[i][j].second;
ll cost = graph[i][j].first;
dist[i][to] = cost;
}
}
for(int k = 0;k < v;++k){
for(int i = 0;i < v;++i){
for(int j = 0;j < v;++j){
if(dist[i][k] != inf && dist[k][j] != inf)
dist[i][j] = min(dist[i][j],
dist[i][k] + dist[k][j]);
}
}
}
}
int main(void){
cin >> v >> e;
graph = vector< vector<P> >(v);
for(int i = 0;i < e;++i){
int s,t;
ll d;
cin >> s >> t >> d;
graph[s].push_back(P(d,t));
}
warshall_floyd();
for(int i = 0;i < v;++i){
if(dist[i][i] < 0){
puts("NEGATIVE CYCLE");
return 0;
}
}
for(int i = 0;i < v;++i){
for(int j = 0;j < v;++j){
if(j != 0)cout << " ";
if(dist[i][j] == inf)cout << "INF";
else cout << dist[i][j];
}
cout << endl;
}
return 0;
}
| true |
d244aee6420504677eedb21b7bd27bf1ed004d5d | C++ | mingyuefly/C_Primer_Plus- | /C_Primer_Plus++/dishiqizhang/dishiqizhang/manip.cpp | UTF-8 | 579 | 2.671875 | 3 | [
"MIT"
] | permissive | //
// manip.cpp
// dishiqizhang
//
// Created by mingyue on 16/2/2.
// Copyright © 2016年 G. All rights reserved.
//
#include <iostream>
int main(int argc, const char * argv[]){
using namespace std;
cout << "Enter an integer:";
int n;
cin >> n;
cout << "n n*n\n";
cout << n << " " << n * n << "(decimal)\n";
cout << hex;
cout << n << " ";
cout << n * n << "(hexadecimal)\n";
cout << oct << n << " " << n * n << "(octal)\n";
dec(cout);
cout << n << " " << n * n << "(decimal)\n";
return 0;
}
| true |
5cdc0ade977190627a34442f63e50a4525406d46 | C++ | Louis5499/leetcode-practice | /647/solution.cpp | UTF-8 | 449 | 3.03125 | 3 | [] | no_license | class Solution {
public:
int count = 0;
int countSubstrings(string s) {
if (s.length() < 2) return 1;
for (int i=0; i<s.length()-1; i++) {
finding(s, i, i);
finding(s, i, i+1);
}
return count+1;
}
void finding(string s, int i, int j) {
while (i >= 0 && j <= s.length()-1 && s[i] == s[j]) {
i--;
j++;
count++;
}
}
}; | true |
3ed3a9bab82a3627200d693349bbbec48be16a1f | C++ | jjedmondson/RGB-CLOCK | /voidmatrix.ino | UTF-8 | 5,581 | 2.8125 | 3 | [] | no_license | /*
* Created by Pi BOTS MakerHub
*
* Email: pibotsmakerhub@gmail.com
*
* Github: https://github.com/pibotsmakerhub
*
* Join Us on Telegram : https://t.me/pibots
* Copyright (c) 2020 Pi BOTS MakerHub
*/
// REQUIRES the following Arduino libraries:
// - DHT Sensor Library: https://github.com/adafruit/DHT-sensor-library
// - Adafruit Unified Sensor Lib: https://github.com/adafruit/Adafruit_Sensor
#include "DHT.h"
#include "Wire.h"
#define DS3231_I2C_ADDRESS 0x68
// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val){
return( (val/10*16) + (val%10) );
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val){
return( (val/16*10) + (val%16) );
}
#define DHTPIN 2 // Digital pin connected to the DHT sensor
#define DHTTYPE DHT11 // DHT 11
//#define DHTTYPE DHT22 // DHT 22 (AM2302), AM2321
//#define DHTTYPE DHT21 // DHT 21 (AM2301)
// Connect pin 1 (on the left) of the sensor to +5V
// NOTE: If using a board with 3.3V logic like an Arduino Due connect pin 1
// to 3.3V instead of 5V!
// Connect pin 2 of the sensor to whatever your DHTPIN is
// Connect pin 4 (on the right) of the sensor to GROUND
// Connect a 10K resistor from pin 2 (data) to pin 1 (power) of the sensor
// Initialize DHT sensor.
// Note that older versions of this library took an optional third parameter to
// tweak the timings for faster processors. This parameter is no longer needed
// as the current DHT reading algorithm adjusts itself to work on faster procs.
DHT dht(DHTPIN, DHTTYPE);
void setup() {
Serial.begin(9600);
Serial.println(F("DHTxx test!"));
dht.begin();
Wire.begin();
// set the initial time here:
// DS3231 seconds, minutes, hours, day, date, month, year
setDS3231time(30,11,12,6,26,3,12);
}
void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte
dayOfMonth, byte month, byte year){
// sets time and date data to DS3231
Wire.beginTransmission(DS3231_I2C_ADDRESS);
Wire.write(0); // set next input to start at the seconds register
Wire.write(decToBcd(second)); // set seconds
Wire.write(decToBcd(minute)); // set minutes
Wire.write(decToBcd(hour)); // set hours
Wire.write(decToBcd(dayOfWeek)); // set day of week (1=Sunday, 7=Saturday)
Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
Wire.write(decToBcd(month)); // set month
Wire.write(decToBcd(year)); // set year (0 to 99)
Wire.endTransmission();
}
void readDS3231time(byte *second,
byte *minute,
byte *hour,
byte *dayOfWeek,
byte *dayOfMonth,
byte *month,
byte *year){
Wire.beginTransmission(DS3231_I2C_ADDRESS);
Wire.write(0); // set DS3231 register pointer to 00h
Wire.endTransmission();
Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
// request seven bytes of data from DS3231 starting from register 00h
*second = bcdToDec(Wire.read() & 0x7f);
*minute = bcdToDec(Wire.read());
*hour = bcdToDec(Wire.read() & 0x3f);
*dayOfWeek = bcdToDec(Wire.read());
*dayOfMonth = bcdToDec(Wire.read());
*month = bcdToDec(Wire.read());
*year = bcdToDec(Wire.read());
}
void displayTime(){
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year;
// retrieve data from DS3231
readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month,
&year);
// send it to the serial monitor
Serial.print(hour, DEC);
// convert the byte variable to a decimal number when displayed
Serial.print(":");
if (minute<10){
Serial.print("0");
}
Serial.print(minute, DEC);
Serial.print(":");
if (second<10){
Serial.print("0");
}
Serial.print(second, DEC);
Serial.print(" ");
Serial.print(dayOfMonth, DEC);
Serial.print("/");
Serial.print(month, DEC);
Serial.print("/");
Serial.print(year, DEC);
Serial.print(" Day of week: ");
switch(dayOfWeek){
case 1:
Serial.println("Sunday");
break;
case 2:
Serial.println("Monday");
break;
case 3:
Serial.println("Tuesday");
break;
case 4:
Serial.println("Wednesday");
break;
case 5:
Serial.println("Thursday");
break;
case 6:
Serial.println("Friday");
break;
case 7:
Serial.println("Saturday");
break;
}
}
void loop () { displayTime(); // display the real-time clock data on the Serial Monitor,
displaytemp(); //displaythetemp?
delay(4000);
}
void displaytemp() {
// Wait a few seconds between measurements.
// Reading temperature or humidity takes about 250 milliseconds!
// Sensor readings may also be up to 2 seconds 'old' (its a very slow sensor)
float h = dht.readHumidity();
// Read temperature as Celsius (the default)
float t = dht.readTemperature();
// Read temperature as Fahrenheit (isFahrenheit = true)
float f = dht.readTemperature(true);
// Check if any reads failed and exit early (to try again).
if (isnan(h) || isnan(t) || isnan(f)) {
Serial.println(F("Failed to read from DHT sensor!"));
return;
}
// Compute heat index in Fahrenheit (the default)
float hif = dht.computeHeatIndex(f, h);
// Compute heat index in Celsius (isFahreheit = false)
float hic = dht.computeHeatIndex(t, h, false);
Serial.print(F(""));
Serial.print(h);
Serial.print(F("% Temperature: "));
Serial.print(t);
// Serial.print(F("C "));
//Serial.print(f);
//Serial.print(F("F Heat index: "));
// Serial.print(hic);
// Serial.print(F("C "));
// Serial.print(hif);
//Serial.println(F("F"));
delay(2000);
}
| true |
537bb20833ccd4a0fb31df19e763b119bf0acf28 | C++ | dictcore/paragon_slovoed_ce | /data/Compiler/Compiler/AbstractItemManager.h | WINDOWS-1251 | 783 | 2.5625 | 3 | [] | no_license | #pragma once
#include "AbstractItemContainer.h"
///
class CAbstractItemManager
{
public:
///
CAbstractItemManager() = default;
///
UInt32 GetItemsCount() const { return c.count(); }
///
AddedFileResourceMap AddAbstractItemContainer(const CAbstractItemContainer &aAbstractItemContainer);
///
std::wstring GetFullItemNameByItemIndex(UInt32 aIndex) const { return to_string(c.getName(aIndex)); }
private:
FileResourceContainer c;
};
| true |
722a4d0224cd8d8a2d1c3898f02d97c4d1ac84f3 | C++ | shushengyuan/PAT | /遍历/1079.cpp | UTF-8 | 1,149 | 2.78125 | 3 | [] | no_license | #include <cmath>
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
struct node
{
double data;
vector<int> child;
};
vector<node> v;
double tolres = 0.0;
int n;
double r, p;
void dfs(int index, int depth)
{
if (v[index].child.size() == 0)
{
double res;
res = p * pow(1 + r / 100, depth) * v[index].data;
tolres += res;
return;
}
for (int i = 0; i < v[index].child.size(); i++)
{
// cout << i << endl;
dfs(v[index].child[i], depth + 1);
}
}
int main()
{
cin >> n >> p >> r;
v.resize(n);
for (int i = 0; i < n; i++)
{
int tempnum;
scanf("%d", &tempnum);
if (tempnum == 0)
{
// scanf("%d", &temp);
scanf("%lf", &v[i].data);
}
else
{
for (int j = 0; j < tempnum; j++)
{
int temp;
scanf("%d", &temp);
v[i].child.push_back(temp);
}
}
// cout << i << endl;
}
dfs(0, 0);
// cout << tolres << endl;
printf("%.1f", tolres);
return 0;
} | true |
f7b917842f6b10cd378c822e739b7099ea46eb44 | C++ | mathieumg/hockedu | /trunk/Sources/C++/Reseau/UsinePaquet.h | ISO-8859-1 | 2,351 | 2.640625 | 3 | [] | no_license | //////////////////////////////////////////////////////////////////////////////
/// @file UsinePaquet.h
/// @author Mathieu Parent
/// @date 2012-12-30
/// @version 1.0
///
/// @addtogroup razergame RazerGame
/// @{
//////////////////////////////////////////////////////////////////////////////
#pragma once
#include <string>
#include "Enum_Declarations.h"
class Paquet;
///////////////////////////////////////////////////////////////////////////
/// @class UsinePaquet
/// @brief Classe Factory (Usine) de base (abstraite) qui fournit l'interface aux autres Usines de Paquets
///
/// @author Mathieu Parent
/// @date 2012-12-30
///////////////////////////////////////////////////////////////////////////
class UsinePaquet
{
public:
/// Destructeur vide dclar virtuel pour les classes drives.
inline virtual ~UsinePaquet() {};
static Paquet* creerPaquet(PacketTypes t);
protected:
/// Fonction surcharger pour la cration d'un paquet.
virtual Paquet* creerPaquet() const = 0;
/// Constructeur qui prend le nom associ l'usine.
UsinePaquet() {}
};
#define PAQUET_FACTORY_DECLARATION(FactoryName) \
class UsinePaquet## FactoryName : public UsinePaquet \
{ \
protected: \
virtual Paquet* creerPaquet() const; \
};
#define PAQUET_FACTORY_IMPLEMENTATION(FactoryName) \
Paquet* UsinePaquet##FactoryName::creerPaquet() const \
{ return new Paquet##FactoryName(); }
PAQUET_FACTORY_DECLARATION(LoginInfo );
PAQUET_FACTORY_DECLARATION(UserStatus );
PAQUET_FACTORY_DECLARATION(GameStatus );
PAQUET_FACTORY_DECLARATION(GameCreation );
PAQUET_FACTORY_DECLARATION(GameConnection );
PAQUET_FACTORY_DECLARATION(Maillet );
PAQUET_FACTORY_DECLARATION(Rondelle );
PAQUET_FACTORY_DECLARATION(GameEvent );
PAQUET_FACTORY_DECLARATION(Portal );
PAQUET_FACTORY_DECLARATION(Bonus );
// extern pour s'assurer d'allouer la memoire a 1 seule place et une seule fois
extern const std::string PaquetNamesArray[NB_PACKET_TYPES];
extern UsinePaquet* PaquetFactories[NB_PACKET_TYPES];
///////////////////////////////////////////////////////////////////////////////
/// @}
///////////////////////////////////////////////////////////////////////////////
| true |
efbe26ef1187183528430423fba3411e0c96c88a | C++ | yuravashuk/PatternsDesignCxx | /Source/Core/World.cxx | UTF-8 | 867 | 2.9375 | 3 | [] | no_license |
#include "World.hpp"
bool World::Load(const std::string &inFileName)
{
// load files (JSON, TXT, Binary etc.)
// parse file
// create actors and append them to mActors variable
return true;
}
void World::Initialize()
{
for (auto actor : mActors)
{
actor->Initialize();
}
}
void World::Destroy()
{
for (auto actor : mActors)
{
actor->Destroy();
}
mActors.clear();
}
void World::AddActor(Actor* inActor)
{
mActors.push_back( inActor );
}
void World::RemoveActor(Actor* inActor)
{
auto itr = std::find( std::begin(mActors), std::end(mActors), inActor );
mActors.erase( itr );
}
void World::RemoveActor(const std::string &inActorName)
{
}
Actor* World::FindActor(const std::string &inActorName)
{
return nullptr;
}
std::vector< Actor* >& World::GetAllActors()
{
return mActors;
} | true |
e7532260f6d0689b9d09c3bc1b08d68c29f16d8a | C++ | PrakharJain/MyPrograms | /DataStructures/trie/trie.h | UTF-8 | 432 | 2.671875 | 3 | [] | no_license | /*
* trie.h
*
* Created on: 19-Feb-2013
* Author: swati
*/
#ifndef TRIE_H_
#define TRIE_H_
#include <string>
#include <iostream>
#include <vector>
using namespace std;
struct Node
{
vector<Node *> children;
char data;
bool isWord;
string word;
};
class Trie
{
public:
void insert(string &s);
Trie();
Node * find(Node* current , char ch );
bool find(string &s);
private:
Node * root;
};
#endif /* TRIE_H_ */
| true |
891f8987f9f4c4b94c4067b87746eddb2456e0ac | C++ | cnsuhao/sc2bot | /D3D9CallbackSC2/Programs/ProgramPressKey.cpp | UTF-8 | 1,835 | 3 | 3 | [] | no_license | #include "Main.h"
void ProgramPressKey::Init(WORD _Key, bool _Shift, bool _Ctrl)
{
CurState = PressKeyPressKey;
Type = PressKeyNormal;
WaitKey = 0;
Key = _Key;
Shift = _Shift;
Ctrl = _Ctrl;
Name = String("PressKey <") + String(Key);
if(Shift)
{
Name = Name + " Shift";
}
if(Ctrl)
{
Name = Name + " Ctrl";
}
Name = Name + String(">");
}
void ProgramPressKey::Init(const Vector<WORD> &_Keys)
{
CurState = PressKeyPressKey;
Type = PressKeyMultiple;
WaitKey = 0;
Keys = _Keys;
Name = String("PressKey <");
for(UINT i = 0; i < Keys.Length(); i++)
{
Name = Name + " " + String(Keys[i]) + " ";
}
Name = Name + String(">");
}
ProgramResultType ProgramPressKey::ExecuteStep()
{
if(CurState == PressKeyPressKey)
{
LogThreadEvent("Key pressed", LogStep);
if(Type == PressKeyMultiple)
{
for(UINT i = 0; i < Keys.Length(); i++)
{
g_Context->Managers.KeyboardMouse.SendKey(Keys[i]);
}
}
else if(Shift)
{
g_Context->Managers.KeyboardMouse.SendShiftKey(Key);
}
else if(Ctrl)
{
g_Context->Managers.KeyboardMouse.SendCtrlKey(Key);
}
else
{
g_Context->Managers.KeyboardMouse.SendKey(Key);
}
CurState = PressKeyWait;
return ProgramResultStillExecuting;
}
if(CurState == PressKeyWait)
{
if(WaitKey)
{
LogThreadEvent("Key wait", LogStep);
WaitKey--;
return ProgramResultStillExecuting;
}
else
{
LogThreadEvent("Key done", LogDone);
return ProgramResultSuccess;
}
}
HANDLE_CRITICAL_FAILURE;
}
| true |
02b63f077a08cd864034e9bba00e1c6969439354 | C++ | tiqwab/atcoder | /abc246/e/main.cpp | UTF-8 | 4,076 | 2.984375 | 3 | [] | no_license | #include <algorithm>
#include <cassert>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <vector>
#include <limits.h>
using namespace std;
typedef long long ll;
template<class T>
inline bool chmax(T &a, T b) {
if(a < b) {
a = b;
return true;
}
return false;
}
template<class T>
inline bool chmin(T &a, T b) {
if(a > b) {
a = b;
return true;
}
return false;
}
const int INF = INT_MAX / 2;
// right down
const int DIR_RD = 0;
// right up
const int DIR_RU = 1;
// {RD, RU, LU, LD}
const vector<int> dir_y = {-1, 1, 1, -1};
const vector<int> dir_x = {1, 1, -1, -1};
int cell_to_id(const int y, const int x, const int dir, const int N) {
if (dir == DIR_RD) {
return 1 + y * N + x;
} else {
return 1 + y * N + x + N * N;
}
}
// {y, x}
// pair<int, int> id_to_cell(int id, const int N) {
// if (id == 0) {
// // start
// return make_pair(-1, -1);
// }
// if (id <= N * N) {
// id -= 1;
// const int y = id / N;
// const int x = id % N;
// return make_pair(y, x);
// } else {
// id -= 1 + N * N;
// const int y = id / N;
// const int x = id % N;
// return make_pair(y, x);
// }
// }
int main(void) {
int N;
cin >> N;
int sy, sx;
cin >> sy >> sx;
sy--;
sx--;
int gy, gx;
cin >> gy >> gx;
gy--;
gx--;
vector<string> board(N);
for (int i = 0; i < N; i++) {
cin >> board[i];
}
// {from, {to, cost}}
vector<vector<pair<int, int>>> edges(N * N * 2 + 10);
for (int y = 0; y < N; y++) {
for (int x = 0; x < N; x++) {
if (board[y][x] == '#') {
continue;
}
const int id_rd = cell_to_id(y, x, DIR_RD, N);
const int id_ru = cell_to_id(y, x, DIR_RU, N);
edges[id_rd].push_back(make_pair(id_ru, 1));
edges[id_ru].push_back(make_pair(id_rd, 1));
for (int i = 0; i < 4; i++) {
const int ny = y + dir_y[i];
const int nx = x + dir_x[i];
if (ny < 0 || ny >= N || nx < 0 || nx >= N) {
continue;
}
if (board[ny][nx] == '#') {
continue;
}
if (i == 0 || i == 2) {
// RD or LU
const int nid = cell_to_id(ny, nx, DIR_RD, N);
edges[id_rd].push_back(make_pair(nid, 0));
} else {
// RU or LD
const int nid = cell_to_id(ny, nx, DIR_RU, N);
edges[id_ru].push_back(make_pair(nid, 0));
}
}
}
}
// for start
{
const int id_start_rd = cell_to_id(sy, sx, DIR_RD, N);
const int id_start_ru = cell_to_id(sy, sx, DIR_RU, N);
edges[0].push_back(make_pair(id_start_rd, 1));
edges[0].push_back(make_pair(id_start_ru, 1));
}
vector<int> dist(N * N * 2 + 10, INF);
dist[0] = 0;
// {id, cost}
deque<pair<int, int>> deq;
deq.push_back(make_pair(0, 0));
while (!deq.empty()) {
auto cur = deq.front();
deq.pop_front();
const int cur_id = cur.first;
const int cur_cost = cur.second;
if (dist[cur_id] < cur_cost) {
continue;
}
for (auto edge : edges[cur_id]) {
const int to = edge.first;
const int cost = edge.second;
if (dist[to] > cur_cost + cost) {
dist[to] = cur_cost + cost;
if (cost == 0) {
deq.push_front(make_pair(to, cur_cost + cost));
} else {
deq.push_back(make_pair(to, cur_cost + cost));
}
}
}
}
int ans = min(dist[cell_to_id(gy, gx, DIR_RD, N)], dist[cell_to_id(gy, gx, DIR_RU, N)]);
if (ans == INF) {
ans = -1;
}
cout << ans << endl;
return 0;
}
| true |
f2f83093c4c2f463911fb8cc58a165f469fdb545 | C++ | wangyongliang/nova | /poj/3581/POJ_3581_3307043_AC_485MS_1772K.cpp | UTF-8 | 924 | 2.640625 | 3 | [] | no_license | #include<stdio.h>
#include<algorithm>
using namespace std;
#define maxn 401000
int st[maxn];
int getmin(int s,int m)
{
int j,a,b,k,flag;
for (j=0;j<m;++j)
st[j+m]=st[j];
a=s,b=s+1,k=0,flag=1;
if (b>=m)
return a;
while (flag)
{
if(st[a+k]==st[b+k])
{
++k;
if (k>=m) break;
}
else if(st[a+k]>st[b+k])
{
a+=k+1;
if (a<=b) a=b+1;
if (a>=m) break;
k=0;
}
else
{
b=b+k+1;
if (b<=a) b=a+1;
if (b>=m) break;
k=0;
}
}
if (a<b) return a;
else return b;
}
int main()
{
int n,i,j;
scanf("%d",&n);
for(i=n-1;i>=0;i--) scanf("%d",&st[i]);
i=getmin(2,n);
//printf("i= %d\n",i);
for(j=i;j<n;j++) printf("%d\n",st[j]);
n=i;
i=getmin(1,n);
// printf("i= %d\n",i);
for(j=i;j<n;j++) printf("%d\n",st[j]);
n=i;
for(j=0;j<n;j++) printf("%d\n",st[j]);
return 0;
}
| true |
0f63f7cb73e527d72ca7e4270bd569b5d1eb1564 | C++ | buckeye-cn/ACM_ICPC_Materials | /solutions/kattis/spotify12/evenland_hcz.cpp | UTF-8 | 1,022 | 2.75 | 3 | [] | no_license | // https://open.kattis.com/problems/evenland
#include <cstdlib>
#include <cstdint>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <iostream>
#define MOD(x) ((x) % 1000000009)
using namespace std;
int n, m;
int uf[100000];
int find(int i) {
if (uf[i] == i) return i;
return uf[i] = find(uf[i]);
}
void merge(int from, int to) {
from = find(from);
to = find(to);
if (from != to) {
uf[from] = to;
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.precision(10);
cin >> n >> m;
for (int i = 0; i < n; ++i) {
uf[i] = i;
}
for (int i = 0; i < m; ++i) {
int from, to;
cin >> from >> to;
merge(from - 1, to - 1);
}
int power = m - n;
for (int i = 0; i < n; ++i) {
if (uf[i] == i) power += 1;
}
long result = 1;
for (int i = 0; i < power; ++i) {
result = MOD(2 * result);
}
cout << result << endl;
return 0;
}
| true |
3cf2d625f765d587724270b34994f250504007d5 | C++ | ronj/teensy-dash | /source/PeripheralLayer/FrequencyCounter.h | UTF-8 | 434 | 2.78125 | 3 | [] | no_license | #pragma once
#include <cinttypes>
namespace HardwareLayer
{
class FrequencyCounter;
}
namespace PeripheralLayer
{
class FrequencyCounter
{
public:
FrequencyCounter(HardwareLayer::FrequencyCounter& counter);
virtual float GetFrequency();
private:
static const uint8_t NUMBER_OF_ITERATIONS = 1;
HardwareLayer::FrequencyCounter& m_Counter;
uint8_t m_Count = 0;
uint32_t m_Sum = 0;
float m_Frequency = 0.f;
};
}
| true |
e2c27cb4e399d907994dc1414a17bf399731c640 | C++ | marccane/Projectes-CPP | /Exercicis EDA/ArbresBinaris1/ArbreBinari.h | UTF-8 | 1,172 | 2.53125 | 3 | [] | no_license | /*******************************************************************************
* Arbre Binari Caracters
*
* Conte totes les operacions, pero nomes cal implementar les necessaries
* Si no es demana el contrari, millor no implementar el destructor.
*
* 2008
* JSS - Actualitzats els metodes
*******************************************************************************/
#ifndef ARBRE_BINARI_CARACTER_H
#define ARBRE_BINARI_CARACTER_H
#include <cstdlib>
using namespace std;
struct node {
node(node*,node*,char);
char c;
node * fe, * fd; };
class ArbreBinari{
node * arrel;
// metode privat per poder fer el constructor
//int iArbreBinari(char * cadena, int i);
node * iArbreBinari(char * cadena, int &i);
public:
ArbreBinari();
ArbreBinari(node * a);
ArbreBinari(ArbreBinari & a, ArbreBinari & b, char c);
ArbreBinari(char cadena[]);
// nomes s'ha d'implementar el destructor si el codi ho demana.
//~ArbreBinari();
bool arbre_nul() const;
ArbreBinari * fill_dret() const;
ArbreBinari * fill_esquerre() const;
char contingut() const;
void arrelar(ArbreBinari & a, ArbreBinari & b, char c);
friend class ItPreordreNodeArbreBinari;
};
#endif
| true |
cc91194c590c6ee14d1d9da93d9c0d9876c2ef66 | C++ | SurajKalsiSky/AdvancedProgramming | /Task 2/Server.cpp | UTF-8 | 2,724 | 2.796875 | 3 | [] | no_license | #include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
#include "stdafx.h"
#include "Server.h"
int Server::Run() {
SOCKET serverSocket;
Server server;
SERVICEPARAMS serviceParams;
this->SetupWinsock();
serverSocket = this->SetupSocket();
this->CreateServiceBinding(serverSocket);
this->ListenForClient(serverSocket);
SOCKET acceptSocket = this->AcceptConnection(serverSocket);
DWORD threadID;
cout << "Client Connected!" << endl;
serviceParams.socket = (LPVOID)acceptSocket;
serviceParams.instance = this;
serviceParams.size = sizeof(Server);
serviceParams.name = "Server";
CreateThread(NULL, 0, this->ServerThreadSender, &serviceParams, 0, &threadID);
cout << "Session started, enter your messages below" << endl << endl;
int byteCount = 0;
while (true) {
this->SocketReceiver<SERVICEPARAMS>(serviceParams, (SOCKET)acceptSocket, byteCount);
}
closesocket(acceptSocket);
return this->EndSession();
}
int Server::CreateServiceBinding(SOCKET serverSocket) {
try {
sockaddr_in service = this->SetupService();
if (bind(serverSocket, (SOCKADDR*)&service, sizeof(Server)) == SOCKET_ERROR) {
throw ServerBindingException();
}
return 1;
} catch (ServerBindingException& e) {
PrintException(e.what());
closesocket(serverSocket);
WSACleanup();
}
}
void Server::ListenForClient(SOCKET serverSocket) {
try {
if (listen(serverSocket, 1) == SOCKET_ERROR) {
throw ServerSocketListenException();
} else {
cout << "Waiting for a client to connect..." << endl;
}
} catch (ServerSocketListenException& e) {
PrintException(e.what());
}
}
int Server::AcceptConnection(SOCKET socket) {
try {
SOCKET acceptSocket = accept(socket, NULL, NULL);
if (acceptSocket == INVALID_SOCKET) {
throw ServerAcceptConnectionException();
}
return acceptSocket;
} catch (ServerAcceptConnectionException& e) {
PrintException(e.what());
return -1;
}
}
DWORD WINAPI Server::ServerThreadSender(void* param) {
SERVICEPARAMS* params = (SERVICEPARAMS*)param;
SOCKET socket = (SOCKET)params->socket;
Server server;
int byteCount;
bool shouldRun = true;
try {
while (shouldRun) {
Sleep(500);
if (socket != INVALID_SOCKET) {
byteCount = send(socket, (char*)&server, sizeof(Server), 0);
if (byteCount == SOCKET_ERROR) {
throw ServerSendException();
} else {
cin >> server.message;
if (server.message == server.QUIT) {
shouldRun = false;
exit(0);
};
}
} else {
throw InvalidSocketException();
}
}
closesocket(socket);
return 0;
} catch (InvalidSocketException& e) {
PrintException(e.what());
} catch (ServerSendException& e) {
PrintException(e.what());
closesocket(socket);
return -1;
}
} | true |
a5311431958fe32bc65daedfb8fee44b569e5ad0 | C++ | Akeepers/algorithm | /leetcode/120.cpp | UTF-8 | 795 | 2.84375 | 3 | [
"MIT"
] | permissive | #include <algorithm>
#include <climits>
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
int minimumTotal(vector<vector<int>> &triangle)
{
long long m = triangle.size(), res = INT_MAX;
if (m == 0)
return 0;
vector<vector<long long>> dp(2, vector<long long>(m, INT_MAX));
dp[0][0] = triangle[0][0];
for (int i = 1; i < m; ++i)
{
for (int j = 0; j <= i; ++j)
{
dp[1][j] = min(dp[0][j], j > 0 ? dp[0][j - 1] : INT_MAX) + triangle[i][j];
}
dp[0] = dp[1];
}
for (auto item : dp[0])
{
res = min(res, item);
}
return res;
}
};
int main()
{
system("pause");
return 0;
} | true |
17031f57823897f0ce5f98d22c10ae966df41656 | C++ | ordinary-developer/education | /cpp/std-11/r_lischner-exploring_cpp_11-2_ed/ch_51-names_and_namespaces/04-comparing_a_using_directive_with_a_using_declaration/main.cpp | UTF-8 | 307 | 2.859375 | 3 | [
"MIT"
] | permissive | #include <iostream>
void demonstrate_using_directive() {
using namespace std;
typedef int ostream;
ostream x{ 0 };
std::cout << x << '\n';
}
void demonstrate_using_declaration() {
using std::ostream;
// typedef int ostream; // here an error will be
}
int main() {
return 0;
}
| true |
74721c46a00d4038529135d4b49e78dd04578e84 | C++ | jfgr27/Object-Oriented-Chess-Game | /piece.h | UTF-8 | 635 | 3.171875 | 3 | [] | no_license | #ifndef PIECE_H
#define PIECE_H
#include <string>
class ChessBoard;
class Piece {
public:
/* DECLARATION OF CONSTRUCTOR */
//constructs the piece
inline Piece(int colour_p, std::string n) : colour(colour_p), name(n){ };
/* DECLARATION OF DESTRUCTOR */
virtual ~Piece(){}
/* need to be public for the helper function to access */
int colour;
std::string name;
protected:
/* DECLARATION OF "isValid" */
//purely virtual function
virtual bool isValid(int pos_in[], int pos_out[]) = 0;
/* class Board needs access to isValid and colour/name for printing out */
friend class ChessBoard;
};
#endif
| true |
943c3989344ecc70104f85c1c6d4d4524c9359e6 | C++ | ShirleyDi/CPSC_221 | /Project1/dynmatrix.cc | UTF-8 | 5,341 | 3.03125 | 3 | [] | no_license | #include "dynmatrix.h"
#include <iostream>
using namespace std;
void addCluster(ClusterNode *&head,ClusterNode *&tail,const std::string& name)
// adds a cluster (at the tail) and the corresponding row and column to data structure
// distance of all added DistanceNodes should be initialized to 0.0
// at the end, tail should point to the newly added ClusterNode
{
ClusterNode * newCluster = new ClusterNode();
newCluster -> name = name;
if (head == NULL) {
head = newCluster;
tail = newCluster;
DistanceNode * distanceNode = new DistanceNode();
distanceNode -> distance = 0.0;
head -> row = distanceNode;
head -> column = distanceNode;
return;
}
tail -> next = newCluster;
newCluster -> prev = tail;
DistanceNode* tailDistance = tail -> column;
newCluster -> column = new DistanceNode();
DistanceNode* newTailDis = newCluster -> column;
newTailDis -> distance = 0.0;
while (tailDistance -> nextInColumn) {
tailDistance -> nextInRow = newTailDis;
tailDistance = tailDistance -> nextInColumn;
newTailDis -> nextInColumn = new DistanceNode();
newTailDis = newTailDis -> nextInColumn;
}
tailDistance -> nextInRow = newTailDis;
tailDistance = tail -> row;
newCluster -> row = new DistanceNode();
newTailDis = newCluster -> row;
newTailDis -> distance = 0.0;
while (tailDistance -> nextInRow){
tailDistance -> nextInColumn = newTailDis;
tailDistance = tailDistance -> nextInRow;
newTailDis -> nextInRow = new DistanceNode();
newTailDis = newTailDis -> nextInRow;
}
tailDistance -> nextInColumn = newTailDis;
tail = newCluster;
}
void removeCluster(ClusterNode *&head,ClusterNode *&tail,ClusterNode *toBeRemoved)
// removes a cluster pointed to by toBeRemoved and the corresponding row and column
// if toBeRemoved is the first or last cluster then head or tail needs to be updated
{
// YOUR CODE HERE
DistanceNode* gar = 0;
if (toBeRemoved -> prev == NULL){
head = head -> next;
head -> prev = NULL;
ClusterNode* temp = head;
while (temp -> next) {
gar = temp->row;
temp -> row = temp -> row -> nextInRow;
delete gar;
gar = temp->column;
temp -> column = temp -> column -> nextInColumn;
delete gar;
temp = temp -> next;
}
gar = temp -> row;
temp -> row = temp -> row -> nextInRow;
delete gar;
gar = temp -> column;
temp -> column = temp -> column -> nextInColumn;
delete gar;
delete toBeRemoved -> row;
delete toBeRemoved;
return;
}
if (toBeRemoved -> next == NULL){
tail -> row = NULL;
tail -> column = NULL;
tail -> prev -> next = NULL;
tail = tail -> prev;
DistanceNode* tempRow = tail->row;
while (tempRow -> nextInRow){
gar = tempRow -> nextInColumn;
tempRow -> nextInColumn = NULL;
tempRow = tempRow -> nextInRow;
delete gar;
}
gar = tempRow -> nextInColumn;
tempRow -> nextInColumn = NULL;
delete gar;
DistanceNode* tempCol = tail -> column;
while (tempCol -> nextInColumn){
gar = tempCol -> nextInRow;
tempCol -> nextInRow = NULL;
tempCol = tempCol -> nextInColumn;
delete gar;
}
gar = tempCol -> nextInRow;
tempCol -> nextInRow = NULL;
delete gar;
delete toBeRemoved;
return;
} else {
DistanceNode* temp = toBeRemoved -> prev -> column;
DistanceNode* temp2 = toBeRemoved -> next -> column;
while (temp){ // remove the whole column
gar = temp -> nextInRow;
temp -> nextInRow = temp2;
temp = temp -> nextInColumn;
temp2 = temp2 -> nextInColumn;
delete gar;
}
DistanceNode* temp3 = toBeRemoved -> prev -> row;
DistanceNode* temp4 = toBeRemoved -> next -> row;
while(temp3){
gar = temp3 -> nextInColumn;
temp3 -> nextInColumn = temp4;
temp4 = temp4 -> nextInRow;
temp3 = temp3 -> nextInRow;
delete gar;
}
toBeRemoved -> prev -> next = toBeRemoved -> next;
toBeRemoved -> next -> prev = toBeRemoved ->prev;
delete toBeRemoved;
}
}
void findMinimum(ClusterNode *head,ClusterNode *&C,ClusterNode *&D)
// finds the minimum distance (between two different clusters) in the data structure
// and returns the two clusters via C and D
{
ClusterNode* temp = head;
double minDis = 1000.0;
int row = 0;
int col = 0;
int minRow = 0;
int minCol = 0;
DistanceNode* disNode = 0;
temp = temp -> next;
while (temp){
disNode = temp -> row;
row++;
col = 0;
for (int i = 0; i < row; i++){
if ((disNode -> distance) < minDis && ((disNode -> distance) != 0) ){
minDis = disNode -> distance;
minRow = row;
minCol = col;
}
col++;
disNode = disNode -> nextInRow;
}
temp = temp -> next;
}
ClusterNode* ptC = head;
ClusterNode* ptD = head;
if ((minRow == 0)&&(minCol != 0)) {
for (int i = 0;i < minCol;i++){
ptD = ptD->next;
}
C = ptC;
D = ptD;
} else
if ((minCol == 0)&&(minRow != 0)) {
for (int i = 0;i < minRow;i++){
ptC = ptC -> next;
}
C = ptC;
D = ptD;
} else {
for (int i = 0;i < minRow;i++){
ptC = ptC -> next;
}
for (int i = 0;i < minCol;i++){
ptD = ptD -> next;
}
C = ptC;
D = ptD;
}
}
void printDynMatrix(ClusterNode *head, ClusterNode *tail){
ClusterNode* temp2 = head;
DistanceNode* temp = 0;
while (temp2){
temp = temp2 -> row;
while (temp){
cout<< "Entry: " <<temp -> distance<< endl;
temp = temp -> nextInRow;
}
cout << "nextRow:" <<endl;
temp2 = temp2 -> next;
}
}
| true |
86bc3cabf451577232058bee678201502a6a0c59 | C++ | sladkehs/Ohjam | /test/test/class.cpp | UTF-8 | 1,288 | 3.234375 | 3 | [] | no_license | #include <iostream>
//#include "Box.h"
//#include "Circle.h"
#include "GeometricObject.h"
#include <string>
#include <vector>
using namespace std;
class Test {
public:
int a_;
Test(const int& _a) : a_(_a) {
std::cout << "int Constructor" << std::endl;
}
Test(const Test& _test) : a_(_test.a_) {
std::cout << "Copy Constructor" << std::endl;
}
void print() {
std::cout << a_ << std::endl;
}
};
void printTest(Test test) {
std::cout << &test << std::endl;
test.print();
}
void printTestRef(Test& test) {
std::cout << &test << std::endl;
test.print();
}
void printTestPtr(Test* test) {
std::cout << test << std::endl;
test->print();
}
//int main() {
//
// Test my_test(123);
// std::cout << &my_test << std::endl;
//
// std::cout << std::endl;
// printTest(my_test);
// std::cout << std::endl;
// printTestRef(my_test);
// std::cout << std::endl;
// printTestPtr(&my_test);
//
// //GeometricObject **ob_list = new GeometricObject *[10];
// /*vector<GeometricObject *> ob_list;
//
// ob_list.push_back(GeometricObject::getGeometricObject("Box"));
// ob_list.push_back(GeometricObject::getGeometricObject("Circle"));*/
//
// /*for(auto itr : ob_list)
// {
// itr->draw();
// }
//
// for (auto itr : ob_list)
// {
// delete itr;
// }*/
//
// return 0;
//} | true |
3f10680012176d588e102fa08f45d3488c51f935 | C++ | tjdwn6459/C- | /Project1/피라미드 역-2.cpp | UTF-8 | 250 | 2.6875 | 3 | [] | no_license | #include <stdio.h>
int main()
{
int i, j, h;
for (i = 0; i < 6; i++)
{
/*for (j = 0; j<i; j++ )*/
for (j = i ; j > 0; j--)
{
printf(" ");
}
for (h = 0; h < (11 - 2 * i); h++)
{
printf("*");
}
printf("\n");
}
return 0;
} | true |
421b1c8480bfcd61ba9c702de3a5ffab74613dff | C++ | djh-sudo/Stone-Interpreter | /source/ASTLeaf.h | GB18030 | 922 | 2.890625 | 3 | [] | no_license | #pragma once
#include "ASTree.h"
#include "Object.h"
#include "Environment.h"
#include <vector>
// Ҷ
/*
ASTLeaf
-> StringLiteral
-> Name
-> NumberLiteral
*/
class ASTLeaf :public ASTree {
protected:
// token
Token::cptr mToken;
public:
// ĬϹ캯
ASTLeaf() = default;
~ASTLeaf() = default;
// ع캯
ASTLeaf(Token::cptr);
bool isLeaf()const override final; // Ҷ
int numberChildren()const override final; //
Token::cptr token() const override final; // token
ASTree::cptr child(rsize_t t)const override final; // ±귵ضӦӶ
virtual std::string location()const override; // λöӦַ
virtual std::string toString()const override; // תΪַ
virtual Object::ptr eval(Environment& env)const override; //
}; | true |
58a2b01f8882742bf9c4654d06f02bd0031c9b94 | C++ | Yokeagoni/DataStructure-Algorithm | /source/stack/sqstack.h | UTF-8 | 984 | 3.015625 | 3 | [
"MIT"
] | permissive | /*
* @Author: yanxinhao
* @Email: 1914607611xh@i.shu.edu.cn
* @LastEditTime: 2020-12-05 14:03:29
* @LastEditors: yanxinhao
* @Description:
*/
#pragma once
#include "vector/vector.h"
template <typename T>
class sqstack : public Vector<T>
{
private:
/* data */
public:
sqstack(/* args */);
sqstack(const T *A, Rank lo, Rank hi);
~sqstack();
bool push(const T &e)
{
this->insert(this->size(), e);
return 1;
};
T pop() { return this->remove(this->size() - 1); };
T top()
{
if (!this->empty())
return (*this)[this->size() - 1];
else
{
T data;
cerr << "stack is empty" << endl;
return data;
}
}
};
template <typename T>
sqstack<T>::sqstack(/* args */)
{
}
template <typename T>
sqstack<T>::sqstack(const T *A, Rank lo, Rank hi) : Vector<T>(A, lo, hi){
};
template <typename T>
sqstack<T>::~sqstack()
{
}
| true |
fad71d2a27846f85e31720cde6be214d945d194e | C++ | HristoHristov95/C-- | /124-str c++/124-str c++/Source3.cpp | UTF-8 | 437 | 3.046875 | 3 | [] | no_license | #include<iostream>
using namespace std;
class base
{
int a;
public:
void load_a(int n){ a = n; }
int get_a(){ return a; }
};
class derived :public base
{
int b;
public:
void load_b(int n){ b = n; }
int get_b(){ return b; }
};
int main()
{
int ret_a1;
int ret_gg;
base a1,a2;
derived gg,gg1;
a1.load_a(10);
ret_a1 = a1.get_a();
ret_gg = gg.get_a();
cout << ret_a1;
cout << "\n";
cout << ret_gg;
cout << "\n";
return 0;
} | true |
83ccbe51a937ee785433d1ac892c346739d904a3 | C++ | Din-Avrunin/cpp5b | /Test.cpp | UTF-8 | 3,742 | 3.0625 | 3 | [] | no_license | #include <iostream>
#include "range.hpp"
#include "chain.hpp"
#include "zip.hpp"
#include "product.hpp"
#include "powerset.hpp"
#include "badkan.hpp"
using namespace std;
using namespace itertools;
template<typename Iterable>
string iterable_to_string( Iterable& iterable) {
ostringstream ostr;
for (decltype(*iterable.begin()) i: iterable)
ostr << i << ",";
return ostr.str();
}
int main() {
badkan::TestCase testcase;
int grade = 0;
int signal = setjmp(badkan::longjmp_buffer);
if (signal == 0) {
/*
testing the range class
*/
myRange<int> intRange(5, 8);
myRange<int> intRange2(-6,-2);
myRange<double> doubleRange(5.3,6.3);
myRange<double> doubleRange2(12.2,15.2);
myRange<char> charRange('g','l');
myRange<char> charRange2('a','c');
myRange<char> charRange3('e','i');
auto startingPosition = intRange.begin();
auto endingPosition = intRange.end();
/*
testing the chain class
*/
myChain<myRange<int>,myRange<int>> chain1(intRange,intRange2);
myChain<myRange<char>,string> chain4(charRange,"abcd");
myChain<string,myRange<char>> chain5("efgh",charRange2);
/*
testing the zip class
*/
myZip<myRange<int>,string> zip1(intRange,"cpp5");
myZip<myRange<double>,string> zip2(doubleRange,"efg");
myZip<myRange<char>,string> zip3(charRange,"hij");
myZip<myZip<myRange<int>,string>,myZip<myRange<double>,string>> zipOfZip(zip1,zip2);
/*
testing the product class
*/
myProduct<myRange<int>,string> proudct1(intRange,"efg");
myProduct<myRange<double>,string> proudct2(doubleRange,"hij");
myProduct<string,string> proudct3("efg","hij");
/*
testing the powerset class
*/
myPowerSet<myRange<int>> powerSet1(intRange);
myPowerSet<myRange<char>> powerSet2(charRange3);
testcase.setname("TESTING RANGE")
.CHECK_OUTPUT(iterable_to_string(intRange), "5,6,7,")
.CHECK_OUTPUT(iterable_to_string(intRange2),"-6,-5,-4,-3,")
.CHECK_OUTPUT (iterable_to_string(doubleRange),"5.3,")
.CHECK_OUTPUT (iterable_to_string(doubleRange2),"12.2,13.2,14.2,")
.CHECK_OUTPUT (iterable_to_string(charRange),"g,h,i,j,k,")
.CHECK_OUTPUT (iterable_to_string(charRange2),"a,b,")
.CHECK_OUTPUT (iterable_to_string(charRange3),"e,f,g,h,")
.CHECK_EQUAL (startingPosition != endingPosition, true );
testcase.setname("TESTING CHAIN")
.CHECK_OUTPUT (iterable_to_string(chain1),"5,6,7,-6,-5,-4,-3,")
.CHECK_OUTPUT (iterable_to_string(chain4),"g,h,i,j,k,a,b,c,d,")
.CHECK_OUTPUT (iterable_to_string(chain5),"e,f,g,h,a,b,");
testcase.setname("TESTING ZIP")
.CHECK_OUTPUT (iterable_to_string(zip1),"5,c,6,p,7,p,")
.CHECK_OUTPUT (iterable_to_string(zip2),"5.3,e,")
.CHECK_OUTPUT (iterable_to_string(zip3),"g,h,h,i,i,j,")
.CHECK_OUTPUT (iterable_to_string(zipOfZip),"5,c,5.3,e,");
testcase.setname("TESTING PRODUCT")
.CHECK_OUTPUT (iterable_to_string(proudct1),"5,e,5,f,5,g,6,e,6,f,6,g,7,e,7,f,7,g,")
.CHECK_OUTPUT (iterable_to_string(proudct2),"5.3,h,5.3,i,5.3,j,")
.CHECK_OUTPUT (iterable_to_string(proudct3),"e,h,e,i,e,j,f,h,f,i,f,j,g,h,g,i,g,j,");
grade = testcase.grade();
} else {
testcase.print_signal(signal);
grade = 0;
}
cout << "Your grade is: " << grade << endl;
return 0;
} | true |
c42a52d04524948be57db5e102ae403467f13d1d | C++ | umbcdavincilab/pathBubbles | /PathBubbles1.0_1/winQt_Test/Diagram.h | UTF-8 | 1,118 | 2.578125 | 3 | [] | no_license | #pragma once
#include <iostream>
#include <vector>
#include <string>
#include <QPainter>
#include "Point.h"
#include "Label.h"
#include "SimData.h"
using namespace std;
class Diagram
{
public:
//Diagram(Label *label, SimData *simdata, double max_var, double min_var);
Diagram(Label *label, double max_var, double min_var);
~Diagram(void);
void add(string parent_name, string child_name, double parent_var, double child_var,
Color co, int p_index, int c_index);
void Render(QPainter *painter);
bool CheckMouse(int x, int y, int &id);
int GetParentIndex(int id){return _index[id].first;}
int GetChildIndex(int id){return _index[id].second;}
protected:
float MapVarianceToDistance(double var);
private:
vector< pair<string, string> > _name;
vector< pair<int, int> > _index; //index in the origin treering
vector<Color> _color;
vector< pair<Point, Point> > _pos;
vector< pair<double, double> > _variance;
vector<double> _correlation; //Store the correlation between two node
double _max_var, _min_var;
Label *_label;
SimData *_sim_data;
float _point_size; //node size in this diagram
};
| true |
5febbdfb3d964dccc0486c89cec73f1509177ffc | C++ | zixuanwang/QtRoom | /Trainer.cpp | UTF-8 | 4,860 | 2.71875 | 3 | [] | no_license | #include "Trainer.h"
Trainer::Trainer()
{
}
void Trainer::train_hog(const std::string& train_directory){
SVMClassifier classifier;
HoGDescriptor hog_descriptor;
std::string positive_directory = train_directory + "/positive";
std::string negative_directory = train_directory + "/negative";
std::vector<std::string> positive_image_vector;
std::vector<std::string> negative_image_vector;
Utility::get_files(positive_image_vector, positive_directory, false, ".jpg");
Utility::get_files(negative_image_vector, negative_directory, false, ".jpg");
int positive_sample_count = 0;
// add positive samples
for(size_t i = 0; i < positive_image_vector.size(); ++i){
cv::Mat image = cv::imread(positive_image_vector[i]);
std::string label_path = Utility::get_stem_path(positive_image_vector[i]) + ".txt";
std::ifstream label_stream(label_path);
std::string line;
while(getline(label_stream, line)){
std::vector<std::string> strs;
boost::split(strs, line, boost::is_any_of(","));
cv::Rect rect(boost::lexical_cast<int>(strs[0]), boost::lexical_cast<int>(strs[1]), boost::lexical_cast<int>(strs[2]), boost::lexical_cast<int>(strs[3]));
cv::Mat sub_image = image(rect);
cv::Mat patch;
cv::resize(sub_image, patch, cv::Size(GlobalConfig::TRAIN_PATCH_WIDTH, GlobalConfig::TRAIN_PATCH_HEIGHT));
std::vector<float> sample;
hog_descriptor.compute(patch, cv::Rect(0, 0, GlobalConfig::TRAIN_PATCH_WIDTH, GlobalConfig::TRAIN_PATCH_HEIGHT), sample);
classifier.add_sample(sample, 1);
++positive_sample_count;
}
qDebug() << "Processing " << positive_image_vector[i].c_str();
label_stream.close();
}
// add negative samples
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<> length_dist(48, 80);
int negative_image_vector_size = static_cast<int>(negative_image_vector.size());
for(int i = 0; i < negative_image_vector_size; ++i){
cv::Mat image = cv::imread(negative_image_vector[i]);
int width = image.cols;
int height = image.rows;
for(int j = 0; j < positive_sample_count / negative_image_vector_size; ++j){
int length = length_dist(gen);
cv::Rect rect(rand() % (width - length -1), rand() % (height - length -1), length, length);
cv::Mat sub_image = image(rect);
cv::Mat patch;
cv::resize(sub_image, patch, cv::Size(GlobalConfig::TRAIN_PATCH_WIDTH, GlobalConfig::TRAIN_PATCH_HEIGHT));
std::vector<float> sample;
hog_descriptor.compute(patch, cv::Rect(0, 0, GlobalConfig::TRAIN_PATCH_WIDTH, GlobalConfig::TRAIN_PATCH_HEIGHT), sample);
classifier.add_sample(sample, -1);
}
}
classifier.build();
classifier.save(train_directory + "/hog.svm");
}
void Trainer::train_cascade(const std::string& train_directory){
// generate info.dat
std::string positive_directory = train_directory + "/positive";
std::vector<std::string> positive_image_vector;
Utility::get_files(positive_image_vector, positive_directory, false, ".jpg");
std::ofstream info_stream(train_directory + "/info.dat");
for(size_t i = 0; i < positive_image_vector.size(); ++i){
info_stream << "positive/" << Utility::get_name(positive_image_vector[i]) << "\t";
std::vector<cv::Rect> rect_vector;
std::string label_path = Utility::get_stem_path(positive_image_vector[i]) + ".txt";
std::ifstream label_stream(label_path);
std::string line;
while(getline(label_stream, line)){
std::vector<std::string> strs;
boost::split(strs, line, boost::is_any_of(","));
cv::Rect rect(boost::lexical_cast<int>(strs[0]), boost::lexical_cast<int>(strs[1]), boost::lexical_cast<int>(strs[2]), boost::lexical_cast<int>(strs[3]));
rect_vector.push_back(rect);
}
label_stream.close();
info_stream << rect_vector.size() << "\t";
for(size_t j = 0; j < rect_vector.size(); ++j){
info_stream << rect_vector[j].x << " " << rect_vector[j].y << " " << rect_vector[j].width << " " << rect_vector[j].height << "\t";
}
info_stream << std::endl;
}
info_stream.close();
// generate bg.txt
std::string negative_directory = train_directory + "/negative";
std::vector<std::string> negative_image_vector;
Utility::get_files(negative_image_vector, negative_directory, false, ".jpg");
std::ofstream bg_stream(train_directory + "/bg.txt");
for(size_t i = 0; i < negative_image_vector.size(); ++i){
bg_stream << "negative/" << Utility::get_name(negative_image_vector[i]) << std::endl;
}
bg_stream.close();
}
| true |
432dc22aafb36a9672ace0cba0f7f1d7cddb9560 | C++ | Daria-Donina/spbu1stYear | /sem1/hw9/hw9.1/hw9.1/list.cpp | UTF-8 | 1,379 | 3.53125 | 4 | [
"Apache-2.0"
] | permissive | #include "list.h"
#include <string>
#include <iostream>
using namespace std;
using namespace list;
struct list::Node
{
std::string data = 0;
int counter = 0;
Node *next{};
};
struct list::List
{
int length = 0;
list::Node *head{};
};
list::List *list::createList()
{
return new List;
}
bool isEmpty(List *list)
{
return !list->head;
}
void addNode(Node *node, string data)
{
while (node->next)
{
node = node->next;
}
node->next = new Node{ data, 1 };
}
Node* list::exists(List *list, const string &data)
{
Node *node = list->head;
while (node)
{
if (node->data == data)
{
return node;
}
node = node->next;
}
return nullptr;
}
int list::length(List *list)
{
return list->length;
}
int list::counter(Node *node)
{
return node->counter;
}
void list::add(List *list, const string &data)
{
if (isEmpty(list))
{
list->head = new Node{ data, 1 };
++list->length;
return;
}
Node *sameNode = exists(list, data);
if (!sameNode)
{
addNode(list->head, data);
++list->length;
}
else
{
++sameNode->counter;
}
}
void list::deleteList(List *list)
{
Node *node = list->head;
while (node)
{
auto temp = node;
node = node->next;
delete temp;
}
delete list;
}
void list::printList(List *list)
{
Node *node = list->head;
while (node)
{
cout << node->data << " - " << node->counter << endl;
node = node->next;
}
} | true |
5b7fdeb983b6cf773ec5e06dd00b72f4ab7523b0 | C++ | rishup132/My-Codes | /spoj/MKTHNUM - K-th Number.cpp | UTF-8 | 1,672 | 2.9375 | 3 | [] | no_license | #include <bits/stdc++.h>
using namespace std;
set <int> segtree[4000010];
int a[1000010];
set <int> merge(set <int> x, set <int> y)
{
if(x.size() > y.size())
{
set <int> :: iterator it;
for(it = y.begin();it != y.end();it++)
x.insert(*it);
return x;
}
else
{
set <int> :: iterator it;
for(it = x.begin();it != x.end();it++)
y.insert(*it);
return y;
}
}
void build(int nd, int st, int ed)
{
if(st == ed)
{
segtree[nd].insert(a[st]);
return;
}
int mid = (st+ed)/2;
build(2*nd,st,mid);
build(2*nd+1,mid+1,ed);
segtree[nd] = merge(segtree[2*nd],segtree[2*nd+1]);
}
set <int> quary(int nd, int st, int ed, int l, int r)
{
int mid = (st+ed)/2;
if(st >= l && ed <= r)
return segtree[nd];
else if(l > mid)
return quary(2*nd+1,mid+1,ed,l,r);
else if(r <= mid)
return quary(2*nd,st,mid,l,r);
else
return merge(quary(2*nd,st,mid,l,r),quary(2*nd+1,mid+1,ed,l,r));
}
int main()
{
int n,q;
cin >> n >> q;
for(int i=0;i<n;i++)
cin >> a[i];
build(1,0,n-1);
while(q--)
{
int x,y,z;
cin >> x >> y;
set <int> s = quary(1,0,n-1,x-1,y-1);
cout << *s.find(s.begin()+z) << endl;
}
} | true |
a959bbef60585df694d3ef99d99c3e8f3146e8d0 | C++ | jpan127/compiler | /unused/wci/intermediate/symtabimpl/SymTabImpl.h | UTF-8 | 1,934 | 2.921875 | 3 | [] | no_license | /**
* <h1>SymTabImpl</h1>
*
* <p>An implementation of the symbol table.</p>
*
* <p>Copyright (c) 2017 by Ronald Mak</p>
* <p>For instructional purposes only. No warranties.</p>
*/
#ifndef SYMTABIMPL_H_
#define SYMTABIMPL_H_
#include <string>
#include <map>
#include "../SymTab.h"
#include "SymTabEntryImpl.h"
namespace wci { namespace intermediate { namespace symtabimpl {
using namespace std;
using namespace wci::intermediate;
class SymTabImpl : public SymTab
{
public:
/**
* Constructor.
* @param nesting_level the scope nesting level of this table
*/
SymTabImpl(const int nesting_level);
/**
* Destructor.
*/
virtual ~SymTabImpl();
/**
* Getter.
* @return the scope nesting level of this entry.
*/
int get_nesting_level() const;
/**
* Create and enter a new entry into the symbol table.
* To be defined by implementation subclasses.
* Implementation of wci::intermediate::SymTab.
* @param name the name of the entry.
* @return the new entry.
*/
SymTabEntry *enter(const string name);
/**
* Look up an existing symbol table entry.
* To be defined by implementation subclasses.
* Implementation of wci::intermediate::SymTab.
* @param name the name of the entry.
* @return the entry, or null if it does not exist.
*/
SymTabEntry *lookup(const string name);
uint32_t lookup_id(const string name);
/**
* Return a vector of entries sorted by key.
* Implementation of wci::intermediate::SymTab.
* @return a list of symbol table entries sorted by name.
*/
vector<SymTabEntry *> sorted_entries();
uint32_t get_size() const
{
return contents.size();
}
private:
int nesting_level; // scope nesting level
map<string, SymTabEntryImpl *> contents;
};
}}} // namespace wci::intermediate::symtabimpl
#endif /* SYMTABIMPL_H_ */
| true |
e2449c5fd720178336d86a3fc11a91e19061de84 | C++ | IDMNYU/shelfisizer | /arduino/09_ENVY/myfscale.ino | UTF-8 | 2,150 | 3.046875 | 3 | [
"MIT"
] | permissive | float myfscale( float inputValue, float originalMin, float originalMax, float newBegin, float
newEnd, float curve) {
float OriginalRange = 0;
float NewRange = 0;
float zeroRefCurVal = 0;
float normalizedCurVal = 0;
float rangedValue = 0;
boolean invFlag = 0;
// condition curve parameter
// limit range
if (curve > 10) curve = 10;
if (curve < -10) curve = -10;
curve = (curve * -.1) ; // - invert and scale - this seems more intuitive - postive numbers give more weight to high end on output
curve = pow(10, curve); // convert linear scale into logarithmic exponent for other pow function
// Check for out of range inputValues
if (inputValue < originalMin) {
inputValue = originalMin;
}
if (inputValue > originalMax) {
inputValue = originalMax;
}
// Zero Reference the values
OriginalRange = originalMax - originalMin;
if (newEnd > newBegin) {
NewRange = newEnd - newBegin;
}
else
{
NewRange = newBegin - newEnd;
invFlag = 1;
}
zeroRefCurVal = inputValue - originalMin;
normalizedCurVal = zeroRefCurVal / OriginalRange; // normalize to 0 - 1 float
// Check for originalMin > originalMax - the math for all other cases i.e. negative numbers seems to work out fine
if (originalMin > originalMax ) {
return 0;
}
if (invFlag == 0) {
rangedValue = (pow(normalizedCurVal, curve) * NewRange) + newBegin;
}
else // invert the ranges
{
rangedValue = newBegin - (pow(normalizedCurVal, curve) * NewRange);
}
// constrain
float highout = newBegin>newEnd?newBegin:newEnd;
float lowout = newBegin<=newEnd?newBegin:newEnd;
rangedValue = rangedValue>highout?highout:rangedValue;
rangedValue = rangedValue<lowout?lowout:rangedValue;
return rangedValue;
//;
}
float myCurve(float x, float fac)
{
float f = fac * 2.0 - 1.0;
float qIn = x * x * x * x; // exp
float v = (x - 1.0);
float qOut = v * v * v * (1.0 - x) + 1.0; // log
float out = 0.;
if (f < 0.) // fade exp
{
out = (fabs(f) * qIn) + ((1.0-fabs(f)) * x);
}
else // fade log
{
out = (f * qOut) + ((1.0 - f) * x);
}
return (out);
}
| true |
088cad3eb4aeec9d5aab2a6cd2d11f56421a8a3e | C++ | holly12ann/OSU-CS261 | /Assignment 9/PostfixEval.cpp | UTF-8 | 2,326 | 3.90625 | 4 | [] | no_license | /****************************************************************************************
Author: HOLLY SWITZER
Date: 6/2/17
Description: This program will calculate postfix equations
****************************************************************************************/
#include <iostream>
#include <stack>
using namespace std;
double postfixEval(char *evalStr)
{
stack<double> evalStack;
char *s = evalStr;
//not an empty or end of string
while(*s != '\0')
{
//finding digits and creating integers
if (*s >= '0' && *s <= '9')
{
int num = 0;
while(*s >= '0' && *s <= '9' && *s != '\0')
{
num *= 10;
num += *s - '0';
s++;
}
evalStack.push(num);
}
//addition
if(*s == '+')
{
double first, second;
first = evalStack.top();
evalStack.pop();
second = evalStack.top();
evalStack.pop();
evalStack.push(second + first);
}
//subtraction
else if(*s == '-')
{
double first, second;
first = evalStack.top();
evalStack.pop();
second = evalStack.top();
evalStack.pop();
evalStack.push(second - first);
}
//multiplication
else if(*s == '*')
{
double first, second;
first = evalStack.top();
evalStack.pop();
second = evalStack.top();
evalStack.pop();
evalStack.push(second * first);
}
//division
else if(*s == '/')
{
double first, second;
first = evalStack.top();
evalStack.pop();
second = evalStack.top();
evalStack.pop();
evalStack.push(second / first);
}
//increment for next character
s++;
}
return evalStack.top();
}
/*int main()
{
char x[] = "50 10 5 - / 2 5 * *";
cout << postfixEval(x) << "\n";
}*/
| true |
604ecca7d0a44ee8a303556a20b9547d9d91a6a0 | C++ | yuji5296/ethiocalendar | /src/date.cxx | UTF-8 | 15,775 | 2.75 | 3 | [] | no_license | /** \file date.cxx
* \brief Class for having a date class
*
* \author Yuji DOI<yuji5296@gmail.com>
* \date 2008-2009
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "date.h"
#include "yaecob.h"
/* Base point */
//const int BASE[2]={1600,1596};
const int BASE[3]={1600,1600,1020};
/* Table of Total Days each month */
int MONTH[6][14]={
{0,31,59,90,120,151,181,212,243,273,304,334,365,365},// Gregorian non-leap year
{0,31,60,91,121,152,182,213,244,274,305,335,366,366},// Gregorian leap year
{0,30,60,90,120,150,180,210,240,270,300,330,360,365},// Ethiopian non-leap year
{0,30,60,90,120,150,180,210,240,270,300,330,360,366},// Ethiopian leap year
{0,30,59,89,118,148,177,207,236,266,295,325,354,354},// Hijula non-leap year
{0,30,59,89,118,148,177,207,236,266,295,325,355,355},// Hijula leap year
// {0,29,59,89,118,147,177,206,236,265,295,324,354,354},// Isramic in Austria
// {0,30,60,90,119,148,178,207,237,266,296,325,355,355},// Isramic in Austria
};
/* Names of Month */
char MONTH_NAME[3][13][16]={
{GC_MONTH01,GC_MONTH02,GC_MONTH03,GC_MONTH04,GC_MONTH05,GC_MONTH06,GC_MONTH07,GC_MONTH08,GC_MONTH09,GC_MONTH10,GC_MONTH11,GC_MONTH12,""},
{EC_MONTH01,EC_MONTH02,EC_MONTH03,EC_MONTH04,EC_MONTH05,EC_MONTH06,EC_MONTH07,EC_MONTH08,EC_MONTH09,EC_MONTH10,EC_MONTH11,EC_MONTH12,EC_MONTH13},
{IC_MONTH01,IC_MONTH02,IC_MONTH03,IC_MONTH04,IC_MONTH05,IC_MONTH06,IC_MONTH07,IC_MONTH08,IC_MONTH09,IC_MONTH10,IC_MONTH11,IC_MONTH12,""},
};
/* Names of Day */
char WEEKDAY_NAME[3][7][16]={
{GC_WEEKDAY0,GC_WEEKDAY1,GC_WEEKDAY2,GC_WEEKDAY3,GC_WEEKDAY4,GC_WEEKDAY5,GC_WEEKDAY6},
{EC_WEEKDAY0,EC_WEEKDAY1,EC_WEEKDAY2,EC_WEEKDAY3,EC_WEEKDAY4,EC_WEEKDAY5,EC_WEEKDAY6},
{IC_WEEKDAY0,IC_WEEKDAY1,IC_WEEKDAY2,IC_WEEKDAY3,IC_WEEKDAY4,IC_WEEKDAY5,IC_WEEKDAY6},
};
static char gc_weekday[][16]={GC_WEEKDAY0_LABEL,GC_WEEKDAY1_LABEL,GC_WEEKDAY2_LABEL,GC_WEEKDAY3_LABEL,GC_WEEKDAY4_LABEL,GC_WEEKDAY5_LABEL,GC_WEEKDAY6_LABEL};
/* Constructor */
DATE1::DATE1(){
serial = 0;
year = 0;
month = 0;
day = 0;
weekday = 0;
type = GREGORIAN;
}
/*DATE1::DATE1(long serial){
serial = serial;
calc_date(serial,GREGORIAN);
}*/
DATE1::DATE1(short y, char m, char d, CALENDAR t){
type = t;
year = y;
month = m;
day = d;
calc_serial();
calc_weekday();
}
/* Judge Leap year */
bool DATE1::isLeap(int x, CALENDAR calendar){
if (calendar == GREGORIAN){
if ((x % 400) == 0){
return true;
}else if ((x % 100) == 0){
// if (x == 1900){
/* Excel specific */
// return 1;
// }else{
return false;
// }
}else if ((x % 4) == 0){
return true;
}else{
return false;
}
}else if(calendar == ETHIOPIAN){
if (((x + 1) % 4) == 0){
return true;
}else{
return false;
}
}else if(calendar == ISLAMIC){
switch ((x+1) % 30){
case 2:
case 5:
case 7:
case 10:
case 13:
case 15:
case 18:
case 20:
case 24:
case 26:
case 29:
return true;
default:
return false;
}
}else {
return false;
}
}
/* Calculate Days of year */
int DATE1::days1(int x, CALENDAR calendar){
if (calendar == ISLAMIC) {
return 354 + isLeap(x,calendar);
}else {
return YEAR1 + isLeap(x,calendar);
}
}
/* Calculate Days of years from X to Y */
int DATE1::days2(int x, int y, CALENDAR calendar){
int d;
for(d=0;y>=x;x++){
d += days1(x, calendar);
}
return d;
}
int DATE1::calc_serial(){
int x;
x = days2(BASE[type],year-1,type);
x += MONTH[2 * type + isLeap(year, type)][month-1];
x += day;
// weekday = calc_weekday(x);
if (type == ETHIOPIAN){
x = x + OFFSET;
}else if (type == ISLAMIC) {
x = x + OFFSET_ISLAMIC;
}
serial = x;
return serial;
}
/* Calculate Name of Day */
void DATE1::calc_weekday(){
int a;
a = abs(serial) % 7;
if (a>=FIRSTWEEKDAY) a -= FIRSTWEEKDAY;
else a += (7-FIRSTWEEKDAY);
weekday = a;
}
int DATE1::number_of_days(){
static int days_of_month[]={31,28,31,30,31,30,31,31,30,31,30,31};//Gregorian
// static int days_of_month_ic[]={29,30,30,29,29,30,29,30,29,30,29,30};// Islamic in Austria
if (type == GREGORIAN){
if (month == 2){
if (isLeap(year,type)) return 29;
else return 28;
}
else return days_of_month[month-1];
}else if (type == ETHIOPIAN){
if (month == 13){
if (isLeap(year,type)) return 6;
else return 5;
}else return 30;
}else if (type == ISLAMIC){
#if 1// Hijula
if (month == 12){
if (isLeap(year,type)) return 30;
else return 29;
}else if (month % 2) return 30;
else return 29;
#else // Islamic in Austria
if (month == 1){
if (isLeap(year,type)) return 30;
else return 29;
}
else return days_of_month_ic[month-1];
#endif
}
}
/* Calculate month and day from Serial number */
int DATE1::calc_month(int x, int leap, int *month, int *day, CALENDAR calendar){
int m,d,len,sub;
int top,mid,*months;
len = 14;
months = MONTH[2 * calendar + leap];
top = 0;
for (;len>1;){
mid = top + len/2;
sub = months[mid-1];
//printf("len=%d, top=%d, mid=%d,sub=%d\n",len,top,mid,sub);
if (x <= sub) {
len = mid - top ;
}else{
len = len - (mid - top);
top = mid ;
}
}
*month = top;
*day = x - months[top-1];
//printf("x=%d, leap=%d, month = %d, day=%d\n",x,leap,*month,*day);
return 0;
}
/* Calculate year from Serial number */
int DATE1::calc_year(int x, int *year, int *month, int *day, CALENDAR calendar){
int Base; /* Base year */
int leap; /* flag of leap year */
int x1, x2, x3, x4, x5; /* days */
int y1, y2, y3, y4;
int rtn;
if (calendar == GREGORIAN) {
if (x <= days1(BASE[calendar],calendar)){
Base = BASE[calendar];
x1 = x;
x4 = x3 = x2 = x1;
y4 = y3 = y2 = y1 = 0;
}else{
Base = 1601;
x1 = x - days1(BASE[calendar],calendar) ;
y1 = x1 / YEAR400 ; /* Number of 400 years */
x2 = x1 - y1 * YEAR400; /* Days from recently 400 years */
y2 = x2 / YEAR100 ; /* Number of 100 years */
if ((x2 % YEAR100) == 0) y2--;
if (y2 > 3) y2 = 3;
x3 = x2 - y2 * YEAR100 ; /* Days from recently 100 years */
y3 = x3 / YEAR4 ; /* Number of 4 years */
if ((x3 % YEAR4) == 0) y3--;
if (y3 > 24) y3 = 24;
x4 = x3 - y3 * YEAR4; /* Days from recently 4 years */
y4 = x4 / YEAR1 ; /* Number of year */
if ((x4 % YEAR1) == 0) y4--;
if (y4 > 3) y4 = 3;
}
*year = Base + (y1 * 400) + (y2 * 100) + (y3 * 4) + y4 ;
}else if (calendar == ETHIOPIAN) {
Base = BASE[calendar];
x1 = x - OFFSET;
y1 = 0 ;
x2 = x1;
y2 = 0 ;
x3 = x2;
y3 = x3 / YEAR4 ; /* Number of 4 years */
if ((x3 % YEAR4) == 0) y3--;
x4 = x3 - y3 * YEAR4; /* Days from recently 4 years */
y4 = x4 / YEAR1 ; /* Number of year */
if ((x4 % YEAR1) == 0) y4--;
if (y4 > 3) y4 = 3;
*year = Base + (y1 * 400) + (y2 * 100) + (y3 * 4) + y4 ;
}else if (calendar == ISLAMIC) {
Base = BASE[calendar];
x1 = x - OFFSET_ISLAMIC;
x3 = x1;
y3 = x3 / 10631 ; /* Number of 30 years */
if ((x3 % 10631) == 0) y3--;
x4 = x3 - y3 * 10631; /* Days from recently 4 years */
for (y4=0;x4 > days1(Base+(y3*30)+y4,calendar);y4++){
x4 -= days1(Base+(y3*30)+y4,calendar);
}
*year = Base + (y3 * 30) + y4 ;
}
leap = isLeap(*year,calendar);
x5 = x1 - days2(Base,*year-1,calendar);
//printf("x=%d, x1=%d, x2=%d, x3=%d, x4=%d, x5=%d, y1=%d, y2=%d, y3=%d, y4=%d, Base=%d, leap=%d:",x,x1,x2,x3,x4,x5,y1,y2,y3,y4,Base,leap);
rtn = calc_month(x5, leap, month, day, calendar);
return rtn;
}
/* Change Serial number to DATE1 type */
void DATE1::calc_date(int x, CALENDAR calendar){
int rtn;
int y,m,d;
rtn = calc_year(x, &y, &m, &d, calendar);
year = y;
month = m;
day = d;
type = calendar;
serial = x;
calc_weekday();
}
/* Change DATE1 to Serial number */
void DATE1::exchange_date(struct tm *from){
year = from->tm_year + 1900;
month = from->tm_mon + 1;
day = from->tm_mday;
type = GREGORIAN;
// to.weekday = from->tm_wday;
calc_serial();
calc_weekday();
}
/* DATE1 Utility */
char* DATE1::print_date(){
static char str[256];
sprintf(str,"%14s %15s(%2d) %2d, %4d",WEEKDAY_NAME[type][weekday],MONTH_NAME[type][month-1],month,day,year);
return str;
}
char* DATE1::print_short(){
static char str[16];
sprintf(str,"%04d/%02d/%02d(%s)",year,month,day,gc_weekday[weekday]);
return str;
}
/* Input date from keyboard */
int DATE1::scan_date(){
printf("Gregorian=0, Ethiopian=1> ");
scanf(" %d",&type);
printf("\nInput date (yyyy mm dd):");
scanf(" %d %d %d",&year, &month, &day);
calc_serial();
calc_weekday();
if (year == 0) return 0;
if (day > number_of_days()){
printf("Input error!\n");
return 0;
}
return 1;
}
int DATE1::scan(const char *str, CALENDAR type){
sscanf(str,"%d/%d/%d",&year, &month, &day);
calc_serial();
calc_weekday();
if (year == 0) return 0;
if (day > number_of_days()){
printf("Input error!\n");
return 0;
}
return 1;
}
char *DATE1::name_of_month(){
return MONTH_NAME[type][month-1];
}
void DATE1::FirstDay(){
day = 1;
calc_serial();
calc_weekday();
}
void DATE1::Today(){
// DATE1 date;
time_t now;
struct tm *d;
// get today
now = time(&now);
printf("Today is %s",ctime(&now));
d = localtime(&now);
// set today
exchange_date(d);
type = GREGORIAN;
// return *this;
}
void DATE1::Tomorrow(){
int lastmonth = (type==ETHIOPIAN) ? 13 : 12;
if (day < number_of_days()){
day++;
}else if (month == lastmonth){ //New Year's Eve
day = 1;
month = 1;
year++;
}else { //end of the month
day = 1;
month++;
}
if (weekday != 6) weekday++;
else weekday=0;
serial++;
}
void DATE1::Yesterday(){
int lastmonth = (type==ETHIOPIAN) ? 13 : 12;
if (day > 1){
day--;
}else if (month == 1){ //New Year's day
year--;
month = lastmonth;
day = number_of_days();
}else { //beging of the month
month--;
day = number_of_days();
}
if (weekday != 0) weekday--;
else weekday=6;
serial--;
}
void DATE1::NextMonth(){
int lastmonth = (type==ETHIOPIAN) ? 13 : 12;
if (month == lastmonth){ //Last month
month = 1;
year++;
}else {
month++;
}
calc_serial();
calc_weekday();
}
void DATE1::NextYear(){
year++;
calc_serial();
calc_weekday();
}
void DATE1::PrevMonth(){
int lastmonth = (type==ETHIOPIAN) ? 13 : 12;
if (month == 1){ //First month
month = lastmonth;
year--;
}else {
month--;
}
calc_serial();
calc_weekday();
}
void DATE1::PrevYear(){
year--;
calc_serial();
calc_weekday();
}
int DATE1::DiffDate(DATE1 d1, DATE1 d2){
int i;
i = d2.serial - d1.serial;
//for(i=0;d1.year!=d2.year||d1.month!=d2.month||d1.day!=d2.day;i++){
// d1.Tomorrow();
//}
return i;
}
bool DATE1::CompDate(DATE1 date){
if ((year == date.year) && (month == date.month) && (day == date.day)) return true;
else return false;
}
bool DATE1::CompDate(DATE1 *date){
if ((year == date->year) && (month == date->month) && (day == date->day)) return true;
else return false;
}
#if 0
int DATE1::days(){
int sum= day;
int lastmonth = (type==ETHIOPIAN) ? 13 : 12;
for(month--;month>0;month--){
sum+=number_of_days();
}
for(;year>0;year--){
for(month=lastmonth;month>0;month--){
sum+=number_of_days();
}
}
return sum;
}
/* return days from dispatched */
char * DATE1::days_dispatched(){
DATE1 *dd = new DATE1(2007,6,19,3,GREGORIAN);
static char str[256];
sprintf(str,"%dth day from dispatched",calc_serial() - dd->calc_serial());
//printf("%dth day from dispatched\n",DiffDate(*dd,*this));
return str;
}
/* return days from specified day */
int DATE1::get_days_from(DATE1 dd){
return calc_serial() - dd.calc_serial();
}
/* return days until specified day */
int DATE1::get_days_until(DATE1 dd){
return dd.calc_serial() - calc_serial();
}
void DATE1::disp_date(){
int x, rtn;
// display
days_dispatched();
print_date();
x = calc_serial();
printf(" => x=%d =>\n",x);
calc_date(x, ETHIOPIAN);
print_date();
printf("\n");
}
void DATE1::disp_calendar(){
int i,d=1,m=month,x;
DATE1 date2;
CALENDAR t;
day = 1;
x = calc_serial();
weekday = calc_weekday(x);
if (type == GREGORIAN ) t = ETHIOPIAN;
else t = GREGORIAN;
date2.calc_date(x, t);
// date.weekday = calc_weekday(calc_serial(&date));
printf("%s, %d\t/\t",MONTH_NAME[type][month-1],year);
printf("%s, %d\n",MONTH_NAME[date2.type][date2.month-1],date2.year);
printf(" Sun Mon Tue Wed Thu Fri Sat\n");
for(i=0;i<weekday;i++) printf(" ");
while(month == m){
printf("%2d/%2d ",day,date2.day);
Tomorrow();
date2.Tomorrow();
if (weekday == 0) {
printf("\n");
}
}
printf("\n");
}
#endif
bool DATE1::Validate(){
if(type==GREGORIAN){
if(year < 1604 || 9999 < year) return false;
}else{
if(year < 1604 || 9999 < year) return false;
}
if(month < 1 || MAXMONTH(type) < month) return false;
if(day < number_of_days() || number_of_days() < day) return false;
return true;
}
bool DATE1::IsHoliday(){
if (type == GREGORIAN) {
if (month==1 && day==7) {strcpy(holiday,"Ethiopian Christmas");return true;}//JICA Calendar
if (month==5 && day==1) {strcpy(holiday,"International Labour Day");return true;}
else {strcpy(holiday,"");return false;}
}else if (type == ETHIOPIAN){
if (month==1 && day==1) {strcpy(holiday,"Ethiopian New Year");return true;}
if (month==1 && day==17) {strcpy(holiday,"Finding of the True cross(Meskel)");return true;}
// if (month==4 && day==29) {strcpy(holiday,"Ethiopian Christmas");return true;}//Which is correct?
if (month==5 && day==11) {strcpy(holiday,"Ethiopian Epiphany(Timqat)");return true;}
if (month==6 && day==23) {strcpy(holiday,"Victory of Adwa Command Day");return true;}
if (month==8 && day==27) {strcpy(holiday,"Ethiopian Patriots Command Day");return true;}
if (month==9 && day==20) {strcpy(holiday,"Dawn Fall of the Dergue");return true;}
if (IsGoodFriday()) {strcpy(holiday,"Good Friday");return true;}
if (IsEaster()) {strcpy(holiday,"Ethiopian Easter");return true;}
else {strcpy(holiday,"");return false;}
}else if (type == ISLAMIC){
//Muslim holiday
if (month==3 && day==12) {strcpy(holiday,"Birth Day of Prophet Mohammed(MAULID)");return true;}
if (month==10 && day==1) {strcpy(holiday,"Id Al Faster(Ramadan)");return true;}
if (month==12 && day==10) {strcpy(holiday,"Id Al Adha(Arefa)");return true;}
}
else {strcpy(holiday,"");return false;}
}
bool DATE1::IsGoodFriday(){
if (CompDate(Good_Friday(year))) return true;
else return false;
}
bool DATE1::IsEaster(){
if (CompDate(Easter(year))) return true;
else return false;
}
bool DATE1::IsRamadan(){
if (year == 2000 && month==2 && day==1) return true;
if (year == 2001 && month==1 && day==21) return true;
else return false;
}
bool DATE1::IsArefa(){
if (year == 2000 && month==4 && day==9) return true;
if (year == 2001 && month==3 && day==29) return true;
else return false;
}
bool DATE1::IsMaulid(){
if (year == 2000 && month==7 && day==10) return true;
if (year == 2001 && month==6 && day==29) return true;
else return false;
}
| true |
33c215fdd01b7185a0fc0129442fe96ecb0b0570 | C++ | i-aki-y/CarND-Path-Planning-Project | /src/Utils.cpp | UTF-8 | 1,318 | 2.90625 | 3 | [
"MIT"
] | permissive | //
// Created by AkiyukiIshikawa on 2018/03/28.
//
#include <iostream>
#include <math.h>
#include <vector>
#include "Utils.h"
using namespace std;
constexpr double pi() { return M_PI; }
// Transform from Frenet s,d coordinates to Cartesian x,y
vector<double> Utils::getXY(double s,
double d,
const vector<double> &maps_s,
const vector<double> &maps_x,
const vector<double> &maps_y) {
int prev_wp = -1;
while (s > maps_s[prev_wp + 1] && (prev_wp < (int) (maps_s.size() - 1))) {
prev_wp++;
}
int wp2 = (prev_wp + 1) % maps_x.size();
double heading = atan2((maps_y[wp2] - maps_y[prev_wp]), (maps_x[wp2] - maps_x[prev_wp]));
// the x,y,s along the segment
double seg_s = (s - maps_s[prev_wp]);
double seg_x = maps_x[prev_wp] + seg_s * cos(heading);
double seg_y = maps_y[prev_wp] + seg_s * sin(heading);
double perp_heading = heading - pi() / 2;
double x = seg_x + d * cos(perp_heading);
double y = seg_y + d * sin(perp_heading);
return {x, y};
}
Utils::Segment::Segment(double x, double y, double x_prev, double y_prev) {
x_ = x;
y_ = y;
x_prev_ = x_prev;
y_prev_ = y_prev;
}
double Utils::Segment::GetYaw() {
return atan2(y_ - y_prev_, x_ - x_prev_);
}
| true |
6275212dd27dab6e22460b0ddbf0dd2257c76272 | C++ | novice9/Algorithm-and-Data-Structure | /DataStructure/2D-SegmentTree.cpp | UTF-8 | 5,397 | 3.421875 | 3 | [] | no_license | // code of a 2D segment tree (initialized with a matrix)
// operation
// 1. update: change the value of a slot in the matrix - O(logn)
// 2. query: check the sum of any sub-matrix - O(logn)
class SegmentTreeNode2D {
public:
int left, right, top, bottom;
int sum;
// top-left, top-right, bottom-left, bottom-right;
vector<SegmentTreeNode2D*> children;
SegmentTreeNode2D(int l, int r, int t, int b, int s = 0)
: left(l), right(r), top(t), bottom(b), sum(s) {
children = vector<SegmentTreeNode2D*>(4, NULL);
}
};
class NumMatrix {
public:
NumMatrix(vector<vector<int>> &matrix) {
int row, col;
row = matrix.size();
if (row != 0) {
col = matrix[0].size();
if (col != 0) {
root = build(matrix, 0, col - 1, 0, row - 1);
} else {
root = NULL;
}
} else {
root = NULL;
}
cout << "Successfully create the Segment Tree!" << endl;
}
void update(int row, int col, int val) {
int ori = query(root, col, col, row, row);
update(root, row, col, val - ori);
}
int sumRegion(int row1, int col1, int row2, int col2) {
int val = query(root, col1, col2, row1, row2);
cout << "query: " << val << endl;
return query(root, col1, col2, row1, row2);
}
private:
SegmentTreeNode2D* root;
SegmentTreeNode2D* build(vector<vector<int>> &matrix, int l, int r, int t, int b) {
if (l > r || t > b) {
return NULL;
} else if (l == r && t == b) {
return new SegmentTreeNode2D(l, r, t, b, matrix[t][l]);
} else {
SegmentTreeNode2D *source = new SegmentTreeNode2D(l, r, t, b);
int colMid = l + (r - l) / 2;
int rowMid = t + (b - t) / 2;
source->children[0] = build(matrix, l, colMid, t, rowMid);
source->children[1] = build(matrix, colMid + 1, r, t, rowMid);
source->children[2] = build(matrix, l, colMid, rowMid + 1, b);
source->children[3] = build(matrix, colMid + 1, r, rowMid + 1, b);
for (int i = 0; i < 4; ++i) {
if (source->children[i] == NULL) {
continue;
}
source->sum += source->children[i]->sum;
}
return source;
}
}
int query(SegmentTreeNode2D* source, int l, int r, int t, int b) {
if (source == NULL || r < source->left || source->right < l || b < source->top || source->bottom < t) {
return 0;
} else if (source->left == l && source->right == r && source->top == t && source->bottom == b) {
return source->sum;
} else {
int colMid = source->left + (source->right - source->left) / 2;
int rowMid = source->top + (source->bottom - source->top) / 2;
if (r <= colMid && b <= rowMid) {
return query(source->children[0], l, r, t, b);
} else if (l > colMid && b <= rowMid) {
return query(source->children[1], l, r, t, b);
} else if (r <= colMid && t > rowMid) {
return query(source->children[2], l, r, t, b);
} else if (l > colMid && t > rowMid) {
return query(source->children[3], l, r, t, b);
} else if (b <= rowMid) {
return query(source->children[0], l, colMid, t, b) + query(source->children[1], colMid + 1, r, t, b);
} else if (t > rowMid) {
return query(source->children[2], l, colMid, t, b) + query(source->children[3], colMid + 1, r, t, b);
} else if (r <= colMid) {
return query(source->children[0], l, r, t, rowMid) + query(source->children[2], l, r, rowMid + 1, b);
} else if (l > colMid) {
return query(source->children[1], l, r, t, rowMid) + query(source->children[3], l, r, rowMid + 1, b);
} else {
return query(source->children[0], l, colMid, t, rowMid) + query(source->children[1], colMid + 1, r, t, rowMid) +
query(source->children[2], l, colMid, rowMid + 1, b) + query(source->children[3], colMid + 1, r, rowMid + 1, b);
}
}
}
void update(SegmentTreeNode2D* source, int row, int col, int chg) {
if (source == NULL || col < source->left || source->right < col || row < source->top || source->bottom < row) {
return;
} else {
source->sum += chg;
if (source->left == col && source->right == col && source->top == row && source->bottom == row) {
return;
}
int colMid = source->left + (source->right - source->left) / 2;
int rowMid = source->top + (source->bottom - source->top) / 2;
if (col <= colMid && row <= rowMid) {
update(source->children[0], row, col, chg);
} else if (col > colMid && row <= rowMid) {
update(source->children[1], row, col, chg);
} else if (col <= colMid && row > rowMid) {
update(source->children[2], row, col, chg);
} else if (col > colMid && row > rowMid) {
update(source->children[3], row, col, chg);
} else {
return;
}
}
}
};
| true |
d371ee8aad6bc8c6b00402f191226c511e571d28 | C++ | thedavekwon/algo-projects | /baekjoon/1671/1671.cpp | UTF-8 | 1,742 | 2.875 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
typedef long long llong;
llong stat[1000][3];
struct MaximumFlow {
int n;
vector<vector<int>> graph;
vector<bool> check;
vector<int> pred;
MaximumFlow(int n) : n(n) {
graph.resize(n);
check.resize(n);
pred.resize(n,-1);
};
void add_Edge(int u, int v) {
graph[u].push_back(v);
}
bool dfs(int x) {
if(x==-1) return true;
for(int next : graph[x]) {
if(check[next]) continue;
check[next] = true;
if(dfs(pred[next])) {
pred[next] = x;
return true;
}
}
return false;
}
int flow() {
int ans = 0;
for(int i=0;i<n;i++) {
fill(check.begin(),check.end(),false);
if(dfs(i)) ans++;
}
for(int i=0;i<n;i++) {
fill(check.begin(),check.end(),false);
if(dfs(i)) ans++;
}
return ans;
}
};
int main() {
int n;
scanf("%d",&n);
for(int i=0;i<n;i++) {
for(int j=0;j<3;j++) {
scanf("%lld",&stat[i][j]);
}
}
MaximumFlow mf(n);
for(int i=0;i<n;i++) {
for(int j=0;j<n;j++) {
if(i==j) continue;
if(stat[i][0]>=stat[j][0] && stat[i][1]>=stat[j][1] &&
stat[i][2]>=stat[j][2]) {
if(stat[i][0]==stat[j][0] && stat[i][1]==stat[j][1] &&
stat[i][2]==stat[j][2]) {
if(i>=j) continue;
}
//cout<<i<<"->"<<j<<endl;
mf.add_Edge(i,j);
}
}
}
cout<<n-mf.flow()<<endl;
} | true |
0847300b98dd991a3da3fcfa5dd45d95651dbc20 | C++ | liumaolin/Solution | /Exercise.cpp | GB18030 | 1,855 | 3.21875 | 3 | [] | no_license | #include "Exercise.h"
void ShareManager::AddItem(const InputInfo& input)
{
if (result_map_.count(input.symbol_))
{
auto item = result_map_.find(input.symbol_);
MiddleInfo* info = item->second;
info->max_time_gap_ = max(info->max_time_gap_, input.time_ - info->last_time_);
info->last_time_ = input.time_;
info->total_qty_ += input.qty_;
info->total_amt_ += input.qty_ * input.price_;
info->max_price_ = max(info->max_price_, input.price_);
}
else
{
MiddleInfo* info = new MiddleInfo();
info->last_time_ = input.time_;
info->max_time_gap_ = 0;
info->total_qty_ = input.qty_;
info->total_amt_ = input.qty_ * input.price_;
info->max_price_ = input.price_;
result_map_[input.symbol_] = info;
}
}
int main(int argc, char* argv[])
{
if (argc != 3)
{
cerr << "θ" << endl;
return 0;
}
string inputfilename(argv[1]);
string outputfilename(argv[2]);
ifstream inputfile(inputfilename, ios::in); //inputfilename
ofstream outputfile(outputfilename, ios::out | ios::trunc); //outputfilename
while (!inputfile.eof())
{
InputInfo share_info;
string line;
inputfile >> line;
istringstream sin(line);
string field;
getline(sin, field, ',');
share_info.time_ = atoi(field.c_str());
getline(sin, field, ',');
share_info.symbol_ = field;
getline(sin, field, ',');
share_info.qty_ = atoi(field.c_str());
getline(sin, field, ',');
share_info.price_ = atoi(field.c_str());
ShareManager::Instance()->AddItem(share_info);
}
auto result_map = ShareManager::Instance()->GetResultMap();
for (auto& item : result_map)
{
outputfile << item.first << ","
<< item.second->max_time_gap_ << ","
<< item.second->total_qty_ << ","
<< item.second->total_amt_ / item.second->total_qty_ << ","
<< item.second->max_price_ << endl;
}
inputfile.close();
outputfile.close();
} | true |
f93d633ccd1313e43cc496c0fef72d8f197ea403 | C++ | dinimar/Projects | /c++/primer_plus_s_pratt/ch_13/pe_1/src/cd.cc | UTF-8 | 1,460 | 3.34375 | 3 | [
"MIT"
] | permissive | #include "cd.h"
#include <cstring>
#include <iostream>
void Cd::InitCharArrays()
{
for(size_t i=0; i<49; ++i)
performers[i]='0';
performers[49] = '\0';
for(size_t i=0; i<19; ++i)
label[i]='0';
label[19] = '\0';
}
void Cd::CopyString(char * dest, char * src)
{
// check that length of src string
// equal or less to length of dest string
// not including the null terminator
if (std::strlen(src) <= std::strlen(dest))
{
std::strcpy(dest, src);
}
else if (std::strlen(src) > std::strlen(dest))
{
std::strncpy(dest, src, std::strlen(dest)-1); // copy characters
dest[std::strlen(dest)-1] = '\0'; // the null terminator
}
}
Cd::Cd(char * sPerformers, char * sLabel, int n, double x): selections(n), playtime(x)
{
InitCharArrays();
CopyString(performers, sPerformers);
CopyString(label, sLabel);
}
Cd::Cd(): performers("No performers"), label("No label"), selections(0), playtime(0)
{}
// Cd::Cd(const Cd & cd)
// {
// strcpy(performers, cd.performers);
// strcpy(label, cd.label);
// selections = cd.selections;
// playtime = cd.playtime;
// }
void Cd::Report() const
{
std::cout << "Performers: " << performers << std::endl;
std::cout << "Label: " << label << std::endl;
std::cout << "Selections: " << selections << std::endl;
std::cout << "Playtime: " << playtime << std::endl << std::endl;
}
| true |
e7cf44156e93f33f14451c16b7454acf25ff29f9 | C++ | NicGanon/Voronoi-based-SweepLine | /source/BeachLine.h | UTF-8 | 860 | 2.671875 | 3 | [] | no_license | #pragma once
#include "BeachNode.h"
#include "EventNode.h"
class BeachLine
{
public:
BeachLine():root(NULL){};
~BeachLine(){};
void LeftRotation(BeachNode* subTree);
void RightRotation(BeachNode* subTree);
void Insert(BeachNode*pos,BeachNode* subTree);
void InsertFixup(BeachNode *newNode);
BeachNode* FindArc( Point &site);
BeachNode* BuildSubTree(BeachNode*arc, Point &site);
BeachNode* BeachLine::BuildSubBeachLine (Point &leftArcSite, Point &rightArcSite);
int GetHeight(BeachNode *subTree);
void DeleteFixup(BeachNode *fixNode);
bool Empty();
void SetRoot (BeachNode *r) { root = r; }
BeachNode* GetRoot() { return root; }
void InorderTrave() {Inorder(root);};
void PreorderTrave() {Preorder(root);};
private:
void Inorder(BeachNode *subTree);
void Preorder(BeachNode *subTree);
private:
BeachNode *root;
};
| true |
e680e2d700fe0c7e68fda81cfa2435a4c264fc26 | C++ | FormylMethionine/lab8-group1 | /string.cpp | UTF-8 | 4,967 | 3.28125 | 3 | [] | no_license | #include "./string.h"
//============================================================================
// Non member useful functions
//============================================================================
int strlen(const char* str){
int i = 0;
for (i; str[i] != '\0'; i++){}
return i;
}
int min(int arg1, int arg2){
if (arg1 < arg2){
return arg1;
} else {
return arg2;
}
}
//============================================================================
// Constructors
//============================================================================
string::string(){
tabsize_ = 0;
nchar_ = 0;
}
string::string(const string& p){
char* p_str = p.c_str();
nchar_ = min(strlen(p_str), maxsize_);
tabsize_ = nchar_;
str_ = new char[tabsize_];
for(int i = 0; i<nchar_; i++){
str_[i] = p_str[i];
}
};
string::string(const char* init){
nchar_ = min(strlen(init), maxsize_);
tabsize_ = nchar_;
str_ = new char[tabsize_];
for(int i = 0; i<nchar_; i++){
str_[i] = init[i];
}
};
//============================================================================
// Destructor
//============================================================================
string::~string(){
delete[] str_;
}
//============================================================================
// char*
//============================================================================
char* string::c_str() const{
char* ret = new char[nchar_+1];
for (int i = 0; i<nchar_; i++){
ret[i] = str_[i];
}
ret[nchar_] = '\0';
return ret;
};
//============================================================================
// size_t
//============================================================================
size_t string::size() const{
size_t ret = nchar_*sizeof(char);
return ret;
}
size_t string::length() const{
return nchar_*sizeof(char);
}
size_t string::capacity() const{
size_t ret = tabsize_*sizeof(char);
return ret;
}
size_t string::maxsize() const{
size_t ret = maxsize_;
return ret;
}
//============================================================================
// void
//============================================================================
void string::clear(){
nchar_ = 0;
tabsize_ = 0;
delete[] str_;
str_ = new char[tabsize_];
}
void string::reserve(size_t n){
int new_size = min(maxsize_, n);
char* new_str = new char[new_size];
for (int i = 0; i<nchar_; i++){
new_str[i] = str_[i];
}
delete[] str_;
str_ = new_str;
tabsize_ = new_size;
}
void string::resize(size_t n){
if (n < nchar_){
nchar_ = n;
} else if (n > nchar_ && n > tabsize_){
int new_size = min(maxsize_, n);
char* new_str = new char[new_size];
for (int i = 0; i<nchar_; i++){
new_str[i] = str_[i];
}
delete[] str_;
str_ = new_str;
tabsize_ = new_size;
}
}
//============================================================================
// bool
//============================================================================
bool string::empty() const{
if (nchar_ == 0){
return true;
} else {
return false;
}
}
//============================================================================
// Operators
//============================================================================
string& string::operator =(char c){
if (tabsize_ == 0){
delete[] str_;
str_ = new char[1];
str_[0] = c;
nchar_ = 1;
tabsize_ = 1;
return *this;
} else {
nchar_ = 1;
str_[0] = c;
return *this;
}
}
string& string::operator =(const char* s){
int size_s = strlen(s);
if (size_s >= tabsize_){
nchar_ = size_s;
for (int i = 0; i<nchar_; i++){
str_[i] = s[i];
}
} else {
nchar_ = min(maxsize_, size_s);
tabsize_ = nchar_;
delete[] str_;
str_ = new char[tabsize_];
for (int i = 0; i<nchar_; i++){
str_[i] = s[i];
}
}
return *this;
}
string& string::operator =(const string& str){
char* cstr = str.c_str();
int size_s = strlen(cstr);
if (size_s >= tabsize_){
nchar_ = size_s;
for (int i = 0; i<nchar_; i++){
str_[i] = cstr[i];
}
} else {
nchar_ = min(maxsize_, size_s);
tabsize_ = nchar_;
delete[] str_;
str_ = new char[tabsize_];
for (int i = 0; i<nchar_; i++){
str_[i] = cstr[i];
}
}
return *this;
}
//============================================================================
// Non member operators
//============================================================================
string operator +(const string& p1, const char* p2){
char* p1_c = p1.c_str();
int lenp1 = strlen(p1_c);
int lenp2 = strlen(p2);
int len = lenp1 + lenp2;
char* ret_c = new char[len];
int i = 0;
for (i; i<lenp1; i++){
ret_c[i] = p1_c[i];
}
for (i; i<len; i++){
ret_c[i] = p2[i - lenp1];
}
string ret(ret_c);
return ret;
}
string operator +(const string& s1, const string& s2){
char* s2_c = s2.c_str();
string ret = s1 + s2_c;
return ret;
}
string operator +(const string& s, const char c){
char c2[1];
c2[0] = c;
string ret = s + c2;
return ret;
}
| true |
eb7f93ebc501aafd8d6481a4e1d44fab681eb404 | C++ | kslinguistics/spellchecker | /spellchecker.cpp | UTF-8 | 2,435 | 3.078125 | 3 | [] | no_license | /********* simple spell checker *********/
/** for 2018A-Tue-02 linguistics class **/
#include <bits/stdc++.h>
struct ToLower{
char operator()(char c){
return std::tolower(c);
}
};
// calculate 'distance' between s1 and s2
int d(std::string s1, std::string s2)
{
int m = int(s1.size()), n = int(s2.size());
int dp[20][20] = {};
for(int i = 0; i != m + 1; i++){
for(int j = 0; j != n + 1; j++){
dp[i][j] = i + j;
if(i > 0) dp[i][j] = std::min(dp[i][j], dp[i - 1][j] + 1); // insertion
if(j > 0) dp[i][j] = std::min(dp[i][j], dp[i][j - 1] + 1); // deletion
if(i > 0 && j > 0){ // replacement
dp[i][j] = std::min(dp[i][j], dp[i - 1][j - 1] + 1 * (s1[i - 1] != s2[j - 1]));
}
if(i > 1 && j > 1){ // swap
if(s1[i - 1] == s2[j - 2] && s1[i - 2] == s2[j - 1]){
dp[i][j] = dp[i - 2][j - 2] + 1;
}
}
}
}
return dp[m][n];
}
// return int(log_5(n))
int logpoor5(int n){
if(n < 5) return 0;
if(n < 25) return 1;
if(n < 125) return 2;
if(n < 625) return 3;
if(n < 3125) return 4;
if(n < 15625) return 5;
if(n < 78125) return 6;
if(n < 390625) return 7;
if(n < 1953125) return 8;
if(n < 9765625) return 9;
return 10;
}
int main(void)
{
// read dictionary data
// "en_full.txt" is the first 110k items of the word
// generated from https://github.com/hermitdave/FrequencyWords/blob/master/content/2016/en/en_full.txt
// items are recorded in the form of "(word) (frequency)"
std::map<std::string, int> dict;
std::ifstream words("en_110k.txt");
std::string str;
std::vector<std::string> data;
while(getline(words, str)){
int pos = str.find(' ');
dict[str.substr(0, pos)] = logpoor5(std::atoi(str.substr(pos + 1).c_str()));
}
while(true){ // find words with correct spelling
int score = -100, score_tmp = -100, d_tmp = 0;
auto itr_max = dict.begin();
std::cin >> str;
if(dict[str] >= 3){ // the string is on the dictionary
std::cout << str << " ";
}else{ // otherwise
std::transform(str.begin(), str.end(), str.begin(), ToLower());
for (auto itr = dict.begin(); itr != dict.end(); itr++){
// variable score_tmp means
// p((correct spelling) | (wrong spelling))
d_tmp = d(str, itr->first);
score_tmp = 2 * itr->second - 7 * d_tmp;
if(score_tmp > score && itr->second != 0){
itr_max = itr;
score = score_tmp;
}
}
std::cout << itr_max->first << " ";
}
}
return 0;
}
| true |
245a18dc14d618474f0bf5e7272ce80f4e89832c | C++ | CacoFFF/XC_Core | /Src/XC_Globals.cpp | UTF-8 | 3,979 | 2.765625 | 3 | [] | no_license | /*=============================================================================
XC_Globals.cpp:
Implementation of some globals
=============================================================================*/
#include "XC_Core.h"
#include "XC_CoreGlobals.h"
#include "UnLinker.h"
//*************************************************
// Name case fixing
// Makes sure that a name has proper casing
// Helps preventing DLL bind failures
//*************************************************
XC_CORE_API UBOOL FixNameCase( const TCHAR* NameToFix)
{
FName AName( NameToFix, FNAME_Find);
if ( AName != NAME_None )
{
TCHAR* Ch = (TCHAR*) *AName;
for ( INT i=0 ; i<63 && Ch[i] ; i++ )
Ch[i] = NameToFix[i];
}
return AName != NAME_None;
}
//*************************************************
// Script stuff
// Finds a (non-state) function in a struct
// Finds a variable in a struct, increments *Found
//*************************************************
XC_CORE_API UFunction* FindBaseFunction( UStruct* InStruct, const TCHAR* FuncName)
{
FName NAME_FuncName = FName( FuncName, FNAME_Find);
if ( NAME_FuncName != NAME_None )
{
for( TFieldIterator<UFunction> Func( InStruct ); Func; ++Func )
if( Func->GetFName() == NAME_FuncName )
return (UFunction*) *Func;
}
return NULL;
}
XC_CORE_API UProperty* FindScriptVariable( UStruct* InStruct, const TCHAR* PropName, INT* Found)
{
FName NAME_PropName = FName( PropName, FNAME_Find);
if ( NAME_PropName != NAME_None )
{
for( TFieldIterator<UProperty> Prop( InStruct ); Prop; ++Prop )
if( Prop->GetFName() == NAME_PropName )
{
if ( Found )
(*Found)++;
return (UProperty*) *Prop;
}
}
return NULL;
}
//*************************************************
// String table sorting
//*************************************************
//Caching OList generates 3 more instructions at start
//But also removes two instructions on the appStricmp call
template<class T> inline void ExchangeUsingRegisters( T& A, T& B )
{
register INT Tmp;
for ( INT i=0 ; i<sizeof(FString)/sizeof(Tmp) ; i++ )
{
Tmp = ((INT*)&A)[i];
((INT*)&A)[i] = ((INT*)&B)[i];
((INT*)&B)[i] = Tmp;
}
}
//Dynamic array
XC_CORE_API void SortStringsA( TArray<FString>* List)
{
SortStringsSA( (FString*) List->GetData(), List->Num() );
}
//Static array, although not fully optimized for speed
XC_CORE_API void SortStringsSA( FString* List, INT ArrayMax)
{
INT iTop=1;
for ( INT i=1 ; i<ArrayMax ; i=++iTop )
/* {
//Optimized for long sorts, test later
while ( appStricmp( *List[iTop], *List[i-1]) < 0 )
if ( --i == 0 )
break;
if ( i != iTop )
{
INT* Ptr = (INT*) &List[iTop];
INT Buffer[3] = { Ptr[0], Ptr[1], Ptr[2] };
appMemmove( List + i + 1, List + i, (iTop-i)*3 );
Ptr = (INT*) &List[i];
Ptr[0] = Buffer[0];
Ptr[1] = Buffer[1];
Ptr[2] = Buffer[2];
}
}*/
//Optimized for short sorts
while ( appStricmp( *List[i], *List[i-1]) < 0 )
{
//Atomically swap data (no FArray reallocs)
//Compiler does a nice job here
ExchangeUsingRegisters( List[i], List[i-1] );
/* INT* Ptr = (INT*) &List[i];
INT iStore = *Ptr;
*Ptr = *(Ptr-3);
*(Ptr-3) = iStore;
iStore = *(Ptr+1);
*(Ptr+1) = *(Ptr-2);
*(Ptr-2) = iStore;
iStore = *(Ptr+2);
*(Ptr+2) = *(Ptr-1);
*(Ptr-1) = iStore;*/
//Bottom index, forced leave
if ( i == 1 )
break;
i--;
}
}
//*************************************************
// Enhanced package file finder
// Strict loading by Name/GUID combo for net games
//*************************************************
inline FGenerationInfo::FGenerationInfo( INT InExportCount, INT InNameCount )
: ExportCount(InExportCount), NameCount( InNameCount)
{
}
XC_CORE_API FPackageFileSummary LoadPackageSummary( const TCHAR* File)
{
guard(LoadPackageSummary);
FPackageFileSummary Summary;
FArchive* Ar = GFileManager->CreateFileReader( File);
if ( Ar )
{
*Ar << Summary;
delete Ar;
}
return Summary;
unguard;
}
| true |
05a839864ac75708c3ae2d963a692cf1261cdf67 | C++ | mbourand/webserv | /incs/Request.hpp | UTF-8 | 1,552 | 2.59375 | 3 | [] | no_license | #ifndef REQUEST_HPP
#define REQUEST_HPP
#include <map>
#include <string>
#include "Logger.hpp"
#include "Methods.h"
#include "Headers.h"
#include "Factory.hpp"
#include "ConfigContext.hpp"
#include "URL.hpp"
#include <vector>
class Request
{
public:
typedef std::vector<Header*> HeadersVector;
public:
std::string _raw;
IMethod* _method;
URL _url;
std::string _protocolVersion;
HeadersVector _headers;
std::string _body;
size_t _content_length;
size_t _max_body_size;
int _error_code;
int _port;
bool _header_section_finished;
bool _url_finished;
bool _finished_parsing;
bool _chunked;
size_t _parse_start;
private:
bool header_line_valid(const std::string& line) const;
bool is_next_paragraph(size_t i) const;
size_t count_concurrent_occurences(size_t index, char c) const;
bool is_valid_URI(const std::string& uri) const;
std::string dechunk(const std::string& str);
void parse_method();
void parse_uri();
void parse_protocol_version();
bool parse_headers();
void parse_body();
public:
Request();
Request(int port);
Request(const Request& other);
virtual ~Request();
Request& operator=(const Request& other);
bool append(const std::string& raw);
void parse();
bool isfinished(void) const;
bool operator==(const Request& other) const;
bool operator!=(const Request& other) const;
std::string getHeaderValue(const std::string& name) const;
friend std::ostream& operator<<(std::ostream& out, const Request& request);
};
#endif
| true |
6a38476c07609102be44b8b5bcc938e8321519dd | C++ | Niraka/ThirdYearProject | /Include/ServerDatabase/Database.h | UTF-8 | 4,828 | 3.203125 | 3 | [] | no_license | /**
ONLY SUPPORTS WINDOWS!
@author Nathan */
#ifndef DATABASE_H
#define DATABASE_H
#include <map>
#include <vector>
#include <string>
#include <iostream>
#include "StoreLoader.h"
#include "StoreAccessor.h"
class Database
{
private:
enum class StoreStates
{
MOUNTED, // The Store is detected but no loaded
LOADED // The Store has been loaded in to memory
};
enum DatabaseMessages
{
DB_STARTING_UP,
DB_STARTED,
DB_SHUTTING_DOWN,
DB_STOPPED,
DB_LOADING_STORE,
DB_LOADED_STORE,
DB_SAVING_STORE,
DB_SAVED_STORE,
DB_DELETING_STORE,
DB_DELETED_STORE,
DB_CREATING_STORE,
DB_CREATED_STORE,
DB_MOUNTING_STORES,
DB_MOUNTED_STORE,
DB_STORE_NAME_IN_USE,
DB_STORE_NAME_ILLEGAL_CHARACTERS,
DB_SAVE_FAILED,
DB_LOAD_FAILED,
DB_DELETE_FAILED,
DB_FILESYSTEM_UNREACHABLE
};
std::map<std::string, std::pair<StoreStates, Store>> m_stores;
bool m_bSilentMode;
static const int m_iNumIllegalChars = 8;
char m_illegalChars[8];
StoreLoader m_storeLoader;
FileUtils m_fileUtils;
std::string m_sDatabaseDirectory;
static bool m_bInstanceExists;
static Database* m_instance;
void scanForTables();
void printMessage(DatabaseMessages msg, std::string arg1 = "", std::string arg2 = "");
protected:
public:
/**
Returns a pointer to the single Database instance. The instance is created if it did not already exist.
Ensure the database has been initialised before calling any further functions.
@return A pointer to the Database instance */
static Database* getInstance();
/**
Enables or disables console output for database errors and messages. Defaults to disabled.
@param bEnabled True to enable, false to disable */
void setSilentModeEnabled(bool bEnabled);
/**
Initialises the Database. This function must be called before operating on the database to ensure file IO
is working.
@return True if the database correctly started up, false otherwise */
bool init();
public:
Database();
~Database();
/**
Verifies the directory structure of the Database, correcting issues as they are
found.
@return True if the structure was in good standing, false otherwise */
bool verifyDatabaseStructure();
/**
Mounts all Stores in the database directory, effectively preventing them from being
overwritten by dynamically allocated Stores. */
void mountStores();
/**
Verifies a name meets a set of naming standards.
@param sName The name to verify
@return True if the name met the naming standards, false if it did not */
bool verifyName(const std::string& sName);
/**
Saves all Stores to disk. */
void saveAllStores();
/**
Loads all Stores in to memory. */
void loadAllStores();
/**
Unloads all Stores from memory. */
void unloadAllStores();
/**
Loads a Store in to memory. This function will fail if the Store did not exist or the
filesystem was innaccessible for some reason.
@param sStoreName The name of the store to load
@return True if the Store loaded successfully, false otherwise */
bool loadStore(const std::string& sStoreName);
/**
Saves a Store to disk. This function will fail if the Store did not exist or the filesystem
was innaccessible for some reason.
@param sStoreName The name of the Store to save
@return True if the Store successfully saved, false otherwise */
bool saveStore(const std::string& sStoreName);
/**
Unloads a Store from memory. THIS DOES NOT SAVE THE STORE. This function will fail if the
Store did not exist or was not loaded in to memory.
@param sStoreName The name of the Store to unload */
bool unloadStore(const std::string& sStoreName);
/**
Creates a Store with the given name. Store names must be unique.
@param sStoreName The name to assign the Store
@return True if the Store was successfully created, false if it was not */
bool createStore(const std::string& sStoreName);
/**
Deletes a Store with the given name. This function is capable of deleting
Stores that are not loaded in to memory
@param sStoreName The name of the Store to delete
@return True if the Store was successfully delete, false if it was not */
bool deleteStore(const std::string& sStoreName);
/**
Queries the existence of a Store with the given name.
@param sStoreName The name of the Store to search for
@return True if a Store with the given name existed, false if it did not */
bool storeExists(const std::string& sStoreName);
/**
Creates a StoreAccessor for the Store with the given name. If no such Store existed, the
returned accessor will be valid but functionally dead.
@param sStoreName The name of the Store to access
@return An accessor for the Store with the given name */
StoreAccessor getStoreAccessor(const std::string& sStoreName);
};
#endif | true |
59bbd5c4ea1ede7a0f09ba6dcf2b85bfdab7d69e | C++ | danchesler/Problems | /rangeSumBSTwithDFSandBFS.cpp | UTF-8 | 1,277 | 3.640625 | 4 | [] | no_license | // By Bernoulli on LeetCode
// DFS
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
if(root == nullptr)
return 0;
int sum = 0;
if(root->val >= L && root->val <= R){
sum+=root->val+rangeSumBST(root->left, L, R)+rangeSumBST(root->right, L, R);
}else if(root->val < L){
sum+=rangeSumBST(root->right, L, R);
}else if(root->val > R){
sum+=rangeSumBST(root->left, L, R);
}
return sum;
}
};
//BFS
class Solution {
public:
int rangeSumBST(TreeNode* root, int L, int R) {
if(root == nullptr)
return 0;
int sum = 0;
queue<TreeNode*> q;
q.push(root);
TreeNode* node;
while(q.size()){
node = q.front();q.pop();
if(node == nullptr)
continue;
if(node->val >= L && node->val <= R){
sum+=node->val;
q.push(node->left);
q.push(node->right);
}else if(node->val < L){
q.push(node->right);
}else{
q.push(node->left);
}
}
return sum;
}
}; | true |
0c8933326651fe9bb7cc46cebc465bcbc2b87b98 | C++ | AndreNolliViana/Kevaomilenar | /FINAL/IBGE/main.cpp | UTF-8 | 848 | 3.21875 | 3 | [] | no_license | #include <iostream>
using namespace std;
int main()
{
int d, cd;
int h, m;
float sm, sh, c, cT, smT, shT = 0.0;
cout << "Dias trabalhados: "; cin >> d;
cout << "Cota diaria: "; cin >> cd;
for(int z=0; z < d; z++){
cout << "Dia " << z+1 << endl;
cin >> h >> m;
while ( h!=-1 && m!=-1){
if(c < cd){
c = c + 1;
sh = sh + h;
sm = sm + m;}
cT = cT + c;
smT= smT + sm;
shT = shT + sh;
cin >> h >> m;
c, sm, sh= 0;
}
}
cout << "Total de casas: " << cT << endl;
cout << "Total de homens: " << shT << endl;
cout << "Total de mulheres: " << smT << endl;
cout << "Media de homens por casa: " << shT/cT << endl;
cout << "Media de mulhreses por casa: "<< smT/cT << endl;
return 0;
}
| true |
aa1fc8aa5975fdd6cf4393ae3c14047847f4a827 | C++ | nhthucdtvt/CPP | /1000btC_Cpp/s2/source_442.cpp | UTF-8 | 6,546 | 2.65625 | 3 | [] | no_license |
#include "stdio.h"
#include "conio.h"
#include "time.h"
#include "Windows.h"
struct hocsinh
{
char HoTen[30];
float Toan;
float Van;
float TrungBinh;
};
typedef struct hocsinh HOCSINH;
struct node
{
HOCSINH Data;
struct node*pNext;
};
typedef struct node NODE;
struct list
{
NODE*pHead;
NODE*pTail;
};
typedef struct list LIST;
void INit(LIST &l)
{
l.pHead=NULL;
l.pTail=NULL;
}
NODE*getnode(HOCSINH x)
{
NODE*p;
p=new NODE;
if(p==NULL)
return NULL;
p->Data=x;
p->pNext=NULL;
return p;
}
void AddTail(LIST &l,NODE*new_ele)
{
if(l.pHead==NULL)
{
l.pHead=new_ele;
l.pTail=l.pHead;
}
else
{
l.pTail->pNext=new_ele;
l.pTail=new_ele;
}
}
void InPut(LIST &l)
{
int n;
quaylai:printf("\nNhap vao so luong hoc sinh:");
scanf("%d",&n);
if(n<0)
{
printf("\nSo luong hoc sinh khong hop le!Xin vui long nhap lai!");
goto quaylai;
}
INit(l);
for(int i=1;i<=n;i++)
{
HOCSINH x;
printf("\n>>>>>>>>> Nhap Vao Du Lieu Hoc Sinh Thu %d <<<<<<<<<<<<\n",i);
fflush(stdin);
printf("\nNhap vao Ho Ten:");
gets(x.HoTen);
do{
printf("\nNhap vao diem Toan:");
scanf("%f",&x.Toan);
if(x.Toan<0||x.Toan>10)
{
printf("\nDiem mon Toan khong hop le!Xin vui long nhap lai!");
}
}while(x.Toan<0||x.Toan>10);
do{
printf("\nNhap vao diem Van:");
scanf("%f",&x.Van);
if(x.Van<0||x.Van>10)
{
printf("\nDiem mon Van khong hop le!Xin vui long nhap lai!");
}
}while(x.Van<0||x.Van>10);
x.TrungBinh=(x.Toan+x.Van)/2;
NODE*p=getnode(x);
AddTail(l,p);
}
}
void OutPut(LIST l)
{
printf("\tHo Va Ten \t");
printf("Diem Toan\t\t");
printf("Diem Van\t\t");
printf("Diem TB \n\n");
for(NODE*p=l.pHead;p!=NULL;p=p->pNext)
{
printf("%20s ",p->Data.HoTen);
printf("%10.2f ",p->Data.Toan);
printf("%20.2f ",p->Data.Van);
printf("%22.2f \n\n",p->Data.TrungBinh);
}
}
void LietKeCacHocSinhCoDiemToanNhoHon5(LIST l)
{
NODE*pNode;
printf("\n>>>>>>>>> Danh Sach Cac Hoc Sinh Co Diem Toan < 5 <<<<<<<<<\n");
printf("\n");
printf("\tHo Va Ten \t");
printf("Diem Toan\t\t");
printf("Diem Van\t\t");
printf("Diem TB \n\n");
for(pNode=l.pHead;pNode!=NULL;pNode=pNode->pNext)
{
if(pNode->Data.Toan<5)
{
printf("%20s ",pNode->Data.HoTen);
printf("%10.2f ",pNode->Data.Toan);
printf("%20.2f ",pNode->Data.Van);
printf("%22.2f \n\n",pNode->Data.TrungBinh);
}
}
}
void DemSoLuongHocSinhCoDiemToanVaDiemVanLonHon8(LIST l)
{
NODE*pNode;
int dem=0;
for(pNode=l.pHead;pNode!=NULL;pNode=pNode->pNext)
{
if(pNode->Data.Toan>8&&pNode->Data.Van>8)
{
dem++;
}
}
printf("\nSo Luong Cac Hoc Sinh Co Diem Toan & Van > 8 La:%d",dem);
}
void HamSapXepGiamDanTheoDiemTrungBinh(LIST &l)
{
NODE *p,*q;
HOCSINH temp;
for(p=l.pHead;p!=NULL;p=p->pNext)
{
for(q=p->pNext;q!=NULL;q=q->pNext)
{
if(p->Data.TrungBinh<q->Data.TrungBinh)
{
temp=p->Data;
p->Data=q->Data;
q->Data=temp;
}
}
}
}
void SapXepDanhSachCacHocSinhGiamDanTheoDiemTrungBinh(LIST l)
{
HamSapXepGiamDanTheoDiemTrungBinh(l);
printf("\n>>>>>>>>>>> Danh Sach Cac Hoc Sinh Sap Giam Dan Theo Diem Trung Binh <<<<<<<<<<\n");
OutPut(l);
}
// Hàm tăng kích cỡ của khung CMD .
void resizeConsole(int width, int height)
{
HWND console = GetConsoleWindow();
RECT r;
GetWindowRect(console, &r);
MoveWindow(console, r.left, r.top, width, height, TRUE);
}
// Hàm lấy tọa độ vị trí .
void gotoxy(int x,int y)
{
HANDLE hstdout=GetStdHandle(STD_OUTPUT_HANDLE);
COORD position = {x,y};
SetConsoleCursorPosition(hstdout,position);
}
// Hàm tô màu .
void textcolor(int x)
{
HANDLE mau;
mau=GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(mau,x);
}
// Hàm đồ họa cho tên tác giả .
void NguyenVietNamSon()
{
textcolor(14); // Tô màu vàng .
printf("\n--------------------------------------------------------------------------------\n");
printf("\n\t\t\tDesigned By : Nguyen Viet Nam Son \n");
printf("\n--------------------------------------------------------------------------------\n");
textcolor(7); // Trả lại màu chữ bình thường .
}
void Thanks()
{
system("cls"); // Xóa đi mọi dữ liệu đã làm trước đó .
srand(time(NULL));
for(int j=1;j<=20;j++)
{
int color=rand()%15+1; // Khởi tạo màu chạy ngẫu nhiên trong đoạn thang màu [1,15].
Sleep(300);
gotoxy(j-1,40);
printf(" ");
gotoxy(j,40);
textcolor(color);
printf("\nThanks You For Using The Program ! Goodbye And See You Later !\n"); // Khi người dùng thoát chương trình sẽ hiển thị lời chào !
}
textcolor(15);
getch();
gotoxy(3,42);
}
void MeNu()
{
resizeConsole(800,600); // Tăng kích cỡ của khung CMD lên thành chiều rộng 800,chiều cao 600 .
LIST lst;
int w;
printf("\n");
quaylai:NguyenVietNamSon();
InPut(lst);
printf("\n>>>>>>>>>>>>>>>>>>>>> Xuat Ra Danh Sach Cac Hoc Sinh <<<<<<<<<<<<<<<<<<<<<<<<\n");
printf("\n");
printf("\n");
OutPut(lst);
printf("\n");
do{
// Bảng MeNu đưa ra cho người dùng các sự lựa chọn .
textcolor(2); // Tô màu xanh nhạt cho MeNu
printf("\n-------------------------------------MeNu---------------------------------------\n");
printf("\n");
printf("\n 1.Liet Ke Cac Hoc Sinh Co Diem Toan < 5 ");
printf("\n");
printf("\n 2.Dem So Luong Hoc Sinh Co Diem Toan & Diem Van > 8 ");
printf("\n");
printf("\n 3.Sap Xep Lai Danh Sach Hoc Sinh Giam Dan Theo Diem Trung Binh ");
printf("\n");
printf("\n 4.Cap Nhat Lai Danh Sach Cac Hoc Sinh ");
printf("\n");
printf("\n 0.Thoat chuong trinh ");
printf("\n");
printf("\n--------------------------------------------------------------------------------\n");
printf("\n");
textcolor(7); // Trả về lại màu bình thường .
printf("\nChon:");
scanf("%d",&w);
printf("\nKet qua:\n");
printf("\n");
// Cấu trúc switch-case .
switch(w)
{
case 1:
{
LietKeCacHocSinhCoDiemToanNhoHon5(lst);
break;
}
case 2:
{
DemSoLuongHocSinhCoDiemToanVaDiemVanLonHon8(lst);
break;
}
case 3:
{
SapXepDanhSachCacHocSinhGiamDanTheoDiemTrungBinh(lst);
break;
}
case 4:
{
goto quaylai;
break;
}
case 0:
{
Thanks();
}
}
}while(w!=0);
}
void main()
{
MeNu();
}
| true |
d95df13da817cfc99897f0a228ac44280220c649 | C++ | Aditya1788/DataStructuresAndAlgorithms | /Amazon-Geeks/Arrays/InfiniteGridProblem.cpp | UTF-8 | 805 | 3.703125 | 4 | [] | no_license | // Important: The assumption made in this question is that the length taken through the hypotenuse is same as taken
// through the x or y axes i.e 1 unit for a unit square grid
// Problem Link:
//https://www.geeksforgeeks.org/minimum-steps-needed-to-cover-a-sequence-of-points-on-an-infinite-grid/
#include<bits/stdc++.h>
using namespace std;
struct col{
int a;
int b;
};
int shortestPath(col x, col y){
int dx = abs(x.a - y.a);
int dy = abs(x.b - y.b);
return max(dx,dy);
}
int call(col arr[], int s){
int distance = 0;
for(int i = 0; i< s-1;i++){
distance += shortestPath(arr[i],arr[i+1]);
}
return distance;
}
int main(){
col arr[] = { { 4, 6 }, { 1, 2 }, { 4, 5 }, { 10, 12 } };
int s = sizeof(arr)/sizeof(arr[0]);
cout << call(arr,s) << endl;
return 0;
}
| true |
708412dbc80e9bfd5b1c2fc24d556c2bde01eb92 | C++ | personaluser01/Algorithm-problems | /20130510/tabletraveling/GenerateSpecialTestType1.cpp | UTF-8 | 659 | 2.578125 | 3 | [] | no_license | #include<cstdio>
#include<ctime>
#include<cstdlib>
#include<algorithm>
using namespace std;
int a[5007][5007];
int main() {
int m = 1000, n = 1000;
int p = 1;
for(int j = 0; j < n; ++j) a[0][j] = p++;
for(int i = 1; i < m; ++i) a[i][n-1] = p++;
for(int i = 1; i < m; ++i)
for(int j = 0; j < n-1; ++j)
a[i][j] = p++;
for(int swp = 0; swp < 3*m*n; ++swp) {
int r1 = rand() % (m-1) + 1, r2 = rand() % (m-1) + 1, c1 = rand() % (n-1), c2 = rand() % (n-1);
swap(a[r1][c1], a[r2][c2]);
}
printf("%d %d\n", m, n);
for(int i = 0; i < m; ++i) {
for(int j = 0; j < n; ++j) {
if(j) printf(" ");
printf("%d", a[i][j]);
}
printf("\n");
}
}
| true |
65475b26e62dbd7b1d8dba8c4919244afb8b8d4f | C++ | ondrej-vesely/GEO1015-hw2 | /c++/src/DatasetASC.cpp | UTF-8 | 1,973 | 3.21875 | 3 | [] | no_license | #include <string>
#include <iostream>
#include <fstream>
#include "DatasetASC.h"
DatasetASC::DatasetASC(std::string ifile) {
std::cout << "Reading file: " << ifile << std::endl;
std::ifstream infile(ifile.c_str(), std::ifstream::in);
if (!infile)
{
std::cerr << "Input file not found." << std::endl;
validity = false;
}
validity = true;
std::string tmp;
//-- ncols
infile >> tmp;
infile >> ncols;
//-- nrows
infile >> tmp;
infile >> nrows;
//-- xllcorner
infile >> tmp;
infile >> xllcorner;
//-- yllcorner
infile >> tmp;
infile >> yllcorner;
//-- cellsize
infile >> tmp;
infile >> cellsize;
//-- nodata_value
infile >> tmp;
infile >> nodata_value;
//-- read the data in a 2D array (here a vector or vector)
double v;
//-- read each row/line
for (int i = 0; i < nrows; i++) {
std::vector<double> onerow;
for (int j = 0; j < ncols; j++) {
infile >> v;
onerow.push_back(v);
}
data.push_back(onerow);
}
// std::cout << ds.data[1][3] << std::endl;
infile.close();
}
//-- returns centre of the pixel from (row, col)
//-- origin is top-left, 0-based index
//-- false if outside
bool DatasetASC::rc2xy(int row, int col, double& x, double& y)
{
if ( (row < 0) || (row > (nrows - 1)) ) {
return false;
}
if ( (col < 0) || (col > (ncols - 1)) ) {
return false;
}
x = xllcorner + (col * cellsize) + (cellsize / 2);
y = yllcorner + ((nrows - 1 - row) * cellsize) + (cellsize / 2);
return true;
}
//-- returns the row/col in the variables passed by reference
//-- if xy inside the ds, then true; otherwise false
bool DatasetASC::xy2rc(double x, double y, int& row, int& col){
if ( (x < xllcorner) || (x > (xllcorner + (ncols * cellsize))) ) {
return false;
}
if ( (y < yllcorner) || (y > (yllcorner + (nrows * cellsize))) ) {
return false;
}
col = (x - xllcorner) / cellsize;
row = nrows - ((y - yllcorner) / cellsize);
return true;
}
| true |
e00c1f9a8b8a24114f9705a2efd02988cbebf9d9 | C++ | viktorb1/Protein-Sequence-Comparison | /program/Blosum.h | UTF-8 | 349 | 2.546875 | 3 | [] | no_license | #ifndef _BLOSUM_H_
#define _BLOSUM_H_
#include <unordered_map>
class Blosum {
const static int num_aa = 20;
// stores the blosum62 matrix
double blosum[num_aa][num_aa];
// used to retrieve column/row for amino acid
unordered_map<char, int> aarowcol;
public:
Blosum();
double getValue(char aa1, char aa2);
};
#endif | true |
d9d03a43870692e0f0207b9a996aa48ac3900f2a | C++ | llebron/arduino | /libraries/Potentiometer/Potentiometer.h | UTF-8 | 896 | 3.03125 | 3 | [
"BSD-2-Clause"
] | permissive | /**
Potentiometer.h
Larry LeBron
A simple library for a potentiometer connected between 5V, ground and an an analog input
*/
#include "Arduino.h"
#ifndef POTENTIOMETER_H
#define POTENTIOMETER_H
const int MAX_POT_VALUE = 1023;
// only considered a value change if the jump is at least of this delta
// prevents noise from random fluctuation
const int MIN_CHANGE_DELTA = 11;
class Potentiometer {
public:
Potentiometer(uint8_t potPin);
//update the pot, must be called every loop for best accuracy
void update();
//returns true if the pot changed this update
bool valChangedThisUpdate();
// returns the percent of the pot, from 0 to 1 (0, MAX_POT_VALUE)
float getPercentVal();
private:
uint8_t potPin; //the pot pin
int lastAcknowledgedReading; // the last pot reading acknowledged as actual input
bool changedThisUpdate = false; // did the pot change this update?
};
#endif
| true |
fbfaf714cd5c91bda4c91ce85e92288bc89b149d | C++ | CaterTsai/C_Ballon | /src/BallBoid.h | UTF-8 | 3,748 | 2.671875 | 3 | [] | no_license | #ifndef BALL_BOID
#define BALL_BOID
#include "ofMain.h"
class BallBoid{
public:
static float REFLECT;
ofVec2f location;
BallBoid(float x_,float y_,float rad_,int tag_){
location=ofVec2f(x_,y_);
acc=ofVec2f(0,0);
maxSpeed=12.0;
maxForce=5.0;
shrinking=false;
dest_shrink=1;
vel=ofVec2f(maxSpeed,0);
vel.rotate(ofRandom(TWO_PI));
tag=tag_;
radius=rad_;
}
void flock(vector<BallBoid> &boids){
ofVec2f sep_sum=ofVec2f(0);
ofVec2f ali_sum=ofVec2f(0);
ofVec2f coh_sum=ofVec2f(0);
int sep_count=0,ali_count=0,coh_count=0;;
int mboid=boids.size();
for(int i=0;i<mboid;++i){
BallBoid other=boids[i];
ofVec2f sep=separate(other);
ofVec2f ali=align(other);
ofVec2f coh=cohesion(other);
if(sep.length()>0){
sep_sum+=sep;
sep_count++;
}
if(ali.length()>0){
ali_sum+=ali;
ali_count++;
}
if(coh.length()>0){
coh_sum+=coh;
coh_count++;
}
}
ofVec2f sep_steer=ofVec2f(0);
if(sep_count>0){
sep_sum/=sep_count;
//sep_sum.scale(maxForce);
sep_steer=sep_sum-vel;
sep_steer.limit(maxForce);
}
ofVec2f ali_steer=ofVec2f(0);
if(ali_count>0){
ali_sum/=sep_count;
//ali_sum.scale(maxForce);
ali_steer=ali_sum-vel;
ali_steer.limit(maxForce);
}
ofVec2f coh_steer=ofVec2f(0);
if(coh_count>0){
coh_sum/=coh_count;
//coh_sum.scale(maxForce);
coh_steer=coh_sum-vel;
coh_steer.limit(maxForce);
}
sep_steer*=force_com.x;
ali_steer*=force_com.y;
coh_steer*=force_com.z;
applyForce(sep_steer);
applyForce(ali_steer);
applyForce(coh_steer);
}
void update(){
// println(acc);
if(location.x<0) acc.x+=REFLECT;
if(location.x>cCANVAS_WIDTH) acc.x-=REFLECT;
if(location.y<0) acc.y+=REFLECT;
if(location.y>cCANVAS_HEIGHT) acc.y-=REFLECT;
ofVec2f center=ofVec2f(cCANVAS_WIDTH/2,cCANVAS_HEIGHT/2);
/*if(to_center.length()>orig_shrink*dest_shrink) location=center+to_center*ofRandom(.8,1);
else shrinking=false;*/
if(shrinking){
ofVec2f to_center=center-location;
to_center.scale(maxForce*dest_shrink);
acc+=to_center;
if(dest_shrink<1) dest_shrink+=.05;
}else{
if(dest_shrink<1){
ofVec2f out_center=location-center;
out_center.scale(maxForce*(1-dest_shrink));
acc+=out_center;
dest_shrink+=.02;
}
}
vel+=acc;
vel.limit(maxSpeed);
acc*=0;
location+=vel;
}
void draw(){
ofSetColor(0,0,255);
ofFill();
ofEllipse(location.x,location.y,radius,radius);
}
void setForce(ofVec3f set_force){
force_com=set_force;
}
void setShrinking(bool set_shrink){
shrinking=set_shrink;
dest_shrink=ofRandom(0.01,0.1);
//orig_shrink=location.distance(ofVec2f(ofGetWidth()/2,ofGetHeight()/2));
}
private:
ofVec2f vel;
ofVec2f acc;
float maxSpeed;
float maxForce;
vector<int> nbs;
float dest_shrink;//=random(0.1,0.8);
bool shrinking;//=false;
float orig_shrink;
ofVec3f force_com;//=new PVector(0.1,0.1,0.1);
int tag;
float radius;
void applyForce(ofVec2f force){
acc+=force;
}
ofVec2f separate(BallBoid& other){
float d=location.distance(other.location);
if(d>60) return ofVec2f(0);
ofVec2f diff=location-other.location;
diff.normalize();
// diff.div(d);
return diff;
}
ofVec2f cohesion(BallBoid& other){
float d=location.distance(other.location);
if(other.tag!=tag) d*=.2;
if(d<200) return ofVec2f(0);
ofVec2f diff=other.location-location;
diff.normalize();
return diff;
}
ofVec2f align(BallBoid& other){
if(other.tag!=tag) return ofVec2f(0);
float d=location.distance(other.location);
if(other.tag!=tag) d*=.5;
if(d>150) return ofVec2f(0);
return other.vel;
}
};
#endif | true |
799f147f6b7096461e74f328a793867502883a8c | C++ | christopherwade/PRG_422 | /Week1/PRG423/main.cpp | UTF-8 | 1,167 | 3 | 3 | [] | no_license | #include <stdio.h>
#include <cstdio>
#include <cstring>
#include <iostream>
#include "BubbleSort.hpp"
#include "Test.hpp"
#include "Node.hpp"
#include "LinkedList.hpp"
using namespace std;
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
//void BubbleSort(int array[], int x)
//{
// int i, k;
// bool swapped;
//
// for (i = 0; i < x - 1; i++)
// {
// swapped = false;
// for (k = 0; k < x - i - 1; k++)
// {
// if (array[k] > array[k + 1])
// {
// swap(&array[k], &array[k + 1]);
// swapped = true;
// }
// }
//
// if (swapped == false)
// break;
// }
//}
//void printArray(int ar[], int size)
//{
// int i;
// for (i = 0; i < size; i++)
// {
// cout << ar[i] << endl;
// }
//
//}
int main(int argc, char* argv[])
{
/*int array[] = { 15,2,4,-1,0 };
int a = sizeof(array) / sizeof(array[0]);
BubbleSort(array, a);
cout << "Sorted array: \n" << endl;
printArray(array, a);*/
//test01();
//test02();
Node *n = new Node();
n->Unit_Test();
LinkedList Lista;
Lista.Unit_Test();
char c;
scanf("%c", &c);
return 0;
}
| true |
2ee3f0090ed165088b335fda864887198965e296 | C++ | uilianries/config | /include/tao/config/internal/phase2_add.hpp | UTF-8 | 5,524 | 2.5625 | 3 | [
"MIT"
] | permissive | // Copyright (c) 2018-2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/config/
#ifndef TAO_CONFIG_INTERNAL_PHASE2_ADD_HH
#define TAO_CONFIG_INTERNAL_PHASE2_ADD_HH
#include <utility>
#include "concat.hpp"
#include "entry.hpp"
#include "format.hpp"
#include "value_traits.hpp"
namespace tao::config::internal
{
struct addition_error
{
json::type l;
json::type r;
};
inline void phase2_boolean_add( json::basic_value< value_traits >& l, const json::basic_value< value_traits >& r )
{
switch( r.type() ) {
case json::type::BOOLEAN:
l.assign( l.get_boolean() || r.get_boolean() );
break;
default:
throw addition_error{ l.type(), r.type() };
}
}
inline void phase2_number_add( json::basic_value< value_traits >& l, const json::basic_value< value_traits >& r )
{
if( l.is_double() || r.is_double() ) {
if( l.is_double() && r.is_double() ) {
l.assign( l.get_double() + r.get_double() );
return;
}
}
else if( l.is_signed() ) {
if( r.is_signed() ) {
l.assign( l.get_signed() + r.get_signed() );
return;
}
if( r.is_unsigned() ) {
l.assign( l.get_signed() + std::int64_t( r.get_unsigned() ) );
return;
}
}
else if( l.is_unsigned() ) {
if( r.is_signed() ) {
l.assign( std::int64_t( l.get_unsigned() ) + r.get_signed() );
return;
}
if( r.is_unsigned() ) {
l.assign( l.get_unsigned() + r.get_unsigned() );
return;
}
}
throw addition_error{ l.type(), r.type() };
}
inline void phase2_string_add( json::basic_value< value_traits >& l, const json::basic_value< value_traits >& r )
{
switch( r.type() ) {
case json::type::STRING:
l.get_string() += r.get_string();
break;
case json::type::STRING_VIEW:
l.get_string() += r.get_string_view();
break;
default:
throw addition_error{ l.type(), r.type() };
}
}
inline void phase2_binary_add( json::basic_value< value_traits >& l, const json::basic_value< value_traits >& r )
{
switch( r.type() ) {
case json::type::BINARY:
l.get_binary().insert( l.get_binary().end(), r.get_binary().begin(), r.get_binary().end() );
break;
case json::type::BINARY_VIEW:
l.get_binary().insert( l.get_binary().end(), r.get_binary_view().begin(), r.get_binary_view().end() );
break;
default:
throw addition_error{ l.type(), r.type() };
}
}
inline void phase2_array_add( json::basic_value< value_traits >& l, json::basic_value< value_traits >&& r )
{
switch( r.type() ) {
case json::type::ARRAY:
l.get_array().reserve( l.get_array().size() + r.get_array().size() );
for( auto&& i : r.get_array() ) {
l.emplace_back( std::move( i ) );
}
break;
default:
throw addition_error{ l.type(), r.type() };
}
}
inline void phase2_value_add( json::basic_value< value_traits >& l, json::basic_value< value_traits >&& r );
inline void phase2_object_add( json::basic_value< value_traits >& l, json::basic_value< value_traits >&& r )
{
switch( r.type() ) {
case json::type::OBJECT:
for( auto&& i : r.get_object() ) {
if( const auto p = l.get_object().try_emplace( i.first, std::move( i.second ) ); !p.second ) {
phase2_value_add( p.first->second, std::move( i.second ) );
}
}
break;
default:
throw addition_error{ l.type(), r.type() };
}
}
inline void phase2_value_add( json::basic_value< value_traits >& l, json::basic_value< value_traits >&& r )
{
if( r.is_null() ) {
return;
}
if( l.is_null() || r.clear ) {
l = std::move( r );
return;
}
switch( l.type() ) {
case json::type::NULL_:
assert( false );
case json::type::BOOLEAN:
phase2_boolean_add( l, r );
break;
case json::type::SIGNED:
case json::type::UNSIGNED:
case json::type::DOUBLE:
phase2_number_add( l, r );
break;
case json::type::STRING:
case json::type::STRING_VIEW:
phase2_string_add( l, r );
break;
case json::type::BINARY:
case json::type::BINARY_VIEW:
phase2_binary_add( l, r );
break;
case json::type::ARRAY:
phase2_array_add( l, std::move( r ) );
break;
case json::type::OBJECT:
phase2_object_add( l, std::move( r ) );
break;
default:
assert( false );
}
}
inline void phase2_add( json::basic_value< value_traits >& l, json::basic_value< value_traits >&& r )
{
try {
phase2_value_add( l, std::move( r ) );
}
catch( const addition_error& e ) {
assert( r.position );
throw pegtl::parse_error( format( __FILE__, __LINE__, "inconsistent types in addition", { { "left", e.l }, { "right", e.r } } ), *r.position ); // l.position?
}
}
} // namespace tao::config::internal
#endif
| true |
a0df47c0653eb6e99ad6bf381158e8d4df423263 | C++ | LibertAntoine/Minecraft_editor | /Minecraft/src/GraphicEngine/Texture.cpp | UTF-8 | 2,306 | 2.6875 | 3 | [] | no_license | #include "Texture.h"
#include "stb_image/stb_image.h"
#include "GLerror.h"
Texture::Texture()
:m_LocalBuffer(nullptr),
m_Width(0), m_Height(0), m_BPP(0),
m_TextureID(0)
{}
Texture::Texture(const std::string& path, const std::string& name)
: m_FilePath(path), m_Name(name),
m_LocalBuffer(nullptr),
m_Width(0), m_Height(0), m_BPP(0)
{
stbi_set_flip_vertically_on_load(1); //Return the texture vertically.
m_LocalBuffer = stbi_load(path.c_str(), &m_Width, &m_Height, &m_BPP, 4);
GLCall(glGenTextures(1, &m_TextureID));
GLCall(glBindTexture(GL_TEXTURE_2D, m_TextureID));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, m_Width, m_Height, 0, GL_RGBA, GL_UNSIGNED_BYTE, m_LocalBuffer));
GLCall(glBindTexture(GL_TEXTURE_2D, 0));
if (m_LocalBuffer)
stbi_image_free(m_LocalBuffer);
}
Texture::~Texture() { GLCall(glDeleteTextures(1, &m_TextureID)); }
void Texture::Bind(unsigned int slot /*= 0*/) const {
GLCall(glActiveTexture(GL_TEXTURE0 + slot));
GLCall(glBindTexture(GL_TEXTURE_2D, m_TextureID));
}
void Texture::Unbind() const { GLCall(glBindTexture(GL_TEXTURE_2D, 0)); }
void Texture::EmptyTextureUI()
{
GLCall(glGenTextures(1, &m_TextureID));
GLCall(glBindTexture(GL_TEXTURE_2D, m_TextureID));
GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32UI, App::WINDOW_WIDTH, App::WINDOW_HEIGHT, 0, GL_RGBA_INTEGER, GL_UNSIGNED_INT, 0));
GLCall(glBindTexture(GL_TEXTURE_2D, 0));
}
void Texture::EmptyTextureF()
{
GLCall(glGenTextures(1, &m_TextureID));
GLCall(glBindTexture(GL_TEXTURE_2D, m_TextureID));
GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32F, App::WINDOW_WIDTH, App::WINDOW_HEIGHT, 0, GL_RGBA, GL_FLOAT, 0));
GLCall(glBindTexture(GL_TEXTURE_2D, 0));
}
void Texture::EmptyTextureI()
{
GLCall(glGenTextures(1, &m_TextureID));
GLCall(glBindTexture(GL_TEXTURE_2D, m_TextureID));
GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA32I, App::WINDOW_WIDTH, App::WINDOW_HEIGHT, 0, GL_RGBA_INTEGER, GL_INT, 0));
GLCall(glBindTexture(GL_TEXTURE_2D, 0));
}
| true |
5b152ac3f99b55534db050fce63565d2ea862b91 | C++ | Asupi/C_plusplus | /4_16/4_16/test.cpp | GB18030 | 2,589 | 3.421875 | 3 | [] | no_license | #include <iostream>
#include <string>
using namespace std;
//class Person
//{
//public:
// void Print()
// {
// cout << "name:" << _name << endl;
// cout << "age:" << _age << endl;
// }
//protected:
// string _name = "peter"; //
// int _age = 18; //
//};
//
//class Student : public Person
//{
//protected:
// int _stuid; // ѧ
//};
//
//class Teacher : public Person
//{
//protected:
// int _jobid; //
//};
//
//int main()
//{
// Person p;
// Student s;
// s.Print();
// Teacher t;
// t.Print();
// return 0;
//}
//class Person
//{
//public:
// void Print()
// {
// cout << _name << endl;
// }
////protected:
//public:
// string _name; //
//private:
// int _age; //
//protected:
// int _id;
//};
//
////class Student : protected Person
////class Student : private Person
//class Student : public Person
//{
//public:
// void fun1()
// {
// _id = 123;
// //_name = "hllo";
// //_age = 18;
// }
//public:
// int _stunum; // ѧ
//
////private:
// //string _name; //
////ɼ:
////int _age; //
////protected:
//// int _id;
//};
// private:
// protected: ʣڲԷ
// public̳У ıԱеķȨ
// protected̳УԱеͷȨΪprotected
// private̳УԱеͷȨΪprivate
///* Person:
//public:
//string _name; //
//private:
//int _age; //
//protected:
//int _id;
//*/
//
//_name _age _id
//A Public B Protected C Private D ɼ
//Student :
//Public̳: ACB ADB ABD ABD ADB
//Protected̳: ABC BDB BBD BBD BDB
//Private̳: CCC CDC CCD CCD CDC
//int main()
//{
// Student s;
// //s._name = "hello";
// //s._id = 234;
// s._name = "hello";
// Person p;
// p._name = "123";
// return 0;
//}
//int main()
//{
// int a = 10;
// float b = 1.5;
// //ʽתƵıԽֵͨʽת
// a = b;
// int* pa = &a;
// int c = 10;
// //ǿת
// pa = (int*)c;
//
// Person p;
// Student s;
// //Ƭ Ը
// p = s;
// //ֵܸ
// //s = p;
// //ָԸָ
// Person* ptr = &s;
// //Ըã õĵײָ
// Person& ref = s;
// //ָ벻ָܸ룺ܻᷢԽ
// //Student* ptr2 = &p;
//
// Student* ptr2 = (Student*)ptr;
//}
| true |
2decc103922182bb16d8e87ecd9e998c9dad90b1 | C++ | famafka/smallest-enclosing-disc | /lab_TK3_Mikhno/segment.cpp | UTF-8 | 342 | 3.234375 | 3 | [] | no_license | #include "segment.h"
segment :: segment()
{
a = point(0, 0);
b = point(0, 0);
}
segment :: segment(const point & a, const point & b) : a(a), b(b)
{
}
point segment :: middle() const
{
return point((a.getX() + b.getX()) / 2., (a.getY() + b.getY()) / 2.);
}
double segment :: length() const
{
return point :: dist(a, b);
}
| true |
4d8e65143d70c7d7383a03876b9f6be2be826fca | C++ | angeluriot/Chess_AI | /sources/OpeningBook.cpp | UTF-8 | 2,870 | 2.9375 | 3 | [] | no_license | #include "OpeningBook.h"
#include <stdexcept>
OpeningBook::OpeningBook(const std::string& name) : book_size(0)
{
file.open(name, std::ifstream::binary);
if (!file.good() || !file.is_open())
throw std::runtime_error("A");
file.seekg(0, std::ios::end);
if (!file.good())
throw std::runtime_error("B");
book_size = file.tellg();
if (book_size == -1)
throw std::runtime_error("C");
book_size /= 16;
}
OpeningBook::~OpeningBook()
{
if (file.is_open())
file.close();
}
std::pair<uint16_t, int> OpeningBook::book_move(BitBoard& board)
{
OpeningBookEntry entry;
std::list<uint16_t> list;
uint64_t hash = board.signature_hash();
if (!file.good() || !file.is_open() || book_size == 0)
throw std::runtime_error("D");
int best_move = -1;
int best_score = 0;
for (int pos = find_pos(hash); pos < book_size; pos++)
{
read_entry(entry,pos);
if (entry.key != hash) break;
if (entry.count <= 0)
throw std::runtime_error("E");
best_score += entry.count;
if (rand() % best_score < entry.count)
best_move = entry.move;
}
if (best_move != -1)
{
uint8_t target_x = best_move & 0b111;
uint8_t target_y = 7 - ((best_move & 0b111000) >> 3);
uint8_t start_x = (best_move & 0b111000000) >> 6;
uint8_t start_y = 7 - ((best_move & 0b111000000000) >> 9);
if (get_bit(board.piece_boards[Piece::White_King] | board.piece_boards[Piece::Black_King], start_y * 8 + start_x))
{
if (start_x == e && target_x == a)
target_x = c;
if (start_x == e && target_x == h)
target_x = g;
}
return std::make_pair(((start_y * 8 + start_x) << 8) | (target_y * 8 + target_x), best_score);
}
return std::make_pair(No_Square, 0);
}
int OpeningBook::find_pos(uint64_t key)
{
int left = 0, right = book_size - 1, mid;
OpeningBookEntry entry;
if (left > right)
throw std::runtime_error("F");
while (left < right)
{
mid = (left + right) / 2;
if (mid < left || mid >= right)
throw std::exception();
read_entry(entry, mid);
if (key <= entry.key)
right = mid;
else
left = mid + 1;
}
if (left != right)
throw std::exception();
read_entry(entry, left);
return entry.key == key ? left : book_size;
}
void OpeningBook::read_entry(OpeningBookEntry& entry, int n)
{
if (n < 0 || n >= book_size)
throw std::exception();
if (!file.good() || !file.is_open())
throw std::exception();
file.seekg(n * 16);
if (file.fail())
throw std::exception();
entry.key = read_integer(8);
entry.move = read_integer(2);
entry.count = read_integer(2);
entry.n = read_integer(2);
entry.sum = read_integer(2);
}
uint64_t OpeningBook::read_integer(int size)
{
uint64_t n = 0;
if (!file.good() || !file.is_open())
throw std::exception();
for (int i = 0; i < size; i++)
{
int byte = file.get();
if (byte < 0 || byte >= 256)
throw std::exception();
n = (n << 8) | byte;
}
return n;
}
| true |
c1b4c09f28a9c75fb2ec49b217f79687956cac8f | C++ | giacomomodica/MyCode | /virtual_machine_gui_test.cpp | UTF-8 | 3,622 | 2.5625 | 3 | [] | no_license | #include <QTest>
#include <QPlainTextEdit>
#include <QTableView>
#include <QLineEdit>
#include <QPushButton>
#include <iostream>
#include "virtual_machine_gui.hpp"
#include "test_config.hpp"
class VirtualMachineGUITest : public QObject {
Q_OBJECT
private slots:
void initTestCase();
void testCase1();
void testCase2();
private:
VirtualMachineGUI widget;
};
// this section just verifies the object names and API
void VirtualMachineGUITest::initTestCase(){
widget.load(QString::fromStdString(TEST_FILE_DIR + "/vm/test00.asm"));
auto textWidget = widget.findChild<QPlainTextEdit *>("text");
QVERIFY2(textWidget, "Could not find QPLainText widget");
auto registerViewWidget = widget.findChild<QTableView *>("registers");
QVERIFY2(registerViewWidget, "Could not find QTableView widget for registers");
auto memoryViewWidget = widget.findChild<QTableView *>("memory");
QVERIFY2(memoryViewWidget, "Could not find QTableView widget for memory");
auto statusViewWidget = widget.findChild<QLineEdit *>("status");
QVERIFY2(statusViewWidget, "Could not find QLineEdit widget for status");
auto stepButtonWidget = widget.findChild<QPushButton *>("step");
QVERIFY2(stepButtonWidget, "Could not find QTableView widget for step");
auto runButtonWidget = widget.findChild<QPushButton *>("run");
QVERIFY2(runButtonWidget, "Could not find QTableView widget for ");
auto breakButtonWidget = widget.findChild<QPushButton *>("break");
QVERIFY2(breakButtonWidget, "Could not find QTableView widget for break");
}
void VirtualMachineGUITest::testCase1()
{
widget.load(QString::fromStdString(TEST_FILE_DIR + "/vm/test01.asm"));
auto memoryViewWidget = widget.findChild<QTableView *>("memory");
QVERIFY2(memoryViewWidget, "Could not find QTableView widget for memory");
auto registerViewWidget = widget.findChild<QTableView *>("registers");
QVERIFY2(registerViewWidget, "Could not find QTableView widget for registers");
auto stepButtonWidget = widget.findChild<QPushButton *>("step");
QVERIFY2(stepButtonWidget, "Could not find QTableView widget for memory");
int init_pc = widget.vm->pc;
stepButtonWidget->click();
int second_pc = widget.vm->pc;
QVERIFY(init_pc + 1 == second_pc);
auto runButtonWidget = widget.findChild<QPushButton *>("run");
QVERIFY2(runButtonWidget, "Could not find QTableView widget for run");
auto breakButtonWidget = widget.findChild<QPushButton *>("break");
QVERIFY2(breakButtonWidget, "Could not find QTableView widget for break");
runButtonWidget->click();
breakButtonWidget->click();
}
void VirtualMachineGUITest::testCase2()
{
widget.load(QString::fromStdString(TEST_FILE_DIR + "/vm/test02.asm"));
auto stepButtonWidget = widget.findChild<QPushButton *>("step");
QVERIFY2(stepButtonWidget, "Could not find QTableView widget for step");
auto runButtonWidget = widget.findChild<QPushButton *>("run");
QVERIFY2(runButtonWidget, "Could not find QTableView widget for run");
auto breakButtonWidget = widget.findChild<QPushButton *>("break");
QVERIFY2(breakButtonWidget, "Could not find QTableView widget for break");
stepButtonWidget->click();
runButtonWidget->click();
std::chrono::duration<double, std::milli> x = std::chrono::milliseconds(50);
std::this_thread::sleep_for(x);
breakButtonWidget->click();
std::cout << "pc should be at the end of the program, pc = " << widget.vm->pc << endl << endl;
//QVERIFY(widget.vm->pc == 7);
}
QTEST_MAIN(VirtualMachineGUITest)
#include "virtual_machine_gui_test.moc"
| true |
f52953ae2576ab309b3f3c726c22c7f6f6b954e5 | C++ | ianms17/CSCE121 | /hw11/DoublyLinkedList.h | UTF-8 | 7,855 | 3.640625 | 4 | [] | no_license | #ifndef DOUBLYLINKEDLIST_H
#define DOUBLYLINKEDLIST_H
#include "Node.h"
#include <string>
#include <iostream>
#include <iomanip>
#include <sstream>
//////////////////////////////////////////////////////////////////////////////
// class template definition //
//////////////////////////////////////////////////////////////////////////////
template<typename T>
class DoublyLinkedList {
public:
/* uncomment the declarations as you implement them */
DoublyLinkedList();
DoublyLinkedList(T data);
DoublyLinkedList(const DoublyLinkedList<T>&);
DoublyLinkedList<T>& operator=(const DoublyLinkedList<T>&);
~DoublyLinkedList();
unsigned int size() const { return sz; }
T& front();
const T& front() const;
T& back();
const T& back() const;
void push_back(T data);
void push_front(T);
void pop_back();
void pop_front();
void erase(unsigned int);
void insert(T data, unsigned int idx);
void clear();
std::string to_str() const;
// breaks encapsulation... gives operator== access to private data... not great approach, but makes the homework easier for you since we haven't talked about iterators :).
// template<typename U> friend bool operator==(DoublyLinkedList<U> const&, DoublyLinkedList<U> const&);
private:
// do not change ordering.
Node<T> *head;
Node<T> *tail;
unsigned int sz;
};
//////////////////////////////////////////////////////////////////////////////
// helper function declarations //
//////////////////////////////////////////////////////////////////////////////
template<typename T> std::ostream& operator<<(std::ostream &, DoublyLinkedList<T> const&);
template<typename T> bool operator==(DoublyLinkedList<T> const&, DoublyLinkedList<T> const&);
template<typename T> bool operator!=(DoublyLinkedList<T> const&, DoublyLinkedList<T> const&);
//////////////////////////////////////////////////////////////////////////////
// member template function definitions //
//////////////////////////////////////////////////////////////////////////////
template<typename T>
std::string DoublyLinkedList<T>::to_str() const
{
std::stringstream os;
const Node<T> *curr = head;
os << std::endl << std::setfill('-') << std::setw(80) << '-' << std::setfill(' ') << std::endl;
os << "head: " << head << std::endl;
os << "tail: " << tail << std::endl;
os << " sz: " << sz << std::endl;
os << std::setw(16) << "node" << std::setw(16) << "node.prev" << std::setw(16) << "node.data" << std::setw(16) << "node.next" << std::endl;
while (curr) {
os << std::setw(16) << curr;
os << std::setw(16) << curr->prev;
os << std::setw(16) << curr->data;
os << std::setw(16) << curr->next;
os << std::endl;
curr = curr->next;
}
os << std::setfill('-') << std::setw(80) << '-' << std::setfill(' ') << std::endl;
return os.str();
}
// Default Constructor
template<typename T>
DoublyLinkedList<T>::DoublyLinkedList() : head(nullptr), tail(nullptr), sz(0) {}
// Parametrized Constructor
template<typename T>
DoublyLinkedList<T>::DoublyLinkedList(T data) : head(nullptr), tail(nullptr), sz(0) {
Node<T>* node = new Node<T>(data);
head = node;
tail = node;
sz++;
}
// Copy Constructor
template<typename T>
DoublyLinkedList<T>::DoublyLinkedList(const DoublyLinkedList<T>& copyList) : head(nullptr), tail(nullptr), sz(0){
Node<T>* currNode = copyList.head;
while (currNode) {
this->push_back(currNode->data);
currNode = currNode->next;
}
}
// Copy Assignment Operator
template<typename T>
DoublyLinkedList<T>& DoublyLinkedList<T>::operator=(const DoublyLinkedList<T>& rhs) {
if (this == &rhs) {
return *this;
}
clear();
Node<T>* currNode = rhs.head;
while (currNode) {
this->push_back(currNode->data);
currNode = currNode->next;
}
return *this;
}
// Destructor
template<typename T>
DoublyLinkedList<T>::~DoublyLinkedList() {
clear();
}
// Front
template<typename T>
T& DoublyLinkedList<T>::front() {
return head->data;
}
// Front const
template<typename T>
const T& DoublyLinkedList<T>::front() const {
return head->data;
}
// Back
template<typename T>
T& DoublyLinkedList<T>::back() {
return tail->data;
}
// Back const
template<typename T>
const T& DoublyLinkedList<T>::back() const {
return tail->data;
}
// Clear
template<typename T>
void DoublyLinkedList<T>::clear() {
Node<T>* currNode = head;
while(currNode) {
Node<T>* nextNode = currNode->next;
delete currNode;
currNode = nextNode;
}
head = nullptr;
tail = nullptr;
sz = 0;
}
// Insert
template<typename T>
void DoublyLinkedList<T>::insert(T data, unsigned int idx) {
if (idx >= size()) {
return;
}
Node<T>* insertNode = head;
if (head == nullptr || idx == 0) {
push_front(data);
} else if (idx == sz - 1) {
push_back(data);
} else {
int cnt = 0;
while (insertNode && cnt != idx) {
insertNode = insertNode->next;
cnt++;
}
Node<T>* insertPrev = insertNode->prev;
Node<T>* insertNext = insertNode->next;
insertPrev->next = insertNext;
if (insertNext != nullptr) {
insertNext->prev = insertPrev;
}
sz++;
}
}
// Erase
template<typename T>
void DoublyLinkedList<T>::erase(unsigned int idx) {
if (idx >= size()) {
return;
}
Node<T>* deleteNode = head;
if (head == nullptr) {
tail = nullptr;
return;
} else {
int cnt = 0;
while (deleteNode && cnt != idx) {
deleteNode = deleteNode->next;
cnt++;
}
if (idx == 0) {
head = deleteNode->next;
head->prev = nullptr;
sz--;
} else if (idx == sz - 1) {
tail = tail->prev;
tail->next = nullptr;
sz--;
} else if (cnt == idx) {
Node<T>* deletePrev = deleteNode->prev;
Node<T>* deleteNext = deleteNode->next;
deletePrev->next = deleteNext;
if (deleteNext != nullptr) {
deleteNext->prev = deletePrev;
}
sz--;
}
}
}
// Push Back
template<typename T>
void DoublyLinkedList<T>::push_back(T data) {
Node<T>* pushNode = new Node<T>(data);
if (tail == nullptr) {
tail = pushNode;
head = pushNode;
sz = 1;
} else {
tail->next = pushNode;
pushNode->prev = tail;
tail = pushNode;
sz++;
}
}
// Pop Back
template<typename T>
void DoublyLinkedList<T>::pop_back() {
if (tail == nullptr) {
return;
} else if (tail == head) {
delete tail;
head = nullptr;
tail = nullptr;
sz--;
} else {
Node<T>* newTailNode = nullptr;
newTailNode = tail->prev;
newTailNode->next = nullptr;
delete tail;
tail = newTailNode;
sz--;
}
}
// Push Front
template<typename T>
void DoublyLinkedList<T>::push_front(T data) {
Node<T>* pushNode = new Node<T>(data);
if (head == nullptr) {
head = pushNode;
tail = pushNode;
sz = 1;
} else {
head->prev = pushNode;
pushNode->next = head;
head = pushNode;
sz++;
}
}
// Pop Front
template<typename T>
void DoublyLinkedList<T>::pop_front() {
if (head == nullptr) {
return;
} else if (head == tail) {
delete head;
head = nullptr;
tail = nullptr;
sz--;
} else {
Node<T>* newHeadNode = nullptr;
newHeadNode = head->next;
newHeadNode->prev = nullptr;
delete head;
head = newHeadNode;
sz--;
}
}
//////////////////////////////////////////////////////////////////////////////
// helper template function definitions //
//////////////////////////////////////////////////////////////////////////////
template<typename T>
bool operator==(DoublyLinkedList<T> const& lhs, DoublyLinkedList<T> const& rhs)
{
if (lhs.head->data == rhs.head->data && lhs.tail->data == rhs.tail->data) {
return true;
} else {
return false;
}
}
template<typename T>
std::ostream& operator<<(std::ostream& os, DoublyLinkedList<T> const& rhs)
{
os << rhs.to_str();
return os;
}
#endif
| true |
74ca6247aaf9c9ba1f16aa2bd30c1f3e970ad2f3 | C++ | andreitudose2000/SQLinCPP | /ProiectPOO/ProiectPOO.h | UTF-8 | 24,073 | 2.84375 | 3 | [] | no_license | #include <iostream>
#include <vector>
#include <string>
#include <tuple>
#include <sstream>
#include <algorithm>
#include <fstream>
using namespace std;
class Tabel
{
string nume_tabel;
vector<tuple<string, string, int>> coloane; // tuplul contine: <nume, tip, dimensiune>
vector<vector<string>> date;
public:
friend class BazaDeDate;
friend class Create;
friend class Drop;
friend class Display;
friend class Insert;
friend class Select;
friend class Delete;
friend class Update;
friend class Import;
friend class Incarcare;
friend class Stocare;
friend class SalvareDate;
};
class Create
{
public:
void create(vector<Tabel>& tabele, vector<string> impartire)
{
Tabel tabel;
bool daca_nu_exista = false;
if (impartire[0] != "CREATE"
|| impartire[1] != "TABLE"
|| impartire.size() < 7)
{
cout << "Comanda a fost scrisa gresit.";
return;
}
tabel.nume_tabel = impartire[2];
for (int i = 0; i < tabele.size(); i++)
{
if (tabele[i].nume_tabel == tabel.nume_tabel)
{
cout << "Tabelul pe care incercati sa-l adaugati exista deja in baza de date.\n";
return;
}
}
int index_parcurgere;
int numar_coloane;
if (impartire[3] == "[DACA"
&& impartire[4] == "NU"
&& impartire[5] == "EXISTA]")
{
daca_nu_exista = true;
index_parcurgere = 6;
numar_coloane = (impartire.size() - 6) / 4;
}
else if (impartire[3].substr(0, 2) == "((")
{
daca_nu_exista = false;
index_parcurgere = 3;
numar_coloane = (impartire.size() - 3) / 4;
}
else
{
cout << "Comanda a fost scrisa gresit.";
return;
}
if (daca_nu_exista)
{
if (impartire.size() < 10)
{
cout << "Comanda a fost scrisa gresit.";
return;
}
}
else
{
if (impartire.size() < 7)
{
cout << "Comanda a fost scrisa gresit.";
return;
}
}
int temp = 1;
for (int i = 0; i < numar_coloane; i++)
{
string nume_col, tip, dimensiune, valoare_implicita;
int dimensiune_int;
nume_col = impartire[index_parcurgere].substr(1 + temp, impartire[index_parcurgere].size() - 2 - temp);
tip = impartire[index_parcurgere + 1].substr(0, impartire[index_parcurgere + 1].size() - 1);
if (tip != "text" && tip != "float" && tip != "integer")
{
cout << "Tipul datelor trebuie sa fie text / float / integer";
return;
}
dimensiune = impartire[index_parcurgere + 2].substr(0, impartire[index_parcurgere + 2].size() - 1);
valoare_implicita = impartire[index_parcurgere + 3].substr(0, impartire[index_parcurgere + 3].size() - 2);
try
{
dimensiune_int = stoi(dimensiune);
}
catch (...)
{
cout << "Dimensiunea trebuie sa fie un numar natural.";
return;
}
tabel.coloane.push_back(make_tuple(nume_col, tip, dimensiune_int));
index_parcurgere += 4;
temp = 0;
}
tabele.push_back(tabel);
cout << "S-a adaugat tabelul " << tabel.nume_tabel << '.';
}
};
class Drop
{
public:
void drop(vector<Tabel>& tabele, vector<string> impartire)
{
if (impartire[0] != "DROP"
|| impartire[1] != "TABLE")
{
cout << "Comanda a fost scrisa gresit.";
return;
}
bool gasit = false;
int index = -1;
for (int i = 0; i < tabele.size(); i++)
{
if (tabele[i].nume_tabel == impartire[2])
{
gasit = true;
index = i;
break;
}
}
if (gasit)
{
string nume_tabel_sters = tabele[index].nume_tabel;
tabele.erase(tabele.begin() + index);
cout << "S-a sters tabelul " << nume_tabel_sters << '.';
}
else
{
cout << "Tabelul pe care incercati sa il stergeti nu exista.";
return;
}
}
};
class Display
{
static int nr_comenzi_display;
public:
static int get_nr_comenzi_display() { return nr_comenzi_display; }
static void set_nr_comenzi_display(int val) { nr_comenzi_display = val; }
void display(vector<Tabel>& tabele, vector<string> impartire)
{
if (impartire[0] != "DISPLAY"
|| impartire[1] != "TABLE")
{
cout << "Comanda a fost scrisa gresit.";
return;
}
bool gasit = false;
int index = -1;
for (int i = 0; i < tabele.size(); i++)
{
if (tabele[i].nume_tabel == impartire[2])
{
gasit = true;
index = i;
break;
}
}
if (gasit)
{
cout << endl;
display(tabele[index]);
}
else
{
cout << "Tabelul pe care incercati sa il afisati nu exista.";
return;
}
}
void display(Tabel tabel)
{
nr_comenzi_display++;
string nume_fisier = "DISPLAY_" + to_string(nr_comenzi_display);
ofstream out_display(nume_fisier);
cout << "--------------" << tabel.nume_tabel << "--------------" << endl;
out_display << "--------------" << tabel.nume_tabel << "--------------" << endl;
for (tuple<string, string, int> t : tabel.coloane)
{
cout << get<0>(t) << ' ' << get<1>(t) << '(' << get<2>(t) << ')' << endl;
out_display << get<0>(t) << ' ' << get<1>(t) << '(' << get<2>(t) << ')' << endl;
}
cout << "--------------------------------------------" << endl;
out_display << "--------------------------------------------" << endl;
vector<string> coloane_cautare;
for (int i = 0; i < tabel.coloane.size(); i++)
{
coloane_cautare.push_back(get<0>(tabel.coloane[i]));
}
cout << endl;
out_display << endl;
for (int j = 0; j < coloane_cautare.size(); j++)
{
cout << coloane_cautare[j] << ' ';
out_display << coloane_cautare[j] << ' ';
}
cout << endl;
out_display << endl;
vector<int> pozitii_coloane_cautare;
for (int i = 0; i < coloane_cautare.size(); i++)
{
for (int j = 0; j < tabel.coloane.size(); j++)
{
if (get<0>(tabel.coloane[j]) == coloane_cautare[i])
{
pozitii_coloane_cautare.push_back(j);
break;
}
}
}
for (int j = 0; j < tabel.date.size(); j++)
{
for (int k = 0; k < pozitii_coloane_cautare.size(); k++)
{
cout << tabel.date[j][pozitii_coloane_cautare[k]] << ' ';
out_display << tabel.date[j][pozitii_coloane_cautare[k]] << ' ';
}
cout << endl;
out_display << endl;
}
out_display.close();
}
};
class Insert
{
public:
void insert(vector<Tabel>& tabele, vector<string> impartire)
{
if (impartire[0] != "INSERT"
|| impartire[1] != "INTO"
|| impartire.size() < 4)
{
cout << "Comanda a fost scrisa gresit.";
return;
}
bool gasit = false;
int index = -1;
for (int i = 0; i < tabele.size(); i++)
{
if (tabele[i].nume_tabel == impartire[2])
{
gasit = true;
index = i;
break;
}
}
if (gasit)
{
cout << endl;
vector<string> valori;
int nr_valori = impartire.size() - 4;
if (nr_valori != tabele[index].coloane.size())
{
cout << "Numarul de valori nu corespunde structurii tabelului.";
return;
}
for (int i = 4; i < 4 + nr_valori; i++)
{
valori.push_back(impartire[i]);
}
for (int i = 0; i < valori.size(); i++)
{
valori[i].erase(remove(valori[i].begin(), valori[i].end(), ','), valori[i].end());
valori[i].erase(remove(valori[i].begin(), valori[i].end(), '('), valori[i].end());
valori[i].erase(remove(valori[i].begin(), valori[i].end(), ')'), valori[i].end());
}
insert(tabele[index], valori);
}
else
{
cout << "Tabelul in care incercati sa inserati nu exista.";
return;
}
}
void insert(Tabel& tabel, vector<string> valori, bool afisare = true)
{
for (int i = 0; i < tabel.coloane.size(); i++)
{
if (get<1>(tabel.coloane[i]) == "integer")
{
int valoare_integer;
try
{
valoare_integer = stoi(valori[i]);
}
catch (...)
{
cout << "Una sau mai multe valori nu sunt de tipul corespunzator.";
return;
}
}
else if (get<1>(tabel.coloane[i]) == "float")
{
float valoare_float;
try
{
valoare_float = stof(valori[i]);
}
catch (...)
{
cout << "Una sau mai multe valori nu sunt de tipul corespunzator.";
return;
}
}
}
tabel.date.push_back(valori);
if (afisare == true)
{
cout << "S-a inserat cu succes in tabelul " << tabel.nume_tabel << ".\n";
}
}
};
class Select
{
static int nr_comenzi_select;
public:
static int get_nr_comenzi_select() { return nr_comenzi_select; }
static void set_nr_comenzi_select(int val) { nr_comenzi_select = val; }
void select(vector<Tabel>& tabele, vector<string> impartire)
{
int indexFrom = -1;
bool gasitMaiMulteFrom = false;
for (int i = 0; i < impartire.size(); i++)
{
if (impartire[i] == "FROM")
{
if (indexFrom != -1)
gasitMaiMulteFrom = true;
indexFrom = i;
}
}
if (indexFrom == -1
|| gasitMaiMulteFrom)
{
cout << "Comanda a fost scrisa gresit.";
return;
}
vector<string> coloane_cautare;
bool selectAll = false;
if (impartire[1] == "ALL")
selectAll = true;
for (int i = 1; i < indexFrom; i++)
{
coloane_cautare.push_back(impartire[i]);
}
for (int i = 0; i < coloane_cautare.size(); i++)
{
coloane_cautare[i].erase(remove(coloane_cautare[i].begin(), coloane_cautare[i].end(), ','), coloane_cautare[i].end());
coloane_cautare[i].erase(remove(coloane_cautare[i].begin(), coloane_cautare[i].end(), '('), coloane_cautare[i].end());
coloane_cautare[i].erase(remove(coloane_cautare[i].begin(), coloane_cautare[i].end(), ')'), coloane_cautare[i].end());
}
bool gasit = false;
int index = -1;
for (int i = 0; i < tabele.size(); i++)
{
if (tabele[i].nume_tabel == impartire[indexFrom + 1])
{
gasit = true;
index = i;
break;
}
}
if (gasit)
{
if (selectAll)
{
coloane_cautare.clear();
for (int i = 0; i < tabele[index].coloane.size(); i++)
{
coloane_cautare.push_back(get<0>(tabele[index].coloane[i]));
}
}
if (impartire.size() > indexFrom + 2)
{
if (impartire[indexFrom + 2] != "WHERE"
|| impartire[indexFrom + 4] != "=")
{
cout << "Comanda a fost scrisa gresit.";
return;
}
string coloana_where, valoare_where;
coloana_where = impartire[indexFrom + 3];
valoare_where = impartire[indexFrom + 5];
select(tabele[index], coloane_cautare, coloana_where, valoare_where);
}
else
{
select(tabele[index], coloane_cautare);
}
}
else
{
cout << "Tabelul din care incercati sa selectati nu exista.";
return;
}
}
void select(Tabel& tabel, vector<string> coloane_cautare, string coloana_where, string valoare_where)
{
nr_comenzi_select++;
string nume_fisier = "SELECT_" + to_string(nr_comenzi_select);
ofstream out_select(nume_fisier);
bool gasit_coloana = false;
int index_coloana = -1;
for (int i = tabel.coloane.size() - 1; i >= 0; i--)
{
if (get<0>(tabel.coloane[i]) == coloana_where)
{
gasit_coloana = true;
index_coloana = i;
break;
}
}
if (!gasit_coloana)
{
cout << "Coloana introdusa nu exista in tabelul dat.";
out_select << "Coloana introdusa nu exista in tabelul dat.";
return;
}
vector<int> pozitii_coloane_cautare;
for (int i = 0; i < coloane_cautare.size(); i++)
{
for (int j = 0; j < tabel.coloane.size(); j++)
{
if (get<0>(tabel.coloane[j]) == coloane_cautare[i])
{
pozitii_coloane_cautare.push_back(j);
break;
}
}
}
cout << endl;
out_select << endl;
for (int j = 0; j < coloane_cautare.size(); j++)
{
cout << coloane_cautare[j] << ' ';
out_select << coloane_cautare[j] << ' ';
}
cout << endl;
out_select << endl;
for (int j = 0; j < tabel.date.size(); j++)
{
if (tabel.date[j][index_coloana] == valoare_where)
{
for (int k = 0; k < pozitii_coloane_cautare.size(); k++)
{
cout << tabel.date[j][pozitii_coloane_cautare[k]] << ' ';
out_select << tabel.date[j][pozitii_coloane_cautare[k]] << ' ';
}
}
cout << endl;
out_select << endl;
}
out_select.close();
}
void select(Tabel& tabel, vector<string> coloane_cautare)
{
nr_comenzi_select++;
string nume_fisier = "SELECT_" + to_string(nr_comenzi_select);
ofstream out_select(nume_fisier);
cout << endl;
for (int j = 0; j < coloane_cautare.size(); j++)
{
cout << coloane_cautare[j] << ' ';
out_select << coloane_cautare[j] << ' ';
}
cout << endl;
out_select << endl;
vector<int> pozitii_coloane_cautare;
for (int i = 0; i < coloane_cautare.size(); i++)
{
for (int j = 0; j < tabel.coloane.size(); j++)
{
if (get<0>(tabel.coloane[j]) == coloane_cautare[i])
{
pozitii_coloane_cautare.push_back(j);
break;
}
}
}
for (int j = 0; j < tabel.date.size(); j++)
{
for (int k = 0; k < pozitii_coloane_cautare.size(); k++)
{
cout << tabel.date[j][pozitii_coloane_cautare[k]] << ' ';
out_select << tabel.date[j][pozitii_coloane_cautare[k]] << ' ';
}
cout << endl;
out_select << endl;
}
out_select.close();
}
};
class Delete
{
public:
void delete1(vector<Tabel>& tabele, vector<string> impartire)
{
if (impartire[0] != "DELETE"
|| impartire[1] != "FROM"
|| impartire[3] != "WHERE"
|| impartire[5] != "=")
{
cout << "Comanda a fost scrisa gresit.";
return;
}
bool gasit = false;
int index = -1;
for (int i = 0; i < tabele.size(); i++)
{
if (tabele[i].nume_tabel == impartire[2])
{
gasit = true;
index = i;
break;
}
}
if (gasit)
{
string coloana_where = impartire[4];
string valoare_where = impartire[6];
delete1(tabele[index], coloana_where, valoare_where);
}
else
{
cout << "Tabelul din care incercati sa stergeti nu exista.";
return;
}
}
void delete1(Tabel& tabel, string coloana_where, string valoare_where)
{
bool gasit_coloana = false;
int index_coloana = -1;
for (int i = tabel.coloane.size() - 1; i >= 0; i--)
{
if (get<0>(tabel.coloane[i]) == coloana_where)
{
gasit_coloana = true;
index_coloana = i;
break;
}
}
if (!gasit_coloana)
{
cout << "Coloana introdusa nu exista in tabelul dat.";
return;
}
bool gasit_linie = false;
int nr_linii_sterse = 0;
for (int i = tabel.date.size() - 1; i >= 0; i--)
{
if (tabel.date[i][index_coloana] == valoare_where)
{
tabel.date.erase(tabel.date.begin() + i);
nr_linii_sterse++;
}
}
cout << "S-au sters " << nr_linii_sterse << " linii.";
}
};
class Update
{
public:
void update(vector<Tabel>& tabele, vector<string> impartire)
{
if (impartire[0] != "UPDATE"
|| impartire[2] != "SET"
|| impartire[4] != "="
|| impartire[6] != "WHERE"
|| impartire[8] != "=")
{
cout << "Comanda a fost scrisa gresit.";
return;
}
bool gasit = false;
int index = -1;
for (int i = 0; i < tabele.size(); i++)
{
if (tabele[i].nume_tabel == impartire[1])
{
gasit = true;
index = i;
break;
}
}
if (gasit)
{
string coloana_set = impartire[3],
valoare_set = impartire[5],
coloana_where = impartire[7],
valoare_where = impartire[9];
update(tabele[index], coloana_set, valoare_set, coloana_where, valoare_where);
}
else
{
cout << "Tabelul in care incercati sa updatati nu exista.";
return;
}
}
void update(Tabel& tabel, string coloana_set, string valoare_set, string coloana_where, string valoare_where)
{
bool gasit_coloana_where = false;
int index_coloana_where = -1;
for (int i = tabel.coloane.size() - 1; i >= 0; i--)
{
if (get<0>(tabel.coloane[i]) == coloana_where)
{
gasit_coloana_where = true;
index_coloana_where = i;
break;
}
}
if (!gasit_coloana_where)
{
cout << "Coloana introdusa in WHERE nu exista in tabelul dat.";
return;
}
bool gasit_coloana_set = false;
int index_coloana_set = -1;
for (int i = tabel.coloane.size() - 1; i >= 0; i--)
{
if (get<0>(tabel.coloane[i]) == coloana_set)
{
gasit_coloana_set = true;
index_coloana_set = i;
break;
}
}
if (!gasit_coloana_set)
{
cout << "Coloana introdusa in SET nu exista in tabelul dat.";
return;
}
int nr_linii_updatate = 0;
for (int i = 0; i < tabel.date.size(); i++)
{
if (tabel.date[i][index_coloana_where] == valoare_where)
{
tabel.date[i][index_coloana_set] = valoare_set;
nr_linii_updatate++;
}
}
cout << "S-au updatat " << nr_linii_updatate << " linii.";
}
};
class Import : public Insert
{
public:
void import1(vector<Tabel>& tabele, vector<string> impartire)
{
if (impartire.size() != 3)
{
cout << "Comanda a fost scrisa gresit.";
return;
}
string nume_tabel_nou = impartire[1];
string nume_fisier_input = impartire[2];
if (nume_fisier_input.substr(nume_fisier_input.size() - 4, 4) != ".csv"
&& nume_fisier_input.substr(nume_fisier_input.size() - 4, 4) != ".CSV")
{
cout << "Va rog incarcati un fisier .CSV.\n";
return;
}
bool gasit = false;
bool index = -1;
for (int i = 0; i < tabele.size(); i++)
{
if (tabele[i].nume_tabel == nume_tabel_nou)
{
gasit = true;
index = i;
break;
}
}
if (gasit)
{
string linie;
vector<string> linii;
string valoare;
vector<string> valori;
vector<vector<string>> toate_valorile;
ifstream importare(nume_fisier_input);
while (getline(importare, linie))
{
linii.push_back(linie);
}
for (string linie : linii)
{
for (int i = 0; i < linie.size(); i++)
{
if (linie[i] < 'A' && linie[i] > 'Z'
&& linie[i] < 'a' && linie[i] > 'z'
&& linie[i] < '0' && linie[i] > '9'
&& linie[i] != ',')
{
cout << "Fisierul .csv nu este formatat cum trebuie sau contine alt simbol de delimitare in afara de virgula.";
return;
}
}
valori.clear();
stringstream ss(linie);
while (getline(ss, valoare, ','))
{
valori.push_back(valoare);
}
if (valori.size() != tabele[index].coloane.size())
{
cout << "Fisierul .csv nu are structura aferenta tabelei indicate.";
return;
}
toate_valorile.push_back(valori);
}
for (int i = 0; i < toate_valorile.size(); i++)
{
insert(tabele[index], toate_valorile[i], false);
}
importare.close();
}
else
{
cout << "Tabelul nu exista in baza de date.\n";
return;
}
}
};
class RulareArgumenteMain
{
public:
vector<string> rulare_comenzi(int argc, char* argv[])
{
char comanda_char[256];
string comanda;
vector<string> comenzi;
for (int i = 1; i < argc; i++)
{
const char* p = argv[i];
ifstream intrare(argv[i]);
if (intrare)
{
while (getline(intrare, comanda))
{
comenzi.push_back(comanda);
}
}
intrare.close();
}
return comenzi;
}
};
class Incarcare
{
public:
void incarcare(vector<Tabel>& tabele, string nume_fisier)
{
ifstream i_incarcare(nume_fisier);
int nr_tabele;
i_incarcare >> nr_tabele;
for (int i = 0; i < nr_tabele; i++)
{
Tabel tabel;
i_incarcare >> tabel.nume_tabel;
int nr_coloane;
i_incarcare >> nr_coloane;
for (int i = 0; i < nr_coloane; i++)
{
string nume_col, tip; int dimensiune;
i_incarcare >> nume_col >> tip >> dimensiune;
tabel.coloane.push_back(make_tuple(nume_col, tip, dimensiune));
}
tabele.push_back(tabel);
}
i_incarcare.close();
}
};
class Stocare
{
public:
void stocare(vector<Tabel> tabele, string nume_fisier)
{
ofstream o_stocare(nume_fisier);
o_stocare << tabele.size() << endl;
for (int i = 0; i < tabele.size(); i++)
{
o_stocare << tabele[i].nume_tabel << endl;
o_stocare << tabele[i].coloane.size() << endl;
for (int j = 0; j < tabele[i].coloane.size(); j++)
{
o_stocare << get<0>(tabele[i].coloane[j]) << ' '
<< get<1>(tabele[i].coloane[j]) << ' '
<< get<2>(tabele[i].coloane[j]) << endl;
}
}
o_stocare.close();
}
};
class SalvareDate : public Insert
{
public:
void incarcare(vector<Tabel>& tabele)
{
for (int i = 0; i < tabele.size(); i++)
{
string nume_fisier = tabele[i].nume_tabel + ".dat";
ifstream i_incarcare(nume_fisier, ios::in | ios::binary);
if (!i_incarcare) {
cout << "Pentru tabelul " << tabele[i].nume_tabel << " nu s-au gasit date!\n";
continue;
}
i_incarcare.seekg(0, i_incarcare.end);
int lungime_fisier = i_incarcare.tellg();
i_incarcare.seekg(0, i_incarcare.beg);
char* input;
if (lungime_fisier > 10000 || lungime_fisier <= 0)
{
cout << "Pentru tabelul " << tabele[i].nume_tabel << " nu s-au gasit date!\n";
continue;
}
input = new char[lungime_fisier + 1];
i_incarcare.read(input, lungime_fisier);
input[lungime_fisier] = '\0';
string data = input;
vector<vector<string>> toate_valorile;
string temp_string = "";
vector<string> temp_vector;
for (int j = 0; j < data.size(); j++)
{
if (data[j] == '\n')
{
temp_vector.push_back(temp_string);
temp_string = "";
toate_valorile.push_back(temp_vector);
temp_vector.clear();
}
else if (data[j] == ',')
{
temp_vector.push_back(temp_string);
temp_string = "";
}
else
{
temp_string += data[j];
}
}
temp_vector.push_back(temp_string);
toate_valorile.push_back(temp_vector);
for (int k = 0; k < toate_valorile.size(); k++)
{
insert(tabele[i], toate_valorile[k], false);
}
i_incarcare.close();
}
}
void stocare(vector<Tabel> tabele)
{
for (int i = 0; i < tabele.size(); i++)
{
if (tabele[i].date.size() > 0)
{
string nume_fisier = tabele[i].nume_tabel + ".dat";
ofstream o_salvare(nume_fisier, ios::out | ios::binary);
string data = "";
for (int j = 0; j < tabele[i].date.size(); j++)
{
for (int k = 0; k < tabele[i].date[j].size(); k++)
{
data += tabele[i].date[j][k];
if (k < tabele[i].date[j].size() - 1)
data += ',';
}
if (j < tabele[i].date.size() - 1)
data += '\n';
}
o_salvare.write(data.c_str(), data.size());
o_salvare.close();
}
}
}
};
class BazaDeDate : public Create, public Drop, public Display, public Select, public Delete, public Update, public Import
{
vector<Tabel> tabele;
RulareArgumenteMain argumente;
Incarcare incarcare;
Stocare stocare;
SalvareDate salvare;
public:
vector<Tabel>& get_tabele() { return tabele; }
RulareArgumenteMain get_argumente() { return argumente; }
Incarcare get_incarcare() { return incarcare; }
Stocare get_stocare() { return stocare; }
SalvareDate get_salvare() { return salvare; }
void interpretare_comanda(string comanda)
{
string s = comanda;
string delimiter = " ";
vector<string> impartire;
size_t pos = 0;
string token;
while ((pos = s.find(delimiter)) != string::npos) {
token = s.substr(0, pos);
impartire.push_back(token);
s.erase(0, pos + delimiter.length());
}
impartire.push_back(s);
if (impartire[0] == "CREATE")
{
create(tabele, impartire);
}
else if (impartire[0] == "DROP")
{
drop(tabele, impartire);
}
else if (impartire[0] == "DISPLAY")
{
display(tabele, impartire);
}
else if (impartire[0] == "INSERT")
{
insert(tabele, impartire);
}
else if (impartire[0] == "DELETE")
{
delete1(tabele, impartire);
}
else if (impartire[0] == "SELECT")
{
select(tabele, impartire);
}
else if (impartire[0] == "UPDATE")
{
update(tabele, impartire);
}
else if (impartire[0] == "IMPORT")
{
import1(tabele, impartire);
}
else if (impartire[0] != "EXIT")
{
cout << "Comanda scrisa gresit.\n";
}
}
};
void afisareComenzi()
{
cout << "================" << endl;
cout << "Puteti folosi urmatoarele comenzi:" << endl;
cout << "- CREATE TABLE table_name [DACA NU EXISTA] ((nume_coloana_1, tip, dimensiune, valoare_implicita), (nume_coloana_2, tip, dimensiune, valoare_implicita), ... )" << endl;
cout << "- DROP TABLE table_name" << endl;
cout << "- DISPLAY TABLE table_name" << endl;
cout << "- INSERT INTO nume_tabela VALUES (...)" << endl;
cout << "- DELETE FROM nume_tabela WHERE nume_coloana = valoare" << endl;
cout << "- SELECT (cel_putin_o_coloana, ...) | ALL FROM nume_tabela [WHERE nume_coloana = valoare]" << endl;
cout << "- UPDATE nume_tabela SET nume_coloana = valoare WHERE nume_coloana = valoare" << endl;
cout << "Introduceti EXIT pentru a inchide programul." << endl;
cout << "================" << endl;
} | true |
7ad1f3d3b9224410f7e8478e09b3ae64dbeaa7da | C++ | guoyu07/oj-leetcode | /set-matrix-zeroes/set_matrix_zeroes.cpp | UTF-8 | 1,864 | 3.25 | 3 | [] | no_license | #include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
// O(n)
void setZeroes(vector<vector<int>>& matrix) {
int m, n;
if( ( m = matrix.size() ) == 0 || ( n = matrix.front().size() ) == 0) return;
int rows[m] {};
int cols[n] {};
for( int i = 0; i < m; ++i )
for(int j = 0; j < n; ++j )
if( matrix[i][j] == 0 ) {
rows[i] = 1;
cols[j] = 1;
}
for( int i = 0; i < m; ++i )
if(rows[i] == 1)
for(int j = 0; j < n; ++j )
matrix[i][j] = 0;
for( int i = 0; i < n; ++i )
if(cols[i] == 1)
for(int j = 0; j < m; ++j )
matrix[j][i] = 0;
}
// O(1)
void setZeroes_O1(vector<vector<int>>& matrix) {
size_t m, n;
if( ( m = matrix.size() ) == 0 || ( n = matrix.front().size() ) == 0) return;
bool is_first_col_zero = false, is_first_row_zero = false;
size_t i, j;
for( i = 0; i < n; ++i )
if(matrix[0][i] == 0) {
is_first_row_zero = true;
break;
}
for( i = 0; i < m; ++i )
if(matrix[i][0] == 0) {
is_first_col_zero = true;
break;
}
for( i = 1; i < m; ++i )
for( j = 1; j < n; ++j )
if( matrix[i][j] == 0 )
matrix[i][0] = matrix[0][j] = 0;
for( i = 1; i < n; ++i )
if(matrix[0][i] == 0)
for( size_t k = 1; k < m; ++k)
matrix[k][i] = 0;
for( i = 1; i < m; ++i )
if(matrix[i][0] == 0 )
for( size_t k = 1; k < n; ++k )
matrix[i][k] = 0;
if(is_first_row_zero == true)
for( size_t k = 0; k < n; ++k )
matrix[0][k] = 0;
if(is_first_col_zero == true)
for(size_t k = 0; k < m; ++k )
matrix[k][0] = 0;
}
};
| true |
9f2eef8e97f9a08ceb9083c41f30d3ba8fcea8fd | C++ | kaba2/pastel | /pastel/sys/allocator/pool_allocator/pool_allocator.hpp | UTF-8 | 9,758 | 2.734375 | 3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | #ifndef PASTELSYS_POOL_ALLOCATOR_HPP
#define PASTELSYS_POOL_ALLOCATOR_HPP
#include "pastel/sys/allocator/pool_allocator.h"
#include "pastel/sys/ensure.h"
#include "pastel/sys/generic/addressof.h"
#include <compare>
namespace Pastel
{
inline PoolAllocator::PoolAllocator(
integer unitSize)
: unitSize_(unitSize)
, unitsAllocated_(0)
, unitsCapacity_(0)
, firstFreeBlock_(0)
, lastFreeBlock_(0)
, freeBlocks_(0)
, deallocationBlock_()
, blockList_()
{
ENSURE_OP(unitSize, >, 0);
deallocationBlock_ = blockList_.end();
}
inline PoolAllocator::~PoolAllocator()
{
REPORT1(unitsAllocated_ > 0, unitsAllocated_);
clear();
}
inline auto PoolAllocator::operator<=>(
const PoolAllocator& that) const
{
return this <=> &that;
}
inline void PoolAllocator::swap(PoolAllocator& that)
{
std::swap(unitSize_, that.unitSize_);
std::swap(unitsAllocated_, that.unitsAllocated_);
std::swap(unitsCapacity_, that.unitsCapacity_);
std::swap(firstFreeBlock_, that.firstFreeBlock_);
std::swap(lastFreeBlock_, that.lastFreeBlock_);
std::swap(freeBlocks_, that.freeBlocks_);
std::swap(deallocationBlock_, that.deallocationBlock_);
blockList_.swap(that.blockList_);
}
inline void PoolAllocator::clear()
{
Iterator iter(blockList_.begin());
Iterator iterEnd(blockList_.end());
while (iter != iterEnd)
{
Block* block = *iter;
deallocateRaw((void*)block);
++iter;
}
unitsAllocated_ = 0;
unitsCapacity_ = 0;
firstFreeBlock_ = 0;
lastFreeBlock_ = 0;
freeBlocks_ = 0;
blockList_.clear();
deallocationBlock_ = blockList_.end();
}
inline integer PoolAllocator::unitSize() const
{
return unitSize_;
}
inline integer PoolAllocator::allocated() const
{
return unitsAllocated_;
}
inline integer PoolAllocator::capacity() const
{
return unitsCapacity_;
}
inline void* PoolAllocator::allocate()
{
Block* block = firstFreeBlock_;
if (!block)
{
allocateBlock();
block = firstFreeBlock_;
}
// As an invariant, the inspected block
// should not be full.
ASSERT(block);
ASSERT(!block->full());
// Calculate the memory address of the first
// free unit inside the block.
uint8 firstFreeUnit = block->firstFreeUnit_;
const integer firstFreeIndex = unitSize_ * firstFreeUnit;
uint8* memAddress = (uint8*)block +
sizeof(Block) + firstFreeIndex;
// Pop the first unit off the internal
// linked list.
const uint8 nextFreeIndex = *memAddress;
block->firstFreeUnit_ = nextFreeIndex;
++(block->unitsAllocated_);
++unitsAllocated_;
if (block->full())
{
removeFreeBlock(block);
}
// Return the allocated memory address.
return (void*)memAddress;
}
inline void PoolAllocator::deallocate(const void* memAddress)
{
// Clearly a null pointer can't
// be allocated from this allocator.
PENSURE(memAddress);
// For convenience, we want to deal with bytes.
uint8* byteAddress = (uint8*)memAddress;
// Search for the block that contains
// the given memory address.
// First try the cache.
Iterator iter(deallocationBlock_);
if (iter == blockList_.end() ||
!blockContains(*iter, byteAddress))
{
// Not found in the cache,
// search for the right block.
iter = searchBlock(byteAddress);
// The memory should be found from some
// block. Otherwise the deallocation is
// a bug from the callers side.
bool invalidMemoryAddress =
(iter == blockList_.end());
PENSURE(!invalidMemoryAddress);
unused(invalidMemoryAddress);
}
// Inspect the found block.
Block* block = *iter;
ASSERT(block);
// If the block contains no allocated
// units, abort. This clearly reflects
// a bug in the caller's side.
PENSURE1(block->unitsAllocated_ != 0,
block->unitsAllocated_);
uint8* blockBegin = (uint8*)block + sizeof(Block);
// Calculate the distance in bytes from
// the block's starting address.
integer indexInBytes = byteAddress - blockBegin;
// If the given memory address is not aligned
// on unit intervals, abort. This clearly reflects
// a bug in the caller's side.
PENSURE3(
indexInBytes % unitSize_ == 0,
indexInBytes, unitSize_,
indexInBytes % unitSize_);
// Append the internal linked list by
// the deallocated unit.
blockBegin[indexInBytes] = block->firstFreeUnit_;
integer index = indexInBytes / unitSize_;
block->firstFreeUnit_ = index;
// If the block was full, it now
// becomes free.
if (block->full())
{
pushBackFreeBlock(block);
}
--(block->unitsAllocated_);
--unitsAllocated_;
deallocationBlock_ = iter;
// If the block now becomes totally
// free, check if we can deallocate
// it. We want to protect ourself
// against the pattern of someone
// allocating and deallocating
// a single unit repeatedly.
// We do this by making sure
// there is always at least
// one free block.
if (block->unitsAllocated_ == 0 &&
freeBlocks_ > 1)
{
deallocateBlock(iter);
}
}
// Private
inline void PoolAllocator::allocateBlock()
{
// Allocate memory for the block.
integer blockSize = unitsAllocated_ >> 1;
integer MinBlockSize = 16;
integer MaxBlockSize = 255;
blockSize = std::max(blockSize, MinBlockSize);
blockSize = std::min(blockSize, MaxBlockSize);
Block* block = (Block*)allocateRaw(
sizeof(Block) + unitSize_ * blockSize);
block->firstFreeUnit_ = 0;
block->unitsAllocated_ = 0;
block->unitsCapacity_ = blockSize;
block->padding_ = 0;
block->nextFreeBlock_ = 0;
block->previousFreeBlock_ = 0;
uint8* data = (uint8*)block + sizeof(Block);
// Insert the new block in the beginning
// of the block list.
try
{
blockList_.insert(block);
}
catch(...)
{
deallocateRaw((void*)block);
throw;
}
// For every unit, its first bytes contains
// an index into the next unit in the
// internal linked list.
// The index is converted into an actual
// memory address by:
// addr = blockBegin + index * unitSize_
for (integer i = 0;i < blockSize;++i)
{
data[i * unitSize_] = i + 1;
}
unitsCapacity_ += blockSize;
pushBackFreeBlock(block);
}
inline PoolAllocator::Iterator PoolAllocator::deallocateBlock(
const Iterator& that)
{
ASSERT(that != blockList_.end());
Block* block = *that;
unitsCapacity_ -= block->unitsCapacity_;
if (that == deallocationBlock_)
{
deallocationBlock_ = blockList_.end();
}
bool isFreeBlock =
block == firstFreeBlock_ ||
block->previousFreeBlock_ != 0 ||
block->nextFreeBlock_ != 0;
if (isFreeBlock)
{
removeFreeBlock(block);
}
deallocateRaw((void*)block);
Iterator result = that;
++result;
blockList_.erase(that);
return result;
}
inline PoolAllocator::Iterator PoolAllocator::searchBlock(
uint8* memAddress)
{
ASSERT(memAddress);
// If there are no allocated blocks,
// return.
if (blockList_.empty())
{
return blockList_.end();
}
// Note that using lower_bound here would
// give wrong results.
Iterator iter(
blockList_.upper_bound((Block*)memAddress));
// If the iterator points to the
// first block, then it is because
// the memAddress is out of range.
if (iter == blockList_.begin())
{
return blockList_.end();
}
// The previous iterator always exists:
// the container is not empty and the
// iterator does not point to the first block.
--iter;
if (blockContains(*iter, memAddress))
{
return iter;
}
return blockList_.end();
}
inline bool PoolAllocator::blockContains(
const Block* block,
const uint8* memAddress) const
{
ASSERT(block);
integer blockSizeInBytes =
unitSize_ * block->unitsCapacity_;
const uint8* blockBegin =
(uint8*)block + sizeof(Block);
if (blockBegin <= memAddress &&
memAddress < blockBegin + blockSizeInBytes)
{
return true;
}
return false;
}
inline void PoolAllocator::pushBackFreeBlock(Block* block)
{
ASSERT(block);
// Append this block
// to the list of empty blocks.
ASSERT(block->previousFreeBlock_ == 0);
ASSERT(block->nextFreeBlock_ == 0);
if (!lastFreeBlock_)
{
ASSERT(!firstFreeBlock_);
ASSERT1(freeBlocks_ == 0, freeBlocks_);
firstFreeBlock_ = block;
lastFreeBlock_ = block;
}
else
{
ASSERT(!lastFreeBlock_->nextFreeBlock_);
lastFreeBlock_->nextFreeBlock_ = block;
block->previousFreeBlock_ = lastFreeBlock_;
lastFreeBlock_ = block;
}
++freeBlocks_;
}
inline void PoolAllocator::removeFreeBlock(Block* block)
{
ASSERT(block);
if (block != firstFreeBlock_ &&
block != lastFreeBlock_)
{
Block* previous = block->previousFreeBlock_;
Block* next = block->nextFreeBlock_;
previous->nextFreeBlock_ = next;
next->previousFreeBlock_ = previous;
}
else
{
if (block == firstFreeBlock_)
{
firstFreeBlock_ = block->nextFreeBlock_;
if (firstFreeBlock_)
{
firstFreeBlock_->previousFreeBlock_ = 0;
}
}
if (block == lastFreeBlock_)
{
lastFreeBlock_ = block->previousFreeBlock_;
if (lastFreeBlock_)
{
lastFreeBlock_->nextFreeBlock_ = 0;
}
}
}
block->previousFreeBlock_ = 0;
block->nextFreeBlock_ = 0;
--freeBlocks_;
}
inline void swap(PoolAllocator& left,
PoolAllocator& right)
{
left.swap(right);
}
}
#endif
| true |
80b54be92ed2287e471b8fc4732f74ab3cd74b9f | C++ | jJayyyyyyy/OJ | /LeetCode/101-200/P136_Single_Number.cpp | UTF-8 | 1,082 | 3.734375 | 4 | [] | no_license | /*
* https://leetcode.com/problems/single-number/description/
* 给定一个数组, 其中只有一个数是单独的, 其他所有的数都会出现2次. 找出那个单独的数
* 同类题目 P136
*
* 线性时间复杂度, 要求空间复杂度为O(1).
* 思路: 异或, ^=
*/
// #include <iostream>
// #include <vector>
// #include <algorithm>
// using namespace std;
// io加速
// static const auto io_speed_up = []() {
// std::ios::sync_with_stdio(false);
// cin.tie(0);
// return 0;
// } ();
class Solution {
public:
int singleNumber(vector<int>& nums) {
int ans = nums[0];
int len = nums.size();
for( int i = 1; i < len; i++ ){
ans ^= nums[i]; // ^ 异或
}
return ans;
}
};
// int main(){
// ios::sync_with_stdio(false);
// cin.tie(0);
// Solution s;
// vector<int> n1, n2;
// n1.push_back(2);
// n1.push_back(2);
// n1.push_back(1);
// cout<<s.singleNumber(n1)<<'\n';
// n2.push_back(4);
// n2.push_back(1);
// n2.push_back(2);
// n2.push_back(1);
// n2.push_back(2);
// cout<<s.singleNumber(n2)<<'\n';
// return 0;
// } | true |
fb900bf4b2b35c9e770cc63f3ecbbddab1d16c6f | C++ | XnorTheUnforgiven/ELE778 | /main.cpp | UTF-8 | 3,887 | 2.828125 | 3 | [] | no_license | /**************************************************************************************
* Name: main.cpp
*
* Written by: Tomy Aumont
* Xavier Mercure-Gagnon
*
* Descritpion:
* 1ère partie: Fait le pré-traitement des données. Termine avec un vecteur de
* de données prêtes à être apprises par le réseau de neurones.
*
* Probleme a regler: Eventuellemet il va falloir gerer les erreur de plusieurs fonctions qui retourne void pour l'instant
*
* Chose a faire :
* OBLIGATOIRE:
* Coder les deux activations, choix deja present ( sigmoide + autre )
* Validation croisee plus temps max d'apprentissage comme critere arret learning
* Posibilite de voir les donnees des neurone des couches cachees et les sauvegarder
*
* FACULTATIF:
* InitWeigth() de plusieurs maniere
* Initialisation du reseau (creation des neurones, connexions)
* Implementer de la fonction d'activation sigmoide
* Implementer du choix de la fonction d'activation
* Implementer une 2e fonction d'activation
* Implementer une sauvegarde des donnees + poids(connexions) apres execution
* ??? Attention au doublon de lien pour 2 neurones, vecteur a mettre dans le network ???
* (optionnel) Choix du nom sauvegarde
* (optionnel) Choix du nom de load
* Deep learning ( initialisation des poids 1 couches a la fois )( long a faire )
**************************************************************************************/
#include "file_parser.h"
#include "GraphTools.h"
#include "NeuralNetwork.h"
using namespace std;
bool main( void )
{
// Objet qui va contenir toutes les information du fichier config.ini
ConfigFile settings;
/* Objet qui va contenir une liste de fichiers et toutes les informations
concernant ces fichiers */
InputFiles trainFiles;
/* Objet qui va contenir une liste de fichiers et toutes les informations
concernant ces fichiers. */
InputFiles testFiles;
/* Objet qui va contenir une liste de fichiers et toutes les informations
concernant ces fichiers. */
InputFiles vcFiles;
// Objet qui va representer tout le reseau de neurone
NeuralNetwork neuralNetwork;
srand( time(NULL) ); // Initialise le random avec le temps actuel
PrintIntroHeader(); // Imprime une en-tete en debut
settings.ReadConfig(); // Recupere les information lu dans le fichier config.ini
settings.UserSetConfig(); // Si l'usager le veut, modifie la configuration
// Si l'usager veut utiliser des fichier déjàa triées, charge la liste de fichiers
int nbData = settings.GetNbBestData();
int isSorted = settings.GetSorted();
if( isSorted )
{
cout << endl << "Chargement des fichiers triees en cours..." << endl;
// Recupere le contenu des fichiers d'entrainement
trainFiles.LoadSortedFiles( (char*)TRAIN_LOAD_PATH );
// Recupere le contenu des fichiers de test
testFiles.LoadSortedFiles( (char*)TEST_LOAD_PATH );
// Recupere le contenu des fichiers de validation croisee
vcFiles.LoadSortedFiles( (char*)VC_LOAD_PATH );
}
else
{
cout << endl << "Triage des fichiers d'entrees en cours..." << endl;
trainFiles.CreateSortedFiles( settings.GetInfoTrainPath() , nbData );
testFiles.CreateSortedFiles( settings.GetInfoTestPath() , nbData );
vcFiles.CreateSortedFiles( settings.GetInfoVCPath() , nbData );
cout << "Triage terminee" << endl;
}
cout << "Initialisation du reseau de neurones" << endl;
neuralNetwork.InitNetwork( &settings );
cout << "Initialisation terminee" << endl;
cout << "Apprentissage en cours..." << endl;
neuralNetwork.Train( trainFiles.GetFileList(), settings.GetLearnMaxDelay(),
settings.GetErrorMargin(), settings.GetActivationFct() );
cout << "Apprentissage terminee" << endl;
cout << "Test en cours..." << endl;
neuralNetwork.Test( );
cout << "Test terminee" << endl;
PrintDebugMessage( SUCCESS );
system( "pause" );
return EXIT_SUCCESS;
}
| true |
b1a4194f8c488300f0a136bedc6fa2a97cecce03 | C++ | rezanour/nativegame | /SliderPuzzle/Tile.h | UTF-8 | 669 | 2.625 | 3 | [] | no_license | #pragma once
#include <d3d11.h>
#include <SimpleMath.h>
class Tile
{
public:
Tile();
Tile(int difficulty, DirectX::SimpleMath::Vector2 initialPosition);
~Tile();
void SlideUp();
void SlideDown();
void SlideLeft();
void SlideRight();
DirectX::SimpleMath::Vector2 GetPosition() const;
void SetPosition(const DirectX::SimpleMath::Vector2& newPosition);
float GetTileSize() const;
DirectX::SimpleMath::Vector2 GetTexCoords() const;
bool IsCorrectPosition();
private:
float _tileSize;
DirectX::SimpleMath::Vector2 _initPos;
DirectX::SimpleMath::Vector2 _position;
DirectX::SimpleMath::Vector2 _texcoords;
}; | true |
88863ed9d582d85b1ae97352592e1366f8b8c7e4 | C++ | alearley26/Programming_Projects | /Image_Processing_Project/Header.cpp | UTF-8 | 1,327 | 3.046875 | 3 | [] | no_license | #include "Header.h"
#include<iostream>
#include <fstream>
using namespace std;
Header::Header() {
idLength = 0;
colorMapType = 0;
imageType = 2;
colorMapOrigin = 0;
colorMapLength = 0;
colorMapDepth = 0;
xOrigin = 0;
yOrigin = 0;
imageWidth = 0;
imageHeight = 0;
bitsPerPixel = 24;
imageDescriptor = 0;
}
Header::Header(short& inputWidth, short& inputHeight) {
idLength = 0;
colorMapType = 0;
imageType = 2;
colorMapOrigin = 0;
colorMapLength = 0;
colorMapDepth = 0;
xOrigin = 0;
yOrigin = 0;
imageWidth = inputWidth;
imageHeight = inputHeight;
bitsPerPixel = 24;
imageDescriptor = 0;
}
void Header::PrintHeader() {
cout << "ID length: " << (int)idLength << endl;
cout << "Color map type: " << (int)colorMapType << endl;
cout << "Image type: " << (int)imageType << endl;
cout << "Color map origin: " << colorMapOrigin << endl;
cout << "Color map length: " << colorMapLength << endl;
cout << "Color map depth: " << (int)colorMapDepth << endl;
cout << "x origin: " << xOrigin << endl;
cout << "y origin: " << yOrigin << endl;
cout << "Image width: " << imageWidth << endl;
cout << "Image height: " << imageHeight << endl;
cout << "Bits per pixel: " << (int)bitsPerPixel << endl;
cout << "Image descriptor: " << (int)imageDescriptor << endl;
} | true |
36737fcd5b3ab7d98657c1a64305bd7d01c6cf45 | C++ | Chung-god/add-nbo | /main.cpp | UTF-8 | 1,261 | 2.6875 | 3 | [] | no_license | #include <stddef.h> // for size_t
#include <stdint.h> // for uint8_t
#include <stdio.h> // for printf
#include <stdlib.h>
#include <string.h>
char file0[50] = "/home/chung/workspace/HW/add-nbo/";
char file1[50] = "/home/chung/workspace/HW/add-nbo/";
char temp[50];
FILE* fp0;
FILE* fp1;
uint8_t buffer[20];
uint8_t add_value[20];
uint16_t my_ntohs(uint16_t a){
return (a<<8)|(a>>8);
}
uint16_t write_0x1234(uint8_t a, uint8_t b) {
uint8_t network_buffer[] = { a, b };
uint16_t* p = reinterpret_cast<uint16_t*>(network_buffer);
uint16_t n = my_ntohs(*p); // TODO
return n;
}
void input_filename(char* arr[]){
strcat(file0,arr[1]);
fp0 = fopen(file0,"r");
fread(buffer,8,1,fp0);
add_value[0] = buffer[2];
add_value[1] = buffer[3];
strcat(file1,arr[2]);
fp1 = fopen(file1,"r");
fread(buffer,8,1,fp1);
add_value[2] = buffer[2];
add_value[3] = buffer[3];
fclose(fp0);
fclose(fp1);
}
int main(int argc, char* argv[]) {
input_filename(argv);
uint16_t add0 = write_0x1234(add_value[0],add_value[1]);
uint16_t add1 = write_0x1234(add_value[2],add_value[3]);
uint32_t result = add0 + add1;
printf("%d(0x%x) + %d(0x%x) = %d(0x%x))\n",add0,add0,add1,add1,result,result);
}
| true |
f51270d85502916ff17427f10bd580daad9fcddc | C++ | IgorYunusov/Mega-collection-cpp-1 | /Windows内核安全编程从入门到实践/Projects/chapter 5 磁盘/QueryPerformance/QueryPerformance/main.cpp | UTF-8 | 1,349 | 2.53125 | 3 | [] | no_license | #include "stdio.h"
#include "windows.h"
int main()
{
HANDLE hFile;
DISK_PERFORMANCE OutBuffer = {0};
ULONG OutBufferSize = sizeof(DISK_PERFORMANCE), dwRet;
BOOL bRet;
hFile = CreateFileA("\\\\.\\PhysicalDrive0", GENERIC_READ,
FILE_SHARE_READ, NULL, OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL, NULL);
if (INVALID_HANDLE_VALUE == hFile) {
printf("CreateFile Failure!err:%d\n", GetLastError());
return 0;
}
bRet = DeviceIoControl(hFile, IOCTL_DISK_PERFORMANCE, NULL, 0, (LPVOID)&OutBuffer, OutBufferSize, &dwRet, NULL);
if (FALSE == bRet) {
printf("DeviceIoControl Failure!err:%d\n", GetLastError());
CloseHandle(hFile);
return 0;
}
printf("\
BytesRead: %I64u\nBytesWritten:%I64u\nReadTime:%I64u\nWriteTime:%I64u\nIdleTime:%I64u\n\
ReadCount:%d\nWriteCount:%d\nQueueDepth:%d\nSplitCount:%d\nQueryTime::%I64u\n\
StorageDeviceNumber:%x\nStorageManagerName:%ws\n",
OutBuffer.BytesRead, OutBuffer.BytesWritten, OutBuffer.ReadTime, OutBuffer.WriteTime, OutBuffer.IdleTime,
OutBuffer.ReadCount, OutBuffer.WriteCount, OutBuffer.QueueDepth, OutBuffer.SplitCount,
OutBuffer.QueryTime, OutBuffer.StorageDeviceNumber, OutBuffer.StorageManagerName
);
CloseHandle(hFile);
return 0;
} | true |
dfbb61675ce5ba40840cee1507fc113be36c8b84 | C++ | longcule/BT-LTNC-INT2215-22 | /BT10-LTNC/A1,2,3-BT10.cpp | UTF-8 | 539 | 3.734375 | 4 | [] | no_license | #include <iostream>
using namespace std;
struct Point
{
int x,y;
void Print()
{
cout<<x<<" "<<y;
}
};
void print1(Point p)
{
cout<<"\nDia chi p ham 1: "<<&p;
}
void print2(Point &p)
{
cout<<"\nDia chi p ham 2: "<<&p;
}
Point mid_point(const Point p1, const Point p2)
{
Point p3;
p3.x = (p1.x + p2.x)/2;
p3.y = (p1.y + p2.y)/2;
return p3;
}
int main()
{
Point p;
cin>>p.x>>p.y;
p.Print();
cout<<"\nDia chi p main :"<<&p;
print1(p);
print2(p);
system("pause");
return 0;
}
| true |